@adhdev/daemon-standalone 0.9.82-rc.562 → 0.9.82-rc.563

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.
@@ -5,7 +5,7 @@ var gm=Object.defineProperty;var xm=(e,t,n)=>t in e?gm(e,t,{enumerable:!0,config
5
5
  `}),o=[e.id?`id:${e.id}`:"",n._localId?`local:${n._localId}`:"",n._turnKey?`turn:${n._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(o.length>0)return o.join("|");const a=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${xf(r)}`,a?`ts:${a}`:""].filter(Boolean).join("|")}function yf(e){let t=2166136261;for(const n of e){const r=String(n||"");for(let o=0;o<r.length;o+=1)t^=r.charCodeAt(o),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function vf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Gd(e){return e?yf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),vf(e.content)]):""}const Ci=200,wf=80,Tl=650,Ln=new Map;function so(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function kf(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const n=String(t||"").trim();if(n)return`${e.length}:${n}`;const r=e[e.length-1];return`${e.length}:${Gd(r)}`}function Sf(e,t,n,r){return e||!t?!1:so(n,r)}function Cf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=wf,bottomThresholdPx:o=Ci}){const a=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(n)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:a>r,showBottom:Math.max(0,i-a-c)>o}}function jf(e){return Cf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function qn(e,t=Ci){return!!e&&e.fromBottom>=t}function Nf(e,t){return so(e,t)?!qn(e):!0}function Af({hasSelection:e,userScrolledUp:t,hasChatContentChanged:n=!0}){return!(e||t||!n)}function Tf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:n}){return e?!1:n||!t}function Ko(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(n)?n:t.top}const Je={size:18};function Kd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function ji({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Is({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function zd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function If({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Mf({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function qd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Vd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Df({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"20 6 9 17 4 12"})})}function So({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Ni({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Pf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Lf({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Zs({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function us({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ai({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function xn({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Co({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ys({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function ar({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function es({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Rf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function Yd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Ti({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function Jd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Ef({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function Ii({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function _f({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Qd({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Mi({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function At({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function $f({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Bf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Ff({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function Hf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Nn({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Xd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),s.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),s.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function Wf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Of({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Uf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Zd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Gf({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Kf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function zf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function qf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function Vf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Yf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function Jf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function Qf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function Xf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),s.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}const eu="adhdev_chat_activity_visible",Il=new Set(["hidden","debug","internal"]),Ml=new Set(["visible","user","chat"]),Zf=new Set(["debug","trace","internal"]),eb=new Set(["tool_call","terminal_command","runtime_activity"]),tb=new Set(["runtime_status","provider_chrome","control"]),sb=new Set(["thought","tool","terminal"]);function tu(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function rn(e){return typeof e=="string"?e.trim().toLowerCase():""}function zo(e,t,n){return e[n]??(t==null?void 0:t[n])}function Dl(e,t,n){const r=e;return n.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function nb(e,t){const n=rn(e.kind);return n||(t==="tool"?"tool":"standard")}function qo(e,t,n){const r=tu(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||(t==="terminal"||n==="terminal_command"?"Terminal":t==="tool"||n==="tool_call"?"Tool":t==="thought"?"Thought":n==="runtime_activity"?"Runtime":"Activity")}function rb(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Di(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=tu(e),n=rn(e.role),r=nb(e,n),o=rn(zo(e,t,"visibility")),a=rn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=rn(zo(e,t,"audience")),c=rn(zo(e,t,"source")),u=Il.has(o)||Il.has(a)||Zf.has(i)||Dl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),h=Ml.has(o)||Ml.has(a)||i==="chat"||Dl(e,t,["userFacing"]),d=sb.has(r)||eb.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:n,kind:r,label:qo(e,r,c)};if(h)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:qo(e,r,c)};if((n==="system"||r==="system")&&rb(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(tb.has(c)||n==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:n,kind:r,label:"Internal"};if(d)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:n,kind:r,label:qo(e,r,c)};const m=(n==="user"||n==="human"||n==="assistant")&&(r==="standard"||r==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:n,kind:r,label:m?"Chat":"Internal"}}function ob(e){return(Array.isArray(e)?e:[]).filter(t=>Di(t).isUserFacing)}function su(e){return(Array.isArray(e)?e:[]).filter(t=>Di(t).isActivityFacing)}function nu(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function ab(e){return`${String(e.role||"")}::${nu(e)}`}function ib(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const o=ab(r);nu(r).trim().length>0&&o===n||(t.push(r),n=o)}return t}function lb(e,t,n){return!n||t.length===0?e:[...e,...t].sort((r,o)=>{const a=Number(r.receivedAt??r.timestamp??0)||0,i=Number(o.receivedAt??o.timestamp??0)||0;if(a!==i)return a-i;const c=Number(r.index??0)||0,u=Number(o.index??0)||0;return c-u})}function Pl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(eu))==="1"}catch{return!1}}function cb({text:e}){const{t}=Le("common"),[n,r]=l.useState(!1),o=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:n?s.jsx(Df,{size:11}):s.jsx(Vd,{size:11})})}const ru=[ym,{singleTilde:!1}],ou=[ru,vm,wm],db=[ru];function wr(e,t,n){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,n?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:n}):null]})}function Ll(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Ud(e)?s.jsx(wi,{remarkPlugins:ou,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const ub=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx(wi,{remarkPlugins:ou,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Rn({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((n,r)=>{if(n.type==="text")return s.jsx("div",{children:Ll(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const o=Go(n),a=n.alt||n.description||Pn(n.uri,"image");return o?s.jsx("img",{src:o,alt:a,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):s.jsx("div",{children:wr("Image",a,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const o=Go(n);return o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:o,className:"max-w-full"}),n.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:n.transcript}):null]},`audio-${r}`):s.jsx("div",{children:wr("Audio",Pn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const o=Go(n),a=n.title||n.name||n.alt||Pn(n.uri,"video"),i=[n.transcript,n.description,n.mimeType].filter(Boolean).join(`
6
6
  `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[o?s.jsx("video",{controls:!0,src:o,poster:n.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):wr("Video",a,i),o&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(n.type==="resource_link"){const o=n.title||n.name||Pn(n.uri,"resource"),a=[n.description,n.mimeType].filter(Boolean).join(`
7
7
  `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[n.uri?s.jsx("a",{href:n.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:o}):wr("Resource",o,a),n.uri&&a?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:a}):null]},`resource-link-${r}`)}if(n.type==="resource"&&n.resource){const o=Pn(n.resource.uri,"resource");if(n.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:o}),Ll(n.resource.text,!0)]},`resource-${r}`);if(n.resource.uri)return s.jsx("a",{href:n.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:o},`resource-uri-${r}`)}return null})})}const hb=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(wi,{remarkPlugins:db,children:t.text}),s.jsx("span",{className:"action-time",children:Od(t.timestamp)})]})},(e,t)=>e.log===t.log);function Rl(e){const t=e.meta;return[Gd(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):""].join("")}const pb=l.memo(function({message:t,receivedAt:n,agentName:r,userName:o,isCliMode:a,isTextExpanded:i,onToggleTextExpanded:c}){var C,A,T;const u=(t.role||"").toLowerCase(),h=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),m=Di(t),f=gf(t.content)?t.content:null,x=!!(f!=null&&f.some(M=>M.type!=="text")),w=Si(t.content,{joiner:`
8
- `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const M=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:M})]}),x&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:w})]})}if(d==="thought"){const M=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Ff,{size:13}),s.jsx("span",{children:M})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const M=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",L=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:M}),s.jsx("span",{children:L})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const p=t.meta,k=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",b=w,j=!1,S=b,v=k,g=!h&&!v&&Ud(S),N=["chat-message-row",h?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||x||h)&&s.jsxs("div",{className:`chat-bubble ${h?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:h?o||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||x)&&s.jsx(cb,{text:w}),n!=null&&s.jsx("span",{className:"chat-time",children:Od(n)})]})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:v}):s.jsx(ub,{content:S,renderAsPreformatted:v,renderAsMarkdown:g})}),j]})})},(e,t)=>(e.message===t.message||Rl(e.message)===Rl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),mb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:h,showActivityMessages:d=!1,emptyState:m,onLoadMore:f,isLoadingMore:x,hasMoreHistory:w,hiddenLiveCount:p=0,loadError:y,scrollToBottomRequestNonce:k,isVisible:b=!0},j){const{t:S}=Le("common"),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(0),A=l.useRef(""),T=l.useRef(""),M=l.useRef(!1),L=l.useRef(null),P=l.useRef(!1),B=l.useRef(null),K=l.useRef(!1),[F,R]=l.useState(new Set),[Q,E]=l.useState({showTop:!1,showBottom:!1}),I=l.useRef(!1),$=l.useRef(!1),D=l.useRef(b),U=l.useRef(b),Y=l.useRef(null);U.current=b;const ae=()=>{const _=v.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight<Ci:!0},z=l.useCallback(()=>{const _=v.current,se=_?jf(_):{showTop:!1,showBottom:!1};E(ve=>ve.showTop===se.showTop&&ve.showBottom===se.showBottom?ve:se)},[]),X=l.useCallback((_="auto")=>{var ve;const se=v.current;se&&(se.scrollTo({top:se.scrollHeight,behavior:_}),(ve=se.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),de=l.useCallback((_="auto")=>{var ve;const se=v.current;se&&(se.scrollTo({top:0,behavior:_}),(ve=se.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),re=l.useCallback(()=>{var H;const _=v.current,se=(H=window.getSelection)==null?void 0:H.call(window);if(!_||!se||se.rangeCount===0||se.isCollapsed){K.current=!1;return}const ve=se.anchorNode,ce=se.focusNode;K.current=!!(ve&&ce&&_.contains(ve)&&_.contains(ce))},[]),W=l.useMemo(()=>{const _=ob(t),se=su(t);return ib(lb(_,se,d))},[t,d]),oe=W.length===t.length?h:void 0,V=kf(W,oe),ie=l.useCallback(()=>{const _=v.current;if(!_||!c||!U.current)return;const se={top:_.scrollTop,fromBottom:Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),messageFingerprint:V};Y.current={contextKey:c,snapshot:se},Ln.set(c,se)},[c,V]),ke=l.useCallback((_="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,X(_)})},[X]),xe=l.useCallback(()=>{I.current=!1,P.current=!0,$.current=!0,B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},[]);l.useEffect(()=>{const _=!M.current,se=T.current!==c;if(T.current=c,_||se){M.current=!0;const ce=c?Ln.get(c):null,H=!!ce&&so(ce,V);I.current=H?qn(ce):!1,P.current=Nf(ce,V),K.current||(H?requestAnimationFrame(()=>{const fe=v.current;fe&&(Ko(fe,ce),I.current=qn(ce),z(),$.current=!0)}):ke("auto")),C.current=W.length,A.current=V;return}W.length>C.current;const ve=V!==A.current;Af({hasSelection:K.current,userScrolledUp:I.current,hasChatContentChanged:ve})&&ke("auto"),C.current=W.length,A.current=V},[V,c,W.length,ke,z]),l.useEffect(()=>{k&&(xe(),K.current||ke("auto"))},[xe,ke,k]),l.useEffect(()=>{const _=D.current;_&&!b&&ie(),U.current=b,D.current=b;const se=c?Ln.get(c):null;if(Sf(_,b,se,V)){if(!se)return;I.current=qn(se),P.current=!1,K.current||requestAnimationFrame(()=>{const ve=v.current;ve&&(Ko(ve,se),z())});return}},[b,c,V,xe,ie,ke,z]),l.useEffect(()=>()=>{const _=Y.current;_&&Ln.set(_.contextKey,_.snapshot),L.current!=null&&cancelAnimationFrame(L.current),B.current!=null&&window.clearTimeout(B.current)},[]),l.useEffect(()=>{const _=g.current,se=v.current;if(!_||!se)return;const ve=()=>{B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},ce=new ResizeObserver(()=>{z();const H=P.current;Tf({hasSelection:K.current,userScrolledUp:I.current,contextAutoScrollActive:H})&&(ke("auto"),H&&ve())});return ce.observe(_),se!==_&&ce.observe(se),()=>{ce.disconnect(),B.current!=null&&(window.clearTimeout(B.current),B.current=null)}},[ke,c,z]),l.useImperativeHandle(j,()=>({scrollToBottom:(_="smooth")=>{X(_)}}),[X]),l.useEffect(()=>{const _=v.current;if(!_)return;let se;const ve=()=>{ie(),clearTimeout(se),se=setTimeout(()=>{I.current=!ae(),z()},50)};return _.addEventListener("scroll",ve,{passive:!0}),()=>{_.removeEventListener("scroll",ve),clearTimeout(se)}},[ie,z]),l.useEffect(()=>(document.addEventListener("selectionchange",re),()=>document.removeEventListener("selectionchange",re)),[re]);const Se=l.useRef(0),pe=l.useRef(!1);l.useEffect(()=>{const _=v.current;if(!_||!pe.current||Se.current===0)return;const se=_.scrollHeight-Se.current;se>0&&(_.scrollTop=se),z(),ie(),Se.current=0,pe.current=!1},[W.length,ie,z]),l.useEffect(()=>{if($.current||!c)return;const _=Ln.get(c),se=v.current;if(!(!_||!se)){if(!so(_,V)){X("auto"),$.current=!0;return}Ko(se,_),I.current=qn(_),z(),$.current=!0}},[c,V,W.length,X,z]);const G=()=>{const _=v.current;_&&(Se.current=_.scrollHeight),pe.current=!0,f==null||f()},O=()=>{I.current=!0,de("smooth"),ie()},Z=()=>{xe(),X("smooth"),ie()},q=l.useMemo(()=>{const _=W.map((H,fe)=>({type:"message",data:H,index:fe,ts:bf(H,fe,u)}));if(!n||n.length===0)return _;const se=[...n].sort((H,fe)=>H.timestamp-fe.timestamp).map((H,fe)=>({type:"action",data:H,index:fe,ts:H.timestamp})),ve=[];let ce=0;for(const H of _){for(;ce<se.length&&H.ts>0&&se[ce].ts<H.ts;)ve.push(se[ce++]);ve.push(H)}for(;ce<se.length;)ve.push(se[ce++]);return ve},[W,n,u]),me=p>0||!!w,Te=p>0?p>80?S("chatList.showEarlierMessagesHidden",{count:Math.min(p,80),total:p}):S("chatList.showEarlierMessages",{count:Math.min(p,80)}):y?S("chatList.loadErrorRetry",{error:y}):S("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:g,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:S("chatList.loadingOlderMessages")}),me&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:G,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${y&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Te})}),q.length===0&&!me&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:S("chatList.waitingForMessages")})),q.map(_=>{if(_.type==="action"){const je=_.data;return s.jsx(hb,{log:je},`action-${_.index}`)}const se=_.data;_.index;const ve=to(se),ce=se.receivedAt||u[ve],H=`${c}-${ve}`,fe=F.has(H);return s.jsx(pb,{message:se,receivedAt:ce,agentName:r,userName:o,isCliMode:a,isTextExpanded:fe,onToggleTextExpanded:()=>R(je=>{const Ce=new Set(je);return fe?Ce.delete(H):Ce.add(H),Ce})},`msg-${ve}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:S("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(Q.showTop||Q.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":S("chatList.jumpToTop"),children:[Q.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:O,"aria-label":S("chatList.jumpToOldestMessages"),title:S("chatList.jumpToTop"),children:S("chatList.top")}),Q.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":S("chatList.jumpToLatestMessages"),title:S("chatList.jumpToBottom"),children:S("chatList.latest")})]})]})}),fb=l.memo(mb,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),bb="modulepreload",gb=function(e){return"/"+e},El={},xb=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(n.map(u=>{if(u=gb(u),u in El)return;El[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const m=document.createElement("link");if(m.rel=h?"stylesheet":bb,h||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),h)return new Promise((f,x)=>{m.addEventListener("load",f),m.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};let _l=!1;const au=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const c=l.useRef(null),[u,h]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),x=l.useRef(!1),w=l.useRef(!1),p=()=>{const y=c.current;if(y){m.current&&(y.clear(),m.current=!1);for(const k of d.current)y.write(k.data,k.onProcessed);d.current=[],f.current&&(y.fit(),f.current=!1),x.current&&(y.bumpResize(),x.current=!1),w.current&&(y.scrollToTop(),w.current=!1)}};return l.useImperativeHandle(i,()=>({write:(y,k)=>{c.current?c.current.write(y,k):d.current.push({data:y,onProcessed:k})},clear:()=>{c.current?c.current.clear():(d.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],m.current=!0)},resize:(y,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(y,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():x.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():w.current=!0},getSelection:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getSelection)==null?void 0:k.call(y))||""},getVisibleText:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getVisibleText)==null?void 0:k.call(y))||""}}),[]),l.useEffect(()=>{u&&p()},[u]),l.useEffect(()=>{let y=!1;return xb(()=>import("./terminal-BNQ0ACgR.js"),__vite__mapDeps([0,1,2])).then(k=>{_l||(_l=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||h(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{y=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:o,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});au.displayName="CliTerminal";function Ht(...e){return km(Sm(e))}const yb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},vb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...o},a){return s.jsx("div",{ref:a,className:Ht("border border-border-subtle bg-bg-secondary",yb[t],vb[n],r),...o})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ss,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function $l({value:e,max:t,label:n,color:r="#8b5cf6",detail:o,compact:a=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return a?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:n}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:n}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),o&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function wb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,o=r.getBoundingClientRect(),a=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,c=r.naturalHeight||o.height,u=i/c,h=o.width/o.height;let d,m,f,x;u>h?(d=o.width,m=o.width/u,f=0,x=(o.height-m)/2):(m=o.height,d=o.height*u,f=(o.width-d)/2,x=0);const w=o.left-a.left+f+d*e.nx,p=o.top-a.top+x+m*e.ny,y=Math.max(8,Math.min(a.width-8,w)),k=Math.max(8,Math.min(a.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-8,top:k-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function kb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:h,zoom:d,isMobile:m,mobileFillZoom:f,onZoomOut:x,onZoomReset:w,onZoomIn:p,transportType:y,screenshotUsage:k,lastActionStatus:b}){const{t:j}=Le("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:j(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(S=>!S),a(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:j("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>c(S.target.value),onKeyDown:S=>{u(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{a(S=>!S),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:h?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:h?"#22c55e":"#eab308",boxShadow:h?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:h?"#22c55e":"#eab308"},children:j(h?"remote.connected":"remote.ws")})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:j("remote.directP2PTitle"),children:j("remote.direct")}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:j("remote.turnRelayTitle"),children:j("remote.relay")}),k&&k.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:j("remote.dailyTurnTitle"),children:k.budgetExhausted?j("remote.turnBlocked"):j("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.dailyBudgetMinutes})}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),o&&s.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:j("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[j("remote.zoom")," ",d<=(m?f:1)+.01?j(m?"remote.fill":"remote.fit"):`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:S=>{S.stopPropagation(),x()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:j(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:S=>{S.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Sb({waitingLabel:e,waitingHint:t,transportType:n}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Cb(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Bl(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function mr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Cb())return;r.current+=1;const o=n.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Bl(c)]))}),n.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Bl(t[i])]))}),n.current=t})}function jb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:c,panYRef:u,setPanX:h,setPanY:d,setZoom:m,lastWheelTimeRef:f,onAction:x,setLastActionStatus:w,spawnRippleFromNormalized:p,clampPan:y,isMobile:k,mobileFillZoom:b}){const[j,S]=l.useState(null),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),T=l.useRef(0),M=l.useRef(null),L=l.useRef(1),P=l.useRef({x:0,y:0}),B=l.useRef(!1),K=l.useRef(r),F=l.useRef(x),R=30,Q=550,E=18,I=60,$=400,D=12,U=()=>{if(v.current)return;const z={nx:.5,ny:.5};v.current=z,S(z)};return l.useEffect(()=>{K.current=r,r==="mouse"&&U()},[r]),l.useEffect(()=>{F.current=x},[x]),l.useEffect(()=>{const z=e.current;if(!z)return;const X=ie=>{if(!n.current)return null;const ke=n.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(ie.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(ie.clientY-ke.top)/ke.height))}},de=(ie,ke)=>{if(!n.current)return{dnx:0,dny:0};const xe=n.current,Se=xe.getBoundingClientRect(),pe=xe.naturalWidth||Se.width,G=xe.naturalHeight||Se.height,O=pe/G,Z=Se.width/Se.height;let q,me;return O>Z?(q=Se.width,me=Se.width/O):(me=Se.height,q=Se.height*O),{dnx:ie/q,dny:ke/me}},re=(ie,ke,xe)=>{if(xe<=1.05)return;const Se=-(ie-.5)*100,pe=-(ke-.5)*100,G=y(Se,pe,xe);(Math.abs(G.x-c.current)>.1||Math.abs(G.y-u.current)>.1)&&(h(G.x),d(G.y),c.current=G.x,u.current=G.y)},W=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target))ie.preventDefault();else return;if(ie.touches.length===1){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},B.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!B.current)if(C.current=!0,K.current==="mouse"){const Se=v.current||{nx:.5,ny:.5};w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{})}else{const Se=X(xe);Se&&(w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{}))}},500);return}if(ie.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,B.current=!0;const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY;M.current=Math.sqrt(xe*xe+Se*Se),L.current=i.current,P.current={x:(ie.touches[0].clientX+ie.touches[1].clientX)/2,y:(ie.touches[0].clientY+ie.touches[1].clientY)/2}}},oe=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target)&&ie.preventDefault(),ie.touches.length===1&&N.current){const xe=ie.touches[0],Se=xe.clientX-N.current.x,pe=xe.clientY-N.current.y;if(!C.current&&g.current){const G=xe.clientX-g.current.x,O=xe.clientY-g.current.y;Math.sqrt(G*G+O*O)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(K.current==="mouse"){const G=de(Se,pe),O=v.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,O.nx+G.dnx)),q=Math.max(0,Math.min(1,O.ny+G.dny));v.current={nx:Z,ny:q},S({nx:Z,ny:q}),w(`Cursor: ${Math.round(Z*100)}%, ${Math.round(q*100)}%`),re(Z,q,i.current);const me=Date.now();me-f.current>=30&&(f.current=me,F.current("input_mouseMoved",{nx:Z,ny:q}).catch(()=>{}))}else if(i.current>1){const G=t.current;if(G){const O=G.clientWidth,Z=G.clientHeight,q=c.current+Se/O*100,me=u.current+pe/Z*100,Te=y(q,me,i.current);h(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}else{const G=X(xe);if(G){const O=Date.now();O-f.current>=40&&(f.current=O,w("Scroll"),F.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-Se*2.5),deltaY:Math.round(-pe*2.5)}).catch(()=>{}))}}N.current={x:xe.clientX,y:xe.clientY};return}if(ie.touches.length===2&&M.current!==null){const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY,G=Math.sqrt(xe*xe+Se*Se)/M.current,O=(ie.touches[0].clientX+ie.touches[1].clientX)/2,Z=(ie.touches[0].clientY+ie.touches[1].clientY)/2,q=O-P.current.x,me=Z-P.current.y,Te=Math.abs(G-1)>.03;if(K.current==="mouse"){if(Te){const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_}else if(Math.abs(q)>2||Math.abs(me)>2){const _=v.current||{nx:.5,ny:.5},se=Date.now();se-f.current>=30&&(f.current=se,w("Scroll"),F.current("input_wheel",{nx:_.nx,ny:_.ny,deltaX:Math.round(-q*3),deltaY:Math.round(-me*3)}).catch(()=>{}))}}else{const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_;const se=t.current;if(se&&_>1){const ve=se.clientWidth,ce=se.clientHeight,H=c.current+q/ve*100,fe=u.current+me/ce*100,je=y(H,fe,_);h(je.x),d(je.y),c.current=je.x,u.current=je.y}}P.current={x:O,y:Z}}},V=ie=>{var ke;if(A.current&&clearTimeout(A.current),M.current=null,ie.touches.length===1&&B.current){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},C.current=!0;return}if(ie.touches.length===0){if(B.current){B.current=!1,C.current=!1;return}if(ie.changedTouches.length===1){const xe=ie.changedTouches[0],Se=Date.now(),pe=Se-(((ke=g.current)==null?void 0:ke.time)||0),G=g.current?xe.clientX-g.current.x:0,O=g.current?xe.clientY-g.current.y:0,Z=Math.sqrt(G*G+O*O);if(K.current==="mouse"){if(pe<R||pe>Q||Z>E){C.current=!1;return}const q=v.current||X(xe);q&&(w(`Click: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(pe<I||pe>$||Z>D){C.current=!1;return}const q=X(xe);if(!q)return;Se-T.current<300?(w("Double tap"),p(q.nx,q.ny,"double"),F.current("input_click",{...q,clickCount:2}).catch(()=>{}),T.current=0):(w(`Tap: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}),T.current=Se)}}C.current=!1}};return z.addEventListener("touchstart",W,{passive:!1}),z.addEventListener("touchmove",oe,{passive:!1}),z.addEventListener("touchend",V,{passive:!1}),()=>{z.removeEventListener("touchstart",W),z.removeEventListener("touchmove",oe),z.removeEventListener("touchend",V),A.current&&clearTimeout(A.current)}},[e,t,n,a,i,c,u,h,d,m,f,w,p,y]),{cursorPos:j,cursorPosRef:v,handleToggleInputMode:()=>{o(z=>{const X=z==="touch"?"mouse":"touch";return X==="mouse"&&U(),X})},handleZoomReset:()=>{const z=k?b:1;m(z),i.current=z,h(0),d(0),c.current=0,u.current=0}}}function iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:o,transportType:a}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[h,d]=l.useState(null),[m,f]=l.useState(""),[,x]=l.useState(!1),[w,p]=l.useState([]),y=l.useRef(0),[k,b]=l.useState(!1),[j,S]=l.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,N]=l.useState(v?"mouse":"touch"),[C,A]=l.useState(1),T=l.useRef(!1),[M,L]=l.useState(1),[P,B]=l.useState(0),[K,F]=l.useState(0);mr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:g,zoom:M,panX:P,panY:K,isMenuOpen:k,isImeOpen:j});const R=l.useRef(0),Q=l.useRef(M),E=l.useRef(P),I=l.useRef(K);l.useEffect(()=>{Q.current=M},[M]),l.useEffect(()=>{E.current=P},[P]),l.useEffect(()=>{I.current=K},[K]),l.useEffect(()=>{var pe;(pe=i.current)==null||pe.focus()},[]);const $=n==="connected",D=r,U=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!v||T.current||!D)return;const pe=u.current,G=c.current;if(!pe||!G)return;const O=()=>{const Z=G.clientWidth,q=G.clientHeight,me=pe.naturalWidth,Te=pe.naturalHeight;if(!me||!Te||!Z||!q)return;const _=Math.min(Z/me,q/Te),ve=Math.max(Z/me,q/Te)/_;ve>1.01&&(A(ve),L(ve),Q.current=ve),T.current=!0};pe.complete&&pe.naturalWidth?O():pe.addEventListener("load",O,{once:!0})},[D,v]);const ae=.5;l.useEffect(()=>{M<=ae&&(B(0),F(0))},[M,ae]);const z=(pe,G,O)=>{if(O<=ae)return{x:0,y:0};const Z=(O-1)/(2*O)*100,q=(O-1)/(2*O)*100;return{x:Math.max(-Z,Math.min(Z,pe)),y:Math.max(-q,Math.min(q,G))}},X=(pe,G)=>{if(!u.current)return null;const O=u.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(pe-O.left)/O.width)),ny:Math.max(0,Math.min(1,(G-O.top)/O.height))}},de=(pe,G,O)=>{const Z=c.current;if(!Z)return;const q=Z.getBoundingClientRect(),me=++y.current;p(Te=>[...Te,{id:me,x:pe-q.left,y:G-q.top,type:O}]),setTimeout(()=>p(Te=>Te.filter(_=>_.id!==me)),600)},re=(pe,G,O)=>{const Z=u.current,q=c.current;if(!Z||!q)return;const me=Z.getBoundingClientRect(),Te=q.getBoundingClientRect(),_=Z.naturalWidth||me.width,se=Z.naturalHeight||me.height,ve=_/se,ce=me.width/me.height;let H,fe,je,Ce;ve>ce?(H=me.width,fe=me.width/ve,je=0,Ce=(me.height-fe)/2):(fe=me.height,H=me.height*ve,je=(me.width-H)/2,Ce=0);const Be=me.left-Te.left+je+H*pe,Xe=me.top-Te.top+Ce+fe*G,dt=++y.current;p(it=>[...it,{id:dt,x:Be,y:Xe,type:O}]),setTimeout(()=>p(it=>it.filter(he=>he.id!==dt)),600)},W=async pe=>{var O;const G=X(pe.clientX,pe.clientY);if(G){d(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),de(pe.clientX,pe.clientY,"left"),(O=i.current)==null||O.focus();try{const Z=await e("input_click",{nx:G.nx,ny:G.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},oe=async(pe,G,O,Z=0)=>{try{await e("input_key",{type:O?"char":"keyDown",key:pe,code:G,text:O?pe:void 0,unmodifiedText:O?pe:void 0,modifiers:Z})}catch(q){t(`❌ Key error: ${q.message||q}`)}},V=async pe=>{if(pe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(pe.key)&&pe.preventDefault();let O=0;pe.altKey&&(O|=1),pe.ctrlKey&&(O|=2),pe.metaKey&&(O|=4),pe.shiftKey&&(O|=8),d(`Key: ${pe.key}`),await oe(pe.key,pe.code,pe.key.length===1,O)},ie=async pe=>{if(pe.key==="Enter"){if(pe.nativeEvent.isComposing)return;if(m){const G=m;f(""),d(`IME Sent: ${G}`);try{const O=await e("input_type",{text:G});O!=null&&O.success||t(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){t(`❌ IME error: ${O.message}`)}}else d("Key: Enter"),await oe("Enter","Enter",!1)}};l.useEffect(()=>{const pe=i.current;if(!pe)return;const G=O=>{var Z;if((Z=u.current)!=null&&Z.contains(O.target)){O.preventDefault();const q=Date.now();if(q-R.current<40)return;R.current=q;const me=X(O.clientX,O.clientY);if(!me)return;d(`Scroll: ${Math.round(O.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return pe.addEventListener("wheel",G,{passive:!1}),()=>pe.removeEventListener("wheel",G)},[e]);const{cursorPos:ke,handleToggleInputMode:xe,handleZoomReset:Se}=jb({containerRef:i,viewportRef:c,imgRef:u,inputMode:g,setInputMode:N,minZoom:ae,zoomRef:Q,panXRef:E,panYRef:I,setPanX:B,setPanY:F,setZoom:L,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:re,clampPan:z,isMobile:v,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:V,onContextMenu:pe=>pe.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[D?s.jsx("img",{ref:u,src:D,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${P}%, ${K}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:pe=>pe.preventDefault(),onDragStart:pe=>pe.preventDefault()}):s.jsx(Sb,{waitingLabel:U,waitingHint:Y,transportType:a}),g==="mouse"&&D&&s.jsx(wb,{cursorPos:ke,viewportRef:c,imgRef:u}),w.map(pe=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[pe.type];return s.jsxs("div",{style:{position:"absolute",left:pe.x,top:pe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},pe.id)})]}),s.jsx(kb,{inputMode:g,onToggleInputMode:xe,isImeOpen:j,setIsImeOpen:S,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ie,isConnActive:$,zoom:M,isMobile:v,mobileFillZoom:C,onZoomOut:()=>L(pe=>Math.max(.5,pe-.25)),onZoomReset:Se,onZoomIn:()=>L(pe=>Math.min(5,pe+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),s.jsx("style",{children:`
8
+ `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const M=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:M})]}),x&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:w})]})}if(d==="thought"){const M=typeof((C=t.meta)==null?void 0:C.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(Ff,{size:13}),s.jsx("span",{children:M})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),x&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const M=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",L=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:M}),s.jsx("span",{children:L})]}),x&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const p=t.meta,k=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",b=w,j=!1,S=b,v=k,g=!h&&!v&&Ud(S),N=["chat-message-row",h?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||x||h)&&s.jsxs("div",{className:`chat-bubble ${h?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:h?o||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||x)&&s.jsx(cb,{text:w}),n!=null&&s.jsx("span",{className:"chat-time",children:Od(n)})]})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:v}):s.jsx(ub,{content:S,renderAsPreformatted:v,renderAsMarkdown:g})}),j]})})},(e,t)=>(e.message===t.message||Rl(e.message)===Rl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),mb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:h,showActivityMessages:d=!1,emptyState:m,onLoadMore:f,isLoadingMore:x,hasMoreHistory:w,hiddenLiveCount:p=0,loadError:y,scrollToBottomRequestNonce:k,isVisible:b=!0},j){const{t:S}=Le("common"),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(0),A=l.useRef(""),T=l.useRef(""),M=l.useRef(!1),L=l.useRef(null),P=l.useRef(!1),B=l.useRef(null),K=l.useRef(!1),[F,R]=l.useState(new Set),[Q,E]=l.useState({showTop:!1,showBottom:!1}),I=l.useRef(!1),$=l.useRef(!1),D=l.useRef(b),U=l.useRef(b),Y=l.useRef(null);U.current=b;const ae=()=>{const _=v.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight<Ci:!0},z=l.useCallback(()=>{const _=v.current,te=_?jf(_):{showTop:!1,showBottom:!1};E(ve=>ve.showTop===te.showTop&&ve.showBottom===te.showBottom?ve:te)},[]),X=l.useCallback((_="auto")=>{var ve;const te=v.current;te&&(te.scrollTo({top:te.scrollHeight,behavior:_}),(ve=te.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),de=l.useCallback((_="auto")=>{var ve;const te=v.current;te&&(te.scrollTo({top:0,behavior:_}),(ve=te.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),re=l.useCallback(()=>{var H;const _=v.current,te=(H=window.getSelection)==null?void 0:H.call(window);if(!_||!te||te.rangeCount===0||te.isCollapsed){K.current=!1;return}const ve=te.anchorNode,ce=te.focusNode;K.current=!!(ve&&ce&&_.contains(ve)&&_.contains(ce))},[]),W=l.useMemo(()=>{const _=ob(t),te=su(t);return ib(lb(_,te,d))},[t,d]),oe=W.length===t.length?h:void 0,V=kf(W,oe),ie=l.useCallback(()=>{const _=v.current;if(!_||!c||!U.current)return;const te={top:_.scrollTop,fromBottom:Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),messageFingerprint:V};Y.current={contextKey:c,snapshot:te},Ln.set(c,te)},[c,V]),ke=l.useCallback((_="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,X(_)})},[X]),xe=l.useCallback(()=>{I.current=!1,P.current=!0,$.current=!0,B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},[]);l.useEffect(()=>{const _=!M.current,te=T.current!==c;if(T.current=c,_||te){M.current=!0;const ce=c?Ln.get(c):null,H=!!ce&&so(ce,V);I.current=H?qn(ce):!1,P.current=Nf(ce,V),K.current||(H?requestAnimationFrame(()=>{const fe=v.current;fe&&(Ko(fe,ce),I.current=qn(ce),z(),$.current=!0)}):ke("auto")),C.current=W.length,A.current=V;return}W.length>C.current;const ve=V!==A.current;Af({hasSelection:K.current,userScrolledUp:I.current,hasChatContentChanged:ve})&&ke("auto"),C.current=W.length,A.current=V},[V,c,W.length,ke,z]),l.useEffect(()=>{k&&(xe(),K.current||ke("auto"))},[xe,ke,k]),l.useEffect(()=>{const _=D.current;_&&!b&&ie(),U.current=b,D.current=b;const te=c?Ln.get(c):null;if(Sf(_,b,te,V)){if(!te)return;I.current=qn(te),P.current=!1,K.current||requestAnimationFrame(()=>{const ve=v.current;ve&&(Ko(ve,te),z())});return}},[b,c,V,xe,ie,ke,z]),l.useEffect(()=>()=>{const _=Y.current;_&&Ln.set(_.contextKey,_.snapshot),L.current!=null&&cancelAnimationFrame(L.current),B.current!=null&&window.clearTimeout(B.current)},[]),l.useEffect(()=>{const _=g.current,te=v.current;if(!_||!te)return;const ve=()=>{B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},ce=new ResizeObserver(()=>{z();const H=P.current;Tf({hasSelection:K.current,userScrolledUp:I.current,contextAutoScrollActive:H})&&(ke("auto"),H&&ve())});return ce.observe(_),te!==_&&ce.observe(te),()=>{ce.disconnect(),B.current!=null&&(window.clearTimeout(B.current),B.current=null)}},[ke,c,z]),l.useImperativeHandle(j,()=>({scrollToBottom:(_="smooth")=>{X(_)}}),[X]),l.useEffect(()=>{const _=v.current;if(!_)return;let te;const ve=()=>{ie(),clearTimeout(te),te=setTimeout(()=>{I.current=!ae(),z()},50)};return _.addEventListener("scroll",ve,{passive:!0}),()=>{_.removeEventListener("scroll",ve),clearTimeout(te)}},[ie,z]),l.useEffect(()=>(document.addEventListener("selectionchange",re),()=>document.removeEventListener("selectionchange",re)),[re]);const Se=l.useRef(0),pe=l.useRef(!1);l.useEffect(()=>{const _=v.current;if(!_||!pe.current||Se.current===0)return;const te=_.scrollHeight-Se.current;te>0&&(_.scrollTop=te),z(),ie(),Se.current=0,pe.current=!1},[W.length,ie,z]),l.useEffect(()=>{if($.current||!c)return;const _=Ln.get(c),te=v.current;if(!(!_||!te)){if(!so(_,V)){X("auto"),$.current=!0;return}Ko(te,_),I.current=qn(_),z(),$.current=!0}},[c,V,W.length,X,z]);const G=()=>{const _=v.current;_&&(Se.current=_.scrollHeight),pe.current=!0,f==null||f()},O=()=>{I.current=!0,de("smooth"),ie()},Z=()=>{xe(),X("smooth"),ie()},q=l.useMemo(()=>{const _=W.map((H,fe)=>({type:"message",data:H,index:fe,ts:bf(H,fe,u)}));if(!n||n.length===0)return _;const te=[...n].sort((H,fe)=>H.timestamp-fe.timestamp).map((H,fe)=>({type:"action",data:H,index:fe,ts:H.timestamp})),ve=[];let ce=0;for(const H of _){for(;ce<te.length&&H.ts>0&&te[ce].ts<H.ts;)ve.push(te[ce++]);ve.push(H)}for(;ce<te.length;)ve.push(te[ce++]);return ve},[W,n,u]),me=p>0||!!w,Te=p>0?p>80?S("chatList.showEarlierMessagesHidden",{count:Math.min(p,80),total:p}):S("chatList.showEarlierMessages",{count:Math.min(p,80)}):y?S("chatList.loadErrorRetry",{error:y}):S("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:g,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:S("chatList.loadingOlderMessages")}),me&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:G,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${y&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Te})}),q.length===0&&!me&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:S("chatList.waitingForMessages")})),q.map(_=>{if(_.type==="action"){const je=_.data;return s.jsx(hb,{log:je},`action-${_.index}`)}const te=_.data;_.index;const ve=to(te),ce=te.receivedAt||u[ve],H=`${c}-${ve}`,fe=F.has(H);return s.jsx(pb,{message:te,receivedAt:ce,agentName:r,userName:o,isCliMode:a,isTextExpanded:fe,onToggleTextExpanded:()=>R(je=>{const Ce=new Set(je);return fe?Ce.delete(H):Ce.add(H),Ce})},`msg-${ve}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:S("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(Q.showTop||Q.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":S("chatList.jumpToTop"),children:[Q.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:O,"aria-label":S("chatList.jumpToOldestMessages"),title:S("chatList.jumpToTop"),children:S("chatList.top")}),Q.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":S("chatList.jumpToLatestMessages"),title:S("chatList.jumpToBottom"),children:S("chatList.latest")})]})]})}),fb=l.memo(mb,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),bb="modulepreload",gb=function(e){return"/"+e},El={},xb=function(t,n,r){let o=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));o=Promise.allSettled(n.map(u=>{if(u=gb(u),u in El)return;El[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const m=document.createElement("link");if(m.rel=h?"stylesheet":bb,h||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),h)return new Promise((f,x)=>{m.addEventListener("load",f),m.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};let _l=!1;const au=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const c=l.useRef(null),[u,h]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),x=l.useRef(!1),w=l.useRef(!1),p=()=>{const y=c.current;if(y){m.current&&(y.clear(),m.current=!1);for(const k of d.current)y.write(k.data,k.onProcessed);d.current=[],f.current&&(y.fit(),f.current=!1),x.current&&(y.bumpResize(),x.current=!1),w.current&&(y.scrollToTop(),w.current=!1)}};return l.useImperativeHandle(i,()=>({write:(y,k)=>{c.current?c.current.write(y,k):d.current.push({data:y,onProcessed:k})},clear:()=>{c.current?c.current.clear():(d.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],m.current=!0)},resize:(y,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(y,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():x.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():w.current=!0},getSelection:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getSelection)==null?void 0:k.call(y))||""},getVisibleText:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getVisibleText)==null?void 0:k.call(y))||""}}),[]),l.useEffect(()=>{u&&p()},[u]),l.useEffect(()=>{let y=!1;return xb(()=>import("./terminal-BNQ0ACgR.js"),__vite__mapDeps([0,1,2])).then(k=>{_l||(_l=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||h(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{y=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:o,sizingMode:a,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});au.displayName="CliTerminal";function Ht(...e){return km(Sm(e))}const yb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},vb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...o},a){return s.jsx("div",{ref:a,className:Ht("border border-border-subtle bg-bg-secondary",yb[t],vb[n],r),...o})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ss,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function $l({value:e,max:t,label:n,color:r="#8b5cf6",detail:o,compact:a=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return a?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:n}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:n}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),o&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function wb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,o=r.getBoundingClientRect(),a=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,c=r.naturalHeight||o.height,u=i/c,h=o.width/o.height;let d,m,f,x;u>h?(d=o.width,m=o.width/u,f=0,x=(o.height-m)/2):(m=o.height,d=o.height*u,f=(o.width-d)/2,x=0);const w=o.left-a.left+f+d*e.nx,p=o.top-a.top+x+m*e.ny,y=Math.max(8,Math.min(a.width-8,w)),k=Math.max(8,Math.min(a.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-8,top:k-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function kb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:h,zoom:d,isMobile:m,mobileFillZoom:f,onZoomOut:x,onZoomReset:w,onZoomIn:p,transportType:y,screenshotUsage:k,lastActionStatus:b}){const{t:j}=Le("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:S=>S.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:j(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(S=>!S),a(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:j("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>c(S.target.value),onKeyDown:S=>{u(S)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{a(S=>!S),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:h?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:h?"#22c55e":"#eab308",boxShadow:h?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:h?"#22c55e":"#eab308"},children:j(h?"remote.connected":"remote.ws")})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:j("remote.directP2PTitle"),children:j("remote.direct")}),y==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:j("remote.turnRelayTitle"),children:j("remote.relay")}),k&&k.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:j("remote.dailyTurnTitle"),children:k.budgetExhausted?j("remote.turnBlocked"):j("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.dailyBudgetMinutes})}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),o&&s.jsxs("div",{onTouchStart:S=>S.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:j("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[j("remote.zoom")," ",d<=(m?f:1)+.01?j(m?"remote.fill":"remote.fit"):`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:S=>{S.stopPropagation(),x()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:S=>{S.stopPropagation(),w()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:j(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:S=>{S.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Sb({waitingLabel:e,waitingHint:t,transportType:n}){return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Cb(){if(typeof window>"u")return!1;try{return window.__ADHDEV_DEBUG_RENDERS__===!0||window.localStorage.getItem("adhdev_debug_renders")==="1"}catch{return window.__ADHDEV_DEBUG_RENDERS__===!0}}function Bl(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function mr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Cb())return;r.current+=1;const o=n.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Bl(c)]))}),n.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Bl(t[i])]))}),n.current=t})}function jb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:c,panYRef:u,setPanX:h,setPanY:d,setZoom:m,lastWheelTimeRef:f,onAction:x,setLastActionStatus:w,spawnRippleFromNormalized:p,clampPan:y,isMobile:k,mobileFillZoom:b}){const[j,S]=l.useState(null),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),T=l.useRef(0),M=l.useRef(null),L=l.useRef(1),P=l.useRef({x:0,y:0}),B=l.useRef(!1),K=l.useRef(r),F=l.useRef(x),R=30,Q=550,E=18,I=60,$=400,D=12,U=()=>{if(v.current)return;const z={nx:.5,ny:.5};v.current=z,S(z)};return l.useEffect(()=>{K.current=r,r==="mouse"&&U()},[r]),l.useEffect(()=>{F.current=x},[x]),l.useEffect(()=>{const z=e.current;if(!z)return;const X=ie=>{if(!n.current)return null;const ke=n.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(ie.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(ie.clientY-ke.top)/ke.height))}},de=(ie,ke)=>{if(!n.current)return{dnx:0,dny:0};const xe=n.current,Se=xe.getBoundingClientRect(),pe=xe.naturalWidth||Se.width,G=xe.naturalHeight||Se.height,O=pe/G,Z=Se.width/Se.height;let q,me;return O>Z?(q=Se.width,me=Se.width/O):(me=Se.height,q=Se.height*O),{dnx:ie/q,dny:ke/me}},re=(ie,ke,xe)=>{if(xe<=1.05)return;const Se=-(ie-.5)*100,pe=-(ke-.5)*100,G=y(Se,pe,xe);(Math.abs(G.x-c.current)>.1||Math.abs(G.y-u.current)>.1)&&(h(G.x),d(G.y),c.current=G.x,u.current=G.y)},W=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target))ie.preventDefault();else return;if(ie.touches.length===1){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},B.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!B.current)if(C.current=!0,K.current==="mouse"){const Se=v.current||{nx:.5,ny:.5};w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{})}else{const Se=X(xe);Se&&(w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{}))}},500);return}if(ie.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,B.current=!0;const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY;M.current=Math.sqrt(xe*xe+Se*Se),L.current=i.current,P.current={x:(ie.touches[0].clientX+ie.touches[1].clientX)/2,y:(ie.touches[0].clientY+ie.touches[1].clientY)/2}}},oe=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target)&&ie.preventDefault(),ie.touches.length===1&&N.current){const xe=ie.touches[0],Se=xe.clientX-N.current.x,pe=xe.clientY-N.current.y;if(!C.current&&g.current){const G=xe.clientX-g.current.x,O=xe.clientY-g.current.y;Math.sqrt(G*G+O*O)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(K.current==="mouse"){const G=de(Se,pe),O=v.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,O.nx+G.dnx)),q=Math.max(0,Math.min(1,O.ny+G.dny));v.current={nx:Z,ny:q},S({nx:Z,ny:q}),w(`Cursor: ${Math.round(Z*100)}%, ${Math.round(q*100)}%`),re(Z,q,i.current);const me=Date.now();me-f.current>=30&&(f.current=me,F.current("input_mouseMoved",{nx:Z,ny:q}).catch(()=>{}))}else if(i.current>1){const G=t.current;if(G){const O=G.clientWidth,Z=G.clientHeight,q=c.current+Se/O*100,me=u.current+pe/Z*100,Te=y(q,me,i.current);h(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}else{const G=X(xe);if(G){const O=Date.now();O-f.current>=40&&(f.current=O,w("Scroll"),F.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-Se*2.5),deltaY:Math.round(-pe*2.5)}).catch(()=>{}))}}N.current={x:xe.clientX,y:xe.clientY};return}if(ie.touches.length===2&&M.current!==null){const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY,G=Math.sqrt(xe*xe+Se*Se)/M.current,O=(ie.touches[0].clientX+ie.touches[1].clientX)/2,Z=(ie.touches[0].clientY+ie.touches[1].clientY)/2,q=O-P.current.x,me=Z-P.current.y,Te=Math.abs(G-1)>.03;if(K.current==="mouse"){if(Te){const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_}else if(Math.abs(q)>2||Math.abs(me)>2){const _=v.current||{nx:.5,ny:.5},te=Date.now();te-f.current>=30&&(f.current=te,w("Scroll"),F.current("input_wheel",{nx:_.nx,ny:_.ny,deltaX:Math.round(-q*3),deltaY:Math.round(-me*3)}).catch(()=>{}))}}else{const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_;const te=t.current;if(te&&_>1){const ve=te.clientWidth,ce=te.clientHeight,H=c.current+q/ve*100,fe=u.current+me/ce*100,je=y(H,fe,_);h(je.x),d(je.y),c.current=je.x,u.current=je.y}}P.current={x:O,y:Z}}},V=ie=>{var ke;if(A.current&&clearTimeout(A.current),M.current=null,ie.touches.length===1&&B.current){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},C.current=!0;return}if(ie.touches.length===0){if(B.current){B.current=!1,C.current=!1;return}if(ie.changedTouches.length===1){const xe=ie.changedTouches[0],Se=Date.now(),pe=Se-(((ke=g.current)==null?void 0:ke.time)||0),G=g.current?xe.clientX-g.current.x:0,O=g.current?xe.clientY-g.current.y:0,Z=Math.sqrt(G*G+O*O);if(K.current==="mouse"){if(pe<R||pe>Q||Z>E){C.current=!1;return}const q=v.current||X(xe);q&&(w(`Click: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(pe<I||pe>$||Z>D){C.current=!1;return}const q=X(xe);if(!q)return;Se-T.current<300?(w("Double tap"),p(q.nx,q.ny,"double"),F.current("input_click",{...q,clickCount:2}).catch(()=>{}),T.current=0):(w(`Tap: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}),T.current=Se)}}C.current=!1}};return z.addEventListener("touchstart",W,{passive:!1}),z.addEventListener("touchmove",oe,{passive:!1}),z.addEventListener("touchend",V,{passive:!1}),()=>{z.removeEventListener("touchstart",W),z.removeEventListener("touchmove",oe),z.removeEventListener("touchend",V),A.current&&clearTimeout(A.current)}},[e,t,n,a,i,c,u,h,d,m,f,w,p,y]),{cursorPos:j,cursorPosRef:v,handleToggleInputMode:()=>{o(z=>{const X=z==="touch"?"mouse":"touch";return X==="mouse"&&U(),X})},handleZoomReset:()=>{const z=k?b:1;m(z),i.current=z,h(0),d(0),c.current=0,u.current=0}}}function iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:o,transportType:a}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[h,d]=l.useState(null),[m,f]=l.useState(""),[,x]=l.useState(!1),[w,p]=l.useState([]),y=l.useRef(0),[k,b]=l.useState(!1),[j,S]=l.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,N]=l.useState(v?"mouse":"touch"),[C,A]=l.useState(1),T=l.useRef(!1),[M,L]=l.useState(1),[P,B]=l.useState(0),[K,F]=l.useState(0);mr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:g,zoom:M,panX:P,panY:K,isMenuOpen:k,isImeOpen:j});const R=l.useRef(0),Q=l.useRef(M),E=l.useRef(P),I=l.useRef(K);l.useEffect(()=>{Q.current=M},[M]),l.useEffect(()=>{E.current=P},[P]),l.useEffect(()=>{I.current=K},[K]),l.useEffect(()=>{var pe;(pe=i.current)==null||pe.focus()},[]);const $=n==="connected",D=r,U=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!v||T.current||!D)return;const pe=u.current,G=c.current;if(!pe||!G)return;const O=()=>{const Z=G.clientWidth,q=G.clientHeight,me=pe.naturalWidth,Te=pe.naturalHeight;if(!me||!Te||!Z||!q)return;const _=Math.min(Z/me,q/Te),ve=Math.max(Z/me,q/Te)/_;ve>1.01&&(A(ve),L(ve),Q.current=ve),T.current=!0};pe.complete&&pe.naturalWidth?O():pe.addEventListener("load",O,{once:!0})},[D,v]);const ae=.5;l.useEffect(()=>{M<=ae&&(B(0),F(0))},[M,ae]);const z=(pe,G,O)=>{if(O<=ae)return{x:0,y:0};const Z=(O-1)/(2*O)*100,q=(O-1)/(2*O)*100;return{x:Math.max(-Z,Math.min(Z,pe)),y:Math.max(-q,Math.min(q,G))}},X=(pe,G)=>{if(!u.current)return null;const O=u.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(pe-O.left)/O.width)),ny:Math.max(0,Math.min(1,(G-O.top)/O.height))}},de=(pe,G,O)=>{const Z=c.current;if(!Z)return;const q=Z.getBoundingClientRect(),me=++y.current;p(Te=>[...Te,{id:me,x:pe-q.left,y:G-q.top,type:O}]),setTimeout(()=>p(Te=>Te.filter(_=>_.id!==me)),600)},re=(pe,G,O)=>{const Z=u.current,q=c.current;if(!Z||!q)return;const me=Z.getBoundingClientRect(),Te=q.getBoundingClientRect(),_=Z.naturalWidth||me.width,te=Z.naturalHeight||me.height,ve=_/te,ce=me.width/me.height;let H,fe,je,Ce;ve>ce?(H=me.width,fe=me.width/ve,je=0,Ce=(me.height-fe)/2):(fe=me.height,H=me.height*ve,je=(me.width-H)/2,Ce=0);const Be=me.left-Te.left+je+H*pe,Xe=me.top-Te.top+Ce+fe*G,dt=++y.current;p(it=>[...it,{id:dt,x:Be,y:Xe,type:O}]),setTimeout(()=>p(it=>it.filter(he=>he.id!==dt)),600)},W=async pe=>{var O;const G=X(pe.clientX,pe.clientY);if(G){d(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),de(pe.clientX,pe.clientY,"left"),(O=i.current)==null||O.focus();try{const Z=await e("input_click",{nx:G.nx,ny:G.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},oe=async(pe,G,O,Z=0)=>{try{await e("input_key",{type:O?"char":"keyDown",key:pe,code:G,text:O?pe:void 0,unmodifiedText:O?pe:void 0,modifiers:Z})}catch(q){t(`❌ Key error: ${q.message||q}`)}},V=async pe=>{if(pe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(pe.key)&&pe.preventDefault();let O=0;pe.altKey&&(O|=1),pe.ctrlKey&&(O|=2),pe.metaKey&&(O|=4),pe.shiftKey&&(O|=8),d(`Key: ${pe.key}`),await oe(pe.key,pe.code,pe.key.length===1,O)},ie=async pe=>{if(pe.key==="Enter"){if(pe.nativeEvent.isComposing)return;if(m){const G=m;f(""),d(`IME Sent: ${G}`);try{const O=await e("input_type",{text:G});O!=null&&O.success||t(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){t(`❌ IME error: ${O.message}`)}}else d("Key: Enter"),await oe("Enter","Enter",!1)}};l.useEffect(()=>{const pe=i.current;if(!pe)return;const G=O=>{var Z;if((Z=u.current)!=null&&Z.contains(O.target)){O.preventDefault();const q=Date.now();if(q-R.current<40)return;R.current=q;const me=X(O.clientX,O.clientY);if(!me)return;d(`Scroll: ${Math.round(O.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return pe.addEventListener("wheel",G,{passive:!1}),()=>pe.removeEventListener("wheel",G)},[e]);const{cursorPos:ke,handleToggleInputMode:xe,handleZoomReset:Se}=jb({containerRef:i,viewportRef:c,imgRef:u,inputMode:g,setInputMode:N,minZoom:ae,zoomRef:Q,panXRef:E,panYRef:I,setPanX:B,setPanY:F,setZoom:L,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:re,clampPan:z,isMobile:v,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:V,onContextMenu:pe=>pe.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[D?s.jsx("img",{ref:u,src:D,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${P}%, ${K}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:pe=>pe.preventDefault(),onDragStart:pe=>pe.preventDefault()}):s.jsx(Sb,{waitingLabel:U,waitingHint:Y,transportType:a}),g==="mouse"&&D&&s.jsx(wb,{cursorPos:ke,viewportRef:c,imgRef:u}),w.map(pe=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[pe.type];return s.jsxs("div",{style:{position:"absolute",left:pe.x,top:pe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},pe.id)})]}),s.jsx(kb,{inputMode:g,onToggleInputMode:xe,isImeOpen:j,setIsImeOpen:S,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ie,isConnActive:$,zoom:M,isMobile:v,mobileFillZoom:C,onZoomOut:()=>L(pe=>Math.max(.5,pe-.25)),onZoomReset:Se,onZoomIn:()=>L(pe=>Math.min(5,pe+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),s.jsx("style",{children:`
9
9
  @keyframes slideUp {
10
10
  from { opacity: 0; transform: translateY(6px); }
11
11
  to { opacity: 1; transform: translateY(0); }
@@ -45,15 +45,15 @@ ${JSON.stringify(t.bundle,null,2)}
45
45
  \`\`\`json
46
46
  ${JSON.stringify(t,null,2)}
47
47
  \`\`\``}function ta(e,t){return`${e}:${t}`}function pw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function mw(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sn(e,t){mw()&&console.debug(`[subscription-manager] ${e}`,t)}class fw{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,n,r,o,a){var d,m;const i=ta(r.topic,r.key),c=this.active.get(i);let u=!0;if(c)c.handlers.add(o),(!pw(c.request,r)||c.daemonId!==n)&&(c.daemonId=n,c.request=r,u=((d=t.sendData)==null?void 0:d.call(t,n,r))??!1,!u&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):u&&this.clearRetry(i),sn("subscribe_update",{daemonId:n,topic:r.topic,key:r.key,accepted:u})),c.lastUpdate&&o(c.lastUpdate);else{const f={daemonId:n,request:r,handlers:new Set([o])};this.active.set(i,f),sn("subscribe",{daemonId:n,topic:r.topic,key:r.key}),u=((m=t.sendData)==null?void 0:m.call(t,n,r))??!1,!u&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(i,t,a.retryIntervalMs)}const h=()=>{var w;this.clearRetry(i);const f=this.active.get(i);if(!f||(f.handlers.delete(o),f.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:r.topic,key:r.key};sn("unsubscribe",{daemonId:n,topic:r.topic,key:r.key}),(w=t.sendData)==null||w.call(t,n,x)};return h.initialSendAccepted=u,h}publish(t){const n=ta(t.topic,t.key),r=this.active.get(n);r&&(this.clearRetry(n),r.lastUpdate=t,bn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),r.handlers.forEach(o=>{o(t),bn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,n,r){const o=ta(t,n),a=this.active.get(o);a&&(a.request={...a.request,params:{...a.request.params,...r}})}resubscribeAll(t){var n;sn("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())(n=t.sendData)==null||n.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,n){var o;const r=Array.from(this.active.values()).filter(a=>a.daemonId===t);sn("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)(o=n.sendData)==null||o.call(n,a.daemonId,a.request)}scheduleRetry(t,n,r){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var c;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((c=n.sendData)==null?void 0:c.call(n,a.daemonId,a.request))??!1;sn("subscribe_retry",{id:t,accepted:i,topic:a.request.topic,key:a.request.key}),i||this.scheduleRetry(t,n,r)},r);this.retryTimers.set(t,o)}clearRetry(t){const n=this.retryTimers.get(t);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(t))}}const ls=new fw;function bw(e,t){const n=new Map;for(const r of e||[])if((r.daemonId||r.id.includes(":")&&r.id.split(":")[0]||"")===t&&r.sessionId){n.set(r.sessionId,{parentSessionId:r.parentSessionId,providerSessionId:r.providerSessionId,workspace:r.workspace??null,sessionCapabilities:r.sessionCapabilities,cdpConnected:r.cdpConnected,activeChat:r.activeChat,controlValues:r.controlValues,providerControls:r.providerControls,summaryMetadata:r.summaryMetadata,runtimeWriteOwner:r.runtimeWriteOwner,runtimeAttachedClients:r.runtimeAttachedClients,cliName:r.cliName,type:r.type,mode:r.mode,status:r.status,lastMessagePreview:r.lastMessagePreview,lastMessageRole:r.lastMessageRole,lastMessageAt:r.lastMessageAt,lastMessageHash:r.lastMessageHash,completionMarker:r.completionMarker,seenCompletionMarker:r.seenCompletionMarker,settings:r.settings,activeInteractivePrompt:r.activeInteractivePrompt});for(const a of r.childSessions||[]){if(!(a!=null&&a.id))continue;const i=n.get(a.id)||{};n.set(a.id,{...i,...a})}}return n}function gw(e){const t=[],n=new Map;for(const r of e)if(r.parentId){const o=n.get(r.parentId)||[];o.push(r),n.set(r.parentId,o)}else t.push(r);return{topLevel:t,childrenByParent:n}}function sa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function xw(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function yw(e){xw()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function ao(e,t){const n=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,c=i||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:h,childrenByParent:d}=gw(u),m=bw(a,r),f=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,x=h.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),w=h.filter(y=>y.kind==="agent"&&y.transport==="pty"),p=h.filter(y=>y.kind==="agent"&&y.transport==="acp");n.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...f&&{machine:f,platform:f.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:x.some(y=>!!y.cdpConnected)});for(const y of x){const k=m.get(y.id),b=zn(y,k),j=(d.get(y.id)||[]).map(S=>zn(S,m.get(S.id)));n.push({id:`${r}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:r,instanceId:sa(r,y.id),workspace:b.workspace,terminals:0,childSessions:j,agents:j.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c})}for(const y of w){const k=m.get(y.id),b=zn(y,k);n.push({id:`${r}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:r,instanceId:sa(r,y.id),cliName:b.providerName||b.providerType,mode:b.mode||(k==null?void 0:k.mode)||"terminal",workspace:b.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isCli:!0})}for(const y of p){const k=m.get(y.id),b=zn(y,k);n.push({id:`${r}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:r,instanceId:sa(r,y.id),cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isAcp:!0})}return yw(n),n}const vw=15e3,ww=15e3,kw=6e4,ac=12,Sw=8e3,Cw=4e3;function jw(e){const{force:t,hasSubscription:n,loadedAt:r,now:o,minFreshMs:a}=e;return t||r<=0?!0:n?!1:o-r>=a}const na=new Map,ra=new Map,Nr=new Set;function Nw(e){if(!e||typeof e!="object")return null;const t=e,n=t.status;if(n&&typeof n=="object")return n;const r=t.result;if(r&&typeof r=="object"&&"status"in r){const o=r.status;if(o&&typeof o=="object")return o}return t}function In(){const{sendCommand:e,sendData:t}=yt(),{injectEntries:n,getIdes:r}=or();return l.useCallback(async(o,a)=>{if(!o)return;const i=(a==null?void 0:a.minFreshMs)??kw;if(!jw({force:a==null?void 0:a.force,hasSubscription:Nr.has(o),loadedAt:ra.get(o)||0,now:Date.now(),minFreshMs:i}))return;const c=na.get(o);if(c)return c;const u=(async()=>{t&&!Nr.has(o)&&(ls.subscribe({sendData:t},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},p=>{const y=r(),k=y.find(j=>j.id===o),b=ao(p.status,{daemonId:o,existingDaemon:k,existingEntries:y,timestamp:p.timestamp});b.length>0&&n(b),ra.set(o,Date.now())}).initialSendAccepted?Nr.add(o):Nr.delete(o));const h=await e(o,"get_status_metadata"),d=Nw(h);if(!d)return;const m=r(),f=m.find(w=>w.id===o),x=ao(d,{daemonId:o,existingDaemon:f,existingEntries:m,timestamp:d.timestamp||Date.now()});x.length>0&&n(x,{authoritativeDaemonIds:[o]}),ra.set(o,Date.now())})().finally(()=>{na.delete(o)});return na.set(o,u),u},[r,n,e,t])}const Aw=60,Tw=50;function Ku(e={}){return e.isCliLike?Tw:Aw}function Iw(e={}){return Ku(e)}const fr=60,Mw=1e3,Dw=750,ic=500,Lo=12e4,zu=new Set(["generating","waiting_approval","starting","streaming","working"]),lr=new Map;let qu=0;const si=new Set;function Pw(){qu+=1;for(const e of si)e()}function Lw(e){return si.add(e),()=>{si.delete(e)}}function lc(){return qu}function br(e,t,n){return`${e}::${t}::${n||t}`}function io(e=fr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Rw([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Rw(e,t=fr){return{tailLimit:t}}function cc(e,t){const n=e[e.length-1];if(!n)return"empty:";let r="";try{r=JSON.stringify(n.content??"")}catch{r=String(n.content??"")}return["",e.length,String(n.id||""),String(n.index??""),String(n.receivedAt??n.timestamp??""),r].join("|")}function lo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(lo).join(`
48
- `);if(typeof e=="object"){const t=e;return lo(t.text??t.content??t.value??"")}return String(e)}function Gi(e){return lo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Ew(e){return e.length===0||e.every(Gi)}function dc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(r==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!Gi(e[t]))return r}return""}function uc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(r==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||Gi(e[t]))continue;if(r!=="assistant")return"";const a=e[t];return`${String(a.bubbleId??a.providerUnitKey??a.id??"")}#${lo(a.content).length}`}return""}function Vu(e,t){if(dc(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return dc(n)!=="assistant"}function _w(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function $w(e,t,n){return _w(n)?Vu(e,t):!1}function Yu(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Ju(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return zu.has(t)}function Qu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Bw(e,t,n,r,o,a){const i=Ju(r)||Yu(r),c=a&&e.hasLiveSnapshot;if(!i&&!c)return!1;const u=i?Qu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(Ew(n))return!0;if(c&&!i&&Vu(e,n))return!1;if(o&&typeof o=="object"){const h=o.selected,d=o.fallbackReason;if(h==="native-history"||typeof d=="string"&&d!==""&&!d.startsWith("native_history_"))return!1}return n.length<u}function Fw(e,t,n,r){if(n.length!==0||Qu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!r||typeof r!="object")return!1;const a=r.selected,i=r.fallbackReason,c=r.nativeSource;return a==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Hw(e,t,n,r,o,a){return Bw(e,t,n,r,o,a)?"defer-busy-shrink":Fw(e,t,n,o)?"skip-transient-empty":"apply"}function Ww(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function hc(e,t){const n=e[t];return typeof n=="string"?n:""}class Ow{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);this.manager=t.manager||ls,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.now=t.now??(()=>Date.now()),this.snapshot=io(Math.max(0,t.tailLimit??fr))}updateOptions(t){const n=this.sendData,r=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(n!==this.sendData||r!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...io(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const n=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,o=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o}),i=Array.isArray(a.messages)?a.messages:[],c=!r&&i.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,u=[...i,...this.snapshot.historyMessages],h=u.length>ic?u.slice(u.length-ic):u;this.snapshot={...this.snapshot,historyMessages:h,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<Dw)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const o=(async()=>{try{const a=await t();a&&this.handleUpdate(a)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Mw}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const n=hc(t,"sessionId");if(n&&n!==this.sessionId)return;const r=hc(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return;const o=Ww(t),a=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Lo;(Ju(t.status)||Yu(t.status))&&(this.lastActiveStatusAt=i);const u=$w(this.snapshot,o,a);if(!u&&Hw(this.snapshot,this.fallbackRecentCount,o,t.status,a,c)!=="apply")return;const h={tailLimit:this.snapshot.cursor.tailLimit};!u&&cc(this.snapshot.liveMessages)===cc(o)&&uc(this.snapshot.liveMessages)===uc(o)&&this.snapshot.cursor.tailLimit===h.tailLimit||(this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:h,messageSource:a},this.emit())}}function Xu(e){const t=br(e.daemonId,e.sessionId,e.historySessionId),n=lr.get(t);if(n)return n.updateOptions(e),n;const r=new Ow(e);return lr.set(t,r),Pw(),r}function Uw(e,t,n){if(!e||!t)return;const r=`${e}::${t}::`,o=br(e,t,n);for(const[a,i]of lr.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function Zu(e){const t=en(e),n=e.sessionId||"";if(!t||!n)return;const r=Io(e),o=br(t,n,r||n),a=lr.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}function Gw(e,t){return{...e,loadHistoryPage:t}}function Kw(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function zw(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(zu.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??Lo)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?r-a<=o:Array.isArray(e.messages)&&e.messages.length>0}function qw(e=Lo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Vw(e,t={}){const n=new Set,r=[];for(const o of e){if(!zw(o,t))continue;const a=en(o),i=o.sessionId||"";if(!a||!i)continue;const c=Io(o),u=br(a,i,c||i);n.has(u)||(n.add(u),r.push({daemonId:a,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(Kw),{descriptors:r,signature:r.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function Yw(e,t){const{sendData:n,sendCommand:r,isConnected:o}=yt(),a=(t==null?void 0:t.enabled)!==!1,i=en(e),c=e.sessionId||"",u=Io(e),h=`daemon:${i}:session:${c}`,d=Math.max(0,(t==null?void 0:t.tailLimit)??fr),m=e.messages.length,f=l.useMemo(()=>!a||!i||!c?null:Xu({daemonId:i,sessionId:c,historySessionId:u,subscriptionKey:h,sendData:n,tailLimit:d,fallbackRecentCount:m}),[i,a,u,n,c,h,d]);l.useEffect(()=>{f==null||f.updateOptions({fallbackRecentCount:m})},[f,m]);const[x,w]=l.useState(()=>(f==null?void 0:f.getSnapshot())||io(d));l.useEffect(()=>{if(!f){w(io(d));return}f.retain(),w(f.getSnapshot());const k=f.subscribe(b=>{w(b)});return()=>{k(),f.release()}},[f,d]);const p=l.useCallback(async()=>{!f||!i||!c||await f.loadHistoryPage(async({offset:k,excludeRecentCount:b})=>{const j=e.agentType,S=await r(i,"chat_history",{agentType:j,offset:k,limit:30,targetSessionId:c,historySessionId:u,excludeRecentCount:b}),v=S&&typeof S=="object"&&"result"in S?S.result||{}:S||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,f,i,u,r,c]),y=l.useCallback((k=!1)=>!f||!i||!c?Promise.resolve():f.refreshAuthoritativeTail(async()=>{const b=await r(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:u,...d>0?{tailLimit:d}:{}}),j=b&&typeof b=="object"&&"result"in b?b.result:b;if(!j||typeof j!="object"||j.success===!1)return null;const S=Array.isArray(j.messages)?j.messages:Array.isArray(j.messagesTail)?j.messagesTail:[];return{topic:"session.chat_tail",key:h,sessionId:c,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof j.status=="string"?j.status:"idle",...j.messageSource&&typeof j.messageSource=="object"?{messageSource:j.messageSource}:{}}},{force:k}),[e.agentType,f,i,u,r,c,h,d]);return l.useEffect(()=>{if(!f||!a||!i||!c)return;y(!0);const k=()=>{typeof document<"u"&&document.visibilityState==="visible"&&y()};typeof document<"u"&&document.addEventListener("visibilitychange",k);let b=o?o(i):!0;const j=setInterval(()=>{if(!o)return;const S=o(i);S&&!b&&y(),b=S},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",k),clearInterval(j)}},[f,i,a,c,u]),l.useMemo(()=>Gw(x,p),[p,x])}function Jw(e,t){const{sendData:n}=yt(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??fr),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Lo)),i=qw(a),[c,u]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const d=setInterval(()=>{u(m=>m+1)},i);return()=>{clearInterval(d)}},[e.length,r,i]);const h=l.useMemo(()=>Vw(e,{recentActivityMs:a}),[e,a,c]);l.useEffect(()=>{if(!r||!n||h.descriptors.length===0)return;const d=h.descriptors.map(m=>Xu({...m,sendData:n,tailLimit:o}));return d.forEach(m=>{m.retain()}),()=>{d.forEach(m=>m.release())}},[h.signature,r,n,o])}function Qw(e){const[t,n]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const u=en(c),h=c.sessionId||"";if(!u||!h)continue;const d=Io(c);i.push(br(u,h,d||h))}return i},[e]),o=r.join("|"),a=l.useSyncExternalStore(Lw,lc,lc);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const u=lr.get(c);if(!u)continue;let h=!1;i.push(u.subscribe(()=>{if(!h){h=!0;return}n(d=>d+1)}))}return()=>{for(const c of i)c()}},[o,a]),t}function Xw(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Zw(e){return Xw(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Kr=new Map,ni=new Set;function pc(e,t){!e||Kr.get(e)===t||(t?Kr.set(e,!0):Kr.delete(e),ni.forEach(r=>r(e,t)))}function e0(e){return e?Kr.get(e)===!0:!1}function t0(e){return ni.add(e),()=>{ni.delete(e)}}function s0(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function n0(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function r0(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function eh(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function th(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function o0(e){return eh(e)?!1:e.inboxBucket==="task_complete"&&th(e).length>0}function mc(e){return e.branch||"detached HEAD"}function a0(e){if(e.error)return`${mc(e)} · Git error: ${e.error}`;const t=[mc(e)];return e.changedFiles>0?t.push(s0(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function i0(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${a0(t)}`}function l0(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function c0(e,t={}){if(t.enabled===!1)return[];if(!r0(e))return[];const n=eh(e)?"working":o0(e)?"complete":null;if(!n)return[];const r=n==="complete"?th(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${n0(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:i0(n,e.git),timestamp:l0(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const d0=60;function u0(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function ri({activeConv:e,ideEntry:t,handleSendChat:n,handleForceSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:u,userName:h,scrollToBottomRequestNonce:d,isInputActive:m=!0,isVisible:f=!0}){var pe,G,O,Z,q,me,Te,_;const{t:x}=Le("common"),w=l.useRef(new Map),p=l.useRef(void 0),y=In(),{sendCommand:k}=yt(),{isVisible:b}=Li();mr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:u.length,isSendingChat:o});const j=Rt.useMemo(()=>An(e),[e.status,e.connectionState]);Rt.useEffect(()=>{const se=e.sessionId;if(se)return pc(se,j.isGenerating),()=>{pc(se,!1)}},[e.sessionId,j.isGenerating]);const S=l.useMemo(()=>ow(e,t),[e,t]),v=l.useMemo(()=>{var se;return $i((se=S.targetEntry)==null?void 0:se.providerControls,{hostIdeType:e.hostIdeType,providerType:S.providerType})},[e.hostIdeType,S.providerType,(pe=S.targetEntry)==null?void 0:pe.providerControls]),g=Ku({isCliLike:S.isCli||S.isAcp}),N=Iw({isCliLike:S.isCli||S.isAcp}),C=Yw(e,{enabled:f&&!!e.sessionId,tailLimit:N}),[A,T]=l.useState(g),[M,L]=l.useState(()=>Pl()),P=e.tabKey,B=C.historyMessages,K=C.hasMoreHistory,F=C.historyError,R=Lu(e,C),Q=su(R).length;l.useEffect(()=>{T(g)},[g,P]);const E=Math.max(0,R.length-A),I=Wi(e),$=en(e),D=Zw(e),U=Oi(e),Y=u0(e),ae=a||U,z=ae||Y,X=!!U,[de,re]=l.useState(!1);l.useEffect(()=>{const se=S.targetEntry;$&&(!se||se.providerControls===void 0||se.controlValues===void 0)&&y($,{minFreshMs:3e4}).catch(()=>{})},[$,S.isAcp,(G=S.targetEntry)==null?void 0:G.providerControls,(O=S.targetEntry)==null?void 0:O.controlValues,y]);const W=l.useCallback(async()=>{if(!de){if(R.length>A){T(se=>Math.min(R.length,se+d0));return}re(!0);try{await C.loadHistoryPage()}finally{re(!1)}}},[C,de,R.length,A]),{allMessages:oe,receivedAtMap:V}=l.useMemo(()=>{const se=Qv({historyMessages:B,liveMessages:R,visibleLiveCount:A}),ve=c0(e),ce=ve.length>0?[...se,...ve]:se,H={};return ce.forEach((fe,je)=>{const Ce=`${e.tabKey}:${to(fe)}`;let Be=Pu(fe)||w.current.get(Ce)||0;Be||(Be=Date.now(),w.current.set(Ce,Be)),H[to(fe)]=Be}),{allMessages:ce,receivedAtMap:H}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,B,R,A]),ie=l.useMemo(()=>u.filter(se=>se.routeId===e.tabKey).sort((se,ve)=>se.timestamp-ve.timestamp),[u,e.tabKey]),ke=l.useCallback(async()=>{var je,Ce;if(!$)return;const se=Wu({activeConv:e,visibleMessages:oe,actionLogs:u,controls:(je=S.targetEntry)==null?void 0:je.providerControls,controlValues:(Ce=S.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:v.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:K,historyError:F,historyMessages:B},ui:{controlsVisible:b,visibleLiveCount:A,activityVisible:M,activityCount:Q,hiddenLiveCount:E,isInputActive:m,isVisible:f}}),ve=await k($,"get_chat_debug_bundle",{agentType:S.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:se}),ce=er(ve),H=Gu(ce),fe=await Uu(H);fe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),pt.showToast(Ou(ce,{locatorCopyStatus:fe}),fe==="failed"?"warning":"success")},[e,u,Q,oe,b,C.hasLiveSnapshot,C.liveMessages,S.providerType,(Z=S.targetEntry)==null?void 0:Z.controlValues,(q=S.targetEntry)==null?void 0:q.providerControls,$,K,E,B,m,f,F,k,M,v.length,A]);l.useEffect(()=>{const se=ve=>{ve.key===eu&&L(Pl())};return window.addEventListener("storage",se),()=>window.removeEventListener("storage",se)},[]);const xe=l.useCallback(()=>{const se=hw(p.current);p.current=se.state,se.shouldCollect&&ke().catch(ve=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ve),pt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ke]),Se=l.useMemo(()=>{if(R.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:[x("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:x("chatPane.establishingP2P")})]})]});if((j.isGenerating||e.status==="streaming")&&re(!1),e.status==="not_monitored"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.switchingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Yd,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.openingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.openPanelHint")})]});if(e.status==="idle"&&!de)return!K&&B.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.noMessagesYet")})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.loadingChat")})]})}},[e.connectionState,e.status,D,i,K,B.length,c,de,R.length,I,j.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(zv,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((me=S.targetEntry)!=null&&me.muted),sendDaemonCommand:k}),s.jsx(Gv,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(fb,{messages:oe,actionLogs:ie,agentName:yn(e)||I||"Agent",userName:h,isCliMode:S.isCli||S.isAcp,isWorking:j.isGenerating,contextKey:e.tabKey,receivedAtMap:V,lastMessageHash:e.lastMessageHash,showActivityMessages:M,onLoadMore:W,isLoadingMore:de,hasMoreHistory:K,hiddenLiveCount:E,loadError:F??void 0,emptyState:Se,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(gv,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:S.providerType,displayLabel:S.displayLabel,controls:(Te=S.targetEntry)==null?void 0:Te.providerControls,controlValues:(_=S.targetEntry)==null?void 0:_.controlValues,currentStatus:e.status,coordinatorHint:Do(e),isActive:m,isCliTerminal:S.isCliTerminal}),!S.isCliTerminal&&s.jsx(Nu,{contextKey:e.tabKey,panelLabel:I,isSending:o,isBusy:X,statusMessage:z,inlineStatusMessage:ae,onSend:n,onForceSend:r,canForceSend:!!r&&j.isGenerating&&!X,isActive:m,showControlsToggle:v.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let sh=gs;function nh(){return sh()}class h0{constructor(){st(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var r;(r=this.listeners.get(t))==null||r.delete(n)}}emit(t,...n){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...n))}}let rh=new h0;class p0{sendPtyInput(t,n,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,r){return()=>{}}requestRuntimeSnapshot(t,n,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let kt=new p0;function m0(e){e.dashboardWS&&(rh=e.dashboardWS),e.connectionManager&&(kt=e.connectionManager),e.useDaemonsHook&&(sh=e.useDaemonsHook)}const f0=.5,b0=1.25,ns="\x1B",fc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function g0(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function bc(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const r=n.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return n}function x0(e,t){if(t in fc){const r=fc[t],o=g0(e);return o===1?`${ns}[${r}`:`${ns}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${ns}\r`:"\r";case"Escape":return e.alt?`${ns}${ns}`:ns;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${ns}${r}`:r}case"Tab":{const r=e.shift?`${ns}[Z`:" ";return e.alt&&!e.shift?`${ns} `:r}case"Space":{const r=bc(" ",e);return e.alt?`${ns}${r}`:r}}const n=bc(t,e);return e.alt?`${ns}${n}`:n}function xt(e){return Wi(e)}function vn(e){return Bu(e).join(" · ")}function oh(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function y0(e){var o,a,i;const t=[],n=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((a=e.coordinator)!=null&&a.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),r&&t.push("Coordinator"),t}function v0(e){var i,c,u;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",r=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((u=e.settings)==null?void 0:u.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",a=r||o;if(n&&t.push(`Mesh node: ${n}`),a&&t.push(`Coordinator: ${a}`),e.meshQueueStats){const{pending:h,assigned:d,completed:m,failed:f}=e.meshQueueStats;t.push(`Queue: ${h} pending, ${d} assigned, ${m} completed, ${f} failed`)}return t.join(" · ")}function ah(e,t){const n=$u(e,t);return n||(e.title?e.title:vn(e)||"No messages yet")}function ih(e,t){const{isReconnecting:n,isConnecting:r}=An(e);return n?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function w0(e,t){const n=["Chat",...Bu(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Gs(e){return ih(e)||vn(e)}function k0(e,t){return`${xt(e)} · ${ah(e,t)}`}function S0(e){const t=oo(e),n=t?$t(t):yn(e);return`${xt(e)} — ${n||"Agent"}`}function C0(e){return yn(e)||"CLI"}function lh(e){return _u(e)}function ch(e){return e?`Remote · ${xt(e)||e.workspaceName||"Session"}`:"Remote"}const gc=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],j0=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function N0(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Ki({cond:e,path:t,sections:n,onChange:r,onRemove:o,onPreview:a,preview:i}){const c=N0(e),u=i[t],h=d=>{const m=gc.find(f=>f.kind===d);m&&r(m.make(n))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:d=>h(d.target.value),className:"bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:gc.map(d=>s.jsx("option",{value:d.kind,children:d.label},d.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),u&&u!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${u.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:u.result?"match ✓":"no match"}),u==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),o&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:d=>r({...e,section:d.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),n.map(d=>s.jsx("option",{value:d,children:d},d))]}),s.jsx("input",{value:e.matches??"",onChange:d=>r({...e,matches:d.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(Ts,{label:"elapsed_ms",value:e.elapsed_ms,onChange:d=>r({elapsed_ms:d})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"stable_ms",value:e.stable_ms,onChange:d=>r({...e,stable_ms:d})}),s.jsx(Ts,{label:"cursor_above",value:e.cursor_above??0,onChange:d=>r({...e,cursor_above:d||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"cursor_above",value:e.cursor_above,onChange:d=>r({...e,cursor_above:d})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:d=>r({...e,changed:d.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(A0,{kind:c,cond:e,path:t,sections:n,onChange:r,onPreview:a,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(Ki,{cond:e.not,path:`${t}.not`,sections:n,onChange:d=>r({not:d}),onPreview:a,preview:i})})]})}function A0({kind:e,cond:t,path:n,sections:r,onChange:o,onPreview:a,preview:i}){const c=(e==="all"?t.all:t.any)??[],u=h=>o(e==="all"?{all:h}:{any:h});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((h,d)=>s.jsx(Ki,{cond:h,path:`${n}.${e}[${d}]`,sections:r,onChange:m=>u(c.map((f,x)=>x===d?m:f)),onRemove:()=>u(c.filter((m,f)=>f!==d)),onPreview:a,preview:i},d)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u([...c,{section:r[0],matches:""}]),children:"+ condition"}),j0.map(h=>s.jsxs("button",{type:"button",className:"text-[10px] text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>u([...c,JSON.parse(JSON.stringify(h.cond))]),title:"insert verified pattern",children:["+ ",h.label]},h.label))]})]})}function Ts({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>n(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function T0({sections:e,otherSectionIds:t,onChange:n,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(m=>[m.id,m])):{},c=(m,f)=>{if(!f||f===m||e[f])return;const x={};for(const[w,p]of Object.entries(e))x[w===m?f:w]=p;n(x)},u=(m,f)=>n({...e,[m]:f}),h=m=>{const f={...e};delete f[m],n(f)},d=()=>{let m="section",f=1;for(;e[m];)m=`section${f++}`;n({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:d,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-[10px] mb-1",children:o.error}),s.jsx("div",{className:"space-y-1.5",children:a.map(m=>{var p;const f=e[m],x=f.anchor!=null?"anchor":"positional",w=y=>{y==="anchor"?u(m,{anchor:f.anchor??"^",anchor_last:f.anchor_last,until:f.until}):u(m,{from_top:f.from_top??0,until:f.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:y=>c(m,y.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>h(m),children:"×"})]}),x==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(Ts,{label:"from_top",value:typeof f.from_top=="number"?f.from_top:0,onChange:y=>u(m,{...f,from_top:y,from_bottom:void 0})}),s.jsx(Ts,{label:"from_bottom",value:typeof f.from_bottom=="number"?f.from_bottom:0,onChange:y=>u(m,{...f,from_bottom:y||void 0})}),s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:f.anchor??"",onChange:y=>u(m,{...f,anchor:y.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!f.anchor_last,onChange:y=>u(m,{...f,anchor_last:y.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((p=f.anchor_context)==null?void 0:p.next)??"",onChange:y=>u(m,{...f,anchor_context:{...f.anchor_context,next:y.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-[9px] text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function xc({def:e,otherIds:t,onChange:n}){const r=e.until??"",o=r.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:["until",s.jsxs("select",{value:o?"__regex__":r,onChange:a=>{const i=a.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(a=>s.jsx("option",{value:a,children:a},a)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&s.jsx("input",{value:r,onChange:a=>n({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function I0({model:e,onChange:t,onPreview:n,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),u=l.useCallback(m=>t({...e,...m}),[e,t]),h=(m,f)=>u({states:e.states.map((x,w)=>w===m?{...x,...f}:x)}),d=(m,f)=>u({transitions:e.transitions.map((x,w)=>w===m?{...x,...f}:x)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(T0,{sections:e.sections??{},otherSectionIds:m=>c.filter(f=>f!==m),onChange:m=>u({sections:m}),onTest:()=>o(e.sections??{}),testResult:a}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:x=>h(f,{id:x.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:x=>h(f,{label:x.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>u({states:e.states.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>u({states:e.states.map((x,w)=>({...x,initial:w===f}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:x=>h(f,{modal:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:x=>h(f,{status:x.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},f))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"from"}),s.jsx(M0,{value:m.from,states:i,onChange:x=>d(f,{from:x})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:x=>d(f,{to:x.target.value}),className:"bg-bg-secondary text-status-online font-mono text-[10px] rounded border border-border-default px-1 py-0.5",children:i.map(x=>s.jsx("option",{value:x,children:x},x))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:x=>d(f,{label:x.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-[10px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u({transitions:e.transitions.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ts,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:x=>d(f,{min_hold_ms:x||void 0})}),s.jsx(Ts,{label:"priority",value:m.priority??0,onChange:x=>d(f,{priority:x||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d(f,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>d(f,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Ki,{cond:m.when,path:`t${f}`,sections:c,onChange:x=>d(f,{when:x}),onPreview:n,preview:r})]})]},f))})]})]})}function M0({value:e,states:t,onChange:n}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const u=t.filter(h=>c.has(h));n(u.length===1?u[0]:u)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Bn(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function yc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const D0={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},P0={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function oa(e){return P0[e]??"text-text-primary bg-bg-glass border border-border-default"}function Ar({children:e}){return s.jsx("div",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function Tr(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function dh({node:e,depth:t=0}){var o;const n=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:n,children:[r," "]}),s.jsx("span",{className:"text-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((a,i)=>s.jsx(dh,{node:a,depth:t+1},i))]})}function L0({t:e}){const[t,n]=l.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>n(o=>!o),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-text-secondary font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-status-online text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(dh,{node:e.cond})})]})}function R0({activeConv:e,onClose:t}){var ie,ke,xe,Se,pe;const{sendCommand:n}=yt(),[r,o]=l.useState(!0),[a,i]=l.useState(null),[c,u]=l.useState(null),[h,d]=l.useState(!1),[m,f]=l.useState(new Set(["footer"])),[x,w]=l.useState("Snapshot"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(""),[N,C]=l.useState(!1),[A,T]=l.useState("idle"),[M,L]=l.useState(null),[P,B]=l.useState([]),[K,F]=l.useState({}),[R,Q]=l.useState(null),[E,I]=l.useState(!1),$=e.daemonId||((ie=e.routeId)==null?void 0:ie.split(":")[0])||e.routeId||"",D=e.sessionId||"",U=l.useCallback(async()=>{o(!0),u(null);try{const G=await n($,"get_spec_debug",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;Z!=null&&Z.success?i(Z):(u((Z==null?void 0:Z.error)||"Failed to load spec debug"),i(null))}catch(G){u((G==null?void 0:G.message)||String(G)),i(null)}finally{o(!1)}},[n,$,D]);l.useEffect(()=>{U()},[U]),l.useEffect(()=>{if(!E)return;const G=setInterval(()=>{U()},1e3);return()=>clearInterval(G)},[E,U]),l.useEffect(()=>{const G=O=>{O.key==="Escape"&&!p&&t()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[t,p]);const Y=l.useCallback(async G=>{try{const O=await n($,"validate_spec",{content:JSON.stringify(G)}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;B(q!=null&&q.valid?[]:(q==null?void 0:q.errors)??["validation failed"])}catch(O){B([(O==null?void 0:O.message)||String(O)])}},[n,$]),ae=l.useCallback(async()=>{L(null),T("idle"),F({});try{const G=await n($,"get_spec_source",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){L((Z==null?void 0:Z.error)||"Failed to load spec source");return}g(Z.content);let q=null;try{q=JSON.parse(Z.content)}catch{}q&&q.$schema==="adhdev:cli/spec@4"?(b(q),S(!1),Y(q)):(b(null),S(!0)),C(!1),y(!0)}catch(G){L((G==null?void 0:G.message)||String(G))}},[n,$,D,Y]),z=l.useCallback(G=>{b(G),g(JSON.stringify(G,null,2)),C(!0),T("idle"),Y(G)},[Y]),X=l.useCallback(async(G,O)=>{F(Z=>({...Z,[G]:"loading"}));try{const Z=await n($,"eval_condition_preview",{targetSessionId:D,condition:O}),q=Z&&typeof Z=="object"?Z:{},me=q.result&&typeof q.result=="object"?q.result:q;!(me!=null&&me.success)||!me.result?F(Te=>({...Te,[G]:{result:!1,detail:me==null?void 0:me.error}})):F(Te=>({...Te,[G]:{result:me.result.result,detail:me.result.detail}}))}catch(Z){F(q=>({...q,[G]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[n,$,D]),de=l.useCallback(async G=>{Q("loading");try{const O=await n($,"resolve_section_preview",{targetSessionId:D,sections:G}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;!(q!=null&&q.success)||!Array.isArray(q.sections)?Q({error:(q==null?void 0:q.error)||"resolve failed"}):Q({sections:q.sections,screenLineCount:q.screenLineCount??0})}catch(O){Q({error:(O==null?void 0:O.message)||String(O)})}},[n,$,D]),re=l.useCallback(async()=>{var Z,q;const G=(Z=a==null?void 0:a.snapshot)==null?void 0:Z.specPath;if(!G){L("No spec path on this session");return}if(!j&&P.length>0){L("Fix validation errors before saving");return}const O=!j&&k?JSON.stringify(k,null,2):v;T("saving"),L(null);try{const me=await n($,"write_spec_source",{specPath:G,content:O}),Te=me&&typeof me=="object"?me:{},_=Te.result&&typeof Te.result=="object"?Te.result:Te;if(!(_!=null&&_.success)){T("error"),L(((q=_==null?void 0:_.validationErrors)==null?void 0:q.join(`
49
- `))||(_==null?void 0:_.error)||"Save failed");return}T("saved"),C(!1),setTimeout(()=>{U()},400),setTimeout(()=>T("idle"),1500)}catch(me){T("error"),L((me==null?void 0:me.message)||String(me))}},[n,$,(ke=a==null?void 0:a.snapshot)==null?void 0:ke.specPath,v,k,j,P,U]),W=a==null?void 0:a.snapshot,oe=async()=>{var _,se,ve;let G=a;G||(await U(),G=a);const O=G==null?void 0:G.snapshot,Z=[];if(Z.push("# Spec Debug Snapshot"),Z.push(`Generated: ${new Date().toISOString()}`),Z.push(`Session: ${(G==null?void 0:G.sessionId)??""} (${(G==null?void 0:G.providerType)??""})`),Z.push(`Spec: ${(O==null?void 0:O.spec_id)??""} (${(O==null?void 0:O.specPath)??""})`),Z.push(`Provider: ${(O==null?void 0:O.name)??""} (${(O==null?void 0:O.cliType)??""})`),Z.push(`Working dir: ${(O==null?void 0:O.workingDir)??""}`),Z.push(`Spawned: ${O!=null&&O.spawnedAtMs?new Date(O.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((_=O==null?void 0:O.current_state)==null?void 0:_.id)??"none"} (${((se=O==null?void 0:O.current_state)==null?void 0:se.label)??""})`),Z.push(`Status: ${(O==null?void 0:O.status)??""}`),Z.push(`Idle hold pending: ${(O==null?void 0:O.idleHoldPending)??!1}`),Z.push(`Exited: ${(O==null?void 0:O.exited)??!1}`),Z.push(`Last busy: ${O!=null&&O.lastBusyAt?Bn(O.lastBusyAt):""}`),Z.push(`Cursor: ${(O==null?void 0:O.cursorPosition)!=null?`(${O.cursorPosition.row},${O.cursorPosition.col})`:"n/a"}`),(ve=O==null?void 0:O.completionIdleDebounce)!=null&&ve.active){const ce=O.completionIdleDebounce;Z.push(`completion_idle_after: age=${ce.ageMs}ms hold=${ce.holdMs}ms force=${ce.forceAfterMs}ms remaining=${Math.max(0,ce.holdMs-ce.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),O!=null&&O.current_modal){const ce=O.current_modal.buttons.map(H=>H.label).join(" / ");Z.push(`${O.current_modal.title??""} [${ce}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const q=O!=null&&O.stateHistory?[...O.stateHistory].reverse().slice(0,20):[];for(const ce of q){const H=ce.reason!=null?typeof ce.reason=="string"?ce.reason:JSON.stringify(ce.reason):"",fe=ce.debounceKind!=null?typeof ce.debounceKind=="string"?ce.debounceKind:JSON.stringify(ce.debounceKind):"",je=ce.matchedStateId!=null?String(ce.matchedStateId):"",Ce=(ce.matchedRules??[]).map(Be=>typeof Be=="string"?Be:JSON.stringify(Be)).join(", ");Z.push(`- ${ce.stateId} @ ${new Date(ce.at).toISOString()} held ${ce.durationMs}ms | reason: ${H} | debounce: ${fe} | eval→${je} | rules: ${Ce}`)}if(Z.push(""),Z.push("## Sections"),O!=null&&O.sections)for(const[ce,H]of Object.entries(O.sections)){const fe=H.split(`
48
+ `);if(typeof e=="object"){const t=e;return lo(t.text??t.content??t.value??"")}return String(e)}function Gi(e){return lo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Ew(e){return e.length===0||e.every(Gi)}function dc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(r==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!Gi(e[t]))return r}return""}function uc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(r==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||Gi(e[t]))continue;if(r!=="assistant")return"";const a=e[t];return`${String(a.bubbleId??a.providerUnitKey??a.id??"")}#${lo(a.content).length}`}return""}function Vu(e,t){if(dc(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return dc(n)!=="assistant"}function _w(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function $w(e,t,n){return _w(n)?Vu(e,t):!1}function Yu(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Ju(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return zu.has(t)}function Qu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Bw(e,t,n,r,o,a){const i=Ju(r)||Yu(r),c=a&&e.hasLiveSnapshot;if(!i&&!c)return!1;const u=i?Qu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(Ew(n))return!0;if(c&&!i&&Vu(e,n))return!1;if(o&&typeof o=="object"){const h=o.selected,d=o.fallbackReason;if(h==="native-history"||typeof d=="string"&&d!==""&&!d.startsWith("native_history_"))return!1}return n.length<u}function Fw(e,t,n,r){if(n.length!==0||Qu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!r||typeof r!="object")return!1;const a=r.selected,i=r.fallbackReason,c=r.nativeSource;return a==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Hw(e,t,n,r,o,a){return Bw(e,t,n,r,o,a)?"defer-busy-shrink":Fw(e,t,n,o)?"skip-transient-empty":"apply"}function Ww(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function hc(e,t){const n=e[t];return typeof n=="string"?n:""}class Ow{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);this.manager=t.manager||ls,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.now=t.now??(()=>Date.now()),this.snapshot=io(Math.max(0,t.tailLimit??fr))}updateOptions(t){const n=this.sendData,r=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(n!==this.sendData||r!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...io(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const n=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,o=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o}),i=Array.isArray(a.messages)?a.messages:[],c=!r&&i.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,u=[...i,...this.snapshot.historyMessages],h=u.length>ic?u.slice(u.length-ic):u;this.snapshot={...this.snapshot,historyMessages:h,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<Dw)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const o=(async()=>{try{const a=await t();a&&this.handleUpdate(a)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Mw}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const n=hc(t,"sessionId");if(n&&n!==this.sessionId)return;const r=hc(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return;const o=Ww(t),a=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Lo;(Ju(t.status)||Yu(t.status))&&(this.lastActiveStatusAt=i);const u=$w(this.snapshot,o,a);if(!u&&Hw(this.snapshot,this.fallbackRecentCount,o,t.status,a,c)!=="apply")return;const h={tailLimit:this.snapshot.cursor.tailLimit};!u&&cc(this.snapshot.liveMessages)===cc(o)&&uc(this.snapshot.liveMessages)===uc(o)&&this.snapshot.cursor.tailLimit===h.tailLimit||(this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:h,messageSource:a},this.emit())}}function Xu(e){const t=br(e.daemonId,e.sessionId,e.historySessionId),n=lr.get(t);if(n)return n.updateOptions(e),n;const r=new Ow(e);return lr.set(t,r),Pw(),r}function Uw(e,t,n){if(!e||!t)return;const r=`${e}::${t}::`,o=br(e,t,n);for(const[a,i]of lr.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function Zu(e){const t=en(e),n=e.sessionId||"";if(!t||!n)return;const r=Io(e),o=br(t,n,r||n),a=lr.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}function Gw(e,t){return{...e,loadHistoryPage:t}}function Kw(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function zw(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(zu.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??Lo)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?r-a<=o:Array.isArray(e.messages)&&e.messages.length>0}function qw(e=Lo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Vw(e,t={}){const n=new Set,r=[];for(const o of e){if(!zw(o,t))continue;const a=en(o),i=o.sessionId||"";if(!a||!i)continue;const c=Io(o),u=br(a,i,c||i);n.has(u)||(n.add(u),r.push({daemonId:a,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(Kw),{descriptors:r,signature:r.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function Yw(e,t){const{sendData:n,sendCommand:r,isConnected:o}=yt(),a=(t==null?void 0:t.enabled)!==!1,i=en(e),c=e.sessionId||"",u=Io(e),h=`daemon:${i}:session:${c}`,d=Math.max(0,(t==null?void 0:t.tailLimit)??fr),m=e.messages.length,f=l.useMemo(()=>!a||!i||!c?null:Xu({daemonId:i,sessionId:c,historySessionId:u,subscriptionKey:h,sendData:n,tailLimit:d,fallbackRecentCount:m}),[i,a,u,n,c,h,d]);l.useEffect(()=>{f==null||f.updateOptions({fallbackRecentCount:m})},[f,m]);const[x,w]=l.useState(()=>(f==null?void 0:f.getSnapshot())||io(d));l.useEffect(()=>{if(!f){w(io(d));return}f.retain(),w(f.getSnapshot());const k=f.subscribe(b=>{w(b)});return()=>{k(),f.release()}},[f,d]);const p=l.useCallback(async()=>{!f||!i||!c||await f.loadHistoryPage(async({offset:k,excludeRecentCount:b})=>{const j=e.agentType,S=await r(i,"chat_history",{agentType:j,offset:k,limit:30,targetSessionId:c,historySessionId:u,excludeRecentCount:b}),v=S&&typeof S=="object"&&"result"in S?S.result||{}:S||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,f,i,u,r,c]),y=l.useCallback((k=!1)=>!f||!i||!c?Promise.resolve():f.refreshAuthoritativeTail(async()=>{const b=await r(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:u,...d>0?{tailLimit:d}:{}}),j=b&&typeof b=="object"&&"result"in b?b.result:b;if(!j||typeof j!="object"||j.success===!1)return null;const S=Array.isArray(j.messages)?j.messages:Array.isArray(j.messagesTail)?j.messagesTail:[];return{topic:"session.chat_tail",key:h,sessionId:c,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof j.status=="string"?j.status:"idle",...j.messageSource&&typeof j.messageSource=="object"?{messageSource:j.messageSource}:{}}},{force:k}),[e.agentType,f,i,u,r,c,h,d]);return l.useEffect(()=>{if(!f||!a||!i||!c)return;y(!0);const k=()=>{typeof document<"u"&&document.visibilityState==="visible"&&y()};typeof document<"u"&&document.addEventListener("visibilitychange",k);let b=o?o(i):!0;const j=setInterval(()=>{if(!o)return;const S=o(i);S&&!b&&y(),b=S},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",k),clearInterval(j)}},[f,i,a,c,u]),l.useMemo(()=>Gw(x,p),[p,x])}function Jw(e,t){const{sendData:n}=yt(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??fr),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Lo)),i=qw(a),[c,u]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const d=setInterval(()=>{u(m=>m+1)},i);return()=>{clearInterval(d)}},[e.length,r,i]);const h=l.useMemo(()=>Vw(e,{recentActivityMs:a}),[e,a,c]);l.useEffect(()=>{if(!r||!n||h.descriptors.length===0)return;const d=h.descriptors.map(m=>Xu({...m,sendData:n,tailLimit:o}));return d.forEach(m=>{m.retain()}),()=>{d.forEach(m=>m.release())}},[h.signature,r,n,o])}function Qw(e){const[t,n]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const u=en(c),h=c.sessionId||"";if(!u||!h)continue;const d=Io(c);i.push(br(u,h,d||h))}return i},[e]),o=r.join("|"),a=l.useSyncExternalStore(Lw,lc,lc);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const u=lr.get(c);if(!u)continue;let h=!1;i.push(u.subscribe(()=>{if(!h){h=!0;return}n(d=>d+1)}))}return()=>{for(const c of i)c()}},[o,a]),t}function Xw(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Zw(e){return Xw(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Kr=new Map,ni=new Set;function pc(e,t){!e||Kr.get(e)===t||(t?Kr.set(e,!0):Kr.delete(e),ni.forEach(r=>r(e,t)))}function e0(e){return e?Kr.get(e)===!0:!1}function t0(e){return ni.add(e),()=>{ni.delete(e)}}function s0(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function n0(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function r0(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function eh(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function th(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function o0(e){return eh(e)?!1:e.inboxBucket==="task_complete"&&th(e).length>0}function mc(e){return e.branch||"detached HEAD"}function a0(e){if(e.error)return`${mc(e)} · Git error: ${e.error}`;const t=[mc(e)];return e.changedFiles>0?t.push(s0(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function i0(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${a0(t)}`}function l0(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function c0(e,t={}){if(t.enabled===!1)return[];if(!r0(e))return[];const n=eh(e)?"working":o0(e)?"complete":null;if(!n)return[];const r=n==="complete"?th(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${n0(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:i0(n,e.git),timestamp:l0(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const d0=60;function u0(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function ri({activeConv:e,ideEntry:t,handleSendChat:n,handleForceSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:u,userName:h,scrollToBottomRequestNonce:d,isInputActive:m=!0,isVisible:f=!0}){var pe,G,O,Z,q,me,Te,_;const{t:x}=Le("common"),w=l.useRef(new Map),p=l.useRef(void 0),y=In(),{sendCommand:k}=yt(),{isVisible:b}=Li();mr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:u.length,isSendingChat:o});const j=Rt.useMemo(()=>An(e),[e.status,e.connectionState]);Rt.useEffect(()=>{const te=e.sessionId;if(te)return pc(te,j.isGenerating),()=>{pc(te,!1)}},[e.sessionId,j.isGenerating]);const S=l.useMemo(()=>ow(e,t),[e,t]),v=l.useMemo(()=>{var te;return $i((te=S.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:S.providerType})},[e.hostIdeType,S.providerType,(pe=S.targetEntry)==null?void 0:pe.providerControls]),g=Ku({isCliLike:S.isCli||S.isAcp}),N=Iw({isCliLike:S.isCli||S.isAcp}),C=Yw(e,{enabled:f&&!!e.sessionId,tailLimit:N}),[A,T]=l.useState(g),[M,L]=l.useState(()=>Pl()),P=e.tabKey,B=C.historyMessages,K=C.hasMoreHistory,F=C.historyError,R=Lu(e,C),Q=su(R).length;l.useEffect(()=>{T(g)},[g,P]);const E=Math.max(0,R.length-A),I=Wi(e),$=en(e),D=Zw(e),U=Oi(e),Y=u0(e),ae=a||U,z=ae||Y,X=!!U,[de,re]=l.useState(!1);l.useEffect(()=>{const te=S.targetEntry;$&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&y($,{minFreshMs:3e4}).catch(()=>{})},[$,S.isAcp,(G=S.targetEntry)==null?void 0:G.providerControls,(O=S.targetEntry)==null?void 0:O.controlValues,y]);const W=l.useCallback(async()=>{if(!de){if(R.length>A){T(te=>Math.min(R.length,te+d0));return}re(!0);try{await C.loadHistoryPage()}finally{re(!1)}}},[C,de,R.length,A]),{allMessages:oe,receivedAtMap:V}=l.useMemo(()=>{const te=Qv({historyMessages:B,liveMessages:R,visibleLiveCount:A}),ve=c0(e),ce=ve.length>0?[...te,...ve]:te,H={};return ce.forEach((fe,je)=>{const Ce=`${e.tabKey}:${to(fe)}`;let Be=Pu(fe)||w.current.get(Ce)||0;Be||(Be=Date.now(),w.current.set(Ce,Be)),H[to(fe)]=Be}),{allMessages:ce,receivedAtMap:H}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,B,R,A]),ie=l.useMemo(()=>u.filter(te=>te.routeId===e.tabKey).sort((te,ve)=>te.timestamp-ve.timestamp),[u,e.tabKey]),ke=l.useCallback(async()=>{var je,Ce;if(!$)return;const te=Wu({activeConv:e,visibleMessages:oe,actionLogs:u,controls:(je=S.targetEntry)==null?void 0:je.providerControls,controlValues:(Ce=S.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:v.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:K,historyError:F,historyMessages:B},ui:{controlsVisible:b,visibleLiveCount:A,activityVisible:M,activityCount:Q,hiddenLiveCount:E,isInputActive:m,isVisible:f}}),ve=await k($,"get_chat_debug_bundle",{agentType:S.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),ce=er(ve),H=Gu(ce),fe=await Uu(H);fe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),pt.showToast(Ou(ce,{locatorCopyStatus:fe}),fe==="failed"?"warning":"success")},[e,u,Q,oe,b,C.hasLiveSnapshot,C.liveMessages,S.providerType,(Z=S.targetEntry)==null?void 0:Z.controlValues,(q=S.targetEntry)==null?void 0:q.providerControls,$,K,E,B,m,f,F,k,M,v.length,A]);l.useEffect(()=>{const te=ve=>{ve.key===eu&&L(Pl())};return window.addEventListener("storage",te),()=>window.removeEventListener("storage",te)},[]);const xe=l.useCallback(()=>{const te=hw(p.current);p.current=te.state,te.shouldCollect&&ke().catch(ve=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ve),pt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ke]),Se=l.useMemo(()=>{if(R.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:[x("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:x("chatPane.establishingP2P")})]})]});if((j.isGenerating||e.status==="streaming")&&re(!1),e.status==="not_monitored"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.switchingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Yd,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.openingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.openPanelHint")})]});if(e.status==="idle"&&!de)return!K&&B.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.noMessagesYet")})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.loadingChat")})]})}},[e.connectionState,e.status,D,i,K,B.length,c,de,R.length,I,j.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(zv,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((me=S.targetEntry)!=null&&me.muted),sendDaemonCommand:k}),s.jsx(Gv,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(fb,{messages:oe,actionLogs:ie,agentName:yn(e)||I||"Agent",userName:h,isCliMode:S.isCli||S.isAcp,isWorking:j.isGenerating,contextKey:e.tabKey,receivedAtMap:V,lastMessageHash:e.lastMessageHash,showActivityMessages:M,onLoadMore:W,isLoadingMore:de,hasMoreHistory:K,hiddenLiveCount:E,loadError:F??void 0,emptyState:Se,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(gv,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:S.providerType,displayLabel:S.displayLabel,controls:(Te=S.targetEntry)==null?void 0:Te.providerControls,controlValues:(_=S.targetEntry)==null?void 0:_.controlValues,currentStatus:e.status,coordinatorHint:Do(e),isActive:m,isCliTerminal:S.isCliTerminal}),!S.isCliTerminal&&s.jsx(Nu,{contextKey:e.tabKey,panelLabel:I,isSending:o,isBusy:X,statusMessage:z,inlineStatusMessage:ae,onSend:n,onForceSend:r,canForceSend:!!r&&j.isGenerating&&!X,isActive:m,showControlsToggle:v.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let sh=gs;function nh(){return sh()}class h0{constructor(){st(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var r;(r=this.listeners.get(t))==null||r.delete(n)}}emit(t,...n){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...n))}}let rh=new h0;class p0{sendPtyInput(t,n,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,r){return()=>{}}requestRuntimeSnapshot(t,n,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let kt=new p0;function m0(e){e.dashboardWS&&(rh=e.dashboardWS),e.connectionManager&&(kt=e.connectionManager),e.useDaemonsHook&&(sh=e.useDaemonsHook)}const f0=.5,b0=1.25,ns="\x1B",fc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function g0(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function bc(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const r=n.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return n}function x0(e,t){if(t in fc){const r=fc[t],o=g0(e);return o===1?`${ns}[${r}`:`${ns}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${ns}\r`:"\r";case"Escape":return e.alt?`${ns}${ns}`:ns;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${ns}${r}`:r}case"Tab":{const r=e.shift?`${ns}[Z`:" ";return e.alt&&!e.shift?`${ns} `:r}case"Space":{const r=bc(" ",e);return e.alt?`${ns}${r}`:r}}const n=bc(t,e);return e.alt?`${ns}${n}`:n}function xt(e){return Wi(e)}function vn(e){return Bu(e).join(" · ")}function oh(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function y0(e){var o,a,i;const t=[],n=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((a=e.coordinator)!=null&&a.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),r&&t.push("Coordinator"),t}function v0(e){var i,c,u;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",r=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((u=e.settings)==null?void 0:u.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",a=r||o;if(n&&t.push(`Mesh node: ${n}`),a&&t.push(`Coordinator: ${a}`),e.meshQueueStats){const{pending:h,assigned:d,completed:m,failed:f}=e.meshQueueStats;t.push(`Queue: ${h} pending, ${d} assigned, ${m} completed, ${f} failed`)}return t.join(" · ")}function ah(e,t){const n=$u(e,t);return n||(e.title?e.title:vn(e)||"No messages yet")}function ih(e,t){const{isReconnecting:n,isConnecting:r}=An(e);return n?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function w0(e,t){const n=["Chat",...Bu(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Gs(e){return ih(e)||vn(e)}function k0(e,t){return`${xt(e)} · ${ah(e,t)}`}function S0(e){const t=oo(e),n=t?$t(t):yn(e);return`${xt(e)} — ${n||"Agent"}`}function C0(e){return yn(e)||"CLI"}function lh(e){return _u(e)}function ch(e){return e?`Remote · ${xt(e)||e.workspaceName||"Session"}`:"Remote"}const gc=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],j0=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function N0(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Ki({cond:e,path:t,sections:n,onChange:r,onRemove:o,onPreview:a,preview:i}){const c=N0(e),u=i[t],h=d=>{const m=gc.find(f=>f.kind===d);m&&r(m.make(n))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:d=>h(d.target.value),className:"bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:gc.map(d=>s.jsx("option",{value:d.kind,children:d.label},d.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),u&&u!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${u.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:u.result?"match ✓":"no match"}),u==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),o&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:d=>r({...e,section:d.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),n.map(d=>s.jsx("option",{value:d,children:d},d))]}),s.jsx("input",{value:e.matches??"",onChange:d=>r({...e,matches:d.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(Ts,{label:"elapsed_ms",value:e.elapsed_ms,onChange:d=>r({elapsed_ms:d})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"stable_ms",value:e.stable_ms,onChange:d=>r({...e,stable_ms:d})}),s.jsx(Ts,{label:"cursor_above",value:e.cursor_above??0,onChange:d=>r({...e,cursor_above:d||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"cursor_above",value:e.cursor_above,onChange:d=>r({...e,cursor_above:d})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:d=>r({...e,changed:d.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(A0,{kind:c,cond:e,path:t,sections:n,onChange:r,onPreview:a,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(Ki,{cond:e.not,path:`${t}.not`,sections:n,onChange:d=>r({not:d}),onPreview:a,preview:i})})]})}function A0({kind:e,cond:t,path:n,sections:r,onChange:o,onPreview:a,preview:i}){const c=(e==="all"?t.all:t.any)??[],u=h=>o(e==="all"?{all:h}:{any:h});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((h,d)=>s.jsx(Ki,{cond:h,path:`${n}.${e}[${d}]`,sections:r,onChange:m=>u(c.map((f,x)=>x===d?m:f)),onRemove:()=>u(c.filter((m,f)=>f!==d)),onPreview:a,preview:i},d)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u([...c,{section:r[0],matches:""}]),children:"+ condition"}),j0.map(h=>s.jsxs("button",{type:"button",className:"text-[10px] text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>u([...c,JSON.parse(JSON.stringify(h.cond))]),title:"insert verified pattern",children:["+ ",h.label]},h.label))]})]})}function Ts({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>n(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function T0({sections:e,otherSectionIds:t,onChange:n,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(m=>[m.id,m])):{},c=(m,f)=>{if(!f||f===m||e[f])return;const x={};for(const[w,p]of Object.entries(e))x[w===m?f:w]=p;n(x)},u=(m,f)=>n({...e,[m]:f}),h=m=>{const f={...e};delete f[m],n(f)},d=()=>{let m="section",f=1;for(;e[m];)m=`section${f++}`;n({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:d,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-[10px] mb-1",children:o.error}),s.jsx("div",{className:"space-y-1.5",children:a.map(m=>{var p;const f=e[m],x=f.anchor!=null?"anchor":"positional",w=y=>{y==="anchor"?u(m,{anchor:f.anchor??"^",anchor_last:f.anchor_last,until:f.until}):u(m,{from_top:f.from_top??0,until:f.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:y=>c(m,y.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>h(m),children:"×"})]}),x==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(Ts,{label:"from_top",value:typeof f.from_top=="number"?f.from_top:0,onChange:y=>u(m,{...f,from_top:y,from_bottom:void 0})}),s.jsx(Ts,{label:"from_bottom",value:typeof f.from_bottom=="number"?f.from_bottom:0,onChange:y=>u(m,{...f,from_bottom:y||void 0})}),s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:f.anchor??"",onChange:y=>u(m,{...f,anchor:y.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!f.anchor_last,onChange:y=>u(m,{...f,anchor_last:y.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((p=f.anchor_context)==null?void 0:p.next)??"",onChange:y=>u(m,{...f,anchor_context:{...f.anchor_context,next:y.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-[9px] text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function xc({def:e,otherIds:t,onChange:n}){const r=e.until??"",o=r.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:["until",s.jsxs("select",{value:o?"__regex__":r,onChange:a=>{const i=a.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(a=>s.jsx("option",{value:a,children:a},a)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&s.jsx("input",{value:r,onChange:a=>n({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function I0({model:e,onChange:t,onPreview:n,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),u=l.useCallback(m=>t({...e,...m}),[e,t]),h=(m,f)=>u({states:e.states.map((x,w)=>w===m?{...x,...f}:x)}),d=(m,f)=>u({transitions:e.transitions.map((x,w)=>w===m?{...x,...f}:x)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(T0,{sections:e.sections??{},otherSectionIds:m=>c.filter(f=>f!==m),onChange:m=>u({sections:m}),onTest:()=>o(e.sections??{}),testResult:a}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:x=>h(f,{id:x.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:x=>h(f,{label:x.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>u({states:e.states.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>u({states:e.states.map((x,w)=>({...x,initial:w===f}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:x=>h(f,{modal:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:x=>h(f,{status:x.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},f))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"from"}),s.jsx(M0,{value:m.from,states:i,onChange:x=>d(f,{from:x})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:x=>d(f,{to:x.target.value}),className:"bg-bg-secondary text-status-online font-mono text-[10px] rounded border border-border-default px-1 py-0.5",children:i.map(x=>s.jsx("option",{value:x,children:x},x))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:x=>d(f,{label:x.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-[10px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u({transitions:e.transitions.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ts,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:x=>d(f,{min_hold_ms:x||void 0})}),s.jsx(Ts,{label:"priority",value:m.priority??0,onChange:x=>d(f,{priority:x||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d(f,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>d(f,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Ki,{cond:m.when,path:`t${f}`,sections:c,onChange:x=>d(f,{when:x}),onPreview:n,preview:r})]})]},f))})]})]})}function M0({value:e,states:t,onChange:n}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const u=t.filter(h=>c.has(h));n(u.length===1?u[0]:u)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Bn(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function yc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const D0={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},P0={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function oa(e){return P0[e]??"text-text-primary bg-bg-glass border border-border-default"}function Ar({children:e}){return s.jsx("div",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function Tr(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function dh({node:e,depth:t=0}){var o;const n=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:n,children:[r," "]}),s.jsx("span",{className:"text-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((a,i)=>s.jsx(dh,{node:a,depth:t+1},i))]})}function L0({t:e}){const[t,n]=l.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>n(o=>!o),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-text-secondary font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-status-online text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(dh,{node:e.cond})})]})}function R0({activeConv:e,onClose:t}){var ie,ke,xe,Se,pe;const{sendCommand:n}=yt(),[r,o]=l.useState(!0),[a,i]=l.useState(null),[c,u]=l.useState(null),[h,d]=l.useState(!1),[m,f]=l.useState(new Set(["footer"])),[x,w]=l.useState("Snapshot"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(""),[N,C]=l.useState(!1),[A,T]=l.useState("idle"),[M,L]=l.useState(null),[P,B]=l.useState([]),[K,F]=l.useState({}),[R,Q]=l.useState(null),[E,I]=l.useState(!1),$=e.daemonId||((ie=e.routeId)==null?void 0:ie.split(":")[0])||e.routeId||"",D=e.sessionId||"",U=l.useCallback(async()=>{o(!0),u(null);try{const G=await n($,"get_spec_debug",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;Z!=null&&Z.success?i(Z):(u((Z==null?void 0:Z.error)||"Failed to load spec debug"),i(null))}catch(G){u((G==null?void 0:G.message)||String(G)),i(null)}finally{o(!1)}},[n,$,D]);l.useEffect(()=>{U()},[U]),l.useEffect(()=>{if(!E)return;const G=setInterval(()=>{U()},1e3);return()=>clearInterval(G)},[E,U]),l.useEffect(()=>{const G=O=>{O.key==="Escape"&&!p&&t()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[t,p]);const Y=l.useCallback(async G=>{try{const O=await n($,"validate_spec",{content:JSON.stringify(G)}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;B(q!=null&&q.valid?[]:(q==null?void 0:q.errors)??["validation failed"])}catch(O){B([(O==null?void 0:O.message)||String(O)])}},[n,$]),ae=l.useCallback(async()=>{L(null),T("idle"),F({});try{const G=await n($,"get_spec_source",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){L((Z==null?void 0:Z.error)||"Failed to load spec source");return}g(Z.content);let q=null;try{q=JSON.parse(Z.content)}catch{}q&&q.$schema==="adhdev:cli/spec@4"?(b(q),S(!1),Y(q)):(b(null),S(!0)),C(!1),y(!0)}catch(G){L((G==null?void 0:G.message)||String(G))}},[n,$,D,Y]),z=l.useCallback(G=>{b(G),g(JSON.stringify(G,null,2)),C(!0),T("idle"),Y(G)},[Y]),X=l.useCallback(async(G,O)=>{F(Z=>({...Z,[G]:"loading"}));try{const Z=await n($,"eval_condition_preview",{targetSessionId:D,condition:O}),q=Z&&typeof Z=="object"?Z:{},me=q.result&&typeof q.result=="object"?q.result:q;!(me!=null&&me.success)||!me.result?F(Te=>({...Te,[G]:{result:!1,detail:me==null?void 0:me.error}})):F(Te=>({...Te,[G]:{result:me.result.result,detail:me.result.detail}}))}catch(Z){F(q=>({...q,[G]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[n,$,D]),de=l.useCallback(async G=>{Q("loading");try{const O=await n($,"resolve_section_preview",{targetSessionId:D,sections:G}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;!(q!=null&&q.success)||!Array.isArray(q.sections)?Q({error:(q==null?void 0:q.error)||"resolve failed"}):Q({sections:q.sections,screenLineCount:q.screenLineCount??0})}catch(O){Q({error:(O==null?void 0:O.message)||String(O)})}},[n,$,D]),re=l.useCallback(async()=>{var Z,q;const G=(Z=a==null?void 0:a.snapshot)==null?void 0:Z.specPath;if(!G){L("No spec path on this session");return}if(!j&&P.length>0){L("Fix validation errors before saving");return}const O=!j&&k?JSON.stringify(k,null,2):v;T("saving"),L(null);try{const me=await n($,"write_spec_source",{specPath:G,content:O}),Te=me&&typeof me=="object"?me:{},_=Te.result&&typeof Te.result=="object"?Te.result:Te;if(!(_!=null&&_.success)){T("error"),L(((q=_==null?void 0:_.validationErrors)==null?void 0:q.join(`
49
+ `))||(_==null?void 0:_.error)||"Save failed");return}T("saved"),C(!1),setTimeout(()=>{U()},400),setTimeout(()=>T("idle"),1500)}catch(me){T("error"),L((me==null?void 0:me.message)||String(me))}},[n,$,(ke=a==null?void 0:a.snapshot)==null?void 0:ke.specPath,v,k,j,P,U]),W=a==null?void 0:a.snapshot,oe=async()=>{var _,te,ve;let G=a;G||(await U(),G=a);const O=G==null?void 0:G.snapshot,Z=[];if(Z.push("# Spec Debug Snapshot"),Z.push(`Generated: ${new Date().toISOString()}`),Z.push(`Session: ${(G==null?void 0:G.sessionId)??""} (${(G==null?void 0:G.providerType)??""})`),Z.push(`Spec: ${(O==null?void 0:O.spec_id)??""} (${(O==null?void 0:O.specPath)??""})`),Z.push(`Provider: ${(O==null?void 0:O.name)??""} (${(O==null?void 0:O.cliType)??""})`),Z.push(`Working dir: ${(O==null?void 0:O.workingDir)??""}`),Z.push(`Spawned: ${O!=null&&O.spawnedAtMs?new Date(O.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((_=O==null?void 0:O.current_state)==null?void 0:_.id)??"none"} (${((te=O==null?void 0:O.current_state)==null?void 0:te.label)??""})`),Z.push(`Status: ${(O==null?void 0:O.status)??""}`),Z.push(`Idle hold pending: ${(O==null?void 0:O.idleHoldPending)??!1}`),Z.push(`Exited: ${(O==null?void 0:O.exited)??!1}`),Z.push(`Last busy: ${O!=null&&O.lastBusyAt?Bn(O.lastBusyAt):""}`),Z.push(`Cursor: ${(O==null?void 0:O.cursorPosition)!=null?`(${O.cursorPosition.row},${O.cursorPosition.col})`:"n/a"}`),(ve=O==null?void 0:O.completionIdleDebounce)!=null&&ve.active){const ce=O.completionIdleDebounce;Z.push(`completion_idle_after: age=${ce.ageMs}ms hold=${ce.holdMs}ms force=${ce.forceAfterMs}ms remaining=${Math.max(0,ce.holdMs-ce.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),O!=null&&O.current_modal){const ce=O.current_modal.buttons.map(H=>H.label).join(" / ");Z.push(`${O.current_modal.title??""} [${ce}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const q=O!=null&&O.stateHistory?[...O.stateHistory].reverse().slice(0,20):[];for(const ce of q){const H=ce.reason!=null?typeof ce.reason=="string"?ce.reason:JSON.stringify(ce.reason):"",fe=ce.debounceKind!=null?typeof ce.debounceKind=="string"?ce.debounceKind:JSON.stringify(ce.debounceKind):"",je=ce.matchedStateId!=null?String(ce.matchedStateId):"",Ce=(ce.matchedRules??[]).map(Be=>typeof Be=="string"?Be:JSON.stringify(Be)).join(", ");Z.push(`- ${ce.stateId} @ ${new Date(ce.at).toISOString()} held ${ce.durationMs}ms | reason: ${H} | debounce: ${fe} | eval→${je} | rules: ${Ce}`)}if(Z.push(""),Z.push("## Sections"),O!=null&&O.sections)for(const[ce,H]of Object.entries(O.sections)){const fe=H.split(`
50
50
  `).slice(0,3).join(`
51
51
  `);Z.push(`${ce}: ${fe}`)}Z.push(""),Z.push("## Last Assistant Message");const Te=[...(O==null?void 0:O.messages)??(O==null?void 0:O.committedMessages)??[]].reverse().find(ce=>ce.role==="assistant");Z.push(Te?Te.content.slice(0,400):""),Z.push(""),Z.push("## Screen (first 50 lines)"),Z.push(O!=null&&O.screen?O.screen.split(`
52
52
  `).slice(0,50).join(`
53
53
  `):"");try{await navigator.clipboard.writeText(Z.join(`
54
54
  `)),w("Copied!"),setTimeout(()=>w("Snapshot"),1500)}catch(ce){console.error("[SpecDebugPanel] clipboard write failed",ce)}},V=G=>{f(O=>{const Z=new Set(O);return Z.has(G)?Z.delete(G):Z.add(G),Z})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:G=>G.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),W&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:W.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(W==null?void 0:W.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${p?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{p?y(!1):ae()},disabled:r,children:p?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{oe()},disabled:r,children:x}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{U()},disabled:r,children:r?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),p&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(j)try{const G=JSON.parse(v);b(G),Y(G)}catch{return}S(!1)},disabled:!k&&j,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{k&&g(JSON.stringify(k,null,2)),S(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:W==null?void 0:W.specPath,children:((W==null?void 0:W.specPath)??"").split("/").slice(-3).join("/")}),N&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!j&&P.length>0&&s.jsxs("span",{className:"text-status-error text-[10px]",children:[P.length," error",P.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${A==="saving"||!j&&P.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{re()},disabled:A==="saving"||!j&&P.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),M&&s.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:M}),!j&&P.length>0&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:P.map((G,O)=>s.jsx("div",{className:"font-mono",children:G},O))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:j||!k?s.jsx("textarea",{value:v,onChange:G=>{g(G.target.value),C(!0),T("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):s.jsx(I0,{model:k,onChange:z,onPreview:X,preview:K,onTestSections:de,sectionPreview:R})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:j?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!p&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),r&&!a&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),a&&!a.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",a.providerType||"unknown",")."]}),W&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[W.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Provider"}),s.jsxs("span",{className:"font-mono text-text-primary",children:[W.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",W.cliType,")"]})]})]}),W.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Dir"}),s.jsx("span",{className:"font-mono text-text-secondary truncate",title:W.workingDir,children:W.workingDir})]}),W.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Bn(W.spawnedAtMs)})]}):null,W.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Session"}),s.jsx("span",{className:"font-mono text-text-muted text-[10px] truncate",title:W.providerSessionId,children:W.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${W.current_state?oa(W.current_state.id):"text-text-muted"}`,children:W.current_state?W.current_state.id:"none"}),((xe=W.current_state)==null?void 0:xe.label)&&W.current_state.label!==W.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:W.current_state.label}),W.status&&W.status!==((Se=W.current_state)==null?void 0:Se.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${oa(W.status)} px-1 py-0.5 rounded text-[10px]`,children:W.status})]}),W.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),W.exited&&s.jsx("span",{className:"text-status-error text-[10px] bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),W.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[W.cursorPosition.row,",",W.cursorPosition.col]})]}),W.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Bn(W.lastBusyAt)})]})]}),((pe=W.completionIdleDebounce)==null?void 0:pe.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),s.jsxs("span",{className:"text-text-secondary",children:["age: ",s.jsxs("span",{className:"text-accent-primary",children:[W.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsxs("span",{className:"text-text-secondary",children:["hold: ",s.jsxs("span",{className:"text-text-secondary",children:[W.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[W.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:W.completionIdleDebounce.ageMs<W.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",W.completionIdleDebounce.holdMs-W.completionIdleDebounce.ageMs,"ms"]}):W.completionIdleDebounce.ageMs<W.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",W.completionIdleDebounce.forceAfterMs-W.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),W.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-text-secondary",children:W.current_modal.title||""}),W.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",W.current_modal.buttons.map(G=>G.label).join(" / "),"]"]})]}),W.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(Tr,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(Ar,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:W.fsm.currentState})," (held ",yc(W.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-text-muted cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:E,onChange:G=>I(G.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[W.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),W.fsm.transitions.map((G,O)=>s.jsx(L0,{t:G},O))]})]})]}),s.jsx(Tr,{}),W.sections&&Object.keys(W.sections).length>0&&s.jsxs("div",{children:[s.jsx(Ar,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(W.sections).map(([G,O])=>{var Te;const Z=m.has(G),q=O.split(`
55
55
  `),me=((Te=q[0])==null?void 0:Te.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>V(G),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Z?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:G}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:me}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[q.length,"L"]})]}),Z&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:O||"(empty)"})]},G)})})]}),s.jsx(Tr,{}),W.stateHistory&&W.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Ar,{children:["State History (",W.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...W.stateHistory].reverse().slice(0,20).map((G,O)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${oa(G.stateId)}`,children:G.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Bn(G.at)}),G.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:yc(G.durationMs)})]}),G.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${D0[String(G.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(G.reason)}),G.debounceKind&&String(G.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(G.debounceKind)]}),G.matchedStateId&&String(G.matchedStateId)!==G.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(G.matchedStateId)})]})]}),G.matchedRules&&G.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[G.matchedRules.slice(0,3).map((Z,q)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof Z=="string"?Z:JSON.stringify(Z)},q)),G.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",G.matchedRules.length-3," more"]})]})]},O))})]}),s.jsx(Tr,{}),(()=>{const G=W.messages??W.committedMessages??[];if(G.length===0)return null;const O=G.filter(me=>me.role==="user").length,Z=G.filter(me=>me.role==="assistant").length,q=[...G].reverse().find(me=>me.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Ar,{children:["Transcript (",G.length," — ",O,"u / ",Z,"a)"]}),q&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",q.receivedAt?Bn(q.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[q.content.slice(0,400),q.content.length>400?"…":""]})]})]})})(),W.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:W.specPath,children:W.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>d(G=>!G),children:[s.jsx("span",{className:"text-text-muted",children:h?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",W.screen?W.screen.split(`
56
- `).length:0," lines)"]})]}),h&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:W.screen||"(empty)"})]})]})]})]})})}function E0({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:c=!0}){var et;const{t:u}=Le("common");gs();const{sendPtyInput:h}=yt(),[d,m]=l.useState(!1),f=l.useRef(!1);f.current=d;const[x,w]=l.useState("Runtime terminal unavailable"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(!1),[N,C]=l.useState(1),[A,T]=l.useState(!1),[M,L]=l.useState(!1),[P,B]=l.useState(!1),[K,F]=l.useState(!1),[R,Q]=l.useState(!1),[E,I]=l.useState({width:0,height:0}),[$,D]=l.useState({width:0,height:0}),[U,Y]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[ae,z]=l.useState(null),X=l.useRef(null),de=l.useRef(null),re=l.useRef(!1),W=l.useRef(!1),oe=l.useRef(i),V=l.useRef(0),ie=l.useRef(!1),ke=l.useRef(""),xe=l.useRef(null),Se=l.useRef(!1),pe=l.useRef(!1),G=l.useRef(null),O=l.useRef(null),Z=l.useRef(null),q=32*1024,me=()=>{var ee,be,we,ze;return((be=(ee=X.current)==null?void 0:ee.ownerDocument)==null?void 0:be.defaultView)||((ze=(we=de.current)==null?void 0:we.ownerDocument)==null?void 0:ze.defaultView)||window},Te=ee=>{const be=me();return{ownerWindow:be,frameId:be.requestAnimationFrame(ee)}},_=()=>{const ee=G.current;if(ee){try{ee.ownerWindow.cancelAnimationFrame(ee.frameId)}catch{}G.current=null}},se=()=>{const ee=O.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}O.current=null}},ve=()=>{const ee=Z.current;if(ee){try{ee.ownerWindow.clearTimeout(ee.timeoutId)}catch{}Z.current=null}},ce=()=>{i&&G.current===null&&(G.current=Te(()=>{J()}))},H=e.tabKey,fe=e.sessionId||"",je=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Ce=Oi(e),Be=d?a||Ce:x,Xe=f0,dt=b0,it=.05,he=()=>{const ee=$.width,be=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(ee)||ee<=0||!Number.isFinite(be)||be<=0)return 1;const we=E.width/ee,ze=E.height/be;return Number(Math.min(dt,Math.max(Xe,Math.min(we,ze))).toFixed(2))},$e=he(),Fe=re.current&&N>$e,Ie=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*N)):E.width,ye=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*N)):E.height,Oe=()=>{Te(()=>{const ee=de.current;ee&&(ee.scrollLeft=0,ee.scrollTop=ee.scrollHeight-ee.clientHeight)})},ut=()=>{var ee,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,re.current||(W.current=!1,C(1)),G.current!==null&&_(),m(!1),w("Runtime terminal unavailable"),ve(),se(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(ee=n.current)==null?void 0:ee.reset)==null||be.call(ee)},at=()=>{var ee,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,G.current!==null&&_(),m(!0),w(""),ve(),se(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(ee=n.current)==null?void 0:ee.reset)==null||be.call(ee)},ht=()=>{pe.current&&(pe.current=!1,Te(()=>{var ee,be;(be=(ee=n.current)==null?void 0:ee.scrollToTop)==null||be.call(ee)}))},J=()=>{if(G.current=null,!i)return;const ee=ke.current;if(!ee)return;const be=ee.slice(0,q);ke.current=ee.slice(be.length);const we=n.current;if(!we){ke.current=be+ke.current,ce();return}we.write(be,()=>{if(ke.current.length>0){ce();return}ht()})},te=ee=>{ee&&(ke.current+=ee,ce())},le=(ee,be=0,we,ze,We={})=>{var qe,Ye,Tt,Wt;const tt=!!We.force;!tt&&be>0&&V.current>=be||!tt&&be===0&&ie.current||(V.current=be,be>0&&S(!0),m(!0),w(""),typeof we=="number"&&typeof ze=="number"&&we>0&&ze>0&&((Ye=(qe=n.current)==null?void 0:qe.resize)==null||Ye.call(qe,we,ze)),ke.current="",(Wt=(Tt=n.current)==null?void 0:Tt.reset)==null||Wt.call(Tt),ee?te(ee):ht())};l.useEffect(()=>{ut()},[fe]),l.useEffect(()=>{var be;if(!fe)return;const ee=((be=kt.onRuntimeEvent)==null?void 0:be.call(kt,fe,we=>{if(!(!we||we.sessionId!==fe)){if(we.type==="runtime_snapshot"){if(!i){xe.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}le(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){ie.current=!0,typeof we.seq=="number"&&(V.current=Math.max(V.current,we.seq),we.seq>0&&S(!0)),f.current||m(!0),f.current||w(""),typeof we.data=="string"&&te(we.data);return}if(we.type==="session_cleared"){if(!i){Se.current=!0,ke.current="",xe.current=null;return}at();return}if(we.type==="session_io_error"){const ze=typeof we.error=="string"&&we.error?we.error:typeof we.reason=="string"&&we.reason?we.reason:"unknown error";m(!1),w(`Runtime input failed: ${ze}`);return}}},je))||(()=>{});return()=>{ee()}},[je,fe,n,i]);const ue=async(ee={})=>{var be;if(!je||!fe)return{success:!1,error:"daemonId and sessionId are required"};ee.preserveStatus||w(ee.loadingMessage||"Loading runtime terminal...");try{const we=await((be=kt.requestRuntimeSnapshot)==null?void 0:be.call(kt,je,fe,{sinceSeq:ee.sinceSeq,force:ee.force}));return we&&we.success===!1?(ee.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${we.error}`)),we):we||{success:!0}}catch(we){const ze=(we==null?void 0:we.message)||String(we);return ee.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${ze}`)),{success:!1,error:ze}}},ge=async ee=>{var tt,qe;const be=((tt=X.current)==null?void 0:tt.ownerDocument)||document,we=be.defaultView||window,ze=(qe=we.navigator)==null?void 0:qe.clipboard;if(ze!=null&&ze.writeText&&we.isSecureContext)try{return await ze.writeText(ee),!0}catch{}let We=null;try{return We=be.createElement("textarea"),We.value=ee,We.setAttribute("readonly","true"),We.style.position="fixed",We.style.left="-9999px",We.style.top="0",be.body.appendChild(We),We.focus(),We.select(),be.execCommand("copy")}catch{return!1}finally{We==null||We.remove()}},Ae=ee=>{se(),z(ee);const be=me();O.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{O.current=null,z(we=>we===ee?null:we)},2200)}},Pe=ee=>{ve(),b(ee);const be=me();Z.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{Z.current=null,b(we=>we===ee?null:we)},2200)}},Ne=async()=>{var We,tt,qe,Ye;const ee=((tt=(We=n.current)==null?void 0:We.getSelection)==null?void 0:tt.call(We))||"",be=((Ye=(qe=n.current)==null?void 0:qe.getVisibleText)==null?void 0:Ye.call(qe))||"",we=ee.trimEnd()||be.trimEnd();if(!we){Ae("Nothing to copy");return}if(!await ge(we)){Ae("Copy failed");return}Ae(ee.trimEnd()?"Copied selection":"Copied visible terminal")},He=ee=>{if(!d||!i)return;((h==null?void 0:h(je,fe,ee))??!1)||Ae("Terminal input failed")},Ue=ee=>{He(x0({ctrl:M,alt:P,shift:K},ee)),L(!1),B(!1),F(!1)},Ze=async()=>{if(p)return;y(!0),b("Loading older terminal output..."),pe.current=!0;const ee=await ue({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(y(!1),(ee==null?void 0:ee.success)===!1){pe.current=!1,b(`Older terminal output unavailable: ${ee.error}`);return}g(!0),Pe("Older terminal output loaded"),Te(()=>{var be;(be=n.current)==null||be.bumpResize()})};l.useEffect(()=>{var be,we;if(!fe)return;je&&((be=kt.getState)==null?void 0:be.call(kt,je))==="connected"&&ue();const ee=(we=kt.onStateChange)==null?void 0:we.call(kt,(ze,We)=>{ze!==je||We!=="connected"||ue()});return()=>{ee==null||ee()}},[je,fe,n]),l.useEffect(()=>{t&&ut()},[t,H,n]),l.useEffect(()=>{var ze,We;const ee=X.current,be=(We=(ze=ee==null?void 0:ee.ownerDocument)==null?void 0:ze.defaultView)==null?void 0:We.ResizeObserver;if(!ee||!be)return;const we=new be(tt=>{const qe=tt[0];if(!qe)return;const{width:Ye,height:Tt}=qe.contentRect;I(Wt=>{const ss=Math.round(Ye),Me=Math.round(Tt);return Wt.width===ss&&Wt.height===Me?Wt:{width:ss,height:Me}})});return we.observe(ee),()=>we.disconnect()},[]),l.useEffect(()=>{if(re.current)return;const ee=he();!Number.isFinite(ee)||ee<=0||C(be=>W.current?ee<be-it?ee:be:(W.current=!0,ee))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{Fe&&Oe()},[Fe,ye,Ie]),l.useEffect(()=>{var we;const ee=oe.current;if(oe.current=i,!i)return;ee||g(!1),Se.current&&(Se.current=!1,at());const be=xe.current;be&&(xe.current=null,le(be.text,be.seq,be.cols,be.rows,{force:!!be.force})),je&&fe&&((we=kt.getState)==null?void 0:we.call(kt,je))==="connected"&&ue(),ke.current&&G.current===null&&ce(),Te(()=>{var ze;(ze=n.current)==null||ze.bumpResize()})},[je,i,fe]),l.useEffect(()=>()=>{G.current!==null&&_(),se(),ve()},[]),l.useEffect(()=>{const ee=ze=>{var tt;const We=ze.detail;We!=null&&We.sessionId&&We.sessionId!==fe||d&&((tt=n.current)==null||tt.bumpResize())},be=me(),we=be===window?[window]:[window,be];for(const ze of we)ze.addEventListener("adhdev:fit-cli-terminal",ee);return()=>{for(const ze of we)ze.removeEventListener("adhdev:fit-cli-terminal",ee)}},[d,fe,n]);const Ge=d&&j&&!v&&(U.atTop||!U.canScroll)||p||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Ge&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ze()},disabled:!fe||p,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(p?"terminal.loadingOlder":"terminal.loadOlderOutput")}),k&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[ae&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:ae}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>Q(ee=>!ee),title:"Spec debug — inspect current state, sections, and transition history",children:u("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ne()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ee=>!ee),disabled:!d,"aria-label":u(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":u("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",M,L],["Alt",P,B],["Shift",K,F]].map(([ee,be,we])=>s.jsx("button",{type:"button","aria-pressed":be,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${be?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>we(ze=>!ze),children:ee},ee))}),s.jsx("div",{className:"grid grid-cols-6 gap-1",children:"abcdefghijklmnopqrstuvwxyz0123456789".split("").map(ee=>s.jsx("button",{type:"button",className:"h-8 rounded-md border border-white/10 bg-white/[0.06] text-[12px] font-semibold uppercase hover:bg-white/[0.12]",onClick:()=>Ue(ee),children:ee},ee))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>He(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ue("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{re.current=!0,C(ee=>{const be=Math.max($e,Number((ee-.1).toFixed(2)));return be>$e&&Oe(),be})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{re.current=!0,C(ee=>{const be=Math.min(dt,Number((ee+.1).toFixed(2)));return be>$e&&Oe(),be})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:Fe?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:ye>0?`${ye}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(au,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:Y,onInput:ee=>{!d||(h==null||h(je,fe,ee))}})})})}),!d&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:x})]}),s.jsx(Nu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:o,isBusy:!!Ce,statusMessage:Be,inlineStatusMessage:Be,onSend:async ee=>Ce?!1:r(ee),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(R0,{activeConv:e,onClose:()=>Q(!1)})]})}const _0=5e3,$0=12e3;function B0(e){return e==="disconnected"||e==="reconnecting"}function F0({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:o=_0,reconnectActionDelayMs:a=$0}){const{t:i}=Le(),c=B0(e),[u,h]=l.useState(()=>!c||o<=0),[d,m]=l.useState(()=>!c||a<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){h(!1);return}if(f.current=!1,o<=0){f.current=!0,h(!0);return}h(!1);const g=setTimeout(()=>{f.current=!0,h(!0)},o);return()=>clearTimeout(g)},[o,c]),l.useEffect(()=>{if(!c){m(!1);return}if(a<=0){m(!0);return}m(!1);const g=setTimeout(()=>{m(!0)},a);return()=>clearTimeout(g)},[a,c]);const x=c?u:e==="offline"||e==="auth_failed",w=!!(r&&e!=="auth_failed"&&(!c||d)),p=l.useMemo(()=>!t||e!=="connected"?!1:o<=0||f.current,[o,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},S="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",v={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:S,style:v,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[y],border:b[y],color:j[y]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),w&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),p&&s.jsx("div",{className:S,style:v,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function uh({mode:e,onChange:t,compact:n=!1}){const{t:r}=Le("common"),o=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Ii,{size:o}):s.jsx(Zs,{size:o})})}const Bs="New session",H0="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function W0(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function O0(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function U0(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function co({git:e,className:t="",compact:n=!1}){const r=W0(e),o=O0(e);if(!r||!o)return null;const a=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${U0(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function G0({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const o=Object.values(r),a=o.filter(c=>c==="connected").length,i=o.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&a===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function vc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function wc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=Le(),c=jo(e.updatedAt),u=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${u?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[u?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),o()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),a()},children:i("notification.delete")})]})]})}function K0({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:h,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:x,inboxOpen:w,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:N,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:M,onOpenGitDialog:L,onOpenMeshGraph:P}){var Z;const{t:B}=Le(),{ides:K,p2pStates:F={}}=gs(),R=!!e&&ct(e)&&!lt(e),Q=!!e&&lt(e),E=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),I=c||(e?Ru(e)?"terminal":"chat":null),[$,D]=l.useState(!1),[U,Y]=l.useState(!1),ae=l.useRef(null),z=l.useRef(null),X=l.useRef(null),de=K.filter(q=>q.type==="adhdev-daemon"),re=G0({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:F}),W=B(re.titleKey),oe=re.subtitleKey?B(re.subtitleKey):null,V=re.tone==="connected"?"#22c55e":re.tone==="limited"?"#eab308":"#ef4444",ie=re.tone==="connected"?"0 0 4px #22c55e80":re.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ke=l.useMemo(()=>g.filter(q=>!q.readAt),[g]),xe=l.useMemo(()=>g.filter(q=>!!q.readAt),[g]),Se=l.useMemo(()=>ke.slice(0,9),[ke]),pe=N;l.useEffect(()=>{if(!w)return;const q=me=>{var Te;(Te=z.current)!=null&&Te.contains(me.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[w,p]),l.useEffect(()=>{if(!y)return;const q=me=>{var Te;(Te=X.current)!=null&&Te.contains(me.target)||k(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[y,k]),l.useEffect(()=>{if(!y&&!w)return;const q=me=>{if(!me.altKey)return;const Te=me.code.match(/^Digit([1-9])$/);if(!Te)return;const _=Number(Te[1])-1,se=y?d[_]:void 0,ve=w?Se[_]:void 0;if(!(!se&&!ve)){if(me.preventDefault(),me.stopPropagation(),se){m==null||m(se),k(!1);return}ve&&(C(ve),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[d,y,w,Se,k,p,C,m]),l.useEffect(()=>{const q=d.length;if(ae.current===null){ae.current=q;return}q>ae.current&&Y(!0),ae.current=q},[d.length]);const G=()=>Y(!1),O=q=>{if(!q)return;const me=r.find(Te=>Te.tabKey===q);me&&(h==null||h(me))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:B("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):B("dashboard.header.title")}),s.jsx("span",{title:W,"aria-label":W,className:"header-title-status-dot",style:{background:V,boxShadow:ie}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:V,boxShadow:ie}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[oe&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",oe]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Bs}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Bs,children:s.jsx(Mi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:B("dashboard.header.guide"),"aria-label":B("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),S&&s.jsx("span",{children:B("dashboard.header.guideShort")})]}),e&&(R||Q||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:vn(e)||xt(e),children:xt(e)}),L&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:B("dashboard.header.openGitStatus"),onClick:()=>L(e.daemonId,e.workspacePath),children:s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:B("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:B("dashboard.header.meshGraph")})]}),(R||Q)&&i&&s.jsxs(s.Fragment,{children:[R&&u&&I&&s.jsx(uh,{mode:I,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:B(Q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(At,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>o(e),className:"btn btn-secondary btn-sm",title:B("dashboard.header.chatHistory"),children:s.jsx(Ai,{size:14})}),!R&&!lt(e)&&s.jsx("button",{onClick:a,className:"btn btn-secondary btn-sm",title:B("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:z,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${U?" hidden-spawn-flash":""}`,onAnimationEnd:G,ref:X,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),D(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",D(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||D(!1)},onDrop:q=>{const me=q.dataTransfer.getData("text/tab-key");q.preventDefault(),D(!1),O(me)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${B("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${B("dashboard.hidden.dragHint")}`,children:[s.jsx(Ti,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${U?" hidden-badge-pop":""}`,children:d.length})]}),y&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:B("dashboard.hidden.title")}),s.jsx(vc,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:x,children:B("dashboard.hidden.resetPanels")}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),k(!1)},children:B("dashboard.hidden.restoreAll")})]})]}),e&&h&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:B("dashboard.hidden.hideCurrentTab")}),s.jsx(vc,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(q),k(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[q.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":B("dashboard.header.generating")}),xt(q)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(q)+1]}):null,vn(q)]})]},q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!w),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:B("dashboard.header.activityInbox"),children:[s.jsx(Nn,{size:16}),pe>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:pe})]}),w&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ke.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.unread")}),ke.map(q=>s.jsx(wc,{notification:q,shortcutIndex:Se.indexOf(q)>=0?Se.indexOf(q)+1:void 0,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.read")}),xe.map(q=>s.jsx(wc,{notification:q,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.inbox.empty")})]})]})]})]})}function Ft(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function z0(e,t){return String(e||"")!==String(t||"")}function q0(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!n&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||n&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
56
+ `).length:0," lines)"]})]}),h&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:W.screen||"(empty)"})]})]})]})]})})}function E0({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:c=!0}){var et;const{t:u}=Le("common");gs();const{sendPtyInput:h}=yt(),[d,m]=l.useState(!1),f=l.useRef(!1);f.current=d;const[x,w]=l.useState("Runtime terminal unavailable"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(!1),[N,C]=l.useState(1),[A,T]=l.useState(!1),[M,L]=l.useState(!1),[P,B]=l.useState(!1),[K,F]=l.useState(!1),[R,Q]=l.useState(!1),[E,I]=l.useState({width:0,height:0}),[$,D]=l.useState({width:0,height:0}),[U,Y]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[ae,z]=l.useState(null),X=l.useRef(null),de=l.useRef(null),re=l.useRef(!1),W=l.useRef(!1),oe=l.useRef(i),V=l.useRef(0),ie=l.useRef(!1),ke=l.useRef(""),xe=l.useRef(null),Se=l.useRef(!1),pe=l.useRef(!1),G=l.useRef(null),O=l.useRef(null),Z=l.useRef(null),q=32*1024,me=()=>{var se,be,we,ze;return((be=(se=X.current)==null?void 0:se.ownerDocument)==null?void 0:be.defaultView)||((ze=(we=de.current)==null?void 0:we.ownerDocument)==null?void 0:ze.defaultView)||window},Te=se=>{const be=me();return{ownerWindow:be,frameId:be.requestAnimationFrame(se)}},_=()=>{const se=G.current;if(se){try{se.ownerWindow.cancelAnimationFrame(se.frameId)}catch{}G.current=null}},te=()=>{const se=O.current;if(se){try{se.ownerWindow.clearTimeout(se.timeoutId)}catch{}O.current=null}},ve=()=>{const se=Z.current;if(se){try{se.ownerWindow.clearTimeout(se.timeoutId)}catch{}Z.current=null}},ce=()=>{i&&G.current===null&&(G.current=Te(()=>{J()}))},H=e.tabKey,fe=e.sessionId||"",je=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Ce=Oi(e),Be=d?a||Ce:x,Xe=f0,dt=b0,it=.05,he=()=>{const se=$.width,be=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(se)||se<=0||!Number.isFinite(be)||be<=0)return 1;const we=E.width/se,ze=E.height/be;return Number(Math.min(dt,Math.max(Xe,Math.min(we,ze))).toFixed(2))},$e=he(),Fe=re.current&&N>$e,Ie=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*N)):E.width,ye=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*N)):E.height,Oe=()=>{Te(()=>{const se=de.current;se&&(se.scrollLeft=0,se.scrollTop=se.scrollHeight-se.clientHeight)})},ut=()=>{var se,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,re.current||(W.current=!1,C(1)),G.current!==null&&_(),m(!1),w("Runtime terminal unavailable"),ve(),te(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(se=n.current)==null?void 0:se.reset)==null||be.call(se)},at=()=>{var se,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,G.current!==null&&_(),m(!0),w(""),ve(),te(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(se=n.current)==null?void 0:se.reset)==null||be.call(se)},ht=()=>{pe.current&&(pe.current=!1,Te(()=>{var se,be;(be=(se=n.current)==null?void 0:se.scrollToTop)==null||be.call(se)}))},J=()=>{if(G.current=null,!i)return;const se=ke.current;if(!se)return;const be=se.slice(0,q);ke.current=se.slice(be.length);const we=n.current;if(!we){ke.current=be+ke.current,ce();return}we.write(be,()=>{if(ke.current.length>0){ce();return}ht()})},ee=se=>{se&&(ke.current+=se,ce())},le=(se,be=0,we,ze,We={})=>{var qe,Ye,Tt,Wt;const tt=!!We.force;!tt&&be>0&&V.current>=be||!tt&&be===0&&ie.current||(V.current=be,be>0&&S(!0),m(!0),w(""),typeof we=="number"&&typeof ze=="number"&&we>0&&ze>0&&((Ye=(qe=n.current)==null?void 0:qe.resize)==null||Ye.call(qe,we,ze)),ke.current="",(Wt=(Tt=n.current)==null?void 0:Tt.reset)==null||Wt.call(Tt),se?ee(se):ht())};l.useEffect(()=>{ut()},[fe]),l.useEffect(()=>{var be;if(!fe)return;const se=((be=kt.onRuntimeEvent)==null?void 0:be.call(kt,fe,we=>{if(!(!we||we.sessionId!==fe)){if(we.type==="runtime_snapshot"){if(!i){xe.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}le(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){ie.current=!0,typeof we.seq=="number"&&(V.current=Math.max(V.current,we.seq),we.seq>0&&S(!0)),f.current||m(!0),f.current||w(""),typeof we.data=="string"&&ee(we.data);return}if(we.type==="session_cleared"){if(!i){Se.current=!0,ke.current="",xe.current=null;return}at();return}if(we.type==="session_io_error"){const ze=typeof we.error=="string"&&we.error?we.error:typeof we.reason=="string"&&we.reason?we.reason:"unknown error";m(!1),w(`Runtime input failed: ${ze}`);return}}},je))||(()=>{});return()=>{se()}},[je,fe,n,i]);const ue=async(se={})=>{var be;if(!je||!fe)return{success:!1,error:"daemonId and sessionId are required"};se.preserveStatus||w(se.loadingMessage||"Loading runtime terminal...");try{const we=await((be=kt.requestRuntimeSnapshot)==null?void 0:be.call(kt,je,fe,{sinceSeq:se.sinceSeq,force:se.force}));return we&&we.success===!1?(se.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${we.error}`)),we):we||{success:!0}}catch(we){const ze=(we==null?void 0:we.message)||String(we);return se.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${ze}`)),{success:!1,error:ze}}},ge=async se=>{var tt,qe;const be=((tt=X.current)==null?void 0:tt.ownerDocument)||document,we=be.defaultView||window,ze=(qe=we.navigator)==null?void 0:qe.clipboard;if(ze!=null&&ze.writeText&&we.isSecureContext)try{return await ze.writeText(se),!0}catch{}let We=null;try{return We=be.createElement("textarea"),We.value=se,We.setAttribute("readonly","true"),We.style.position="fixed",We.style.left="-9999px",We.style.top="0",be.body.appendChild(We),We.focus(),We.select(),be.execCommand("copy")}catch{return!1}finally{We==null||We.remove()}},Ae=se=>{te(),z(se);const be=me();O.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{O.current=null,z(we=>we===se?null:we)},2200)}},Pe=se=>{ve(),b(se);const be=me();Z.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{Z.current=null,b(we=>we===se?null:we)},2200)}},Ne=async()=>{var We,tt,qe,Ye;const se=((tt=(We=n.current)==null?void 0:We.getSelection)==null?void 0:tt.call(We))||"",be=((Ye=(qe=n.current)==null?void 0:qe.getVisibleText)==null?void 0:Ye.call(qe))||"",we=se.trimEnd()||be.trimEnd();if(!we){Ae("Nothing to copy");return}if(!await ge(we)){Ae("Copy failed");return}Ae(se.trimEnd()?"Copied selection":"Copied visible terminal")},He=se=>{if(!d||!i)return;((h==null?void 0:h(je,fe,se))??!1)||Ae("Terminal input failed")},Ke=se=>{He(x0({ctrl:M,alt:P,shift:K},se)),L(!1),B(!1),F(!1)},Ze=async()=>{if(p)return;y(!0),b("Loading older terminal output..."),pe.current=!0;const se=await ue({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(y(!1),(se==null?void 0:se.success)===!1){pe.current=!1,b(`Older terminal output unavailable: ${se.error}`);return}g(!0),Pe("Older terminal output loaded"),Te(()=>{var be;(be=n.current)==null||be.bumpResize()})};l.useEffect(()=>{var be,we;if(!fe)return;je&&((be=kt.getState)==null?void 0:be.call(kt,je))==="connected"&&ue();const se=(we=kt.onStateChange)==null?void 0:we.call(kt,(ze,We)=>{ze!==je||We!=="connected"||ue()});return()=>{se==null||se()}},[je,fe,n]),l.useEffect(()=>{t&&ut()},[t,H,n]),l.useEffect(()=>{var ze,We;const se=X.current,be=(We=(ze=se==null?void 0:se.ownerDocument)==null?void 0:ze.defaultView)==null?void 0:We.ResizeObserver;if(!se||!be)return;const we=new be(tt=>{const qe=tt[0];if(!qe)return;const{width:Ye,height:Tt}=qe.contentRect;I(Wt=>{const ss=Math.round(Ye),Me=Math.round(Tt);return Wt.width===ss&&Wt.height===Me?Wt:{width:ss,height:Me}})});return we.observe(se),()=>we.disconnect()},[]),l.useEffect(()=>{if(re.current)return;const se=he();!Number.isFinite(se)||se<=0||C(be=>W.current?se<be-it?se:be:(W.current=!0,se))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{Fe&&Oe()},[Fe,ye,Ie]),l.useEffect(()=>{var we;const se=oe.current;if(oe.current=i,!i)return;se||g(!1),Se.current&&(Se.current=!1,at());const be=xe.current;be&&(xe.current=null,le(be.text,be.seq,be.cols,be.rows,{force:!!be.force})),je&&fe&&((we=kt.getState)==null?void 0:we.call(kt,je))==="connected"&&ue(),ke.current&&G.current===null&&ce(),Te(()=>{var ze;(ze=n.current)==null||ze.bumpResize()})},[je,i,fe]),l.useEffect(()=>()=>{G.current!==null&&_(),te(),ve()},[]),l.useEffect(()=>{const se=ze=>{var tt;const We=ze.detail;We!=null&&We.sessionId&&We.sessionId!==fe||d&&((tt=n.current)==null||tt.bumpResize())},be=me(),we=be===window?[window]:[window,be];for(const ze of we)ze.addEventListener("adhdev:fit-cli-terminal",se);return()=>{for(const ze of we)ze.removeEventListener("adhdev:fit-cli-terminal",se)}},[d,fe,n]);const Ue=d&&j&&!v&&(U.atTop||!U.canScroll)||p||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Ue&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ze()},disabled:!fe||p,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(p?"terminal.loadingOlder":"terminal.loadOlderOutput")}),k&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[ae&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:ae}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>Q(se=>!se),title:"Spec debug — inspect current state, sections, and transition history",children:u("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ne()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(se=>!se),disabled:!d,"aria-label":u(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":u("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",M,L],["Alt",P,B],["Shift",K,F]].map(([se,be,we])=>s.jsx("button",{type:"button","aria-pressed":be,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${be?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>we(ze=>!ze),children:se},se))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>He(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{re.current=!0,C(se=>{const be=Math.max($e,Number((se-.1).toFixed(2)));return be>$e&&Oe(),be})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{re.current=!0,C(se=>{const be=Math.min(dt,Number((se+.1).toFixed(2)));return be>$e&&Oe(),be})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:Fe?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:ye>0?`${ye}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(au,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:Y,onInput:se=>{!d||(h==null||h(je,fe,se))}})})})}),!d&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:x})]}),s.jsx(Nu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:o,isBusy:!!Ce,statusMessage:Be,inlineStatusMessage:Be,onSend:async se=>Ce?!1:r(se),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(R0,{activeConv:e,onClose:()=>Q(!1)})]})}const _0=5e3,$0=12e3;function B0(e){return e==="disconnected"||e==="reconnecting"}function F0({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:o=_0,reconnectActionDelayMs:a=$0}){const{t:i}=Le(),c=B0(e),[u,h]=l.useState(()=>!c||o<=0),[d,m]=l.useState(()=>!c||a<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){h(!1);return}if(f.current=!1,o<=0){f.current=!0,h(!0);return}h(!1);const g=setTimeout(()=>{f.current=!0,h(!0)},o);return()=>clearTimeout(g)},[o,c]),l.useEffect(()=>{if(!c){m(!1);return}if(a<=0){m(!0);return}m(!1);const g=setTimeout(()=>{m(!0)},a);return()=>clearTimeout(g)},[a,c]);const x=c?u:e==="offline"||e==="auth_failed",w=!!(r&&e!=="auth_failed"&&(!c||d)),p=l.useMemo(()=>!t||e!=="connected"?!1:o<=0||f.current,[o,t,e]),y=e==="auth_failed"?"red":e==="offline"?"orange":"accent",k={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},S="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",v={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:S,style:v,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:k[y],border:b[y],color:j[y]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),w&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),p&&s.jsx("div",{className:S,style:v,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function uh({mode:e,onChange:t,compact:n=!1}){const{t:r}=Le("common"),o=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Ii,{size:o}):s.jsx(Zs,{size:o})})}const Bs="New session",H0="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function W0(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function O0(e){return!e||e.isGitRepo===!1||e.reason==="not_git_repo"?null:e.hasConflicts?"conflict":e.error?"error":e.dirty||e.changedFiles>0||e.ahead>0||e.behind>0?"dirty":"quiet"}function U0(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function co({git:e,className:t="",compact:n=!1}){const r=W0(e),o=O0(e);if(!r||!o)return null;const a=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${U0(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function G0({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const o=Object.values(r),a=o.filter(c=>c==="connected").length,i=o.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&a===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function vc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function wc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=Le(),c=jo(e.updatedAt),u=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${u?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[u?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),o()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),a()},children:i("notification.delete")})]})]})}function K0({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:h,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:x,inboxOpen:w,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:N,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:M,onOpenGitDialog:L,onOpenMeshGraph:P}){var Z;const{t:B}=Le(),{ides:K,p2pStates:F={}}=gs(),R=!!e&&ct(e)&&!lt(e),Q=!!e&&lt(e),E=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),I=c||(e?Ru(e)?"terminal":"chat":null),[$,D]=l.useState(!1),[U,Y]=l.useState(!1),ae=l.useRef(null),z=l.useRef(null),X=l.useRef(null),de=K.filter(q=>q.type==="adhdev-daemon"),re=G0({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:F}),W=B(re.titleKey),oe=re.subtitleKey?B(re.subtitleKey):null,V=re.tone==="connected"?"#22c55e":re.tone==="limited"?"#eab308":"#ef4444",ie=re.tone==="connected"?"0 0 4px #22c55e80":re.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ke=l.useMemo(()=>g.filter(q=>!q.readAt),[g]),xe=l.useMemo(()=>g.filter(q=>!!q.readAt),[g]),Se=l.useMemo(()=>ke.slice(0,9),[ke]),pe=N;l.useEffect(()=>{if(!w)return;const q=me=>{var Te;(Te=z.current)!=null&&Te.contains(me.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[w,p]),l.useEffect(()=>{if(!y)return;const q=me=>{var Te;(Te=X.current)!=null&&Te.contains(me.target)||k(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[y,k]),l.useEffect(()=>{if(!y&&!w)return;const q=me=>{if(!me.altKey)return;const Te=me.code.match(/^Digit([1-9])$/);if(!Te)return;const _=Number(Te[1])-1,te=y?d[_]:void 0,ve=w?Se[_]:void 0;if(!(!te&&!ve)){if(me.preventDefault(),me.stopPropagation(),te){m==null||m(te),k(!1);return}ve&&(C(ve),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[d,y,w,Se,k,p,C,m]),l.useEffect(()=>{const q=d.length;if(ae.current===null){ae.current=q;return}q>ae.current&&Y(!0),ae.current=q},[d.length]);const G=()=>Y(!1),O=q=>{if(!q)return;const me=r.find(Te=>Te.tabKey===q);me&&(h==null||h(me))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:B("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):B("dashboard.header.title")}),s.jsx("span",{title:W,"aria-label":W,className:"header-title-status-dot",style:{background:V,boxShadow:ie}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:V,boxShadow:ie}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[oe&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",oe]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Bs}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Bs,children:s.jsx(Mi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:B("dashboard.header.guide"),"aria-label":B("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),S&&s.jsx("span",{children:B("dashboard.header.guideShort")})]}),e&&(R||Q||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:vn(e)||xt(e),children:xt(e)}),L&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:B("dashboard.header.openGitStatus"),onClick:()=>L(e.daemonId,e.workspacePath),children:s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:B("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:B("dashboard.header.meshGraph")})]}),(R||Q)&&i&&s.jsxs(s.Fragment,{children:[R&&u&&I&&s.jsx(uh,{mode:I,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:B(Q?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(At,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>o(e),className:"btn btn-secondary btn-sm",title:B("dashboard.header.chatHistory"),children:s.jsx(Ai,{size:14})}),!R&&!lt(e)&&s.jsx("button",{onClick:a,className:"btn btn-secondary btn-sm",title:B("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:z,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${U?" hidden-spawn-flash":""}`,onAnimationEnd:G,ref:X,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),D(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",D(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||D(!1)},onDrop:q=>{const me=q.dataTransfer.getData("text/tab-key");q.preventDefault(),D(!1),O(me)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${B("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${B("dashboard.hidden.dragHint")}`,children:[s.jsx(Ti,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${U?" hidden-badge-pop":""}`,children:d.length})]}),y&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:B("dashboard.hidden.title")}),s.jsx(vc,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:x,children:B("dashboard.hidden.resetPanels")}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),k(!1)},children:B("dashboard.hidden.restoreAll")})]})]}),e&&h&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:B("dashboard.hidden.hideCurrentTab")}),s.jsx(vc,{value:v==null?void 0:v.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(q),k(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[q.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":B("dashboard.header.generating")}),xt(q)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(q)+1]}):null,vn(q)]})]},q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!w),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:B("dashboard.header.activityInbox"),children:[s.jsx(Nn,{size:16}),pe>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:pe})]}),w&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ke.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.unread")}),ke.map(q=>s.jsx(wc,{notification:q,shortcutIndex:Se.indexOf(q)>=0?Se.indexOf(q)+1:void 0,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.read")}),xe.map(q=>s.jsx(wc,{notification:q,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.inbox.empty")})]})]})]})]})}function Ft(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function z0(e,t){return String(e||"")!==String(t||"")}function q0(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!n&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||n&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
57
57
  `).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!vu(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
58
58
  `).includes(o)))}function V0(e,t="recent"){const n=e.slice();return n.sort((r,o)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(t==="messages"){const a=(Number(o.messageCount)||0)-(Number(r.messageCount)||0);if(a!==0)return a}return(Number(o.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function hh(e,t={}){return V0(q0(e,t),t.sortMode||"recent")}function oi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function ph(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Y0(e){return e?e("launch.startFresh"):"Start fresh"}function J0(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Q0(e){return e?e("launch.openSavedHistory"):"Open saved history"}function X0(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function zi(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Z0(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function ek(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function tk(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function uo(e,t,n){if(typeof e=="function"){const a=t,i=n;return a==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,o=t;return r==="start-fresh"?`Start fresh with ${o}?`:`Restart ${o}?`}function ho(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function po(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function mo(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function mh(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function fh(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function sk(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 bh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:h,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:x,onResumeSavedSession:w}){var L;const{t:p}=Le("common"),y=t.find(P=>P.id===e.routeId),k=(y==null?void 0:y.chats)||[],b=(L=y==null?void 0:y.activeChat)==null?void 0:L.id,j=ct(e)&&!lt(e),[S,v]=l.useState(()=>Ft()),g=c||S,N=String(u||"").trim(),C=P=>{if(h){h(P);return}v(P)},A=l.useMemo(()=>o.map(P=>{const B=String(P.workspace||"").trim();return P.canResume||B||!N?P:{...P,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,o]),T=l.useMemo(()=>hh(A,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[A,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),M=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:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:j?X0(p):p("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:S0(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:zi(p)})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!j&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:p(n?"historyModal.creating":"historyModal.startNewChat")}),j?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:g.textQuery,onChange:P=>C({...g,textQuery:P.target.value}),placeholder:p("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.workspaceQuery,onChange:P=>C({...g,workspaceQuery:P.target.value}),placeholder:p("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:g.modelQuery,onChange:P=>C({...g,modelQuery:P.target.value}),placeholder:p("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:g.sortMode,onChange:P=>C({...g,sortMode:P.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:p("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:p("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:p("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:g.resumableOnly,onChange:P=>C({...g,resumableOnly:P.target.checked})}),p("historyModal.resumeReadyOnly")]})]}),T.map(P=>{const B=e.providerSessionId===P.providerSessionId,K=B||!P.canResume||!!i,F=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!w||w(P)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||p("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:sk(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||p("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[P.workspace||p("historyModal.workspaceUnknown"),F?p("historyModal.selectedWorkspaceSuffix"):"",Js(P.summaryMetadata)?` · ${Js(P.summaryMetadata)}`:"",P.messageCount>0?` · ${p("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?p("historyModal.statusActive"):P.canResume?F?p("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?p("historyModal.statusResuming"):p("historyModal.statusResume"):p("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):k.map(P=>s.jsxs("div",{onClick:()=>{f(e.routeId,P.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||p("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:p("historyModal.statusActive")})]})]},P.id)),(j&&!a&&T.length===0||!j&&k.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Hf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?o.length>0?p("historyModal.noMatchingHistory"):Z0(p):p("historyModal.noRecentChats")})]}),j&&a&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:tk(p)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:x,disabled:r||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||a?p("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Co,{size:13})," ",j?ek(p):p("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?M:fn.createPortal(M,document.body)}const kc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function gh({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Le();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(o=>{const a=kc[o.type]||kc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=o.actions)!=null&&i.length||n&&n(o)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(o.id)},"aria-label":r("toast.dismiss"),children:s.jsx(At,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:r(a.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:o.message}),o.actions&&o.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:o.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:u=>{u.stopPropagation(),i.onClick(),t(o.id)},children:i.label},c))})]})]},o.id)})})}const nk=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function rk(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function ok(e,t){return xh(e)||t}function xh(e){var o,a,i;const t=(a=(o=e.summaryMetadata)==null?void 0:o.items)==null?void 0:a.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function ak(e){return xh(e)||void 0}function ik(e){return e.sessionId||e.instanceId||e.agentType}function yh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function vh(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Ny(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function qi(e,t={}){return lk(e,vh(e,t))}function lk(e,t={}){var f,x,w,p,y,k,b,j,S;const n=[],r=t.machineName,o=t.connectionState,a=rk(e),i=e.workspace||"",c=Py(e.type,{agentName:e.cliName}),u=ct(e)||lt(e)?c:$t(e.type),h=ok(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var g,N,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(g=v.activeChat)==null?void 0:g.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||$t(v.providerType),model:ak(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((N=v.activeChat)==null?void 0:N.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=nk(e);if(m){const v=e.sessionId||e.instanceId,g=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((x=e.settings)==null?void 0:x.meshNodeFor)||!((w=e.settings)!=null&&w.meshCoordinatorFor)&&((p=e.settings)==null?void 0:p.launchedByCoordinator),C=g?" (Coordinator)":N?" (Mesh Node)":"",A=c+C,T=(y=e.activeChat)==null?void 0:y.activeModal,M=T&&Array.isArray(T.buttons)&&T.buttons.length>0,L=Ly(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const K=(b=e.activeChat)==null?void 0:b.id,F=e.chats;if(K&&Array.isArray(F)&&F.length>0){const Y=F.find(ae=>ae.id===K||ae.id&&String(ae.id)===String(K));Y!=null&&Y.title&&String(Y.title).trim()&&(B=String(Y.title).trim())}const R=(ct(e)||lt(e),e.type),Q=(ct(e)||lt(e))&&zl(B,A,R)?"":B,E=P.messages||[],I=typeof K=="string"?K.trim():"",$=(ct(e)||lt(e))&&I===String(e.type||"").trim(),D=I&&!$?I:e.providerSessionId,U=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:D,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:A,agentType:R,status:L,title:Q,messages:E,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||Q||(ct(e)?e.mode==="chat"?A:`Terminal${C}`:A),displaySecondary:h,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:M?T.buttons:void 0,modalMessage:M?T.message:void 0,streamSource:"native",tabKey:Qo(v,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:U,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const v of d){const g=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,N=Ry(v),C=ik(v),A=`${e.id}:${C}`,T=v.title&&String(v.title).trim()||"",M=zl(T,v.agentName,v.agentType)?"":T,L=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||L.length>0||g||!!M||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const B=v.coordinator||(typeof((S=v.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:N,title:M,messages:L,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:v.git||e.git,displayPrimary:a||M||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:g?v.activeModal.buttons:void 0,modalMessage:g?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Qo(v.sessionId||v.instanceId,A),machineName:r,connectionState:o,settings:v.settings,coordinator:B,messageInput:v.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||u,displaySecondary:h,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Qo(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),n}function wh(e){return String(e.type||e.id||"").trim()}function fo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function ck(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(o=>o.type===n);return fo(r==null?void 0:r.modelOptions)}function dk(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(o=>o.type===n);return fo(r==null?void 0:r.thinkingLevelOptions)}function kh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:fo(n.modelOptions),thinking:fo(n.thinkingLevelOptions)});return t}function uk(e){var t;return e.category!=="cli"||!wh(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function wn(e){var r;const t=new Set,n=[];for(const o of e||[]){if(!uk(o))continue;const a=wh(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),c=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;n.push({type:a,label:i,icon:o.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return n}function kn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const o of t){const a=typeof o=="string"?o.trim():"";!a||n.has(a)||(n.add(a),r.push(a))}return r}function cr(e){return e.map(t=>t.type)}function hk(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function pk(e,t){return kn(e).filter(n=>n!==t)}function Sc(e,t,n){const r=kn(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(c=>c!==t);if(n==="top")return[t,...a];if(n==="bottom")return[...a,t];const i=n==="up"?Math.max(0,o-1):Math.min(a.length,o+1);return a.splice(i,0,t),a}function Cc({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function mk({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:o}){const[a,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(f=>[f.type,f])),[t]),u=l.useMemo(()=>kn(e),[e]),h=u.filter(f=>!c.has(f)).length,d=t.filter(f=>!u.includes(f.type)),m=()=>{a&&(n(hk(u,a)),i(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:u.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):u.map((f,x)=>{const w=c.get(f),p=!!w;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${p?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",x+1]}),(w==null?void 0:w.icon)&&s.jsx("span",{"aria-hidden":"true",children:w.icon}),s.jsx("span",{className:`font-mono text-[12px] ${p?"text-text-primary":"text-text-muted"}`,children:f}),p?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:w?`${w.label} · ${w.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||x===0,title:"Move up",onClick:()=>n(Sc(u,f,"up")),children:s.jsx(Cc,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:r||x===u.length-1,title:"Move down",onClick:()=>n(Sc(u,f,"down")),children:s.jsx(Cc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(pk(u,f)),children:"Remove"})]})]},f)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:a,onChange:f=>i(f.target.value),disabled:r||d.length===0,children:[s.jsx("option",{value:"",children:d.length?"Select provider…":"No additional detected CLI providers"}),d.map(f=>s.jsxs("option",{value:f.type,children:[f.label," (",f.type,")"]},f.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!a,onClick:m,children:"Add provider"}),o]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",h>0?` ${h} provider${h===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function fk(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Sh(e,t){const n=fk(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Ch=[{id:"antigravity",name:"Antigravity",icon:"🌀"},{id:"cursor",name:"Cursor",icon:"⚡"},{id:"kiro",name:"Kiro",icon:"🎯"},{id:"pearai",name:"PearAI",icon:"🍐"},{id:"trae",name:"Trae",icon:"🔮"},{id:"vscode",name:"VS Code",icon:"💙"},{id:"vscodium",name:"VSCodium",icon:"💚"},{id:"windsurf",name:"Windsurf",icon:"🏄"}],jh=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Nh=[{id:"cline",name:"Cline",icon:"🧠"},{id:"codex",name:"Codex",icon:"📦"},{id:"roo-code",name:"Roo Code",icon:"🦘"},{id:"claude-code-vscode",name:"Claude Code (VS Code)",icon:"🟠"}],bk=Ch,gk=jh,xk=Nh;function yk({icon:e,title:t,subtitle:n,badge:r,actions:o,className:a}){return s.jsxs("div",{className:Ht("dashboard-header",a),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),o&&s.jsx("div",{className:"flex gap-2",children:o})]})}function gr({icon:e,title:t,subtitle:n,badge:r,actions:o,widthClassName:a="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(yk,{icon:e,title:t,subtitle:n,badge:r,actions:o}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ht("mx-auto flex w-full flex-col gap-4",a,i),children:c})})]})}const ai="adhdev:themechange";function vk(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ln(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function cn(e){return e==="system"?vk():e}function Ah(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function zr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ai,{detail:{preference:e,theme:t}}))}function wk(){const e=ln(),t=cn(e);Ah(t),zr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Ah(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const h=u.matches?"light":"dark";r(h),zr("system",h)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const h=u.detail||{},d=h.preference,m=h.theme;t(d==="dark"||d==="light"||d==="system"?d:ln()),r(m==="dark"||m==="light"?m:cn(ln()))},c=u=>{if(u.key!=="theme")return;const h=ln(),d=cn(h);t(h),r(d)};return window.addEventListener(ai,i),window.addEventListener("storage",c),()=>{window.removeEventListener(ai,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{const c=cn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}zr(i,c)},[]),a=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=cn(c);r(u);try{localStorage.setItem("theme",c)}catch{}return zr(c,u),c})},[]);return{theme:n,preference:e,setPreference:o,cycleTheme:a,isDark:n==="dark"}}const jc={dark:"Dark",light:"Light",system:"System"};function kk({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(Of,{size:16}):t==="light"?s.jsx(Wf,{size:16}):s.jsx(Uf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${jc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:jc[t]})]})}const ii="adhdev:langchange";function Sk(){const e=wt.language;return un(e)?e:mu()}function Ck(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ii,{detail:{language:e}}))}function jk(){const[e,t]=l.useState(Sk);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},o=i=>{const c=i.detail||{};un(c.language)&&t(c.language)},a=i=>{if(i.key!==za)return;const c=i.newValue;un(c)&&c!==wt.language&&(wt.changeLanguage(c),qa(c))};return wt.on("languageChanged",r),window.addEventListener(ii,o),window.addEventListener("storage",a),()=>{wt.off("languageChanged",r),window.removeEventListener(ii,o),window.removeEventListener("storage",a)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(za,r)}catch{}wt.changeLanguage(r),qa(r),Ck(r)}},[]);return{language:e,setLanguage:n}}function Nk({collapsed:e}){const{language:t,setLanguage:n}=jk(),{t:r}=Le("common"),o=Yo.find(i=>i.code===t)??Yo[0],a=r("language.select",{defaultValue:"Select language"});return s.jsxs("div",{className:`nav-item relative cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,title:`${r("language.label",{defaultValue:"Language"})}: ${o.label}`,children:[s.jsx("span",{className:"nav-icon",children:s.jsx(Xf,{size:16})}),!e&&s.jsx("span",{className:"text-xs",children:o.label}),s.jsx("select",{"aria-label":a,value:t,onChange:i=>n(i.target.value),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",children:Yo.map(i=>s.jsx("option",{value:i.code,children:i.label},i.code))})]})}function aa(e,t){return e?typeof e=="function"?e(t):e:null}function Ak({children:e,brand:t,navItems:n,sidebarSections:r=[],footerItems:o=[],footerInfo:a,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:h}=Le("common"),[d,m]=l.useState(!1),[f,x]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),w=()=>m(!0),p=()=>m(!1),y=()=>{x(S=>{const v=!S;try{localStorage.setItem(u,v?"1":"0")}catch{}return v})},k=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:w,closeMobileMenu:p,toggleCollapsed:y}),[f,d]),b=S=>`nav-item${S.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${S.className?` ${S.className}`:""}`,j=S=>s.jsxs("div",{className:b(S),id:`nav-${S.id}`,onClick:()=>{S.onSelect(),p()},title:f?S.title??(typeof S.label=="string"?S.label:void 0):S.title,children:[s.jsx("span",{className:"nav-icon",children:S.icon}),!f&&S.label]},S.id);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":h("app.openMenu"),onClick:w,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":h("app.closeMenu"),onClick:p,onKeyDown:S=>S.key==="Escape"&&p()}),s.jsxs("aside",{className:`sidebar ${d?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:aa(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":h("app.closeMenu"),onClick:p,children:s.jsx(At,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:n.map(j)}),r.map(S=>s.jsxs("div",{className:S.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&S.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:S.title}):null,S.items.map(j)]},S.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(j),aa(a,k),s.jsx(kk,{collapsed:f}),s.jsx(Nk,{collapsed:f}),aa(i,k)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function bt({title:e,icon:t,description:n,accentColor:r,className:o,collapsible:a,defaultOpen:i=!0,badge:c,children:u}){const[h,d]=l.useState(i),m=a?h:!0,f=(e||n)&&s.jsxs("div",{className:Ht("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),a&&s.jsx("span",{className:Ht("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Ht("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",o),style:r?{borderLeftColor:r}:void 0,children:[a&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(x=>!x),"aria-expanded":m,children:f}):f,m&&u]})}function Ro({icon:e,title:t,description:n,action:r,className:o}){return s.jsxs("div",{className:Ht("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const Tk={error:"bg-red-500/10 border-red-500/30 text-red-400",warning:"bg-yellow-500/10 border-yellow-500/30 text-yellow-400",success:"bg-green-500/10 border-green-500/30 text-green-400",info:"bg-indigo-500/10 border-indigo-500/30 text-indigo-400"},Ik={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Gt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ht("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Tk[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Ik[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Ct({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Ht("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function is(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Ht("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const Mk={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:o,...a},i){return s.jsx("button",{ref:i,type:r??"button",className:Ht("btn",Mk[t],n==="sm"&&"btn-sm",o),...a})}),Dk=l.forwardRef(function({options:t,children:n,className:r,...o},a){return s.jsx("select",{ref:a,className:Ht("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...o,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),Pk={online:"bg-green-500/10 text-green-400 border-green-500/30",idle:"bg-yellow-500/10 text-yellow-400 border-yellow-500/30",busy:"bg-orange-500/10 text-orange-400 border-orange-500/30",error:"bg-red-500/10 text-red-400 border-red-500/30",offline:"bg-gray-500/10 text-text-secondary border-gray-500/30"},Lk={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Rk({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ht("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Pk[e],n),children:[s.jsx("span",{className:Ht("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Lk[e])}),r]})}function Fs({label:e,description:t,checked:n,disabled:r,onChange:o,extra:a}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[a,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>o(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function Ek({onPrefChange:e}){const[t,n]=Gy(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const a=(i,c)=>{n({[i]:c}),e==null||e(i,c)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>a("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>a("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Su().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:"Allow notifications"})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>a("completionAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>a("approvalAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>a("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function li(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const o=n.match(/(?:^|\.)(\d+)$/);r=o?Number(o[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function bo(e){var t;return((t=li(e))==null?void 0:t.base)??null}function _k(e,t){const n=bo(e),r=bo(t);if(!n||!r)return e.localeCompare(t);for(let o=0;o<3;o+=1){if(n[o]<r[o])return-1;if(n[o]>r[o])return 1}return 0}function $k(e,t){const n=li(e),r=li(t);if(!n||!r)return e!==t;for(let o=0;o<3;o+=1){if(n.base[o]<r.base[o])return!0;if(n.base[o]>r.base[o])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function Vi(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:$k(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||_k(n,t)>=0)return!1;const r=bo(n),o=bo(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function Bk(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ia(e,t){return e instanceof Error?e.message:t}function Fk({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o}){const{t:a}=Le("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ro,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:a("machine.connectedMachines.noMachines"),description:t||a("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(Wk,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o},c.id))})}function Nc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:o,onCancel:a}){const{t:i}=Le("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return fn.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:a,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:u=>u.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:a,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:o,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function Hk(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...bk,...gk,...xk].find(o=>o.id===t||t.includes(o.id)||o.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function Wk({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o}){var K,F;const{t:a}=Le("common"),[i,c]=l.useState("idle"),[u,h]=l.useState(""),[d,m]=l.useState(null),[f,x]=l.useState("idle"),[w,p]=l.useState(""),y=e.version||null,k=((K=e.machine)==null?void 0:K.platform)||((F=e.system)==null?void 0:F.platform)||"",b=ts(e,{fallbackId:e.id}),j=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",S=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),g=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),N=e.p2p,C=async()=>{if(n){c("upgrading"),h(a("machine.connectedMachines.startingUpgrade"));try{const R=Bk(await n(e.id,"daemon_upgrade",{}));R.alreadyLatest?(c("done"),h(`Already on v${R.version||"latest"}.`)):R.upgraded||R.success?(c("done"),h(`Upgrade to v${R.version||"latest"} started. Daemon is restarting...`)):(c("error"),h(R.error||"Upgrade failed"))}catch(R){c("error"),h(ia(R,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){x("loading");try{await r(e.id),x("done"),p(a("machine.connectedMachines.machineDisconnected"))}catch(R){x("error"),p(ia(R,a("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!o){x("loading");try{await o(e.id),x("done"),p(a("machine.connectedMachines.tokenRevoked"))}catch(R){x("error"),p(ia(R,a("machine.connectedMachines.failedToRevokeToken")))}}},M="0.9.82",L=Vi(e,M),P=tr(e,M),B=S.length+v.length+g.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:j}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),y&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",y,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&L&&s.jsx("button",{onClick:C,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${M}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",a("machine.connectedMachines.upgrading")]}):i==="done"?a("machine.connectedMachines.updated"):P?a("machine.connectedMachines.updateNow"):a("machine.connectedMachines.updateTo",{version:M})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:a("machine.connectedMachines.disconnect")}),o&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:a("machine.connectedMachines.remove")}),s.jsx(Rk,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?a("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&B>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),B>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(R=>{const Q=Hk(R.type),E=R.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:Q.icon}),s.jsx("span",{children:Q.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:a(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),v.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:R.cliName||"CLI"})]},R.id)),g.map(R=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:a("machine.connectedMachines.noIdesConnected")})]}),(u||w)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:w||u})]}),d==="disconnect"&&s.jsx(Nc,{title:a("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
59
59
 
@@ -67,8 +67,8 @@ This will:
67
67
  • Require restarting ADHDev on that machine
68
68
 
69
69
  Use this if you want to permanently remove a machine.`,confirmLabel:a("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const Ok=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function Uk({daemonId:e,knownCliTypes:t=Ok}){const{sendCommand:n}=yt(),[r,o]=l.useState({}),[a,i]=l.useState({}),[c,u]=l.useState(!0),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(""),p=l.useCallback(async()=>{if(e){u(!0),f(null);try{const b=await n(e,"list_coordinator_prompts",{}),j=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(j!=null&&j.success)){f((j==null?void 0:j.error)||"Failed to load");return}const S=j.entries||{};w(j.dir||"");const v={};for(const g of t)v[g]=S[g]||{override:"",append:""};for(const g of Object.keys(S))v[g]||(v[g]=S[g]);o(v),i(JSON.parse(JSON.stringify(v)))}catch(b){f((b==null?void 0:b.message)||String(b))}finally{u(!1)}}},[n,e,t]);l.useEffect(()=>{p()},[p]);const y=l.useCallback(async(b,j)=>{var S;if(e){d(`${b}:${j}`),f(null);try{const v=((S=r[b])==null?void 0:S[j])||"",g=await n(e,"write_coordinator_prompt",{key:b,kind:j,content:v}),N=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(N!=null&&N.success)){f((N==null?void 0:N.error)||"Save failed");return}i(C=>({...C,[b]:{...C[b]||{override:"",append:""},[j]:v}}))}catch(v){f((v==null?void 0:v.message)||String(v))}finally{d(null)}}},[n,e,r]),k=l.useMemo(()=>(b,j)=>{var S,v;return(((S=r[b])==null?void 0:S[j])||"")!==(((v=a[b])==null?void 0:v[j])||"")},[r,a]);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:x||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),m&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:m}),c&&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(([b,j])=>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:b}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),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:j.override,onChange:S=>o(v=>({...v,[b]:{...v[b],override:S.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:h===`${b}: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 y(b,"override"),disabled:h===`${b}:override`||!k(b,"override"),children:h===`${b}:override`?"Saving…":k(b,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),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:j.append,onChange:S=>o(v=>({...v,[b]:{...v[b],append:S.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:h===`${b}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(b,"append"),disabled:h===`${b}:append`||!k(b,"append"),children:h===`${b}:append`?"Saving…":k(b,"append")?"Save append":"Saved"})})]},b))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Gk=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Kk(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:Gk.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 zk(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 qk(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function la(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ac(e){const{r:t,g:n,b:r}=qk(e);return .2126*la(t)+.7152*la(n)+.0722*la(r)}function Tc(e,t){const n=Ac(e),r=Ac(t),o=Math.max(n,r),a=Math.min(n,r);return(o+.05)/(a+.05)}function Th(e){const t=zk(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Tc(t,n)>=Tc(t,r)?n:r}const ci={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},di={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},Vk=[{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"}}}],Ih="adhdev-chat-theme",Mh="adhdev-chat-theme-custom";function qr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ih)||"ember"}catch{return"ember"}}function as(e){try{const t=localStorage.getItem(Mh);if(t){const n=JSON.parse(t);return{...e==="dark"?ci:di,...n[e]}}}catch{}return e==="dark"?ci:di}function Ir(e,t){try{localStorage.setItem(Mh,JSON.stringify({dark:e,light:t}))}catch{}}function Qt(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${o}, ${t})`}function go(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),o=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const Yk={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,t){var o;const n=(o=Yk[e])==null?void 0:o[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",go(n,24)),r.style.setProperty("--accent-on-primary",Th(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${go(n,18)})`),r.style.setProperty("--border-accent",Qt(n,.35)),r.style.setProperty("--nav-active-bg",Qt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Qt(n,.06)}`)}function Ks(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Qt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Qt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Qt(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",Qt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Qt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",go(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Th(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${go(e.accentColor,40)})`),t.style.setProperty("--border-accent",Qt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Qt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Qt(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 ${Qt(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 Yi(){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 Jk(e){try{localStorage.setItem(Ih,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Ks(as(t))}else Yi(),sr(e,zs()?"dark":"light")}function Qk(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=qr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Ks(as(t))}else Yi(),sr(e,zs()?"dark":"light")}function zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Bt({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:r=>n(r.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:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.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 Fn({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 Xk({dark:e,onColorsChange:t}){const{t:n}=Le("common"),r=e?"dark":"light",[o,a]=l.useState(()=>as(r));l.useEffect(()=>{a(as(r))},[r]);const i=l.useCallback((c,u)=>{a(h=>{const d={...h,[c]:u},f=as(r==="dark"?"light":"dark");return r==="dark"?Ir(d,f):Ir(f,d),Ks(d),t(d),d})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[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(Fn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Bt,{label:n("settings.theme.colorBackground"),value:o.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Bt,{label:n("settings.theme.colorSurface"),value:o.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Bt,{label:n("settings.theme.colorCard"),value:o.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Bt,{label:n("settings.theme.colorPrimary"),value:o.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Bt,{label:n("settings.theme.colorSecondary"),value:o.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Bt,{label:n("settings.theme.colorMuted"),value:o.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Bt,{label:n("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Bt,{label:n("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Bt,{label:n("settings.theme.colorAccent"),value:o.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Fn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Bt,{label:n("settings.theme.colorUserBubble"),value:o.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Bt,{label:n("settings.theme.colorUserText"),value:o.userText,onChange:c=>i("userText",c)}),s.jsx(Bt,{label:n("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Bt,{label:n("settings.theme.colorAgentText"),value:o.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Bt,{label:n("settings.theme.colorChatBg"),value:o.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Bt,{label:n("settings.theme.colorSendButton"),value:o.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Bt,{label:n("settings.theme.colorInputBorder"),value:o.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:o.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:[o.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ci:di,h=as(e?"light":"dark");e?Ir(c,h):Ir(h,c),a(c),Ks(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 Zk(){const{t:e}=Le("common"),[t,n]=l.useState(qr),[r,o]=l.useState(!0),[a,i]=l.useState(()=>as("dark"));l.useEffect(()=>{o(zs());const h=new MutationObserver(()=>{const f=zs();o(f);const x=qr();x==="custom"?Ks(as(f?"dark":"light")):sr(x,f?"dark":"light")});h.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=zs();o(f);const x=qr();x==="custom"?Ks(as(f?"dark":"light")):sr(x,f?"dark":"light")};return d.addEventListener("change",m),()=>{h.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ks(as(r?"dark":"light")):(Yi(),sr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(as(r?"dark":"light"))},[r]);const c=h=>{n(h),Jk(h)},u=[...Vk,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(h=>{const d=t===h.id,m=r?h.preview.dark:h.preview.light,f=h.id==="honey"||h.id==="ember"?"#1a1a1a":h.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(h.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?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:f},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:[d&&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:h.id==="custom"?e("settings.theme.customLabel"):h.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:h.description})]})]})]},h.id)})}),t==="custom"&&s.jsx(Xk,{dark:r,onColorsChange:h=>i(h)})]})}const Ji="adhdev_mobileDashboardMode_v1",ui="adhdev:mobile-dashboard-mode-change";function Qi(){try{return localStorage.getItem(Ji)==="workspace"?"workspace":"chat"}catch{return"chat"}}function eS(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Qi())},n=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Ji||t()};return window.addEventListener(ui,n),window.addEventListener("storage",r),()=>{window.removeEventListener(ui,n),window.removeEventListener("storage",r)}}function tS(e){try{localStorage.setItem(Ji,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ui,{detail:e}))}function sS(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Qi()==="chat")},[]),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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),tS(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const nS="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",rS="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function oS({themeDescription:e=nS,mobileDescription:t=rS,fontsSlot:n}){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:"Mode"}),s.jsx(Kk,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(Zk,{})]}),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:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(sS,{})]})]})}const ca=new Map,Ic=new Map;function aS(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function iS(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function Dh(){const{sendCommand:e}=yt(),{injectEntries:t,getIdes:n}=or();return l.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??ww,i=Ic.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const c=ca.get(r);if(c)return c;const u=(async()=>{const h=await e(r,"get_machine_runtime_stats"),d=aS(h);if(!d)return;const m=n().find(x=>x.id===r),f=iS(m,r,d.machine,d.timestamp||Date.now());t([f]),Ic.set(r,Date.now())})().finally(()=>{ca.delete(r)});return ca.set(r,u),u},[n,t,e])}function lS(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 cS(e,t){const{sendData:n}=yt(),{injectEntries:r,getIdes:o}=or(),a=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=a?a.split("|"):[];if(i.length===0)return;const c=i.map(u=>ls.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=o().find(x=>x.id===u),f=lS(m,u,d);r([f])}));return()=>{c.forEach(u=>u())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function dS(e,t){const{sendData:n}=yt(),[r,o]=l.useState(null),[a,i]=l.useState(!1);return l.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}o(null),i(!0);let c=null;const u=ls.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}:{}}},h=>{c&&(clearTimeout(c),c=null),o(h.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Cw):i(!1),()=>{c&&clearTimeout(c),u()}},[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:r,loading:a,applyDiagnostics:o}}function uS(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ph(e){const{sendData:t}=yt(),[n,r]=l.useState({});return l.useEffect(()=>{const o=uS(e);if(!o||!e.sessionId||!t){r({});return}const a=ls.subscribe({sendData:t},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),bn.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 a.initialSendAccepted||r({}),()=>{a()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function hS(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function pS(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 mS(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let o=`HTTP ${r.status}`;try{const a=await r.json();typeof(a==null?void 0:a.error)=="string"&&(o=a.error)}catch{}throw new Error(o)}}async function fS({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:o=fetch}){if(n){const a=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!hS(a))throw new Error(pS(a));return}await mS(e.sessionId,t,o)}function Lh(e){const{ides:t,isP2PActive:n,p2pStates:r}=gs(),{sendCommand:o}=yt(),[a,i]=l.useState(null),[c,u]=l.useState(!1),[h,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Tb(t,e),[t,e]),x=!!f,w=l.useMemo(()=>f?f.prompt.promptId===a?null:f:null,[a,f]),p=l.useCallback(async b=>{if(!w||m.current)return;m.current=!0;const j=lu(w.prompt,b);u(!0),d(null);try{const S=(r==null?void 0:r[w.daemonId])==="connected"||n===!0;await fS({promptSession:w,response:j,useP2PCommand:S,sendCommand:o}),i(w.prompt.promptId)}catch(S){throw d(S instanceof Error?S.message:String(S)),S}finally{u(!1),m.current=!1}},[n,r,w,o]),y=l.useCallback(()=>{w&&i(w.prompt.promptId)},[w]),k=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:w,hasActivePrompt:x,responseError:h,isSubmitting:c,submit:p,cancel:y,reopen:k}}function Rh(e){return e instanceof Error?e.message:String(e||"")}function bS(e){const t=Rh(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 gS(e){const t=Rh(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Eh({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ct(e)||lt(e))return;const a=Tn(e);if(a===t)return;const i=e.sessionId;i&&o(c=>({...c,[i]:t}));try{await r(Ps(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:bs(e),mode:t})}catch(c){const u=gS(c);i&&!u&&o(h=>{const d={...h};return a===yS(n,i)?delete d[i]:d[i]=a,d}),bS(c)?console.warn(u?"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 Mc(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 r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function xS(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(o=>{const a=Mc(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(u=>Mc(u,t)):o.childSessions,c=i!==o.childSessions;return a!==o||c?(n=!0,{...a,...c?{childSessions:i}:{}}):o});return n?r:e}function yS(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 r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function vS({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:o}){l.useEffect(()=>{Su()},[]);const a=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:lh(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:o?o(i):!1})),[e,o]);return Vy(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const h=Date.now(),d={};for(const[m,f]of Object.entries(u))h-f<5e3&&(d[m]=f);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(u=>{const h=u.filter(d=>d.timestamp>c).slice(-100);return h.length===u.length?u:h})},6e4);return()=>clearInterval(i)},[r]),null}function Dc(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 qs(e){const t=[...e.messages].reverse().find(o=>!(o!=null&&o._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Dc(t==null?void 0:t.receivedAt)||Dc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function hi(e,t=0){return qs(e)||e.lastUpdated||t||0}function _h(e){return qs(e)||e.lastUpdated||0}function $h(e,t,n=_h){const r=n(t)-n(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function pi(e){var n;const t=Zt(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function wS(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pi(e)&&!e.title.trim()}function kS(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(pi(n))-Number(pi(t));if(r!==0)return r;const o=n.messages.length-t.messages.length;return o!==0?o:$h(t,n)})[0]||null}function cs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,o=n.filter(i=>i.streamSource==="agent-stream"),a=kS(o);return r?a&&wS(r)?a:r:a||n[0]||null}function SS(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),n=new Set;for(const o of t){if(!Qa(o))continue;const a=gu(o);a&&n.add(a)}const r=new Map;for(const o of t){const a=jy(o,n),i=r.get(a);if(!i){r.set(a,o);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),h=c(o),d=h>u||h===u&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,CS(d,d===o?i:o))}return Array.from(r.values())}function CS(e,t){const n=Qa(t),r=Qa(e);if(!n&&!r)return e;const o=r?n?void 0:t:e,a=r?e:n?t:void 0,i=o&&String(o.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!r&&{settings:{...u,...e.settings??{}}}}}function da(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 jS(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 Pc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?jS(gn(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)??""),r].join(":")}function NS(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||""),Pc(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||""),Pc(n.activeChat)].join(":"))].join("|")}function AS(e,t){const n=Date.now();return e.map(r=>{const o=t[r.tabKey];return o&&n-o<5e3?{...r,messages:[],title:""}:r})}function TS(e,t){const n=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of Xn({routeId:r.routeId}))n.set(a,o);for(const a of Xn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(a,r.streamSource==="native"?o:r);for(const a of Xn({tabKey:r.tabKey}))n.set(a,r)}return n}function IS(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function MS(e){const t=IS(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||""),r=gn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function DS({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>SS(e),[e]),o=l.useMemo(()=>uu(e),[e]),a=l.useMemo(()=>yh(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),h=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const S=new Map,v=[];for(const A of r){const{connectionState:T="new",machineName:M}=vh(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),L=NS(A),P=h.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===L&&P.connectionState===T&&P.machineName===M){S.set(A.id,P),v.push(...P.conversations);continue}const B=qi(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),K={ide:A,sourceSignature:L,connectionState:T,machineName:M,conversations:B};S.set(A.id,K),v.push(...B)}h.current=S;const g=new Map,N=A=>{const T=MS(A),M=d.current.get(A.tabKey);if(M&&M.signature===T)return g.set(A.tabKey,M),M.timestamp;const L={signature:T,timestamp:_h(A)||(M==null?void 0:M.timestamp)||0};return g.set(A.tabKey,L),L.timestamp},C=[...v].sort((A,T)=>$h(A,T,N));return d.current=g,C},[r,t,a]),f=l.useMemo(()=>{const S=AS(m,n);return da(i.current,S)?i.current:(i.current=S,S)},[m,n]),x=l.useMemo(()=>{const S=new Map,v=Array.from(new Set(f.map(g=>g.routeId)));for(const g of v){const N=cs(f,g);N&&S.set(g,N)}return S},[f]),w=l.useMemo(()=>{const S=new Map;for(const v of f){const g=x.get(v.routeId),N=v.streamSource==="native"&&g?g:v;for(const C of Xn({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))S.set(C,N)}return S},[f,x]),p=l.useMemo(()=>TS(f,x),[f,x]),y=l.useCallback(S=>{if(S)return w.get(S)},[w]),k=l.useCallback(S=>{if(S)return p.get(S)},[p]),b=l.useMemo(()=>{const S=f.filter(v=>!Ds(v,o).surfaceHidden);return da(c.current,S)?c.current:(c.current=S,S)},[f,o]),j=l.useMemo(()=>{const S=b.map(v=>v.tabKey);return da(u.current,S)?u.current:(u.current=S,S)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:y,resolveConversationByTarget:k}}function PS({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const o=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),a=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[r,t]);return{requestedDesktopTabKey:o,requestedMobileTabKey:a,consumeRequestedActiveTab:i}}function LS({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{pt.setIdes(e)},[e]),l.useEffect(()=>{pt.setResolveAction((o,a,i)=>{t(o,a,i).catch(()=>{})})},[t]),l.useEffect(()=>{const o=pt.onToast(a=>{n(c=>c.some(h=>h.message===a.message&&a.timestamp-h.timestamp<3e3)?c:[...c.slice(-4),{id:a.id,message:a.message,type:a.type,timestamp:a.timestamp,targetKey:a.targetKey,actions:a.actions}]);const i=a.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==a.id)),i)});return()=>{o()}},[n]),l.useEffect(()=>{const o=rh.on("status_event",a=>{pt.handleRawEvent(a,"ws")});return()=>{o()}},[]),l.useEffect(()=>{var a;const o=i=>{var p;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 u=c.targetSessionId||c.targetKey||c.daemonId,h=r(u),d=(h==null?void 0:h.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),f=c.button||((p=h==null?void 0:h.modalButtons)==null?void 0:p[m])||"Approve",x=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(x);t(d,"resolve_action",{action:w?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(h==null?void 0:h.sessionId)&&{targetSessionId:h.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(a=navigator.serviceWorker)==null||a.addEventListener("message",o),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",o)}},[r,t])}const RS="adhdev_dashboardLayout_v1",ES="adhdev_dashboardDockview_v1",_S="adhdev_dashboardDockviewHiddenRestore_v1",Hn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Xi(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function $S(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Bh(e){return`${RS}:${e}`}function BS(e){const t=Bh(e);return Xi(t,null)}function FS(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,r=Bh(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fh(e){return`${ES}:${e}`}function HS(e){const t=Fh(e);return Xi(t,null)}function WS(e,t){try{const n=Fh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hh(e){return`${_S}:${e}`}function OS(e){const t=Hh(e);return Xi(t,{})}function US(e,t){try{const n=Hh(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function GS(){return{groupAssignments:[...Hn.groupAssignments],focusedGroup:Hn.focusedGroup,groupActiveTabIds:{...Hn.groupActiveTabIds},groupTabOrders:{...Hn.groupTabOrders},groupSizes:[...Hn.groupSizes]}}function KS(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function zS(){const[e]=l.useState(()=>$S(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,o]=l.useState(0),[a,i]=l.useState({}),[c,u]=l.useState({}),[h,d]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[x,w]=l.useState(!1),p=l.useCallback(()=>{if(x)return;const A=BS(e)??GS();n(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),w(!0)},[x,e]);l.useEffect(()=>{x&&FS(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:c,groupSizes:h})},[x,e,t,r,a,c,h]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=M=>f(M.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const y=l.useCallback(A=>{n(A)},[]),k=l.useCallback(A=>{o(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{u(A)},[]),S=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{k(A)},[k]),g=l.useCallback((A,T)=>{i(M=>(M[A]??null)===(T??null)?M:{...M,[A]:T})},[]),N=l.useCallback((A,T)=>{u(M=>{const L=M[A];return KS(L,T)?M:{...M,[A]:T}})},[]),C=l.useCallback((A,T)=>{const M=T.get(A)??0;return g(M,A),v(M),M},[v,g]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:r,updateFocusedGroup:k,focusGroup:v,groupActiveTabIds:a,updateGroupActiveTabIds:b,setGroupActiveTab:g,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:h,updateGroupSizes:S,isMobile:m,hasHydratedStoredLayout:x,hydrateStoredLayout:p,focusConversationTab:C}}function qS(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Ao(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function VS({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:h,isRefreshingHistory:d,ides:m,handleRefreshHistory:f}){const x=l.useRef(!1),w=l.useRef(!1),p=l.useRef(null),y=l.useRef(!1);l.useEffect(()=>{if(!e||x.current||t.length===0)return;if(!o){a();return}const k=n(e);k&&(i(k.tabKey,r),x.current=!0,w.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,o,a,i,c]),l.useEffect(()=>{if(!(w.current||o)&&t.length!==0){if(!e){a(),w.current=!0;return}if(x.current){w.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(w.current||o)&&(a(),w.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,o,a]),l.useEffect(()=>{if(!u){y.current=!1;return}if(!h||y.current||d)return;const k=m.find(b=>b.id===h.routeId);k&&(!k.chats||k.chats.length===0||qS(k.chats,h))&&(y.current=!0,f())},[u,h,d,m,f])}function ua(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 r=Ao(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Wh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,c]=l.useState(!1),[u,h]=l.useState(!1),d=l.useCallback(async w=>{try{await e("standalone","launch_ide",{ideType:w,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),m=l.useCallback(async(w,p)=>{try{const y=w||(t==null?void 0:t.daemonId)||"",k=await e(y,"switch_chat",{id:p,sessionId:p,...Os(t)}),b=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?an(o,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?an(o,`⚠️ Switch error: ${b}`):an(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),an(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,o]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const w=Us(t);await e(w,"new_chat",{...Os(t)}),Uw(w,t.sessionId,Ao(t)[0]),a(p=>({...p,[t.tabKey]:Date.now()}))}catch(w){console.error("New chat failed",w)}finally{c(!1)}}},[t,i,e,a]),x=l.useCallback(async()=>{var w,p;if(!(!t||u)){h(!0);try{const y=Us(t),k=async()=>e(y,"list_chats",{forceExpand:!0,...Os(t)});let b=await k(),j=(b==null?void 0:b.chats)||((w=b==null?void 0:b.result)==null?void 0:w.chats);ua(j,t)&&(await new Promise(S=>setTimeout(S,450)),b=await k(),j=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),ua(j,t)&&!ua(n,t)&&an(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{h(!1)}}},[t,n,u,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:x}}function YS(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function JS(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Lc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>t[Number(o)]===e[Number(o)])}function Mr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const o={};r.forEach((i,c)=>{o[i]=c}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=o[c];typeof u=="number"&&u>0&&a.set(i,u)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function Rc(e,t){const n={};for(const[r,o]of Object.entries(e)){const a=t[Number(r)];typeof a=="number"&&(n[a]=o)}return n}function QS(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(o=>o<e)??t[0];return n[r]??0}function XS(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),o=r.length===t.length?r:Array(n).fill(100/n),a=o.reduce((i,c)=>i+c,0);return a>0?o.map(i=>i/a*100):Array(n).fill(100/n)}function Ec(e,t){const n={};for(const[r,o]of Object.entries(e)){const a=Number(r);n[a>=t?a+1:a]=o}return n}function _c(e){return Array(e).fill(100/e)}function ZS({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:h}){const d=l.useRef(null),m=l.useMemo(()=>Mr(e,h),[e,h]),f=m.assignments,x=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),w=x>1,p=l.useCallback((v,g)=>{t(N=>{const C=new Map(Mr(N,h).assignments);return g===0?C.delete(v):C.set(v,g),C}),r(N=>({...N,[g]:v})),n(g)},[t,h,r,n]),y=l.useCallback(v=>{t(g=>{const N=Mr(g,h).assignments,C=new Map;for(const[A,T]of N)T!==v&&(T>v?C.set(A,T-1):C.set(A,T));return C}),i(g=>{if(g.length<=1)return[];const N=[...g];N.splice(v,1);const C=N.reduce((A,T)=>A+T,0);return C>0?N.map(A=>A/C*100):[]}),n(0)},[t,h,i,n]),k=l.useCallback((v,g)=>{g.preventDefault();const N=d.current;if(!N)return;const C=g.clientX,A=N.offsetWidth,T=a.length===x?[...a]:_c(x),M=P=>{const K=(P.clientX-C)/A*100,F=[...T];F[v]=Math.max(15,T[v]+K),F[v+1]=Math.max(15,T[v+1]-K),i(F)},L=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",L)},[a,x,i]),b=l.useCallback((v,g,N)=>{if(x>=4)return;const C=N==="left"?g:g+1;t(A=>{const T=Mr(A,h).assignments,M=new Map;for(const L of u){const P=T.get(L.tabKey)??0,B=P>=C?P+1:P;B>0&&M.set(L.tabKey,B)}return C>0&&M.set(v,C),M}),i(A=>{const T=A.length===x?[...A]:_c(x),M=T[g]??100/x,L=Math.max(15,M/2),P=Math.max(15,M/2),B=[...T];B[g]=L,B.splice(C,0,P);const K=B.reduce((F,R)=>F+R,0);return B.map(F=>F/K*100)}),r(A=>{const T=Ec(A,C);return T[C]=v,T}),o(A=>{const T=Ec(A,C);return T[C]=[v],T}),n(C)},[x,t,h,u,i,r,o,n]);l.useEffect(()=>{YS(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:g}=m;r(N=>{const C=Rc(N,v);return Lc(N,C)?N:C}),o(N=>{const C=Rc(N,v);return Lc(N,C)?N:C}),n(N=>{const C=c?0:QS(N,g,v);return N===C?N:C}),i(N=>{const C=c?[]:XS(N,g,m.groupCount);return JS(N,C)?N:C})},[m,c,r,o,n,i]);const j=l.useMemo(()=>{const v=Array.from({length:x},()=>[]);for(const g of u){const N=f.get(g.tabKey)??0,C=Math.min(N,x-1);v[C].push(g)}return v},[u,f,x]),S=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:x,isSplitMode:w,groupedConvs:j,moveTabToGroup:p,closeGroup:y,handleResizeStart:k,splitTabRelative:b,clearAllSplits:S}}function ha(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function eC(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function Dr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Zi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=ha(t.channel)||ha(e.updateChannel)||ha(e.releaseChannel)||void 0,r=eC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),o=Dr(t.targetVersion)||Dr(e.serverVersion)||void 0,a=Dr(t.minVersion)||void 0,i=Dr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function dn(e,t=null){return Zi(e).targetVersion||t}function Oh(e){return Zi(e).channel||null}function Uh(e){const t=Zi(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function tC({ides:e,sendDaemonCommand:t}){const n="0.9.82",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Vi(m,dn(m,n))).sort((m,f)=>Number(tr(f,dn(f,n)))-Number(tr(m,dn(m,n)))),[n,e]),o=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),a=l.useMemo(()=>r.map(m=>dn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[u,h]=l.useState({}),d=l.useCallback(async m=>{var x,w;const f=e.find(p=>p.id===m);if(f){h(p=>({...p,[m]:"upgrading"}));try{const p=await t(m,"daemon_upgrade",Uh(f));(x=p==null?void 0:p.result)!=null&&x.upgraded||(w=p==null?void 0:p.result)!=null&&w.success?h(y=>({...y,[m]:"done"})):h(y=>({...y,[m]:"error"}))}catch{h(p=>({...p,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Gh=80;function Vr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function sC(e){return{...e,createdAt:Vr(e.createdAt),updatedAt:Vr(e.updatedAt,e.createdAt),lastEventAt:Vr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nC(e){const t=bu(e);return t==="unknown:"?e.id:t}function rC(e){return[e.type,fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oC(e,t=Gh){const n=new Map;for(const r of e){if(r.deletedAt)continue;const o=nC(r),a=n.get(o);if(!a){n.set(o,r);continue}(r.updatedAt>a.updatedAt||r.updatedAt===a.updatedAt&&r.createdAt>a.createdAt)&&n.set(o,r)}return Array.from(n.values()).sort((r,o)=>{const a=o.updatedAt-r.updatedAt;return a!==0?a:o.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function aC(e,t){const n=Date.now(),r=[];for(const o of e){const a=o.sessionId?t.get(o.sessionId):void 0;if(a!=null&&a.surfaceHidden||a!=null&&a.muted)continue;const i=No(o,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Vr(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,n),h=rC({type:c,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,lastMessageHash:o.lastMessageHash,lastMessageAt:o.lastMessageAt,lastUpdated:(a==null?void 0:a.lastUpdated)||o.lastUpdated});r.push(sC({id:h,dedupKey:h,type:c,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:_u(o),preview:tw(o),createdAt:u,updatedAt:u,lastEventAt:u}))}return oC(r)}function iC(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lC(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=Gh}=e,o=l.useMemo(()=>aC(t,n).slice(0,Math.max(0,r)),[t,n,r]),a=l.useMemo(()=>iC(o),[o]);return{notifications:o,unreadCount:a}}function cC({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(a=>{const i=e.find(u=>u.id===a),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]),r=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=l.useCallback(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:o}}function el(...e){const t=new Set,n=[],r=o=>{const a=typeof o=="string"?o.trim():"";if(!a)return;const i=a.toLowerCase();t.has(i)||(t.add(i),n.push(a))};for(const o of e){if(Array.isArray(o)){for(const a of o)r(a);continue}r(o)}return n}function dC(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 r=n[1].toUpperCase(),o=(n[2]||"").replace(/[\\/]+/g,"\\");return o?`${r}:\\${o}`:`${r}:\\`}return null}function tl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=dC(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function uC(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function hC(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function sl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),o=hC(r);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(r==null?void 0:r.error)||"Could not browse folder");const a=typeof(o==null?void 0:o.path)=="string"?o.path:n,i=a.includes("\\")?"\\":"/",c=(h,d)=>/^[A-Za-z]:\\?$/.test(h)?`${h.replace(/\\?$/,"\\")}${d}`:h==="/"||h==="\\"?`${i}${d}`:`${h.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(o==null?void 0:o.files)?o.files.filter(h=>(h==null?void 0:h.type)==="directory"&&typeof(h==null?void 0:h.name)=="string").map(h=>({name:h.name,path:typeof(h==null?void 0:h.path)=="string"&&h.path.trim()?h.path:c(a,h.name)})).sort((h,d)=>h.name.localeCompare(d.name)):[];return{path:a,directories:u}}function $c(e,t){const n=t.meshId||"",r={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,(o,a)=>r[a]||"")}function Kh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const o=$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!o.includes(`
70
- `)&&!o.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:$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function pC(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?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:r}}function dr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function zh(e){return To(e)||e.tabKey||e.routeId||null}function qh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Vh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function mC(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function fC(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return o?o.tabKey:r||n||null}function bC(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Vh(t.daemonId);if(r&&r!==e.machineId)return null;const o=Ns(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),u=Ns(t.targetSessionId);if(a&&a!==c&&a!==u||i&&i!==c&&i!==u)return null;const h=xo(e.workspacePath);if(h){const d=xo(t.workspaceName);if(d&&!mC(d,h))return null}return fC(t,n)}function Bc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gC({ides:e,conversations:t,onOpenSession:n}){const[r,o]=l.useState(null),a=l.useRef(null),i=l.useCallback(()=>{a.current=null,o(null)},[]),c=l.useCallback(u=>{a.current=u,o(u)},[]);return l.useEffect(()=>{if(!r)return;const u=xo(r.workspacePath),h=e.find(m=>{var y,k,b,j;if(!m||m.type==="adhdev-daemon"||Vh(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":pn(m)?"acp":"ide")!==r.kind)return!1;const w=String(m.agentType||m.type||"");if(r.providerType&&w!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const S=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(g=>String(g||"")).filter(Boolean).includes(S)}if(u){const S=xo(m.workspace||m.runtimeWorkspaceLabel);return S?S===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(k=(y=m.activeChat)==null?void 0:y.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!h)return;const d=qh({entrySessionId:h.sessionId,entryInstanceId:h.instanceId,entryRouteId:h.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>pt.onStatusEvent(u=>{const h=a.current;if(!h)return;const d=bC(h,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const u=window.setTimeout(()=>{o(h=>!h||h.startedAt!==r.startedAt?h:(a.current=null,null))},45e3);return()=>window.clearTimeout(u)},[r]),{trackPendingLaunch:c}}function xC({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Bi(),{launchCli:c}=ko(),u=l.useCallback(async(y,k)=>sl(e,y,k),[e]),h=l.useCallback(async(y,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(y,"workspace_add",{path:k.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]),d=l.useCallback(async(y,k,b)=>{var j;try{const S={ideType:k,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(S.workspace=b.workspacePath.trim());const v=await e(y,"launch_ide",S);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:y,kind:"ide",providerType:k,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(y,k,b,j)=>{var v,g,N,C;const S=Date.now();try{const A={cliType:b};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?A.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(A.workspaceId=j.workspaceId),(g=j==null?void 0:j.resumeSessionId)!=null&&g.trim()&&(A.resumeSessionId=j.resumeSessionId.trim()),Array.isArray(j==null?void 0:j.cliArgs)&&j.cliArgs.length>0&&(A.cliArgs=j.cliArgs),(N=j==null?void 0:j.initialModel)!=null&&N.trim()&&(A.initialModel=j.initialModel.trim()),(C=j==null?void 0:j.initialThinkingLevel)!=null&&C.trim()&&(A.initialThinkingLevel=j.initialThinkingLevel.trim());const T=await c(y,A),M=(T==null?void 0:T.result)||T,L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return T!=null&&T.success&&L?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:L,startedAt:S}),{ok:!0}):T!=null&&T.success?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:(T==null?void 0:T.error)||(M==null?void 0:M.error)||`Could not launch ${k.toUpperCase()} session`}}catch(A){return Bc(A)?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async y=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(y);if(!y)return[];try{const b=await e(y,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((k=j==null?void 0:j.result)==null?void 0:k.meshes)?j.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),x=l.useCallback(async(y,k,b,j)=>{var v,g;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(y,k,b,j);const S=Date.now();try{const N={meshId:k.trim()};b.trim()&&(N.cliType=b.trim());const C=(v=j==null?void 0:j.initialModel)==null?void 0:v.trim(),A=(g=j==null?void 0:j.initialThinkingLevel)==null?void 0:g.trim();C&&(N.initialModel=C),A&&(N.initialThinkingLevel=A);const T=await e(y,"launch_mesh_coordinator",N),M=(T==null?void 0:T.result)??T;if((M==null?void 0:M.success)===!1||(T==null?void 0:T.success)===!1){const P=String((M==null?void 0:M.code)||(T==null?void 0:T.code)||""),B=pC((M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(M==null?void 0:M.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:B}}const L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return L?n(L):t({machineId:y,kind:"cli",providerType:(M==null?void 0:M.cliType)||b.trim()||void 0,workspacePath:(M==null?void 0:M.workspace)||null,startedAt:S}),{ok:!0}}catch(N){return Bc(N)?(t({machineId:y,kind:"cli",providerType:b.trim()||void 0,startedAt:S}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),w=l.useCallback(async(y,k)=>{if(!y||!k)return[];try{const b=await e(y,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),p=l.useCallback(async y=>{await Eh({conversation:r,mode:y,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:h,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:w,setActiveCliViewMode:p}}function yC(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 vC(e,t,n=Date.now()){return!e||!yC(t)?null:{tabKey:e,nonce:n}}function wC({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[c,u]=l.useState(null),[h,d]=l.useState(null),m=l.useMemo(()=>{var y,k;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const p=r[o];if(p){const b=t.find(j=>j.tabKey===p);if(b)return b}return((y=a[o])==null?void 0:y[0])||((k=a[0])==null?void 0:k[0])},[t,c,o,r,a,e,n]),f=l.useCallback(p=>{u(p)},[]),x=l.useCallback(p=>{u(p.tabKey),i(y=>{const k=new URLSearchParams(y),b=nw(p);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),w=l.useCallback((p,y)=>{const k=vC(p,y);k&&d(k)},[]);return{activeConv:m,openDesktopConversation:x,requestScrollToBottom:w,scrollToBottomRequest:h,setDesktopActiveTab:f}}function kC(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 SC(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),o=!!e.liveState.unread,a=[e.tabKey,e.historySessionId||"",t,n,r,o?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&o&&(!t||t!==n)),autoReadKey:a,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function CC({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const o=l.useRef(null),a=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const h=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),a.current=null};if(t){h(),o.current=null;return}if(!(e!=null&&e.sessionId)){h(),o.current=null;return}const d=Ds(e,n),m=SC({tabKey:e.tabKey,historySessionId:To(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:qs(e),liveState:d}),f=m.autoReadKey,x=kC({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!m.shouldMarkSeen){x.shouldCancelPending&&h(),o.current=f;return}if(!x.shouldSchedule)return;x.shouldCancelPending&&h();const w=()=>{if(document.visibilityState!=="visible"||o.current===f)return;o.current=f,a.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const y=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:m.completionMarker}).catch(()=>{})};if(a.current=x.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(w,1500);const y=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(w,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function pa(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 jC({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:c,setSearchParams:u}){var Q;const{launchCli:h}=ko(),[d,m]=l.useState(!1),[f,x]=l.useState([]),[w,p]=l.useState(()=>Ft()),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),g=!!v&&ct(v)&&!lt(v),N=l.useMemo(()=>{if(!v||!g)return null;const E=v.daemonId||v.routeId||"",I=bs(v),$=pa(v);return`${E}:${I}:${v.providerSessionId||""}:${$}`},[v,g]),C=l.useMemo(()=>!v||!g?"":pa(v),[v,g]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:M,handleNewChat:L,handleRefreshHistory:P}=Wh({sendDaemonCommand:o,activeConv:v,chats:(Q=r.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:Q.chats,updateRouteChats:a,setToasts:i,setClearedTabs:c}),B=l.useCallback(()=>{m(!0)},[]),K=l.useCallback(()=>{m(!1)},[]),F=l.useCallback(async()=>{if(!(!v||!g||y)){k(!0);try{const E=v.daemonId||v.routeId,I=bs(v),$=pa(v),D=await o(E,"list_saved_sessions",{agentType:I,providerType:I,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...$?{workspace:$}:{}}),U=(D==null?void 0:D.result)??D;x(Array.isArray(U==null?void 0:U.sessions)?U.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),x([])}finally{k(!1)}}},[v,y,g,o]);l.useEffect(()=>{if(!d){S.current=null;return}if(!g){S.current=null,x([]),k(!1);return}!N||y||S.current!==N&&(S.current=N,F())},[F,d,y,g,N]);const R=l.useCallback(async E=>{if(!v||!g||!E.providerSessionId||!E.workspace)return;const I=v.daemonId||v.routeId,$=bs(v);try{j(E.providerSessionId);const D=await h(I,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),U=(D==null?void 0:D.result)??D,Y=typeof(U==null?void 0:U.sessionId)=="string"?U.sessionId:typeof(U==null?void 0:U.id)=="string"?U.id:"";Y&&u(ae=>{const z=new URLSearchParams(ae);return z.set("activeTab",Y),z},{replace:!0}),K()}catch(D){console.error("Resume saved session failed",D)}finally{j(null)}},[K,v,g,o,u]);return{historyModalOpen:d,openHistoryModal:B,closeHistoryModal:K,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:M,handleHistoryNewChat:L,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:p,missingWorkspaceResumePath:C,isSavedHistoryLoading:y,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:R}}function NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}){const[u,h]=l.useState(null),[d,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const k=c(r);return k&&!ct(k)&&!lt(k)?k:null},[e,r,c]),x=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const b=u!=null&&u.tabKey?a.find(j=>j.tabKey===u.tabKey):o?a.find(j=>j.tabKey===o):null;return(b==null?void 0:b.routeId)===k?b:cs(a,k)},[a,u,o]),w=l.useMemo(()=>{if(x)return i.find(k=>k.id===x.routeId)},[i,x]);l.useEffect(()=>{f&&(h({routeId:f.routeId,tabKey:ec(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const p=l.useCallback(k=>{k&&(h({routeId:k.routeId,tabKey:ec(k)}),m(k))},[]),y=l.useCallback(()=>{h(null),m(null)},[]);return{remoteDialogConv:x,remoteDialogIdeEntry:w,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:p,closeRemoteDialog:y}}function AC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:h}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p}=NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useCallback(async N=>{const C=N||u;!C||!ct(C)&&!lt(C)||(j(C),k(!0))},[u]),v=l.useCallback(()=>{k(!1),j(null)},[]),g=l.useCallback(async N=>{const C=b||u;if(!C||!ct(C)&&!lt(C)){v();return}k(!1);try{const A=bs(C),T=C.routeId||C.daemonId||"";await h(T,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:N,...Do(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[u,v,b,h]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:b,requestCliStop:S,cancelCliStop:v,confirmCliStop:g}}function ma(e,t=!0){return(e??!0)&&t}const nl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:o,terminalRef:a,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k=!0,isVisible:b=!0}){const j=r,S=!r,v=ma(b,j),g=ma(b,S),N=ma(b),C=Ph(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(hu,{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(Ys,{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":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(E0,{activeConv:A,clearToken:n,terminalRef:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:k&&v})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(ri,{activeConv:A,ideEntry:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k&&g,isVisible:g})})]}):s.jsx(ri,{activeConv:A,ideEntry:o,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k&&N,isVisible:N})]})},(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 TC({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){var j,S,v;const i=pr(),c=Ps(e),u=a?null:Eu(e),h=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!a&&e.streamSource==="agent-stream"&&!!e.agentName,m=!a&&!d&&(e.transport==="pty"||e.transport==="acp"),f=yn(e),x=sw(e),w=(j=e.settings)==null?void 0:j.meshNodeFor,p=e.meshQueueStats,y=((S=e.coordinator)==null?void 0:S.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),k=l.useCallback(()=>{if(r){r();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,r]),b=l.useCallback(()=>{if(n){n();return}const g=zh(e);g&&i(dr(g))},[e,i,n]);return!h&&!d&&!m&&!u&&!w&&!p?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[h&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]}):s.jsxs("span",{className:"conversation-meta-chip",title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),u&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]}):s.jsxs("span",{className:"conversation-meta-chip",title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]})),w&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),y&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Rf,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function IC({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:o,userName:a,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:h,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:w,onStopCli:p,cliViewMode:y,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:S,handleModalButton:v,handleRelaunch:g}){var L,P;const N=l.useRef(null),C=ct(e)&&!t,A=C&&y==="terminal",T=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),M=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 ${M} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(ji,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(TC,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&y&&s.jsx(uh,{mode:y,onChange:k,compact:!0}),C&&p&&s.jsx("button",{onClick:()=>{p(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(At,{size:14})}),T&&w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(es,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ai,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(nl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:v,handleRelaunch:g,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:S,isFocusingAgent:u,actionLogs:o,userName:a})})]})}const fa={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 MC(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Yh(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[o,a]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(MC())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fa[i].cmd).catch(()=>{}),a(!0),setTimeout(()=>a(!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:()=>r("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:()=>r("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:fa[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fa[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:o?"✓":"📋"})]}),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 Jh({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{key:"chats",label:"Chats",icon:Zs}];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:r,label:o,icon:a})=>{const i=e===r;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(r),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(a,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function Pr({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 nn({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 Wn({icon:e,title:t,subtitle:n,children:r}){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}),r]})}function DC({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Le(),o=xt(e);return 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:r("mobileInbox.hideTitle",{title:o})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("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:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Lr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:h}){const{t:d}=Le(),m=t==="needs_attention"||t==="task_complete",f=t==="working",x=t==="earlier",w=t==="task_complete",{isReconnecting:p,isConnecting:y}=An(e.conversation),k=xt(e.conversation),b=vn(e.conversation),j=ih(e.conversation,{requiresAction:t==="needs_attention"}),S=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":x?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":x?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",g=x?"text-text-secondary":"text-text-primary",N=x?"text-text-muted":"text-text-secondary",C=x?"text-text-secondary opacity-80":"text-text-muted",A=x?"text-text-muted opacity-80":"text-text-muted",T=!f&&!w,M=oh(e.conversation),L="text-[color:var(--status-warning)]",P=B=>{if(!c)return;B.preventDefault(),B.stopPropagation();const K=c==null?void 0:c(e.conversation);Promise.resolve(K).catch(F=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",F)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?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 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(k)}),M&&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:B=>{B.preventDefault(),B.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:k}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(es,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:P,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 ${g}`,children:k})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(co,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${L} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,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:du(e.timestamp)}),w&&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:d("mobileInbox.done")}),h&&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 ${u?"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:B=>{B.preventDefault(),B.stopPropagation(),h()},"aria-label":u?d("mobileInbox.unmute",{title:k}):d("mobileInbox.mute",{title:k}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(Xd,{size:13}):s.jsx(Nn,{size:13})}),o&&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:B=>{B.preventDefault(),B.stopPropagation(),o()},"aria-label":d("mobileInbox.hideConversationAria",{title:k}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Ti,{size:13})}),a&&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:B=>{B.preventDefault(),B.stopPropagation(),a()},"aria-label":d("mobileInbox.stopSessionAria",{title:k}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(At,{size:13})})]})]})},e.conversation.tabKey)}function Fc({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 PC({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:h,onOpenConversation:d,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:x,onStopCli:w,onOpenNewSession:p,onOpenMachine:y,onOpenSettings:k,onSectionChange:b,wsStatus:j="connected",isStandalone:S=!1,onCollectChatDebugBundle:v,isConversationMuted:g,onToggleMuteConversation:N}){const{t:C}=Le(),[A,T]=l.useState(null),M=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",L=i.length>0,P=t.length>0||n.length>0||r.length>0||o.length>0,B=C(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),K=S?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=S?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",R=l.useCallback(async I=>{const $=Us(I);if(!$)return;const D=Array.isArray(I.messages)?I.messages:[],U=Wu({activeConv:I,visibleMessages:D,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:D.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Y=await h($,"get_chat_debug_bundle",{...Os(I),delivery:"daemon_file",frontendSnapshot:U}),ae=er(Y),z=Gu(ae),X=await Uu(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),pt.showToast(Ou(ae,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,h]),Q=v||R,E=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${K}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),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(Nn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:k,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(So,{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] ${F}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(Wn,{icon:s.jsx(Fc,{}),title:C(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:C(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Wn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C(S?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:C(S?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!S&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Yh,{})})}):s.jsx(nn,{children:i.map((I,$)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(I.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(I.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:I.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?s.jsx("span",{className:"text-accent-primary",children:C("mobileInbox.newCount",{count:I.unread})}):I.total>0?C("mobileInbox.chatCount",{count:I.total}):C("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C("mobileInbox.chatCount",{count:I.total}),I.unread>0?C("mobileInbox.unreadSuffix",{count:I.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:C("mobileInbox.noActiveChats")})]})]},I.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(Pr,{title:C("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.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(Pr,{title:C("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Pr,{title:C("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&s.jsx(Pr,{title:C("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?s.jsx(nn,{children:o.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:C("mobileInbox.allCaughtUp")}):M?s.jsx(Wn,{icon:s.jsx(Fc,{size:28}),title:C("mobileInbox.connecting"),subtitle:C("mobileInbox.connectingSubtitle")}):L?s.jsx(Wn,{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(Zs,{size:20})}),title:C("mobileInbox.noConversations"),subtitle:H0,children:p&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:p,"aria-label":Bs,title:Bs,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:Bs})]})}):s.jsx(Wn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:C("mobileInbox.noMachinesConnected"),subtitle:C("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(nn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:C("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:C("mobileInbox.collapsedCount",{count:a.length})})]}),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:C("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&p&&P&&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:p,"aria-label":Bs,title:Bs,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"})]})}),A&&s.jsx(DC,{conversation:A,onCancel:()=>T(null),onConfirm:E}),s.jsx(Jh,{section:e,onSectionChange:b})]})}function LC(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 Qh(e){const t=[e.workspace||"Workspace unknown"],n=Js(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=LC(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function rl({title:e,description:t,currentPath:n,directories:r,busy:o=!1,error:a="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:h}){const[d,m]=l.useState(n);l.useEffect(()=>{m(n)},[n]);const f=uC(n),x=d.trim();return 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(At,{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:()=>{!f||o||u(f)},disabled:!f||o,children:[s.jsx(ji,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!x||o||(w.preventDefault(),u(x))},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:()=>{!x||o||u(x)},disabled:!x||o,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):a?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):r.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:r.map(w=>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:()=>u(w.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(xn,{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:w.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:w.path})]})]},w.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:()=>h(x||n),disabled:!x&&!n||o,children:i})]})]})})}function Xh({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:h,argsValue:d,onArgsChange:m,showModelInput:f,modelValue:x,onModelChange:w,historyProviderNode:p,onConfirm:y,onCancel:k}){const{t:b}=Le("common"),j=i??b("machine.launchConfirm.launch"),S=c??b("machine.launchConfirm.launching"),v=r==null?void 0:r.find(g=>g.key===o);return 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:k,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(At,{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:[r&&r.length>0&&a&&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:o||"",onChange:g=>a(g.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:u,children:r.map(g=>s.jsx("option",{value:g.key,children:g.label},g.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),p,n.map(g=>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:g.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:g.value})]},`${g.label}:${g.value}`)),f&&w&&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:x||"",onChange:g=>w(g.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:u})]}),h&&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:d||"",onChange:g=>m(g.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:u})]})]}),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:k,disabled:u,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:y,disabled:u,children:[s.jsx(Qd,{size:14}),u?S:j]})]})]})})}function Hc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Zh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:o=!0}=e,a=[];o&&a.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])a.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Hc(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const i=(n==null?void 0:n.trim())||"",c=i?(t.workspaces||[]).find(u=>u.path===i):null;if(i&&!c&&a.push({key:`custom:${i}`,label:Hc(i),description:i,workspaceId:null,workspacePath:i}),r){const u=`saved:${r}`;if(a.some(h=>h.key===u))return{options:a,selectedKey:u}}return c?{options:a,selectedKey:`saved:${c.id}`}:i?{options:a,selectedKey:`custom:${i}`}:{options:a,selectedKey:"__home__"}}function RC(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function EC(e){return[RC(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function _C(e){return e.lastLaunchedAt?jo(e.lastLaunchedAt):""}function ep(e){return{metaText:EC(e),updatedLabel:_C(e)}}function ba(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function $C({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:o,onListSavedSessions:a}){var he,$e,Fe,Ie;const i=In(),[c,u]=l.useState(!1),h=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),m=e.defaultWorkspaceId||null,[f,x]=l.useState(m||(($e=d[0])==null?void 0:$e.id)||""),[w,p]=l.useState(""),[y,k]=l.useState(""),[b,j]=l.useState([]),[S,v]=l.useState(!1),[g,N]=l.useState(""),[C,A]=l.useState(!1),[T,M]=l.useState(ba(h,t.length,n.length)),L=l.useRef(null),[P,B]=l.useState(null),K=l.useRef("__home__"),[F,R]=l.useState("__home__"),[Q,E]=l.useState(""),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState([]),[z,X]=l.useState(()=>Ft().textQuery),[de,re]=l.useState(()=>Ft().workspaceQuery),[W,oe]=l.useState(()=>Ft().modelQuery),[V,ie]=l.useState(()=>Ft().resumableOnly),[ke,xe]=l.useState(()=>Ft().sortMode),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),Z=l.useRef(null),q=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const me=f==="__custom__"?w.trim():((Fe=d.find(ye=>ye.id===f))==null?void 0:Fe.path)||"",Te=f==="__custom__"&&!!me&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),_=f!=="__custom__"&&((Ie=d.find(ye=>ye.id===f))==null?void 0:Ie.path)||"",se=l.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),ve=l.useCallback(async ye=>{v(!0),N("");try{const Oe=await o(ye);k(Oe.path),p(Oe.path),j(Oe.directories)}catch(Oe){N(Oe instanceof Error?Oe.message:"Could not load folder")}finally{v(!1)}},[o]),ce=l.useCallback(()=>{var Oe;x("__custom__"),A(!0);const ye=tl(e.platform,el(w.trim(),_,se,e.defaultWorkspacePath,(Oe=d.find(ut=>ut.id===m))==null?void 0:Oe.path,d.map(ut=>ut.path)));ve(ye)},[w,m,ve,se,_,e.platform,d]),H=l.useCallback(ye=>{if(ye!=null&&ye.workspaceId){x(ye.workspaceId),p("");return}if(ye!=null&&ye.workspacePath){x("__custom__"),p(ye.workspacePath);return}x(""),p("")},[]),fe=l.useCallback(ye=>{if(x(ye),ye==="__custom__"){ce();return}p("")},[ce]),je=l.useCallback(ye=>{x("__custom__"),p(ye)},[]),Ce=l.useCallback((ye,Oe)=>{L.current=Oe,K.current=ye.selectedWorkspaceKey||"__home__",R(ye.selectedWorkspaceKey||"__home__"),E(ye.initialArgs||""),$(ye.initialModel||""),U(""),ae([]);const ut=ye.providerType?`${e.id}:${ye.providerType}`:null;if(z0(q.current,ut)){const at=Ft();X(at.textQuery),re(at.workspaceQuery),oe(at.modelQuery),ie(at.resumableOnly),xe(at.sortMode)}q.current=ut,B(ye),ye.providerType&&a&&(pe(!0),a(ye.providerType).then(at=>ae(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>pe(!1)))},[a,e.id]),Be=l.useMemo(()=>hh(Y,{textQuery:z,workspaceQuery:de,modelQuery:W,resumableOnly:V,sortMode:ke}),[W,V,Y,ke,z,de]);l.useEffect(()=>{D&&(Be.some(ye=>ye.providerSessionId===D)||U(""))},[Be,D]);const Xe=l.useCallback(()=>{L.current&&(O(!0),L.current().finally(()=>{L.current=null,O(!1),B(null)}))},[]),dt=l.useCallback(()=>{L.current=null,B(null)},[]),it=l.useCallback(ye=>{K.current=ye,R(ye)},[]);return l.useEffect(()=>{var ye;Z.current!==e.id&&(Z.current=e.id,x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"),p(""),k(""),j([]),N(""),A(!1),X(Ft().textQuery),re(Ft().workspaceQuery),oe(Ft().modelQuery),ie(Ft().resumableOnly),xe(Ft().sortMode),q.current=null,M(ba(h,t.length,n.length)))},[n.length,t.length,m,h,e.id,d]),l.useEffect(()=>{var ye;f!=="__custom__"&&(f&&d.some(Oe=>Oe.id===f)||x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{T==="ide"&&h||T==="cli"&&t.length>0||T==="acp"&&n.length>0||M(ba(h,t.length,n.length))},[T,n.length,t.length,h]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:h,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:w,browseCurrentPath:y,browseDirectories:b,browseBusy:S,browseError:g,browseDialogOpen:C,activeLauncherKind:T,launchConfirm:P,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:F,launchConfirmArgs:Q,launchConfirmModel:I,launchConfirmResumeId:D,launchConfirmSavedSessions:Y,launchConfirmTextFilter:z,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:W,launchConfirmResumableOnly:V,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:Be,launchConfirmSessionsLoading:Se,launchConfirmBusy:G,resolvedWorkspacePath:me,canCreateMissingWorkspace:Te,openBrowseDialog:ce,loadBrowsePath:ve,handleWorkspaceChoiceChange:fe,chooseCustomWorkspacePath:je,setCustomWorkspacePath:p,setBrowseDialogOpen:A,setActiveLauncherKind:M,openLaunchConfirm:Ce,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:H,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:U,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:re,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:ie,setLaunchConfirmSortMode:xe}}function BC({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:o,selectedMachineNeedsUpgrade:a,appVersion:i,machineAction:c,isStandalone:u,section:h,showBottomNav:d,onBack:m,onSectionChange:f,onOpenConversation:x,onOpenRecent:w,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const{t:g}=Le("common"),N=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),T=$C({selectedMachineEntry:e,cliProviders:r,acpProviders:o,machineAction:c,onBrowseDirectory:j,onListSavedSessions:v}),M=l.useMemo(()=>C.map(R=>{const{metaText:Q,updatedLabel:E}=ep(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:Q,updatedLabel:E,onClick:()=>{const{options:I,selectedKey:$}=Zh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace});T.openLaunchConfirm({title:R.kind==="ide"?uo(g,"restart-ide",R.label):R.providerSessionId?mh(g,R.label):uo(g,"start-fresh",R.label),description:R.kind==="ide"?ho(g,"restart-ide"):R.providerSessionId?fh(g):ho(g,"start-fresh"),confirmLabel:R.kind==="ide"?po(g,"restart-ide"):R.providerSessionId?oi(g,!0):po(g,"start-fresh"),busyLabel:R.kind==="ide"?mo(g,"restart-ide"):R.providerSessionId?ph(g,!0):mo(g,"start-fresh"),workspaceOptions:I,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const D=I.find(U=>U.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(D),await w({...R,workspace:(D==null?void 0:D.workspacePath)??null})})}}}),[T,w,C,g]),L=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:xt(R.conversation),secondary:w0(R.conversation,{timestampLabel:R.timestamp?du(R.timestamp):null}),unread:R.unread,onClick:()=>x(R.conversation)})),[x,A]),P=T.showAllRecent?M:M.slice(0,4),B=M.length>0,K=L.length>0,F=u?"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 ${F} 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(ji,{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:ts(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:[K&&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:L.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),B&&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:P.map(R=>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:R.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:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),M.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(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${M.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:[a&&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:y,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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(rl,{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:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Xh,{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?oi(g,!!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:zi(g)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.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:R=>T.setLaunchConfirmWorkspaceFilter(R.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:R=>T.setLaunchConfirmModelFilter(R.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:R=>T.setLaunchConfirmSortMode(R.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:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.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:Y0(g)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.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 R=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const Q=Qh(R);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:Q.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:Q.providerSessionId}),s.jsx("div",{className:"mt-1",children:Q.metaLine}),Q.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:Q.updatedLabel}),Q.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:Q.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(Jh,{section:h,onSectionChange:f})]})}const Wc=8e3;function FC(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,o=n&&t.mirrorStale===!0;return!r&&!o?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:o?"the coordinator did not confirm the change":"command was rejected"}}function tp(e,t,n){const r=l.useRef(new Map),[,o]=l.useState(0),a=l.useCallback(()=>o(x=>x+1),[]);l.useEffect(()=>{const x=r.current;if(x.size===0)return;const w=Date.now();let p=!1;for(const[y,k]of x){const b=e.get(y),j=k.muted===void 0||(b?b.muted===k.muted:!1),S=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),v=w-k.at>Wc;(j&&S||v)&&(x.delete(y),p=!0)}p&&a()},[e,a]),l.useEffect(()=>{if(r.current.size===0)return;const x=setInterval(()=>{const w=r.current,p=Date.now();let y=!1;for(const[k,b]of w)p-b.at>Wc&&(w.delete(k),y=!0);y&&a(),w.size===0&&clearInterval(x)},1e3);return()=>clearInterval(x)});const i=l.useCallback((x,w)=>{const p=r.current.get(x);r.current.set(x,{...p,...w,at:Date.now()}),a()},[a]),c=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.muted)!==void 0?p.muted:Ds(x,e).muted},[e]),u=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.hidden)!==void 0?p.hidden:Ds(x,e).surfaceHidden},[e]),h=l.useCallback((x,w)=>{const p=Ps(x),y=x.sessionId;!p||!y||(i(y,w),t(p,"set_conversation_prefs",{sessionId:y,...w,...Do(x)}).then(k=>{const b=FC(k);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(y),a(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(y),a();const b=k instanceof Error?k.message:String(k??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,a,n]),d=l.useCallback(x=>{h(x,{muted:!c(x)})},[h,c]),m=l.useCallback((x,w)=>{h(x,{hidden:w})},[h]),f=l.useCallback(x=>{h(x,{hidden:!u(x)})},[h,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function Yr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function HC(e,t=[]){const n=new Map(e.map(o=>[o.conversation.tabKey,o])),r=t.map(o=>n.get(o)).filter(o=>!!o);return r.length===e.length?r:Yr(e)}function WC(e){var r,o,a;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((o=e.p2p)!=null&&o.available)||!!((a=e.p2p)!=null&&a.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function OC(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:Js(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const o=ir(r)?"cli":pn(r)?"acp":"ide",a=Js(r.summaryMetadata);return{id:`${o}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:pn(r)&&r.cliName||r.type),kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:pn(r)?a||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function UC(e,t){const n=new Map;for(const r of t){const o=Ps(r.conversation),a=n.get(o);a?a.push(r):n.set(o,[r])}return e.map(r=>{const o=n.get(r.id)||[],a=[...o].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(a==null?void 0:a.conversation)||null,c=Xa(r),u=o.filter(m=>m.unread||m.requiresAction).length,h=WC(r),d=[r.platform||"machine",h].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:u,total:o.length,latestConversation:i,latestTimestamp:(a==null?void 0:a.timestamp)||0,fallbackActivityAt:c,preview:i?k0(i,Zu(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,o)=>{const a=r.latestTimestamp||r.fallbackActivityAt||0,i=o.latestTimestamp||o.fallbackActivityAt||0;return i!==a?i-a:r.label.localeCompare(o.label)})}function GC(e){return e==="chat"}function Rr(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 KC({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:w,setScreen:p,setSelectedMachineId:y,setSection:k,setMachineBackTarget:b,resetMachineAction:j}){const S=l.useRef(null),v=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ds(g,i),C=Math.max(Date.now(),qs(g),N.lastUpdated||0);Rr("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:xt(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:qs(g),readAt:C}),c(Ps(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:C,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:A})}).catch(A=>{Rr("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){GC(a)&&p("inbox"),w(((N=e[0])==null?void 0:N.tabKey)||null),S.current=null;return}if(a!=="chat"){S.current=null;return}const g=`${r.tabKey}:${r.sessionId||""}`;S.current!==g&&(S.current=g,v(r))},[e,v,a,r,p,w]),l.useEffect(()=>{if(!u)return;const g=e.find(N=>N.tabKey===u);g&&(w(g.tabKey),p("chat"),h==null||h())},[e,h,u,p,w]),l.useEffect(()=>{if(!d)return;const g=t.find(N=>N.id===d);g&&(y(g.id),j(),k("machines"),b("inbox"),p("machine"),m==null||m())},[t,m,d,j,b,p,k,y]),l.useEffect(()=>{f&&(k(f),p("inbox"),x==null||x())},[x,f,p,k]),l.useEffect(()=>{const g=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&Rr("inbox_state",{screen:a,selectedTabKey:o,items:g.map(N=>{const C=Ds(N.conversation,i);return{liveState:C,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:C.inboxBucket,computedBucket:N.inboxBucket,serverUnread:C.unread,computedUnread:N.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:qs(N.conversation)}})})},[n,i,a,o]),{markConversationRead:v}}function zC(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Oc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qC(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function VC({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:o}=ko(),[a,i]=l.useState("idle"),[c,u]=l.useState(""),[h,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(j,S,v)=>{var g;try{i("loading"),u(`Launching ${S}…`);const N={ideType:S,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(N.workspace=v.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),u(`${S} launch requested`)}catch(N){i("error"),u(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),x=l.useCallback(async(j,S,v)=>{if(S.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(j,"workspace_add",{path:S.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),u(g instanceof Error?g.message:"Could not save workspace")}},[e]),w=l.useCallback(async j=>{var S,v,g,N,C,A;try{i("loading"),u("Starting daemon upgrade…");const T=await e(j,"daemon_upgrade",{});if((S=T==null?void 0:T.result)!=null&&S.alreadyLatest){i("done"),u(`Already on v${((v=T==null?void 0:T.result)==null?void 0:v.version)||"latest"}.`);return}if((g=T==null?void 0:T.result)!=null&&g.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),u(`Upgrade to v${((C=T==null?void 0:T.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((A=T==null?void 0:T.result)==null?void 0:A.error)||"Upgrade failed")}catch(T){i("error"),u(T instanceof Error?T.message:"Upgrade failed")}},[e]),p=l.useCallback(async(j,S,v,g)=>{var A,T,M;const N=Date.now(),C={machineId:j,kind:S,providerType:v,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:N};try{i("loading"),u(`Launching ${v}…`),d(C);const L={cliType:v};(A=g==null?void 0:g.workspacePath)!=null&&A.trim()?L.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(L.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(L.resumeSessionId=g.resumeSessionId),(T=g==null?void 0:g.args)!=null&&T.trim()&&(L.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(M=g==null?void 0:g.model)!=null&&M.trim()&&(L.initialModel=g.model.trim());const P=await o(j,L),B=(P==null?void 0:P.result)||P,K=(B==null?void 0:B.sessionId)||(B==null?void 0:B.id);if(P!=null&&P.success&&K){d(null),i("done"),u(`${v} launched`),t(dr(K));return}if(P!=null&&P.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((P==null?void 0:P.error)||(B==null?void 0:B.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(qC(L)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[t,e]),y=l.useCallback(async(j,S)=>{try{const v=await e(j,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),k=l.useCallback(async(j,S)=>sl(e,j,S),[e]);l.useEffect(()=>{if(!h)return;const j=Oc(h.workspacePath),S=n.find(g=>{var L,P,B,K;if(!g||g.type==="adhdev-daemon"||zC(g.daemonId||g.id)!==h.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==h.kind||String(g.agentType||g.type||"")!==h.providerType)return!1;const T=String(g.providerSessionId||"");if(h.resumeSessionId&&T)return T===h.resumeSessionId;if(j){const F=Oc(g.workspace||g.runtimeWorkspaceLabel);return F?F===j:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(B=(P=(L=g.activeChat)==null?void 0:L.messages)==null?void 0:P.at)==null?void 0:B.call(P,-1))==null?void 0:K.timestamp)||0)>=h.startedAt-5e3});if(!S)return;const v=qh({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:r});v&&(d(null),i("done"),u(`${h.providerType} launched`),t(dr(v)))},[r,n,t,h]),l.useEffect(()=>{if(!h)return;const j=window.setTimeout(()=>{d(S=>!S||S.startedAt!==h.startedAt?S:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[h]);const b=l.useCallback(async(j,S)=>{if(S.kind==="ide"&&S.providerType){await f(j,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await p(j,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,p]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:p,handleListSavedSessions:y,handleBrowseDirectory:k,handleOpenRecent:b}}function YC({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:h}){const d=l.useCallback(k=>{a(k.tabKey),i("chat"),r(k)},[r,i,a]),m=l.useCallback(k=>{const b=e.find(j=>j.routeId===k.routeId&&j.streamSource==="native");b&&(a(b.tabKey),i("chat"),r(b))},[e,r,i,a]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),x=l.useCallback((k,b="inbox")=>{c(k),o(),u("machines"),h(b),i("machine")},[o,h,i,u,c]),w=l.useCallback(k=>{const b=Ps(k);b&&x(b,"chat")},[x]),p=l.useCallback(()=>{o(),i(n)},[n,o,i]),y=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:x,openConversationMachine:w,backFromMachine:p,changeMachineSection:y}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function JC(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function QC({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,onOpenHistory:w,onOpenRemote:p,onStopCli:y,wsStatus:k,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:S,onOpenMeshGraph:v,onOpenNewSession:g,liveSessionInboxState:N,setCliViewModeOverrides:C}){const[A,T]=l.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,L]=l.useState(()=>e[0]?"chat":"inbox"),[P,B]=l.useState("chats"),[K,F]=l.useState(null),[R,Q]=l.useState("inbox"),E=l.useRef([]),I=pr(),$="0.9.82",D=l.useMemo(()=>e.find(H=>H.tabKey===A)||e[0]||null,[e,A]),U=l.useMemo(()=>D?n.find(H=>H.id===D.routeId):void 0,[n,D]),Y=l.useMemo(()=>!D||lt(D)||!ct(D)?null:Tn(D),[D]),ae=l.useMemo(()=>n.filter(H=>H.type==="adhdev-daemon").sort(Ei),[n]),z=l.useMemo(()=>ae.find(H=>H.id===K)||null,[ae,K]),X=Po({sendDaemonCommand:o,activeConv:D||void 0,setActionLogs:a,isStandalone:i}),de=VC({sendDaemonCommand:o,navigate:I,ides:n,conversations:e}),re=Qw(e),W=l.useMemo(()=>e.map(H=>{const fe=M==="chat"&&(D==null?void 0:D.tabKey)===H.tabKey,je=No(H,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:fe}),Ce=qs(H),Be=Zu(H),Xe=ah(H,Be);return{conversation:H,timestamp:Ce,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,M,D,re]),{markConversationRead:oe}=KC({conversations:e,machineEntries:ae,items:W,selectedConversation:D,selectedTabKey:A,screen:M,liveSessionInboxState:N,sendDaemonCommand:o,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q,resetMachineAction:de.resetMachineAction}),V=YC({conversations:e,selectedConversation:D,machineBackTarget:R,markConversationRead:oe,resetMachineAction:de.resetMachineAction,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q}),{isMuted:ie,toggleMute:ke}=tp(N,o),xe=l.useMemo(()=>Yr(W.filter(H=>H.requiresAction&&!ie(H.conversation))),[W,ie]),Se=l.useMemo(()=>Yr(W.filter(H=>H.unread&&!H.requiresAction&&!ie(H.conversation))),[W,ie]),pe=l.useMemo(()=>HC(W.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking),E.current),[W]);l.useEffect(()=>{E.current=pe.map(H=>H.conversation.tabKey)},[pe]);const G=l.useMemo(()=>Yr(W.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[W]),O=l.useMemo(()=>z?W.filter(H=>Ps(H.conversation)===z.id):[],[W,z]),Z=l.useMemo(()=>OC(z,n),[n,z]),q=(z==null?void 0:z.version)||null,me=!!z&&!!q&&!0&&q!==$,Te=l.useMemo(()=>(z==null?void 0:z.availableProviders)||[],[z]),_=l.useMemo(()=>Te.filter(H=>Sn(H,"cli")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),se=l.useMemo(()=>Te.filter(H=>Sn(H,"acp")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),ve=l.useMemo(()=>UC(ae,W),[W,ae]),ce=l.useCallback(async H=>{z&&await de.handleOpenRecent(z.id,H)},[de,z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&D?s.jsx(IC,{selectedConversation:D,isAcp:lt(D),isStandalone:i,selectedIdeEntry:U,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:V.backFromConversation,onOpenNativeConversation:V.openNativeConversation,onOpenMachine:V.openConversationMachine,onOpenHistory:w,onOpenRemote:p,onOpenMeshGraph:v,onStopCli:y,cliViewMode:Y,onSetCliViewMode:async H=>{await Eh({conversation:D,mode:H,ides:n,sendDaemonCommand:o,setCliViewModeOverrides:C})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):M==="machine"&&z?s.jsx(BC,{selectedMachineEntry:z,selectedMachineConversations:O,selectedMachineRecentLaunches:Z,cliProviders:_,acpProviders:se,selectedMachineNeedsUpgrade:me,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:R==="inbox",onBack:V.backFromMachine,onSectionChange:V.changeMachineSection,onOpenConversation:V.openConversation,onOpenRecent:ce,onOpenMachineDetails:()=>I(`/machines/${z.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(z.id),onLaunchDetectedIde:(H,fe)=>de.handleLaunchDetectedIde(z.id,H,fe),onAddWorkspace:(H,fe)=>de.handleAddWorkspace(z.id,H,fe),onBrowseDirectory:H=>de.handleBrowseDirectory(z.id,H),onLaunchWorkspaceProvider:(H,fe,je)=>de.handleLaunchWorkspaceProvider(z.id,H,fe,je),onListSavedSessions:H=>de.handleListSavedSessions(z.id,H)}):s.jsx(PC,{section:P,attentionItems:xe,unreadItems:Se,workingItems:pe,completedItems:G,hiddenConversations:t,machineCards:ve,getAvatarText:JC,actionLogs:r,sendDaemonCommand:o,onOpenConversation:V.openConversation,onShowAllHidden:j,onHideConversation:S,onOpenMeshGraph:v,onStopCli:y,onOpenNewSession:g,onOpenMachine:V.openMachine,onOpenSettings:()=>I("/settings"),onSectionChange:B,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:ie,onToggleMuteConversation:ke})})}function ga(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function XC({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=l.useRef(0),[c,u]=l.useState(!1),[h,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),x=l.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!ga(t,n)){d("merge");return}const k=y.currentTarget.getBoundingClientRect(),b=y.clientX-k.left,j=k.width/3;b<j?d("split-left"):b>j*2?d("split-right"):d("merge")},[t,n]),w=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),p=l.useCallback(y=>{i.current=0,u(!1);const k=y.dataTransfer.getData("text/tab-key"),b=k?e.some(S=>S.tabKey===k):!1,j=h;if(d(null),a(),!!k){if(y.preventDefault(),j==="split-left"&&ga(t,n)){n==null||n(k,"split-left");return}if(j==="split-right"&&ga(t,n)){n==null||n(k,"split-right");return}if(b){o(k);return}r==null||r(k)}},[e,h,t,n,r,o,a]);return{dragOver:c,dropAction:h,resetDragState:m,handleDragEnter:f,handleDragOver:x,handleDragLeave:w,handleDrop:p}}function ZC(e,t){const n=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>n.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function e1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[h,d]=l.useState(null),m=l.useRef(null),f=l.useRef(null),x=l.useRef(r),w=l.useRef(o);l.useEffect(()=>{x.current=r},[r]),l.useEffect(()=>{w.current=o},[o]),l.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),l.useEffect(()=>{u(N=>{const C=ZC(N,e);return C.length===N.length&&C.every((A,T)=>A===N[T])?N:C})},[e]);const p=l.useMemo(()=>{const N=h??c;if(N.length===0)return e;const C=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const M=C.get(A.tabKey)??999,L=C.get(T.tabKey)??999;return M-L})},[e,h,c]);l.useEffect(()=>{var C,A;if(p.length===0){a!==null&&(i(null),(C=x.current)==null||C.call(x,null));return}if(a&&p.some(T=>T.tabKey===a))return;const N=p[0].tabKey;N!==a&&(i(N),(A=x.current)==null||A.call(x,N))},[p,a]);const y=l.useMemo(()=>p.find(N=>N.tabKey===a),[p,a]),k=l.useCallback(N=>{var C;i(N),(C=x.current)==null||C.call(x,N)},[]),b=l.useCallback((N,C,A)=>{u(T=>{var B;const M=T.filter(K=>K!==N),L=M.indexOf(C);if(L<0)return T;const P=A==="left"?L:L+1;return M.splice(P,0,N),(B=w.current)==null||B.call(w,M),M}),d(null)},[]),j=l.useCallback((N,C,A)=>{const M=(c.length>0?c:e.map(B=>B.tabKey)).filter(B=>B!==N),L=M.indexOf(C);if(L<0)return;const P=A==="left"?L:L+1;M.splice(P,0,N),m.current=M,d(M)},[c,e]),S=l.useCallback(()=>{var C;const N=m.current;N&&(u(N),(C=w.current)==null||C.call(w,N))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),g=l.useCallback(N=>{u(C=>{var T;const A=C.filter(M=>M!==N);return A.push(N),(T=w.current)==null||T.call(w,A),A})},[]);return{activeTabId:a,activeConv:y,sortedConversations:p,previewOrderRef:m,draggingTabRef:f,selectTab:k,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:g,setDraggingTabKey:N=>{f.current=N}}}function t1({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 ol({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a}){const{t:i}=Le("common");if(o)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,u=r&&!!a,h=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),d=i(r?"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:h}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),u&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:a,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Mi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(Yh,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const sp="adhdev-tab-shortcuts";function np(){try{return JSON.parse(localStorage.getItem(sp)||"{}")}catch{return{}}}function rp({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=l.useState(()=>np()),[c,u]=l.useState(null),h=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(o?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(o?"⌥":"Alt"),m.shiftKey&&f.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[o]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(sp,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const x=h(f);if(!x)return;const w={...a};for(const[p,y]of Object.entries(w))y===x&&delete w[p];w[c]=x,d(w),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,a,d,h]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[x,w]of Object.entries(a))if(t.includes(x)&&h(f)===w){f.preventDefault(),n(),r(x);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,a,t,n,r,h]),{isMac:o,tabShortcuts:a,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const xa=e=>{e.preventDefault()},s1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:h,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:x,onClearPreviewOrder:w,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:j,isGroupActive:S}){const v=An(t),g=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",N=v.isReconnecting,C=y0(t),A=v0(t),T=oh(t),M=l.useCallback(I=>{c.current=t.tabKey,y(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,c,y]),L=l.useCallback(()=>{c.current=null,y(null),x(),w(),p()},[c,y,x,w,p]),P=l.useCallback(I=>{const $=c.current;if(!(!$||$===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";m($,t.tabKey,U)}},[t.tabKey,c,m]),B=l.useCallback(I=>{I.preventDefault(),I.stopPropagation();const $=I.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";i.includes($)?f($,t.tabKey,U):k&&k($)}w()},[t.tabKey,i,f,k,w]),K=l.useCallback(I=>{I.stopPropagation(),u(),h(t.tabKey),d(t)},[t,d,u,h]),F=l.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(I=>{const $=I.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),Q=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",g,n&&"is-active",S&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:M,onDragEnd:L,onDragOver:P,onDrop:B,onClick:K,onContextMenu:F,onTouchStart:R,onTouchEnd:Q,onTouchMove:Q,style:{position:"relative",cursor:"pointer",opacity:r?.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(es,{size:11})}),o&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Gs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Gs(t)}),s.jsx(co,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${a}`,children:a})]})},(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 n1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onHideTab:p,isGroupActive:y,allowTabShortcuts:k=!0}){const[b,j]=l.useState(null),S=l.useRef(null),v=l.useRef(null),g=l.useMemo(()=>e.map(P=>P.tabKey),[e]);mr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:N,tabShortcuts:C,shortcutListening:A,setShortcutListening:T,saveShortcuts:M}=rp({enabled:k,sortedTabKeys:e.map(P=>P.tabKey),onFocus:a,onSelectTab:i});l.useEffect(()=>{if(!b)return;const P=B=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(B.target)||j(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),l.useEffect(()=>{const P=v.current;if(!P)return;const B=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),P.scrollLeft+=K.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const L=l.useCallback((P,B,K)=>{j({x:P,y:B,tabKey:K})},[]);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(P=>s.jsx(s1,{conv:P,isActive:t===P.tabKey,isDraggedTab:o.current===P.tabKey,isTaskCompleteUnread:r.has(P.tabKey),shortcut:k?C[P.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:L,longPressTimer:S,isGroupActive:y},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[k&&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:xa,onClick:P=>{P.stopPropagation(),T(b.tabKey),j(null)},children:["⌨ ",C[b.tabKey]?`Change shortcut (${C[b.tabKey]})`:"Set shortcut"]}),C[b.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:xa,onClick:()=>{const P={...C};delete P[b.tabKey],M(P),j(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[k&&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:xa,onClick:()=>{p(b.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&A&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>T(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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:"Press Esc to cancel"})]})})]})}function r1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:h,onFocus:d,isSplitMode:m,numGroups:f,onMoveTab:x,onReceiveTab:w,style:p,onActiveTabChange:y,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:j,onHideTab:S,isFocused:v,allowTabShortcuts:g=!0,onOpenNewSession:N,liveSessionInboxState:C}){const{sendCommand:A}=yt(),T=l.useRef(null),{activeTabId:M,activeConv:L,sortedConversations:P,draggingTabRef:B,selectTab:K,handleTabReorder:F,updatePreviewOrder:R,commitPreviewOrder:Q,clearPreviewOrder:E,moveTabToEnd:I,setDraggingTabKey:$}=e1({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:y,onTabOrderChange:j}),D=Po({sendDaemonCommand:o,activeConv:L,setActionLogs:a,isStandalone:i}),{dragOver:U,dropAction:Y,resetDragState:ae,handleDragEnter:z,handleDragOver:X,handleDragLeave:de,handleDrop:re}=XC({conversations:e,numGroups:f,onMoveTab:x,onReceiveTab:w,onOwnTabDrop:I,onClearPreviewOrder:E}),W=L&&!lt(L)&&Tn(L)==="terminal",oe=l.useMemo(()=>L?t.find(xe=>xe.id===L.routeId):void 0,[t,L]),V=l.useMemo(()=>L?r.filter(xe=>xe.routeId===L.tabKey):[],[r,L]),ie=l.useMemo(()=>new Set(P.filter(xe=>Pb(xe,C,{isOpenConversation:xe.tabKey===M})).map(xe=>xe.tabKey)),[M,C,P]);mr("PaneGroup",{groupIndex:h,conversationCount:e.length,activeTabId:M,dragOver:U});const ke=l.useCallback(xe=>{xe.streamSource==="agent-stream"&&xe.agentType&&A(xe.routeId,Hu(),{agentType:xe.agentType,...xe.sessionId&&{targetSessionId:xe.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(n1,{conversations:P,activeTabId:M,groupIndex:h,numGroups:f,unreadTabKeys:ie,draggingTabRef:B,onFocus:d,onSelectTab:K,onConversationActivated:ke,onPreviewReorder:R,onReorderTab:F,onCommitPreviewOrder:Q,onClearPreviewOrder:E,onDragStateReset:ae,onDragTabKeyChange:$,onMoveTab:x,onReceiveTab:w,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:z,onDragOver:X,onDragLeave:de,onDrop:re,children:[U&&s.jsx(t1,{dropAction:Y,canSplit:!!(f<4&&x)}),L?s.jsx(nl,{activeConv:L,clearToken:n[L.tabKey]||0,isCliTerminal:!!W,ideEntry:oe,terminalRef:T,handleModalButton:D.handleModalButton,handleRelaunch:D.handleRelaunch,handleSendChat:D.handleSendChat,handleForceSendChat:D.handleForceSendChat,isSendingChat:D.isSendingChat,sendFeedbackMessage:D.sendFeedbackMessage,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:V,userName:u,isInputActive:!m||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function o1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,focusedGroup:x,focusGroup:w,moveTabToGroup:p,splitTabRelative:y,closeGroup:k,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:g,toggleHiddenTab:N,onOpenNewSession:C,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,L)=>{const P=t&&r.length===n?`${r[L]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&L>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:B=>b(L-1,B),onDoubleClick:()=>k(L),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(r1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:L,isFocused:t&&x===L,onFocus:()=>w(L),isSplitMode:t,numGroups:n,onMoveTab:(B,K)=>{K==="left"&&L>0?p(B,L-1):K==="right"&&L<n-1?p(B,L+1):K==="split-left"&&n<4?y(B,L,"left"):K==="split-right"&&n<4&&y(B,L,"right")},onReceiveTab:B=>p(B,L),onActiveTabChange:B=>S(L,B),initialActiveTabId:j[L],initialTabOrder:v[L],onTabOrderChange:B=>g(L,B),onHideTab:N,onOpenNewSession:C,allowTabShortcuts:A,liveSessionInboxState:T})]},L)})})}const op="adhdev-dashboard-action-shortcuts",a1=1200,i1=[["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 l1(){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 ap(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 mi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function yo(e){const t=Object.fromEntries(ap(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(op)||"{}"),r={...t,...n};for(const[o,a]of i1)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function ip(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function c1({enabled:e=!0,onTrigger:t}){const n=l1(),[r,o]=l.useState(()=>yo(n)),[a,i]=l.useState(null),[c,u]=l.useState([]),h=l.useRef({parts:[],timer:null}),d=l.useCallback(p=>{const y=[];return p.metaKey&&y.push(n?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(n?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(ip(p.key)),y.join("+"))},[n]),m=l.useCallback(p=>{o(p);try{localStorage.setItem(op,JSON.stringify(p))}catch{}},[]);l.useEffect(()=>{const p=yo(n),y=Object.entries(r),k=Object.entries(p);y.length===k.length&&y.every(([b,j])=>p[b]===j)||m(p)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current={parts:[],timer:null}},[]),x=l.useCallback(()=>{typeof window>"u"||(h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current.timer=window.setTimeout(()=>{h.current={parts:[],timer:null}},a1))},[]);l.useEffect(()=>{if(!a)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){i(null),u([]);return}const k=d(y);if(!k)return;const j=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&j){u([k]);return}const v=[...c,k].slice(0,2).join(" "),g={...r};for(const[N,C]of Object.entries(g))C===v&&delete g[N];g[a]=v,m(g),i(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[r,d,m,a,c]),l.useEffect(()=>{if(!e||a)return;const p=y=>{if(y.defaultPrevented)return;const k=d(y);if(!k)return;const b=y.metaKey||y.ctrlKey||y.altKey;if(mi(y.target))return;const j=h.current.parts,S=b?[k]:[...j.slice(-1),k].slice(-2),v=S.join(" "),g=S[S.length-1],N=Object.entries(r).filter(([,L])=>!!L),C=N.find(([,L])=>L===v);if(C){y.preventDefault(),f(),t(C[0]);return}if(N.some(([,L])=>L.startsWith(`${v} `))){y.preventDefault(),h.current.parts=S,x();return}const T=N.find(([,L])=>L===g);if(T){y.preventDefault(),f(),t(T[0]);return}if(N.some(([,L])=>L.startsWith(`${g} `))){y.preventDefault(),h.current.parts=[g],x();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,x,e,d,t,f,a]),l.useEffect(()=>()=>f(),[f]);const w=l.useMemo(()=>ap(n),[n]);return{isMac:n,actionDefinitions:w,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function d1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const o=[];return e?(t&&o.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),o.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?o.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):o.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),o.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&o.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),o.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),o}function lp(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Uc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!lp(r):!0}function u1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:lp(n)}const cp=1e3,h1=4;function Gc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Kc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function p1({detachDelayMs:e=cp,stillnessThresholdPx:t=h1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,u=null,h=null,d=!1;const m=()=>{h!=null&&(o(h),h=null)},f=()=>{m(),c=null},x=()=>{m(),a=null,i=null,c=null,u=null,d=!1},w=()=>{!a||!c||!u||d||h!=null||(h=r(()=>{h=null,!(!a||!c||!u||d)&&Gc(u,i)&&(Kc(c,u,t)||(d=!0,n({panelId:a,clientX:u.clientX,clientY:u.clientY})))},e))},p=k=>{if(!(!a||d)){if(!Gc(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Kc(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},w()}},y=k=>{!a||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{m(),a=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:x,isDragging:()=>a!=null,hasDetached:()=>d,dispose:x}}function m1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Jr(e){return xt(e)||e.tabKey}function f1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function zc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ya(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=o=>{if(o)try{o.focus({preventScroll:!0})}catch{try{o.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function va(e,t){e.classList.remove(Fa.className,Ha.className),e.classList.add(t==="light"?Fa.className:Ha.className)}function qc(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function b1(e,t,n){var i;const r=[t];let o;for(const c of r){let u;for(const h of c){const d=e.addPanel({id:h.tabKey,component:"conversation",title:Jr(h),params:{kind:"conversation",tabKey:h.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});u||(u=d.id)}o=u??o}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Vc(e,t){const n=new Set(t.map(o=>o.tabKey)),r=new Map;for(const o of t)r.set(o.tabKey,(r.get(o.tabKey)||0)+1);for(const o of[...e.panels])rs(o.id)||n.has(o.id)||e.removePanel(o);for(const o of t){const a=e.getPanel(o.tabKey);if(a){(r.get(o.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:o.tabKey,daemonId:o.daemonId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,panelId:a.id}),a.update({params:{tabKey:o.tabKey}}),a.title!==Jr(o)&&a.api.setTitle(Jr(o));continue}e.addPanel({id:o.tabKey,component:"conversation",title:Jr(o),params:{kind:"conversation",tabKey:o.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 Yc(e,t,n){var u,h;const r=n?f1(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const o=cs(t,n);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=ch(o);if(a){a.title!==i&&a.api.setTitle(i);return}const c=(o==null?void 0:o.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((h=e.panels.find(d=>!rs(d.id)))==null?void 0:h.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function dp({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[o,a]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?kt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>a(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&a(null)},[n]),l.useEffect(()=>{var d;return e?((d=kt.onStatus)==null?void 0:d.call(kt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{a(null)},[e,t]),l.useEffect(()=>{const h=e?kt.get(e):null;if(!(!h||n!=="connected"))return r!=="chat"&&t?h.startScreenshots(t):h.stopScreenshots(t),()=>{h.stopScreenshots(t)}},[r,n,t,e]);const u=l.useCallback(async(h,d)=>{const m=e?kt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(h,d,t)},[e,n,t]);return{connScreenshot:o,screenshotUsage:i,handleRemoteAction:u}}const up=l.createContext(null);function Eo(){const e=l.useContext(up);if(!e)throw new Error("DashboardDockviewContext missing");return e}function g1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(o=>o+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const o of r)o.dispose()}},[e.api,e.containerApi])}function x1({params:e}){var u;const t=Eo(),n=l.useMemo(()=>cs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(h=>h.id===e.routeId),[t.ides,e.routeId]),o=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:a,screenshotUsage:i,handleRemoteAction:c}=dp({doId:o,targetSessionId:n?Fu(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.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(iu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:a,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 y1(){const e=Eo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function v1(e){var b,j;g1(e);const t=Eo(),n=l.useCallback(S=>{"button"in S&&S.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),o=r==null?void 0:r.sessionId,a=l.useCallback(S=>t0(S),[]),i=l.useCallback(()=>e0(o),[o]),c=l.useSyncExternalStore(a,i,i);if(e.params.kind==="remote"){const S=cs([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(S==null?void 0:S.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:S!=null&&S.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:S.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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 h=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,d=e.api.isGroupActive,m=No(u,t.liveSessionInboxState,{isOpenConversation:h}),f=m.isReconnecting,x=m.isConnecting,w=m.isGenerating||c,p=m.isWaiting,y=m.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:S=>{var v;S.preventDefault(),n(S),t.openTabContextMenu({x:S.clientX,y:S.clientY,tabKey:u.tabKey,sourceDocument:((v=S.target)==null?void 0:v.ownerDocument)??document})},children:[y&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:w?s.jsx("div",{className:"tab-spinner"}):p?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):x?s.jsx("div",{className:"tab-connecting-spinner"}):u.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:xt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(u)}):x?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(u)}):s.jsx("span",{children:Gs(u)})})]}),k&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:k,children:k})]})}function Er(e){return e.isActive}function Jc(e){return e.isVisible}function w1(e){e.preventDefault()}function k1({params:e,api:t}){var x;const n=Eo(),r=l.useRef(null),[o,a]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Jc(t)),u=n.conversationsByTabKey.get(e.tabKey),h=Po({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{a(Er(t)),c(Jc(t));const w=[t.onDidActiveChange(p=>a(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Er(t)&&!p.isActive){a(!1);return}a(Er(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of w)p.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(w=>w.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(w=>w.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!lt(u)&&Tn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(nl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:r,handleModalButton:h.handleModalButton,handleRelaunch:h.handleRelaunch,handleSendChat:h.handleSendChat,handleForceSendChat:h.handleForceSendChat,isSendingChat:h.isSendingChat,handleFocusAgent:h.handleFocusAgent,isFocusingAgent:h.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((x=n.scrollToBottomRequest)==null?void 0:x.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function S1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:h,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:x,onOpenNewSession:w,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:S,layoutProfile:v}){var ut,at,ht;const{theme:g}=Ls(),{sendCommand:N}=yt(),C=l.useRef(null),A=l.useRef(null),T=l.useRef(null),M=l.useRef(!1),L=l.useRef(!1),P=l.useRef(!1),B=l.useRef(null),K=l.useRef([]),[F,R]=l.useState(null),[Q,E]=l.useState(0),I=l.useRef(typeof window>"u"?{}:OS(v)),$=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),D=l.useMemo(()=>{const J=C.current;return J?J.groups.some(te=>{try{const le=te.model.location.type;return le!=="floating"&&le!=="popout"?!1:te.panels.some(ue=>$.has(ue.id))}catch{return!1}}):!1},[$,Q,e]),U=l.useCallback(()=>{var J;(J=C.current)==null||J.focus()},[]),Y=l.useCallback((J,te)=>{p==null||p(J,te)},[p]),ae=l.useCallback(J=>{const te=document,le=J.document;for(const Ne of te.querySelectorAll('link[rel="stylesheet"]')){const He=le.createElement("link");He.rel="stylesheet",He.href=Ne.href,Ne.crossOrigin&&(He.crossOrigin=Ne.crossOrigin),le.head.appendChild(He)}for(const Ne of te.querySelectorAll("style")){const He=le.createElement("style");He.textContent=Ne.textContent,le.head.appendChild(He)}const ue=[];for(const Ne of te.styleSheets)try{for(const He of Ne.cssRules)He instanceof CSSStyleRule&&(He.selectorText===":root"||He.selectorText==="html")&&ue.push(He.cssText)}catch{}if(ue.length>0){const Ne=le.createElement("style");Ne.textContent=ue.join(`
71
- `),le.head.appendChild(Ne)}const ge=te.documentElement.getAttribute("data-theme");ge&&le.documentElement.setAttribute("data-theme",ge),le.documentElement.style.colorScheme=ge==="light"?"light":"dark",le.body.className=te.body.className;const Ae=te.documentElement.getAttribute("style");Ae&&le.documentElement.setAttribute("style",Ae);const Pe=le.getElementById("dv-popout-window");Pe instanceof HTMLElement&&(Pe.classList.add("adhdev-dockview"),va(Pe,g))},[g]),z=l.useCallback(()=>{var te;const J=C.current;if(J)for(const le of J.groups)try{const ue=(te=le.element)==null?void 0:te.ownerDocument;if(!ue||ue===document)continue;const ge=ue.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),va(ge,g));const Ae=document.documentElement.getAttribute("data-theme");Ae&&ue.documentElement.setAttribute("data-theme",Ae),ue.documentElement.style.colorScheme=Ae==="light"?"light":"dark",ue.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe?ue.documentElement.setAttribute("style",Pe):ue.documentElement.removeAttribute("style")}catch{}},[g]),X=l.useCallback(J=>{const te=C.current;if(!te)return;const le=te.getPanel(J);le&&te.addPopoutGroup(le,{popoutUrl:"/popout.html",onDidOpen:({window:ue})=>{ae(ue),Se();const ge=$.get(J);ue.document.title=ge?`${xt(ge)} — ADHDev`:"ADHDev — Popout"}})},[$,ae]),de=l.useCallback(J=>{const te=C.current,le=te==null?void 0:te.getPanel(J);if(!te||!le)return;const ue=te.groups.filter(ge=>{var Ae;try{return((Ae=ge.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),re=l.useCallback(J=>{var ue;const te=C.current;if(!te)return!1;const le=te.getPanel(J);if(!le)return!1;try{return((ue=le.group.element)==null?void 0:ue.ownerDocument)!==document}catch{return!1}},[]),W=l.useCallback(J=>{re(J)&&de(J),d(J)},[re,de,d]),oe=l.useCallback(J=>{const te=C.current,le=te==null?void 0:te.getPanel(J);!te||!le||te.addFloatingGroup(le,{width:600,height:500})},[]),V=l.useCallback(J=>{var le;const te=(le=C.current)==null?void 0:le.getPanel(J);if(!te)return!1;try{return te.group.model.location.type==="floating"}catch{return!1}},[]),ie=l.useCallback(()=>{var te,le;const J=(le=(te=C.current)==null?void 0:te.activePanel)==null?void 0:le.id;return!J||rs(J)?null:$.has(J)?J:null},[$]),ke=l.useCallback(J=>{const te=C.current,le=te==null?void 0:te.getPanel(J);if(!te||!le)return;const ue=te.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),xe=l.useCallback(()=>{var Ae;const J=C.current;if(!J)return;const le=J.groups.filter(Pe=>{var Ne;try{return((Ne=Pe.element)==null?void 0:Ne.ownerDocument)===document&&Pe.model.location.type==="grid"}catch{return!1}})[0]||null,ue=[...J.panels];for(const Pe of ue){const Ne=(Ae=Pe.group.element)==null?void 0:Ae.ownerDocument,He=Pe.group.model.location.type;Ne===document&&He==="grid"||(le&&le.id!==Pe.group.id?Pe.api.moveTo({group:le,position:"center"}):Pe.api.moveTo({position:"center"}))}const ge=J.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),ya(document)},[]),Se=l.useCallback(()=>{var te,le;const J=C.current;if(J)for(const ue of J.groups){const ge=(te=ue.element)==null?void 0:te.ownerDocument;if(!ge||ge===document)continue;const Ae=ge.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let Pe=null,Ne=ge.title||"ADHDev",He="Popout workspace";const Ue=ue.activePanel;if(Ue)if(Pe=Ue.id,rs(Ue.id)){const ee=((le=Ue.params)==null?void 0:le.routeId)||Ue.id.slice(7),be=cs([...$.values()],ee);Ne=ch(be),He=be!=null&&be.machineName?`Remote view · ${be.machineName}`:"Remote view"}else{const ee=$.get(Ue.id);Ne=ee?xt(ee):Ue.title||Ue.id,He=ee?Gs(ee):"Dockview panel"}ge.title=`${Ne} — ADHDev`;const Ze=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const ee of Ze)ee.remove();const _e=ge.createElement("div");_e.id="adhdev-popout-header",ge.body.appendChild(_e),_e.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(";")),_e.innerHTML=`
70
+ `)&&!o.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:$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function pC(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?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:r}}function dr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function zh(e){return To(e)||e.tabKey||e.routeId||null}function qh(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Vh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function mC(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function fC(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return o?o.tabKey:r||n||null}function bC(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Vh(t.daemonId);if(r&&r!==e.machineId)return null;const o=Ns(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),u=Ns(t.targetSessionId);if(a&&a!==c&&a!==u||i&&i!==c&&i!==u)return null;const h=xo(e.workspacePath);if(h){const d=xo(t.workspaceName);if(d&&!mC(d,h))return null}return fC(t,n)}function Bc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gC({ides:e,conversations:t,onOpenSession:n}){const[r,o]=l.useState(null),a=l.useRef(null),i=l.useCallback(()=>{a.current=null,o(null)},[]),c=l.useCallback(u=>{a.current=u,o(u)},[]);return l.useEffect(()=>{if(!r)return;const u=xo(r.workspacePath),h=e.find(m=>{var y,k,b,j;if(!m||m.type==="adhdev-daemon"||Vh(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":pn(m)?"acp":"ide")!==r.kind)return!1;const w=String(m.agentType||m.type||"");if(r.providerType&&w!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const S=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(g=>String(g||"")).filter(Boolean).includes(S)}if(u){const S=xo(m.workspace||m.runtimeWorkspaceLabel);return S?S===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(k=(y=m.activeChat)==null?void 0:y.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!h)return;const d=qh({entrySessionId:h.sessionId,entryInstanceId:h.instanceId,entryRouteId:h.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>pt.onStatusEvent(u=>{const h=a.current;if(!h)return;const d=bC(h,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const u=window.setTimeout(()=>{o(h=>!h||h.startedAt!==r.startedAt?h:(a.current=null,null))},45e3);return()=>window.clearTimeout(u)},[r]),{trackPendingLaunch:c}}function xC({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Bi(),{launchCli:c}=ko(),u=l.useCallback(async(y,k)=>sl(e,y,k),[e]),h=l.useCallback(async(y,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(y,"workspace_add",{path:k.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]),d=l.useCallback(async(y,k,b)=>{var j;try{const S={ideType:k,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(S.workspace=b.workspacePath.trim());const v=await e(y,"launch_ide",S);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:y,kind:"ide",providerType:k,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(y,k,b,j)=>{var v,g,N,C;const S=Date.now();try{const A={cliType:b};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?A.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(A.workspaceId=j.workspaceId),(g=j==null?void 0:j.resumeSessionId)!=null&&g.trim()&&(A.resumeSessionId=j.resumeSessionId.trim()),Array.isArray(j==null?void 0:j.cliArgs)&&j.cliArgs.length>0&&(A.cliArgs=j.cliArgs),(N=j==null?void 0:j.initialModel)!=null&&N.trim()&&(A.initialModel=j.initialModel.trim()),(C=j==null?void 0:j.initialThinkingLevel)!=null&&C.trim()&&(A.initialThinkingLevel=j.initialThinkingLevel.trim());const T=await c(y,A),M=(T==null?void 0:T.result)||T,L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return T!=null&&T.success&&L?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:L,startedAt:S}),{ok:!0}):T!=null&&T.success?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:(T==null?void 0:T.error)||(M==null?void 0:M.error)||`Could not launch ${k.toUpperCase()} session`}}catch(A){return Bc(A)?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async y=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(y);if(!y)return[];try{const b=await e(y,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((k=j==null?void 0:j.result)==null?void 0:k.meshes)?j.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),x=l.useCallback(async(y,k,b,j)=>{var v,g;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(y,k,b,j);const S=Date.now();try{const N={meshId:k.trim()};b.trim()&&(N.cliType=b.trim());const C=(v=j==null?void 0:j.initialModel)==null?void 0:v.trim(),A=(g=j==null?void 0:j.initialThinkingLevel)==null?void 0:g.trim();C&&(N.initialModel=C),A&&(N.initialThinkingLevel=A);const T=await e(y,"launch_mesh_coordinator",N),M=(T==null?void 0:T.result)??T;if((M==null?void 0:M.success)===!1||(T==null?void 0:T.success)===!1){const P=String((M==null?void 0:M.code)||(T==null?void 0:T.code)||""),B=pC((M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(M==null?void 0:M.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:B}}const L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return L?n(L):t({machineId:y,kind:"cli",providerType:(M==null?void 0:M.cliType)||b.trim()||void 0,workspacePath:(M==null?void 0:M.workspace)||null,startedAt:S}),{ok:!0}}catch(N){return Bc(N)?(t({machineId:y,kind:"cli",providerType:b.trim()||void 0,startedAt:S}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),w=l.useCallback(async(y,k)=>{if(!y||!k)return[];try{const b=await e(y,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),p=l.useCallback(async y=>{await Eh({conversation:r,mode:y,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:h,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:w,setActiveCliViewMode:p}}function yC(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 vC(e,t,n=Date.now()){return!e||!yC(t)?null:{tabKey:e,nonce:n}}function wC({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[c,u]=l.useState(null),[h,d]=l.useState(null),m=l.useMemo(()=>{var y,k;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const p=r[o];if(p){const b=t.find(j=>j.tabKey===p);if(b)return b}return((y=a[o])==null?void 0:y[0])||((k=a[0])==null?void 0:k[0])},[t,c,o,r,a,e,n]),f=l.useCallback(p=>{u(p)},[]),x=l.useCallback(p=>{u(p.tabKey),i(y=>{const k=new URLSearchParams(y),b=nw(p);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),w=l.useCallback((p,y)=>{const k=vC(p,y);k&&d(k)},[]);return{activeConv:m,openDesktopConversation:x,requestScrollToBottom:w,scrollToBottomRequest:h,setDesktopActiveTab:f}}function kC(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 SC(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),o=!!e.liveState.unread,a=[e.tabKey,e.historySessionId||"",t,n,r,o?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&o&&(!t||t!==n)),autoReadKey:a,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function CC({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const o=l.useRef(null),a=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const h=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),a.current=null};if(t){h(),o.current=null;return}if(!(e!=null&&e.sessionId)){h(),o.current=null;return}const d=Ds(e,n),m=SC({tabKey:e.tabKey,historySessionId:To(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:qs(e),liveState:d}),f=m.autoReadKey,x=kC({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!m.shouldMarkSeen){x.shouldCancelPending&&h(),o.current=f;return}if(!x.shouldSchedule)return;x.shouldCancelPending&&h();const w=()=>{if(document.visibilityState!=="visible"||o.current===f)return;o.current=f,a.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const y=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:m.completionMarker}).catch(()=>{})};if(a.current=x.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(w,1500);const y=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(w,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=p,document.addEventListener("visibilitychange",p)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function pa(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 jC({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:c,setSearchParams:u}){var Q;const{launchCli:h}=ko(),[d,m]=l.useState(!1),[f,x]=l.useState([]),[w,p]=l.useState(()=>Ft()),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),g=!!v&&ct(v)&&!lt(v),N=l.useMemo(()=>{if(!v||!g)return null;const E=v.daemonId||v.routeId||"",I=bs(v),$=pa(v);return`${E}:${I}:${v.providerSessionId||""}:${$}`},[v,g]),C=l.useMemo(()=>!v||!g?"":pa(v),[v,g]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:M,handleNewChat:L,handleRefreshHistory:P}=Wh({sendDaemonCommand:o,activeConv:v,chats:(Q=r.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:Q.chats,updateRouteChats:a,setToasts:i,setClearedTabs:c}),B=l.useCallback(()=>{m(!0)},[]),K=l.useCallback(()=>{m(!1)},[]),F=l.useCallback(async()=>{if(!(!v||!g||y)){k(!0);try{const E=v.daemonId||v.routeId,I=bs(v),$=pa(v),D=await o(E,"list_saved_sessions",{agentType:I,providerType:I,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...$?{workspace:$}:{}}),U=(D==null?void 0:D.result)??D;x(Array.isArray(U==null?void 0:U.sessions)?U.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),x([])}finally{k(!1)}}},[v,y,g,o]);l.useEffect(()=>{if(!d){S.current=null;return}if(!g){S.current=null,x([]),k(!1);return}!N||y||S.current!==N&&(S.current=N,F())},[F,d,y,g,N]);const R=l.useCallback(async E=>{if(!v||!g||!E.providerSessionId||!E.workspace)return;const I=v.daemonId||v.routeId,$=bs(v);try{j(E.providerSessionId);const D=await h(I,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),U=(D==null?void 0:D.result)??D,Y=typeof(U==null?void 0:U.sessionId)=="string"?U.sessionId:typeof(U==null?void 0:U.id)=="string"?U.id:"";Y&&u(ae=>{const z=new URLSearchParams(ae);return z.set("activeTab",Y),z},{replace:!0}),K()}catch(D){console.error("Resume saved session failed",D)}finally{j(null)}},[K,v,g,o,u]);return{historyModalOpen:d,openHistoryModal:B,closeHistoryModal:K,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:M,handleHistoryNewChat:L,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:p,missingWorkspaceResumePath:C,isSavedHistoryLoading:y,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:R}}function NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}){const[u,h]=l.useState(null),[d,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const k=c(r);return k&&!ct(k)&&!lt(k)?k:null},[e,r,c]),x=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const b=u!=null&&u.tabKey?a.find(j=>j.tabKey===u.tabKey):o?a.find(j=>j.tabKey===o):null;return(b==null?void 0:b.routeId)===k?b:cs(a,k)},[a,u,o]),w=l.useMemo(()=>{if(x)return i.find(k=>k.id===x.routeId)},[i,x]);l.useEffect(()=>{f&&(h({routeId:f.routeId,tabKey:ec(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const p=l.useCallback(k=>{k&&(h({routeId:k.routeId,tabKey:ec(k)}),m(k))},[]),y=l.useCallback(()=>{h(null),m(null)},[]);return{remoteDialogConv:x,remoteDialogIdeEntry:w,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:p,closeRemoteDialog:y}}function AC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:h}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p}=NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useCallback(async N=>{const C=N||u;!C||!ct(C)&&!lt(C)||(j(C),k(!0))},[u]),v=l.useCallback(()=>{k(!1),j(null)},[]),g=l.useCallback(async N=>{const C=b||u;if(!C||!ct(C)&&!lt(C)){v();return}k(!1);try{const A=bs(C),T=C.routeId||C.daemonId||"";await h(T,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:N,...Do(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[u,v,b,h]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:b,requestCliStop:S,cancelCliStop:v,confirmCliStop:g}}function ma(e,t=!0){return(e??!0)&&t}const nl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:o,terminalRef:a,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k=!0,isVisible:b=!0}){const j=r,S=!r,v=ma(b,j),g=ma(b,S),N=ma(b),C=Ph(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(hu,{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(Ys,{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":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(E0,{activeConv:A,clearToken:n,terminalRef:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:k&&v})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(ri,{activeConv:A,ideEntry:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k&&g,isVisible:g})})]}):s.jsx(ri,{activeConv:A,ideEntry:o,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k&&N,isVisible:N})]})},(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 TC({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){var j,S,v;const i=pr(),c=Ps(e),u=a?null:Eu(e),h=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!a&&e.streamSource==="agent-stream"&&!!e.agentName,m=!a&&!d&&(e.transport==="pty"||e.transport==="acp"),f=yn(e),x=sw(e),w=(j=e.settings)==null?void 0:j.meshNodeFor,p=e.meshQueueStats,y=((S=e.coordinator)==null?void 0:S.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),k=l.useCallback(()=>{if(r){r();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,r]),b=l.useCallback(()=>{if(n){n();return}const g=zh(e);g&&i(dr(g))},[e,i,n]);return!h&&!d&&!m&&!u&&!w&&!p?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[h&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]}):s.jsxs("span",{className:"conversation-meta-chip",title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),u&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]}):s.jsxs("span",{className:"conversation-meta-chip",title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]})),w&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),y&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Rf,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function IC({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:o,userName:a,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:h,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:w,onStopCli:p,cliViewMode:y,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:S,handleModalButton:v,handleRelaunch:g}){var L,P;const N=l.useRef(null),C=ct(e)&&!t,A=C&&y==="terminal",T=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),M=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 ${M} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:s.jsx(ji,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(TC,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[C&&y&&s.jsx(uh,{mode:y,onChange:k,compact:!0}),C&&p&&s.jsx("button",{onClick:()=>{p(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(At,{size:14})}),T&&w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(es,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ai,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(nl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:v,handleRelaunch:g,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:S,isFocusingAgent:u,actionLogs:o,userName:a})})]})}const fa={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 MC(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Yh(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[o,a]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(MC())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fa[i].cmd).catch(()=>{}),a(!0),setTimeout(()=>a(!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:()=>r("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:()=>r("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:fa[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fa[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:o?"✓":"📋"})]}),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 Jh({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{key:"chats",label:"Chats",icon:Zs}];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:r,label:o,icon:a})=>{const i=e===r;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(r),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(a,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function Pr({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 nn({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 Wn({icon:e,title:t,subtitle:n,children:r}){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}),r]})}function DC({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Le(),o=xt(e);return 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:r("mobileInbox.hideTitle",{title:o})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("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:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Lr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:h}){const{t:d}=Le(),m=t==="needs_attention"||t==="task_complete",f=t==="working",x=t==="earlier",w=t==="task_complete",{isReconnecting:p,isConnecting:y}=An(e.conversation),k=xt(e.conversation),b=vn(e.conversation),j=ih(e.conversation,{requiresAction:t==="needs_attention"}),S=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":x?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":x?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",g=x?"text-text-secondary":"text-text-primary",N=x?"text-text-muted":"text-text-secondary",C=x?"text-text-secondary opacity-80":"text-text-muted",A=x?"text-text-muted opacity-80":"text-text-muted",T=!f&&!w,M=oh(e.conversation),L="text-[color:var(--status-warning)]",P=B=>{if(!c)return;B.preventDefault(),B.stopPropagation();const K=c==null?void 0:c(e.conversation);Promise.resolve(K).catch(F=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",F)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${S}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?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 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(k)}),M&&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:B=>{B.preventDefault(),B.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:k}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(es,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:P,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 ${g}`,children:k})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(co,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${L} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):y?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,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:du(e.timestamp)}),w&&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:d("mobileInbox.done")}),h&&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 ${u?"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:B=>{B.preventDefault(),B.stopPropagation(),h()},"aria-label":u?d("mobileInbox.unmute",{title:k}):d("mobileInbox.mute",{title:k}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(Xd,{size:13}):s.jsx(Nn,{size:13})}),o&&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:B=>{B.preventDefault(),B.stopPropagation(),o()},"aria-label":d("mobileInbox.hideConversationAria",{title:k}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Ti,{size:13})}),a&&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:B=>{B.preventDefault(),B.stopPropagation(),a()},"aria-label":d("mobileInbox.stopSessionAria",{title:k}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(At,{size:13})})]})]})},e.conversation.tabKey)}function Fc({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 PC({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:h,onOpenConversation:d,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:x,onStopCli:w,onOpenNewSession:p,onOpenMachine:y,onOpenSettings:k,onSectionChange:b,wsStatus:j="connected",isStandalone:S=!1,onCollectChatDebugBundle:v,isConversationMuted:g,onToggleMuteConversation:N}){const{t:C}=Le(),[A,T]=l.useState(null),M=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",L=i.length>0,P=t.length>0||n.length>0||r.length>0||o.length>0,B=C(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),K=S?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=S?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",R=l.useCallback(async I=>{const $=Us(I);if(!$)return;const D=Array.isArray(I.messages)?I.messages:[],U=Wu({activeConv:I,visibleMessages:D,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:D.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Y=await h($,"get_chat_debug_bundle",{...Os(I),delivery:"daemon_file",frontendSnapshot:U}),ae=er(Y),z=Gu(ae),X=await Uu(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),pt.showToast(Ou(ae,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,h]),Q=v||R,E=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${K}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:B}),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(Nn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:k,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(So,{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] ${F}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?s.jsx(Wn,{icon:s.jsx(Fc,{}),title:C(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:C(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Wn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C(S?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:C(S?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!S&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Yh,{})})}):s.jsx(nn,{children:i.map((I,$)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(I.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(I.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:I.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?s.jsx("span",{className:"text-accent-primary",children:C("mobileInbox.newCount",{count:I.unread})}):I.total>0?C("mobileInbox.chatCount",{count:I.total}):C("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C("mobileInbox.chatCount",{count:I.total}),I.unread>0?C("mobileInbox.unreadSuffix",{count:I.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:C("mobileInbox.noActiveChats")})]})]},I.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(Pr,{title:C("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.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(Pr,{title:C("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(Pr,{title:C("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&s.jsx(Pr,{title:C("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?s.jsx(nn,{children:o.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:C("mobileInbox.allCaughtUp")}):M?s.jsx(Wn,{icon:s.jsx(Fc,{size:28}),title:C("mobileInbox.connecting"),subtitle:C("mobileInbox.connectingSubtitle")}):L?s.jsx(Wn,{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(Zs,{size:20})}),title:C("mobileInbox.noConversations"),subtitle:H0,children:p&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:p,"aria-label":Bs,title:Bs,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:Bs})]})}):s.jsx(Wn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:C("mobileInbox.noMachinesConnected"),subtitle:C("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&a.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(nn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:C("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:C("mobileInbox.collapsedCount",{count:a.length})})]}),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:C("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&p&&P&&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:p,"aria-label":Bs,title:Bs,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"})]})}),A&&s.jsx(DC,{conversation:A,onCancel:()=>T(null),onConfirm:E}),s.jsx(Jh,{section:e,onSectionChange:b})]})}function LC(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 Qh(e){const t=[e.workspace||"Workspace unknown"],n=Js(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=LC(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function rl({title:e,description:t,currentPath:n,directories:r,busy:o=!1,error:a="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:h}){const[d,m]=l.useState(n);l.useEffect(()=>{m(n)},[n]);const f=uC(n),x=d.trim();return 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(At,{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:()=>{!f||o||u(f)},disabled:!f||o,children:[s.jsx(ji,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!x||o||(w.preventDefault(),u(x))},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:()=>{!x||o||u(x)},disabled:!x||o,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):a?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):r.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:r.map(w=>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:()=>u(w.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(xn,{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:w.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:w.path})]})]},w.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:()=>h(x||n),disabled:!x&&!n||o,children:i})]})]})})}function Xh({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:h,argsValue:d,onArgsChange:m,showModelInput:f,modelValue:x,onModelChange:w,historyProviderNode:p,onConfirm:y,onCancel:k}){const{t:b}=Le("common"),j=i??b("machine.launchConfirm.launch"),S=c??b("machine.launchConfirm.launching"),v=r==null?void 0:r.find(g=>g.key===o);return 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:k,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(At,{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:[r&&r.length>0&&a&&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:o||"",onChange:g=>a(g.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:u,children:r.map(g=>s.jsx("option",{value:g.key,children:g.label},g.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),p,n.map(g=>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:g.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:g.value})]},`${g.label}:${g.value}`)),f&&w&&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:x||"",onChange:g=>w(g.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:u})]}),h&&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:d||"",onChange:g=>m(g.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:u})]})]}),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:k,disabled:u,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:y,disabled:u,children:[s.jsx(Qd,{size:14}),u?S:j]})]})]})})}function Hc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Zh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:o=!0}=e,a=[];o&&a.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])a.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Hc(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const i=(n==null?void 0:n.trim())||"",c=i?(t.workspaces||[]).find(u=>u.path===i):null;if(i&&!c&&a.push({key:`custom:${i}`,label:Hc(i),description:i,workspaceId:null,workspacePath:i}),r){const u=`saved:${r}`;if(a.some(h=>h.key===u))return{options:a,selectedKey:u}}return c?{options:a,selectedKey:`saved:${c.id}`}:i?{options:a,selectedKey:`custom:${i}`}:{options:a,selectedKey:"__home__"}}function RC(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function EC(e){return[RC(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function _C(e){return e.lastLaunchedAt?jo(e.lastLaunchedAt):""}function ep(e){return{metaText:EC(e),updatedLabel:_C(e)}}function ba(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function $C({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:o,onListSavedSessions:a}){var he,$e,Fe,Ie;const i=In(),[c,u]=l.useState(!1),h=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),m=e.defaultWorkspaceId||null,[f,x]=l.useState(m||(($e=d[0])==null?void 0:$e.id)||""),[w,p]=l.useState(""),[y,k]=l.useState(""),[b,j]=l.useState([]),[S,v]=l.useState(!1),[g,N]=l.useState(""),[C,A]=l.useState(!1),[T,M]=l.useState(ba(h,t.length,n.length)),L=l.useRef(null),[P,B]=l.useState(null),K=l.useRef("__home__"),[F,R]=l.useState("__home__"),[Q,E]=l.useState(""),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState([]),[z,X]=l.useState(()=>Ft().textQuery),[de,re]=l.useState(()=>Ft().workspaceQuery),[W,oe]=l.useState(()=>Ft().modelQuery),[V,ie]=l.useState(()=>Ft().resumableOnly),[ke,xe]=l.useState(()=>Ft().sortMode),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),Z=l.useRef(null),q=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const me=f==="__custom__"?w.trim():((Fe=d.find(ye=>ye.id===f))==null?void 0:Fe.path)||"",Te=f==="__custom__"&&!!me&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),_=f!=="__custom__"&&((Ie=d.find(ye=>ye.id===f))==null?void 0:Ie.path)||"",te=l.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),ve=l.useCallback(async ye=>{v(!0),N("");try{const Oe=await o(ye);k(Oe.path),p(Oe.path),j(Oe.directories)}catch(Oe){N(Oe instanceof Error?Oe.message:"Could not load folder")}finally{v(!1)}},[o]),ce=l.useCallback(()=>{var Oe;x("__custom__"),A(!0);const ye=tl(e.platform,el(w.trim(),_,te,e.defaultWorkspacePath,(Oe=d.find(ut=>ut.id===m))==null?void 0:Oe.path,d.map(ut=>ut.path)));ve(ye)},[w,m,ve,te,_,e.platform,d]),H=l.useCallback(ye=>{if(ye!=null&&ye.workspaceId){x(ye.workspaceId),p("");return}if(ye!=null&&ye.workspacePath){x("__custom__"),p(ye.workspacePath);return}x(""),p("")},[]),fe=l.useCallback(ye=>{if(x(ye),ye==="__custom__"){ce();return}p("")},[ce]),je=l.useCallback(ye=>{x("__custom__"),p(ye)},[]),Ce=l.useCallback((ye,Oe)=>{L.current=Oe,K.current=ye.selectedWorkspaceKey||"__home__",R(ye.selectedWorkspaceKey||"__home__"),E(ye.initialArgs||""),$(ye.initialModel||""),U(""),ae([]);const ut=ye.providerType?`${e.id}:${ye.providerType}`:null;if(z0(q.current,ut)){const at=Ft();X(at.textQuery),re(at.workspaceQuery),oe(at.modelQuery),ie(at.resumableOnly),xe(at.sortMode)}q.current=ut,B(ye),ye.providerType&&a&&(pe(!0),a(ye.providerType).then(at=>ae(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>pe(!1)))},[a,e.id]),Be=l.useMemo(()=>hh(Y,{textQuery:z,workspaceQuery:de,modelQuery:W,resumableOnly:V,sortMode:ke}),[W,V,Y,ke,z,de]);l.useEffect(()=>{D&&(Be.some(ye=>ye.providerSessionId===D)||U(""))},[Be,D]);const Xe=l.useCallback(()=>{L.current&&(O(!0),L.current().finally(()=>{L.current=null,O(!1),B(null)}))},[]),dt=l.useCallback(()=>{L.current=null,B(null)},[]),it=l.useCallback(ye=>{K.current=ye,R(ye)},[]);return l.useEffect(()=>{var ye;Z.current!==e.id&&(Z.current=e.id,x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"),p(""),k(""),j([]),N(""),A(!1),X(Ft().textQuery),re(Ft().workspaceQuery),oe(Ft().modelQuery),ie(Ft().resumableOnly),xe(Ft().sortMode),q.current=null,M(ba(h,t.length,n.length)))},[n.length,t.length,m,h,e.id,d]),l.useEffect(()=>{var ye;f!=="__custom__"&&(f&&d.some(Oe=>Oe.id===f)||x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{T==="ide"&&h||T==="cli"&&t.length>0||T==="acp"&&n.length>0||M(ba(h,t.length,n.length))},[T,n.length,t.length,h]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:h,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:w,browseCurrentPath:y,browseDirectories:b,browseBusy:S,browseError:g,browseDialogOpen:C,activeLauncherKind:T,launchConfirm:P,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:F,launchConfirmArgs:Q,launchConfirmModel:I,launchConfirmResumeId:D,launchConfirmSavedSessions:Y,launchConfirmTextFilter:z,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:W,launchConfirmResumableOnly:V,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:Be,launchConfirmSessionsLoading:Se,launchConfirmBusy:G,resolvedWorkspacePath:me,canCreateMissingWorkspace:Te,openBrowseDialog:ce,loadBrowsePath:ve,handleWorkspaceChoiceChange:fe,chooseCustomWorkspacePath:je,setCustomWorkspacePath:p,setBrowseDialogOpen:A,setActiveLauncherKind:M,openLaunchConfirm:Ce,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:H,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:U,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:re,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:ie,setLaunchConfirmSortMode:xe}}function BC({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:o,selectedMachineNeedsUpgrade:a,appVersion:i,machineAction:c,isStandalone:u,section:h,showBottomNav:d,onBack:m,onSectionChange:f,onOpenConversation:x,onOpenRecent:w,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const{t:g}=Le("common"),N=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),T=$C({selectedMachineEntry:e,cliProviders:r,acpProviders:o,machineAction:c,onBrowseDirectory:j,onListSavedSessions:v}),M=l.useMemo(()=>C.map(R=>{const{metaText:Q,updatedLabel:E}=ep(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:Q,updatedLabel:E,onClick:()=>{const{options:I,selectedKey:$}=Zh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace});T.openLaunchConfirm({title:R.kind==="ide"?uo(g,"restart-ide",R.label):R.providerSessionId?mh(g,R.label):uo(g,"start-fresh",R.label),description:R.kind==="ide"?ho(g,"restart-ide"):R.providerSessionId?fh(g):ho(g,"start-fresh"),confirmLabel:R.kind==="ide"?po(g,"restart-ide"):R.providerSessionId?oi(g,!0):po(g,"start-fresh"),busyLabel:R.kind==="ide"?mo(g,"restart-ide"):R.providerSessionId?ph(g,!0):mo(g,"start-fresh"),workspaceOptions:I,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const D=I.find(U=>U.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(D),await w({...R,workspace:(D==null?void 0:D.workspacePath)??null})})}}}),[T,w,C,g]),L=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:xt(R.conversation),secondary:w0(R.conversation,{timestampLabel:R.timestamp?du(R.timestamp):null}),unread:R.unread,onClick:()=>x(R.conversation)})),[x,A]),P=T.showAllRecent?M:M.slice(0,4),B=M.length>0,K=L.length>0,F=u?"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 ${F} 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(ji,{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:ts(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:[K&&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:L.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),B&&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:P.map(R=>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:R.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:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),M.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(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${M.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:[a&&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:y,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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(rl,{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:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Xh,{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?oi(g,!!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:zi(g)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.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:R=>T.setLaunchConfirmWorkspaceFilter(R.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:R=>T.setLaunchConfirmModelFilter(R.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:R=>T.setLaunchConfirmSortMode(R.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:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.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:Y0(g)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.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 R=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const Q=Qh(R);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:Q.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:Q.providerSessionId}),s.jsx("div",{className:"mt-1",children:Q.metaLine}),Q.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:Q.updatedLabel}),Q.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:Q.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(Jh,{section:h,onSectionChange:f})]})}const Wc=8e3;function FC(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,o=n&&t.mirrorStale===!0;return!r&&!o?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:o?"the coordinator did not confirm the change":"command was rejected"}}function tp(e,t,n){const r=l.useRef(new Map),[,o]=l.useState(0),a=l.useCallback(()=>o(x=>x+1),[]);l.useEffect(()=>{const x=r.current;if(x.size===0)return;const w=Date.now();let p=!1;for(const[y,k]of x){const b=e.get(y),j=k.muted===void 0||(b?b.muted===k.muted:!1),S=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),v=w-k.at>Wc;(j&&S||v)&&(x.delete(y),p=!0)}p&&a()},[e,a]),l.useEffect(()=>{if(r.current.size===0)return;const x=setInterval(()=>{const w=r.current,p=Date.now();let y=!1;for(const[k,b]of w)p-b.at>Wc&&(w.delete(k),y=!0);y&&a(),w.size===0&&clearInterval(x)},1e3);return()=>clearInterval(x)});const i=l.useCallback((x,w)=>{const p=r.current.get(x);r.current.set(x,{...p,...w,at:Date.now()}),a()},[a]),c=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.muted)!==void 0?p.muted:Ds(x,e).muted},[e]),u=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.hidden)!==void 0?p.hidden:Ds(x,e).surfaceHidden},[e]),h=l.useCallback((x,w)=>{const p=Ps(x),y=x.sessionId;!p||!y||(i(y,w),t(p,"set_conversation_prefs",{sessionId:y,...w,...Do(x)}).then(k=>{const b=FC(k);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(y),a(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(y),a();const b=k instanceof Error?k.message:String(k??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,a,n]),d=l.useCallback(x=>{h(x,{muted:!c(x)})},[h,c]),m=l.useCallback((x,w)=>{h(x,{hidden:w})},[h]),f=l.useCallback(x=>{h(x,{hidden:!u(x)})},[h,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function Yr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function HC(e,t=[]){const n=new Map(e.map(o=>[o.conversation.tabKey,o])),r=t.map(o=>n.get(o)).filter(o=>!!o);return r.length===e.length?r:Yr(e)}function WC(e){var r,o,a;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((o=e.p2p)!=null&&o.available)||!!((a=e.p2p)!=null&&a.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function OC(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:Js(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const o=ir(r)?"cli":pn(r)?"acp":"ide",a=Js(r.summaryMetadata);return{id:`${o}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:pn(r)&&r.cliName||r.type),kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:pn(r)?a||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function UC(e,t){const n=new Map;for(const r of t){const o=Ps(r.conversation),a=n.get(o);a?a.push(r):n.set(o,[r])}return e.map(r=>{const o=n.get(r.id)||[],a=[...o].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(a==null?void 0:a.conversation)||null,c=Xa(r),u=o.filter(m=>m.unread||m.requiresAction).length,h=WC(r),d=[r.platform||"machine",h].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:u,total:o.length,latestConversation:i,latestTimestamp:(a==null?void 0:a.timestamp)||0,fallbackActivityAt:c,preview:i?k0(i,Zu(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,o)=>{const a=r.latestTimestamp||r.fallbackActivityAt||0,i=o.latestTimestamp||o.fallbackActivityAt||0;return i!==a?i-a:r.label.localeCompare(o.label)})}function GC(e){return e==="chat"}function Rr(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 KC({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:w,setScreen:p,setSelectedMachineId:y,setSection:k,setMachineBackTarget:b,resetMachineAction:j}){const S=l.useRef(null),v=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ds(g,i),C=Math.max(Date.now(),qs(g),N.lastUpdated||0);Rr("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:xt(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:qs(g),readAt:C}),c(Ps(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:C,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:A})}).catch(A=>{Rr("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){GC(a)&&p("inbox"),w(((N=e[0])==null?void 0:N.tabKey)||null),S.current=null;return}if(a!=="chat"){S.current=null;return}const g=`${r.tabKey}:${r.sessionId||""}`;S.current!==g&&(S.current=g,v(r))},[e,v,a,r,p,w]),l.useEffect(()=>{if(!u)return;const g=e.find(N=>N.tabKey===u);g&&(w(g.tabKey),p("chat"),h==null||h())},[e,h,u,p,w]),l.useEffect(()=>{if(!d)return;const g=t.find(N=>N.id===d);g&&(y(g.id),j(),k("machines"),b("inbox"),p("machine"),m==null||m())},[t,m,d,j,b,p,k,y]),l.useEffect(()=>{f&&(k(f),p("inbox"),x==null||x())},[x,f,p,k]),l.useEffect(()=>{const g=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&Rr("inbox_state",{screen:a,selectedTabKey:o,items:g.map(N=>{const C=Ds(N.conversation,i);return{liveState:C,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:C.inboxBucket,computedBucket:N.inboxBucket,serverUnread:C.unread,computedUnread:N.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:qs(N.conversation)}})})},[n,i,a,o]),{markConversationRead:v}}function zC(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Oc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qC(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function VC({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:o}=ko(),[a,i]=l.useState("idle"),[c,u]=l.useState(""),[h,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(j,S,v)=>{var g;try{i("loading"),u(`Launching ${S}…`);const N={ideType:S,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(N.workspace=v.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),u(`${S} launch requested`)}catch(N){i("error"),u(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),x=l.useCallback(async(j,S,v)=>{if(S.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(j,"workspace_add",{path:S.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),u(g instanceof Error?g.message:"Could not save workspace")}},[e]),w=l.useCallback(async j=>{var S,v,g,N,C,A;try{i("loading"),u("Starting daemon upgrade…");const T=await e(j,"daemon_upgrade",{});if((S=T==null?void 0:T.result)!=null&&S.alreadyLatest){i("done"),u(`Already on v${((v=T==null?void 0:T.result)==null?void 0:v.version)||"latest"}.`);return}if((g=T==null?void 0:T.result)!=null&&g.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),u(`Upgrade to v${((C=T==null?void 0:T.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((A=T==null?void 0:T.result)==null?void 0:A.error)||"Upgrade failed")}catch(T){i("error"),u(T instanceof Error?T.message:"Upgrade failed")}},[e]),p=l.useCallback(async(j,S,v,g)=>{var A,T,M;const N=Date.now(),C={machineId:j,kind:S,providerType:v,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:N};try{i("loading"),u(`Launching ${v}…`),d(C);const L={cliType:v};(A=g==null?void 0:g.workspacePath)!=null&&A.trim()?L.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(L.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(L.resumeSessionId=g.resumeSessionId),(T=g==null?void 0:g.args)!=null&&T.trim()&&(L.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(M=g==null?void 0:g.model)!=null&&M.trim()&&(L.initialModel=g.model.trim());const P=await o(j,L),B=(P==null?void 0:P.result)||P,K=(B==null?void 0:B.sessionId)||(B==null?void 0:B.id);if(P!=null&&P.success&&K){d(null),i("done"),u(`${v} launched`),t(dr(K));return}if(P!=null&&P.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((P==null?void 0:P.error)||(B==null?void 0:B.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(qC(L)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[t,e]),y=l.useCallback(async(j,S)=>{try{const v=await e(j,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),k=l.useCallback(async(j,S)=>sl(e,j,S),[e]);l.useEffect(()=>{if(!h)return;const j=Oc(h.workspacePath),S=n.find(g=>{var L,P,B,K;if(!g||g.type==="adhdev-daemon"||zC(g.daemonId||g.id)!==h.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==h.kind||String(g.agentType||g.type||"")!==h.providerType)return!1;const T=String(g.providerSessionId||"");if(h.resumeSessionId&&T)return T===h.resumeSessionId;if(j){const F=Oc(g.workspace||g.runtimeWorkspaceLabel);return F?F===j:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(B=(P=(L=g.activeChat)==null?void 0:L.messages)==null?void 0:P.at)==null?void 0:B.call(P,-1))==null?void 0:K.timestamp)||0)>=h.startedAt-5e3});if(!S)return;const v=qh({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:r});v&&(d(null),i("done"),u(`${h.providerType} launched`),t(dr(v)))},[r,n,t,h]),l.useEffect(()=>{if(!h)return;const j=window.setTimeout(()=>{d(S=>!S||S.startedAt!==h.startedAt?S:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[h]);const b=l.useCallback(async(j,S)=>{if(S.kind==="ide"&&S.providerType){await f(j,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await p(j,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,p]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:p,handleListSavedSessions:y,handleBrowseDirectory:k,handleOpenRecent:b}}function YC({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:h}){const d=l.useCallback(k=>{a(k.tabKey),i("chat"),r(k)},[r,i,a]),m=l.useCallback(k=>{const b=e.find(j=>j.routeId===k.routeId&&j.streamSource==="native");b&&(a(b.tabKey),i("chat"),r(b))},[e,r,i,a]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),x=l.useCallback((k,b="inbox")=>{c(k),o(),u("machines"),h(b),i("machine")},[o,h,i,u,c]),w=l.useCallback(k=>{const b=Ps(k);b&&x(b,"chat")},[x]),p=l.useCallback(()=>{o(),i(n)},[n,o,i]),y=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:x,openConversationMachine:w,backFromMachine:p,changeMachineSection:y}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function JC(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function QC({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,onOpenHistory:w,onOpenRemote:p,onStopCli:y,wsStatus:k,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:S,onOpenMeshGraph:v,onOpenNewSession:g,liveSessionInboxState:N,setCliViewModeOverrides:C}){const[A,T]=l.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,L]=l.useState(()=>e[0]?"chat":"inbox"),[P,B]=l.useState("chats"),[K,F]=l.useState(null),[R,Q]=l.useState("inbox"),E=l.useRef([]),I=pr(),$="0.9.82",D=l.useMemo(()=>e.find(H=>H.tabKey===A)||e[0]||null,[e,A]),U=l.useMemo(()=>D?n.find(H=>H.id===D.routeId):void 0,[n,D]),Y=l.useMemo(()=>!D||lt(D)||!ct(D)?null:Tn(D),[D]),ae=l.useMemo(()=>n.filter(H=>H.type==="adhdev-daemon").sort(Ei),[n]),z=l.useMemo(()=>ae.find(H=>H.id===K)||null,[ae,K]),X=Po({sendDaemonCommand:o,activeConv:D||void 0,setActionLogs:a,isStandalone:i}),de=VC({sendDaemonCommand:o,navigate:I,ides:n,conversations:e}),re=Qw(e),W=l.useMemo(()=>e.map(H=>{const fe=M==="chat"&&(D==null?void 0:D.tabKey)===H.tabKey,je=No(H,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:fe}),Ce=qs(H),Be=Zu(H),Xe=ah(H,Be);return{conversation:H,timestamp:Ce,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,M,D,re]),{markConversationRead:oe}=KC({conversations:e,machineEntries:ae,items:W,selectedConversation:D,selectedTabKey:A,screen:M,liveSessionInboxState:N,sendDaemonCommand:o,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q,resetMachineAction:de.resetMachineAction}),V=YC({conversations:e,selectedConversation:D,machineBackTarget:R,markConversationRead:oe,resetMachineAction:de.resetMachineAction,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q}),{isMuted:ie,toggleMute:ke}=tp(N,o),xe=l.useMemo(()=>Yr(W.filter(H=>H.requiresAction&&!ie(H.conversation))),[W,ie]),Se=l.useMemo(()=>Yr(W.filter(H=>H.unread&&!H.requiresAction&&!ie(H.conversation))),[W,ie]),pe=l.useMemo(()=>HC(W.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking),E.current),[W]);l.useEffect(()=>{E.current=pe.map(H=>H.conversation.tabKey)},[pe]);const G=l.useMemo(()=>Yr(W.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[W]),O=l.useMemo(()=>z?W.filter(H=>Ps(H.conversation)===z.id):[],[W,z]),Z=l.useMemo(()=>OC(z,n),[n,z]),q=(z==null?void 0:z.version)||null,me=!!z&&!!q&&!0&&q!==$,Te=l.useMemo(()=>(z==null?void 0:z.availableProviders)||[],[z]),_=l.useMemo(()=>Te.filter(H=>Sn(H,"cli")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),te=l.useMemo(()=>Te.filter(H=>Sn(H,"acp")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),ve=l.useMemo(()=>UC(ae,W),[W,ae]),ce=l.useCallback(async H=>{z&&await de.handleOpenRecent(z.id,H)},[de,z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&D?s.jsx(IC,{selectedConversation:D,isAcp:lt(D),isStandalone:i,selectedIdeEntry:U,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:V.backFromConversation,onOpenNativeConversation:V.openNativeConversation,onOpenMachine:V.openConversationMachine,onOpenHistory:w,onOpenRemote:p,onOpenMeshGraph:v,onStopCli:y,cliViewMode:Y,onSetCliViewMode:async H=>{await Eh({conversation:D,mode:H,ides:n,sendDaemonCommand:o,setCliViewModeOverrides:C})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):M==="machine"&&z?s.jsx(BC,{selectedMachineEntry:z,selectedMachineConversations:O,selectedMachineRecentLaunches:Z,cliProviders:_,acpProviders:te,selectedMachineNeedsUpgrade:me,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:R==="inbox",onBack:V.backFromMachine,onSectionChange:V.changeMachineSection,onOpenConversation:V.openConversation,onOpenRecent:ce,onOpenMachineDetails:()=>I(`/machines/${z.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(z.id),onLaunchDetectedIde:(H,fe)=>de.handleLaunchDetectedIde(z.id,H,fe),onAddWorkspace:(H,fe)=>de.handleAddWorkspace(z.id,H,fe),onBrowseDirectory:H=>de.handleBrowseDirectory(z.id,H),onLaunchWorkspaceProvider:(H,fe,je)=>de.handleLaunchWorkspaceProvider(z.id,H,fe,je),onListSavedSessions:H=>de.handleListSavedSessions(z.id,H)}):s.jsx(PC,{section:P,attentionItems:xe,unreadItems:Se,workingItems:pe,completedItems:G,hiddenConversations:t,machineCards:ve,getAvatarText:JC,actionLogs:r,sendDaemonCommand:o,onOpenConversation:V.openConversation,onShowAllHidden:j,onHideConversation:S,onOpenMeshGraph:v,onStopCli:y,onOpenNewSession:g,onOpenMachine:V.openMachine,onOpenSettings:()=>I("/settings"),onSectionChange:B,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:ie,onToggleMuteConversation:ke})})}function ga(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function XC({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=l.useRef(0),[c,u]=l.useState(!1),[h,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(y=>{y.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),x=l.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!ga(t,n)){d("merge");return}const k=y.currentTarget.getBoundingClientRect(),b=y.clientX-k.left,j=k.width/3;b<j?d("split-left"):b>j*2?d("split-right"):d("merge")},[t,n]),w=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),p=l.useCallback(y=>{i.current=0,u(!1);const k=y.dataTransfer.getData("text/tab-key"),b=k?e.some(S=>S.tabKey===k):!1,j=h;if(d(null),a(),!!k){if(y.preventDefault(),j==="split-left"&&ga(t,n)){n==null||n(k,"split-left");return}if(j==="split-right"&&ga(t,n)){n==null||n(k,"split-right");return}if(b){o(k);return}r==null||r(k)}},[e,h,t,n,r,o,a]);return{dragOver:c,dropAction:h,resetDragState:m,handleDragEnter:f,handleDragOver:x,handleDragLeave:w,handleDrop:p}}function ZC(e,t){const n=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>n.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function e1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[h,d]=l.useState(null),m=l.useRef(null),f=l.useRef(null),x=l.useRef(r),w=l.useRef(o);l.useEffect(()=>{x.current=r},[r]),l.useEffect(()=>{w.current=o},[o]),l.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),l.useEffect(()=>{u(N=>{const C=ZC(N,e);return C.length===N.length&&C.every((A,T)=>A===N[T])?N:C})},[e]);const p=l.useMemo(()=>{const N=h??c;if(N.length===0)return e;const C=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const M=C.get(A.tabKey)??999,L=C.get(T.tabKey)??999;return M-L})},[e,h,c]);l.useEffect(()=>{var C,A;if(p.length===0){a!==null&&(i(null),(C=x.current)==null||C.call(x,null));return}if(a&&p.some(T=>T.tabKey===a))return;const N=p[0].tabKey;N!==a&&(i(N),(A=x.current)==null||A.call(x,N))},[p,a]);const y=l.useMemo(()=>p.find(N=>N.tabKey===a),[p,a]),k=l.useCallback(N=>{var C;i(N),(C=x.current)==null||C.call(x,N)},[]),b=l.useCallback((N,C,A)=>{u(T=>{var B;const M=T.filter(K=>K!==N),L=M.indexOf(C);if(L<0)return T;const P=A==="left"?L:L+1;return M.splice(P,0,N),(B=w.current)==null||B.call(w,M),M}),d(null)},[]),j=l.useCallback((N,C,A)=>{const M=(c.length>0?c:e.map(B=>B.tabKey)).filter(B=>B!==N),L=M.indexOf(C);if(L<0)return;const P=A==="left"?L:L+1;M.splice(P,0,N),m.current=M,d(M)},[c,e]),S=l.useCallback(()=>{var C;const N=m.current;N&&(u(N),(C=w.current)==null||C.call(w,N))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),g=l.useCallback(N=>{u(C=>{var T;const A=C.filter(M=>M!==N);return A.push(N),(T=w.current)==null||T.call(w,A),A})},[]);return{activeTabId:a,activeConv:y,sortedConversations:p,previewOrderRef:m,draggingTabRef:f,selectTab:k,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:g,setDraggingTabKey:N=>{f.current=N}}}function t1({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 ol({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a}){const{t:i}=Le("common");if(o)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,u=r&&!!a,h=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),d=i(r?"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:h}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),u&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:a,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Mi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(Yh,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const sp="adhdev-tab-shortcuts";function np(){try{return JSON.parse(localStorage.getItem(sp)||"{}")}catch{return{}}}function rp({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=l.useState(()=>np()),[c,u]=l.useState(null),h=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(o?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(o?"⌥":"Alt"),m.shiftKey&&f.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[o]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(sp,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const x=h(f);if(!x)return;const w={...a};for(const[p,y]of Object.entries(w))y===x&&delete w[p];w[c]=x,d(w),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,a,d,h]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[x,w]of Object.entries(a))if(t.includes(x)&&h(f)===w){f.preventDefault(),n(),r(x);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,a,t,n,r,h]),{isMac:o,tabShortcuts:a,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const xa=e=>{e.preventDefault()},s1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:h,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:x,onClearPreviewOrder:w,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:j,isGroupActive:S}){const v=An(t),g=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",N=v.isReconnecting,C=y0(t),A=v0(t),T=oh(t),M=l.useCallback(I=>{c.current=t.tabKey,y(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,c,y]),L=l.useCallback(()=>{c.current=null,y(null),x(),w(),p()},[c,y,x,w,p]),P=l.useCallback(I=>{const $=c.current;if(!(!$||$===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";m($,t.tabKey,U)}},[t.tabKey,c,m]),B=l.useCallback(I=>{I.preventDefault(),I.stopPropagation();const $=I.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";i.includes($)?f($,t.tabKey,U):k&&k($)}w()},[t.tabKey,i,f,k,w]),K=l.useCallback(I=>{I.stopPropagation(),u(),h(t.tabKey),d(t)},[t,d,u,h]),F=l.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(I=>{const $=I.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),Q=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",g,n&&"is-active",S&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:M,onDragEnd:L,onDragOver:P,onDrop:B,onClick:K,onContextMenu:F,onTouchStart:R,onTouchEnd:Q,onTouchMove:Q,style:{position:"relative",cursor:"pointer",opacity:r?.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(es,{size:11})}),o&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:Gs(t)}):v.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Gs(t)}),s.jsx(co,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${a}`,children:a})]})},(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 n1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onHideTab:p,isGroupActive:y,allowTabShortcuts:k=!0}){const[b,j]=l.useState(null),S=l.useRef(null),v=l.useRef(null),g=l.useMemo(()=>e.map(P=>P.tabKey),[e]);mr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:N,tabShortcuts:C,shortcutListening:A,setShortcutListening:T,saveShortcuts:M}=rp({enabled:k,sortedTabKeys:e.map(P=>P.tabKey),onFocus:a,onSelectTab:i});l.useEffect(()=>{if(!b)return;const P=B=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(B.target)||j(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),l.useEffect(()=>{const P=v.current;if(!P)return;const B=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),P.scrollLeft+=K.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const L=l.useCallback((P,B,K)=>{j({x:P,y:B,tabKey:K})},[]);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(P=>s.jsx(s1,{conv:P,isActive:t===P.tabKey,isDraggedTab:o.current===P.tabKey,isTaskCompleteUnread:r.has(P.tabKey),shortcut:k?C[P.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:L,longPressTimer:S,isGroupActive:y},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:b.x,top:b.y},children:[k&&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:xa,onClick:P=>{P.stopPropagation(),T(b.tabKey),j(null)},children:["⌨ ",C[b.tabKey]?`Change shortcut (${C[b.tabKey]})`:"Set shortcut"]}),C[b.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:xa,onClick:()=>{const P={...C};delete P[b.tabKey],M(P),j(null)},children:"✕ Remove shortcut"})]}),p&&s.jsxs(s.Fragment,{children:[k&&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:xa,onClick:()=>{p(b.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&A&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>T(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:P=>P.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:"Press Esc to cancel"})]})})]})}function r1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:h,onFocus:d,isSplitMode:m,numGroups:f,onMoveTab:x,onReceiveTab:w,style:p,onActiveTabChange:y,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:j,onHideTab:S,isFocused:v,allowTabShortcuts:g=!0,onOpenNewSession:N,liveSessionInboxState:C}){const{sendCommand:A}=yt(),T=l.useRef(null),{activeTabId:M,activeConv:L,sortedConversations:P,draggingTabRef:B,selectTab:K,handleTabReorder:F,updatePreviewOrder:R,commitPreviewOrder:Q,clearPreviewOrder:E,moveTabToEnd:I,setDraggingTabKey:$}=e1({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:y,onTabOrderChange:j}),D=Po({sendDaemonCommand:o,activeConv:L,setActionLogs:a,isStandalone:i}),{dragOver:U,dropAction:Y,resetDragState:ae,handleDragEnter:z,handleDragOver:X,handleDragLeave:de,handleDrop:re}=XC({conversations:e,numGroups:f,onMoveTab:x,onReceiveTab:w,onOwnTabDrop:I,onClearPreviewOrder:E}),W=L&&!lt(L)&&Tn(L)==="terminal",oe=l.useMemo(()=>L?t.find(xe=>xe.id===L.routeId):void 0,[t,L]),V=l.useMemo(()=>L?r.filter(xe=>xe.routeId===L.tabKey):[],[r,L]),ie=l.useMemo(()=>new Set(P.filter(xe=>Pb(xe,C,{isOpenConversation:xe.tabKey===M})).map(xe=>xe.tabKey)),[M,C,P]);mr("PaneGroup",{groupIndex:h,conversationCount:e.length,activeTabId:M,dragOver:U});const ke=l.useCallback(xe=>{xe.streamSource==="agent-stream"&&xe.agentType&&A(xe.routeId,Hu(),{agentType:xe.agentType,...xe.sessionId&&{targetSessionId:xe.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(n1,{conversations:P,activeTabId:M,groupIndex:h,numGroups:f,unreadTabKeys:ie,draggingTabRef:B,onFocus:d,onSelectTab:K,onConversationActivated:ke,onPreviewReorder:R,onReorderTab:F,onCommitPreviewOrder:Q,onClearPreviewOrder:E,onDragStateReset:ae,onDragTabKeyChange:$,onMoveTab:x,onReceiveTab:w,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:z,onDragOver:X,onDragLeave:de,onDrop:re,children:[U&&s.jsx(t1,{dropAction:Y,canSplit:!!(f<4&&x)}),L?s.jsx(nl,{activeConv:L,clearToken:n[L.tabKey]||0,isCliTerminal:!!W,ideEntry:oe,terminalRef:T,handleModalButton:D.handleModalButton,handleRelaunch:D.handleRelaunch,handleSendChat:D.handleSendChat,handleForceSendChat:D.handleForceSendChat,isSendingChat:D.isSendingChat,sendFeedbackMessage:D.sendFeedbackMessage,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:V,userName:u,isInputActive:!m||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function o1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,focusedGroup:x,focusGroup:w,moveTabToGroup:p,splitTabRelative:y,closeGroup:k,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:g,toggleHiddenTab:N,onOpenNewSession:C,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,L)=>{const P=t&&r.length===n?`${r[L]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&L>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:B=>b(L-1,B),onDoubleClick:()=>k(L),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(r1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:L,isFocused:t&&x===L,onFocus:()=>w(L),isSplitMode:t,numGroups:n,onMoveTab:(B,K)=>{K==="left"&&L>0?p(B,L-1):K==="right"&&L<n-1?p(B,L+1):K==="split-left"&&n<4?y(B,L,"left"):K==="split-right"&&n<4&&y(B,L,"right")},onReceiveTab:B=>p(B,L),onActiveTabChange:B=>S(L,B),initialActiveTabId:j[L],initialTabOrder:v[L],onTabOrderChange:B=>g(L,B),onHideTab:N,onOpenNewSession:C,allowTabShortcuts:A,liveSessionInboxState:T})]},L)})})}const op="adhdev-dashboard-action-shortcuts",a1=1200,i1=[["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 l1(){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 ap(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 mi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function yo(e){const t=Object.fromEntries(ap(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(op)||"{}"),r={...t,...n};for(const[o,a]of i1)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function ip(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function c1({enabled:e=!0,onTrigger:t}){const n=l1(),[r,o]=l.useState(()=>yo(n)),[a,i]=l.useState(null),[c,u]=l.useState([]),h=l.useRef({parts:[],timer:null}),d=l.useCallback(p=>{const y=[];return p.metaKey&&y.push(n?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(n?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(ip(p.key)),y.join("+"))},[n]),m=l.useCallback(p=>{o(p);try{localStorage.setItem(op,JSON.stringify(p))}catch{}},[]);l.useEffect(()=>{const p=yo(n),y=Object.entries(r),k=Object.entries(p);y.length===k.length&&y.every(([b,j])=>p[b]===j)||m(p)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current={parts:[],timer:null}},[]),x=l.useCallback(()=>{typeof window>"u"||(h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current.timer=window.setTimeout(()=>{h.current={parts:[],timer:null}},a1))},[]);l.useEffect(()=>{if(!a)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){i(null),u([]);return}const k=d(y);if(!k)return;const j=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&j){u([k]);return}const v=[...c,k].slice(0,2).join(" "),g={...r};for(const[N,C]of Object.entries(g))C===v&&delete g[N];g[a]=v,m(g),i(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[r,d,m,a,c]),l.useEffect(()=>{if(!e||a)return;const p=y=>{if(y.defaultPrevented)return;const k=d(y);if(!k)return;const b=y.metaKey||y.ctrlKey||y.altKey;if(mi(y.target))return;const j=h.current.parts,S=b?[k]:[...j.slice(-1),k].slice(-2),v=S.join(" "),g=S[S.length-1],N=Object.entries(r).filter(([,L])=>!!L),C=N.find(([,L])=>L===v);if(C){y.preventDefault(),f(),t(C[0]);return}if(N.some(([,L])=>L.startsWith(`${v} `))){y.preventDefault(),h.current.parts=S,x();return}const T=N.find(([,L])=>L===g);if(T){y.preventDefault(),f(),t(T[0]);return}if(N.some(([,L])=>L.startsWith(`${g} `))){y.preventDefault(),h.current.parts=[g],x();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,x,e,d,t,f,a]),l.useEffect(()=>()=>f(),[f]);const w=l.useMemo(()=>ap(n),[n]);return{isMac:n,actionDefinitions:w,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function d1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const o=[];return e?(t&&o.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),o.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?o.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):o.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),o.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&o.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),o.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),o}function lp(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Uc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!lp(r):!0}function u1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:lp(n)}const cp=1e3,h1=4;function Gc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Kc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function p1({detachDelayMs:e=cp,stillnessThresholdPx:t=h1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,u=null,h=null,d=!1;const m=()=>{h!=null&&(o(h),h=null)},f=()=>{m(),c=null},x=()=>{m(),a=null,i=null,c=null,u=null,d=!1},w=()=>{!a||!c||!u||d||h!=null||(h=r(()=>{h=null,!(!a||!c||!u||d)&&Gc(u,i)&&(Kc(c,u,t)||(d=!0,n({panelId:a,clientX:u.clientX,clientY:u.clientY})))},e))},p=k=>{if(!(!a||d)){if(!Gc(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Kc(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},w()}},y=k=>{!a||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{m(),a=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:x,isDragging:()=>a!=null,hasDetached:()=>d,dispose:x}}function m1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Jr(e){return xt(e)||e.tabKey}function f1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function zc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ya(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=o=>{if(o)try{o.focus({preventScroll:!0})}catch{try{o.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function va(e,t){e.classList.remove(Fa.className,Ha.className),e.classList.add(t==="light"?Fa.className:Ha.className)}function qc(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function b1(e,t,n){var i;const r=[t];let o;for(const c of r){let u;for(const h of c){const d=e.addPanel({id:h.tabKey,component:"conversation",title:Jr(h),params:{kind:"conversation",tabKey:h.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});u||(u=d.id)}o=u??o}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Vc(e,t){const n=new Set(t.map(o=>o.tabKey)),r=new Map;for(const o of t)r.set(o.tabKey,(r.get(o.tabKey)||0)+1);for(const o of[...e.panels])rs(o.id)||n.has(o.id)||e.removePanel(o);for(const o of t){const a=e.getPanel(o.tabKey);if(a){(r.get(o.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:o.tabKey,daemonId:o.daemonId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,panelId:a.id}),a.update({params:{tabKey:o.tabKey}}),a.title!==Jr(o)&&a.api.setTitle(Jr(o));continue}e.addPanel({id:o.tabKey,component:"conversation",title:Jr(o),params:{kind:"conversation",tabKey:o.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 Yc(e,t,n){var u,h;const r=n?f1(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const o=cs(t,n);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=ch(o);if(a){a.title!==i&&a.api.setTitle(i);return}const c=(o==null?void 0:o.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((h=e.panels.find(d=>!rs(d.id)))==null?void 0:h.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function dp({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[o,a]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?kt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>a(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&a(null)},[n]),l.useEffect(()=>{var d;return e?((d=kt.onStatus)==null?void 0:d.call(kt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{a(null)},[e,t]),l.useEffect(()=>{const h=e?kt.get(e):null;if(!(!h||n!=="connected"))return r!=="chat"&&t?h.startScreenshots(t):h.stopScreenshots(t),()=>{h.stopScreenshots(t)}},[r,n,t,e]);const u=l.useCallback(async(h,d)=>{const m=e?kt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(h,d,t)},[e,n,t]);return{connScreenshot:o,screenshotUsage:i,handleRemoteAction:u}}const up=l.createContext(null);function Eo(){const e=l.useContext(up);if(!e)throw new Error("DashboardDockviewContext missing");return e}function g1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(o=>o+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const o of r)o.dispose()}},[e.api,e.containerApi])}function x1({params:e}){var u;const t=Eo(),n=l.useMemo(()=>cs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(h=>h.id===e.routeId),[t.ides,e.routeId]),o=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:a,screenshotUsage:i,handleRemoteAction:c}=dp({doId:o,targetSessionId:n?Fu(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.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(iu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:a,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 y1(){const e=Eo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function v1(e){var b,j;g1(e);const t=Eo(),n=l.useCallback(S=>{"button"in S&&S.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),o=r==null?void 0:r.sessionId,a=l.useCallback(S=>t0(S),[]),i=l.useCallback(()=>e0(o),[o]),c=l.useSyncExternalStore(a,i,i);if(e.params.kind==="remote"){const S=cs([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(S==null?void 0:S.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:S!=null&&S.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:S.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)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 h=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,d=e.api.isGroupActive,m=No(u,t.liveSessionInboxState,{isOpenConversation:h}),f=m.isReconnecting,x=m.isConnecting,w=m.isGenerating||c,p=m.isWaiting,y=m.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:S=>{var v;S.preventDefault(),n(S),t.openTabContextMenu({x:S.clientX,y:S.clientY,tabKey:u.tabKey,sourceDocument:((v=S.target)==null?void 0:v.ownerDocument)??document})},children:[y&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:w?s.jsx("div",{className:"tab-spinner"}):p?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):x?s.jsx("div",{className:"tab-connecting-spinner"}):u.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:xt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(u)}):x?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(u)}):s.jsx("span",{children:Gs(u)})})]}),k&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:k,children:k})]})}function Er(e){return e.isActive}function Jc(e){return e.isVisible}function w1(e){e.preventDefault()}function k1({params:e,api:t}){var x;const n=Eo(),r=l.useRef(null),[o,a]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Jc(t)),u=n.conversationsByTabKey.get(e.tabKey),h=Po({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{a(Er(t)),c(Jc(t));const w=[t.onDidActiveChange(p=>a(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Er(t)&&!p.isActive){a(!1);return}a(Er(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of w)p.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(w=>w.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(w=>w.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!lt(u)&&Tn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(nl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:r,handleModalButton:h.handleModalButton,handleRelaunch:h.handleRelaunch,handleSendChat:h.handleSendChat,handleForceSendChat:h.handleForceSendChat,isSendingChat:h.isSendingChat,handleFocusAgent:h.handleFocusAgent,isFocusingAgent:h.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((x=n.scrollToBottomRequest)==null?void 0:x.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function S1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:h,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:x,onOpenNewSession:w,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:S,layoutProfile:v}){var ut,at,ht;const{theme:g}=Ls(),{sendCommand:N}=yt(),C=l.useRef(null),A=l.useRef(null),T=l.useRef(null),M=l.useRef(!1),L=l.useRef(!1),P=l.useRef(!1),B=l.useRef(null),K=l.useRef([]),[F,R]=l.useState(null),[Q,E]=l.useState(0),I=l.useRef(typeof window>"u"?{}:OS(v)),$=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),D=l.useMemo(()=>{const J=C.current;return J?J.groups.some(ee=>{try{const le=ee.model.location.type;return le!=="floating"&&le!=="popout"?!1:ee.panels.some(ue=>$.has(ue.id))}catch{return!1}}):!1},[$,Q,e]),U=l.useCallback(()=>{var J;(J=C.current)==null||J.focus()},[]),Y=l.useCallback((J,ee)=>{p==null||p(J,ee)},[p]),ae=l.useCallback(J=>{const ee=document,le=J.document;for(const Ne of ee.querySelectorAll('link[rel="stylesheet"]')){const He=le.createElement("link");He.rel="stylesheet",He.href=Ne.href,Ne.crossOrigin&&(He.crossOrigin=Ne.crossOrigin),le.head.appendChild(He)}for(const Ne of ee.querySelectorAll("style")){const He=le.createElement("style");He.textContent=Ne.textContent,le.head.appendChild(He)}const ue=[];for(const Ne of ee.styleSheets)try{for(const He of Ne.cssRules)He instanceof CSSStyleRule&&(He.selectorText===":root"||He.selectorText==="html")&&ue.push(He.cssText)}catch{}if(ue.length>0){const Ne=le.createElement("style");Ne.textContent=ue.join(`
71
+ `),le.head.appendChild(Ne)}const ge=ee.documentElement.getAttribute("data-theme");ge&&le.documentElement.setAttribute("data-theme",ge),le.documentElement.style.colorScheme=ge==="light"?"light":"dark",le.body.className=ee.body.className;const Ae=ee.documentElement.getAttribute("style");Ae&&le.documentElement.setAttribute("style",Ae);const Pe=le.getElementById("dv-popout-window");Pe instanceof HTMLElement&&(Pe.classList.add("adhdev-dockview"),va(Pe,g))},[g]),z=l.useCallback(()=>{var ee;const J=C.current;if(J)for(const le of J.groups)try{const ue=(ee=le.element)==null?void 0:ee.ownerDocument;if(!ue||ue===document)continue;const ge=ue.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),va(ge,g));const Ae=document.documentElement.getAttribute("data-theme");Ae&&ue.documentElement.setAttribute("data-theme",Ae),ue.documentElement.style.colorScheme=Ae==="light"?"light":"dark",ue.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe?ue.documentElement.setAttribute("style",Pe):ue.documentElement.removeAttribute("style")}catch{}},[g]),X=l.useCallback(J=>{const ee=C.current;if(!ee)return;const le=ee.getPanel(J);le&&ee.addPopoutGroup(le,{popoutUrl:"/popout.html",onDidOpen:({window:ue})=>{ae(ue),Se();const ge=$.get(J);ue.document.title=ge?`${xt(ge)} — ADHDev`:"ADHDev — Popout"}})},[$,ae]),de=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!ee||!le)return;const ue=ee.groups.filter(ge=>{var Ae;try{return((Ae=ge.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),re=l.useCallback(J=>{var ue;const ee=C.current;if(!ee)return!1;const le=ee.getPanel(J);if(!le)return!1;try{return((ue=le.group.element)==null?void 0:ue.ownerDocument)!==document}catch{return!1}},[]),W=l.useCallback(J=>{re(J)&&de(J),d(J)},[re,de,d]),oe=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);!ee||!le||ee.addFloatingGroup(le,{width:600,height:500})},[]),V=l.useCallback(J=>{var le;const ee=(le=C.current)==null?void 0:le.getPanel(J);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),ie=l.useCallback(()=>{var ee,le;const J=(le=(ee=C.current)==null?void 0:ee.activePanel)==null?void 0:le.id;return!J||rs(J)?null:$.has(J)?J:null},[$]),ke=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!ee||!le)return;const ue=ee.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),xe=l.useCallback(()=>{var Ae;const J=C.current;if(!J)return;const le=J.groups.filter(Pe=>{var Ne;try{return((Ne=Pe.element)==null?void 0:Ne.ownerDocument)===document&&Pe.model.location.type==="grid"}catch{return!1}})[0]||null,ue=[...J.panels];for(const Pe of ue){const Ne=(Ae=Pe.group.element)==null?void 0:Ae.ownerDocument,He=Pe.group.model.location.type;Ne===document&&He==="grid"||(le&&le.id!==Pe.group.id?Pe.api.moveTo({group:le,position:"center"}):Pe.api.moveTo({position:"center"}))}const ge=J.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),ya(document)},[]),Se=l.useCallback(()=>{var ee,le;const J=C.current;if(J)for(const ue of J.groups){const ge=(ee=ue.element)==null?void 0:ee.ownerDocument;if(!ge||ge===document)continue;const Ae=ge.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let Pe=null,Ne=ge.title||"ADHDev",He="Popout workspace";const Ke=ue.activePanel;if(Ke)if(Pe=Ke.id,rs(Ke.id)){const se=((le=Ke.params)==null?void 0:le.routeId)||Ke.id.slice(7),be=cs([...$.values()],se);Ne=ch(be),He=be!=null&&be.machineName?`Remote view · ${be.machineName}`:"Remote view"}else{const se=$.get(Ke.id);Ne=se?xt(se):Ke.title||Ke.id,He=se?Gs(se):"Dockview panel"}ge.title=`${Ne} — ADHDev`;const Ze=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const se of Ze)se.remove();const _e=ge.createElement("div");_e.id="adhdev-popout-header",ge.body.appendChild(_e),_e.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(";")),_e.innerHTML=`
72
72
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
73
73
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
74
74
  <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zc(Ne)}</div>
@@ -78,22 +78,22 @@ Use this if you want to permanently remove a machine.`,confirmLabel:a("machine.c
78
78
  <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
79
79
  <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
80
80
  </div>
81
- `,Ae.style.top="52px",Ae.style.height="calc(100% - 52px)";const Ge=_e.querySelector("[data-adhdev-popout-focus]");Ge&&(Ge.onclick=()=>{window.focus()});const et=_e.querySelector("[data-adhdev-popout-dock]");et&&(et.disabled=!Pe,et.style.opacity=Pe?"1":"0.5",et.style.cursor=Pe?"pointer":"default",et.onclick=()=>{var ee;Pe&&de(Pe),(ee=ge.defaultView)==null||ee.focus()})}},[$,de]),pe=l.useCallback(J=>{var ue;const te=C.current,le=te==null?void 0:te.getPanel(J);if(!(!te||!le)){le.group.model.openPanel(le),le.api.setActive(),Y(J,"dockview-shortcut");try{const ge=le.group.model.location;ge.type==="popout"?ge.getWindow().focus():ya((ue=le.group.element)==null?void 0:ue.ownerDocument)}catch{}}},[Y]),G=l.useCallback(J=>{const te=C.current,le=te==null?void 0:te.activePanel,ue=(te==null?void 0:te.activeGroup)||(le==null?void 0:le.group);if(!te||!le||!ue)return;const ge=ue.panels||[];if(ge.length<=1)return;const Ae=ge.findIndex(He=>He.id===le.id);if(Ae<0)return;const Pe=(Ae+J+ge.length)%ge.length,Ne=ge[Pe];Ne&&(Ne.group.model.openPanel(Ne),Ne.api.setActive(),rs(Ne.id)||Y(Ne.id,"dockview-shortcut"))},[Y]),O=l.useCallback(J=>{var Ge;const te=C.current,le=(te==null?void 0:te.activeGroup)||((Ge=te==null?void 0:te.activePanel)==null?void 0:Ge.group);if(!te||!le)return;const ue=te.groups||[],ge=ue.find(et=>et.id===le.id);if(!ge)return;const Ae=ge.element.getBoundingClientRect(),Pe=Ae.left+Ae.width/2,Ne=Ae.top+Ae.height/2,He=(et,ee,be,we)=>Math.max(0,Math.min(ee,we)-Math.max(et,be)),Ue=et=>{const ee=et.element.getBoundingClientRect(),be=ee.left+ee.width/2,we=ee.top+ee.height/2;let ze=0,We=0,tt=0,qe=!1;if(J==="left"?(qe=be<Pe,ze=Math.max(0,Ae.left-ee.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,ee.top,ee.bottom)):J==="right"?(qe=be>Pe,ze=Math.max(0,ee.left-Ae.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,ee.top,ee.bottom)):J==="above"?(qe=we<Ne,ze=Math.max(0,Ae.top-ee.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,ee.left,ee.right)):(qe=we>Ne,ze=Math.max(0,ee.top-Ae.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,ee.left,ee.right)),!qe)return Number.POSITIVE_INFINITY;const Ye=tt>0?0:120;return ze*3+We+Ye};let Ze=null,_e=Number.POSITIVE_INFINITY;for(const et of ue){if(et.id===ge.id)continue;const ee=Ue(et);Number.isFinite(ee)&&(ee>=_e||(_e=ee,Ze=et))}return Ze||void 0},[]),Z=l.useCallback(J=>{var ue;const te=O(J);if(!te)return;const le=te.activePanel||te.panels[0];le&&(te.model.openPanel(le),le.api.setActive(),rs(le.id)||Y(le.id,"dockview-focus"),ya((ue=te.element)==null?void 0:ue.ownerDocument))},[O,Y]),q=l.useCallback((J,te)=>{const le=C.current,ue=le==null?void 0:le.activePanel,ge=(le==null?void 0:le.activeGroup)||(ue==null?void 0:ue.group);if(!le||!ue||!ge)return;let Ae=O(J);!Ae&&(te!=null&&te.createGroupIfMissing)&&(Ae=le.addGroup({referenceGroup:ge,direction:J})),Ae&&(ue.api.moveTo({group:Ae,position:"center"}),ue.group.model.openPanel(ue),ue.api.setActive(),rs(ue.id)||Y(ue.id,te!=null&&te.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,Y]),{isMac:me,tabShortcuts:Te,shortcutListening:_,setShortcutListening:se,saveShortcuts:ve}=rp({sortedTabKeys:e.map(J=>J.tabKey),onFocus:U,onSelectTab:pe}),ce=l.useCallback(()=>{var le;const J=C.current;if(!J)return;const te=J.activePanel;if(te){if(rs(te.id)){const ue=((le=te.params)==null?void 0:le.routeId)||te.id.slice(7),ge=cs(e,ue);ge!=null&&ge.tabKey&&se(ge.tabKey);return}$.has(te.id)&&se(te.id)}},[$,pe,se,e]),H=l.useCallback(J=>{const te=[];return J.metaKey&&te.push(me?"⌘":"Meta"),J.ctrlKey&&te.push("Ctrl"),J.altKey&&te.push(me?"⌥":"Alt"),J.shiftKey&&J.key.length!==1&&te.push(me?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(J.key)?null:(te.push(ip(J.key)),te.join("+"))},[me]),fe=l.useCallback(J=>{var te,le;switch(J){case"splitActiveTabRight":q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ue=ie();ue&&oe(ue);return}case"popoutActiveTab":{const ue=ie();ue&&X(ue);return}case"dockActiveTab":{const ue=ie();if(!ue)return;re(ue)?de(ue):V(ue)&&ke(ue);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":q("left");return;case"moveActiveTabToRightPane":q("right");return;case"moveActiveTabToUpPane":q("above");return;case"moveActiveTabToDownPane":q("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":ce();return;case"hideCurrentTab":{const ue=(le=(te=C.current)==null?void 0:te.activePanel)==null?void 0:le.id;ue&&!rs(ue)&&W(ue);return}default:return}},[G,ke,Z,oe,ie,W,V,re,de,q,X,ce]);l.useEffect(()=>{if(!F)return;const J=F.sourceDocument,te=J.defaultView??window,le=ue=>{const ge=J.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(ue.target)||R(null)};return te.addEventListener("mousedown",le,!0),te!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{te.removeEventListener("mousedown",le,!0),te!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[F]);const je=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:D,ides:n,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:w,liveSessionInboxState:S,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:W,userName:h,scrollToBottomRequest:j,tabShortcuts:Te,openTabContextMenu:({x:J,y:te,tabKey:le,sourceDocument:ue})=>R({x:J,y:te,tabKey:le,sourceDocument:ue??document}),popoutTab:X,moveTabBackToMain:de,isTabInPopout:re,floatTab:oe,isTabFloating:V}),[r,t,$,D,n,i,c,w,S,o,a,W,h,j,Te,X,de,re,oe,V]),Ce=F?d1({isTabInPopout:re(F.tabKey),isTabFloating:V(F.tabKey),tabShortcut:Te[F.tabKey],actionShortcuts:m}):[],Be=l.useCallback(J=>{var ue;const te=C.current;if((((ue=te==null?void 0:te.activePanel)==null?void 0:ue.id)??null)===J.id){J.group.model.openPanel(J);return}J.group.model.openPanel(J),J.api.setActive()},[]),Xe=l.useCallback((J,te="requested-tab")=>{if(!J)return!1;const le=C.current;if(!le)return!1;const ue=le.getPanel(J);return ue?(Be(ue),Y(J,te),b==null||b(),!0):!1},[Be,b,Y]),dt=l.useCallback(()=>{if(P.current)return!1;const J=Xe(B.current,"stored-layout-restore");return J&&(P.current=!0),J},[Xe]),it=l.useCallback(()=>{var te;const J=C.current;J&&WS(v,{activeTabId:((te=J.activePanel)==null?void 0:te.id)??null,layout:J.toJSON()})},[v]),he=l.useCallback(()=>{US(v,I.current)},[v]),$e=l.useCallback(J=>{var ue,ge,Ae,Pe;const te=C.current;if(!te)return{kind:"grid"};const le=te.toJSON();for(const Ne of le.floatingGroups||[])if((ge=(ue=Ne.data)==null?void 0:ue.views)!=null&&ge.includes(J)&&Ne.position)return{kind:"floating",position:Ne.position};for(const Ne of le.popoutGroups||[])if((Pe=(Ae=Ne.data)==null?void 0:Ae.views)!=null&&Pe.includes(J))return{kind:"popout",position:Ne.position,popoutUrl:Ne.url};return{kind:"grid"}},[]),Fe=l.useCallback(J=>{const te=C.current;if(!te)return;const le=te.getPanel(J),ue=I.current[J];if(!le||!ue||ue.kind==="grid")return;if(le.group.model.location.type===ue.kind){delete I.current[J],he();return}if(ue.kind==="floating"){te.addFloatingGroup(le,{x:ue.position.left??24,y:ue.position.top??24,width:ue.position.width,height:ue.position.height}),delete I.current[J],he();return}delete I.current[J],he()},[he]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:ce,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:pe,resetAllPanelsToMain:xe,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const J=ie();J&&oe(J)},popoutActiveTab:()=>{const J=ie();J&&X(J)},dockActiveTab:()=>{const J=ie();J&&(re(J)?de(J):V(J)&&ke(J))},splitActiveTabRight:()=>q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>q("left"),moveActiveTabToRightPane:()=>q("right"),moveActiveTabToUpPane:()=>q("above"),moveActiveTabToDownPane:()=>q("below")}),()=>f==null?void 0:f(null)),[G,ke,oe,Z,ie,V,re,q,de,X,f,xe,Fe,pe,ce]),l.useEffect(()=>()=>{var J;(J=T.current)==null||J.call(T),T.current=null},[]);const Ie=l.useCallback(J=>{var le,ue;C.current=J.api,(le=T.current)==null||le.call(T),T.current=null;const te=HS(v);if(B.current=(te==null?void 0:te.activeTabId)??null,te!=null&&te.layout&&J.api.fromJSON(te.layout,{reuseExistingPanels:!1}),L.current=Uc({hasStoredLayout:!!(te!=null&&te.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:n}),L.current||(Vc(J.api,e),Yc(J.api,e,k)),J.api.totalPanels===0&&e.length>0){const ge=b1(J.api,e,y);if(ge){const Ae=J.api.getPanel(ge);Ae&&Be(Ae)}}else!L.current&&!Xe(y)&&dt();if(M.current=!0,J.api.onDidActivePanelChange(ge=>{var Pe;if(B.current=(ge==null?void 0:ge.id)??null,P.current=!0,Se(),ge&&rs(ge.id)){const Ne=((Pe=ge.params)==null?void 0:Pe.routeId)||ge.id.slice(7),He=cs(e,Ne);x((He==null?void 0:He.tabKey)??null),it();return}if(x((ge==null?void 0:ge.id)??null),it(),!ge)return;const Ae=$.get(ge.id);(Ae==null?void 0:Ae.streamSource)==="agent-stream"&&Ae.agentType&&N(Ae.routeId,Hu(),{agentType:Ae.agentType,...Ae.sessionId&&{targetSessionId:Ae.sessionId}}).catch(()=>{})}),J.api.onDidLayoutChange(()=>{it(),Se(),E(ge=>ge+1)}),m1()){const ge=_e=>({clientX:_e.clientX,clientY:_e.clientY}),Ae=_e=>{const Ge=_e==null?void 0:_e.getBoundingClientRect();return Ge?{left:Ge.left,right:Ge.right,top:Ge.top,bottom:Ge.bottom}:null},Pe=_e=>{var et;const Ge=(et=A.current)==null?void 0:et.getBoundingClientRect();return Ge?_e.clientX<Ge.left||_e.clientX>Ge.right||_e.clientY<Ge.top||_e.clientY>Ge.bottom:!1},Ne=p1({detachDelayMs:cp,onDetach:({panelId:_e,clientX:Ge,clientY:et})=>{var tt,qe;const ee=J.api.getPanel(_e);if(!ee)return;try{if(ee.group.model.location.type!=="grid")return}catch{return}const be=(tt=A.current)==null?void 0:tt.getBoundingClientRect(),we=(qe=ee.group.element)==null?void 0:qe.getBoundingClientRect(),ze=Math.round(Math.min(Math.max((we==null?void 0:we.width)??600,360),720)),We=Math.round(Math.min(Math.max((we==null?void 0:we.height)??500,260),640));J.api.addFloatingGroup(ee,{x:be?Math.max(0,Ge-be.left-32):void 0,y:be?Math.max(0,et-be.top-18):void 0,width:ze,height:We}),ee.api.setActive(),it(),Se(),E(Ye=>Ye+1)}}),He=[J.api.onWillDragPanel(_e=>{if(!(_e.nativeEvent.defaultPrevented||_e.nativeEvent.shiftKey)){try{if(_e.panel.group.model.location.type!=="grid")return}catch{return}Ne.startDrag({panelId:_e.panel.id,selfPanelBounds:Ae(_e.panel.group.element),...ge(_e.nativeEvent)})}}),J.api.onWillShowOverlay(_e=>{if(Ne.hasDetached()){_e.preventDefault();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onWillDrop(_e=>{if(Ne.hasDetached()){_e.preventDefault(),Ne.endDrag();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onDidDrop(()=>Ne.endDrag()),J.api.onUnhandledDragOverEvent(_e=>{Ne.isDragging()&&Ne.markSelfPanel(ge(_e.nativeEvent))})],Ue=_e=>{if(!Ne.isDragging())return;const Ge=ge(_e);Pe(Ge)&&Ne.markNonSelfPanel(Ge)},Ze=()=>Ne.endDrag();window.addEventListener("dragover",Ue,!0),window.addEventListener("drop",Ze,!0),window.addEventListener("dragend",Ze,!0),T.current=()=>{Ne.dispose();for(const _e of He)_e.dispose();window.removeEventListener("dragover",Ue,!0),window.removeEventListener("drop",Ze,!0),window.removeEventListener("dragend",Ze,!0)}}J.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var Ae,Pe;try{const Ne=(Ae=ge.element)==null?void 0:Ae.ownerDocument;if(!Ne||Ne===document)return;(Pe=Ne.getElementById("dv-popout-window"))==null||Pe.classList.add("adhdev-dockview");const He=document.documentElement.getAttribute("data-theme");He&&Ne.documentElement.setAttribute("data-theme",He),Ne.body.className=document.body.className;const Ue=document.documentElement.getAttribute("style");Ue&&Ne.documentElement.setAttribute("style",Ue)}catch{}Se(),E(Ne=>Ne+1)})}),x(((ue=J.api.activePanel)==null?void 0:ue.id)??null)},[Be,Xe,$,n,u,v,x,it,y,k,N,Se,e]);l.useLayoutEffect(()=>{const J=C.current;if(!J||!M.current||L.current&&Uc({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:n}))return;L.current&&(L.current=!1);const te=K.current,le=new Set(te),ue=e.map(Ze=>Ze.tabKey),ge=new Set(ue),Ae=u1({previousVisibleConversationCount:te.length,visibleConversationCount:e.length,ides:n});let Pe=!1;for(const Ze of te)ge.has(Ze)||Ae||(I.current[Ze]=$e(Ze),Pe=!0);Pe&&he(),Ae||(Vc(J,e),Yc(J,e,k));const Ne=ue.filter(Ze=>!le.has(Ze));let He=!1;for(const Ze of Ne){const _e=J.getPanel(Ze),Ge=I.current[Ze];if(!_e||!Ge||Ge.kind==="grid")continue;if(_e.group.model.location.type===Ge.kind){delete I.current[Ze],He=!0;continue}if(Ge.kind==="floating"){J.addFloatingGroup(_e,{x:Ge.position.left??24,y:Ge.position.top??24,width:Ge.position.width,height:Ge.position.height}),delete I.current[Ze],He=!0;continue}}if(He&&he(),K.current=ue,y&&Xe(y))return;!J.activePanel&&J.panels[0]&&Be(J.panels[0]),!!(J.activePanel&&J.getPanel(J.activePanel.id))||dt()},[Be,Xe,dt,n,u,he,$e,y,k,e]),l.useEffect(()=>{M.current&&Xe(y)},[Xe,y]),l.useEffect(()=>{const J=le=>{const ue=le.target;if(!ue)return;const ge=ue.querySelector("[data-tab-key]")||ue.closest("[data-tab-key]");if(ge){const Ae=ge.getAttribute("data-tab-key");if(Ae&&le.dataTransfer){const Pe=ue.closest(".dv-tab")||ge.closest(".dv-tab")||ge;le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/tab-key",Ae),Pe instanceof HTMLElement&&le.dataTransfer.setDragImage(Pe,Math.max(12,Math.round(Pe.clientWidth/2)),Math.max(10,Math.round(Pe.clientHeight/2)))}}};window.addEventListener("dragstart",J);const te=qc(C.current);for(const le of te)le.addEventListener("dragstart",J);return()=>{window.removeEventListener("dragstart",J);for(const le of te)le.removeEventListener("dragstart",J)}},[Q]),l.useEffect(()=>{var te;const J=(te=A.current)==null?void 0:te.querySelector(".adhdev-dockview");J instanceof HTMLElement&&va(J,g),z(),Se()},[Se,z,g]),l.useEffect(()=>{Se()},[Se]),l.useEffect(()=>{const J=te=>{if(te.defaultPrevented||_)return;const le=H(te);if(!le)return;const ue=te.metaKey||te.ctrlKey||te.altKey;mi(te.target)&&!ue||yo(me).setActiveTabShortcut!==le||(te.preventDefault(),te.stopPropagation(),ce())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[H,me,_,ce]),l.useEffect(()=>{const J=A.current;if(!J)return;const te=le=>{var Ne,He;if(!le.isTrusted)return;const ue=(He=(Ne=le.target)==null?void 0:Ne.closest)==null?void 0:He.call(Ne,".dv-scrollable");if(!ue)return;le.preventDefault(),le.stopPropagation();const ge=Math.abs(le.deltaX),Ae=Math.abs(le.deltaY),Pe=ge>Ae?le.deltaX:le.deltaY;ue.dispatchEvent(new WheelEvent("wheel",{deltaY:Pe,deltaMode:le.deltaMode,bubbles:!1,cancelable:!0}))};return J.addEventListener("wheel",te,{passive:!1,capture:!0}),()=>J.removeEventListener("wheel",te,{capture:!0})},[]),l.useEffect(()=>{const J=qc(C.current);if(J.length===0)return;const te=J.map(le=>{let ue=[],ge=null;const Ae=()=>{ge!=null&&le.clearTimeout(ge),ge=null,ue=[]},Pe=()=>{ge!=null&&le.clearTimeout(ge),ge=le.setTimeout(()=>{ge=null,ue=[]},1200)},Ne=Ue=>{if(!Ue.ctrlKey&&!Ue.metaKey&&!Ue.altKey)return;const Ze=H(Ue);if(!Ze)return;const _e=np();for(const[Ge,et]of Object.entries(_e))if(e.some(ee=>ee.tabKey===Ge)&&et===Ze){Ue.preventDefault(),pe(Ge);return}},He=Ue=>{if(Ue.defaultPrevented||_)return;const Ze=H(Ue);if(!Ze)return;const _e=Ue.metaKey||Ue.ctrlKey||Ue.altKey;if(mi(Ue.target))return;const Ge=yo(me),et=Object.entries(Ge).filter(([Ye,Tt])=>!!Tt&&(Ye==="splitActiveTabRight"||Ye==="splitActiveTabDown"||Ye==="floatActiveTab"||Ye==="popoutActiveTab"||Ye==="dockActiveTab"||Ye==="focusLeftPane"||Ye==="focusRightPane"||Ye==="focusUpPane"||Ye==="focusDownPane"||Ye==="moveActiveTabToLeftPane"||Ye==="moveActiveTabToRightPane"||Ye==="moveActiveTabToUpPane"||Ye==="moveActiveTabToDownPane"||Ye==="selectPreviousGroupTab"||Ye==="selectNextGroupTab"||Ye==="setActiveTabShortcut"||Ye==="hideCurrentTab")),ee=_e?[Ze]:[...ue.slice(-1),Ze].slice(-2),be=ee.join(" "),we=ee[ee.length-1],ze=et.find(([,Ye])=>Ye===be);if(ze){Ue.preventDefault(),Ae(),fe(ze[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${be} `))){Ue.preventDefault(),ue=ee,Pe();return}const tt=et.find(([,Ye])=>Ye===we);if(tt){Ue.preventDefault(),Ae(),fe(tt[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${we} `))){Ue.preventDefault(),ue=[we],Pe();return}Ae()};return le.addEventListener("keydown",Ne),le.addEventListener("keydown",He),()=>{Ae(),le.removeEventListener("keydown",Ne),le.removeEventListener("keydown",He)}});return()=>{for(const le of te)le()}},[H,me,Q,pe,_,fe,e]);const ye=g==="light"?Fa:Ha,Oe=((ht=(at=(ut=C.current)==null?void 0:ut.activePanel)==null?void 0:at.group.element)==null?void 0:ht.ownerDocument)??document;return s.jsxs(up.Provider,{value:je,children:[s.jsx("div",{ref:A,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(jm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:k1,remote:x1},defaultTabComponent:v1,watermarkComponent:y1,onReady:Ie,singleTabMode:"default",tabAnimation:"smooth",theme:ye,popoutUrl:"/popout.html"})}),F&&fn.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:F.x,top:F.y},children:Ce.map(J=>{if(J.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},J.id);let te=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{};switch(J.id){case"dockInWindow":case"dockBackToGrid":te=s.jsx(Qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ke(F.tabKey),R(null)};break;case"moveBackToMain":te=s.jsx(Vf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{de(F.tabKey),R(null)};break;case"floatAsPanel":te=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{oe(F.tabKey),R(null)};break;case"openInNewWindow":te=s.jsx(qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{X(F.tabKey),R(null)};break;case"setShortcut":le=ue=>{ue.stopPropagation(),se(F.tabKey),R(null)};break;case"removeShortcut":te=s.jsx(At,{size:13,className:"shrink-0 opacity-70"}),le=()=>{const ue={...Te};delete ue[F.tabKey],ve(ue),R(null)};break;case"hideTab":te=s.jsx(Ti,{size:13,className:"shrink-0 opacity-70"}),le=()=>{W(F.tabKey),R(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${J.tone==="muted"?"text-text-muted":""}`,onMouseDown:w1,onClick:le,children:[te,s.jsx("span",{className:"flex-1 min-w-0",children:J.label}),J.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:J.shortcut}):null]},J.id)})}),F.sourceDocument.body),_&&fn.createPortal(s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>se(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:J=>J.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. ",me?"⌘+1":"Ctrl+1",", ",me?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Oe.body)]})}const hp="adhdev-recent-launch-args-v1",C1=8;function j1(e){return String(e||"").trim().replace(/\s+/g," ")}function pp(e,t){return`${e.trim()}::${t.trim()}`}function mp(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(hp)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function N1(e){if(!(typeof window>"u"))try{window.localStorage.setItem(hp,JSON.stringify(e))}catch{}}function A1(e,t){var a;const n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?[]:((a=mp().byKey[pp(n,r)])==null?void 0:a.items)||[]}function T1(e,t,n){var d;const r=String(e||"").trim(),o=String(t||"").trim(),a=j1(n);if(!r||!o||!a)return;const i=mp(),c=pp(r,o),u=((d=i.byKey[c])==null?void 0:d.items)||[],h=[a,...u.filter(m=>m!==a)].slice(0,C1);i.byKey[c]={items:h},N1(i)}function I1(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vn({title:e,description:t,action:n,children:r,className:o="",contentClassName:a=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),n?s.jsx("div",{className:"flex items-center gap-2",children:n}):null]}),r?s.jsx("div",{className:t||n?`mt-3 ${a}`.trim():a,children:r}):null]})}function M1({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:n=0}){return e?"Refreshing saved history…":t?n>0?`${n} saved ${n===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function D1({busy:e,savedSessionsLoading:t,savedSessionsError:n,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const{t:h}=Le("common"),d=a?Qh(a):null,m=M1({savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o});return s.jsxs(Vn,{title:"Saved history",description:zi(h),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Q0(h)})]}),children:[d?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:d.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:d.providerSessionId}),s.jsx("div",{className:"mt-1",children:d.metaLine}),d.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:d.updatedLabel}),d.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:d.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),n&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:n})]})}function fp({setup:e,providerName:t,className:n=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${n}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const wa={cli:"CLI",ide:"IDE",acp:"ACP"};function P1({workspaceMode:e,activeKind:t,cliEnabled:n,ideEnabled:r,acpEnabled:o,busy:a,onSelect:i}){const{t:c}=Le();return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:c("newSession.category")}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:wa.cli,enabled:n},{id:"ide",label:wa.ide,enabled:r},{id:"acp",label:wa.acp,enabled:o}].map(u=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===u.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(u.id),disabled:!u.enabled||a,children:u.label},u.id))})]})}function ka(e){var r;if(!e)return null;const t=e.availableProviders||[];return t.some(o=>Sn(o,"cli"))?"cli":(((r=e.detectedIdes)==null?void 0:r.length)||0)>0?"ide":t.some(o=>Sn(o,"acp"))?"acp":null}function _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function L1({machines:e,ides:t,onClose:n,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:h}){var jt,Ot;const{t:d}=Le(),m=In(),f=l.useMemo(()=>[...e].sort(Ei),[e]),[x,w]=l.useState(((jt=f[0])==null?void 0:jt.id)||""),p=l.useMemo(()=>f.find(ne=>ne.id===x)||f[0],[x,f]),y=l.useMemo(()=>((p==null?void 0:p.workspaces)||[]).map(ne=>({id:ne.id,path:ne.path,label:ne.label})),[p]),k=(p==null?void 0:p.defaultWorkspaceId)||null,[b,j]=l.useState("workspace"),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState([]),[T,M]=l.useState(""),[L,P]=l.useState(!1),[B,K]=l.useState(null),[F,R]=l.useState(""),[Q,E]=l.useState(ka(f[0])),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState(""),[z,X]=l.useState(""),[de,re]=l.useState(!1),[W,oe]=l.useState([]),[V,ie]=l.useState(""),[ke,xe]=l.useState([]),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),[Z,q]=l.useState(""),[me,Te]=l.useState(!1),[_,se]=l.useState(()=>Ft()),[ve,ce]=l.useState(null),[H,fe]=l.useState(!1),[je,Ce]=l.useState(""),[Be,Xe]=l.useState("error"),[dt,it]=l.useState(null),[he,$e]=l.useState(!1),[Fe,Ie]=l.useState(""),[ye,Oe]=l.useState([]),[ut,at]=l.useState(!1),[ht,J]=l.useState(""),[te,le]=l.useState(!1),ue=l.useRef(null),ge=l.useRef(0);l.useEffect(()=>{var ne;!x&&((ne=f[0])!=null&&ne.id)&&w(f[0].id)},[x,f]),l.useEffect(()=>{!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||m(p.id,{minFreshMs:3e4}).catch(()=>{})},[m,p]);const Ae=l.useCallback(ne=>{ne&&m(ne,{minFreshMs:3e4}).catch(()=>{})},[m]),Pe=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"cli")),[p]),Ne=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"acp")),[p]),He=l.useMemo(()=>((p==null?void 0:p.detectedIdes)||[]).map(ne=>({id:ne.type,label:ne.name||ne.type,meta:ne.running?d("newSession.detectedLocally"):d("newSession.availableToOpen")})),[p,d]),Ue=l.useMemo(()=>Q==="cli"?Pe.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):Q==="acp"?Ne.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):He,[Ne,Q,Pe,He]),Ze=l.useMemo(()=>C.find(ne=>ne.id===T)||null,[C,T]),_e=l.useMemo(()=>Pe.find(ne=>ne.type===I)||null,[Pe,I]),Ge=l.useMemo(()=>[...Pe,...Ne].find(ne=>ne.type===I),[Pe,Ne,I]),et=l.useMemo(()=>ck(Ge?[Ge]:[],Ge==null?void 0:Ge.type),[Ge]),ee=l.useMemo(()=>{const ne=dk(Ge?[Ge]:[],Ge==null?void 0:Ge.type);return ne.length?ne:["low","medium","high"]},[Ge]),be=l.useMemo(()=>Kh(_e==null?void 0:_e.meshCoordinator,{meshId:(Ze==null?void 0:Ze.id)||"",workspace:(Ze==null?void 0:Ze.workspace)||""}),[_e,Ze]),we=dt||be,ze=l.useCallback(async ne=>{P(!0),R("");try{const Ke=await c(ne);A(Ke),M(Ee=>{var vt;return Ke.some(Jt=>Jt.id===Ee)?Ee:((vt=Ke[0])==null?void 0:vt.id)||""}),K(ne)}catch(Ke){A([]),M(""),K(ne),R(Ke instanceof Error?Ke.message:d("newSession.errorLoadMeshes"))}finally{P(!1)}},[c,d]);l.useEffect(()=>{var Ke;if(!p)return;if(ue.current!==p.id){ue.current=p.id,j("workspace"),v(k||((Ke=y[0])==null?void 0:Ke.id)||"__home__"),N(""),A([]),M(""),K(null),R(""),E(ka(p)),$(""),U(""),ae(""),X(""),re(!1),ie(""),xe([]),O(!1),q(""),se(Ft()),Ce(""),it(null);return}v(Ee=>{var vt;return Ee==="__custom__"||Ee==="__home__"||y.some(Jt=>Jt.id===Ee)?Ee:k||((vt=y[0])==null?void 0:vt.id)||"__home__"}),E(Ee=>Ee==="ide"&&He.length>0||Ee==="cli"&&Pe.length>0||Ee==="acp"&&Ne.length>0?Ee:ka(p))},[Ne.length,Pe.length,k,He.length,p,y]),l.useEffect(()=>{!p||b!=="mesh"||B===p.id||L||ze(p.id)},[ze,B,L,p,b]),l.useEffect(()=>{b==="mesh"&&Q!=="cli"&&Pe.length>0&&E("cli")},[Q,Pe.length,b]),l.useEffect(()=>{var ne;Q&&(Ue.some(Ke=>Ke.id===I)||$(((ne=Ue[0])==null?void 0:ne.id)||""))},[Q,Ue,I]),l.useEffect(()=>{it(null)},[p==null?void 0:p.id,T,I,b]),l.useEffect(()=>{ae(""),X(""),re(!1)},[I]);const We=l.useCallback(async(ne,Ke)=>{const Ee=ge.current+1;return ge.current=Ee,pe(!0),q(""),h(ne,Ke).then(vt=>{ge.current===Ee&&xe(vt)}).catch(vt=>{ge.current===Ee&&(xe([]),q(vt instanceof Error?vt.message:d("newSession.errorLoadSavedSessions")))}).finally(()=>{ge.current===Ee&&(pe(!1),O(!0))})},[h,d]),tt=l.useCallback((ne,Ke)=>{oe(A1(ne,Ke))},[]);l.useEffect(()=>{ge.current+=1,ie(""),se(Ft()),!p||!I||Q==="ide"?oe([]):tt(p.id,I),O(!1),xe([]),q(""),pe(!1)},[Q,tt,We,p,I]),l.useEffect(()=>{if(!V)return;const ne=ke.find(Ke=>Ke.providerSessionId===V);ne!=null&&ne.canResume||ie("")},[ke,V]);const qe=S==="__custom__"?g.trim():S==="__home__"?"":((Ot=y.find(ne=>ne.id===S))==null?void 0:Ot.path)||"",Ye=l.useMemo(()=>p?t.filter(ne=>ne.id!==p.id&&ne.daemonId===p.id).map(ne=>ne.workspace):[],[t,p]),Tt=l.useMemo(()=>((p==null?void 0:p.recentLaunches)||[]).map(ne=>ne.workspace),[p]),Wt=l.useCallback(ne=>{const Ke=String(ne.workspace||"").trim();if(!Ke)return;const Ee=y.find(vt=>_r(vt.path)===_r(Ke));if(Ee){v(Ee.id),N("");return}v("__custom__"),N(Ke)},[y]),ss=l.useCallback(ne=>{const Ke=String(ne.workspace||"").trim();if(!Ke)return{workspaceId:null,workspacePath:null};const Ee=y.find(vt=>_r(vt.path)===_r(Ke));return Ee?{workspaceId:Ee.id,workspacePath:null}:{workspaceId:null,workspacePath:Ke}},[y]),Me=l.useMemo(()=>ke.find(ne=>ne.providerSessionId===V)||null,[ke,V]),Qe=l.useMemo(()=>{var Ke;if(Q!=="cli"||!p||!I)return null;const ne=((Ke=Pe.find(Ee=>Ee.type===I))==null?void 0:Ke.displayName)||I;return{routeId:p.id,daemonId:p.id,providerSessionId:V||void 0,transport:"pty",mode:"chat",agentName:ne,agentType:I,status:"idle",title:ne,messages:[],ideType:I,workspaceName:qe,workspacePath:qe,displayPrimary:ne,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${p.id}:${I}`,machineName:ts(p,{fallbackId:p.id})}},[Q,Pe,qe,p,V,I]),Dt=l.useCallback(()=>{var Ke;if(!p)return;v("__custom__"),$e(!0),J("");const ne=tl(p.platform,el(g.trim(),qe,Ye,Tt,p.defaultWorkspacePath,(Ke=y.find(Ee=>Ee.id===k))==null?void 0:Ke.path,y.map(Ee=>Ee.path)));at(!0),r(p.id,ne).then(Ee=>{Ie(Ee.path),N(Ee.path),Oe(Ee.directories)}).catch(Ee=>{J(Ee instanceof Error?Ee.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1))},[g,k,Tt,Ye,r,qe,p,y]),It=l.useCallback(ne=>{p&&(at(!0),J(""),r(p.id,ne).then(Ke=>{Ie(Ke.path),N(Ke.path),Oe(Ke.directories)}).catch(Ke=>{J(Ke instanceof Error?Ke.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1)))},[r,p]),qt=l.useCallback(async()=>{if(!p||!qe)return;le(!0),Ce("");const ne=await o(p.id,qe);if(le(!1),!ne.ok){Xe("error"),Ce(ne.error||d("newSession.errorSaveWorkspace"));return}Xe("info"),Ce(d("newSession.workspaceSaved"))},[o,qe,p,d]),Vt=l.useCallback(async()=>{if(!p)return;if(b==="mesh"){if(!T||!I)return;fe(!0),Ce(""),it(null);const Ee=await u(p.id,T,I,{initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ee.ok){if(Ee.code==="mesh_coordinator_manual_mcp_setup_required"&&Ee.manualSetup){it(Ee.manualSetup),Xe("info"),Ce(d("newSession.errorManualMcpSetup"));return}Xe("error"),Ce(Ee.error||d("newSession.errorStartMeshCoordinator"));return}n();return}if(!Q||!I)return;fe(!0),Ce("");const ne=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Ke=Q==="ide"?await a(p.id,I,{workspacePath:qe||null}):await i(p.id,Q,I,{workspaceId:S!=="__home__"&&S!=="__custom__"?S:null,workspacePath:S==="__custom__"&&qe||null,resumeSessionId:Q==="cli"&&V?V:null,cliArgs:ne,initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ke.ok){Xe("error"),Ce(Ke.error||d("newSession.errorStartSession"));return}Q!=="ide"&&D.trim()&&(T1(p.id,I,D),tt(p.id,I)),n()},[Q,D,Y,z,tt,n,a,u,i,qe,p,T,V,I,S,b,d]),Yt=Q==="cli"&&!!V,xs=d(b==="mesh"?"newSession.startMeshCoordinator":Q==="cli"?Yt?"newSession.resumeSavedHistory":"newSession.startFresh":Q==="ide"?"newSession.startIde":Q==="acp"?"newSession.startAcpSession":"newSession.start"),Re=d(b==="mesh"?"newSession.startingCoordinator":Q==="cli"?Yt?"newSession.resumingSavedHistory":"newSession.startingFresh":Q==="ide"?"newSession.startingIde":Q==="acp"?"newSession.startingAcpSession":"newSession.starting"),rt=f.length>5;return p?s.jsxs(s.Fragment,{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":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] 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-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsx("div",{className:"min-w-0",children:s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:d("newSession.title")})}),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:n,"aria-label":d("newSession.close"),children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[f.length>1&&s.jsx(Vn,{title:d("newSession.machine"),children:rt?s.jsx("select",{"aria-label":d("newSession.machine"),value:p.id,onChange:ne=>w(ne.target.value),onFocus:()=>f.forEach(ne=>Ae(ne.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:f.map(ne=>s.jsx("option",{value:ne.id,children:ts(ne,{fallbackId:ne.id})},ne.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":d("newSession.machine"),children:f.map(ne=>{const Ke=ts(ne,{fallbackId:ne.id}),Ee=p.id===ne.id;return s.jsxs("button",{type:"button","aria-label":d("newSession.selectMachine",{name:Ke}),"aria-pressed":Ee,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Ee?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>w(ne.id),onMouseEnter:()=>Ae(ne.id),onFocus:()=>Ae(ne.id),disabled:H,title:Ke,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ne.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ke})]},ne.id)})})}),s.jsxs(Vn,{title:d("newSession.workspace"),action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:d("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":d("newSession.launchTargetType"),children:[{id:"workspace",label:d("newSession.modeWorkspace"),desc:d("newSession.modeWorkspaceDesc")},{id:"mesh",label:d("newSession.modeMesh"),desc:d("newSession.modeMeshDesc")}].map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===ne.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===ne.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{j(ne.id),Ce(""),ne.id==="mesh"&&p&&B!==p.id&&!L&&ze(p.id)},disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold",children:ne.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ne.desc})]},ne.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:S,onChange:ne=>{const Ke=ne.target.value;v(Ke),Ke==="__custom__"?Dt():Ce("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:[s.jsx("option",{value:"__home__",children:d("newSession.homeDirectory")}),y.map(ne=>s.jsxs("option",{value:ne.id,children:[ne.id===k?"⭐ ":"",xu(ne.path,ne.label)||ne.path]},ne.id)),s.jsx("option",{value:"__custom__",children:d("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:S==="__home__"?d("newSession.launchWithoutWorkspace"):qe||d("newSession.selectWorkspaceFolder")}),S==="__custom__"&&qe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:[s.jsx(xn,{size:14}),d("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qt,disabled:H||te,children:d(te?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.loadingMeshes")}),!L&&F&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:F}),!L&&!F&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:d("newSession.noMeshes")}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":d("newSession.mesh"),children:C.map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":T===ne.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${T===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ne.repoIdentity||d("newSession.repoMesh"),typeof ne.nodesCount=="number"?` · ${d("newSession.nodeCount",{count:ne.nodesCount})}`:""]}),ne.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:d("newSession.coordinatorWorkspace",{path:ne.workspace})})]},ne.id))})]})]}),s.jsx(P1,{workspaceMode:b,activeKind:Q,cliEnabled:Pe.length>0,ideEnabled:He.length>0,acpEnabled:Ne.length>0,busy:H,onSelect:E}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:d(Q==="ide"?"newSession.chooseIde":Q==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ue.map(ne=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.label}),ne.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ne.meta})]},ne.id)),Ue.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.noProviders")})]})]}),b==="mesh"&&we&&s.jsx(fp,{setup:we,providerName:(_e==null?void 0:_e.displayName)||(_e==null?void 0:_e.name)||I}),b!=="mesh"&&Q!=="ide"&&s.jsxs(Vn,{title:d("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:D,onChange:ne=>U(ne.target.value),placeholder:d("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H}),W.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:W.map(ne=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(ne),disabled:H,title:ne,children:ne},ne))})]}),(b==="mesh"&&!!I||b!=="mesh"&&Q!=="ide")&&s.jsx(Vn,{title:d("newSession.modelAndThinking"),children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.model")}),et.length>0&&!de?s.jsxs("select",{value:et.includes(Y)?Y:"",onChange:ne=>{ne.target.value==="__custom__"?(re(!0),ae("")):ae(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),et.map(ne=>s.jsx("option",{value:ne,children:ne},ne)),s.jsx("option",{value:"__custom__",children:d("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:Y,onChange:ne=>ae(ne.target.value),placeholder:d("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,autoFocus:de}),et.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{re(!1),ae("")},disabled:H,children:d("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.thinkingLevel")}),s.jsxs("select",{value:z,onChange:ne=>X(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),ee.map(ne=>s.jsx("option",{value:ne,children:ne},ne))]})]})]})}),b!=="mesh"&&Q==="cli"&&s.jsx(D1,{busy:H,savedSessionsLoading:Se,savedSessionsError:Z,selectedSession:Me,onRefresh:()=>{!p||!I||We(p.id,I)},onOpenHistory:()=>{!p||!I||(Te(!0),I1({hasLoadedInitialResults:G,isLoading:Se})&&We(p.id,I))},onClearSelection:()=>ie("")}),je&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Be==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:je})]}),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:n,disabled:H,children:d("common.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:Vt,disabled:H||(b==="mesh"?!T||!I||Q!=="cli"||L:!Q||!I||S==="__custom__"&&!qe),children:[s.jsx(Qd,{size:14}),H?Re:xs]})]})]})}),he&&s.jsx(rl,{title:d("newSession.selectWorkspaceTitle"),description:d("newSession.selectWorkspaceDescription"),currentPath:Fe,directories:ye,busy:ut,error:ht,onClose:()=>$e(!1),onNavigate:It,onConfirm:ne=>{N(ne),Ie(ne),v("__custom__"),$e(!1)}}),me&&Qe&&s.jsx(bh,{activeConv:Qe,ides:[],isCreatingChat:!1,isRefreshingHistory:Se,savedSessions:ke,isSavedSessionsLoading:Se,isResumingSavedSessionId:ve,savedHistoryFilters:_,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:se,onClose:()=>Te(!1),onNewChat:()=>{ie(""),Te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!p||!I||We(p.id,I)},onResumeSavedSession:ne=>{if(!p||!I||ve||!ne.canResume)return;const Ke=ss(ne);ie(ne.providerSessionId),Wt(ne),ce(ne.providerSessionId),Te(!1),fe(!0),Ce(""),i(p.id,"cli",I,{workspaceId:Ke.workspaceId,workspacePath:Ke.workspacePath,resumeSessionId:ne.providerSessionId}).then(Ee=>{if(!Ee.ok){Xe("error"),Ce(Ee.error||d("newSession.errorResumeSession"));return}n()}).finally(()=>{fe(!1),ce(Ee=>Ee===ne.providerSessionId?null:Ee)})}})]}):null}function bp(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function al(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const n=bp(e);return n?{label:n,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function il(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function gp(e){var t;return!il(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function $r(e){return[...new Set(e.filter(t=>!!t))]}function R1(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,n=(t==null?void 0:t.branch)??null,r=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!n&&i.branch===n),o=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),a=e.nodes.filter(i=>i.type!=="submoduleNode");return t||r.length>0?$r([t==null?void 0:t.id,...r.map(i=>i.id)]):o.length>0?$r(o.map(i=>i.id)):a.length>0?$r(a.map(i=>i.id)):$r(e.nodes.map(i=>i.id))}function xp(e){const t=[...e.nodes].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.type,r.branch??"",r.parentNodeId??"",r.submodulePath??""].join(":")).join("|"),n=[...e.edges].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.source,r.target,r.type].join(":")).join("|");return`${e.meshId}::${t}::${n}`}function E1(e,t,n){const r=Math.max(0,Math.round(t)),o=Math.max(0,Math.round(n));return`${xp(e)}::${r}x${o}`}const _1={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},$1={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},B1={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},F1={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Rs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[rgba(15,23,42,0.82)] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>$1[t],actionButton:t=>F1[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[#030617]/[0.92] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>_1[t],actionButton:t=>B1[t]}}const Cn={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},xr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},H1={maxWidth:180};function W1(e){return e==="TB"?"DOWN":"RIGHT"}function ll(e,t){return{"elk.algorithm":"layered","elk.direction":W1(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"}}const O1=ll(Cn,"LR");ll(xr,"LR");function U1(e){const t=e.nodes.length;if(t<8)return"LR";const n=new Map;for(const o of e.edges)n.set(o.source,(n.get(o.source)??0)+1);let r=0;for(const o of n.values())o>r&&(r=o);return r>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const G1=new Nm;function ur(e,t=!1){const n=t?xr:Cn;return e.type==="submoduleNode"?n.submoduleCardWidth:n.worktreeCardWidth}function Qr(e){var n;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const r=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?r.push("out of sync"):e.dirty?r.push("local changes"):r.push("synced"),r.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const r=bp(e);r&&t.push(r)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(n=e.branchConvergence)!=null&&n.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function yp(e,t=!1){const n=t?xr:Cn,r=ur(e,t),o=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,a=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(K1(e)/a),c=Br(e.label,o,2),u=Br(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,o,2),h=Br(Qr(e),o+(t?1:4),t?2:3),d=al(e),m=gp(e)?il(e):null,f=t?0:Br(m,Math.max(24,Math.floor(r/8)),4),x=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,h*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,h*18)+(f>0?22+f*16:0),w=e.type==="submoduleNode"?n.minSubmoduleCardHeight:n.minWorktreeCardHeight;return Math.min(n.maxEstimatedCardHeight,Math.max(w,Math.ceil(x)))}function Br(e,t,n){const r=(e||"").trim();return r?Math.max(1,Math.min(n,Math.ceil(r.length/t))):0}function K1(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function z1(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function q1(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function V1(e,t,n,r=!0){return{id:e.id,type:"meshNode",position:{x:t,y:n},graphNode:e,selected:!1,draggable:!1,selectable:r}}function Y1(e,t,n){return{id:e.id,x:t,y:n,width:ur(e),height:yp(e)}}function J1(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function vp(e){const t=[...e.nodes].sort(z1),n=t.find(o=>o.type==="defaultBranchNode")??null,r=t.some(o=>o.id!==(n==null?void 0:n.id)&&o.type!=="submoduleNode");return!n||r?t:[...t,J1(n,e)]}function Q1(e,t=O1,n=!1,r="LR"){const o=vp(e),a=new Set(o.map(u=>u.id)),i=o.map(u=>({id:u.id,width:ur(u,n),height:yp(u,n)})),c=e.edges.filter(u=>a.has(u.source)&&a.has(u.target)).sort(q1).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function X1(e,t=!1){const n=[...new Set(e.map(o=>Math.round(o.x)))].sort((o,a)=>o-a),r=t?xr.layerGap:Cn.layerGap;return n.length<2?r:Math.min(...n.slice(1).map((o,a)=>o-n[a]))}async function wp(e,t=!1,n="LR",r){var w,p;const a=ll(t?xr:Cn,n),i=vp(e),c=new Map(i.map(y=>[y.id,y])),u=Q1(e,a,t,n);if(r&&r.size>0)for(const y of u.children??[]){const k=r.get(y.id);k&&k>0&&(y.height=k)}const h=await G1.layout(u),d=(h.children??[]).map(y=>{const k=c.get(y.id);return k?V1(k,Math.round(y.x??0),Math.round(y.y??Cn.placeholderTopOffset),!y.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((y,k)=>[y.id,k]));d.sort((y,k)=>(m.get(y.id)??0)-(m.get(k.id)??0));const f=d.map(y=>Y1(y.graphNode,y.position.x,y.position.y)),x=new Map;for(const y of h.edges??[]){const k=y.sections;if(!k||k.length===0)continue;const b=k[0],j=(w=y.sources)==null?void 0:w[0],S=(p=y.targets)==null?void 0:p[0];if(!j||!S)continue;const v=[];v.push({x:Math.round(b.startPoint.x),y:Math.round(b.startPoint.y)});for(const g of b.bendPoints??[])v.push({x:Math.round(g.x),y:Math.round(g.y)});v.push({x:Math.round(b.endPoint.x),y:Math.round(b.endPoint.y)}),x.set(y.id,{id:y.id,source:j,target:S,points:v})}return{nodes:d,bounds:f,edgeRoutes:x,columnGap:X1(f,t),layoutOptions:{...a}}}function Z1(e){var t,n;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(r=>[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.role??"",r.isSelfCoordinator?1:0,r.statusNote??"",r.startedAt??"",r.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(n=e.branchConvergence)!=null&&n.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function kp(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function ej(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Z1),...e.edges.map(kp)].join("::")}function tj(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var n,r;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((n=t.branchConvergence)==null?void 0:n.status)??"",(r=t.branchConvergence)!=null&&r.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(kp)].join("::")}const sj=5*60*1e3;function Sp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Cp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function nj(e){var t,n,r;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((n=e.connection)==null?void 0:n.transport)==="direct"||((r=e.connection)==null?void 0:r.transport)==="relay"||Sp(e)||Cp(e)?"remote":"unknown"}function rj(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const n=t.rttMs,r=typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:r}}function jp(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const n=e.connectionState;return n==="connecting"?"connecting":n==="disconnected"?"disconnected":n==="failed"?"failed":n==="closed"?"closed":null}function oj(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=jp(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function aj(e){return Fi(e)}function Np(e){var t;return aj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Ap(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ij(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Tp(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Ip(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function cl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function lj(e){return cl(e)?"degraded":Ip(e)?"dirty":"online"}function cj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Qc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function Sa(e){return e.length===0?"unknown":e.reduce((t,n)=>Qc(n)>Qc(t)?n:t)}function dj(e){var a,i,c,u,h;const t=new Map,n=new Map;for(const d of e){const m=(i=(a=d.git)==null?void 0:a.branch)==null?void 0:i.trim();m&&(n.set(m,(n.get(m)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const r=[...t.entries()].sort((d,m)=>{if(m[1]!==d[1])return m[1]-d[1];const f=["main","master","develop","dev"],x=f.indexOf(d[0]),w=f.indexOf(m[0]);return x!==-1||w!==-1?x===-1?1:w===-1?-1:x-w:d[0].localeCompare(m[0])});return(u=r[0])!=null&&u[0]?r[0][0]:((h=[...n.entries()].sort((d,m)=>m[1]-d[1])[0])==null?void 0:h[0])??null}function uj(e,t){const n=[],r=e.git;return r?r.isGitRepo?(!r.branch&&r.headCommit&&n.push("Detached HEAD"),r.hasConflicts&&n.push("Merge conflicts need resolution"),r.branch&&t&&r.branch!==t&&!r.upstream&&n.push(`No upstream tracking for ${r.branch}`),r.upstream&&r.upstreamStatus&&r.upstreamStatus!=="fresh"&&n.push(`Upstream freshness unverified for ${r.branch??"workspace"}`),e.error&&n.push(e.error),n):(n.push("Not a git repository"),n):(n.push("No git status available"),n)}function Xc(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function hj(e){return e.reduce((t,n)=>Xc(n.status)>Xc(t.status)?n:t)}function pj(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const n=e.followUps;return Array.isArray(n)?n:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function mj(e){var o,a,i;const t=e.sourceOfTruth,n=[],r=(o=t==null?void 0:t.fallback)==null?void 0:o.warning;return typeof r=="string"&&r.trim()&&n.push(r.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((a=t.directPeerTruth)==null?void 0:a.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!n.some(c=>c.includes("direct mesh truth"))&&n.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),n}function fj(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(!r||typeof r!="object")continue;const o=r,a=typeof o.jobId=="string"?o.jobId:null,i=o.status;a&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||n.push({jobId:a,status:i,nodeId:typeof o.nodeId=="string"?o.nodeId:void 0,targetNodeId:typeof o.targetNodeId=="string"?o.targetNodeId:void 0,workspace:typeof o.workspace=="string"?o.workspace:void 0,branch:typeof o.branch=="string"?o.branch:void 0,into:typeof o.into=="string"?o.into:void 0,lastUpdatedAt:typeof o.lastUpdatedAt=="string"?o.lastUpdatedAt:void 0,startedAt:typeof o.startedAt=="string"?o.startedAt:void 0,completedAt:typeof o.completedAt=="string"?o.completedAt:void 0}))}return n}function Zc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function ed(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Ap(t)??0}function bj(e){return e.length===0?null:e.reduce((t,n)=>{const r=Zc(t.status),o=Zc(n.status);return o!==r?o<r?n:t:ed(n)>ed(t)?n:t})}function gj(e){var n,r;const t=new Map;for(const o of e){const a=((n=o.nodeId)==null?void 0:n.trim())||((r=o.targetNodeId)==null?void 0:r.trim());if(!a)continue;const i=t.get(a)??[];i.push(o),t.set(a,i)}return t}function xj(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function yj(e,t){var n,r;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((n=t.find(o=>o.upstream))==null?void 0:n.upstream)??null,upstreamStatus:((r=t.find(o=>o.upstreamStatus))==null?void 0:r.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function vj(e,t){if(Np(e))return null;const n=e.branchConvergence;if(!n||typeof n!="object")return null;const r=n.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const o=e.git,a=Tp(o)||Ip(o),i=!!(o!=null&&o.hasConflicts)||cl(o),c=(o==null?void 0:o.ahead)??0,u=(o==null?void 0:o.behind)??0,h=(o==null?void 0:o.branch)??null,d=(o==null?void 0:o.upstream)??null,m=(o==null?void 0:o.upstreamStatus)??null,f=n.defaultBranch??t??null;return{status:r,needsConvergence:n.needsConvergence??r!=="merged_to_main",reason:n.reason??"provided_by_coordinator",nextStep:n.nextStep??null,branch:n.branch??h,defaultBranch:f,upstream:n.upstream??d,upstreamStatus:n.upstreamStatus??m,ahead:n.ahead??c,behind:n.behind??u,dirty:n.dirty??a,hasConflicts:n.hasConflicts??i}}function wj(e,t){const n=vj(e,t);return n?{...n,defaultBranch:n.defaultBranch??t}:null}function kj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Sj(e){var u,h,d;const{nodeStatus:t,expectedSubmodulePaths:n,refreshedAtMs:r}=e,o=[],a=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Np(t))return o.push(`${a} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:o};const m=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((h=t.connection)==null?void 0:h.state)==="self";return o.push(m?`${a} is online but no peer git snapshot is visible yet.`:`${a} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:o}}const c=new Set((i.submodules??[]).map(m=>m.path));if(n.size>0){const m=[...n].filter(f=>!c.has(f));m.length>0&&o.push(`${a} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&r!==null&&typeof i.lastCheckedAt=="number"&&r-i.lastCheckedAt>sj&&o.push(`${a} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),o.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:o}:o.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:o}:{snapshotCompleteness:"complete",snapshotWarnings:o}}function Mp(e){const t=Mu(e),r=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??dj(t.nodes),o=Ap(t.refreshedAt),a=new Set(t.nodes.flatMap(F=>{var R;return(((R=F.git)==null?void 0:R.submodules)??[]).map(Q=>Q.path)})),i=[],c=[],u=mj(t),h=new Map,d=gj(fj(t));for(const F of t.nodes){const R=F.git,Q=(R==null?void 0:R.branch)??null,E=lj(R),I=Tp(R)||E==="dirty",$=uj(F,r),D=wj(F,r),U=Sj({nodeStatus:F,expectedSubmodulePaths:a,refreshedAtMs:o}),Y=typeof F.clonedFromNodeId=="string"?F.clonedFromNodeId:null,ae=ij(F),z=bj(d.get(F.nodeId)??[]),X=rj(F),de={id:F.nodeId,type:$.length>0?"orphanNode":"worktreeNode",label:F.machineLabel||F.nodeId.slice(0,8),workspace:F.workspace,branch:Q,upstream:(R==null?void 0:R.upstream)??null,upstreamStatus:(R==null?void 0:R.upstreamStatus)??null,daemonId:Sp(F),machineId:Cp(F),machineLabel:F.machineLabel||null,locality:nj(F),connectionTransport:X.connectionTransport,connectionState:X.connectionState,connectionReason:X.connectionReason,connectionReported:X.connectionReported,connectionRttMs:X.connectionRttMs,health:Sa([F.health,E]),ahead:(R==null?void 0:R.ahead)??0,behind:(R==null?void 0:R.behind)??0,dirty:I,dirtyFiles:cj(R),hasConflicts:(R==null?void 0:R.hasConflicts)??!1,activeSessionCount:ae.length,activeSessions:ae.map(re=>re.sessionId),sessionDetails:ae,providers:F.providers??[],isOrphan:$.length>0,orphanReasons:$,error:F.error,nextStepHint:U.snapshotWarnings[0]??$[0]??(D==null?void 0:D.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:Y,worktreeBranch:F.worktreeBranch??null,submodulePath:null,submoduleCommit:(R==null?void 0:R.headCommit)??null,outOfSync:cl(R),snapshotCompleteness:U.snapshotCompleteness,snapshotWarnings:U.snapshotWarnings,branchConvergence:D,refineJobStatus:(z==null?void 0:z.status)??null,refineJobId:(z==null?void 0:z.jobId)??null,refineJobBranch:(z==null?void 0:z.branch)??null,refineJobInto:(z==null?void 0:z.into)??null,source:F};if(i.push(de),Q){const re=h.get(Q)??[];re.push(de.id),h.set(Q,re)}for(const re of(R==null?void 0:R.submodules)??[]){const W=`${de.id}::submodule::${re.path}`,oe=re.path.split("/").filter(Boolean).pop()||re.path;i.push({id:W,type:"submoduleNode",label:oe,workspace:re.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:de.daemonId,machineId:de.machineId,machineLabel:de.machineLabel,locality:de.locality,connectionTransport:de.connectionTransport,connectionState:de.connectionState,connectionReason:de.connectionReason,connectionReported:de.connectionReported,connectionRttMs:de.connectionRttMs,health:kj(re),ahead:0,behind:0,dirty:re.dirty,dirtyFiles:re.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:re.error,nextStepHint:re.error||(re.outOfSync?`${re.path} is out of sync with the parent checkout`:re.dirty?`${re.path} has local changes`:`${re.path} is in sync with the parent checkout`),parentNodeId:de.id,submodulePath:re.path,submoduleCommit:re.commit,outOfSync:re.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:de.id,parentWorkspace:F.workspace,submodule:re}}),c.push({id:`${de.id}--${W}`,source:de.id,target:W,type:"submoduleLink",label:re.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=r?`__branch_${r}`:null;if(m&&r){const R=(h.get(r)??[]).map(Y=>i.find(ae=>ae.id===Y)).filter(Boolean),Q=R.map(Y=>Y.branchConvergence).filter(Boolean),E=pj(t),I=R.length>0&&R.every(Y=>xj(Y,r)),$=(E==null?void 0:E.length)===0&&I?yj(r,R):Q.length>0?hj(Q):null,D=(E==null?void 0:E.length)===0&&I?0:Q.filter(Y=>Y.needsConvergence).length,U={id:m,type:"defaultBranchNode",label:r,workspace:t.repoIdentity,branch:r,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:Sa(R.map(Y=>Y.health)),ahead:0,behind:0,dirty:R.some(Y=>Y.dirty),dirtyFiles:R.reduce((Y,ae)=>Y+ae.dirtyFiles,0),hasConflicts:R.some(Y=>Y.hasConflicts),activeSessionCount:R.reduce((Y,ae)=>Y+ae.activeSessionCount,0),activeSessions:R.flatMap(Y=>Y.activeSessions),sessionDetails:R.flatMap(Y=>Y.sessionDetails),providers:[...new Set(R.flatMap(Y=>Y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:D>0?`${D} workspace(s) on ${r} still need follow-up`:R.length>0?`${R.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:$,source:{nodeId:m,machineLabel:r,workspace:t.repoIdentity,health:Sa(R.map(Y=>Y.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(U);for(const Y of i)if(!(Y.id===m||Y.type==="submoduleNode")){if(Y.branch===r){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(Y.branch){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:Y.isOrphan?"orphanLink":"parentBranch",label:Y.branch,direction:"undirected"});continue}Y.isOrphan&&c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const f=new Set(i.map(F=>F.id)),x=new Set;for(const F of i){if(!F.clonedFromNodeId||F.type==="submoduleNode"||!f.has(F.clonedFromNodeId))continue;const R=`clone_${F.clonedFromNodeId}--${F.id}`;if(x.has(R))continue;x.add(R);const Q=F.worktreeBranch??F.branch??void 0;c.push({id:R,source:F.clonedFromNodeId,target:F.id,type:"cloneLink",label:Q?`cloned · ${Q}`:"cloned",direction:"directed"})}const w=i.filter(F=>F.type!=="defaultBranchNode"),p=w.filter(F=>F.isOrphan).length,y=w.filter(F=>F.hasConflicts).length,k=w.filter(F=>F.health==="offline").length,b=w.filter(F=>F.type==="submoduleNode"&&F.outOfSync).length,j=w.filter(F=>{var R;return F.type!=="submoduleNode"&&((R=F.branchConvergence)==null?void 0:R.needsConvergence)}).length,S=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="blocked_review"}).length,v=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="pushed_feature_branch_needs_merge"}).length,g=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="cleanup_candidate"}).length,N=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="not_mergeable"}).length,C=w.filter(F=>F.snapshotWarnings.length>0).length,A=w.filter(F=>F.snapshotCompleteness==="pending_git").length,T=w.filter(F=>F.snapshotCompleteness==="missing_git").length,M=w.filter(F=>F.snapshotCompleteness==="missing_submodule_report").length,L=w.filter(F=>F.snapshotCompleteness==="stale").length,P=w.filter(F=>F.refineJobStatus==="running"||F.refineJobStatus==="accepted").length,B=w.filter(F=>F.refineJobStatus==="failed").length,K=[A>0?`${A} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,M>0?`${M} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,L>0?`${L} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return j>0&&u.push(`${j} workspace(s) still need follow-up before the mesh is converged`),p>0&&u.push(`${p} workspace(s) need attention before safe coordination`),S>0&&u.push(`${S} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&u.push(`${v} clean feature branch workspace(s) still need merge follow-up`),g>0&&u.push(`${g} worktree workspace(s) are ready for refine / cleanup`),N>0&&u.push(`${N} workspace(s) have local changes or conflicts blocking convergence`),y>0&&u.push(`${y} workspace(s) report merge conflicts`),k>0&&u.push(`${k} node(s) are currently offline`),b>0&&u.push(`${b} submodule(s) are out of sync with their parent checkout`),u.push(...K),r||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:w.length,onlineNodes:w.filter(F=>F.health==="online").length,dirtyNodes:w.filter(F=>F.dirty).length,orphanNodes:p,errorNodes:w.filter(F=>!!F.error||F.outOfSync).length,offlineNodes:k,followUpNodes:j,blockedReviewNodes:S,mergeReadyNodes:v,cleanupCandidateNodes:g,notMergeableNodes:N,incompleteSnapshotNodes:C,pendingGitSnapshotNodes:A,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:M,staleGitSnapshotNodes:L,activeRefineNodes:P,failedRefineNodes:B,totalActiveSessions:w.reduce((F,R)=>F+R.activeSessionCount,0)},warnings:u,snapshotWarnings:K}}function Cj(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const jj=7,Nj=640,dl=l.createContext(Rs("dark")),Dp=l.createContext(!1),Pp=l.createContext("LR"),Lp={overflowWrap:"anywhere",wordBreak:"break-word"},Aj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Tj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Rp(e){return e.activeSessionCount>0}function Ij(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function td(e,t,n){const r=Rp(e),o=Ij(e);let a;t?a="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?a=n?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":o?a=n?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":a=n?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=al(e);if((i==null?void 0:i.tone)==="danger")return`${a} ${n?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${a} ${n?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${a} ${n?r?"bg-emerald-500/10":"bg-emerald-500/8":r?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${a} ${n?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${a} ${n?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${a} ${n?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${a} ${n?"bg-slate-950/78":"bg-white/96"}`}}function Lt(e,t){switch(e){case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function sd(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function nd(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function Mj(e){return e.replace(/_/g," ")}function hs(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?n.replace(/_/g," "):n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function Dj(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(n=>hs(n)==="generating"))??!1}function Ca(e,t){const n=hs(e);return n.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":n==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":n==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":Lt("health",t)}function Pj(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function rd(e){const t=Pj(e);if(t===null)return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const o=Math.floor(r/60);return o<48?`${o}h ${r%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function ja(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function On(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Lj(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(a=>hs(a)==="generating").length,n=e.sessionDetails.filter(a=>a.isSelfCoordinator).length,r=e.sessionDetails.length-n,o=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&o.push(`${t} generating`),n>0&&o.push(n===1?"coordinator attached":`${n} coordinators`),r>0&&o.push(`${r} worker${r===1?"":"s"}`),t===0&&n>0&&o.push("sampled status"),o.join(" · ")}function od(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Rj(e){return e.locality==="remote"?"meta":"health"}function Ej({data:e,selected:t}){const{t:n}=Le("common"),r=l.useContext(dl),o=l.useContext(Dp),a=l.useContext(Pp),i=e.graphNode,c=i.type==="defaultBranchNode",u=i.type==="submoduleNode",h=gp(i),d=c?"default branch anchor":u?i.submodulePath||"submodule checkout":[i.machineLabel,od(i.locality)].filter(Boolean).join(" · ")||i.workspace,m=i.submoduleCommit?i.submoduleCommit.slice(0,7):null,f=!u&&!c&&i.connectionState!=="self",x=f?jp(i):null,w=x==="local"?null:x,p=f?oj(i):null,y=al(i),k=il(i),b=Rp(i),j=i.sessionDetails,S=i.sessionDetails,v=Lj(i),g=i.sessionDetails.map(C=>{const A=hs(C),T=C.providerType||"provider unknown",M=On(C),L=C.startedAt||C.createdAt||null,P=C.statusNote?` · ${C.statusNote}`:"";return`Session: ${C.sessionId} · ${T} · ${A} · ${M} · ${rd(L)}${P}`});if(o)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}`,style:{width:ur(i,!0)},title:[i.label,i.branch?`Branch: ${i.branch}`:null,i.machineLabel?`Machine: ${i.machineLabel}`:null,i.workspace?`Workspace: ${i.workspace}`:null,y?`Status: ${y.label}`:null,Qr(i),...g].filter(Boolean).join(`
81
+ `,Ae.style.top="52px",Ae.style.height="calc(100% - 52px)";const Ue=_e.querySelector("[data-adhdev-popout-focus]");Ue&&(Ue.onclick=()=>{window.focus()});const et=_e.querySelector("[data-adhdev-popout-dock]");et&&(et.disabled=!Pe,et.style.opacity=Pe?"1":"0.5",et.style.cursor=Pe?"pointer":"default",et.onclick=()=>{var se;Pe&&de(Pe),(se=ge.defaultView)==null||se.focus()})}},[$,de]),pe=l.useCallback(J=>{var ue;const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!(!ee||!le)){le.group.model.openPanel(le),le.api.setActive(),Y(J,"dockview-shortcut");try{const ge=le.group.model.location;ge.type==="popout"?ge.getWindow().focus():ya((ue=le.group.element)==null?void 0:ue.ownerDocument)}catch{}}},[Y]),G=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.activePanel,ue=(ee==null?void 0:ee.activeGroup)||(le==null?void 0:le.group);if(!ee||!le||!ue)return;const ge=ue.panels||[];if(ge.length<=1)return;const Ae=ge.findIndex(He=>He.id===le.id);if(Ae<0)return;const Pe=(Ae+J+ge.length)%ge.length,Ne=ge[Pe];Ne&&(Ne.group.model.openPanel(Ne),Ne.api.setActive(),rs(Ne.id)||Y(Ne.id,"dockview-shortcut"))},[Y]),O=l.useCallback(J=>{var Ue;const ee=C.current,le=(ee==null?void 0:ee.activeGroup)||((Ue=ee==null?void 0:ee.activePanel)==null?void 0:Ue.group);if(!ee||!le)return;const ue=ee.groups||[],ge=ue.find(et=>et.id===le.id);if(!ge)return;const Ae=ge.element.getBoundingClientRect(),Pe=Ae.left+Ae.width/2,Ne=Ae.top+Ae.height/2,He=(et,se,be,we)=>Math.max(0,Math.min(se,we)-Math.max(et,be)),Ke=et=>{const se=et.element.getBoundingClientRect(),be=se.left+se.width/2,we=se.top+se.height/2;let ze=0,We=0,tt=0,qe=!1;if(J==="left"?(qe=be<Pe,ze=Math.max(0,Ae.left-se.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,se.top,se.bottom)):J==="right"?(qe=be>Pe,ze=Math.max(0,se.left-Ae.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,se.top,se.bottom)):J==="above"?(qe=we<Ne,ze=Math.max(0,Ae.top-se.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,se.left,se.right)):(qe=we>Ne,ze=Math.max(0,se.top-Ae.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,se.left,se.right)),!qe)return Number.POSITIVE_INFINITY;const Ye=tt>0?0:120;return ze*3+We+Ye};let Ze=null,_e=Number.POSITIVE_INFINITY;for(const et of ue){if(et.id===ge.id)continue;const se=Ke(et);Number.isFinite(se)&&(se>=_e||(_e=se,Ze=et))}return Ze||void 0},[]),Z=l.useCallback(J=>{var ue;const ee=O(J);if(!ee)return;const le=ee.activePanel||ee.panels[0];le&&(ee.model.openPanel(le),le.api.setActive(),rs(le.id)||Y(le.id,"dockview-focus"),ya((ue=ee.element)==null?void 0:ue.ownerDocument))},[O,Y]),q=l.useCallback((J,ee)=>{const le=C.current,ue=le==null?void 0:le.activePanel,ge=(le==null?void 0:le.activeGroup)||(ue==null?void 0:ue.group);if(!le||!ue||!ge)return;let Ae=O(J);!Ae&&(ee!=null&&ee.createGroupIfMissing)&&(Ae=le.addGroup({referenceGroup:ge,direction:J})),Ae&&(ue.api.moveTo({group:Ae,position:"center"}),ue.group.model.openPanel(ue),ue.api.setActive(),rs(ue.id)||Y(ue.id,ee!=null&&ee.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,Y]),{isMac:me,tabShortcuts:Te,shortcutListening:_,setShortcutListening:te,saveShortcuts:ve}=rp({sortedTabKeys:e.map(J=>J.tabKey),onFocus:U,onSelectTab:pe}),ce=l.useCallback(()=>{var le;const J=C.current;if(!J)return;const ee=J.activePanel;if(ee){if(rs(ee.id)){const ue=((le=ee.params)==null?void 0:le.routeId)||ee.id.slice(7),ge=cs(e,ue);ge!=null&&ge.tabKey&&te(ge.tabKey);return}$.has(ee.id)&&te(ee.id)}},[$,pe,te,e]),H=l.useCallback(J=>{const ee=[];return J.metaKey&&ee.push(me?"⌘":"Meta"),J.ctrlKey&&ee.push("Ctrl"),J.altKey&&ee.push(me?"⌥":"Alt"),J.shiftKey&&J.key.length!==1&&ee.push(me?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(J.key)?null:(ee.push(ip(J.key)),ee.join("+"))},[me]),fe=l.useCallback(J=>{var ee,le;switch(J){case"splitActiveTabRight":q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ue=ie();ue&&oe(ue);return}case"popoutActiveTab":{const ue=ie();ue&&X(ue);return}case"dockActiveTab":{const ue=ie();if(!ue)return;re(ue)?de(ue):V(ue)&&ke(ue);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":q("left");return;case"moveActiveTabToRightPane":q("right");return;case"moveActiveTabToUpPane":q("above");return;case"moveActiveTabToDownPane":q("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":ce();return;case"hideCurrentTab":{const ue=(le=(ee=C.current)==null?void 0:ee.activePanel)==null?void 0:le.id;ue&&!rs(ue)&&W(ue);return}default:return}},[G,ke,Z,oe,ie,W,V,re,de,q,X,ce]);l.useEffect(()=>{if(!F)return;const J=F.sourceDocument,ee=J.defaultView??window,le=ue=>{const ge=J.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(ue.target)||R(null)};return ee.addEventListener("mousedown",le,!0),ee!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{ee.removeEventListener("mousedown",le,!0),ee!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[F]);const je=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:D,ides:n,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:w,liveSessionInboxState:S,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:W,userName:h,scrollToBottomRequest:j,tabShortcuts:Te,openTabContextMenu:({x:J,y:ee,tabKey:le,sourceDocument:ue})=>R({x:J,y:ee,tabKey:le,sourceDocument:ue??document}),popoutTab:X,moveTabBackToMain:de,isTabInPopout:re,floatTab:oe,isTabFloating:V}),[r,t,$,D,n,i,c,w,S,o,a,W,h,j,Te,X,de,re,oe,V]),Ce=F?d1({isTabInPopout:re(F.tabKey),isTabFloating:V(F.tabKey),tabShortcut:Te[F.tabKey],actionShortcuts:m}):[],Be=l.useCallback(J=>{var ue;const ee=C.current;if((((ue=ee==null?void 0:ee.activePanel)==null?void 0:ue.id)??null)===J.id){J.group.model.openPanel(J);return}J.group.model.openPanel(J),J.api.setActive()},[]),Xe=l.useCallback((J,ee="requested-tab")=>{if(!J)return!1;const le=C.current;if(!le)return!1;const ue=le.getPanel(J);return ue?(Be(ue),Y(J,ee),b==null||b(),!0):!1},[Be,b,Y]),dt=l.useCallback(()=>{if(P.current)return!1;const J=Xe(B.current,"stored-layout-restore");return J&&(P.current=!0),J},[Xe]),it=l.useCallback(()=>{var ee;const J=C.current;J&&WS(v,{activeTabId:((ee=J.activePanel)==null?void 0:ee.id)??null,layout:J.toJSON()})},[v]),he=l.useCallback(()=>{US(v,I.current)},[v]),$e=l.useCallback(J=>{var ue,ge,Ae,Pe;const ee=C.current;if(!ee)return{kind:"grid"};const le=ee.toJSON();for(const Ne of le.floatingGroups||[])if((ge=(ue=Ne.data)==null?void 0:ue.views)!=null&&ge.includes(J)&&Ne.position)return{kind:"floating",position:Ne.position};for(const Ne of le.popoutGroups||[])if((Pe=(Ae=Ne.data)==null?void 0:Ae.views)!=null&&Pe.includes(J))return{kind:"popout",position:Ne.position,popoutUrl:Ne.url};return{kind:"grid"}},[]),Fe=l.useCallback(J=>{const ee=C.current;if(!ee)return;const le=ee.getPanel(J),ue=I.current[J];if(!le||!ue||ue.kind==="grid")return;if(le.group.model.location.type===ue.kind){delete I.current[J],he();return}if(ue.kind==="floating"){ee.addFloatingGroup(le,{x:ue.position.left??24,y:ue.position.top??24,width:ue.position.width,height:ue.position.height}),delete I.current[J],he();return}delete I.current[J],he()},[he]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:ce,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:pe,resetAllPanelsToMain:xe,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const J=ie();J&&oe(J)},popoutActiveTab:()=>{const J=ie();J&&X(J)},dockActiveTab:()=>{const J=ie();J&&(re(J)?de(J):V(J)&&ke(J))},splitActiveTabRight:()=>q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>q("left"),moveActiveTabToRightPane:()=>q("right"),moveActiveTabToUpPane:()=>q("above"),moveActiveTabToDownPane:()=>q("below")}),()=>f==null?void 0:f(null)),[G,ke,oe,Z,ie,V,re,q,de,X,f,xe,Fe,pe,ce]),l.useEffect(()=>()=>{var J;(J=T.current)==null||J.call(T),T.current=null},[]);const Ie=l.useCallback(J=>{var le,ue;C.current=J.api,(le=T.current)==null||le.call(T),T.current=null;const ee=HS(v);if(B.current=(ee==null?void 0:ee.activeTabId)??null,ee!=null&&ee.layout&&J.api.fromJSON(ee.layout,{reuseExistingPanels:!1}),L.current=Uc({hasStoredLayout:!!(ee!=null&&ee.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:n}),L.current||(Vc(J.api,e),Yc(J.api,e,k)),J.api.totalPanels===0&&e.length>0){const ge=b1(J.api,e,y);if(ge){const Ae=J.api.getPanel(ge);Ae&&Be(Ae)}}else!L.current&&!Xe(y)&&dt();if(M.current=!0,J.api.onDidActivePanelChange(ge=>{var Pe;if(B.current=(ge==null?void 0:ge.id)??null,P.current=!0,Se(),ge&&rs(ge.id)){const Ne=((Pe=ge.params)==null?void 0:Pe.routeId)||ge.id.slice(7),He=cs(e,Ne);x((He==null?void 0:He.tabKey)??null),it();return}if(x((ge==null?void 0:ge.id)??null),it(),!ge)return;const Ae=$.get(ge.id);(Ae==null?void 0:Ae.streamSource)==="agent-stream"&&Ae.agentType&&N(Ae.routeId,Hu(),{agentType:Ae.agentType,...Ae.sessionId&&{targetSessionId:Ae.sessionId}}).catch(()=>{})}),J.api.onDidLayoutChange(()=>{it(),Se(),E(ge=>ge+1)}),m1()){const ge=_e=>({clientX:_e.clientX,clientY:_e.clientY}),Ae=_e=>{const Ue=_e==null?void 0:_e.getBoundingClientRect();return Ue?{left:Ue.left,right:Ue.right,top:Ue.top,bottom:Ue.bottom}:null},Pe=_e=>{var et;const Ue=(et=A.current)==null?void 0:et.getBoundingClientRect();return Ue?_e.clientX<Ue.left||_e.clientX>Ue.right||_e.clientY<Ue.top||_e.clientY>Ue.bottom:!1},Ne=p1({detachDelayMs:cp,onDetach:({panelId:_e,clientX:Ue,clientY:et})=>{var tt,qe;const se=J.api.getPanel(_e);if(!se)return;try{if(se.group.model.location.type!=="grid")return}catch{return}const be=(tt=A.current)==null?void 0:tt.getBoundingClientRect(),we=(qe=se.group.element)==null?void 0:qe.getBoundingClientRect(),ze=Math.round(Math.min(Math.max((we==null?void 0:we.width)??600,360),720)),We=Math.round(Math.min(Math.max((we==null?void 0:we.height)??500,260),640));J.api.addFloatingGroup(se,{x:be?Math.max(0,Ue-be.left-32):void 0,y:be?Math.max(0,et-be.top-18):void 0,width:ze,height:We}),se.api.setActive(),it(),Se(),E(Ye=>Ye+1)}}),He=[J.api.onWillDragPanel(_e=>{if(!(_e.nativeEvent.defaultPrevented||_e.nativeEvent.shiftKey)){try{if(_e.panel.group.model.location.type!=="grid")return}catch{return}Ne.startDrag({panelId:_e.panel.id,selfPanelBounds:Ae(_e.panel.group.element),...ge(_e.nativeEvent)})}}),J.api.onWillShowOverlay(_e=>{if(Ne.hasDetached()){_e.preventDefault();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onWillDrop(_e=>{if(Ne.hasDetached()){_e.preventDefault(),Ne.endDrag();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onDidDrop(()=>Ne.endDrag()),J.api.onUnhandledDragOverEvent(_e=>{Ne.isDragging()&&Ne.markSelfPanel(ge(_e.nativeEvent))})],Ke=_e=>{if(!Ne.isDragging())return;const Ue=ge(_e);Pe(Ue)&&Ne.markNonSelfPanel(Ue)},Ze=()=>Ne.endDrag();window.addEventListener("dragover",Ke,!0),window.addEventListener("drop",Ze,!0),window.addEventListener("dragend",Ze,!0),T.current=()=>{Ne.dispose();for(const _e of He)_e.dispose();window.removeEventListener("dragover",Ke,!0),window.removeEventListener("drop",Ze,!0),window.removeEventListener("dragend",Ze,!0)}}J.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var Ae,Pe;try{const Ne=(Ae=ge.element)==null?void 0:Ae.ownerDocument;if(!Ne||Ne===document)return;(Pe=Ne.getElementById("dv-popout-window"))==null||Pe.classList.add("adhdev-dockview");const He=document.documentElement.getAttribute("data-theme");He&&Ne.documentElement.setAttribute("data-theme",He),Ne.body.className=document.body.className;const Ke=document.documentElement.getAttribute("style");Ke&&Ne.documentElement.setAttribute("style",Ke)}catch{}Se(),E(Ne=>Ne+1)})}),x(((ue=J.api.activePanel)==null?void 0:ue.id)??null)},[Be,Xe,$,n,u,v,x,it,y,k,N,Se,e]);l.useLayoutEffect(()=>{const J=C.current;if(!J||!M.current||L.current&&Uc({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:n}))return;L.current&&(L.current=!1);const ee=K.current,le=new Set(ee),ue=e.map(Ze=>Ze.tabKey),ge=new Set(ue),Ae=u1({previousVisibleConversationCount:ee.length,visibleConversationCount:e.length,ides:n});let Pe=!1;for(const Ze of ee)ge.has(Ze)||Ae||(I.current[Ze]=$e(Ze),Pe=!0);Pe&&he(),Ae||(Vc(J,e),Yc(J,e,k));const Ne=ue.filter(Ze=>!le.has(Ze));let He=!1;for(const Ze of Ne){const _e=J.getPanel(Ze),Ue=I.current[Ze];if(!_e||!Ue||Ue.kind==="grid")continue;if(_e.group.model.location.type===Ue.kind){delete I.current[Ze],He=!0;continue}if(Ue.kind==="floating"){J.addFloatingGroup(_e,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete I.current[Ze],He=!0;continue}}if(He&&he(),K.current=ue,y&&Xe(y))return;!J.activePanel&&J.panels[0]&&Be(J.panels[0]),!!(J.activePanel&&J.getPanel(J.activePanel.id))||dt()},[Be,Xe,dt,n,u,he,$e,y,k,e]),l.useEffect(()=>{M.current&&Xe(y)},[Xe,y]),l.useEffect(()=>{const J=le=>{const ue=le.target;if(!ue)return;const ge=ue.querySelector("[data-tab-key]")||ue.closest("[data-tab-key]");if(ge){const Ae=ge.getAttribute("data-tab-key");if(Ae&&le.dataTransfer){const Pe=ue.closest(".dv-tab")||ge.closest(".dv-tab")||ge;le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/tab-key",Ae),Pe instanceof HTMLElement&&le.dataTransfer.setDragImage(Pe,Math.max(12,Math.round(Pe.clientWidth/2)),Math.max(10,Math.round(Pe.clientHeight/2)))}}};window.addEventListener("dragstart",J);const ee=qc(C.current);for(const le of ee)le.addEventListener("dragstart",J);return()=>{window.removeEventListener("dragstart",J);for(const le of ee)le.removeEventListener("dragstart",J)}},[Q]),l.useEffect(()=>{var ee;const J=(ee=A.current)==null?void 0:ee.querySelector(".adhdev-dockview");J instanceof HTMLElement&&va(J,g),z(),Se()},[Se,z,g]),l.useEffect(()=>{Se()},[Se]),l.useEffect(()=>{const J=ee=>{if(ee.defaultPrevented||_)return;const le=H(ee);if(!le)return;const ue=ee.metaKey||ee.ctrlKey||ee.altKey;mi(ee.target)&&!ue||yo(me).setActiveTabShortcut!==le||(ee.preventDefault(),ee.stopPropagation(),ce())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[H,me,_,ce]),l.useEffect(()=>{const J=A.current;if(!J)return;const ee=le=>{var Ne,He;if(!le.isTrusted)return;const ue=(He=(Ne=le.target)==null?void 0:Ne.closest)==null?void 0:He.call(Ne,".dv-scrollable");if(!ue)return;le.preventDefault(),le.stopPropagation();const ge=Math.abs(le.deltaX),Ae=Math.abs(le.deltaY),Pe=ge>Ae?le.deltaX:le.deltaY;ue.dispatchEvent(new WheelEvent("wheel",{deltaY:Pe,deltaMode:le.deltaMode,bubbles:!1,cancelable:!0}))};return J.addEventListener("wheel",ee,{passive:!1,capture:!0}),()=>J.removeEventListener("wheel",ee,{capture:!0})},[]),l.useEffect(()=>{const J=qc(C.current);if(J.length===0)return;const ee=J.map(le=>{let ue=[],ge=null;const Ae=()=>{ge!=null&&le.clearTimeout(ge),ge=null,ue=[]},Pe=()=>{ge!=null&&le.clearTimeout(ge),ge=le.setTimeout(()=>{ge=null,ue=[]},1200)},Ne=Ke=>{if(!Ke.ctrlKey&&!Ke.metaKey&&!Ke.altKey)return;const Ze=H(Ke);if(!Ze)return;const _e=np();for(const[Ue,et]of Object.entries(_e))if(e.some(se=>se.tabKey===Ue)&&et===Ze){Ke.preventDefault(),pe(Ue);return}},He=Ke=>{if(Ke.defaultPrevented||_)return;const Ze=H(Ke);if(!Ze)return;const _e=Ke.metaKey||Ke.ctrlKey||Ke.altKey;if(mi(Ke.target))return;const Ue=yo(me),et=Object.entries(Ue).filter(([Ye,Tt])=>!!Tt&&(Ye==="splitActiveTabRight"||Ye==="splitActiveTabDown"||Ye==="floatActiveTab"||Ye==="popoutActiveTab"||Ye==="dockActiveTab"||Ye==="focusLeftPane"||Ye==="focusRightPane"||Ye==="focusUpPane"||Ye==="focusDownPane"||Ye==="moveActiveTabToLeftPane"||Ye==="moveActiveTabToRightPane"||Ye==="moveActiveTabToUpPane"||Ye==="moveActiveTabToDownPane"||Ye==="selectPreviousGroupTab"||Ye==="selectNextGroupTab"||Ye==="setActiveTabShortcut"||Ye==="hideCurrentTab")),se=_e?[Ze]:[...ue.slice(-1),Ze].slice(-2),be=se.join(" "),we=se[se.length-1],ze=et.find(([,Ye])=>Ye===be);if(ze){Ke.preventDefault(),Ae(),fe(ze[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${be} `))){Ke.preventDefault(),ue=se,Pe();return}const tt=et.find(([,Ye])=>Ye===we);if(tt){Ke.preventDefault(),Ae(),fe(tt[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${we} `))){Ke.preventDefault(),ue=[we],Pe();return}Ae()};return le.addEventListener("keydown",Ne),le.addEventListener("keydown",He),()=>{Ae(),le.removeEventListener("keydown",Ne),le.removeEventListener("keydown",He)}});return()=>{for(const le of ee)le()}},[H,me,Q,pe,_,fe,e]);const ye=g==="light"?Fa:Ha,Oe=((ht=(at=(ut=C.current)==null?void 0:ut.activePanel)==null?void 0:at.group.element)==null?void 0:ht.ownerDocument)??document;return s.jsxs(up.Provider,{value:je,children:[s.jsx("div",{ref:A,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(jm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:k1,remote:x1},defaultTabComponent:v1,watermarkComponent:y1,onReady:Ie,singleTabMode:"default",tabAnimation:"smooth",theme:ye,popoutUrl:"/popout.html"})}),F&&fn.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:F.x,top:F.y},children:Ce.map(J=>{if(J.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},J.id);let ee=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{};switch(J.id){case"dockInWindow":case"dockBackToGrid":ee=s.jsx(Qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ke(F.tabKey),R(null)};break;case"moveBackToMain":ee=s.jsx(Vf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{de(F.tabKey),R(null)};break;case"floatAsPanel":ee=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{oe(F.tabKey),R(null)};break;case"openInNewWindow":ee=s.jsx(qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{X(F.tabKey),R(null)};break;case"setShortcut":le=ue=>{ue.stopPropagation(),te(F.tabKey),R(null)};break;case"removeShortcut":ee=s.jsx(At,{size:13,className:"shrink-0 opacity-70"}),le=()=>{const ue={...Te};delete ue[F.tabKey],ve(ue),R(null)};break;case"hideTab":ee=s.jsx(Ti,{size:13,className:"shrink-0 opacity-70"}),le=()=>{W(F.tabKey),R(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${J.tone==="muted"?"text-text-muted":""}`,onMouseDown:w1,onClick:le,children:[ee,s.jsx("span",{className:"flex-1 min-w-0",children:J.label}),J.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:J.shortcut}):null]},J.id)})}),F.sourceDocument.body),_&&fn.createPortal(s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>te(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:J=>J.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. ",me?"⌘+1":"Ctrl+1",", ",me?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Oe.body)]})}const hp="adhdev-recent-launch-args-v1",C1=8;function j1(e){return String(e||"").trim().replace(/\s+/g," ")}function pp(e,t){return`${e.trim()}::${t.trim()}`}function mp(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(hp)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function N1(e){if(!(typeof window>"u"))try{window.localStorage.setItem(hp,JSON.stringify(e))}catch{}}function A1(e,t){var a;const n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?[]:((a=mp().byKey[pp(n,r)])==null?void 0:a.items)||[]}function T1(e,t,n){var d;const r=String(e||"").trim(),o=String(t||"").trim(),a=j1(n);if(!r||!o||!a)return;const i=mp(),c=pp(r,o),u=((d=i.byKey[c])==null?void 0:d.items)||[],h=[a,...u.filter(m=>m!==a)].slice(0,C1);i.byKey[c]={items:h},N1(i)}function I1(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vn({title:e,description:t,action:n,children:r,className:o="",contentClassName:a=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),n?s.jsx("div",{className:"flex items-center gap-2",children:n}):null]}),r?s.jsx("div",{className:t||n?`mt-3 ${a}`.trim():a,children:r}):null]})}function M1({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:n=0}){return e?"Refreshing saved history…":t?n>0?`${n} saved ${n===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function D1({busy:e,savedSessionsLoading:t,savedSessionsError:n,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const{t:h}=Le("common"),d=a?Qh(a):null,m=M1({savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o});return s.jsxs(Vn,{title:"Saved history",description:zi(h),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Q0(h)})]}),children:[d?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:d.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:d.providerSessionId}),s.jsx("div",{className:"mt-1",children:d.metaLine}),d.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:d.updatedLabel}),d.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:d.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),n&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:n})]})}function fp({setup:e,providerName:t,className:n=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${n}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const wa={cli:"CLI",ide:"IDE",acp:"ACP"};function P1({workspaceMode:e,activeKind:t,cliEnabled:n,ideEnabled:r,acpEnabled:o,busy:a,onSelect:i}){const{t:c}=Le();return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:c("newSession.category")}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:wa.cli,enabled:n},{id:"ide",label:wa.ide,enabled:r},{id:"acp",label:wa.acp,enabled:o}].map(u=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===u.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(u.id),disabled:!u.enabled||a,children:u.label},u.id))})]})}function ka(e){var r;if(!e)return null;const t=e.availableProviders||[];return t.some(o=>Sn(o,"cli"))?"cli":(((r=e.detectedIdes)==null?void 0:r.length)||0)>0?"ide":t.some(o=>Sn(o,"acp"))?"acp":null}function _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function L1({machines:e,ides:t,onClose:n,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:h}){var jt,Ot;const{t:d}=Le(),m=In(),f=l.useMemo(()=>[...e].sort(Ei),[e]),[x,w]=l.useState(((jt=f[0])==null?void 0:jt.id)||""),p=l.useMemo(()=>f.find(ne=>ne.id===x)||f[0],[x,f]),y=l.useMemo(()=>((p==null?void 0:p.workspaces)||[]).map(ne=>({id:ne.id,path:ne.path,label:ne.label})),[p]),k=(p==null?void 0:p.defaultWorkspaceId)||null,[b,j]=l.useState("workspace"),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState([]),[T,M]=l.useState(""),[L,P]=l.useState(!1),[B,K]=l.useState(null),[F,R]=l.useState(""),[Q,E]=l.useState(ka(f[0])),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState(""),[z,X]=l.useState(""),[de,re]=l.useState(!1),[W,oe]=l.useState([]),[V,ie]=l.useState(""),[ke,xe]=l.useState([]),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),[Z,q]=l.useState(""),[me,Te]=l.useState(!1),[_,te]=l.useState(()=>Ft()),[ve,ce]=l.useState(null),[H,fe]=l.useState(!1),[je,Ce]=l.useState(""),[Be,Xe]=l.useState("error"),[dt,it]=l.useState(null),[he,$e]=l.useState(!1),[Fe,Ie]=l.useState(""),[ye,Oe]=l.useState([]),[ut,at]=l.useState(!1),[ht,J]=l.useState(""),[ee,le]=l.useState(!1),ue=l.useRef(null),ge=l.useRef(0);l.useEffect(()=>{var ne;!x&&((ne=f[0])!=null&&ne.id)&&w(f[0].id)},[x,f]),l.useEffect(()=>{!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||m(p.id,{minFreshMs:3e4}).catch(()=>{})},[m,p]);const Ae=l.useCallback(ne=>{ne&&m(ne,{minFreshMs:3e4}).catch(()=>{})},[m]),Pe=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"cli")),[p]),Ne=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"acp")),[p]),He=l.useMemo(()=>((p==null?void 0:p.detectedIdes)||[]).map(ne=>({id:ne.type,label:ne.name||ne.type,meta:ne.running?d("newSession.detectedLocally"):d("newSession.availableToOpen")})),[p,d]),Ke=l.useMemo(()=>Q==="cli"?Pe.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):Q==="acp"?Ne.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):He,[Ne,Q,Pe,He]),Ze=l.useMemo(()=>C.find(ne=>ne.id===T)||null,[C,T]),_e=l.useMemo(()=>Pe.find(ne=>ne.type===I)||null,[Pe,I]),Ue=l.useMemo(()=>[...Pe,...Ne].find(ne=>ne.type===I),[Pe,Ne,I]),et=l.useMemo(()=>ck(Ue?[Ue]:[],Ue==null?void 0:Ue.type),[Ue]),se=l.useMemo(()=>{const ne=dk(Ue?[Ue]:[],Ue==null?void 0:Ue.type);return ne.length?ne:["low","medium","high"]},[Ue]),be=l.useMemo(()=>Kh(_e==null?void 0:_e.meshCoordinator,{meshId:(Ze==null?void 0:Ze.id)||"",workspace:(Ze==null?void 0:Ze.workspace)||""}),[_e,Ze]),we=dt||be,ze=l.useCallback(async ne=>{P(!0),R("");try{const Ge=await c(ne);A(Ge),M(Ee=>{var vt;return Ge.some(Jt=>Jt.id===Ee)?Ee:((vt=Ge[0])==null?void 0:vt.id)||""}),K(ne)}catch(Ge){A([]),M(""),K(ne),R(Ge instanceof Error?Ge.message:d("newSession.errorLoadMeshes"))}finally{P(!1)}},[c,d]);l.useEffect(()=>{var Ge;if(!p)return;if(ue.current!==p.id){ue.current=p.id,j("workspace"),v(k||((Ge=y[0])==null?void 0:Ge.id)||"__home__"),N(""),A([]),M(""),K(null),R(""),E(ka(p)),$(""),U(""),ae(""),X(""),re(!1),ie(""),xe([]),O(!1),q(""),te(Ft()),Ce(""),it(null);return}v(Ee=>{var vt;return Ee==="__custom__"||Ee==="__home__"||y.some(Jt=>Jt.id===Ee)?Ee:k||((vt=y[0])==null?void 0:vt.id)||"__home__"}),E(Ee=>Ee==="ide"&&He.length>0||Ee==="cli"&&Pe.length>0||Ee==="acp"&&Ne.length>0?Ee:ka(p))},[Ne.length,Pe.length,k,He.length,p,y]),l.useEffect(()=>{!p||b!=="mesh"||B===p.id||L||ze(p.id)},[ze,B,L,p,b]),l.useEffect(()=>{b==="mesh"&&Q!=="cli"&&Pe.length>0&&E("cli")},[Q,Pe.length,b]),l.useEffect(()=>{var ne;Q&&(Ke.some(Ge=>Ge.id===I)||$(((ne=Ke[0])==null?void 0:ne.id)||""))},[Q,Ke,I]),l.useEffect(()=>{it(null)},[p==null?void 0:p.id,T,I,b]),l.useEffect(()=>{ae(""),X(""),re(!1)},[I]);const We=l.useCallback(async(ne,Ge)=>{const Ee=ge.current+1;return ge.current=Ee,pe(!0),q(""),h(ne,Ge).then(vt=>{ge.current===Ee&&xe(vt)}).catch(vt=>{ge.current===Ee&&(xe([]),q(vt instanceof Error?vt.message:d("newSession.errorLoadSavedSessions")))}).finally(()=>{ge.current===Ee&&(pe(!1),O(!0))})},[h,d]),tt=l.useCallback((ne,Ge)=>{oe(A1(ne,Ge))},[]);l.useEffect(()=>{ge.current+=1,ie(""),te(Ft()),!p||!I||Q==="ide"?oe([]):tt(p.id,I),O(!1),xe([]),q(""),pe(!1)},[Q,tt,We,p,I]),l.useEffect(()=>{if(!V)return;const ne=ke.find(Ge=>Ge.providerSessionId===V);ne!=null&&ne.canResume||ie("")},[ke,V]);const qe=S==="__custom__"?g.trim():S==="__home__"?"":((Ot=y.find(ne=>ne.id===S))==null?void 0:Ot.path)||"",Ye=l.useMemo(()=>p?t.filter(ne=>ne.id!==p.id&&ne.daemonId===p.id).map(ne=>ne.workspace):[],[t,p]),Tt=l.useMemo(()=>((p==null?void 0:p.recentLaunches)||[]).map(ne=>ne.workspace),[p]),Wt=l.useCallback(ne=>{const Ge=String(ne.workspace||"").trim();if(!Ge)return;const Ee=y.find(vt=>_r(vt.path)===_r(Ge));if(Ee){v(Ee.id),N("");return}v("__custom__"),N(Ge)},[y]),ss=l.useCallback(ne=>{const Ge=String(ne.workspace||"").trim();if(!Ge)return{workspaceId:null,workspacePath:null};const Ee=y.find(vt=>_r(vt.path)===_r(Ge));return Ee?{workspaceId:Ee.id,workspacePath:null}:{workspaceId:null,workspacePath:Ge}},[y]),Me=l.useMemo(()=>ke.find(ne=>ne.providerSessionId===V)||null,[ke,V]),Qe=l.useMemo(()=>{var Ge;if(Q!=="cli"||!p||!I)return null;const ne=((Ge=Pe.find(Ee=>Ee.type===I))==null?void 0:Ge.displayName)||I;return{routeId:p.id,daemonId:p.id,providerSessionId:V||void 0,transport:"pty",mode:"chat",agentName:ne,agentType:I,status:"idle",title:ne,messages:[],ideType:I,workspaceName:qe,workspacePath:qe,displayPrimary:ne,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${p.id}:${I}`,machineName:ts(p,{fallbackId:p.id})}},[Q,Pe,qe,p,V,I]),Dt=l.useCallback(()=>{var Ge;if(!p)return;v("__custom__"),$e(!0),J("");const ne=tl(p.platform,el(g.trim(),qe,Ye,Tt,p.defaultWorkspacePath,(Ge=y.find(Ee=>Ee.id===k))==null?void 0:Ge.path,y.map(Ee=>Ee.path)));at(!0),r(p.id,ne).then(Ee=>{Ie(Ee.path),N(Ee.path),Oe(Ee.directories)}).catch(Ee=>{J(Ee instanceof Error?Ee.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1))},[g,k,Tt,Ye,r,qe,p,y]),It=l.useCallback(ne=>{p&&(at(!0),J(""),r(p.id,ne).then(Ge=>{Ie(Ge.path),N(Ge.path),Oe(Ge.directories)}).catch(Ge=>{J(Ge instanceof Error?Ge.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1)))},[r,p]),qt=l.useCallback(async()=>{if(!p||!qe)return;le(!0),Ce("");const ne=await o(p.id,qe);if(le(!1),!ne.ok){Xe("error"),Ce(ne.error||d("newSession.errorSaveWorkspace"));return}Xe("info"),Ce(d("newSession.workspaceSaved"))},[o,qe,p,d]),Vt=l.useCallback(async()=>{if(!p)return;if(b==="mesh"){if(!T||!I)return;fe(!0),Ce(""),it(null);const Ee=await u(p.id,T,I,{initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ee.ok){if(Ee.code==="mesh_coordinator_manual_mcp_setup_required"&&Ee.manualSetup){it(Ee.manualSetup),Xe("info"),Ce(d("newSession.errorManualMcpSetup"));return}Xe("error"),Ce(Ee.error||d("newSession.errorStartMeshCoordinator"));return}n();return}if(!Q||!I)return;fe(!0),Ce("");const ne=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Ge=Q==="ide"?await a(p.id,I,{workspacePath:qe||null}):await i(p.id,Q,I,{workspaceId:S!=="__home__"&&S!=="__custom__"?S:null,workspacePath:S==="__custom__"&&qe||null,resumeSessionId:Q==="cli"&&V?V:null,cliArgs:ne,initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ge.ok){Xe("error"),Ce(Ge.error||d("newSession.errorStartSession"));return}Q!=="ide"&&D.trim()&&(T1(p.id,I,D),tt(p.id,I)),n()},[Q,D,Y,z,tt,n,a,u,i,qe,p,T,V,I,S,b,d]),Yt=Q==="cli"&&!!V,xs=d(b==="mesh"?"newSession.startMeshCoordinator":Q==="cli"?Yt?"newSession.resumeSavedHistory":"newSession.startFresh":Q==="ide"?"newSession.startIde":Q==="acp"?"newSession.startAcpSession":"newSession.start"),Re=d(b==="mesh"?"newSession.startingCoordinator":Q==="cli"?Yt?"newSession.resumingSavedHistory":"newSession.startingFresh":Q==="ide"?"newSession.startingIde":Q==="acp"?"newSession.startingAcpSession":"newSession.starting"),rt=f.length>5;return p?s.jsxs(s.Fragment,{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":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] 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-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsx("div",{className:"min-w-0",children:s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:d("newSession.title")})}),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:n,"aria-label":d("newSession.close"),children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 space-y-4",children:[f.length>1&&s.jsx(Vn,{title:d("newSession.machine"),children:rt?s.jsx("select",{"aria-label":d("newSession.machine"),value:p.id,onChange:ne=>w(ne.target.value),onFocus:()=>f.forEach(ne=>Ae(ne.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:f.map(ne=>s.jsx("option",{value:ne.id,children:ts(ne,{fallbackId:ne.id})},ne.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":d("newSession.machine"),children:f.map(ne=>{const Ge=ts(ne,{fallbackId:ne.id}),Ee=p.id===ne.id;return s.jsxs("button",{type:"button","aria-label":d("newSession.selectMachine",{name:Ge}),"aria-pressed":Ee,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Ee?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>w(ne.id),onMouseEnter:()=>Ae(ne.id),onFocus:()=>Ae(ne.id),disabled:H,title:Ge,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ne.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ge})]},ne.id)})})}),s.jsxs(Vn,{title:d("newSession.workspace"),action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:d("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":d("newSession.launchTargetType"),children:[{id:"workspace",label:d("newSession.modeWorkspace"),desc:d("newSession.modeWorkspaceDesc")},{id:"mesh",label:d("newSession.modeMesh"),desc:d("newSession.modeMeshDesc")}].map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===ne.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===ne.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{j(ne.id),Ce(""),ne.id==="mesh"&&p&&B!==p.id&&!L&&ze(p.id)},disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold",children:ne.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ne.desc})]},ne.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:S,onChange:ne=>{const Ge=ne.target.value;v(Ge),Ge==="__custom__"?Dt():Ce("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:[s.jsx("option",{value:"__home__",children:d("newSession.homeDirectory")}),y.map(ne=>s.jsxs("option",{value:ne.id,children:[ne.id===k?"⭐ ":"",xu(ne.path,ne.label)||ne.path]},ne.id)),s.jsx("option",{value:"__custom__",children:d("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:S==="__home__"?d("newSession.launchWithoutWorkspace"):qe||d("newSession.selectWorkspaceFolder")}),S==="__custom__"&&qe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:[s.jsx(xn,{size:14}),d("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qt,disabled:H||ee,children:d(ee?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.loadingMeshes")}),!L&&F&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:F}),!L&&!F&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:d("newSession.noMeshes")}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":d("newSession.mesh"),children:C.map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":T===ne.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${T===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ne.repoIdentity||d("newSession.repoMesh"),typeof ne.nodesCount=="number"?` · ${d("newSession.nodeCount",{count:ne.nodesCount})}`:""]}),ne.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:d("newSession.coordinatorWorkspace",{path:ne.workspace})})]},ne.id))})]})]}),s.jsx(P1,{workspaceMode:b,activeKind:Q,cliEnabled:Pe.length>0,ideEnabled:He.length>0,acpEnabled:Ne.length>0,busy:H,onSelect:E}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:d(Q==="ide"?"newSession.chooseIde":Q==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ke.map(ne=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.label}),ne.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ne.meta})]},ne.id)),Ke.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.noProviders")})]})]}),b==="mesh"&&we&&s.jsx(fp,{setup:we,providerName:(_e==null?void 0:_e.displayName)||(_e==null?void 0:_e.name)||I}),b!=="mesh"&&Q!=="ide"&&s.jsxs(Vn,{title:d("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:D,onChange:ne=>U(ne.target.value),placeholder:d("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H}),W.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:W.map(ne=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(ne),disabled:H,title:ne,children:ne},ne))})]}),(b==="mesh"&&!!I||b!=="mesh"&&Q!=="ide")&&s.jsx(Vn,{title:d("newSession.modelAndThinking"),children:s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.model")}),et.length>0&&!de?s.jsxs("select",{value:et.includes(Y)?Y:"",onChange:ne=>{ne.target.value==="__custom__"?(re(!0),ae("")):ae(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),et.map(ne=>s.jsx("option",{value:ne,children:ne},ne)),s.jsx("option",{value:"__custom__",children:d("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:Y,onChange:ne=>ae(ne.target.value),placeholder:d("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,autoFocus:de}),et.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{re(!1),ae("")},disabled:H,children:d("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.thinkingLevel")}),s.jsxs("select",{value:z,onChange:ne=>X(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),se.map(ne=>s.jsx("option",{value:ne,children:ne},ne))]})]})]})}),b!=="mesh"&&Q==="cli"&&s.jsx(D1,{busy:H,savedSessionsLoading:Se,savedSessionsError:Z,selectedSession:Me,onRefresh:()=>{!p||!I||We(p.id,I)},onOpenHistory:()=>{!p||!I||(Te(!0),I1({hasLoadedInitialResults:G,isLoading:Se})&&We(p.id,I))},onClearSelection:()=>ie("")}),je&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Be==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:je})]}),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:n,disabled:H,children:d("common.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:Vt,disabled:H||(b==="mesh"?!T||!I||Q!=="cli"||L:!Q||!I||S==="__custom__"&&!qe),children:[s.jsx(Qd,{size:14}),H?Re:xs]})]})]})}),he&&s.jsx(rl,{title:d("newSession.selectWorkspaceTitle"),description:d("newSession.selectWorkspaceDescription"),currentPath:Fe,directories:ye,busy:ut,error:ht,onClose:()=>$e(!1),onNavigate:It,onConfirm:ne=>{N(ne),Ie(ne),v("__custom__"),$e(!1)}}),me&&Qe&&s.jsx(bh,{activeConv:Qe,ides:[],isCreatingChat:!1,isRefreshingHistory:Se,savedSessions:ke,isSavedSessionsLoading:Se,isResumingSavedSessionId:ve,savedHistoryFilters:_,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:te,onClose:()=>Te(!1),onNewChat:()=>{ie(""),Te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!p||!I||We(p.id,I)},onResumeSavedSession:ne=>{if(!p||!I||ve||!ne.canResume)return;const Ge=ss(ne);ie(ne.providerSessionId),Wt(ne),ce(ne.providerSessionId),Te(!1),fe(!0),Ce(""),i(p.id,"cli",I,{workspaceId:Ge.workspaceId,workspacePath:Ge.workspacePath,resumeSessionId:ne.providerSessionId}).then(Ee=>{if(!Ee.ok){Xe("error"),Ce(Ee.error||d("newSession.errorResumeSession"));return}n()}).finally(()=>{fe(!1),ce(Ee=>Ee===ne.providerSessionId?null:Ee)})}})]}):null}function bp(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function al(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const n=bp(e);return n?{label:n,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function il(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function gp(e){var t;return!il(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function $r(e){return[...new Set(e.filter(t=>!!t))]}function R1(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,n=(t==null?void 0:t.branch)??null,r=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!n&&i.branch===n),o=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),a=e.nodes.filter(i=>i.type!=="submoduleNode");return t||r.length>0?$r([t==null?void 0:t.id,...r.map(i=>i.id)]):o.length>0?$r(o.map(i=>i.id)):a.length>0?$r(a.map(i=>i.id)):$r(e.nodes.map(i=>i.id))}function xp(e){const t=[...e.nodes].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.type,r.branch??"",r.parentNodeId??"",r.submodulePath??""].join(":")).join("|"),n=[...e.edges].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.source,r.target,r.type].join(":")).join("|");return`${e.meshId}::${t}::${n}`}function E1(e,t,n){const r=Math.max(0,Math.round(t)),o=Math.max(0,Math.round(n));return`${xp(e)}::${r}x${o}`}const _1={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},$1={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},B1={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},F1={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Rs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[rgba(15,23,42,0.82)] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>$1[t],actionButton:t=>F1[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[#030617]/[0.92] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>_1[t],actionButton:t=>B1[t]}}const Cn={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},xr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},H1={maxWidth:180};function W1(e){return e==="TB"?"DOWN":"RIGHT"}function ll(e,t){return{"elk.algorithm":"layered","elk.direction":W1(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"}}const O1=ll(Cn,"LR");ll(xr,"LR");function U1(e){const t=e.nodes.length;if(t<8)return"LR";const n=new Map;for(const o of e.edges)n.set(o.source,(n.get(o.source)??0)+1);let r=0;for(const o of n.values())o>r&&(r=o);return r>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const G1=new Nm;function ur(e,t=!1){const n=t?xr:Cn;return e.type==="submoduleNode"?n.submoduleCardWidth:n.worktreeCardWidth}function Qr(e){var n;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const r=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?r.push("out of sync"):e.dirty?r.push("local changes"):r.push("synced"),r.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const r=bp(e);r&&t.push(r)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(n=e.branchConvergence)!=null&&n.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function yp(e,t=!1){const n=t?xr:Cn,r=ur(e,t),o=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,a=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(K1(e)/a),c=Br(e.label,o,2),u=Br(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,o,2),h=Br(Qr(e),o+(t?1:4),t?2:3),d=al(e),m=gp(e)?il(e):null,f=t?0:Br(m,Math.max(24,Math.floor(r/8)),4),x=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,h*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,h*18)+(f>0?22+f*16:0),w=e.type==="submoduleNode"?n.minSubmoduleCardHeight:n.minWorktreeCardHeight;return Math.min(n.maxEstimatedCardHeight,Math.max(w,Math.ceil(x)))}function Br(e,t,n){const r=(e||"").trim();return r?Math.max(1,Math.min(n,Math.ceil(r.length/t))):0}function K1(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function z1(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function q1(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function V1(e,t,n,r=!0){return{id:e.id,type:"meshNode",position:{x:t,y:n},graphNode:e,selected:!1,draggable:!1,selectable:r}}function Y1(e,t,n){return{id:e.id,x:t,y:n,width:ur(e),height:yp(e)}}function J1(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function vp(e){const t=[...e.nodes].sort(z1),n=t.find(o=>o.type==="defaultBranchNode")??null,r=t.some(o=>o.id!==(n==null?void 0:n.id)&&o.type!=="submoduleNode");return!n||r?t:[...t,J1(n,e)]}function Q1(e,t=O1,n=!1,r="LR"){const o=vp(e),a=new Set(o.map(u=>u.id)),i=o.map(u=>({id:u.id,width:ur(u,n),height:yp(u,n)})),c=e.edges.filter(u=>a.has(u.source)&&a.has(u.target)).sort(q1).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function X1(e,t=!1){const n=[...new Set(e.map(o=>Math.round(o.x)))].sort((o,a)=>o-a),r=t?xr.layerGap:Cn.layerGap;return n.length<2?r:Math.min(...n.slice(1).map((o,a)=>o-n[a]))}async function wp(e,t=!1,n="LR",r){var w,p;const a=ll(t?xr:Cn,n),i=vp(e),c=new Map(i.map(y=>[y.id,y])),u=Q1(e,a,t,n);if(r&&r.size>0)for(const y of u.children??[]){const k=r.get(y.id);k&&k>0&&(y.height=k)}const h=await G1.layout(u),d=(h.children??[]).map(y=>{const k=c.get(y.id);return k?V1(k,Math.round(y.x??0),Math.round(y.y??Cn.placeholderTopOffset),!y.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((y,k)=>[y.id,k]));d.sort((y,k)=>(m.get(y.id)??0)-(m.get(k.id)??0));const f=d.map(y=>Y1(y.graphNode,y.position.x,y.position.y)),x=new Map;for(const y of h.edges??[]){const k=y.sections;if(!k||k.length===0)continue;const b=k[0],j=(w=y.sources)==null?void 0:w[0],S=(p=y.targets)==null?void 0:p[0];if(!j||!S)continue;const v=[];v.push({x:Math.round(b.startPoint.x),y:Math.round(b.startPoint.y)});for(const g of b.bendPoints??[])v.push({x:Math.round(g.x),y:Math.round(g.y)});v.push({x:Math.round(b.endPoint.x),y:Math.round(b.endPoint.y)}),x.set(y.id,{id:y.id,source:j,target:S,points:v})}return{nodes:d,bounds:f,edgeRoutes:x,columnGap:X1(f,t),layoutOptions:{...a}}}function Z1(e){var t,n;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(r=>[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.role??"",r.isSelfCoordinator?1:0,r.statusNote??"",r.startedAt??"",r.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(n=e.branchConvergence)!=null&&n.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function kp(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function ej(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Z1),...e.edges.map(kp)].join("::")}function tj(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var n,r;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((n=t.branchConvergence)==null?void 0:n.status)??"",(r=t.branchConvergence)!=null&&r.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(kp)].join("::")}const sj=5*60*1e3;function Sp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Cp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function nj(e){var t,n,r;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((n=e.connection)==null?void 0:n.transport)==="direct"||((r=e.connection)==null?void 0:r.transport)==="relay"||Sp(e)||Cp(e)?"remote":"unknown"}function rj(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const n=t.rttMs,r=typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:r}}function jp(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const n=e.connectionState;return n==="connecting"?"connecting":n==="disconnected"?"disconnected":n==="failed"?"failed":n==="closed"?"closed":null}function oj(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=jp(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function aj(e){return Fi(e)}function Np(e){var t;return aj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Ap(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ij(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Tp(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Ip(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function cl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function lj(e){return cl(e)?"degraded":Ip(e)?"dirty":"online"}function cj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Qc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function Sa(e){return e.length===0?"unknown":e.reduce((t,n)=>Qc(n)>Qc(t)?n:t)}function dj(e){var a,i,c,u,h;const t=new Map,n=new Map;for(const d of e){const m=(i=(a=d.git)==null?void 0:a.branch)==null?void 0:i.trim();m&&(n.set(m,(n.get(m)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const r=[...t.entries()].sort((d,m)=>{if(m[1]!==d[1])return m[1]-d[1];const f=["main","master","develop","dev"],x=f.indexOf(d[0]),w=f.indexOf(m[0]);return x!==-1||w!==-1?x===-1?1:w===-1?-1:x-w:d[0].localeCompare(m[0])});return(u=r[0])!=null&&u[0]?r[0][0]:((h=[...n.entries()].sort((d,m)=>m[1]-d[1])[0])==null?void 0:h[0])??null}function uj(e,t){const n=[],r=e.git;return r?r.isGitRepo?(!r.branch&&r.headCommit&&n.push("Detached HEAD"),r.hasConflicts&&n.push("Merge conflicts need resolution"),r.branch&&t&&r.branch!==t&&!r.upstream&&n.push(`No upstream tracking for ${r.branch}`),r.upstream&&r.upstreamStatus&&r.upstreamStatus!=="fresh"&&n.push(`Upstream freshness unverified for ${r.branch??"workspace"}`),e.error&&n.push(e.error),n):(n.push("Not a git repository"),n):(n.push("No git status available"),n)}function Xc(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function hj(e){return e.reduce((t,n)=>Xc(n.status)>Xc(t.status)?n:t)}function pj(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const n=e.followUps;return Array.isArray(n)?n:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function mj(e){var o,a,i;const t=e.sourceOfTruth,n=[],r=(o=t==null?void 0:t.fallback)==null?void 0:o.warning;return typeof r=="string"&&r.trim()&&n.push(r.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((a=t.directPeerTruth)==null?void 0:a.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!n.some(c=>c.includes("direct mesh truth"))&&n.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),n}function fj(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(!r||typeof r!="object")continue;const o=r,a=typeof o.jobId=="string"?o.jobId:null,i=o.status;a&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||n.push({jobId:a,status:i,nodeId:typeof o.nodeId=="string"?o.nodeId:void 0,targetNodeId:typeof o.targetNodeId=="string"?o.targetNodeId:void 0,workspace:typeof o.workspace=="string"?o.workspace:void 0,branch:typeof o.branch=="string"?o.branch:void 0,into:typeof o.into=="string"?o.into:void 0,lastUpdatedAt:typeof o.lastUpdatedAt=="string"?o.lastUpdatedAt:void 0,startedAt:typeof o.startedAt=="string"?o.startedAt:void 0,completedAt:typeof o.completedAt=="string"?o.completedAt:void 0}))}return n}function Zc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function ed(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Ap(t)??0}function bj(e){return e.length===0?null:e.reduce((t,n)=>{const r=Zc(t.status),o=Zc(n.status);return o!==r?o<r?n:t:ed(n)>ed(t)?n:t})}function gj(e){var n,r;const t=new Map;for(const o of e){const a=((n=o.nodeId)==null?void 0:n.trim())||((r=o.targetNodeId)==null?void 0:r.trim());if(!a)continue;const i=t.get(a)??[];i.push(o),t.set(a,i)}return t}function xj(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function yj(e,t){var n,r;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((n=t.find(o=>o.upstream))==null?void 0:n.upstream)??null,upstreamStatus:((r=t.find(o=>o.upstreamStatus))==null?void 0:r.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function vj(e,t){if(Np(e))return null;const n=e.branchConvergence;if(!n||typeof n!="object")return null;const r=n.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const o=e.git,a=Tp(o)||Ip(o),i=!!(o!=null&&o.hasConflicts)||cl(o),c=(o==null?void 0:o.ahead)??0,u=(o==null?void 0:o.behind)??0,h=(o==null?void 0:o.branch)??null,d=(o==null?void 0:o.upstream)??null,m=(o==null?void 0:o.upstreamStatus)??null,f=n.defaultBranch??t??null;return{status:r,needsConvergence:n.needsConvergence??r!=="merged_to_main",reason:n.reason??"provided_by_coordinator",nextStep:n.nextStep??null,branch:n.branch??h,defaultBranch:f,upstream:n.upstream??d,upstreamStatus:n.upstreamStatus??m,ahead:n.ahead??c,behind:n.behind??u,dirty:n.dirty??a,hasConflicts:n.hasConflicts??i}}function wj(e,t){const n=vj(e,t);return n?{...n,defaultBranch:n.defaultBranch??t}:null}function kj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Sj(e){var u,h,d;const{nodeStatus:t,expectedSubmodulePaths:n,refreshedAtMs:r}=e,o=[],a=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Np(t))return o.push(`${a} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:o};const m=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((h=t.connection)==null?void 0:h.state)==="self";return o.push(m?`${a} is online but no peer git snapshot is visible yet.`:`${a} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:o}}const c=new Set((i.submodules??[]).map(m=>m.path));if(n.size>0){const m=[...n].filter(f=>!c.has(f));m.length>0&&o.push(`${a} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&r!==null&&typeof i.lastCheckedAt=="number"&&r-i.lastCheckedAt>sj&&o.push(`${a} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),o.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:o}:o.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:o}:{snapshotCompleteness:"complete",snapshotWarnings:o}}function Mp(e){const t=Mu(e),r=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??dj(t.nodes),o=Ap(t.refreshedAt),a=new Set(t.nodes.flatMap(F=>{var R;return(((R=F.git)==null?void 0:R.submodules)??[]).map(Q=>Q.path)})),i=[],c=[],u=mj(t),h=new Map,d=gj(fj(t));for(const F of t.nodes){const R=F.git,Q=(R==null?void 0:R.branch)??null,E=lj(R),I=Tp(R)||E==="dirty",$=uj(F,r),D=wj(F,r),U=Sj({nodeStatus:F,expectedSubmodulePaths:a,refreshedAtMs:o}),Y=typeof F.clonedFromNodeId=="string"?F.clonedFromNodeId:null,ae=ij(F),z=bj(d.get(F.nodeId)??[]),X=rj(F),de={id:F.nodeId,type:$.length>0?"orphanNode":"worktreeNode",label:F.machineLabel||F.nodeId.slice(0,8),workspace:F.workspace,branch:Q,upstream:(R==null?void 0:R.upstream)??null,upstreamStatus:(R==null?void 0:R.upstreamStatus)??null,daemonId:Sp(F),machineId:Cp(F),machineLabel:F.machineLabel||null,locality:nj(F),connectionTransport:X.connectionTransport,connectionState:X.connectionState,connectionReason:X.connectionReason,connectionReported:X.connectionReported,connectionRttMs:X.connectionRttMs,health:Sa([F.health,E]),ahead:(R==null?void 0:R.ahead)??0,behind:(R==null?void 0:R.behind)??0,dirty:I,dirtyFiles:cj(R),hasConflicts:(R==null?void 0:R.hasConflicts)??!1,activeSessionCount:ae.length,activeSessions:ae.map(re=>re.sessionId),sessionDetails:ae,providers:F.providers??[],isOrphan:$.length>0,orphanReasons:$,error:F.error,nextStepHint:U.snapshotWarnings[0]??$[0]??(D==null?void 0:D.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:Y,worktreeBranch:F.worktreeBranch??null,submodulePath:null,submoduleCommit:(R==null?void 0:R.headCommit)??null,outOfSync:cl(R),snapshotCompleteness:U.snapshotCompleteness,snapshotWarnings:U.snapshotWarnings,branchConvergence:D,refineJobStatus:(z==null?void 0:z.status)??null,refineJobId:(z==null?void 0:z.jobId)??null,refineJobBranch:(z==null?void 0:z.branch)??null,refineJobInto:(z==null?void 0:z.into)??null,source:F};if(i.push(de),Q){const re=h.get(Q)??[];re.push(de.id),h.set(Q,re)}for(const re of(R==null?void 0:R.submodules)??[]){const W=`${de.id}::submodule::${re.path}`,oe=re.path.split("/").filter(Boolean).pop()||re.path;i.push({id:W,type:"submoduleNode",label:oe,workspace:re.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:de.daemonId,machineId:de.machineId,machineLabel:de.machineLabel,locality:de.locality,connectionTransport:de.connectionTransport,connectionState:de.connectionState,connectionReason:de.connectionReason,connectionReported:de.connectionReported,connectionRttMs:de.connectionRttMs,health:kj(re),ahead:0,behind:0,dirty:re.dirty,dirtyFiles:re.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:re.error,nextStepHint:re.error||(re.outOfSync?`${re.path} is out of sync with the parent checkout`:re.dirty?`${re.path} has local changes`:`${re.path} is in sync with the parent checkout`),parentNodeId:de.id,submodulePath:re.path,submoduleCommit:re.commit,outOfSync:re.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:de.id,parentWorkspace:F.workspace,submodule:re}}),c.push({id:`${de.id}--${W}`,source:de.id,target:W,type:"submoduleLink",label:re.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=r?`__branch_${r}`:null;if(m&&r){const R=(h.get(r)??[]).map(Y=>i.find(ae=>ae.id===Y)).filter(Boolean),Q=R.map(Y=>Y.branchConvergence).filter(Boolean),E=pj(t),I=R.length>0&&R.every(Y=>xj(Y,r)),$=(E==null?void 0:E.length)===0&&I?yj(r,R):Q.length>0?hj(Q):null,D=(E==null?void 0:E.length)===0&&I?0:Q.filter(Y=>Y.needsConvergence).length,U={id:m,type:"defaultBranchNode",label:r,workspace:t.repoIdentity,branch:r,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:Sa(R.map(Y=>Y.health)),ahead:0,behind:0,dirty:R.some(Y=>Y.dirty),dirtyFiles:R.reduce((Y,ae)=>Y+ae.dirtyFiles,0),hasConflicts:R.some(Y=>Y.hasConflicts),activeSessionCount:R.reduce((Y,ae)=>Y+ae.activeSessionCount,0),activeSessions:R.flatMap(Y=>Y.activeSessions),sessionDetails:R.flatMap(Y=>Y.sessionDetails),providers:[...new Set(R.flatMap(Y=>Y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:D>0?`${D} workspace(s) on ${r} still need follow-up`:R.length>0?`${R.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:$,source:{nodeId:m,machineLabel:r,workspace:t.repoIdentity,health:Sa(R.map(Y=>Y.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(U);for(const Y of i)if(!(Y.id===m||Y.type==="submoduleNode")){if(Y.branch===r){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(Y.branch){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:Y.isOrphan?"orphanLink":"parentBranch",label:Y.branch,direction:"undirected"});continue}Y.isOrphan&&c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const f=new Set(i.map(F=>F.id)),x=new Set;for(const F of i){if(!F.clonedFromNodeId||F.type==="submoduleNode"||!f.has(F.clonedFromNodeId))continue;const R=`clone_${F.clonedFromNodeId}--${F.id}`;if(x.has(R))continue;x.add(R);const Q=F.worktreeBranch??F.branch??void 0;c.push({id:R,source:F.clonedFromNodeId,target:F.id,type:"cloneLink",label:Q?`cloned · ${Q}`:"cloned",direction:"directed"})}const w=i.filter(F=>F.type!=="defaultBranchNode"),p=w.filter(F=>F.isOrphan).length,y=w.filter(F=>F.hasConflicts).length,k=w.filter(F=>F.health==="offline").length,b=w.filter(F=>F.type==="submoduleNode"&&F.outOfSync).length,j=w.filter(F=>{var R;return F.type!=="submoduleNode"&&((R=F.branchConvergence)==null?void 0:R.needsConvergence)}).length,S=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="blocked_review"}).length,v=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="pushed_feature_branch_needs_merge"}).length,g=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="cleanup_candidate"}).length,N=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="not_mergeable"}).length,C=w.filter(F=>F.snapshotWarnings.length>0).length,A=w.filter(F=>F.snapshotCompleteness==="pending_git").length,T=w.filter(F=>F.snapshotCompleteness==="missing_git").length,M=w.filter(F=>F.snapshotCompleteness==="missing_submodule_report").length,L=w.filter(F=>F.snapshotCompleteness==="stale").length,P=w.filter(F=>F.refineJobStatus==="running"||F.refineJobStatus==="accepted").length,B=w.filter(F=>F.refineJobStatus==="failed").length,K=[A>0?`${A} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,M>0?`${M} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,L>0?`${L} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return j>0&&u.push(`${j} workspace(s) still need follow-up before the mesh is converged`),p>0&&u.push(`${p} workspace(s) need attention before safe coordination`),S>0&&u.push(`${S} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&u.push(`${v} clean feature branch workspace(s) still need merge follow-up`),g>0&&u.push(`${g} worktree workspace(s) are ready for refine / cleanup`),N>0&&u.push(`${N} workspace(s) have local changes or conflicts blocking convergence`),y>0&&u.push(`${y} workspace(s) report merge conflicts`),k>0&&u.push(`${k} node(s) are currently offline`),b>0&&u.push(`${b} submodule(s) are out of sync with their parent checkout`),u.push(...K),r||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:w.length,onlineNodes:w.filter(F=>F.health==="online").length,dirtyNodes:w.filter(F=>F.dirty).length,orphanNodes:p,errorNodes:w.filter(F=>!!F.error||F.outOfSync).length,offlineNodes:k,followUpNodes:j,blockedReviewNodes:S,mergeReadyNodes:v,cleanupCandidateNodes:g,notMergeableNodes:N,incompleteSnapshotNodes:C,pendingGitSnapshotNodes:A,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:M,staleGitSnapshotNodes:L,activeRefineNodes:P,failedRefineNodes:B,totalActiveSessions:w.reduce((F,R)=>F+R.activeSessionCount,0)},warnings:u,snapshotWarnings:K}}function Cj(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const jj=7,Nj=640,dl=l.createContext(Rs("dark")),Dp=l.createContext(!1),Pp=l.createContext("LR"),Lp={overflowWrap:"anywhere",wordBreak:"break-word"},Aj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Tj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Rp(e){return e.activeSessionCount>0}function Ij(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function td(e,t,n){const r=Rp(e),o=Ij(e);let a;t?a="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?a=n?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":o?a=n?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":a=n?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=al(e);if((i==null?void 0:i.tone)==="danger")return`${a} ${n?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${a} ${n?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${a} ${n?r?"bg-emerald-500/10":"bg-emerald-500/8":r?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${a} ${n?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${a} ${n?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${a} ${n?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${a} ${n?"bg-slate-950/78":"bg-white/96"}`}}function Lt(e,t){switch(e){case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function sd(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function nd(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function Mj(e){return e.replace(/_/g," ")}function hs(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?n.replace(/_/g," "):n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function Dj(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(n=>hs(n)==="generating"))??!1}function Ca(e,t){const n=hs(e);return n.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":n==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":n==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":Lt("health",t)}function Pj(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function rd(e){const t=Pj(e);if(t===null)return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const o=Math.floor(r/60);return o<48?`${o}h ${r%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function ja(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function On(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Lj(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(a=>hs(a)==="generating").length,n=e.sessionDetails.filter(a=>a.isSelfCoordinator).length,r=e.sessionDetails.length-n,o=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&o.push(`${t} generating`),n>0&&o.push(n===1?"coordinator attached":`${n} coordinators`),r>0&&o.push(`${r} worker${r===1?"":"s"}`),t===0&&n>0&&o.push("sampled status"),o.join(" · ")}function od(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Rj(e){return e.locality==="remote"?"meta":"health"}function Ej({data:e,selected:t}){const{t:n}=Le("common"),r=l.useContext(dl),o=l.useContext(Dp),a=l.useContext(Pp),i=e.graphNode,c=i.type==="defaultBranchNode",u=i.type==="submoduleNode",h=gp(i),d=c?"default branch anchor":u?i.submodulePath||"submodule checkout":[i.machineLabel,od(i.locality)].filter(Boolean).join(" · ")||i.workspace,m=i.submoduleCommit?i.submoduleCommit.slice(0,7):null,f=!u&&!c&&i.connectionState!=="self",x=f?jp(i):null,w=x==="local"?null:x,p=f?oj(i):null,y=al(i),k=il(i),b=Rp(i),j=i.sessionDetails,S=i.sessionDetails,v=Lj(i),g=i.sessionDetails.map(C=>{const A=hs(C),T=C.providerType||"provider unknown",M=On(C),L=C.startedAt||C.createdAt||null,P=C.statusNote?` · ${C.statusNote}`:"";return`Session: ${C.sessionId} · ${T} · ${A} · ${M} · ${rd(L)}${P}`});if(o)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}`,style:{width:ur(i,!0)},title:[i.label,i.branch?`Branch: ${i.branch}`:null,i.machineLabel?`Machine: ${i.machineLabel}`:null,i.workspace?`Workspace: ${i.workspace}`:null,y?`Status: ${y.label}`:null,Qr(i),...g].filter(Boolean).join(`
82
82
  `),children:[s.jsx(vr,{type:"target",position:a==="TB"?Cs.Top:Cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:i.label}),!c&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:nd(i.health)},"aria-hidden":!0})]})]}),i.health==="unknown"&&!y&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${Lt("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:n("meshGraph.obs.connecting")})}),y&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${sd(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}),!y&&i.branch&&!u&&i.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Lt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:i.branch,children:i.branch}),v&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:g.join(`
83
83
  `),children:v}),S.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:S.map(C=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${On(C)}`].filter(Boolean).join(`
84
84
  `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:C.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:ja(C.sessionId)}),s.jsx("span",{className:"shrink-0",children:On(C)})]})]},C.sessionId))}),s.jsx(vr,{type:"source",position:a==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const N=[i.label,d,y?`Status: ${y.label}`:null,Qr(i),i.branch?`Branch: ${i.branch}`:null,i.dirty?u?"Local changes":`${i.dirtyFiles} dirty`:null,i.hasConflicts?"Has conflicts":null,i.outOfSync?"Out of sync":null,!u&&i.upstream&&i.upstreamStatus!=="fresh"?"Upstream unverified":null,i.isOrphan?"Needs follow-up":null,h&&k?`Note: ${k}`:null,...g].filter(Boolean).join(`
85
85
  `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}${Dj(i)?" mesh-node-generating":""}`,style:{width:ur(i)},title:N,children:[s.jsx(vr,{type:"target",position:a==="TB"?Cs.Top:Cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:i.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:nd(i.health)},"aria-hidden":!0})]})]}),y?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${sd(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}):i.branch&&!u?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${Lt("meta",r.isDark)}`,title:i.branch,children:s.jsx("span",{className:"truncate",children:i.branch})}):null,v&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:g.join(`
86
86
  `),children:s.jsx("span",{className:"truncate",children:v})}),S.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:S.map(C=>{const A=On(C);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${A}`].filter(Boolean).join(`
87
87
  `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:C.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:ja(C.sessionId)}),s.jsx("span",{children:A})]})]},C.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[i.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:n("meshGraph.obs.connecting")}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Lt("health",r.isDark)}`,children:Mj(i.health)}),u&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("submodule",r.isDark)}`,children:n("meshGraph.panel.submoduleBadge")}),!c&&i.health==="unknown"&&!i.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:"..."}),!c&&(i.health!=="unknown"||i.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt(Rj(i),r.isDark)}`,children:od(i.locality)}),w&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:w==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${w}`,children:w}),p&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:"P2P round-trip latency",children:p}),m&&u&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,children:m}),i.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("dirty",r.isDark)}`,children:u?"local changes":`${i.dirtyFiles} dirty`}),i.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.outOfSyncBadge")}),i.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.conflictBadge")}),!u&&i.upstream&&i.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.upstreamUnverified")}),i.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.needsFollowUp")}),!u&&i.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("refineDone",r.isDark)}`,title:i.refineJobBranch?`refined ${i.refineJobBranch}${i.refineJobInto?` → ${i.refineJobInto}`:""}`:"refine completed",children:n("meshGraph.panel.refined")})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:Aj,children:Qr(i)}),j.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:n("meshGraph.panel.attachedChats")}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:j.map(C=>{const A=C.startedAt||C.createdAt||null,T=On(C);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${T}`,A?`Started: ${A}`:"Started: not reported",C.statusNote?`Note: ${C.statusNote}`:null].filter(Boolean).join(`
88
- `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:ja(C.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:C.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:T}),s.jsx("span",{children:rd(A)})]}),C.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:C.statusNote})]},C.sessionId)})})]}),h&&k&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Tj,children:k})]}),s.jsx(vr,{type:"source",position:a==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const _j={meshNode:Ej},$j=8;function Bj(e){if(e.length<2)return null;if(e.length===2){const[h,d]=e;return{d:`M ${h.x},${h.y} L ${d.x},${d.y}`,labelX:(h.x+d.x)/2,labelY:(h.y+d.y)/2}}const t=$j,n=[`M ${e[0].x},${e[0].y}`];for(let h=1;h<e.length-1;h+=1){const d=e[h-1],m=e[h],f=e[h+1],x=Math.sign(m.x-d.x),w=Math.sign(m.y-d.y),p=Math.sign(f.x-m.x),y=Math.sign(f.y-m.y),k=Math.hypot(m.x-d.x,m.y-d.y),b=Math.hypot(f.x-m.x,f.y-m.y),j=Math.min(t,k/2,b/2);if(j<1||x===p&&w===y){n.push(`L ${m.x},${m.y}`);continue}const S=m.x-x*j,v=m.y-w*j,g=m.x+p*j,N=m.y+y*j;n.push(`L ${S},${v}`),n.push(`Q ${m.x},${m.y} ${g},${N}`)}const r=e[e.length-1];n.push(`L ${r.x},${r.y}`);let o=0;const a=[0];for(let h=1;h<e.length;h+=1)o+=Math.hypot(e[h].x-e[h-1].x,e[h].y-e[h-1].y),a.push(o);const i=o/2;let c=e[0].x,u=e[0].y;for(let h=1;h<e.length;h+=1)if(a[h]>=i){const d=a[h]-a[h-1],m=d===0?0:(i-a[h-1])/d;c=e[h-1].x+(e[h].x-e[h-1].x)*m,u=e[h-1].y+(e[h].y-e[h-1].y)*m;break}return{d:n.join(" "),labelX:c,labelY:u}}function Fj(e){const t=e.data.routePoints;if(t&&t.length>=2){const a=Bj(t);if(a)return[a.d,a.labelX,a.labelY]}const n={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;let o;return r.type==="parentBranch"?o=Fm(n):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?o=$m(n):o=Bm(n),[o[0],o[1],o[2]]}function Hj(e,t){const n="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${n} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${n} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${n} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${n} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${n} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${n} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${n} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${n} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${n} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${n} border-sky-300 bg-white/95 text-sky-700`}}function Wj(e){const t=l.useContext(dl),n=e.data.graphEdge,[r,o,a]=Fj(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Pm,{id:e.id,path:r,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Lm,{children:s.jsx("div",{className:Hj(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${o}px, ${a}px)`,pointerEvents:"none",maxWidth:H1.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Oj={meshEdge:Wj};async function Uj(e,t,n,r,o){const a=await wp(e,n,r,o);return Ep(e,a,t,n)}async function Gj(e,t=Rs("dark"),n=!1,r="LR"){const o=await wp(e,n,r);return Ep(e,o,t,n)}function Ep(e,t,n,r=!1){const o=new Set(t.nodes.map(h=>h.id)),a=t.nodes.map(h=>({id:h.id,type:h.type,position:h.position,data:{graphNode:h.graphNode,compact:r},selected:h.selected,draggable:h.draggable,selectable:h.selectable})),i=e.edges.filter(h=>o.has(h.source)&&o.has(h.target)),c=qj(i),u=i.map(h=>{var d;return{id:h.id,source:h.source,target:h.target,label:c.has(h.id)?h.label:void 0,type:"meshEdge",data:{graphEdge:h,routePoints:(d=t.edgeRoutes.get(h.id))==null?void 0:d.points},animated:h.type==="orphanLink",markerEnd:h.direction==="directed"?{type:_m.ArrowClosed,width:h.type==="submoduleLink"?16:18,height:h.type==="submoduleLink"?16:18,color:id(h)}:void 0,style:{stroke:id(h),strokeWidth:h.type==="orphanLink"?2.25:h.type==="submoduleLink"?1.7:h.type==="worktreeLink"?1.8:h.type==="cloneLink"?1.6:2,strokeDasharray:h.type==="orphanLink"?"5 4":h.type==="submoduleLink"?"4 3":h.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:n.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:n.edgeLabelBackgroundColor,fillOpacity:1,stroke:n.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:a,edges:u}}const Kj=3,zj=2;function ad(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function qj(e){const t=new Set,n=new Map;for(const r of e){if(!r.label)continue;const o=n.get(r.source);o?o.push(r):n.set(r.source,[r])}for(const r of n.values()){if(r.length<Kj){for(const a of r)t.add(a.id);continue}const o=[...r].sort((a,i)=>{const c=ad(i)-ad(a);return c!==0?c:a.id.localeCompare(i.id)});for(const a of o.slice(0,zj))t.add(a.id)}return t}function id(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Vj(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function Yj(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function Jj({data:e,viewportKey:t}){const n=Rm(),r=Em(),o=l.useRef(null),a=l.useMemo(()=>xp(e),[e]),i=l.useMemo(()=>R1(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||o.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const h=i.length>0&&i.length<e.nodes.length;r.fitView({nodes:h?i.map(d=>({id:d})):void 0,padding:h?.24:.2,maxZoom:h?.98:.9,duration:260}),o.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,a,n,r,t]),null}const Qj=12;function Xj(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function Zj({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:r,onEdgeClick:o,onNodeHoverChange:a,onEdgeHoverChange:i}){const{theme:c}=Ls(),u=l.useMemo(()=>Rs(c),[c]),h=l.useMemo(()=>ej(e),[e]),d=l.useMemo(()=>tj(e),[e]),m=l.useRef(null),[f,x]=l.useState({width:0,height:0}),w=f.width>0&&f.width<Nj,p=e.nodes.length>=jj||w,[y]=l.useState("LR"),k=n??y,b=l.useMemo(()=>n==="LR"||n==="TB"?n:w?"TB":k==="auto"?U1(e):k,[k,n,h,e,w]),j=e.nodes.length>=Qj,[S,v]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${E1(e,f.width,f.height)}::${b}`,[h,e,f.height,f.width,b]);l.useEffect(()=>{let C=!1;return Gj(e,u,p,b).then(A=>{if(C)return;v(A);const T=requestAnimationFrame(()=>{if(C)return;const M=m.current;if(!M)return;const L=new Map;for(const P of A.nodes){const B=M.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&L.set(P.id,B.offsetHeight)}L.size!==0&&Uj(e,u,p,b,L).then(P=>{C||v(P)})});return()=>cancelAnimationFrame(T)}),()=>{C=!0}},[e,d,u,p,b]);const N=l.useMemo(()=>S.nodes.map(C=>({...C,selected:C.id===t})),[S.nodes,t]);return l.useEffect(()=>{const C=m.current;if(!C)return;const A=()=>{const M=Math.max(0,Math.round(C.clientWidth)),L=Math.max(0,Math.round(C.clientHeight));x(P=>P.width===M&&P.height===L?P:{width:M,height:L})};A();const T=typeof ResizeObserver=="function"?new ResizeObserver(()=>A()):null;return T==null||T.observe(C),window.addEventListener("resize",A),()=>{T==null||T.disconnect(),window.removeEventListener("resize",A)}},[]),s.jsx(dl.Provider,{value:u,children:s.jsx(Dp.Provider,{value:p,children:s.jsx(Pp.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${u.graphShellClass} ${Xj(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${u.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Am,{nodes:N,edges:S.edges,nodeTypes:_j,edgeTypes:Oj,minZoom:w?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,A)=>r==null?void 0:r(A.data.graphNode),onEdgeClick:(C,A)=>{var M;const T=(M=A.data)==null?void 0:M.graphEdge;T&&(o==null||o(T))},onNodeMouseEnter:(C,A)=>a==null?void 0:a(A.data.graphNode),onNodeMouseLeave:()=>a==null?void 0:a(null),onEdgeMouseEnter:(C,A)=>{var T;return i==null?void 0:i(((T=A.data)==null?void 0:T.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:u.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Jj,{data:e,viewportKey:g}),s.jsx(Tm,{className:u.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),j&&s.jsx(Im,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Vj,nodeClassName:Yj,nodeStrokeWidth:3,className:u.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Mm,{variant:Dm.Dots,gap:18,size:1.2,color:u.graphBackgroundDotColor})]})})]})})})})}const eN="You are one independent member of a multi-agent cross-verification quorum";function tN(e){var r,o;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(eN))return t;const n=(o=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:o.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function sN(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function nN(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=n.activeSessionDetails;if(Array.isArray(r))for(const o of r)o!=null&&o.sessionId&&sN(o).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:o.sessionId,providerType:o.providerType,machineLabel:n.machineLabel||n.nodeId,detail:o.statusNote??o.title??null})}return t}function rN({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:r=!0}){const{t:o}=Le(),a=l.useMemo(()=>e??nN(t),[e,t]),[i,c]=l.useState({});if(r&&a.length===0)return null;const u=(h,d)=>{i[h.sessionId]||(c(m=>({...m,[h.sessionId]:d})),Promise.resolve(n(h.nodeId,h.sessionId,d)).finally(()=>{c(m=>{const f={...m};return delete f[h.sessionId],f})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ys,{size:14}),o("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:o("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(h=>{const d=i[h.sessionId]??null,m=d!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[h.machineLabel||h.nodeId,h.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:h.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:h.detail?h.detail.replace(/[\n\r]+/g," ").slice(0,120):o("meshGraph.approvals.sessionFallback",{id:h.sessionId})})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>u(h,"approve"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:d==="approve"?"⏳ ...":o("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>u(h,"reject"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:d==="reject"?"⏳ ...":o("meshGraph.approvals.reject")})]})]},`${h.nodeId}:${h.sessionId}`)})})]})}const oN=5,aN=40,iN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function _o(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function _p(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function $p(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function lN(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`✎${n}`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"clean"}function Bp(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function cN(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Fp(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function ld(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function ds(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const o=Math.floor(r/60);return o<48?`${o}h ago`:`${Math.floor(o/24)}d ago`}function cd(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),n=t%60,r=Math.floor(t/60),o=r%60,a=Math.floor(r/60),i=[];return a>0&&i.push(`${a}h`),o>0&&i.push(`${o}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function ul(e){return e.replace(/[_-]+/g," ")}function Hp(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Wp(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function dN({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:r=null}){var S,v,g,N;const{theme:o}=Ls(),a=l.useMemo(()=>Rs(o),[o]),i=((S=e.queue)==null?void 0:S.summary)??null,c=((v=e.queue)==null?void 0:v.tasks)??[],u=((g=e.ledger)==null?void 0:g.summary)??iN,h=((N=e.ledger)==null?void 0:N.entries)??[],d=e.missions??[],m=d.filter(C=>C.status==="active"||C.status==="paused"),f=d.filter(C=>C.status==="completed"||C.status==="abandoned"),x=e.asyncRefineJobs??[],[w,p]=l.useState(null),y=l.useCallback(()=>p(null),[]),k=l.useCallback(async(C,A,T)=>{!t||!r||await r(t,"mesh_approve",{meshId:n??void 0,node_id:C,session_id:A,action:T})},[t,n,r]),b=l.useCallback(C=>{if(!C)return"";const A=e.nodes.find(T=>T.nodeId===C);return(A==null?void 0:A.machineLabel)||C},[e.nodes]),j=l.useMemo(()=>{const C=[];for(const A of e.nodes){const T=A.activeSessionDetails&&A.activeSessionDetails.length>0?A.activeSessionDetails:(A.activeSessions??[]).map(M=>({sessionId:M,workspace:A.workspace,isCached:!0}));for(const M of T)C.push({node:A,session:M})}return C},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(rN,{nodes:e.nodes,onResolve:k}),s.jsx(yN,{meshTheme:a,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:C=>p({kind:"mission",mission:C})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(vN,{meshTheme:a,ledgerSummary:u,entries:h,resolveNodeLabel:b,onSelect:C=>p({kind:"ledger",entry:C})}),s.jsx(wN,{meshTheme:a,queueSummary:i,tasks:c,onSelect:C=>p({kind:"queue",task:C})})]}),s.jsx(SN,{meshTheme:a,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(CN,{meshTheme:a,entries:j,onSelect:(C,A)=>p({kind:"session",node:C,session:A})}),s.jsx(jN,{meshTheme:a,jobs:x})]}),w&&s.jsx(hN,{meshTheme:a,detail:w,onClose:y,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:r,resolveNodeLabel:b})]})}function Qs({meshTheme:e,title:t,count:n,children:r,action:o}){const a=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),o&&s.jsx("span",{className:"ml-auto",children:o})]}),r]})}function Kt({meshTheme:e,label:t,tone:n}){const r=e.isDark,o=n==="rose"?r?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?r?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?r?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?r?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":r?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${o}`,children:t})}function St({meshTheme:e,label:t,value:n,tone:r}){const o=e.isDark,a=r==="rose"?o?"text-rose-300":"text-rose-600":r==="sky"?o?"text-sky-300":"text-sky-600":r==="amber"?o?"text-amber-300":"text-amber-600":r==="emerald"?o?"text-emerald-300":"text-emerald-600":r==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${a}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function yr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function $o({meshTheme:e,onClick:t,children:n}){const r=e.isDark,o=t?r?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${o} ${t?"cursor-pointer":"cursor-default"}`,children:n})}function Bo({meshTheme:e,expanded:t,hiddenCount:n,onToggle:r}){const{t:o}=Le("common");return n<=0?null:s.jsx("button",{type:"button",onClick:r,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?o("mesh.overview.showFewer"):o("mesh.overview.showMore",{count:n})})}function Fo(e,t=oN){const[n,r]=l.useState(!1),o=n?e:e.slice(0,t),a=Math.max(0,e.length-t),i=l.useCallback(()=>r(c=>!c),[]);return{visible:o,hiddenCount:a,expanded:n,toggle:i}}function gt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function uN(e,t){switch(e.kind){case"mission":return{kicker:t("mesh.overview.detailKickerMission"),title:e.mission.title};case"ledger":return{kicker:t("mesh.overview.detailKickerLedger"),title:ul(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:_o(e.session.sessionId)}}}function hN({meshTheme:e,detail:t,onClose:n,daemonId:r,meshId:o,sendDaemonCommand:a,resolveNodeLabel:i}){const{t:c}=Le("common");l.useEffect(()=>{const x=w=>{w.key==="Escape"&&n()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n]);const u=e.isDark,{kicker:h,title:d}=uN(t,c),m=u?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=u?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${m}`,role:"dialog","aria-modal":"true",onClick:n,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${f} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:h}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:d})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:u?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(fN,{meshTheme:e,mission:t.mission,daemonId:r,meshId:o,sendDaemonCommand:a}),t.kind==="ledger"&&s.jsx(bN,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(gN,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(xN,{meshTheme:e,node:t.node,session:t.session})]})]})})}const pN=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function mN(e){const t=pN(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function fN({meshTheme:e,mission:t,daemonId:n,meshId:r,sendDaemonCommand:o}){var v;const{t:a}=Le("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",u="goalTruncated"in t?t.goalTruncated===!0:!1,[h,d]=l.useState(null),[m,f]=l.useState(!1),[x,w]=l.useState(null),p=u&&!h&&!!n&&!!o,y=l.useCallback(async()=>{if(!(!n||!o)){f(!0),w(null);try{const g=await o(n,"mesh_status",{meshId:r??void 0,verbose:!0}),N=mN(g),A=(Array.isArray(N==null?void 0:N.missions)?N.missions:[]).find(M=>(M==null?void 0:M.id)===t.id),T=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;T?d(T):w("Full goal unavailable")}catch(g){w(g instanceof Error?g.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,r,o,t.id]),k=h??c,b=u&&!h,j=t.stats??null,S=((v=j==null?void 0:j.incompleteTaskIds)==null?void 0:v.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx(Kt,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),k&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[k,b&&!p&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),x&&s.jsx("div",{className:"text-[11px] text-amber-400",children:x}),p&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:y,disabled:m,children:a(m?"mesh.overview.loadingGoal":"mesh.overview.showFullGoal")}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statPending"),value:i.pending}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),j&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statWallClock"),value:cd(j.wallClockMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statTotalRuntime"),value:cd(j.totalDurationMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statRetries"),value:j.retries,tone:j.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelLastActivity"),value:ds(i.lastActivityAt)??i.lastActivityAt}),S>0&&j&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:a("mesh.overview.incompleteTaskCount_other",{count:S})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:j.incompleteTaskIds.map(g=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:g},g))})]})})]})]})}function bN({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:r}=Le("common"),o=Wp(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Kt,{meshTheme:e,label:ul(t.kind),tone:Hp(t.kind)})}),o&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:o}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelEntryId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWhen"),value:ds(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:n(t.nodeId)}),t.sessionId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSession"),value:_o(t.sessionId)}),t.providerType&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelProvider"),value:t.providerType})]}),a&&a!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:r("mesh.overview.detailLabelPayload")}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:a})]})]})}function gN({meshTheme:e,task:t}){const{t:n}=Le("common");return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Fp(t.status)}),(t.requeueCount??0)>0&&s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeued",{count:t.requeueCount}),tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelTaskId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelNode"),value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelSession"),value:_o(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCancelReason"),value:t.cancelReason}),t.requeueReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeueReason"),value:t.requeueReason}),t.autoLaunch&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelAutoLaunch"),value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function xN({meshTheme:e,node:t,session:n}){var a,i;const{t:r}=Le("common"),o=_p(n);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:o,tone:$p(o)}),s.jsx(Kt,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSessionId"),value:n.sessionId}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:t.machineLabel}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWorkspace"),value:n.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelBranch"),value:((i=t.git)==null?void 0:i.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelRole"),value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelStarted"),value:ds(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function dd({meshTheme:e,mission:t,onSelect:n}){const r=t.tasks,o=ds(r.lastActivityAt);return s.jsxs($o,{meshTheme:e,onClick:n,children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",r.completed,"/",r.total]}),o&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:o})]})}function yN({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:r,onSelect:o}){const{t:a}=Le("common"),[i,c]=l.useState(!1),u=e.isDark,h=Fo(t);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.missionCard"),count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.visible.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id)),s.jsx(Bo,{meshTheme:e,expanded:h.expanded,hiddenCount:h.hiddenCount,onToggle:h.toggle})]}):s.jsx(yr,{meshTheme:e,children:a(r?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(d=>!d),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${i?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:a("mesh.overview.completedHistory")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:n.length})]}),i&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id))})]})]})}function vN({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:r,onSelect:o}){const{t:a}=Le("common"),i=ds(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),u=Fo(c);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.ledgerCard"),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCheckpoints"),value:t.checkpointCreated})]}),c.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[u.visible.map(h=>{const d=Wp(h.payload);return s.jsxs($o,{meshTheme:e,onClick:()=>o(h),children:[s.jsx(Kt,{meshTheme:e,label:ul(h.kind),tone:Hp(h.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:h.nodeId||void 0,children:d||r(h.nodeId)||h.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(h.timestamp)??""})]},h.id)}),s.jsx(Bo,{meshTheme:e,expanded:u.expanded,hiddenCount:u.hiddenCount,onToggle:u.toggle})]})]}),(t.recentFailures>0||i&&c.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsx("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:a("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function wN({meshTheme:e,queueSummary:t,tasks:n,onSelect:r}){const o=l.useMemo(()=>[...n].sort((c,u)=>{const h=ld(c.status)-ld(u.status);return h!==0?h:(u.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,aN),[n]),a=Fo(o),{t:i}=Le("common");return t?s.jsxs(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),count:t.active>0?i("mesh.overview.activeCount",{count:t.active}):void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:i("mesh.overview.statPending"),value:t.pending}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statAssigned"),value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statActive"),value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCompleted"),value:t.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statFailed"),value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCancelled"),value:t.cancelled,tone:"muted"})]}),o.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:i("mesh.overview.recentTasks")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.visible.map(c=>s.jsxs($o,{meshTheme:e,onClick:()=>r(c),children:[s.jsx(Kt,{meshTheme:e,label:c.status,tone:Fp(c.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:tN(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(c.updatedAt)??""})]},c.id)),s.jsx(Bo,{meshTheme:e,expanded:a.expanded,hiddenCount:a.hiddenCount,onToggle:a.toggle})]})]})]}):s.jsx(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(yr,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function kN(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function SN({meshTheme:e,nodes:t}){const{t:n}=Le("common"),r=e.isDark;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(o=>{var u,h,d;const a=(((u=o.activeSessionDetails)==null?void 0:u.length)??0)||(((h=o.activeSessions)==null?void 0:h.length)??0),i=kN(o),c=((d=o.git)==null?void 0:d.branch)??o.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Kt,{meshTheme:e,label:o.health,tone:cN(o.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:o.workspace,children:o.machineLabel}),c&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:c,children:c}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:lN(o)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof o.daemonBuildVersion=="string"&&o.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",o.daemonBuildVersion]}),i&&s.jsx(Kt,{meshTheme:e,label:i.label,tone:i.tone})]},o.nodeId)})})})}function CN({meshTheme:e,entries:t,onSelect:n}){const{t:r}=Le("common"),o=Fo(t);return s.jsx(Qs,{meshTheme:e,title:r("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:r("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(({node:a,session:i})=>{const c=_p(i);return s.jsxs($o,{meshTheme:e,onClick:()=>n(a,i),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:_o(i.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),s.jsx(Kt,{meshTheme:e,label:c,tone:$p(c)})]},i.sessionId)}),s.jsx(Bo,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})})}function jN({meshTheme:e,jobs:t}){const{t:n}=Le("common"),r=e.isDark,o=t.filter(a=>a.status==="failed").length;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:o>0?s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.failedCount",{count:o}),tone:"rose"}):void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const NN=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function AN({meshTheme:e,open:t,onToggle:n}){const{t:r}=Le(),o=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?o?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":o?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:n,"aria-label":r("meshGraph.help.toggleAria"),"aria-expanded":t,title:r("meshGraph.help.toggleTitle"),className:`${a} ${i}`,children:s.jsx(Pf,{size:15})})}function TN({meshTheme:e,onClose:t}){const{t:n}=Le(),r=e.isDark,o=l.useMemo(()=>NN.map(a=>({term:n(`meshGraph.help.sections.${a}.term`),summary:n(`meshGraph.help.sections.${a}.summary`),details:n(`meshGraph.help.sections.${a}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const a=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("meshGraph.help.regionAria"),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(At,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:o.map(a=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:a.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:a.summary}),a.details&&a.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:a.details.map((i,c)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:i})]},c))})]},a.term))})]})}const tn=l.createContext(Rs("dark"));function Ve({label:e,tone:t="default",className:n,title:r}){const o=l.useContext(tn);return s.jsx("span",{title:r,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${o.badge(t)}${n?` ${n}`:""}`,children:e})}function Pt({label:e,value:t}){const n=l.useContext(tn);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}const IN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Op(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function Na(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function Xr(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function MN(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function DN(e){return e.startedAt||e.createdAt||null}function PN(e){const t=DN(e);if(!t)return"runtime age not reported";const n=Date.parse(t);if(!Number.isFinite(n))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-n)/1e3));if(r<60)return`${r}s`;const o=Math.floor(r/60);if(o<60)return`${o}m`;const a=Math.floor(o/60);return a<48?`${a}h ${o%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Up(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function LN(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function RN(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function EN(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];t.branch&&r.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&r.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`${n} dirty`);const o=(t.submodules??[]).filter(i=>i.dirty),a=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return o.length>0&&r.push(`${o.length} submodule dirty`),a.length>0&&r.push(`${a.length} submodule drift`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"Clean"}const _N={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function $N(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function BN(e){var n;const t=[];for(const r of e.nodes){const o=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(a=>({sessionId:a,workspace:r.workspace,isCached:!0}));for(const a of o)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((n=r.git)==null?void 0:n.branch)??null,nodeHealth:r.health,session:a})}return t}function FN(e){return e.assignedNodeId||e.targetNodeId||null}function fi(e){return e?e.slice(0,7):null}function HN(e,t){var a,i,c;const n=fi((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(n||r)return[n,r].filter(Boolean).join(" · ");const o=t[0];return o?[fi(o.commit),o.message].filter(Boolean).join(" · "):null}function WN(e,t){const n=HN(e,t);return n||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function ON(e){const t=(e==null?void 0:e.result)??e,n=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(n==null?void 0:n.entries)?n.entries:[]}function UN(e){var n,r,o,a,i,c;const t=((n=e.selectedSessionEntry)==null?void 0:n.session.workspace)||((r=e.selectedSessionEntry)==null?void 0:r.workspace)||((a=(o=e.selectedNodeStatus)==null?void 0:o.git)==null?void 0:a.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function GN(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":RN(e.connection)}function KN(e){var n;const t=e.source;return t!=null&&t.kind?t.kind:((n=t==null?void 0:t.connection)==null?void 0:n.source)??"mesh_status"}function ud(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function zN(e){return e.direction==="directed"?"directed":"undirected"}function qN(e,t){return t?e.nodes.find(n=>n.id===t)??null:null}function VN(e){var t,n,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((n=(t=e.queue)==null?void 0:t.summary)==null?void 0:n.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,c,u,h,d,m,f,x,w,p,y,k,b,j,S,v,g,N,C,A,T,M;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((c=a.connection)==null?void 0:c.transport)??"",((u=a.connection)==null?void 0:u.source)??"",a.health,a.gitProbePending?1:0,((h=a.git)==null?void 0:h.branch)??"",((d=a.git)==null?void 0:d.upstream)??"",((m=a.git)==null?void 0:m.upstreamStatus)??"",((f=a.git)==null?void 0:f.ahead)??"",((x=a.git)==null?void 0:x.behind)??"",((w=a.git)==null?void 0:w.headCommit)??"",((p=a.git)==null?void 0:p.staged)??"",((y=a.git)==null?void 0:y.modified)??"",((k=a.git)==null?void 0:k.untracked)??"",((b=a.git)==null?void 0:b.deleted)??"",((j=a.git)==null?void 0:j.renamed)??"",(S=a.git)!=null&&S.hasConflicts?1:0,((v=a.git)==null?void 0:v.lastCheckedAt)??"",((g=a.activeSessions)==null?void 0:g.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((C=a.activeSessionDetails)==null?void 0:C.map(L=>[L.sessionId,L.providerType??"",L.state??"",L.chatStatus??"",L.lifecycle??"",L.role??"",L.isSelfCoordinator?1:0,L.statusNote??"",L.startedAt??"",L.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((T=a.providerPriority)==null?void 0:T.join(","))??"",a.error??"",(((M=a.git)==null?void 0:M.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function YN(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function JN({scheduling:e}){const{t}=Le("common"),n=l.useContext(tn);if(!e)return s.jsx("div",{className:`${n.cardClass} rounded-2xl p-4 text-[12px] ${n.textSecondary}`,children:t("mesh.status.schedulingNotReported")});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.schedulingTitle")}),s.jsx(Ve,{label:_N[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ve,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ve,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:t("mesh.status.distributionTitle")})]})}function QN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ve,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ve,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ve,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ve,{label:$N(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function XN({node:e}){var d,m,f,x;const t=l.useContext(tn),n=((d=e.activeSessionDetails)==null?void 0:d.length)??((m=e.activeSessions)==null?void 0:m.length)??0,r=fi((f=e.git)==null?void 0:f.headCommit),o=e.isLocalWorktree===!0,a=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,u=c?Object.entries(c).filter(([,w])=>typeof w=="string"&&w):[],h=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ve,{label:e.health,tone:Op(e.health)}),o&&s.jsx(Ve,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(a==null?void 0:a.status)&&a.status!=="ready"&&s.jsx(Ve,{label:`bootstrap ${a.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((x=e.connection)==null?void 0:x.state)&&e.connection.state!=="self"&&s.jsx(Ve,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),n>0&&s.jsx(Ve,{label:`${n} session${n===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ve,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ve,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),h&&s.jsx(Ve,{label:`build ${h}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(QN,{scheduling:e.scheduling})]}),u.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:u.map(([w,p])=>s.jsx(Ve,{label:`${w}@${p}`,tone:"info",title:"Detected provider version on this node"},w))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[EN(e),r?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",r]}):null]})]})}function ZN({status:e}){const{t}=Le("common"),n=l.useContext(tn),r=e.meshProtocolMetrics,o=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&o.length===0?null:s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.protocolTitle")}),r&&s.jsx(Ve,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),o.length>0&&s.jsx(Ve,{label:`${o.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,i])=>s.jsx(Ve,{label:`${a}: ${i}`,tone:"default",title:"v2 event scope breakdown"},a))}),o.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:o.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:a.provider}),a.versions.map(i=>s.jsx(Ve,{label:`${i.version} · ${i.nodeIds.length} node${i.nodeIds.length===1?"":"s"}`,tone:"default",title:i.nodeIds.join(", ")},i.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function eA({canonicalStatus:e}){const{t}=Le("common"),n=l.useContext(tn);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(JN,{scheduling:e.scheduling}),s.jsx(ZN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.nodesRuntime")}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${n.textSecondary} ${n.isDark?"border-white/10":"border-slate-200"}`,children:t("mesh.status.noNodesReporting")}):e.nodes.map(r=>s.jsx(XN,{node:r},r.nodeId))]})]})}function tA({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:r,meshTheme:o,sessionEntries:a,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),u=n.recentFailures>0||n.taskFailed>0,h=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],d=e.asyncRefineJobs,m=(d==null?void 0:d.filter(g=>g.status==="running"||g.status==="accepted"))??[],f=(d==null?void 0:d.filter(g=>g.status==="failed"))??[],x=e.staleDirectWorkSummary,w=x&&x.count>0;if(!c&&!u&&e.nodes.length===0&&!r&&m.length===0&&f.length===0&&!w&&a.length===0)return null;const p=o.isDark,y=`border-t ${p?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${p?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${o.textSecondary}`;function j({label:g,value:N,tone:C}){const A=C==="rose"?p?"text-rose-300":"text-rose-600":C==="sky"?p?"text-sky-300":"text-sky-600":C==="amber"?p?"text-amber-300":"text-amber-600":C==="emerald"?p?"text-emerald-300":"text-emerald-600":C==="muted"?o.textMuted:o.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${p?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${A}`,children:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${o.textMuted}`,children:g})]})}const S=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Pending",value:t.pending}),s.jsx(j,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(j,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(j,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(j,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${o.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var L;const N=((L=g.connection)==null?void 0:L.state)??"unknown",C=N==="unknown"||N==="connecting",M=C?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?p?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?p?"bg-emerald-400":"bg-emerald-500":p?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${M}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${o.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${o.textMuted}`,children:C?"…":N})]},g.nodeId)})})}),d&&d.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:d.length}),f.length>0&&s.jsxs("span",{className:p?"text-rose-300":"text-rose-600",children:[f.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:d.slice(0,8).map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,children:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?p?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?p?"text-sky-300":"text-sky-600":p?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),h.length>0&&s.jsx("div",{className:d&&d.length>0?"":`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:`flex-1 ${p?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${p?"text-rose-400":"text-rose-500"}`,children:h.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:h.map(g=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${p?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${o.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),w&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${y}`,children:[s.jsx("span",{className:o.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${p?"text-amber-300":"text-amber-600"}`,children:x.count})]}),a.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:a.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:a.map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,title:g.session.sessionId,children:Up(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${o.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${o.textMuted}`,children:Xr(g.session)})]},g.session.sessionId))})]})})]});return i?S:s.jsxs("details",{className:`rounded-2xl border text-xs ${o.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${o.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),f.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[f.length," refine failed"]}),u&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[n.recentFailures," recent failures"]}),r&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),S]})}function Gp({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:r,onHelpOpenChange:o}){const{t:a}=Le("common"),i=c=>c?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:i(t==="overview"),onClick:()=>n("overview"),children:a("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:a("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:a("meshGraph.obs.tabGraph")})]}),s.jsx(AN,{meshTheme:e,open:r,onToggle:()=>o(!r)})]})}function sA({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:r=null,bootstrapFallback:o,activeTab:a,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:u,hideControls:h=!1}){var Xe,dt,it;const{t:d}=Le("common"),{theme:m}=Ls(),f=l.useMemo(()=>Rs(m),[m]),x=l.useMemo(()=>({merged_to_main:d("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:d("meshGraph.obs.convergenceNeedsMerge"),blocked_review:d("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:d("meshGraph.obs.convergenceCleanup"),not_mergeable:d("meshGraph.obs.convergenceNotMergeable")}),[d]),w=t??d("meshGraph.obs.emptyGraph"),p=l.useMemo(()=>Mu(e),[e]),y=o??YN(p),k=l.useMemo(()=>VN(p),[p]),b=l.useMemo(()=>Mp(p),[k]),[j,S]=l.useState("overview"),[v,g]=l.useState(!1),N=a??j,C=c??v,A=l.useCallback(he=>{i?i(he):S(he)},[i]),T=l.useCallback(he=>{u?u(he):g(he)},[u]),[M,L]=l.useState(!1);l.useEffect(()=>{N==="graph"&&L(!0)},[N]);const[P,B]=l.useState(null),[K,F]=l.useState(null),[R,Q]=l.useState(null),[E,I]=l.useState({}),[$,D]=l.useState(null),[U,Y]=l.useState(null),ae=l.useMemo(()=>new Map(p.nodes.map(he=>[he.nodeId,he])),[p.nodes]),z=l.useMemo(()=>new Map(b.nodes.map(he=>[he.id,he])),[b.nodes]),X=((Xe=p.queue)==null?void 0:Xe.summary)??null,de=((dt=p.ledger)==null?void 0:dt.summary)??IN,re=l.useMemo(()=>BN(p),[p]),W=l.useMemo(()=>{const he=new Map;for(const $e of re){const Fe=Xr($e.session);he.set(Fe,(he.get(Fe)??0)+1)}return[...he.entries()].sort(($e,Fe)=>Fe[1]-$e[1])},[re]);l.useEffect(()=>{P&&(z.has(P)||(B(null),Q(he=>!he||"nodeId"in he&&he.nodeId===P?null:he)))},[z,P]);const oe=P?ae.get(P)??null:null,V=qN(b,P),ie=(R==null?void 0:R.kind)==="edge"&&K?b.edges.find(he=>he.id===K)??null:null,ke=ie?b.nodes.find(he=>he.id===ie.source)??null:null,xe=ie?b.nodes.find(he=>he.id===ie.target)??null:null;l.useEffect(()=>{var he,$e,Fe;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:p.meshId,selectedNodeId:P,canonicalNode:Pv(oe),graphNode:V?{id:V.id,branch:V.branch,upstream:V.upstream,headCommit:V.submoduleCommit,submoduleCount:(($e=(he=oe==null?void 0:oe.git)==null?void 0:he.submodules)==null?void 0:$e.length)??0,snapshotCompleteness:V.snapshotCompleteness,snapshotWarnings:V.snapshotWarnings,branchConvergence:((Fe=V.branchConvergence)==null?void 0:Fe.status)??null}:null})}catch{}},[p.meshId,V,P,oe]);const Se=(R==null?void 0:R.kind)==="session"?re.find(he=>he.nodeId===R.nodeId&&he.session.sessionId===R.sessionId)??null:null,pe=l.useMemo(()=>re.filter(he=>he.nodeId===P),[P,re]),G=UN({coordinatorDaemonId:n,selectedNodeStatus:oe,selectedSessionEntry:Se}),O=(G==null?void 0:G.workspace)??null,Z=O?E[O]??null:null,q=WN(oe,(Z==null?void 0:Z.entries)??[]),me=(V==null?void 0:V.daemonId)??(oe==null?void 0:oe.daemonId)??n??null,Te=!!(V&&r&&me&&V.type!=="submoduleNode"&&V.behind>0&&V.ahead===0&&V.dirtyFiles===0&&!V.dirty&&!V.hasConflicts&&V.upstreamStatus==="fresh"),_=l.useCallback(()=>{B(null),F(null),Q(null),D(null)},[]);l.useEffect(()=>{D(null)},[P]);const se=l.useCallback(async()=>{if(!V||!me||!r||!Te)return;Y(V.id),D(null);const he=(oe==null?void 0:oe.workspace)??V.workspace??"";try{const $e=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!0,execute:!1}),Fe=($e==null?void 0:$e.result)??$e;if(D({phase:"dry_run",code:typeof(Fe==null?void 0:Fe.code)=="string"?Fe.code:void 0,error:typeof(Fe==null?void 0:Fe.operationError)=="string"?Fe.operationError:null,executed:(Fe==null?void 0:Fe.executed)===!0}),!(Fe!=null&&Fe.success)||Fe.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${V.label}?`))return;const ye=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!1,execute:!0}),Oe=(ye==null?void 0:ye.result)??ye;D({phase:"execute",code:typeof(Oe==null?void 0:Oe.code)=="string"?Oe.code:void 0,error:typeof(Oe==null?void 0:Oe.operationError)=="string"?Oe.operationError:null,executed:(Oe==null?void 0:Oe.executed)===!0})}catch($e){D({phase:"dry_run",error:$e instanceof Error?$e.message:"fast-forward failed"})}finally{Y(null)}},[Te,p.meshId,V,me,r]);l.useEffect(()=>{if(!V&&!ie)return;const he=$e=>{$e.key==="Escape"&&_()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[_,ie,V]),l.useEffect(()=>{if(!G||!r)return;const{daemonId:he,workspace:$e}=G,Fe=E[$e];if(Fe!=null&&Fe.loading||Fe&&(Fe.entries.length>0||Fe.error))return;let Ie=!1;return I(ye=>{var Oe;return{...ye,[$e]:{loading:!0,error:null,entries:((Oe=ye[$e])==null?void 0:Oe.entries)??[]}}}),r(he,"git_log",{workspace:$e,limit:5}).then(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:null,entries:ON(ye)}}))}).catch(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:ye instanceof Error?ye.message:"git_log failed",entries:[]}}))}),()=>{Ie=!0}},[E,G,r]);const ve=[...b.warnings??[],...p.nodes.filter(he=>he.machineStatus&&he.machineStatus!=="online").map(he=>`${he.machineLabel}: ${he.machineStatus}`)],ce=b.stats.incompleteSnapshotNodes>0,H=b.stats.followUpNodes>0?`${b.stats.followUpNodes} need follow-up`:ce?"mesh visibility incomplete":"mesh converged",fe=b.stats.followUpNodes>0?"danger":ce?"warn":"good",[je,Ce]=l.useState("LR"),Be=he=>he?f.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":f.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(tn.Provider,{value:f,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!h&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Gp,{meshTheme:f,activeTab:N,onActiveTabChange:A,helpOpen:C,onHelpOpenChange:T})}),C&&s.jsx(TN,{meshTheme:f,onClose:()=>T(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:N==="overview"&&s.jsx(dN,{status:p,daemonId:n,meshId:p.meshId,sendDaemonCommand:r})}),s.jsx("div",{className:`${N==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="status"&&s.jsx(eA,{canonicalStatus:p})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${f.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${f.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${f.textSecondary}`,children:[s.jsx(Ve,{label:H,tone:fe,className:"shrink-0"}),b.stats.blockedReviewNodes>0&&s.jsx(Ve,{label:`${b.stats.blockedReviewNodes} blocked`,title:`${b.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),b.stats.notMergeableNodes>0&&s.jsx(Ve,{label:`${b.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),b.stats.mergeReadyNodes>0&&s.jsx(Ve,{label:`${b.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),b.stats.cleanupCandidateNodes>0&&s.jsx(Ve,{label:`${b.stats.cleanupCandidateNodes} cleanup`,title:`${b.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),b.stats.offlineNodes>0&&s.jsx(Ve,{label:`${b.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),b.stats.incompleteSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.incompleteSnapshotNodes} incomplete`,title:`${b.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingGitSnapshotNodes} no-git`,title:`${b.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${b.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),b.stats.staleGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.staleGitSnapshotNodes} stale`,title:`${b.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((X==null?void 0:X.active)??0)>0&&s.jsx(Ve,{label:`${(X==null?void 0:X.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ve,{label:`${b.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),b.stats.totalActiveSessions>0&&s.jsx(Ve,{label:`${b.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:f.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Ce("auto"),className:Be(je==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Ce("LR"),className:Be(je==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ce("TB"),className:Be(je==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Fe;const he=((Fe=p.asyncRefineJobs)==null?void 0:Fe.filter(Ie=>Ie.status==="failed").length)??0,$e=de.recentFailures;return he>0?s.jsxs("span",{className:f.isDark?"text-rose-300":"text-rose-600",children:[he," refine failed"]}):$e>0?s.jsxs("span",{className:f.isDark?"text-amber-300":"text-amber-600",children:[$e," failures"]}):d("meshGraph.obs.health")})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(tA,{canonicalStatus:p,queueSummary:X,ledgerSummary:de,isBootstrapMode:y,meshTheme:f,sessionEntries:re,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.obs.legend")}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:`${b.stats.dirtyNodes} dirty`,tone:b.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${b.stats.orphanNodes} orphan`,tone:b.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${de.recentFailures} recent failures`,tone:de.recentFailures>0?"danger":"good"}),W.length===0?s.jsx(Ve,{label:"no session metadata"}):W.slice(0,2).map(([he,$e])=>s.jsx(Ve,{label:`${$e} ${he}`,tone:Na(he)},he))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ve,{label:"Submodule link = child checkout",tone:"warn"})]}),ve.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:ve.map(he=>s.jsx("span",{className:f.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:he},he))}),s.jsx("div",{className:`text-xs ${f.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&b.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${f.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${f.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:d("meshGraph.obs.bootstrapBanner")})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:M?b.nodes.length>0?s.jsx(Zj,{data:b,selectedNodeId:P,directionPref:je,onNodeClick:he=>{if((R==null?void 0:R.kind)==="node"&&P===he.id){_();return}F(null),B(he.id),Q({kind:"node",nodeId:he.id})},onEdgeClick:he=>{if((R==null?void 0:R.kind)==="edge"&&K===he.id){_();return}B(null),F(he.id),Q({kind:"edge",edgeId:he.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:w}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:d("meshGraph.obs.loadingGraph")})}),V&&(R==null?void 0:R.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedNode")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:V.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${f.textMuted}`,children:V.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[V.behind>0&&s.jsx("button",{type:"button",onClick:()=>{se()},disabled:!Te||U===V.id,className:f.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:U===V.id?d("meshGraph.obs.checking"):d("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const he=(oe==null?void 0:oe.health)??V.health;return he==="unknown"?s.jsx(Ve,{label:d("meshGraph.obs.connecting"),tone:"default"}):s.jsx(Ve,{label:he,tone:Op(he)})})(),V.branch&&s.jsx(Ve,{label:V.branch,tone:"default"}),V.ahead>0&&s.jsx(Ve,{label:`ahead ${V.ahead}`,tone:"warn"}),V.behind>0&&s.jsx(Ve,{label:`behind ${V.behind}`,tone:"warn"}),V.dirtyFiles>0&&s.jsx(Ve,{label:`${V.dirtyFiles} dirty`,tone:"warn"}),(oe==null?void 0:oe.connection)&&oe.connection.state!=="unknown"&&s.jsx(Ve,{label:GN(oe),tone:LN(oe.connection)}),((it=oe==null?void 0:oe.connection)==null?void 0:it.state)==="unknown"&&s.jsx(Ve,{label:d("meshGraph.obs.meshConnecting"),tone:"warn"}),pe.length>0&&s.jsx(Ve,{label:`${pe.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[V.machineLabel&&s.jsx(Pt,{label:d("meshGraph.obs.fieldMachine"),value:V.machineLabel}),V.locality&&V.locality!=="unknown"&&s.jsx(Pt,{label:d("meshGraph.obs.fieldLocality"),value:V.locality}),s.jsx(Pt,{label:d("meshGraph.obs.fieldWorkspace"),value:(oe==null?void 0:oe.workspace)??V.workspace}),q&&s.jsx(Pt,{label:d("meshGraph.obs.fieldHead"),value:q}),(V.dirtyFiles>0||V.ahead>0||V.behind>0)&&s.jsx(Pt,{label:d("meshGraph.obs.fieldDirtyAheadBehind"),value:`${V.dirtyFiles}/${V.ahead}/${V.behind}`}),pe.length>0&&s.jsx(Pt,{label:d("meshGraph.obs.fieldSessions"),value:String(pe.length)}),V.upstream&&s.jsx(Pt,{label:d("meshGraph.obs.fieldUpstream"),value:V.upstream}),(()=>{var $e;const he=(($e=oe==null?void 0:oe.connection)==null?void 0:$e.source)??KN(V);return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldSource"),value:String(he)}):null})(),(()=>{var $e;const he=($e=oe==null?void 0:oe.connection)==null?void 0:$e.transport;return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldTransport"),value:he}):null})(),(()=>{const he=V.machineId??(oe==null?void 0:oe.machineId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldMachineId"),value:he}):null})(),(()=>{const he=V.daemonId??(oe==null?void 0:oe.daemonId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldDaemonId"),value:he}):null})()]}),pe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:pe.map(he=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${f.textMuted}`,title:he.session.sessionId,children:Up(he.session.sessionId)}),s.jsx(Ve,{label:Xr(he.session),tone:Na(Xr(he.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${f.textMuted}`,children:[s.jsx("span",{className:"truncate",children:he.session.providerType||d("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:MN(he.session)}),s.jsx("span",{children:PN(he.session)})]}),he.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${f.textMuted}`,children:he.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${f.textMuted}`,title:he.session.workspace||he.workspace,children:[(he.session.workspace||he.workspace).slice(0,38),he.branch?` · ${he.branch}`:""]})]},he.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldCompleted"),value:String(de.taskCompleted)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:de.taskFailed>0?f.isDark?"text-rose-300":"text-rose-600":"",children:de.taskFailed})}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLaunched"),value:String(de.sessionLaunched)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:de.recentFailures>0?f.isDark?"text-amber-300":"text-amber-600":"",children:de.recentFailures})})]})]}),(()=>{var Fe,Ie;const he=((Fe=p.queue)==null?void 0:Fe.tasks)??((Ie=p.queue)==null?void 0:Ie.items)??null;if(!Array.isArray(he)||he.length===0)return null;const $e=he.filter(ye=>FN(ye)===P).slice(0,3);return $e.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:$e.map(ye=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${f.textMuted}`,children:ye.id.slice(0,12)}),s.jsx(Ve,{label:ye.status??"unknown",tone:Na(ye.status)})]}),ye.message&&s.jsx("div",{className:`mt-0.5 truncate ${f.textMuted}`,children:ye.message.slice(0,48)})]},ye.id))})]})})(),V.snapshotWarnings.length>0&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:V.snapshotWarnings[0]})]}),V.branchConvergence&&(V.branchConvergence.reason||V.branchConvergence.nextStep)&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.followUpLabel",{status:x[V.branchConvergence.status]??V.branchConvergence.status})}),V.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:V.branchConvergence.reason}),V.branchConvergence.nextStep&&s.jsx("div",{className:`${V.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:V.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?d("meshGraph.obs.healResult"):d("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:$.code??$.error??d("meshGraph.obs.noResultCode")})]})]}),ie&&(R==null?void 0:R.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedEdge")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:ie.label||ud(ie)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${f.textMuted}`,children:ie.id})]}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ve,{label:ud(ie),tone:"default"}),s.jsx(Ve,{label:zN(ie),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldFrom"),value:(ke==null?void 0:ke.label)??ie.source}),s.jsx(Pt,{label:d("meshGraph.obs.fieldTo"),value:(xe==null?void 0:xe.label)??ie.target}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLabel"),value:ie.label??"none"})]})]})]})]})})]})})}function Nt(e){return typeof e=="string"?e.trim():""}function bi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function hl(...e){const t=new Set;for(const n of e){const r=Nt(n);r&&t.add(r)}return[...t]}function nA(e,t){var m,f;const n=bi(e==null?void 0:e.settings),r=Nt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||Nt(n.meshCoordinatorFor),o=Nt(n.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const c=bi(e==null?void 0:e.activeChat),u=hl(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),h=u[0]||"";if(!h)return null;const d=r===t?Nt((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":o===t?Nt(n.meshNodeRole)||"worker":Nt(e==null?void 0:e.role)||Nt(n.meshNodeRole)||void 0;return{sessionId:h,aliases:u,meshId:t,nodeId:i&&Nt(n.meshNodeId)||null,providerType:Nt(e==null?void 0:e.providerType)||void 0,state:Nt(e==null?void 0:e.status)||void 0,chatStatus:Nt(c.status)||void 0,lifecycle:Nt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Nt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Nt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Nt(e==null?void 0:e.workspace)||null}}function Kp(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>nA(o,t)).filter(o=>o!==null):[]}function vo(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function rA(e,t){const n=new Set(vo(t));return vo(e).some(r=>n.has(r))}function oA(e,t){const n=t.filter(o=>!!o);return n.length===0?e:[...e.filter(o=>!n.some(a=>rA(o,a))),...n]}function aA(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of vo(i))n.set(c,i);let r=!1;const a=(e.nodes??[]).map((i,c)=>{const u=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],h=new Map;for(const f of u){const x=hl(f==null?void 0:f.sessionId,f==null?void 0:f.session_id,f==null?void 0:f.id,f==null?void 0:f.providerSessionId,f==null?void 0:f.provider_session_id),w=x[0]||"";if(!w)continue;const p=x.map(y=>n.get(y)).find(Boolean);p&&(r=!0),h.set(w,p?{...f,sessionId:w,providerType:p.providerType||f.providerType,state:p.state||f.state,chatStatus:p.chatStatus||f.chatStatus,lifecycle:p.lifecycle||f.lifecycle,surfaceKind:p.surfaceKind||f.surfaceKind,recoveryState:p.recoveryState||f.recoveryState,role:p.role||f.role,isSelfCoordinator:p.isSelfCoordinator??f.isSelfCoordinator,workspace:p.workspace||f.workspace}:{...f,sessionId:w})}for(const f of i.activeSessions??[])h.has(f)||h.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const d=c===0;for(const f of t){if(vo(f).some(y=>h.has(y)))continue;const w=f.nodeId!=null&&f.nodeId===i.nodeId,p=f.isSelfCoordinator&&!f.nodeId&&d;!w&&!p||(r=!0,h.set(f.sessionId,{sessionId:f.sessionId,providerType:f.providerType,state:f.state,chatStatus:f.chatStatus,lifecycle:f.lifecycle,surfaceKind:f.surfaceKind,recoveryState:f.recoveryState,role:f.role,isSelfCoordinator:f.isSelfCoordinator,workspace:f.workspace||i.workspace}))}const m=[...h.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return r?{...e,nodes:a}:e}function iA(e,t){const r=Kp(e,t).map(o=>{var u;const a=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(h=>Nt(h==null?void 0:h.id)===o.sessionId),i=bi(a==null?void 0:a.activeInteractivePrompt),c=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",Nt(i.status)||Nt(i.kind)||Nt(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
88
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:ja(C.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:C.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:T}),s.jsx("span",{children:rd(A)})]}),C.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:C.statusNote})]},C.sessionId)})})]}),h&&k&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Tj,children:k})]}),s.jsx(vr,{type:"source",position:a==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const _j={meshNode:Ej},$j=8;function Bj(e){if(e.length<2)return null;if(e.length===2){const[h,d]=e;return{d:`M ${h.x},${h.y} L ${d.x},${d.y}`,labelX:(h.x+d.x)/2,labelY:(h.y+d.y)/2}}const t=$j,n=[`M ${e[0].x},${e[0].y}`];for(let h=1;h<e.length-1;h+=1){const d=e[h-1],m=e[h],f=e[h+1],x=Math.sign(m.x-d.x),w=Math.sign(m.y-d.y),p=Math.sign(f.x-m.x),y=Math.sign(f.y-m.y),k=Math.hypot(m.x-d.x,m.y-d.y),b=Math.hypot(f.x-m.x,f.y-m.y),j=Math.min(t,k/2,b/2);if(j<1||x===p&&w===y){n.push(`L ${m.x},${m.y}`);continue}const S=m.x-x*j,v=m.y-w*j,g=m.x+p*j,N=m.y+y*j;n.push(`L ${S},${v}`),n.push(`Q ${m.x},${m.y} ${g},${N}`)}const r=e[e.length-1];n.push(`L ${r.x},${r.y}`);let o=0;const a=[0];for(let h=1;h<e.length;h+=1)o+=Math.hypot(e[h].x-e[h-1].x,e[h].y-e[h-1].y),a.push(o);const i=o/2;let c=e[0].x,u=e[0].y;for(let h=1;h<e.length;h+=1)if(a[h]>=i){const d=a[h]-a[h-1],m=d===0?0:(i-a[h-1])/d;c=e[h-1].x+(e[h].x-e[h-1].x)*m,u=e[h-1].y+(e[h].y-e[h-1].y)*m;break}return{d:n.join(" "),labelX:c,labelY:u}}function Fj(e){const t=e.data.routePoints;if(t&&t.length>=2){const a=Bj(t);if(a)return[a.d,a.labelX,a.labelY]}const n={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;let o;return r.type==="parentBranch"?o=Fm(n):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?o=$m(n):o=Bm(n),[o[0],o[1],o[2]]}function Hj(e,t){const n="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${n} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${n} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${n} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${n} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${n} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${n} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${n} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${n} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${n} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${n} border-sky-300 bg-white/95 text-sky-700`}}function Wj(e){const t=l.useContext(dl),n=e.data.graphEdge,[r,o,a]=Fj(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Pm,{id:e.id,path:r,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Lm,{children:s.jsx("div",{className:Hj(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${o}px, ${a}px)`,pointerEvents:"none",maxWidth:H1.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Oj={meshEdge:Wj};async function Uj(e,t,n,r,o){const a=await wp(e,n,r,o);return Ep(e,a,t,n)}async function Gj(e,t=Rs("dark"),n=!1,r="LR"){const o=await wp(e,n,r);return Ep(e,o,t,n)}function Ep(e,t,n,r=!1){const o=new Set(t.nodes.map(h=>h.id)),a=t.nodes.map(h=>({id:h.id,type:h.type,position:h.position,data:{graphNode:h.graphNode,compact:r},selected:h.selected,draggable:h.draggable,selectable:h.selectable})),i=e.edges.filter(h=>o.has(h.source)&&o.has(h.target)),c=qj(i),u=i.map(h=>{var d;return{id:h.id,source:h.source,target:h.target,label:c.has(h.id)?h.label:void 0,type:"meshEdge",data:{graphEdge:h,routePoints:(d=t.edgeRoutes.get(h.id))==null?void 0:d.points},animated:h.type==="orphanLink",markerEnd:h.direction==="directed"?{type:_m.ArrowClosed,width:h.type==="submoduleLink"?16:18,height:h.type==="submoduleLink"?16:18,color:id(h)}:void 0,style:{stroke:id(h),strokeWidth:h.type==="orphanLink"?2.25:h.type==="submoduleLink"?1.7:h.type==="worktreeLink"?1.8:h.type==="cloneLink"?1.6:2,strokeDasharray:h.type==="orphanLink"?"5 4":h.type==="submoduleLink"?"4 3":h.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:n.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:n.edgeLabelBackgroundColor,fillOpacity:1,stroke:n.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:a,edges:u}}const Kj=3,zj=2;function ad(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function qj(e){const t=new Set,n=new Map;for(const r of e){if(!r.label)continue;const o=n.get(r.source);o?o.push(r):n.set(r.source,[r])}for(const r of n.values()){if(r.length<Kj){for(const a of r)t.add(a.id);continue}const o=[...r].sort((a,i)=>{const c=ad(i)-ad(a);return c!==0?c:a.id.localeCompare(i.id)});for(const a of o.slice(0,zj))t.add(a.id)}return t}function id(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Vj(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function Yj(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function Jj({data:e,viewportKey:t}){const n=Rm(),r=Em(),o=l.useRef(null),a=l.useMemo(()=>xp(e),[e]),i=l.useMemo(()=>R1(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||o.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const h=i.length>0&&i.length<e.nodes.length;r.fitView({nodes:h?i.map(d=>({id:d})):void 0,padding:h?.24:.2,maxZoom:h?.98:.9,duration:260}),o.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,a,n,r,t]),null}const Qj=12;function Xj(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function Zj({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:r,onEdgeClick:o,onNodeHoverChange:a,onEdgeHoverChange:i}){const{theme:c}=Ls(),u=l.useMemo(()=>Rs(c),[c]),h=l.useMemo(()=>ej(e),[e]),d=l.useMemo(()=>tj(e),[e]),m=l.useRef(null),[f,x]=l.useState({width:0,height:0}),w=f.width>0&&f.width<Nj,p=e.nodes.length>=jj||w,[y]=l.useState("LR"),k=n??y,b=l.useMemo(()=>n==="LR"||n==="TB"?n:w?"TB":k==="auto"?U1(e):k,[k,n,h,e,w]),j=e.nodes.length>=Qj,[S,v]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${E1(e,f.width,f.height)}::${b}`,[h,e,f.height,f.width,b]);l.useEffect(()=>{let C=!1;return Gj(e,u,p,b).then(A=>{if(C)return;v(A);const T=requestAnimationFrame(()=>{if(C)return;const M=m.current;if(!M)return;const L=new Map;for(const P of A.nodes){const B=M.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&L.set(P.id,B.offsetHeight)}L.size!==0&&Uj(e,u,p,b,L).then(P=>{C||v(P)})});return()=>cancelAnimationFrame(T)}),()=>{C=!0}},[e,d,u,p,b]);const N=l.useMemo(()=>S.nodes.map(C=>({...C,selected:C.id===t})),[S.nodes,t]);return l.useEffect(()=>{const C=m.current;if(!C)return;const A=()=>{const M=Math.max(0,Math.round(C.clientWidth)),L=Math.max(0,Math.round(C.clientHeight));x(P=>P.width===M&&P.height===L?P:{width:M,height:L})};A();const T=typeof ResizeObserver=="function"?new ResizeObserver(()=>A()):null;return T==null||T.observe(C),window.addEventListener("resize",A),()=>{T==null||T.disconnect(),window.removeEventListener("resize",A)}},[]),s.jsx(dl.Provider,{value:u,children:s.jsx(Dp.Provider,{value:p,children:s.jsx(Pp.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${u.graphShellClass} ${Xj(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${u.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Am,{nodes:N,edges:S.edges,nodeTypes:_j,edgeTypes:Oj,minZoom:w?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,A)=>r==null?void 0:r(A.data.graphNode),onEdgeClick:(C,A)=>{var M;const T=(M=A.data)==null?void 0:M.graphEdge;T&&(o==null||o(T))},onNodeMouseEnter:(C,A)=>a==null?void 0:a(A.data.graphNode),onNodeMouseLeave:()=>a==null?void 0:a(null),onEdgeMouseEnter:(C,A)=>{var T;return i==null?void 0:i(((T=A.data)==null?void 0:T.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:u.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Jj,{data:e,viewportKey:g}),s.jsx(Tm,{className:u.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),j&&s.jsx(Im,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Vj,nodeClassName:Yj,nodeStrokeWidth:3,className:u.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Mm,{variant:Dm.Dots,gap:18,size:1.2,color:u.graphBackgroundDotColor})]})})]})})})})}const eN="You are one independent member of a multi-agent cross-verification quorum";function tN(e){var r,o;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(eN))return t;const n=(o=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:o.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function sN(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function nN(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=n.activeSessionDetails;if(Array.isArray(r))for(const o of r)o!=null&&o.sessionId&&sN(o).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:o.sessionId,providerType:o.providerType,machineLabel:n.machineLabel||n.nodeId,detail:o.statusNote??o.title??null})}return t}function rN({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:r=!0}){const{t:o}=Le(),a=l.useMemo(()=>e??nN(t),[e,t]),[i,c]=l.useState({});if(r&&a.length===0)return null;const u=(h,d)=>{i[h.sessionId]||(c(m=>({...m,[h.sessionId]:d})),Promise.resolve(n(h.nodeId,h.sessionId,d)).finally(()=>{c(m=>{const f={...m};return delete f[h.sessionId],f})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ys,{size:14}),o("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:o("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(h=>{const d=i[h.sessionId]??null,m=d!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[h.machineLabel||h.nodeId,h.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:h.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:h.detail?h.detail.replace(/[\n\r]+/g," ").slice(0,120):o("meshGraph.approvals.sessionFallback",{id:h.sessionId})})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>u(h,"approve"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:d==="approve"?"⏳ ...":o("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>u(h,"reject"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:d==="reject"?"⏳ ...":o("meshGraph.approvals.reject")})]})]},`${h.nodeId}:${h.sessionId}`)})})]})}const oN=5,aN=40,iN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function _o(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function _p(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function $p(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function lN(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`✎${n}`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"clean"}function Bp(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function cN(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Fp(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function ld(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function ds(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const o=Math.floor(r/60);return o<48?`${o}h ago`:`${Math.floor(o/24)}d ago`}function cd(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),n=t%60,r=Math.floor(t/60),o=r%60,a=Math.floor(r/60),i=[];return a>0&&i.push(`${a}h`),o>0&&i.push(`${o}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function ul(e){return e.replace(/[_-]+/g," ")}function Hp(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Wp(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function dN({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:r=null}){var S,v,g,N;const{theme:o}=Ls(),a=l.useMemo(()=>Rs(o),[o]),i=((S=e.queue)==null?void 0:S.summary)??null,c=((v=e.queue)==null?void 0:v.tasks)??[],u=((g=e.ledger)==null?void 0:g.summary)??iN,h=((N=e.ledger)==null?void 0:N.entries)??[],d=e.missions??[],m=d.filter(C=>C.status==="active"||C.status==="paused"),f=d.filter(C=>C.status==="completed"||C.status==="abandoned"),x=e.asyncRefineJobs??[],[w,p]=l.useState(null),y=l.useCallback(()=>p(null),[]),k=l.useCallback(async(C,A,T)=>{!t||!r||await r(t,"mesh_approve",{meshId:n??void 0,node_id:C,session_id:A,action:T})},[t,n,r]),b=l.useCallback(C=>{if(!C)return"";const A=e.nodes.find(T=>T.nodeId===C);return(A==null?void 0:A.machineLabel)||C},[e.nodes]),j=l.useMemo(()=>{const C=[];for(const A of e.nodes){const T=A.activeSessionDetails&&A.activeSessionDetails.length>0?A.activeSessionDetails:(A.activeSessions??[]).map(M=>({sessionId:M,workspace:A.workspace,isCached:!0}));for(const M of T)C.push({node:A,session:M})}return C},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(rN,{nodes:e.nodes,onResolve:k}),s.jsx(yN,{meshTheme:a,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:C=>p({kind:"mission",mission:C})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(vN,{meshTheme:a,ledgerSummary:u,entries:h,resolveNodeLabel:b,onSelect:C=>p({kind:"ledger",entry:C})}),s.jsx(wN,{meshTheme:a,queueSummary:i,tasks:c,onSelect:C=>p({kind:"queue",task:C})})]}),s.jsx(SN,{meshTheme:a,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(CN,{meshTheme:a,entries:j,onSelect:(C,A)=>p({kind:"session",node:C,session:A})}),s.jsx(jN,{meshTheme:a,jobs:x})]}),w&&s.jsx(hN,{meshTheme:a,detail:w,onClose:y,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:r,resolveNodeLabel:b})]})}function Qs({meshTheme:e,title:t,count:n,children:r,action:o}){const a=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),o&&s.jsx("span",{className:"ml-auto",children:o})]}),r]})}function Kt({meshTheme:e,label:t,tone:n}){const r=e.isDark,o=n==="rose"?r?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?r?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?r?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?r?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":r?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${o}`,children:t})}function St({meshTheme:e,label:t,value:n,tone:r}){const o=e.isDark,a=r==="rose"?o?"text-rose-300":"text-rose-600":r==="sky"?o?"text-sky-300":"text-sky-600":r==="amber"?o?"text-amber-300":"text-amber-600":r==="emerald"?o?"text-emerald-300":"text-emerald-600":r==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${a}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function yr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function $o({meshTheme:e,onClick:t,children:n}){const r=e.isDark,o=t?r?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${o} ${t?"cursor-pointer":"cursor-default"}`,children:n})}function Bo({meshTheme:e,expanded:t,hiddenCount:n,onToggle:r}){const{t:o}=Le("common");return n<=0?null:s.jsx("button",{type:"button",onClick:r,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?o("mesh.overview.showFewer"):o("mesh.overview.showMore",{count:n})})}function Fo(e,t=oN){const[n,r]=l.useState(!1),o=n?e:e.slice(0,t),a=Math.max(0,e.length-t),i=l.useCallback(()=>r(c=>!c),[]);return{visible:o,hiddenCount:a,expanded:n,toggle:i}}function gt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function uN(e,t){switch(e.kind){case"mission":return{kicker:t("mesh.overview.detailKickerMission"),title:e.mission.title};case"ledger":return{kicker:t("mesh.overview.detailKickerLedger"),title:ul(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:_o(e.session.sessionId)}}}function hN({meshTheme:e,detail:t,onClose:n,daemonId:r,meshId:o,sendDaemonCommand:a,resolveNodeLabel:i}){const{t:c}=Le("common");l.useEffect(()=>{const x=w=>{w.key==="Escape"&&n()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n]);const u=e.isDark,{kicker:h,title:d}=uN(t,c),m=u?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=u?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${m}`,role:"dialog","aria-modal":"true",onClick:n,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${f} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:h}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:d})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:u?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(fN,{meshTheme:e,mission:t.mission,daemonId:r,meshId:o,sendDaemonCommand:a}),t.kind==="ledger"&&s.jsx(bN,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(gN,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(xN,{meshTheme:e,node:t.node,session:t.session})]})]})})}const pN=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function mN(e){const t=pN(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function fN({meshTheme:e,mission:t,daemonId:n,meshId:r,sendDaemonCommand:o}){var v;const{t:a}=Le("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",u="goalTruncated"in t?t.goalTruncated===!0:!1,[h,d]=l.useState(null),[m,f]=l.useState(!1),[x,w]=l.useState(null),p=u&&!h&&!!n&&!!o,y=l.useCallback(async()=>{if(!(!n||!o)){f(!0),w(null);try{const g=await o(n,"mesh_status",{meshId:r??void 0,verbose:!0}),N=mN(g),A=(Array.isArray(N==null?void 0:N.missions)?N.missions:[]).find(M=>(M==null?void 0:M.id)===t.id),T=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;T?d(T):w("Full goal unavailable")}catch(g){w(g instanceof Error?g.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,r,o,t.id]),k=h??c,b=u&&!h,j=t.stats??null,S=((v=j==null?void 0:j.incompleteTaskIds)==null?void 0:v.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx(Kt,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),k&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[k,b&&!p&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),x&&s.jsx("div",{className:"text-[11px] text-amber-400",children:x}),p&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:y,disabled:m,children:a(m?"mesh.overview.loadingGoal":"mesh.overview.showFullGoal")}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statPending"),value:i.pending}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),j&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statWallClock"),value:cd(j.wallClockMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statTotalRuntime"),value:cd(j.totalDurationMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statRetries"),value:j.retries,tone:j.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelLastActivity"),value:ds(i.lastActivityAt)??i.lastActivityAt}),S>0&&j&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:a("mesh.overview.incompleteTaskCount_other",{count:S})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:j.incompleteTaskIds.map(g=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:g},g))})]})})]})]})}function bN({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:r}=Le("common"),o=Wp(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Kt,{meshTheme:e,label:ul(t.kind),tone:Hp(t.kind)})}),o&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:o}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelEntryId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWhen"),value:ds(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:n(t.nodeId)}),t.sessionId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSession"),value:_o(t.sessionId)}),t.providerType&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelProvider"),value:t.providerType})]}),a&&a!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:r("mesh.overview.detailLabelPayload")}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:a})]})]})}function gN({meshTheme:e,task:t}){const{t:n}=Le("common");return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Fp(t.status)}),(t.requeueCount??0)>0&&s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeued",{count:t.requeueCount}),tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelTaskId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelNode"),value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelSession"),value:_o(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCancelReason"),value:t.cancelReason}),t.requeueReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeueReason"),value:t.requeueReason}),t.autoLaunch&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelAutoLaunch"),value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function xN({meshTheme:e,node:t,session:n}){var a,i;const{t:r}=Le("common"),o=_p(n);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:o,tone:$p(o)}),s.jsx(Kt,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSessionId"),value:n.sessionId}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:t.machineLabel}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWorkspace"),value:n.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelBranch"),value:((i=t.git)==null?void 0:i.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelRole"),value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelStarted"),value:ds(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function dd({meshTheme:e,mission:t,onSelect:n}){const r=t.tasks,o=ds(r.lastActivityAt);return s.jsxs($o,{meshTheme:e,onClick:n,children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",r.completed,"/",r.total]}),o&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:o})]})}function yN({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:r,onSelect:o}){const{t:a}=Le("common"),[i,c]=l.useState(!1),u=e.isDark,h=Fo(t);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.missionCard"),count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.visible.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id)),s.jsx(Bo,{meshTheme:e,expanded:h.expanded,hiddenCount:h.hiddenCount,onToggle:h.toggle})]}):s.jsx(yr,{meshTheme:e,children:a(r?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(d=>!d),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${i?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:a("mesh.overview.completedHistory")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:n.length})]}),i&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id))})]})]})}function vN({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:r,onSelect:o}){const{t:a}=Le("common"),i=ds(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),u=Fo(c);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.ledgerCard"),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCheckpoints"),value:t.checkpointCreated})]}),c.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[u.visible.map(h=>{const d=Wp(h.payload);return s.jsxs($o,{meshTheme:e,onClick:()=>o(h),children:[s.jsx(Kt,{meshTheme:e,label:ul(h.kind),tone:Hp(h.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:h.nodeId||void 0,children:d||r(h.nodeId)||h.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(h.timestamp)??""})]},h.id)}),s.jsx(Bo,{meshTheme:e,expanded:u.expanded,hiddenCount:u.hiddenCount,onToggle:u.toggle})]})]}),(t.recentFailures>0||i&&c.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsx("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:a("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function wN({meshTheme:e,queueSummary:t,tasks:n,onSelect:r}){const o=l.useMemo(()=>[...n].sort((c,u)=>{const h=ld(c.status)-ld(u.status);return h!==0?h:(u.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,aN),[n]),a=Fo(o),{t:i}=Le("common");return t?s.jsxs(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),count:t.active>0?i("mesh.overview.activeCount",{count:t.active}):void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:i("mesh.overview.statPending"),value:t.pending}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statAssigned"),value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statActive"),value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCompleted"),value:t.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statFailed"),value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCancelled"),value:t.cancelled,tone:"muted"})]}),o.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:i("mesh.overview.recentTasks")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.visible.map(c=>s.jsxs($o,{meshTheme:e,onClick:()=>r(c),children:[s.jsx(Kt,{meshTheme:e,label:c.status,tone:Fp(c.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:tN(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(c.updatedAt)??""})]},c.id)),s.jsx(Bo,{meshTheme:e,expanded:a.expanded,hiddenCount:a.hiddenCount,onToggle:a.toggle})]})]})]}):s.jsx(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(yr,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function kN(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function SN({meshTheme:e,nodes:t}){const{t:n}=Le("common"),r=e.isDark;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(o=>{var u,h,d;const a=(((u=o.activeSessionDetails)==null?void 0:u.length)??0)||(((h=o.activeSessions)==null?void 0:h.length)??0),i=kN(o),c=((d=o.git)==null?void 0:d.branch)??o.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Kt,{meshTheme:e,label:o.health,tone:cN(o.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:o.workspace,children:o.machineLabel}),c&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:c,children:c}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:lN(o)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof o.daemonBuildVersion=="string"&&o.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",o.daemonBuildVersion]}),i&&s.jsx(Kt,{meshTheme:e,label:i.label,tone:i.tone})]},o.nodeId)})})})}function CN({meshTheme:e,entries:t,onSelect:n}){const{t:r}=Le("common"),o=Fo(t);return s.jsx(Qs,{meshTheme:e,title:r("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:r("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(({node:a,session:i})=>{const c=_p(i);return s.jsxs($o,{meshTheme:e,onClick:()=>n(a,i),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:_o(i.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),s.jsx(Kt,{meshTheme:e,label:c,tone:$p(c)})]},i.sessionId)}),s.jsx(Bo,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})})}function jN({meshTheme:e,jobs:t}){const{t:n}=Le("common"),r=e.isDark,o=t.filter(a=>a.status==="failed").length;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:o>0?s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.failedCount",{count:o}),tone:"rose"}):void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const NN=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function AN({meshTheme:e,open:t,onToggle:n}){const{t:r}=Le(),o=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?o?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":o?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:n,"aria-label":r("meshGraph.help.toggleAria"),"aria-expanded":t,title:r("meshGraph.help.toggleTitle"),className:`${a} ${i}`,children:s.jsx(Pf,{size:15})})}function TN({meshTheme:e,onClose:t}){const{t:n}=Le(),r=e.isDark,o=l.useMemo(()=>NN.map(a=>({term:n(`meshGraph.help.sections.${a}.term`),summary:n(`meshGraph.help.sections.${a}.summary`),details:n(`meshGraph.help.sections.${a}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const a=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("meshGraph.help.regionAria"),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(At,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:o.map(a=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:a.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:a.summary}),a.details&&a.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:a.details.map((i,c)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:i})]},c))})]},a.term))})]})}const tn=l.createContext(Rs("dark"));function Ve({label:e,tone:t="default",className:n,title:r}){const o=l.useContext(tn);return s.jsx("span",{title:r,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${o.badge(t)}${n?` ${n}`:""}`,children:e})}function Pt({label:e,value:t}){const n=l.useContext(tn);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}const IN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Op(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function Na(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function Xr(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function MN(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function DN(e){return e.startedAt||e.createdAt||null}function PN(e){const t=DN(e);if(!t)return"runtime age not reported";const n=Date.parse(t);if(!Number.isFinite(n))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-n)/1e3));if(r<60)return`${r}s`;const o=Math.floor(r/60);if(o<60)return`${o}m`;const a=Math.floor(o/60);return a<48?`${a}h ${o%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Up(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function LN(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function RN(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function EN(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];t.branch&&r.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&r.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`${n} dirty`);const o=(t.submodules??[]).filter(i=>i.dirty),a=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return o.length>0&&r.push(`${o.length} submodule dirty`),a.length>0&&r.push(`${a.length} submodule drift`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"Clean"}const _N={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function $N(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function BN(e){var n;const t=[];for(const r of e.nodes){const o=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(a=>({sessionId:a,workspace:r.workspace,isCached:!0}));for(const a of o)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((n=r.git)==null?void 0:n.branch)??null,nodeHealth:r.health,session:a})}return t}function FN(e){return e.assignedNodeId||e.targetNodeId||null}function fi(e){return e?e.slice(0,7):null}function HN(e,t){var a,i,c;const n=fi((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(n||r)return[n,r].filter(Boolean).join(" · ");const o=t[0];return o?[fi(o.commit),o.message].filter(Boolean).join(" · "):null}function WN(e,t){const n=HN(e,t);return n||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function ON(e){const t=(e==null?void 0:e.result)??e,n=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(n==null?void 0:n.entries)?n.entries:[]}function UN(e){var n,r,o,a,i,c;const t=((n=e.selectedSessionEntry)==null?void 0:n.session.workspace)||((r=e.selectedSessionEntry)==null?void 0:r.workspace)||((a=(o=e.selectedNodeStatus)==null?void 0:o.git)==null?void 0:a.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function GN(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":RN(e.connection)}function KN(e){var n;const t=e.source;return t!=null&&t.kind?t.kind:((n=t==null?void 0:t.connection)==null?void 0:n.source)??"mesh_status"}function ud(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function zN(e){return e.direction==="directed"?"directed":"undirected"}function qN(e,t){return t?e.nodes.find(n=>n.id===t)??null:null}function VN(e){var t,n,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((n=(t=e.queue)==null?void 0:t.summary)==null?void 0:n.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,c,u,h,d,m,f,x,w,p,y,k,b,j,S,v,g,N,C,A,T,M;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((c=a.connection)==null?void 0:c.transport)??"",((u=a.connection)==null?void 0:u.source)??"",a.health,a.gitProbePending?1:0,((h=a.git)==null?void 0:h.branch)??"",((d=a.git)==null?void 0:d.upstream)??"",((m=a.git)==null?void 0:m.upstreamStatus)??"",((f=a.git)==null?void 0:f.ahead)??"",((x=a.git)==null?void 0:x.behind)??"",((w=a.git)==null?void 0:w.headCommit)??"",((p=a.git)==null?void 0:p.staged)??"",((y=a.git)==null?void 0:y.modified)??"",((k=a.git)==null?void 0:k.untracked)??"",((b=a.git)==null?void 0:b.deleted)??"",((j=a.git)==null?void 0:j.renamed)??"",(S=a.git)!=null&&S.hasConflicts?1:0,((v=a.git)==null?void 0:v.lastCheckedAt)??"",((g=a.activeSessions)==null?void 0:g.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((C=a.activeSessionDetails)==null?void 0:C.map(L=>[L.sessionId,L.providerType??"",L.state??"",L.chatStatus??"",L.lifecycle??"",L.role??"",L.isSelfCoordinator?1:0,L.statusNote??"",L.startedAt??"",L.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((T=a.providerPriority)==null?void 0:T.join(","))??"",a.error??"",(((M=a.git)==null?void 0:M.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function YN(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function JN({scheduling:e}){const{t}=Le("common"),n=l.useContext(tn);if(!e)return s.jsx("div",{className:`${n.cardClass} rounded-2xl p-4 text-[12px] ${n.textSecondary}`,children:t("mesh.status.schedulingNotReported")});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.schedulingTitle")}),s.jsx(Ve,{label:_N[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ve,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ve,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:t("mesh.status.distributionTitle")})]})}function QN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ve,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ve,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ve,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ve,{label:$N(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function XN({node:e}){var d,m,f,x;const t=l.useContext(tn),n=((d=e.activeSessionDetails)==null?void 0:d.length)??((m=e.activeSessions)==null?void 0:m.length)??0,r=fi((f=e.git)==null?void 0:f.headCommit),o=e.isLocalWorktree===!0,a=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,u=c?Object.entries(c).filter(([,w])=>typeof w=="string"&&w):[],h=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ve,{label:e.health,tone:Op(e.health)}),o&&s.jsx(Ve,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(a==null?void 0:a.status)&&a.status!=="ready"&&s.jsx(Ve,{label:`bootstrap ${a.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((x=e.connection)==null?void 0:x.state)&&e.connection.state!=="self"&&s.jsx(Ve,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),n>0&&s.jsx(Ve,{label:`${n} session${n===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ve,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ve,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),h&&s.jsx(Ve,{label:`build ${h}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(QN,{scheduling:e.scheduling})]}),u.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:u.map(([w,p])=>s.jsx(Ve,{label:`${w}@${p}`,tone:"info",title:"Detected provider version on this node"},w))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[EN(e),r?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",r]}):null]})]})}function ZN({status:e}){const{t}=Le("common"),n=l.useContext(tn),r=e.meshProtocolMetrics,o=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&o.length===0?null:s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.protocolTitle")}),r&&s.jsx(Ve,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),o.length>0&&s.jsx(Ve,{label:`${o.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,i])=>s.jsx(Ve,{label:`${a}: ${i}`,tone:"default",title:"v2 event scope breakdown"},a))}),o.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:o.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:a.provider}),a.versions.map(i=>s.jsx(Ve,{label:`${i.version} · ${i.nodeIds.length} node${i.nodeIds.length===1?"":"s"}`,tone:"default",title:i.nodeIds.join(", ")},i.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function eA({canonicalStatus:e}){const{t}=Le("common"),n=l.useContext(tn);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(JN,{scheduling:e.scheduling}),s.jsx(ZN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.nodesRuntime")}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${n.textSecondary} ${n.isDark?"border-white/10":"border-slate-200"}`,children:t("mesh.status.noNodesReporting")}):e.nodes.map(r=>s.jsx(XN,{node:r},r.nodeId))]})]})}function tA({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:r,meshTheme:o,sessionEntries:a,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),u=n.recentFailures>0||n.taskFailed>0,h=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],d=e.asyncRefineJobs,m=(d==null?void 0:d.filter(g=>g.status==="running"||g.status==="accepted"))??[],f=(d==null?void 0:d.filter(g=>g.status==="failed"))??[],x=e.staleDirectWorkSummary,w=x&&x.count>0;if(!c&&!u&&e.nodes.length===0&&!r&&m.length===0&&f.length===0&&!w&&a.length===0)return null;const p=o.isDark,y=`border-t ${p?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${p?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${o.textSecondary}`;function j({label:g,value:N,tone:C}){const A=C==="rose"?p?"text-rose-300":"text-rose-600":C==="sky"?p?"text-sky-300":"text-sky-600":C==="amber"?p?"text-amber-300":"text-amber-600":C==="emerald"?p?"text-emerald-300":"text-emerald-600":C==="muted"?o.textMuted:o.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${p?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${A}`,children:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${o.textMuted}`,children:g})]})}const S=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Pending",value:t.pending}),s.jsx(j,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(j,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(j,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(j,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${o.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var L;const N=((L=g.connection)==null?void 0:L.state)??"unknown",C=N==="unknown"||N==="connecting",M=C?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?p?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?p?"bg-emerald-400":"bg-emerald-500":p?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${M}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${o.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${o.textMuted}`,children:C?"…":N})]},g.nodeId)})})}),d&&d.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:d.length}),f.length>0&&s.jsxs("span",{className:p?"text-rose-300":"text-rose-600",children:[f.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:d.slice(0,8).map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,children:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?p?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?p?"text-sky-300":"text-sky-600":p?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),h.length>0&&s.jsx("div",{className:d&&d.length>0?"":`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:`flex-1 ${p?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${p?"text-rose-400":"text-rose-500"}`,children:h.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:h.map(g=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${p?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${o.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),w&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${y}`,children:[s.jsx("span",{className:o.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${p?"text-amber-300":"text-amber-600"}`,children:x.count})]}),a.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:a.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:a.map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,title:g.session.sessionId,children:Up(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${o.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${o.textMuted}`,children:Xr(g.session)})]},g.session.sessionId))})]})})]});return i?S:s.jsxs("details",{className:`rounded-2xl border text-xs ${o.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${o.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),f.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[f.length," refine failed"]}),u&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[n.recentFailures," recent failures"]}),r&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),S]})}function Gp({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:r,onHelpOpenChange:o}){const{t:a}=Le("common"),i=c=>c?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:i(t==="overview"),onClick:()=>n("overview"),children:a("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:a("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:a("meshGraph.obs.tabGraph")})]}),s.jsx(AN,{meshTheme:e,open:r,onToggle:()=>o(!r)})]})}function sA({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:r=null,bootstrapFallback:o,activeTab:a,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:u,hideControls:h=!1}){var Xe,dt,it;const{t:d}=Le("common"),{theme:m}=Ls(),f=l.useMemo(()=>Rs(m),[m]),x=l.useMemo(()=>({merged_to_main:d("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:d("meshGraph.obs.convergenceNeedsMerge"),blocked_review:d("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:d("meshGraph.obs.convergenceCleanup"),not_mergeable:d("meshGraph.obs.convergenceNotMergeable")}),[d]),w=t??d("meshGraph.obs.emptyGraph"),p=l.useMemo(()=>Mu(e),[e]),y=o??YN(p),k=l.useMemo(()=>VN(p),[p]),b=l.useMemo(()=>Mp(p),[k]),[j,S]=l.useState("overview"),[v,g]=l.useState(!1),N=a??j,C=c??v,A=l.useCallback(he=>{i?i(he):S(he)},[i]),T=l.useCallback(he=>{u?u(he):g(he)},[u]),[M,L]=l.useState(!1);l.useEffect(()=>{N==="graph"&&L(!0)},[N]);const[P,B]=l.useState(null),[K,F]=l.useState(null),[R,Q]=l.useState(null),[E,I]=l.useState({}),[$,D]=l.useState(null),[U,Y]=l.useState(null),ae=l.useMemo(()=>new Map(p.nodes.map(he=>[he.nodeId,he])),[p.nodes]),z=l.useMemo(()=>new Map(b.nodes.map(he=>[he.id,he])),[b.nodes]),X=((Xe=p.queue)==null?void 0:Xe.summary)??null,de=((dt=p.ledger)==null?void 0:dt.summary)??IN,re=l.useMemo(()=>BN(p),[p]),W=l.useMemo(()=>{const he=new Map;for(const $e of re){const Fe=Xr($e.session);he.set(Fe,(he.get(Fe)??0)+1)}return[...he.entries()].sort(($e,Fe)=>Fe[1]-$e[1])},[re]);l.useEffect(()=>{P&&(z.has(P)||(B(null),Q(he=>!he||"nodeId"in he&&he.nodeId===P?null:he)))},[z,P]);const oe=P?ae.get(P)??null:null,V=qN(b,P),ie=(R==null?void 0:R.kind)==="edge"&&K?b.edges.find(he=>he.id===K)??null:null,ke=ie?b.nodes.find(he=>he.id===ie.source)??null:null,xe=ie?b.nodes.find(he=>he.id===ie.target)??null:null;l.useEffect(()=>{var he,$e,Fe;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:p.meshId,selectedNodeId:P,canonicalNode:Pv(oe),graphNode:V?{id:V.id,branch:V.branch,upstream:V.upstream,headCommit:V.submoduleCommit,submoduleCount:(($e=(he=oe==null?void 0:oe.git)==null?void 0:he.submodules)==null?void 0:$e.length)??0,snapshotCompleteness:V.snapshotCompleteness,snapshotWarnings:V.snapshotWarnings,branchConvergence:((Fe=V.branchConvergence)==null?void 0:Fe.status)??null}:null})}catch{}},[p.meshId,V,P,oe]);const Se=(R==null?void 0:R.kind)==="session"?re.find(he=>he.nodeId===R.nodeId&&he.session.sessionId===R.sessionId)??null:null,pe=l.useMemo(()=>re.filter(he=>he.nodeId===P),[P,re]),G=UN({coordinatorDaemonId:n,selectedNodeStatus:oe,selectedSessionEntry:Se}),O=(G==null?void 0:G.workspace)??null,Z=O?E[O]??null:null,q=WN(oe,(Z==null?void 0:Z.entries)??[]),me=(V==null?void 0:V.daemonId)??(oe==null?void 0:oe.daemonId)??n??null,Te=!!(V&&r&&me&&V.type!=="submoduleNode"&&V.behind>0&&V.ahead===0&&V.dirtyFiles===0&&!V.dirty&&!V.hasConflicts&&V.upstreamStatus==="fresh"),_=l.useCallback(()=>{B(null),F(null),Q(null),D(null)},[]);l.useEffect(()=>{D(null)},[P]);const te=l.useCallback(async()=>{if(!V||!me||!r||!Te)return;Y(V.id),D(null);const he=(oe==null?void 0:oe.workspace)??V.workspace??"";try{const $e=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!0,execute:!1}),Fe=($e==null?void 0:$e.result)??$e;if(D({phase:"dry_run",code:typeof(Fe==null?void 0:Fe.code)=="string"?Fe.code:void 0,error:typeof(Fe==null?void 0:Fe.operationError)=="string"?Fe.operationError:null,executed:(Fe==null?void 0:Fe.executed)===!0}),!(Fe!=null&&Fe.success)||Fe.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${V.label}?`))return;const ye=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!1,execute:!0}),Oe=(ye==null?void 0:ye.result)??ye;D({phase:"execute",code:typeof(Oe==null?void 0:Oe.code)=="string"?Oe.code:void 0,error:typeof(Oe==null?void 0:Oe.operationError)=="string"?Oe.operationError:null,executed:(Oe==null?void 0:Oe.executed)===!0})}catch($e){D({phase:"dry_run",error:$e instanceof Error?$e.message:"fast-forward failed"})}finally{Y(null)}},[Te,p.meshId,V,me,r]);l.useEffect(()=>{if(!V&&!ie)return;const he=$e=>{$e.key==="Escape"&&_()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[_,ie,V]),l.useEffect(()=>{if(!G||!r)return;const{daemonId:he,workspace:$e}=G,Fe=E[$e];if(Fe!=null&&Fe.loading||Fe&&(Fe.entries.length>0||Fe.error))return;let Ie=!1;return I(ye=>{var Oe;return{...ye,[$e]:{loading:!0,error:null,entries:((Oe=ye[$e])==null?void 0:Oe.entries)??[]}}}),r(he,"git_log",{workspace:$e,limit:5}).then(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:null,entries:ON(ye)}}))}).catch(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:ye instanceof Error?ye.message:"git_log failed",entries:[]}}))}),()=>{Ie=!0}},[E,G,r]);const ve=[...b.warnings??[],...p.nodes.filter(he=>he.machineStatus&&he.machineStatus!=="online").map(he=>`${he.machineLabel}: ${he.machineStatus}`)],ce=b.stats.incompleteSnapshotNodes>0,H=b.stats.followUpNodes>0?`${b.stats.followUpNodes} need follow-up`:ce?"mesh visibility incomplete":"mesh converged",fe=b.stats.followUpNodes>0?"danger":ce?"warn":"good",[je,Ce]=l.useState("LR"),Be=he=>he?f.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":f.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(tn.Provider,{value:f,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!h&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Gp,{meshTheme:f,activeTab:N,onActiveTabChange:A,helpOpen:C,onHelpOpenChange:T})}),C&&s.jsx(TN,{meshTheme:f,onClose:()=>T(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:N==="overview"&&s.jsx(dN,{status:p,daemonId:n,meshId:p.meshId,sendDaemonCommand:r})}),s.jsx("div",{className:`${N==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="status"&&s.jsx(eA,{canonicalStatus:p})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${f.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${f.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${f.textSecondary}`,children:[s.jsx(Ve,{label:H,tone:fe,className:"shrink-0"}),b.stats.blockedReviewNodes>0&&s.jsx(Ve,{label:`${b.stats.blockedReviewNodes} blocked`,title:`${b.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),b.stats.notMergeableNodes>0&&s.jsx(Ve,{label:`${b.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),b.stats.mergeReadyNodes>0&&s.jsx(Ve,{label:`${b.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),b.stats.cleanupCandidateNodes>0&&s.jsx(Ve,{label:`${b.stats.cleanupCandidateNodes} cleanup`,title:`${b.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),b.stats.offlineNodes>0&&s.jsx(Ve,{label:`${b.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),b.stats.incompleteSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.incompleteSnapshotNodes} incomplete`,title:`${b.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingGitSnapshotNodes} no-git`,title:`${b.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${b.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),b.stats.staleGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.staleGitSnapshotNodes} stale`,title:`${b.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((X==null?void 0:X.active)??0)>0&&s.jsx(Ve,{label:`${(X==null?void 0:X.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ve,{label:`${b.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),b.stats.totalActiveSessions>0&&s.jsx(Ve,{label:`${b.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:f.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Ce("auto"),className:Be(je==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Ce("LR"),className:Be(je==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ce("TB"),className:Be(je==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Fe;const he=((Fe=p.asyncRefineJobs)==null?void 0:Fe.filter(Ie=>Ie.status==="failed").length)??0,$e=de.recentFailures;return he>0?s.jsxs("span",{className:f.isDark?"text-rose-300":"text-rose-600",children:[he," refine failed"]}):$e>0?s.jsxs("span",{className:f.isDark?"text-amber-300":"text-amber-600",children:[$e," failures"]}):d("meshGraph.obs.health")})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(tA,{canonicalStatus:p,queueSummary:X,ledgerSummary:de,isBootstrapMode:y,meshTheme:f,sessionEntries:re,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.obs.legend")}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:`${b.stats.dirtyNodes} dirty`,tone:b.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${b.stats.orphanNodes} orphan`,tone:b.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${de.recentFailures} recent failures`,tone:de.recentFailures>0?"danger":"good"}),W.length===0?s.jsx(Ve,{label:"no session metadata"}):W.slice(0,2).map(([he,$e])=>s.jsx(Ve,{label:`${$e} ${he}`,tone:Na(he)},he))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ve,{label:"Submodule link = child checkout",tone:"warn"})]}),ve.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:ve.map(he=>s.jsx("span",{className:f.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:he},he))}),s.jsx("div",{className:`text-xs ${f.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&b.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${f.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${f.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:d("meshGraph.obs.bootstrapBanner")})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:M?b.nodes.length>0?s.jsx(Zj,{data:b,selectedNodeId:P,directionPref:je,onNodeClick:he=>{if((R==null?void 0:R.kind)==="node"&&P===he.id){_();return}F(null),B(he.id),Q({kind:"node",nodeId:he.id})},onEdgeClick:he=>{if((R==null?void 0:R.kind)==="edge"&&K===he.id){_();return}B(null),F(he.id),Q({kind:"edge",edgeId:he.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:w}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:d("meshGraph.obs.loadingGraph")})}),V&&(R==null?void 0:R.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedNode")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:V.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${f.textMuted}`,children:V.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[V.behind>0&&s.jsx("button",{type:"button",onClick:()=>{te()},disabled:!Te||U===V.id,className:f.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:U===V.id?d("meshGraph.obs.checking"):d("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const he=(oe==null?void 0:oe.health)??V.health;return he==="unknown"?s.jsx(Ve,{label:d("meshGraph.obs.connecting"),tone:"default"}):s.jsx(Ve,{label:he,tone:Op(he)})})(),V.branch&&s.jsx(Ve,{label:V.branch,tone:"default"}),V.ahead>0&&s.jsx(Ve,{label:`ahead ${V.ahead}`,tone:"warn"}),V.behind>0&&s.jsx(Ve,{label:`behind ${V.behind}`,tone:"warn"}),V.dirtyFiles>0&&s.jsx(Ve,{label:`${V.dirtyFiles} dirty`,tone:"warn"}),(oe==null?void 0:oe.connection)&&oe.connection.state!=="unknown"&&s.jsx(Ve,{label:GN(oe),tone:LN(oe.connection)}),((it=oe==null?void 0:oe.connection)==null?void 0:it.state)==="unknown"&&s.jsx(Ve,{label:d("meshGraph.obs.meshConnecting"),tone:"warn"}),pe.length>0&&s.jsx(Ve,{label:`${pe.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[V.machineLabel&&s.jsx(Pt,{label:d("meshGraph.obs.fieldMachine"),value:V.machineLabel}),V.locality&&V.locality!=="unknown"&&s.jsx(Pt,{label:d("meshGraph.obs.fieldLocality"),value:V.locality}),s.jsx(Pt,{label:d("meshGraph.obs.fieldWorkspace"),value:(oe==null?void 0:oe.workspace)??V.workspace}),q&&s.jsx(Pt,{label:d("meshGraph.obs.fieldHead"),value:q}),(V.dirtyFiles>0||V.ahead>0||V.behind>0)&&s.jsx(Pt,{label:d("meshGraph.obs.fieldDirtyAheadBehind"),value:`${V.dirtyFiles}/${V.ahead}/${V.behind}`}),pe.length>0&&s.jsx(Pt,{label:d("meshGraph.obs.fieldSessions"),value:String(pe.length)}),V.upstream&&s.jsx(Pt,{label:d("meshGraph.obs.fieldUpstream"),value:V.upstream}),(()=>{var $e;const he=(($e=oe==null?void 0:oe.connection)==null?void 0:$e.source)??KN(V);return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldSource"),value:String(he)}):null})(),(()=>{var $e;const he=($e=oe==null?void 0:oe.connection)==null?void 0:$e.transport;return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldTransport"),value:he}):null})(),(()=>{const he=V.machineId??(oe==null?void 0:oe.machineId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldMachineId"),value:he}):null})(),(()=>{const he=V.daemonId??(oe==null?void 0:oe.daemonId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldDaemonId"),value:he}):null})()]}),pe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:pe.map(he=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${f.textMuted}`,title:he.session.sessionId,children:Up(he.session.sessionId)}),s.jsx(Ve,{label:Xr(he.session),tone:Na(Xr(he.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${f.textMuted}`,children:[s.jsx("span",{className:"truncate",children:he.session.providerType||d("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:MN(he.session)}),s.jsx("span",{children:PN(he.session)})]}),he.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${f.textMuted}`,children:he.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${f.textMuted}`,title:he.session.workspace||he.workspace,children:[(he.session.workspace||he.workspace).slice(0,38),he.branch?` · ${he.branch}`:""]})]},he.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldCompleted"),value:String(de.taskCompleted)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:de.taskFailed>0?f.isDark?"text-rose-300":"text-rose-600":"",children:de.taskFailed})}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLaunched"),value:String(de.sessionLaunched)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:de.recentFailures>0?f.isDark?"text-amber-300":"text-amber-600":"",children:de.recentFailures})})]})]}),(()=>{var Fe,Ie;const he=((Fe=p.queue)==null?void 0:Fe.tasks)??((Ie=p.queue)==null?void 0:Ie.items)??null;if(!Array.isArray(he)||he.length===0)return null;const $e=he.filter(ye=>FN(ye)===P).slice(0,3);return $e.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:$e.map(ye=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${f.textMuted}`,children:ye.id.slice(0,12)}),s.jsx(Ve,{label:ye.status??"unknown",tone:Na(ye.status)})]}),ye.message&&s.jsx("div",{className:`mt-0.5 truncate ${f.textMuted}`,children:ye.message.slice(0,48)})]},ye.id))})]})})(),V.snapshotWarnings.length>0&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:V.snapshotWarnings[0]})]}),V.branchConvergence&&(V.branchConvergence.reason||V.branchConvergence.nextStep)&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.followUpLabel",{status:x[V.branchConvergence.status]??V.branchConvergence.status})}),V.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:V.branchConvergence.reason}),V.branchConvergence.nextStep&&s.jsx("div",{className:`${V.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:V.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?d("meshGraph.obs.healResult"):d("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:$.code??$.error??d("meshGraph.obs.noResultCode")})]})]}),ie&&(R==null?void 0:R.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedEdge")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:ie.label||ud(ie)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${f.textMuted}`,children:ie.id})]}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ve,{label:ud(ie),tone:"default"}),s.jsx(Ve,{label:zN(ie),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldFrom"),value:(ke==null?void 0:ke.label)??ie.source}),s.jsx(Pt,{label:d("meshGraph.obs.fieldTo"),value:(xe==null?void 0:xe.label)??ie.target}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLabel"),value:ie.label??"none"})]})]})]})]})})]})})}function Nt(e){return typeof e=="string"?e.trim():""}function bi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function hl(...e){const t=new Set;for(const n of e){const r=Nt(n);r&&t.add(r)}return[...t]}function nA(e,t){var m,f;const n=bi(e==null?void 0:e.settings),r=Nt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||Nt(n.meshCoordinatorFor),o=Nt(n.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const c=bi(e==null?void 0:e.activeChat),u=hl(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),h=u[0]||"";if(!h)return null;const d=r===t?Nt((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":o===t?Nt(n.meshNodeRole)||"worker":Nt(e==null?void 0:e.role)||Nt(n.meshNodeRole)||void 0;return{sessionId:h,aliases:u,meshId:t,nodeId:i&&Nt(n.meshNodeId)||null,providerType:Nt(e==null?void 0:e.providerType)||void 0,state:Nt(e==null?void 0:e.status)||void 0,chatStatus:Nt(c.status)||void 0,lifecycle:Nt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Nt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Nt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Nt(e==null?void 0:e.workspace)||null}}function Kp(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>nA(o,t)).filter(o=>o!==null):[]}function vo(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function rA(e,t){const n=new Set(vo(t));return vo(e).some(r=>n.has(r))}function oA(e,t){const n=t.filter(o=>!!o);return n.length===0?e:[...e.filter(o=>!n.some(a=>rA(o,a))),...n]}function aA(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of vo(i))n.set(c,i);let r=!1;const a=(e.nodes??[]).map((i,c)=>{const u=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],h=new Map;for(const f of u){const x=hl(f==null?void 0:f.sessionId,f==null?void 0:f.session_id,f==null?void 0:f.id,f==null?void 0:f.providerSessionId,f==null?void 0:f.provider_session_id),w=x[0]||"";if(!w)continue;const p=x.map(y=>n.get(y)).find(Boolean);p&&(r=!0),h.set(w,p?{...f,sessionId:w,providerType:p.providerType||f.providerType,state:p.state||f.state,chatStatus:p.chatStatus||f.chatStatus,lifecycle:p.lifecycle||f.lifecycle,surfaceKind:p.surfaceKind||f.surfaceKind,recoveryState:p.recoveryState||f.recoveryState,role:p.role||f.role,isSelfCoordinator:p.isSelfCoordinator??f.isSelfCoordinator,workspace:p.workspace||f.workspace}:{...f,sessionId:w})}for(const f of i.activeSessions??[])h.has(f)||h.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const d=c===0;for(const f of t){if(vo(f).some(y=>h.has(y)))continue;const w=f.nodeId!=null&&f.nodeId===i.nodeId,p=f.isSelfCoordinator&&!f.nodeId&&d;!w&&!p||(r=!0,h.set(f.sessionId,{sessionId:f.sessionId,providerType:f.providerType,state:f.state,chatStatus:f.chatStatus,lifecycle:f.lifecycle,surfaceKind:f.surfaceKind,recoveryState:f.recoveryState,role:f.role,isSelfCoordinator:f.isSelfCoordinator,workspace:f.workspace||i.workspace}))}const m=[...h.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return r?{...e,nodes:a}:e}function iA(e,t){const r=Kp(e,t).map(o=>{var u;const a=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(h=>Nt(h==null?void 0:h.id)===o.sessionId),i=bi(a==null?void 0:a.activeInteractivePrompt),c=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",Nt(i.status)||Nt(i.kind)||Nt(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
89
89
  `):null}function zp({status:e,daemonId:t,extraDaemonIds:n,meshId:r,sendData:o,extraLiveSessions:a=[]}){const[i,c]=l.useState(new Map),u=l.useRef(new Map),h=l.useMemo(()=>{const x=new Set;if(t&&x.add(t),n)for(const w of n)w&&x.add(w);return[...x].sort()},[t,n]),d=h.join(",");l.useEffect(()=>{u.current=new Map,c(new Map)},[t,r]),l.useEffect(()=>{if(!r||!o||h.length===0)return;const x=h.map(w=>ls.subscribe({sendData:o},w,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${w}`,params:{includeSessions:!0}},p=>{if(p.topic!=="daemon.metadata")return;const y=iA(p,r);if(y===(u.current.get(w)??null))return;u.current.set(w,y);const k=Kp(p,r);c(b=>{const j=new Map(b);return j.set(w,k),j})}));return()=>{for(const w of x)w()}},[d,r,o]);const m=l.useMemo(()=>{const x=[];for(const w of i.values())x.push(...w);return x},[i]),f=l.useMemo(()=>oA(m,a),[a,m]);return l.useMemo(()=>e?aA(e,f):null,[f,e])}const hd=[1500,4e3,9e3];function lA(e){var t,n,r,o,a,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(n=e.git)!=null&&n.branch||(r=e.git)!=null&&r.upstream||(o=e.git)!=null&&o.headCommit||(a=e.git)!=null&&a.workspace||(i=e.git)!=null&&i.repoRoot)}function cA(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var n;return lA(t)?!1:t.gitProbePending||((n=t.connection)==null?void 0:n.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function dA(e){return!Number.isInteger(e)||e<0?hd[0]:hd[e]??null}const Aa=new Map;function uA(e,t){return!e||!t?null:`${e}::${t}`}function hA(e,t){var a,i,c,u;if(!t||!e.sessionId)return null;const n=((a=e.coordinator)==null?void 0:a.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),r=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(n!==t&&r!==t)return null;const o=typeof((u=e.settings)==null?void 0:u.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:hl(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:o,providerType:e.agentType,state:e.status,chatStatus:e.status,role:n===t?"coordinator":"worker",isSelfCoordinator:n===t,workspace:e.workspacePath??null}}function qp({activeConv:e,sendDaemonCommand:t,onClose:n}){var ae,z,X,de,re,W;const r=((ae=e.coordinator)==null?void 0:ae.meshId)??(typeof((z=e.settings)==null?void 0:z.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),o=e.daemonId??null,a=uA(o,r),i=a?Aa.get(a)??null:null,c=Bi(),{sendData:u}=yt(),{theme:h}=Ls(),d=l.useMemo(()=>Rs(h),[h]),[m,f]=l.useState("overview"),[x,w]=l.useState(!1),p=l.useMemo(()=>hA(e,r),[e.agentType,(X=e.coordinator)==null?void 0:X.meshId,e.sessionId,(de=e.settings)==null?void 0:de.meshCoordinatorFor,(re=e.settings)==null?void 0:re.meshNodeFor,(W=e.settings)==null?void 0:W.meshNodeId,e.status,e.workspacePath,r]),[y,k]=l.useState(i),[b,j]=l.useState(!1),[S,v]=l.useState(!1),[g,N]=l.useState(!1),[C,A]=l.useState(null),[T,M]=l.useState((i==null?void 0:i.refreshedAt)??null),L=l.useRef(i!==null),P=l.useRef(!1),B=l.useRef(!1),K=l.useRef(!0),F=l.useRef(0),R=l.useRef(null);l.useEffect(()=>{L.current=y!==null},[y]);const Q=l.useCallback(()=>{R.current!==null&&(clearTimeout(R.current),R.current=null)},[]);l.useEffect(()=>{Q(),F.current=0;const oe=a?Aa.get(a)??null:null;k(oe),M((oe==null?void 0:oe.refreshedAt)??null),L.current=oe!==null,B.current=!1,v(!1),A(null)},[a,Q]);const E=l.useCallback(async(oe=!1,V=!1)=>{if(!o||!r){A("This coordinator does not expose a live mesh id."),k(null);return}if(P.current){oe&&(B.current=!0);return}V||(Q(),F.current=0),P.current=!0;const ie=!L.current;j(ie),v(oe&&L.current),A(null);try{const ke=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(o,r,{refresh:oe,retryProfile:V?"interactive":"settled"}):await t(o,"mesh_status",{meshId:r,refresh:oe}),xe=Hi(ke);if(!xe){A("mesh_status returned an unexpected payload.");return}if(a&&Aa.set(a,xe),k(xe),L.current=!0,M(xe.refreshedAt||new Date().toISOString()),cA(xe.nodes)){const Se=dA(F.current);Se!==null&&K.current&&(F.current+=1,R.current=setTimeout(()=>{K.current&&E(!0,!0)},Se))}else F.current=0}catch(ke){A(ke instanceof Error?ke.message:"Failed to load live mesh status")}finally{P.current=!1,j(!1),v(!1),B.current&&K.current&&(B.current=!1,window.setTimeout(()=>{K.current&&E(!0)},0))}},[a,Q,o,r,c,t]);l.useEffect(()=>(K.current=!0,F.current=0,(async()=>(await E(!1,!0),K.current&&R.current===null&&!P.current&&E(!0,!0)))(),()=>{K.current=!1,Q()}),[E,Q]),l.useEffect(()=>{const oe=V=>{V.key==="Escape"&&n()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[n]);const I=(y==null?void 0:y.meshName)||r||"Repo Mesh",$=l.useMemo(()=>p?[p]:[],[p]),D=zp({status:y,daemonId:o,meshId:r,sendData:u,extraLiveSessions:$}),U=T?new Date(T).toLocaleTimeString():null,Y=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:n,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:`relative ${d.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:n,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${d.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(At,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(es,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:d.dialogTitleClass,children:I}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>N(oe=>!oe),"aria-expanded":g,"aria-label":g?"Hide mesh details":"Show mesh details",className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:g?"Hide mesh details":"Show mesh details",children:s.jsx(Ni,{size:14})})]}),s.jsxs("p",{className:`${d.dialogSubtitleClass} ${g?"block":"hidden"} md:block`,children:[xt(e),e.workspaceName?` · ${e.workspaceName}`:"",y!=null&&y.repoIdentity?` · ${y.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Gp,{meshTheme:d,activeTab:m,onActiveTabChange:f,helpOpen:x,onHelpOpenChange:w}),U&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${U}`}),!S&&y&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:u&&!C?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{E(!0)},disabled:b||S,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||S?"Refreshing…":"Refresh"})]})]}),C&&s.jsx("div",{className:d.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:C}),s.jsx("div",{className:d.dialogBodyClass,children:D?s.jsx(sA,{status:D,emptyMessage:Y,daemonId:o,sendDaemonCommand:t,activeTab:m,onActiveTabChange:f,helpOpen:x,onHelpOpenChange:w,hideControls:!0}):s.jsx("div",{className:d.dialogEmptyClass,children:Y})})]})})}function pA(e,t){const{sendCommand:n}=yt(),[r,o]=l.useState(null),[a,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){o(null);return}i(!0),n(e,"git_remote_url",{workspace:t}).then(u=>{const h=(u==null?void 0:u.result)??u;o(typeof(h==null?void 0:h.remoteUrl)=="string"?h.remoteUrl:null)}).catch(()=>{o(null)}).finally(()=>i(!1))},[e,t,n]);const c=mA(r);return{remoteUrl:r,githubUrl:c,loading:a}}function mA(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const n=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return n?`https://github.com/${n[1]}`:null}const Vp=5e3;function fA(e){return`git:${e}`}function bA({workspace:e,includeDiffSummary:t=!1,intervalMs:n=Vp}){return{type:"subscribe",topic:"workspace.git",key:fA(e),params:{workspace:e,includeDiffSummary:t,intervalMs:n}}}function pl(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message}return t}function gA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{status:null,error:Xs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Xs(t,"Git status response did not include status")}}function xA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Xs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Xs(t,"Git diff summary response did not include diffSummary")}}function Ta(e){return e===void 0||typeof e=="boolean"}function yA(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ta(t.binary)&&Ta(t.truncated)&&Ta(t.staged)}function vA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Xs(t,"Git file diff request failed")}:yA(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Xs(t,"Git file diff response did not include a valid diff object")}}function wA({daemonId:e,workspace:t,enabled:n=!0,includeDiffSummary:r=!1,intervalMs:o=Vp}){const{sendCommand:a,sendData:i}=yt(),c=typeof t=="string"?t.trim():"",u=!!(n&&e&&c),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(!1),[p,y]=l.useState(null),k=l.useCallback(async()=>{if(!(!u||!e||!c)){w(!0),y(null);try{const j=gA(await a(e,"git_status",{workspace:c}));if(j.error){d(null),f(null),y(j.error);return}if(d(j.status),!r){f(null);return}const S=xA(await a(e,"git_diff_summary",{workspace:c}));if(S.error){f(null),y(S.error);return}f(S.diffSummary)}catch(j){y(Xs(j,"Git status request failed"))}finally{w(!1)}}},[u,e,r,a,c]),b=l.useMemo(()=>c?bA({workspace:c,includeDiffSummary:r,intervalMs:o}):null,[r,o,c]);return l.useEffect(()=>{if(!u||!e||!c||!b){d(null),f(null),w(!1),y(null);return}const j=i?ls.subscribe({sendData:i},e,b,S=>{var v,g;S.workspace===c&&(d(S.status),f(S.diffSummary??null),y(((v=S.status)==null?void 0:v.error)||((g=S.diffSummary)==null?void 0:g.error)||null),w(!1))},{retryIntervalMs:1e3}):null;return k(),()=>{j==null||j()}},[u,e,k,b,i,c]),{status:h,diffSummary:m,loading:x,error:p,refresh:k}}const kA={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},SA={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function pd(e){return e.split("/").pop()??e}function CA(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function jA({files:e,truncated:t,onFileClick:n,selectedPath:r,className:o=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${o}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(a=>{const i=r===a.path,c=kA[a.status]??"?",u=SA[a.status]??"text-text-muted",h=CA(a.path),d=pd(a.path),m=a.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>n==null?void 0:n(a),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:a.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[h&&s.jsxs("span",{className:"text-text-secondary",children:[h,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),a.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",pd(a.oldPath)]}),m]}),!a.binary&&(a.insertions>0||a.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[a.insertions>0&&s.jsxs("span",{className:"text-status-online",children:["+",a.insertions]}),a.insertions>0&&a.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),a.deletions>0&&s.jsxs("span",{className:"text-status-error",children:["-",a.deletions]})]}),a.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${a.path}-${a.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function NA(e,t){let n="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?n="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?n="bg-status-error/10 text-status-error":e.startsWith("@@")?n="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(n="text-text-secondary"),s.jsx("div",{className:`px-3 ${n}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function AA({diff:e,binary:t,truncated:n,loading:r,error:o,className:a=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),r)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:"Loading diff…"});if(o)return s.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${a}`,children:o});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"No diff available."});const c=e.split(`
90
90
  `);return s.jsxs("div",{ref:i,className:`overflow-auto ${a}`,children:[s.jsx("div",{className:"py-1",children:c.map((u,h)=>NA(u,h))}),n&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function TA(e,t){const n=[`Branch: ${e||"unknown"}`];n.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const o of t.files)r[o.status]||(r[o.status]=[]),r[o.status].push(o.path);for(const[o,a]of Object.entries(r))n.push(`${o}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return n.join(`
91
- `)}function Yp({daemonId:e,workspace:t,onClose:n}){const{sendCommand:r}=yt(),{status:o,diffSummary:a,loading:i,error:c,refresh:u}=wA({daemonId:e,workspace:t,includeDiffSummary:!0}),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(""),[p,y]=l.useState(!1),[k,b]=l.useState(!1),[j,S]=l.useState(null),[v,g]=l.useState(null),{githubUrl:N}=pA(e,t),C=l.useCallback(async B=>{if(!((h==null?void 0:h.path)===B.path&&!h.loading)){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const K=await r(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),F=vA(K);if(F.error||!F.diff){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F.error??"Failed to load diff"});return}d({path:B.path,diff:F.diff.diff,binary:F.diff.binary??!1,truncated:F.diff.truncated??!1,loading:!1,error:null})}catch(K){const F=K instanceof Error?K.message:"Failed to load diff";d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F})}}},[e,r,h,t]),A=l.useCallback(B=>{w(""),y(!1),S(null),g(null),f(B)},[]),T=l.useCallback(()=>{f(null),S(null),b(!1)},[]),M=l.useCallback(async()=>{var B,K,F;if(m){b(!0),S(null);try{let R;m==="checkpoint"?R=await r(e,"git_checkpoint",{workspace:t,message:x,includeUntracked:p}):m==="stash"?R=await r(e,"git_stash_push",{workspace:t,message:x,includeUntracked:p}):m==="stash_pop"?R=await r(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&h&&(R=await r(e,"git_checkout_files",{workspace:t,paths:[h.path]}));const Q=(R==null?void 0:R.result)??R;if((Q==null?void 0:Q.success)===!1||Q!=null&&Q.error){S((Q==null?void 0:Q.error)??"Action failed"),b(!1);return}m==="checkpoint"?g(`Checkpoint created: ${((K=(B=Q==null?void 0:Q.checkpoint)==null?void 0:B.commit)==null?void 0:K.slice(0,7))??"done"}`):m==="stash"?g(`Stashed as ${((F=Q==null?void 0:Q.stash)==null?void 0:F.stashRef)??"stash@{0}"}`):m==="stash_pop"?g("Stash restored"):(g("File reverted"),d(null)),f(null),await u()}catch(R){S(R instanceof Error?R.message:"Action failed")}finally{b(!1)}}},[m,r,e,t,x,p,h,u]),L=!!(o!=null&&o.hasConflicts),P=o?o.staged+o.modified+o.untracked+o.deleted+o.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:B=>{B.target===B.currentTarget&&n()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(o==null?void 0:o.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&s.jsx("a",{href:`${N}/tree/${(o==null?void 0:o.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:n,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(At,{className:"h-4 w-4"})})]}),o&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[o.headCommit&&s.jsxs("span",{title:o.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:o.headCommit.slice(0,7)}),o.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:o.headMessage.slice(0,60)})]}),o.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",o.ahead," ahead"]}),o.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",o.behind," behind"]}),o.staged>0&&s.jsxs("span",{className:"text-status-online",children:[o.staged," staged"]}),o.modified>0&&s.jsxs("span",{children:[o.modified," modified"]}),o.untracked>0&&s.jsxs("span",{children:[o.untracked," untracked"]}),o.deleted>0&&s.jsxs("span",{className:"text-status-error",children:[o.deleted," deleted"]}),o.stashCount>0&&s.jsxs("span",{children:[o.stashCount," stashed"]}),o.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!o.error&&s.jsx("span",{className:"text-status-online",children:"clean"}),a&&a.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[a.files.length," file",a.files.length!==1?"s":"",a.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",a.totalInsertions]}),a.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",a.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!a&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),a&&s.jsx(jA,{files:a.files,truncated:a.truncated,selectedPath:(h==null?void 0:h.path)??null,onFileClick:C}),!i&&!a&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:h?s.jsx(AA,{diff:h.diff,binary:h.binary,truncated:h.truncated,loading:h.loading,error:h.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>A("checkpoint"),disabled:L,title:L?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>A("stash"),disabled:L,title:L?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>A("stash_pop"),disabled:L||!(o!=null&&o.stashCount),title:L?"Resolve conflicts before restoring a stash":o!=null&&o.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>A("checkout_files"),disabled:!h,title:h?`Revert changes to ${h.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),a&&a.files.length>0&&s.jsx("button",{onClick:()=>{const B=TA((o==null?void 0:o.branch)??null,a);navigator.clipboard.writeText(B),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(h==null?void 0:h.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:x,onChange:B=>w(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:B=>y(B.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-status-error",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:T,disabled:k,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:k||(m==="checkpoint"||m==="stash")&&!x.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:k?"Working…":"Confirm"})]})]})})]})})}function IA({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[r,o]=l.useState(!1),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(!1),[m,f]=l.useState(!1),[x,w]=l.useState("quickstart"),[p,y]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(C=>{o(C),C&&i(!1)},[]),j=l.useCallback(C=>{i(C),C&&o(!1)},[]),S=l.useCallback(()=>{w(n===0?"quickstart":"shortcuts"),y("workspace"),u(!0),o(!1),i(!1)},[n]),v=l.useCallback(()=>{u(!1)},[]),g=l.useCallback(()=>{d(!0)},[]),N=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!k){f(!1);return}f(!0);const C=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(C)},[k]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:c,newSessionOpen:h,guideNudgeVisible:m,guideTab:x,shortcutSection:p,isDesktopDashboard:k,setGuideTab:w,setShortcutSection:y,handleInboxOpenChange:b,handleHiddenOpenChange:j,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:g,closeNewSession:N}}function MA(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function DA(e){return e instanceof Error?e.message:String(e||"")}function PA(e){const t=DA(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function LA({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:h,mobileChatConversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,initialDataLoaded:b,userName:j,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,visibleConversations:X,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:re,onDesktopActiveTabChange:W,onRequestScrollToBottom:oe,onHideConversation:V,onShowHiddenConversation:ie,onShowAllHiddenConversations:ke,scrollToBottomRequest:xe,machineEntries:Se,layoutProfile:pe,onBrowseMachineDirectory:G,onSaveMachineWorkspace:O,onLaunchMachineIde:Z,onLaunchMachineProvider:q,onListMachineMeshes:me,onLaunchMeshCoordinator:Te,onListMachineSavedSessions:_,notifications:se,notificationUnreadCount:ve,liveSessionInboxState:ce,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}){const Ce=Rt.useRef(null),{inboxOpen:Be,hiddenOpen:Xe,shortcutHelpOpen:dt,newSessionOpen:it,guideNudgeVisible:he,guideTab:$e,shortcutSection:Fe,isDesktopDashboard:Ie,setGuideTab:ye,setShortcutSection:Oe,handleInboxOpenChange:ut,handleHiddenOpenChange:at,handleOpenShortcutHelp:ht,closeShortcutHelp:J,openNewSession:te,closeNewSession:le}=IA({isMobile:t,showMobileChatMode:e,visibleConversationCount:X.length}),[ue,ge]=Rt.useState(null),[Ae,Pe]=Rt.useState(null),Ne=Rt.useCallback((Me,Qe)=>{ge({daemonId:Me,workspace:Qe})},[]),He=Rt.useCallback(Me=>{Pe(Me)},[]),Ue=Rt.useCallback(Me=>{var Qe;fn.flushSync(()=>{ie(Me)}),(Qe=Ce.current)==null||Qe.restoreHiddenTabToSavedLocation(Me.tabKey)},[ie]),Ze=Rt.useCallback(Me=>{var Dt;const Qe=d.find(It=>Ja(It,Me))||m.find(It=>Ja(It,Me));Qe&&(m.some(It=>It.tabKey===Qe.tabKey)&&Ue(Qe),W(Qe.tabKey),(Dt=Ce.current)==null||Dt.activateConversationTab(Qe.tabKey),oe(Qe.tabKey,"notification-open")),H(Me.id),ut(!1)},[Ue,m,d,W,H,oe]),_e=Rt.useCallback(()=>{var Qe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Qe=Ce.current)==null||Qe.resetAllPanelsToMain(),at(!1))},[at]),Ge=Rt.useCallback(async Me=>{var Vt;if(!n)return;const Qe=(Vt=n.modalButtons)==null?void 0:Vt[Me];if(!Qe)return;const Dt=Us(n);if(!Dt)return;const It=Qe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),qt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(It);try{await w(Dt,"resolve_action",{button:Qe,action:qt?"approve":"reject",buttonIndex:Me,...Os(n)})}catch(Yt){PA(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[n,w]),{isMac:et,actionDefinitions:ee,actionShortcuts:be,shortcutListening:we,shortcutListeningDraft:ze,setShortcutListening:We,setShortcutListeningDraft:tt,saveShortcuts:qe}=c1({enabled:Ie&&!dt,onTrigger:Me=>{var Qe,Dt,It,qt,Vt,Yt,xs,Re,rt,jt,Ot,ne,Ke,Ee,vt,Jt;if(Me==="openShortcutHelp"){ht();return}if(Me==="openNewSession"){te();return}if(Me==="hideCurrentTab"){n&&V(n);return}if(Me==="toggleHiddenTabs"){at(!Xe);return}if(Me==="openHistoryForActiveTab"){n&&!lt(n)&&a(n);return}if(Me==="openRemoteForActiveTab"){n&&!ct(n)&&!lt(n)&&i(n);return}if(Me==="splitActiveTabRight"){(Qe=Ce.current)==null||Qe.splitActiveTabRight();return}if(Me==="splitActiveTabDown"){(Dt=Ce.current)==null||Dt.splitActiveTabDown();return}if(Me==="floatActiveTab"){(It=Ce.current)==null||It.floatActiveTab();return}if(Me==="popoutActiveTab"){(qt=Ce.current)==null||qt.popoutActiveTab();return}if(Me==="dockActiveTab"){(Vt=Ce.current)==null||Vt.dockActiveTab();return}if(Me==="focusLeftPane"){(Yt=Ce.current)==null||Yt.focusLeftPane();return}if(Me==="focusRightPane"){(xs=Ce.current)==null||xs.focusRightPane();return}if(Me==="focusUpPane"){(Re=Ce.current)==null||Re.focusUpPane();return}if(Me==="focusDownPane"){(rt=Ce.current)==null||rt.focusDownPane();return}if(Me==="moveActiveTabToLeftPane"){(jt=Ce.current)==null||jt.moveActiveTabToLeftPane();return}if(Me==="moveActiveTabToRightPane"){(Ot=Ce.current)==null||Ot.moveActiveTabToRightPane();return}if(Me==="moveActiveTabToUpPane"){(ne=Ce.current)==null||ne.moveActiveTabToUpPane();return}if(Me==="moveActiveTabToDownPane"){(Ke=Ce.current)==null||Ke.moveActiveTabToDownPane();return}if(Me==="triggerPrimaryApprovalAction"){Ge(0);return}if(Me==="triggerSecondaryApprovalAction"){Ge(1);return}if(Me==="triggerTertiaryApprovalAction"){Ge(2);return}if(Me==="setActiveTabShortcut"){(Ee=Ce.current)==null||Ee.setShortcutForActiveTab();return}if(Me==="selectPreviousGroupTab"){(vt=Ce.current)==null||vt.activatePreviousTabInGroup();return}if(Me==="selectNextGroupTab"){(Jt=Ce.current)==null||Jt.activateNextTabInGroup();return}!n||!ct(n)||lt(n)||Me==="toggleCliView"&&h(u==="chat"?"terminal":"chat")}}),Ye=Rt.useCallback(()=>{J(),We(null),tt([])},[J,We,tt]),Tt=Rt.useMemo(()=>Fe==="all"?ee:ee.filter(Me=>MA(Me)===Fe),[ee,Fe]),Wt=Rt.useCallback(()=>{const Me=Object.fromEntries(ee.map(Qe=>[Qe.id,""]));qe(Me)},[ee,qe]),ss=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Me=Object.fromEntries(ee.map(Qe=>[Qe.id,Qe.defaultShortcut]));qe(Me)},[ee,qe]);return Rt.useEffect(()=>{const Me=Qe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Qe.metaKey&&Qe.key.toLowerCase()==="w":Qe.ctrlKey&&Qe.key.toLowerCase()==="w")&&(Qe.preventDefault(),n&&V&&V(n))};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[n,V]),Rt.useEffect(()=>{if(!dt||we)return;const Me=Qe=>{Qe.key==="Escape"&&(Qe.preventDefault(),Ye())};return window.addEventListener("keydown",Me,!0),()=>window.removeEventListener("keydown",Me,!0)},[Ye,dt,we]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(K0,{activeConv:n,wsStatus:r,isConnected:o,conversations:X,hiddenConversations:m,onOpenHistory:a,onHideConversation:V,onShowConversation:Ue,onShowAllHidden:ke,onResetPanelsToMain:_e,notifications:se,notificationUnreadCount:ve,onOpenNotification:Ze,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je,inboxOpen:Be,onInboxOpenChange:ut,hiddenOpen:Xe,onHiddenOpenChange:at,onOpenNewSession:t?void 0:te,onOpenDashboardGuide:ht,guideNudgeVisible:he,actionShortcuts:be,onOpenRemote:()=>{!n||ct(n)||lt(n)||i(n)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:h,onOpenGitDialog:Ne,onOpenMeshGraph:He}),e?s.jsx(QC,{conversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,userName:j,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,onOpenHistory:a,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:o,onShowAllHiddenConversations:ke,onHideConversation:V,onOpenMeshGraph:He,onOpenNewSession:te,liveSessionInboxState:ce}):t?s.jsx(o1,{containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,userName:j,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,onOpenNewSession:te,allowTabShortcuts:!1,liveSessionInboxState:ce}):s.jsx(S1,{visibleConversations:X,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,initialDataLoaded:b,userName:j,toggleHiddenTab:z,actionShortcuts:be,registerActionHandlers:Me=>{Ce.current=Me},onActiveTabChange:W,requestedActiveTabKey:de,onRequestedActiveTabConsumed:re,onRequestScrollToBottom:oe,scrollToBottomRequest:xe,onOpenNewSession:te,liveSessionInboxState:ce,layoutProfile:pe}),it&&s.jsx(L1,{machines:Se,ides:f,onClose:le,onBrowseDirectory:G,onSaveWorkspace:O,onLaunchIde:Z,onLaunchProvider:q,onListMeshes:me,onLaunchMeshCoordinator:Te,onListSavedSessions:_}),Ae&&s.jsx(qp,{activeConv:Ae,sendDaemonCommand:w,onClose:()=>Pe(null)}),ue&&s.jsx(Yp,{daemonId:ue.daemonId,workspace:ue.workspace,onClose:()=>ge(null)}),dt&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ye,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Me=>Me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ye,"aria-label":"Close dashboard guide",children:s.jsx(At,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${$e===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ye(Me.id),children:Me.label},Me.id))}),$e==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",et?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),$e==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),$e==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Fe===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>Oe(Me.id),children:Me.label},Me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Wt,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:ss,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Tt.map(Me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${we===Me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:we===Me.id?ze.length>0?`${ze.join(" ")} ...`:"Listening...":be[Me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{We(Me.id),tt([])},children:we===Me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Qe={...be};Qe[Me.id]="",qe(Qe)},children:"Disable"})]})]})},Me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",et?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const RA=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"👀",title:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],EA={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},_A={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function $A({onClose:e,standalone:t=!1}){const[n,r]=l.useState(0),o=[...RA,t?_A:EA],a=o[n],i=n===o.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(At,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:o.map((c,u)=>s.jsx("div",{style:{width:u===n?24:8,height:8,borderRadius:4,background:u===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:a.visual||a.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:a.icon})," ",a.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:a.desc}),a.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),a.code]}),i&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>i?e():r(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
91
+ `)}function Yp({daemonId:e,workspace:t,onClose:n}){const{sendCommand:r}=yt(),{status:o,diffSummary:a,loading:i,error:c,refresh:u}=wA({daemonId:e,workspace:t,includeDiffSummary:!0}),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(""),[p,y]=l.useState(!1),[k,b]=l.useState(!1),[j,S]=l.useState(null),[v,g]=l.useState(null),{githubUrl:N}=pA(e,t),C=l.useCallback(async B=>{if(!((h==null?void 0:h.path)===B.path&&!h.loading)){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const K=await r(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),F=vA(K);if(F.error||!F.diff){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F.error??"Failed to load diff"});return}d({path:B.path,diff:F.diff.diff,binary:F.diff.binary??!1,truncated:F.diff.truncated??!1,loading:!1,error:null})}catch(K){const F=K instanceof Error?K.message:"Failed to load diff";d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F})}}},[e,r,h,t]),A=l.useCallback(B=>{w(""),y(!1),S(null),g(null),f(B)},[]),T=l.useCallback(()=>{f(null),S(null),b(!1)},[]),M=l.useCallback(async()=>{var B,K,F;if(m){b(!0),S(null);try{let R;m==="checkpoint"?R=await r(e,"git_checkpoint",{workspace:t,message:x,includeUntracked:p}):m==="stash"?R=await r(e,"git_stash_push",{workspace:t,message:x,includeUntracked:p}):m==="stash_pop"?R=await r(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&h&&(R=await r(e,"git_checkout_files",{workspace:t,paths:[h.path]}));const Q=(R==null?void 0:R.result)??R;if((Q==null?void 0:Q.success)===!1||Q!=null&&Q.error){S((Q==null?void 0:Q.error)??"Action failed"),b(!1);return}m==="checkpoint"?g(`Checkpoint created: ${((K=(B=Q==null?void 0:Q.checkpoint)==null?void 0:B.commit)==null?void 0:K.slice(0,7))??"done"}`):m==="stash"?g(`Stashed as ${((F=Q==null?void 0:Q.stash)==null?void 0:F.stashRef)??"stash@{0}"}`):m==="stash_pop"?g("Stash restored"):(g("File reverted"),d(null)),f(null),await u()}catch(R){S(R instanceof Error?R.message:"Action failed")}finally{b(!1)}}},[m,r,e,t,x,p,h,u]),L=!!(o!=null&&o.hasConflicts),P=o?o.staged+o.modified+o.untracked+o.deleted+o.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:B=>{B.target===B.currentTarget&&n()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(o==null?void 0:o.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&s.jsx("a",{href:`${N}/tree/${(o==null?void 0:o.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:n,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(At,{className:"h-4 w-4"})})]}),o&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[o.headCommit&&s.jsxs("span",{title:o.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:o.headCommit.slice(0,7)}),o.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:o.headMessage.slice(0,60)})]}),o.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",o.ahead," ahead"]}),o.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",o.behind," behind"]}),o.staged>0&&s.jsxs("span",{className:"text-status-online",children:[o.staged," staged"]}),o.modified>0&&s.jsxs("span",{children:[o.modified," modified"]}),o.untracked>0&&s.jsxs("span",{children:[o.untracked," untracked"]}),o.deleted>0&&s.jsxs("span",{className:"text-status-error",children:[o.deleted," deleted"]}),o.stashCount>0&&s.jsxs("span",{children:[o.stashCount," stashed"]}),o.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!o.error&&s.jsx("span",{className:"text-status-online",children:"clean"}),a&&a.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[a.files.length," file",a.files.length!==1?"s":"",a.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",a.totalInsertions]}),a.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",a.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!a&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),a&&s.jsx(jA,{files:a.files,truncated:a.truncated,selectedPath:(h==null?void 0:h.path)??null,onFileClick:C}),!i&&!a&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:h?s.jsx(AA,{diff:h.diff,binary:h.binary,truncated:h.truncated,loading:h.loading,error:h.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>A("checkpoint"),disabled:L,title:L?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>A("stash"),disabled:L,title:L?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>A("stash_pop"),disabled:L||!(o!=null&&o.stashCount),title:L?"Resolve conflicts before restoring a stash":o!=null&&o.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>A("checkout_files"),disabled:!h,title:h?`Revert changes to ${h.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),a&&a.files.length>0&&s.jsx("button",{onClick:()=>{const B=TA((o==null?void 0:o.branch)??null,a);navigator.clipboard.writeText(B),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(h==null?void 0:h.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:x,onChange:B=>w(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:B=>y(B.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-status-error",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:T,disabled:k,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:k||(m==="checkpoint"||m==="stash")&&!x.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:k?"Working…":"Confirm"})]})]})})]})})}function IA({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[r,o]=l.useState(!1),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(!1),[m,f]=l.useState(!1),[x,w]=l.useState("quickstart"),[p,y]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(C=>{o(C),C&&i(!1)},[]),j=l.useCallback(C=>{i(C),C&&o(!1)},[]),S=l.useCallback(()=>{w(n===0?"quickstart":"shortcuts"),y("workspace"),u(!0),o(!1),i(!1)},[n]),v=l.useCallback(()=>{u(!1)},[]),g=l.useCallback(()=>{d(!0)},[]),N=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!k){f(!1);return}f(!0);const C=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(C)},[k]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:c,newSessionOpen:h,guideNudgeVisible:m,guideTab:x,shortcutSection:p,isDesktopDashboard:k,setGuideTab:w,setShortcutSection:y,handleInboxOpenChange:b,handleHiddenOpenChange:j,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:g,closeNewSession:N}}function MA(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function DA(e){return e instanceof Error?e.message:String(e||"")}function PA(e){const t=DA(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function LA({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:h,mobileChatConversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,initialDataLoaded:b,userName:j,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,visibleConversations:X,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:re,onDesktopActiveTabChange:W,onRequestScrollToBottom:oe,onHideConversation:V,onShowHiddenConversation:ie,onShowAllHiddenConversations:ke,scrollToBottomRequest:xe,machineEntries:Se,layoutProfile:pe,onBrowseMachineDirectory:G,onSaveMachineWorkspace:O,onLaunchMachineIde:Z,onLaunchMachineProvider:q,onListMachineMeshes:me,onLaunchMeshCoordinator:Te,onListMachineSavedSessions:_,notifications:te,notificationUnreadCount:ve,liveSessionInboxState:ce,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}){const Ce=Rt.useRef(null),{inboxOpen:Be,hiddenOpen:Xe,shortcutHelpOpen:dt,newSessionOpen:it,guideNudgeVisible:he,guideTab:$e,shortcutSection:Fe,isDesktopDashboard:Ie,setGuideTab:ye,setShortcutSection:Oe,handleInboxOpenChange:ut,handleHiddenOpenChange:at,handleOpenShortcutHelp:ht,closeShortcutHelp:J,openNewSession:ee,closeNewSession:le}=IA({isMobile:t,showMobileChatMode:e,visibleConversationCount:X.length}),[ue,ge]=Rt.useState(null),[Ae,Pe]=Rt.useState(null),Ne=Rt.useCallback((Me,Qe)=>{ge({daemonId:Me,workspace:Qe})},[]),He=Rt.useCallback(Me=>{Pe(Me)},[]),Ke=Rt.useCallback(Me=>{var Qe;fn.flushSync(()=>{ie(Me)}),(Qe=Ce.current)==null||Qe.restoreHiddenTabToSavedLocation(Me.tabKey)},[ie]),Ze=Rt.useCallback(Me=>{var Dt;const Qe=d.find(It=>Ja(It,Me))||m.find(It=>Ja(It,Me));Qe&&(m.some(It=>It.tabKey===Qe.tabKey)&&Ke(Qe),W(Qe.tabKey),(Dt=Ce.current)==null||Dt.activateConversationTab(Qe.tabKey),oe(Qe.tabKey,"notification-open")),H(Me.id),ut(!1)},[Ke,m,d,W,H,oe]),_e=Rt.useCallback(()=>{var Qe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Qe=Ce.current)==null||Qe.resetAllPanelsToMain(),at(!1))},[at]),Ue=Rt.useCallback(async Me=>{var Vt;if(!n)return;const Qe=(Vt=n.modalButtons)==null?void 0:Vt[Me];if(!Qe)return;const Dt=Us(n);if(!Dt)return;const It=Qe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),qt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(It);try{await w(Dt,"resolve_action",{button:Qe,action:qt?"approve":"reject",buttonIndex:Me,...Os(n)})}catch(Yt){PA(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[n,w]),{isMac:et,actionDefinitions:se,actionShortcuts:be,shortcutListening:we,shortcutListeningDraft:ze,setShortcutListening:We,setShortcutListeningDraft:tt,saveShortcuts:qe}=c1({enabled:Ie&&!dt,onTrigger:Me=>{var Qe,Dt,It,qt,Vt,Yt,xs,Re,rt,jt,Ot,ne,Ge,Ee,vt,Jt;if(Me==="openShortcutHelp"){ht();return}if(Me==="openNewSession"){ee();return}if(Me==="hideCurrentTab"){n&&V(n);return}if(Me==="toggleHiddenTabs"){at(!Xe);return}if(Me==="openHistoryForActiveTab"){n&&!lt(n)&&a(n);return}if(Me==="openRemoteForActiveTab"){n&&!ct(n)&&!lt(n)&&i(n);return}if(Me==="splitActiveTabRight"){(Qe=Ce.current)==null||Qe.splitActiveTabRight();return}if(Me==="splitActiveTabDown"){(Dt=Ce.current)==null||Dt.splitActiveTabDown();return}if(Me==="floatActiveTab"){(It=Ce.current)==null||It.floatActiveTab();return}if(Me==="popoutActiveTab"){(qt=Ce.current)==null||qt.popoutActiveTab();return}if(Me==="dockActiveTab"){(Vt=Ce.current)==null||Vt.dockActiveTab();return}if(Me==="focusLeftPane"){(Yt=Ce.current)==null||Yt.focusLeftPane();return}if(Me==="focusRightPane"){(xs=Ce.current)==null||xs.focusRightPane();return}if(Me==="focusUpPane"){(Re=Ce.current)==null||Re.focusUpPane();return}if(Me==="focusDownPane"){(rt=Ce.current)==null||rt.focusDownPane();return}if(Me==="moveActiveTabToLeftPane"){(jt=Ce.current)==null||jt.moveActiveTabToLeftPane();return}if(Me==="moveActiveTabToRightPane"){(Ot=Ce.current)==null||Ot.moveActiveTabToRightPane();return}if(Me==="moveActiveTabToUpPane"){(ne=Ce.current)==null||ne.moveActiveTabToUpPane();return}if(Me==="moveActiveTabToDownPane"){(Ge=Ce.current)==null||Ge.moveActiveTabToDownPane();return}if(Me==="triggerPrimaryApprovalAction"){Ue(0);return}if(Me==="triggerSecondaryApprovalAction"){Ue(1);return}if(Me==="triggerTertiaryApprovalAction"){Ue(2);return}if(Me==="setActiveTabShortcut"){(Ee=Ce.current)==null||Ee.setShortcutForActiveTab();return}if(Me==="selectPreviousGroupTab"){(vt=Ce.current)==null||vt.activatePreviousTabInGroup();return}if(Me==="selectNextGroupTab"){(Jt=Ce.current)==null||Jt.activateNextTabInGroup();return}!n||!ct(n)||lt(n)||Me==="toggleCliView"&&h(u==="chat"?"terminal":"chat")}}),Ye=Rt.useCallback(()=>{J(),We(null),tt([])},[J,We,tt]),Tt=Rt.useMemo(()=>Fe==="all"?se:se.filter(Me=>MA(Me)===Fe),[se,Fe]),Wt=Rt.useCallback(()=>{const Me=Object.fromEntries(se.map(Qe=>[Qe.id,""]));qe(Me)},[se,qe]),ss=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Me=Object.fromEntries(se.map(Qe=>[Qe.id,Qe.defaultShortcut]));qe(Me)},[se,qe]);return Rt.useEffect(()=>{const Me=Qe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Qe.metaKey&&Qe.key.toLowerCase()==="w":Qe.ctrlKey&&Qe.key.toLowerCase()==="w")&&(Qe.preventDefault(),n&&V&&V(n))};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[n,V]),Rt.useEffect(()=>{if(!dt||we)return;const Me=Qe=>{Qe.key==="Escape"&&(Qe.preventDefault(),Ye())};return window.addEventListener("keydown",Me,!0),()=>window.removeEventListener("keydown",Me,!0)},[Ye,dt,we]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(K0,{activeConv:n,wsStatus:r,isConnected:o,conversations:X,hiddenConversations:m,onOpenHistory:a,onHideConversation:V,onShowConversation:Ke,onShowAllHidden:ke,onResetPanelsToMain:_e,notifications:te,notificationUnreadCount:ve,onOpenNotification:Ze,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je,inboxOpen:Be,onInboxOpenChange:ut,hiddenOpen:Xe,onHiddenOpenChange:at,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:ht,guideNudgeVisible:he,actionShortcuts:be,onOpenRemote:()=>{!n||ct(n)||lt(n)||i(n)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:h,onOpenGitDialog:Ne,onOpenMeshGraph:He}),e?s.jsx(QC,{conversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,userName:j,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,onOpenHistory:a,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:o,onShowAllHiddenConversations:ke,onHideConversation:V,onOpenMeshGraph:He,onOpenNewSession:ee,liveSessionInboxState:ce}):t?s.jsx(o1,{containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,userName:j,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:ce}):s.jsx(S1,{visibleConversations:X,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,initialDataLoaded:b,userName:j,toggleHiddenTab:z,actionShortcuts:be,registerActionHandlers:Me=>{Ce.current=Me},onActiveTabChange:W,requestedActiveTabKey:de,onRequestedActiveTabConsumed:re,onRequestScrollToBottom:oe,scrollToBottomRequest:xe,onOpenNewSession:ee,liveSessionInboxState:ce,layoutProfile:pe}),it&&s.jsx(L1,{machines:Se,ides:f,onClose:le,onBrowseDirectory:G,onSaveWorkspace:O,onLaunchIde:Z,onLaunchProvider:q,onListMeshes:me,onLaunchMeshCoordinator:Te,onListSavedSessions:_}),Ae&&s.jsx(qp,{activeConv:Ae,sendDaemonCommand:w,onClose:()=>Pe(null)}),ue&&s.jsx(Yp,{daemonId:ue.daemonId,workspace:ue.workspace,onClose:()=>ge(null)}),dt&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ye,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Me=>Me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ye,"aria-label":"Close dashboard guide",children:s.jsx(At,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${$e===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ye(Me.id),children:Me.label},Me.id))}),$e==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",et?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),$e==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),$e==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Fe===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>Oe(Me.id),children:Me.label},Me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Wt,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:ss,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Tt.map(Me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${we===Me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:we===Me.id?ze.length>0?`${ze.join(" ")} ...`:"Listening...":be[Me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{We(Me.id),tt([])},children:we===Me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Qe={...be};Qe[Me.id]="",qe(Qe)},children:"Disable"})]})]})},Me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",et?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const RA=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"👀",title:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],EA={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},_A={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function $A({onClose:e,standalone:t=!1}){const[n,r]=l.useState(0),o=[...RA,t?_A:EA],a=o[n],i=n===o.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(At,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:o.map((c,u)=>s.jsx("div",{style:{width:u===n?24:8,height:8,borderRadius:4,background:u===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:a.visual||a.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:a.icon})," ",a.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:a.desc}),a.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),a.code]}),i&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>i?e():r(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
92
92
  @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
93
93
  @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
94
- `})]})}function BA({hasExtensions:e,ideName:t,activeChatTab:n,extensionTabs:r,onSelectTab:o}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${n==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=n===a.tabKey,c=a.status==="waiting_approval",u=a.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),a.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function FA({ideData:e,allIdes:t,connectionStates:n,ideName:r,preferredTabKey:o}){const[a,i]=l.useState(()=>o||"native"),c=l.useMemo(()=>yh(t),[t]),u=l.useMemo(()=>e?qi(e,{machineNames:c,connectionStates:n,defaultConnectionState:"new"}):[],[e,c,n]),h=l.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=l.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),m=l.useMemo(()=>e?cs(u,e.id):null,[u,e]);l.useEffect(()=>{o&&i(o)},[o]),l.useEffect(()=>{if(o||!m)return;const p=m.streamSource==="native"?"native":m.tabKey;!p||a===p||a==="native"&&i(p)},[a,m,o]),l.useEffect(()=>{var p;a!=="native"&&(d.some(y=>y.tabKey===a)||i(((p=d[0])==null?void 0:p.tabKey)||"native"))},[a,d]),l.useEffect(()=>{a==="native"&&(h||d[0]&&i(d[0].tabKey))},[a,h,d]);const f=l.useMemo(()=>a==="native"&&h?h:d.find(p=>p.tabKey===a)||m||h||d[0],[a,h,m,d]),x=l.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:lh(p)||r,status:p.status})),[d,r]),w=l.useCallback(p=>{if(p)return u.find(y=>Ja(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:a,setActiveChatTab:i,activeConv:f,conversations:u,extensionTabs:x,hasExtensions:x.length>0,resolveConversationByTarget:w}}function HA({activeConv:e,ideEntry:t,ides:n,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:u,onOpenHistory:h,onConversationChange:d,onClose:m}){const[f,x]=l.useState("split"),[w,p]=l.useState(()=>Ms(e)?"native":e.tabKey),y=l.useRef(null),k=l.useMemo(()=>t||n.find(R=>R.id===e.routeId),[e.routeId,t,n]),b=l.useMemo(()=>$t((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:j,extensionTabs:S,hasExtensions:v}=FA({ideData:k,allIdes:n,connectionStates:r,ideName:b||"IDE",preferredTabKey:Ms(e)?void 0:e.tabKey}),g=l.useMemo(()=>k?cs(j,k.id):null,[k,j]);l.useEffect(()=>{const R=y.current,Q={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=Q,!(R&&R.routeId===Q.routeId&&R.tabKey===Q.tabKey&&R.streamSource===Q.streamSource)){if(Ms(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(w==="native"){if(j.some(R=>R.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&p(g.tabKey);return}if(!j.some(R=>R.tabKey===w)){if((g==null?void 0:g.streamSource)==="agent-stream"){p(g.tabKey);return}p("native")}},[j,w,g]);const N=l.useMemo(()=>w==="native"?j.find(R=>R.streamSource==="native")||e:j.find(R=>R.tabKey===w)||e,[e,j,w]),C=Ph(N),A=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...N,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:N,[N,C]),T=en(A),M=Po({sendDaemonCommand:a,activeConv:A,setActionLogs:i,isStandalone:c}),{connScreenshot:L,screenshotUsage:P,handleRemoteAction:B}=dp({doId:T,targetSessionId:Fu(A),connState:A.connectionState||"new",viewMode:f}),K=l.useMemo(()=>o.filter(R=>R.routeId===A.tabKey),[o,A.tabKey]);l.useEffect(()=>{d==null||d(A)},[A,d]),l.useEffect(()=>{const R=Q=>{Q.key==="Escape"&&m()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[m]);const F=l.useCallback(R=>{R.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:F,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(us,{size:16})}),s.jsx("span",{className:"truncate",children:Wi(N)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const Q=f===R;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${Q?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>x(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?s.jsx(_f,{size:15}):s.jsx(us,{size:15})},R)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>h(N),title:"Chat History",children:[s.jsx(Ai,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(BA,{hasExtensions:v,ideName:b||"IDE",activeChatTab:w,extensionTabs:S,onSelectTab:p}),s.jsx(hu,{activeConv:A,onModalButton:M.handleModalButton}),s.jsx(ri,{activeConv:A,ideEntry:k,showMetaChips:!1,handleSendChat:M.handleSendChat,handleForceSendChat:M.handleForceSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(iu,{addLog:()=>{},connState:A.connectionState||"new",connScreenshot:L,screenshotUsage:P,transportType:A.transport,onAction:B})})]})]})})}function WA({activeConv:e,canSaveAndStop:t=!1,onCancel:n,onStopNow:r,onSaveAndStop:o}){const{t:a}=Le(),i=C0(e);return 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:n,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",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",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})}function OA({historyModal:e,remoteDialog:t,cliStopDialog:n,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(F0,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&s.jsx(bh,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(HA,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),n.open&&n.targetConv&&(ct(n.targetConv)||lt(n.targetConv))&&s.jsx(WA,{activeConv:n.targetConv,canSaveAndStop:ct(n.targetConv)&&!lt(n.targetConv)&&!!((c=n.targetConv.resume)!=null&&c.supported),onCancel:n.onCancel,onStopNow:n.onStopNow,onSaveAndStop:n.onSaveAndStop}),s.jsx(gh,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),s.jsx(cu,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),a.open&&s.jsx($A,{onClose:a.onClose,standalone:a.standalone})]})}function UA({daemons:e,targetVersion:t,required:n=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:n?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:n?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:n?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Co,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[n?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const c=ts(i,{fallbackId:i.id}),u=r[i.id],h=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,f=Oh(i)==="preview"?"Update to preview":d?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",h]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(i.id),children:f})]},i.id)})]}),!n&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:"Dismiss",children:s.jsx(At,{size:16})})]})}function GA(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function KA(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function zA(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>KA(t)).map(t=>t.id)}}function qA(){var yl,vl,wl,kl;const{sendCommand:e}=yt(),t=In(),n=Dh(),r=ki(),o=pr(),[a,i]=Hm(),c=a.get("activeTab"),u=((yl=r.state)==null?void 0:yl.openRemoteForTabKey)||null,h=((vl=r.state)==null?void 0:vl.openMachineId)||null,d=((wl=r.state)==null?void 0:wl.mobileSection)||null,m=nh(),f=m.ides||[],x=m.initialLoaded??!0,{updateRouteChats:w,setToasts:p}=m,[y,k]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=m.toasts||[],j=m.wsStatus||"connected",S=m.isConnected??!0,v=m.connectionStates||{},g=m.showReconnected||!1,{layoutProfile:N,groupAssignments:C,updateGroupAssignments:A,focusedGroup:T,updateFocusedGroup:M,focusGroup:L,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:K,groupTabOrders:F,updateGroupTabOrders:R,setGroupTabOrder:Q,groupSizes:E,updateGroupSizes:I,isMobile:$,hasHydratedStoredLayout:D,hydrateStoredLayout:U,focusConversationTab:Y}=zS(),[ae,z]=l.useState(()=>Qi());l.useEffect(()=>eS(z),[]);const X=l.useMemo(()=>GA({isMobile:$,mobileViewMode:ae}),[$,ae]),[de,re]=l.useState([]),[W,oe]=l.useState({}),[V,ie]=l.useState({});mr("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:T,groupCount:Object.keys(C).length,actionLogCount:de.length});const ke=l.useMemo(()=>f.filter(ot=>ot.type==="adhdev-daemon").sort(Ei),[f]),Se=!!ke[0];l.useEffect(()=>{const{metadataDaemonIds:ot,runtimeDaemonIds:Ut}=zA(ke);for(const Dn of ot)t(Dn,{minFreshMs:3e4}).catch(()=>{});for(const Dn of Ut)n(Dn,{minFreshMs:3e4}).catch(()=>{})},[t,n,ke]);const pe=l.useMemo(()=>xS(f,W),[f,W]),{conversations:G,visibleConversations:O,visibleTabKeys:Z,resolveConversationBySessionId:q,resolveConversationByTarget:me}=DS({ides:pe,connectionStates:v,clearedTabs:V}),Te=l.useMemo(()=>new Map(G.map(ot=>[ot.tabKey,ot])),[G]);Jw(O,X);const _=l.useMemo(()=>uu(f),[f]),se=tp(_,e,l.useCallback(ot=>an(p,`⚠️ ${ot}`),[p])),{notifications:ve,unreadCount:ce}=lC({conversations:G,liveSessionInboxState:_}),{handleMarkDashboardNotificationRead:H,handleMarkDashboardNotificationUnread:fe,handleDeleteDashboardNotification:je}=cC({notifications:ve,sendDaemonCommand:e}),{containerRef:Ce,normalizedGroupAssignments:Be,numGroups:Xe,isSplitMode:dt,groupedConvs:it,moveTabToGroup:he,closeGroup:$e,handleResizeStart:Fe,splitTabRelative:Ie}=ZS({groupAssignments:C,updateGroupAssignments:A,updateFocusedGroup:M,updateGroupActiveTabIds:B,updateGroupTabOrders:R,groupSizes:E,updateGroupSizes:I,isMobile:$,visibleConversations:O,visibleTabKeys:Z}),{activeConv:ye,openDesktopConversation:Oe,requestScrollToBottom:ut,scrollToBottomRequest:at,setDesktopActiveTab:ht}=wC({isMobile:$,conversations:G,visibleConversations:O,groupActiveTabIds:P,focusedGroup:T,groupedConvs:it,setSearchParams:i});CC({activeConv:ye,isMobile:$,liveSessionInboxState:_,sendDaemonCommand:e});const{requestedDesktopTabKey:J,requestedMobileTabKey:te,consumeRequestedActiveTab:le}=PS({isMobile:$,urlActiveTab:c,resolveConversationBySessionId:q,setSearchParams:i}),{remoteDialogConv:ue,remoteDialogIdeEntry:ge,remoteDialogActiveConv:Ae,setRemoteDialogActiveConv:Pe,openRemoteDialog:Ne,closeRemoteDialog:He,cliStopDialogOpen:Ue,cliStopTargetConv:Ze,requestCliStop:_e,cancelCliStop:Ge,confirmCliStop:et}=AC({isMobile:$,location:r,navigate:o,requestedRemoteTabTarget:u,requestedDesktopTabKey:J,conversations:G,ides:f,resolveConversationByTarget:me,activeConv:ye,sendDaemonCommand:e}),{historyModalOpen:ee,openHistoryModal:be,closeHistoryModal:we,historyTargetConv:ze,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:qe,handleHistorySwitchSession:Ye,handleHistoryNewChat:Tt,handleHistoryRefresh:Wt,savedHistorySessions:ss,savedHistoryFilters:Me,setSavedHistoryFilters:Qe,missingWorkspaceResumePath:Dt,isSavedHistoryLoading:It,resumingSavedHistorySessionId:qt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:Yt}=jC({activeConv:ye,remoteDialogConv:ue,remoteDialogActiveConv:Ae,ides:f,sendDaemonCommand:e,updateRouteChats:w,setToasts:p,setClearedTabs:ie,setSearchParams:i}),xs=l.useMemo(()=>O,[O]),Re=$&&ae==="chat",rt=l.useMemo(()=>G.filter(ot=>Ds(ot,_).surfaceHidden),[G,_]),jt=l.useCallback(ot=>{const Ut=new URLSearchParams(a);Ut.set("activeTab",ot),i(Ut,{replace:!0})},[a,i]),{trackPendingLaunch:Ot}=gC({ides:f,conversations:G,onOpenSession:jt}),{handleBrowseMachineDirectory:ne,handleSaveMachineWorkspace:Ke,handleLaunchMachineIde:Ee,handleLaunchMachineProvider:vt,handleListMachineMeshes:Jt,handleLaunchMeshCoordinator:Mn,handleListMachineSavedSessions:Oo,setActiveCliViewMode:ys}=xC({sendDaemonCommand:e,trackPendingLaunch:Ot,onOpenSession:jt,activeConv:ye,ides:f,setCliViewModeOverrides:oe});vS({visibleConversations:O,clearedTabs:V,setClearedTabs:ie,setActionLogs:re,isConversationMuted:se.isMuted}),LS({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:me});const rm=Lh(),{isRefreshingHistory:om,handleRefreshHistory:am}=Wh({sendDaemonCommand:e,activeConv:ye,chats:(kl=f.find(ot=>ot.id===(ye==null?void 0:ye.routeId)))==null?void 0:kl.chats,updateRouteChats:w,setToasts:p,setClearedTabs:ie});VS({urlActiveTab:$&&!Re?c:null,conversations:G,resolveConversationBySessionId:q,normalizedGroupAssignments:Be,hasHydratedStoredLayout:$&&!Re?D:!0,hydrateStoredLayout:$&&!Re?U:()=>{},focusConversationTab:Y,setSearchParams:i,historyModalOpen:ee,activeConv:ye,isRefreshingHistory:om,ides:f,handleRefreshHistory:am});const im=l.useMemo(()=>!ye||!ct(ye)||lt(ye)?null:Tn(ye),[ye]),{versionMismatchDaemons:lm,hasRequiredVersionDaemons:gl,targetVersion:cm,versionBannerDismissed:dm,setVersionBannerDismissed:um,upgradingDaemons:hm,handleBannerUpgrade:pm}=tC({ides:f,sendDaemonCommand:e}),xl=l.useCallback(ot=>{se.setHidden(ot,!1),Oe(ot)},[Oe,se]),mm=l.useCallback(()=>{for(const ot of rt)se.setHidden(ot,!1)},[rt,se]),fm=l.useCallback(ot=>{se.setHidden(ot,!0)},[se]),bm=l.useCallback(ot=>{se.toggleHidden(ot)},[se]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!dm||gl)&&s.jsx(UA,{daemons:lm,targetVersion:cm,required:gl,upgradingDaemons:hm,onUpgrade:pm,onDismiss:()=>um(!0)}),s.jsx(LA,{showMobileChatMode:Re,isMobile:$,activeConv:ye,wsStatus:j,isConnected:S,onOpenHistory:ot=>{ot&&Pe(ot),be()},onOpenRemote:Ne,onStopCli:_e,activeCliViewMode:im,onSetActiveCliViewMode:ys,mobileChatConversations:xs,ides:f,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,setCliViewModeOverrides:oe,isStandalone:Se,initialDataLoaded:x,userName:m.userName,requestedMobileTabKey:te,onRequestedMobileTabConsumed:le,requestedMachineId:h,onRequestedMachineConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},containerRef:Ce,isSplitMode:dt,numGroups:Xe,groupSizes:E,groupedConvs:it,clearedTabs:V,focusedGroup:T,focusGroup:L,moveTabToGroup:he,splitTabRelative:Ie,closeGroup:$e,handleResizeStart:Fe,groupActiveTabIds:P,setGroupActiveTab:K,groupTabOrders:F,setGroupTabOrder:Q,toggleHiddenTab:ot=>{const Ut=Te.get(ot);Ut&&bm(Ut)},visibleConversations:O,hiddenConversations:rt,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:ht,onRequestScrollToBottom:ut,onHideConversation:fm,onShowHiddenConversation:xl,onShowAllHiddenConversations:mm,scrollToBottomRequest:at,machineEntries:ke,layoutProfile:N,onBrowseMachineDirectory:ne,onSaveMachineWorkspace:Ke,onLaunchMachineIde:Ee,onLaunchMachineProvider:vt,onListMachineMeshes:Jt,onLaunchMeshCoordinator:Mn,onListMachineSavedSessions:Oo,notifications:ve,notificationUnreadCount:ce,liveSessionInboxState:_,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}),s.jsx("style",{children:`
94
+ `})]})}function BA({hasExtensions:e,ideName:t,activeChatTab:n,extensionTabs:r,onSelectTab:o}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${n==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=n===a.tabKey,c=a.status==="waiting_approval",u=a.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),a.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function FA({ideData:e,allIdes:t,connectionStates:n,ideName:r,preferredTabKey:o}){const[a,i]=l.useState(()=>o||"native"),c=l.useMemo(()=>yh(t),[t]),u=l.useMemo(()=>e?qi(e,{machineNames:c,connectionStates:n,defaultConnectionState:"new"}):[],[e,c,n]),h=l.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=l.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),m=l.useMemo(()=>e?cs(u,e.id):null,[u,e]);l.useEffect(()=>{o&&i(o)},[o]),l.useEffect(()=>{if(o||!m)return;const p=m.streamSource==="native"?"native":m.tabKey;!p||a===p||a==="native"&&i(p)},[a,m,o]),l.useEffect(()=>{var p;a!=="native"&&(d.some(y=>y.tabKey===a)||i(((p=d[0])==null?void 0:p.tabKey)||"native"))},[a,d]),l.useEffect(()=>{a==="native"&&(h||d[0]&&i(d[0].tabKey))},[a,h,d]);const f=l.useMemo(()=>a==="native"&&h?h:d.find(p=>p.tabKey===a)||m||h||d[0],[a,h,m,d]),x=l.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:lh(p)||r,status:p.status})),[d,r]),w=l.useCallback(p=>{if(p)return u.find(y=>Ja(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:a,setActiveChatTab:i,activeConv:f,conversations:u,extensionTabs:x,hasExtensions:x.length>0,resolveConversationByTarget:w}}function HA({activeConv:e,ideEntry:t,ides:n,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:u,onOpenHistory:h,onConversationChange:d,onClose:m}){const[f,x]=l.useState("split"),[w,p]=l.useState(()=>Ms(e)?"native":e.tabKey),y=l.useRef(null),k=l.useMemo(()=>t||n.find(R=>R.id===e.routeId),[e.routeId,t,n]),b=l.useMemo(()=>$t((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:j,extensionTabs:S,hasExtensions:v}=FA({ideData:k,allIdes:n,connectionStates:r,ideName:b||"IDE",preferredTabKey:Ms(e)?void 0:e.tabKey}),g=l.useMemo(()=>k?cs(j,k.id):null,[k,j]);l.useEffect(()=>{const R=y.current,Q={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=Q,!(R&&R.routeId===Q.routeId&&R.tabKey===Q.tabKey&&R.streamSource===Q.streamSource)){if(Ms(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(w==="native"){if(j.some(R=>R.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&p(g.tabKey);return}if(!j.some(R=>R.tabKey===w)){if((g==null?void 0:g.streamSource)==="agent-stream"){p(g.tabKey);return}p("native")}},[j,w,g]);const N=l.useMemo(()=>w==="native"?j.find(R=>R.streamSource==="native")||e:j.find(R=>R.tabKey===w)||e,[e,j,w]),C=Ph(N),A=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...N,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:N,[N,C]),T=en(A),M=Po({sendDaemonCommand:a,activeConv:A,setActionLogs:i,isStandalone:c}),{connScreenshot:L,screenshotUsage:P,handleRemoteAction:B}=dp({doId:T,targetSessionId:Fu(A),connState:A.connectionState||"new",viewMode:f}),K=l.useMemo(()=>o.filter(R=>R.routeId===A.tabKey),[o,A.tabKey]);l.useEffect(()=>{d==null||d(A)},[A,d]),l.useEffect(()=>{const R=Q=>{Q.key==="Escape"&&m()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[m]);const F=l.useCallback(R=>{R.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:F,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(us,{size:16})}),s.jsx("span",{className:"truncate",children:Wi(N)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const Q=f===R;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${Q?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>x(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?s.jsx(_f,{size:15}):s.jsx(us,{size:15})},R)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>h(N),title:"Chat History",children:[s.jsx(Ai,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(BA,{hasExtensions:v,ideName:b||"IDE",activeChatTab:w,extensionTabs:S,onSelectTab:p}),s.jsx(hu,{activeConv:A,onModalButton:M.handleModalButton}),s.jsx(ri,{activeConv:A,ideEntry:k,showMetaChips:!1,handleSendChat:M.handleSendChat,handleForceSendChat:M.handleForceSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(iu,{addLog:()=>{},connState:A.connectionState||"new",connScreenshot:L,screenshotUsage:P,transportType:A.transport,onAction:B})})]})]})})}function WA({activeConv:e,canSaveAndStop:t=!1,onCancel:n,onStopNow:r,onSaveAndStop:o}){const{t:a}=Le(),i=C0(e);return 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:n,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",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",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})}function OA({historyModal:e,remoteDialog:t,cliStopDialog:n,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(F0,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&s.jsx(bh,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(HA,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),n.open&&n.targetConv&&(ct(n.targetConv)||lt(n.targetConv))&&s.jsx(WA,{activeConv:n.targetConv,canSaveAndStop:ct(n.targetConv)&&!lt(n.targetConv)&&!!((c=n.targetConv.resume)!=null&&c.supported),onCancel:n.onCancel,onStopNow:n.onStopNow,onSaveAndStop:n.onSaveAndStop}),s.jsx(gh,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),s.jsx(cu,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),a.open&&s.jsx($A,{onClose:a.onClose,standalone:a.standalone})]})}function UA({daemons:e,targetVersion:t,required:n=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:n?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:n?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:n?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Co,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[n?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const c=ts(i,{fallbackId:i.id}),u=r[i.id],h=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,f=Oh(i)==="preview"?"Update to preview":d?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",h]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(i.id),children:f})]},i.id)})]}),!n&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:"Dismiss",children:s.jsx(At,{size:16})})]})}function GA(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function KA(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function zA(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>KA(t)).map(t=>t.id)}}function qA(){var yl,vl,wl,kl;const{sendCommand:e}=yt(),t=In(),n=Dh(),r=ki(),o=pr(),[a,i]=Hm(),c=a.get("activeTab"),u=((yl=r.state)==null?void 0:yl.openRemoteForTabKey)||null,h=((vl=r.state)==null?void 0:vl.openMachineId)||null,d=((wl=r.state)==null?void 0:wl.mobileSection)||null,m=nh(),f=m.ides||[],x=m.initialLoaded??!0,{updateRouteChats:w,setToasts:p}=m,[y,k]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=m.toasts||[],j=m.wsStatus||"connected",S=m.isConnected??!0,v=m.connectionStates||{},g=m.showReconnected||!1,{layoutProfile:N,groupAssignments:C,updateGroupAssignments:A,focusedGroup:T,updateFocusedGroup:M,focusGroup:L,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:K,groupTabOrders:F,updateGroupTabOrders:R,setGroupTabOrder:Q,groupSizes:E,updateGroupSizes:I,isMobile:$,hasHydratedStoredLayout:D,hydrateStoredLayout:U,focusConversationTab:Y}=zS(),[ae,z]=l.useState(()=>Qi());l.useEffect(()=>eS(z),[]);const X=l.useMemo(()=>GA({isMobile:$,mobileViewMode:ae}),[$,ae]),[de,re]=l.useState([]),[W,oe]=l.useState({}),[V,ie]=l.useState({});mr("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:T,groupCount:Object.keys(C).length,actionLogCount:de.length});const ke=l.useMemo(()=>f.filter(ot=>ot.type==="adhdev-daemon").sort(Ei),[f]),Se=!!ke[0];l.useEffect(()=>{const{metadataDaemonIds:ot,runtimeDaemonIds:Ut}=zA(ke);for(const Dn of ot)t(Dn,{minFreshMs:3e4}).catch(()=>{});for(const Dn of Ut)n(Dn,{minFreshMs:3e4}).catch(()=>{})},[t,n,ke]);const pe=l.useMemo(()=>xS(f,W),[f,W]),{conversations:G,visibleConversations:O,visibleTabKeys:Z,resolveConversationBySessionId:q,resolveConversationByTarget:me}=DS({ides:pe,connectionStates:v,clearedTabs:V}),Te=l.useMemo(()=>new Map(G.map(ot=>[ot.tabKey,ot])),[G]);Jw(O,X);const _=l.useMemo(()=>uu(f),[f]),te=tp(_,e,l.useCallback(ot=>an(p,`⚠️ ${ot}`),[p])),{notifications:ve,unreadCount:ce}=lC({conversations:G,liveSessionInboxState:_}),{handleMarkDashboardNotificationRead:H,handleMarkDashboardNotificationUnread:fe,handleDeleteDashboardNotification:je}=cC({notifications:ve,sendDaemonCommand:e}),{containerRef:Ce,normalizedGroupAssignments:Be,numGroups:Xe,isSplitMode:dt,groupedConvs:it,moveTabToGroup:he,closeGroup:$e,handleResizeStart:Fe,splitTabRelative:Ie}=ZS({groupAssignments:C,updateGroupAssignments:A,updateFocusedGroup:M,updateGroupActiveTabIds:B,updateGroupTabOrders:R,groupSizes:E,updateGroupSizes:I,isMobile:$,visibleConversations:O,visibleTabKeys:Z}),{activeConv:ye,openDesktopConversation:Oe,requestScrollToBottom:ut,scrollToBottomRequest:at,setDesktopActiveTab:ht}=wC({isMobile:$,conversations:G,visibleConversations:O,groupActiveTabIds:P,focusedGroup:T,groupedConvs:it,setSearchParams:i});CC({activeConv:ye,isMobile:$,liveSessionInboxState:_,sendDaemonCommand:e});const{requestedDesktopTabKey:J,requestedMobileTabKey:ee,consumeRequestedActiveTab:le}=PS({isMobile:$,urlActiveTab:c,resolveConversationBySessionId:q,setSearchParams:i}),{remoteDialogConv:ue,remoteDialogIdeEntry:ge,remoteDialogActiveConv:Ae,setRemoteDialogActiveConv:Pe,openRemoteDialog:Ne,closeRemoteDialog:He,cliStopDialogOpen:Ke,cliStopTargetConv:Ze,requestCliStop:_e,cancelCliStop:Ue,confirmCliStop:et}=AC({isMobile:$,location:r,navigate:o,requestedRemoteTabTarget:u,requestedDesktopTabKey:J,conversations:G,ides:f,resolveConversationByTarget:me,activeConv:ye,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:be,closeHistoryModal:we,historyTargetConv:ze,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:qe,handleHistorySwitchSession:Ye,handleHistoryNewChat:Tt,handleHistoryRefresh:Wt,savedHistorySessions:ss,savedHistoryFilters:Me,setSavedHistoryFilters:Qe,missingWorkspaceResumePath:Dt,isSavedHistoryLoading:It,resumingSavedHistorySessionId:qt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:Yt}=jC({activeConv:ye,remoteDialogConv:ue,remoteDialogActiveConv:Ae,ides:f,sendDaemonCommand:e,updateRouteChats:w,setToasts:p,setClearedTabs:ie,setSearchParams:i}),xs=l.useMemo(()=>O,[O]),Re=$&&ae==="chat",rt=l.useMemo(()=>G.filter(ot=>Ds(ot,_).surfaceHidden),[G,_]),jt=l.useCallback(ot=>{const Ut=new URLSearchParams(a);Ut.set("activeTab",ot),i(Ut,{replace:!0})},[a,i]),{trackPendingLaunch:Ot}=gC({ides:f,conversations:G,onOpenSession:jt}),{handleBrowseMachineDirectory:ne,handleSaveMachineWorkspace:Ge,handleLaunchMachineIde:Ee,handleLaunchMachineProvider:vt,handleListMachineMeshes:Jt,handleLaunchMeshCoordinator:Mn,handleListMachineSavedSessions:Oo,setActiveCliViewMode:ys}=xC({sendDaemonCommand:e,trackPendingLaunch:Ot,onOpenSession:jt,activeConv:ye,ides:f,setCliViewModeOverrides:oe});vS({visibleConversations:O,clearedTabs:V,setClearedTabs:ie,setActionLogs:re,isConversationMuted:te.isMuted}),LS({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:me});const rm=Lh(),{isRefreshingHistory:om,handleRefreshHistory:am}=Wh({sendDaemonCommand:e,activeConv:ye,chats:(kl=f.find(ot=>ot.id===(ye==null?void 0:ye.routeId)))==null?void 0:kl.chats,updateRouteChats:w,setToasts:p,setClearedTabs:ie});VS({urlActiveTab:$&&!Re?c:null,conversations:G,resolveConversationBySessionId:q,normalizedGroupAssignments:Be,hasHydratedStoredLayout:$&&!Re?D:!0,hydrateStoredLayout:$&&!Re?U:()=>{},focusConversationTab:Y,setSearchParams:i,historyModalOpen:se,activeConv:ye,isRefreshingHistory:om,ides:f,handleRefreshHistory:am});const im=l.useMemo(()=>!ye||!ct(ye)||lt(ye)?null:Tn(ye),[ye]),{versionMismatchDaemons:lm,hasRequiredVersionDaemons:gl,targetVersion:cm,versionBannerDismissed:dm,setVersionBannerDismissed:um,upgradingDaemons:hm,handleBannerUpgrade:pm}=tC({ides:f,sendDaemonCommand:e}),xl=l.useCallback(ot=>{te.setHidden(ot,!1),Oe(ot)},[Oe,te]),mm=l.useCallback(()=>{for(const ot of rt)te.setHidden(ot,!1)},[rt,te]),fm=l.useCallback(ot=>{te.setHidden(ot,!0)},[te]),bm=l.useCallback(ot=>{te.toggleHidden(ot)},[te]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!dm||gl)&&s.jsx(UA,{daemons:lm,targetVersion:cm,required:gl,upgradingDaemons:hm,onUpgrade:pm,onDismiss:()=>um(!0)}),s.jsx(LA,{showMobileChatMode:Re,isMobile:$,activeConv:ye,wsStatus:j,isConnected:S,onOpenHistory:ot=>{ot&&Pe(ot),be()},onOpenRemote:Ne,onStopCli:_e,activeCliViewMode:im,onSetActiveCliViewMode:ys,mobileChatConversations:xs,ides:f,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,setCliViewModeOverrides:oe,isStandalone:Se,initialDataLoaded:x,userName:m.userName,requestedMobileTabKey:ee,onRequestedMobileTabConsumed:le,requestedMachineId:h,onRequestedMachineConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},containerRef:Ce,isSplitMode:dt,numGroups:Xe,groupSizes:E,groupedConvs:it,clearedTabs:V,focusedGroup:T,focusGroup:L,moveTabToGroup:he,splitTabRelative:Ie,closeGroup:$e,handleResizeStart:Fe,groupActiveTabIds:P,setGroupActiveTab:K,groupTabOrders:F,setGroupTabOrder:Q,toggleHiddenTab:ot=>{const Ut=Te.get(ot);Ut&&bm(Ut)},visibleConversations:O,hiddenConversations:rt,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:ht,onRequestScrollToBottom:ut,onHideConversation:fm,onShowHiddenConversation:xl,onShowAllHiddenConversations:mm,scrollToBottomRequest:at,machineEntries:ke,layoutProfile:N,onBrowseMachineDirectory:ne,onSaveMachineWorkspace:Ge,onLaunchMachineIde:Ee,onLaunchMachineProvider:vt,onListMachineMeshes:Jt,onLaunchMeshCoordinator:Mn,onListMachineSavedSessions:Oo,notifications:ve,notificationUnreadCount:ce,liveSessionInboxState:_,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}),s.jsx("style",{children:`
95
95
  body { overflow: hidden; overscroll-behavior: none; }
96
- `}),s.jsx(OA,{historyModal:{open:ee,targetConv:ze,ides:f,isCreatingChat:tt,isRefreshingHistory:We?!1:qe,savedSessions:ss,savedHistoryFilters:Me,missingWorkspaceResumePath:Dt||null,onSavedHistoryFiltersChange:Qe,isSavedSessionsLoading:It,isResumingSavedSessionId:qt,onClose:we,onNewChat:Tt,onSwitchSession:Ye,onRefreshHistory:We?Vt:Wt,onResumeSavedSession:Yt},remoteDialog:{conversation:ue,ideEntry:ge,ides:f,connectionStates:v,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,isStandalone:Se,userName:m.userName,onOpenHistory:ot=>{ot&&Pe(ot),be()},onConversationChange:Pe,onClose:He},cliStopDialog:{open:Ue,targetConv:Ze,onCancel:Ge,onStopNow:async()=>{await et("hard")},onSaveAndStop:async()=>{await et("save")}},connectionBanner:{wsStatus:j,showReconnected:g,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:b,onDismiss:ot=>p(Ut=>Ut.filter(Dn=>Dn.id!==ot)),onClick:ot=>{if(ot.targetKey){const Ut=me(ot.targetKey);Ut&&(Y(Ut.tabKey,Be),xl(Ut),ut(Ut.tabKey,"toast-open"))}}},onboarding:{open:y,standalone:Se,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:rm})]})}function VA({machineId:e,registeredMachineId:t,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:o}){const{launchCli:a}=ko(),[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(!1),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),S=l.useRef(null),v=l.useCallback(I=>{S.current=I},[]),g=l.useCallback((I,$,D=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:I,message:$}]),setTimeout(()=>{var U;return(U=o.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),D&&pt.showToast($,I==="error"||I==="warn"?"warning":"success")},[o]),N=l.useCallback(I=>{const $=I instanceof Error?I.message:String(I||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),C=l.useCallback(async(I,$)=>{var D;if(!e||u)return!1;h(I),g("info",`Launching ${$t(I)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const U={ideType:I,enableCdp:!0};(D=$==null?void 0:$.workspace)!=null&&D.trim()?U.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const Y=await n(e,"launch_ide",U);return g(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${$t(I)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(U){return g("error",`Launch error: ${U.message}`,!0),!1}finally{h(null)}},[e,u,g,n]),A=l.useCallback(async I=>{if(!e)return{success:!1};const{cliType:$,dir:D,workspaceId:U,useDefaultWorkspace:Y,useHome:ae,argsStr:z,model:X,resumeSessionId:de}=I;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const re=z?z.split(/\s+/).filter(Boolean):void 0,W=(D==null?void 0:D.trim())||(U?"(saved id)":Y?"(default workspace)":ae?"(home)":"");g("info",`Launching ${$}${W?` in ${W}`:""}${X?` (model: ${X})`:""}...`),m($);try{const oe={cliType:$,cliArgs:re,initialModel:X||void 0};D!=null&&D.trim()?oe.dir=D.trim():U?oe.workspaceId=U:Y?oe.useDefaultWorkspace=!0:ae&&(oe.useHome=!0),de&&(oe.resumeSessionId=de);const V=await a(e,oe),ie=(V==null?void 0:V.result)||V;return V!=null&&V.success?(g("info",`${$} launched`,!0),(ie==null?void 0:ie.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ie==null?void 0:ie.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ie==null?void 0:ie.sessionId}):(g("error",`Failed: ${(V==null?void 0:V.error)||(ie==null?void 0:ie.error)}`,!0),(V==null?void 0:V.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&p({cliType:$,argsStr:z,model:X}),{success:!1,sessionId:ie==null?void 0:ie.sessionId})}catch(oe){return N(oe)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${oe.message}`,!0),{success:!1})}finally{m(null)}},[e,g,N,n]),T=l.useCallback(async(I,$,D,U)=>e?I?$.trim()?A({cliType:I,dir:$,argsStr:D,model:U}):(p({cliType:I,argsStr:D,model:U}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,A]),M=l.useCallback(async(I,$,D)=>{if(e&&window.confirm(`Stop ${I}?
96
+ `}),s.jsx(OA,{historyModal:{open:se,targetConv:ze,ides:f,isCreatingChat:tt,isRefreshingHistory:We?!1:qe,savedSessions:ss,savedHistoryFilters:Me,missingWorkspaceResumePath:Dt||null,onSavedHistoryFiltersChange:Qe,isSavedSessionsLoading:It,isResumingSavedSessionId:qt,onClose:we,onNewChat:Tt,onSwitchSession:Ye,onRefreshHistory:We?Vt:Wt,onResumeSavedSession:Yt},remoteDialog:{conversation:ue,ideEntry:ge,ides:f,connectionStates:v,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,isStandalone:Se,userName:m.userName,onOpenHistory:ot=>{ot&&Pe(ot),be()},onConversationChange:Pe,onClose:He},cliStopDialog:{open:Ke,targetConv:Ze,onCancel:Ue,onStopNow:async()=>{await et("hard")},onSaveAndStop:async()=>{await et("save")}},connectionBanner:{wsStatus:j,showReconnected:g,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:b,onDismiss:ot=>p(Ut=>Ut.filter(Dn=>Dn.id!==ot)),onClick:ot=>{if(ot.targetKey){const Ut=me(ot.targetKey);Ut&&(Y(Ut.tabKey,Be),xl(Ut),ut(Ut.tabKey,"toast-open"))}}},onboarding:{open:y,standalone:Se,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:rm})]})}function VA({machineId:e,registeredMachineId:t,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:o}){const{launchCli:a}=ko(),[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(!1),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),S=l.useRef(null),v=l.useCallback(I=>{S.current=I},[]),g=l.useCallback((I,$,D=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:I,message:$}]),setTimeout(()=>{var U;return(U=o.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),D&&pt.showToast($,I==="error"||I==="warn"?"warning":"success")},[o]),N=l.useCallback(I=>{const $=I instanceof Error?I.message:String(I||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),C=l.useCallback(async(I,$)=>{var D;if(!e||u)return!1;h(I),g("info",`Launching ${$t(I)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const U={ideType:I,enableCdp:!0};(D=$==null?void 0:$.workspace)!=null&&D.trim()?U.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const Y=await n(e,"launch_ide",U);return g(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${$t(I)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(U){return g("error",`Launch error: ${U.message}`,!0),!1}finally{h(null)}},[e,u,g,n]),A=l.useCallback(async I=>{if(!e)return{success:!1};const{cliType:$,dir:D,workspaceId:U,useDefaultWorkspace:Y,useHome:ae,argsStr:z,model:X,resumeSessionId:de}=I;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const re=z?z.split(/\s+/).filter(Boolean):void 0,W=(D==null?void 0:D.trim())||(U?"(saved id)":Y?"(default workspace)":ae?"(home)":"");g("info",`Launching ${$}${W?` in ${W}`:""}${X?` (model: ${X})`:""}...`),m($);try{const oe={cliType:$,cliArgs:re,initialModel:X||void 0};D!=null&&D.trim()?oe.dir=D.trim():U?oe.workspaceId=U:Y?oe.useDefaultWorkspace=!0:ae&&(oe.useHome=!0),de&&(oe.resumeSessionId=de);const V=await a(e,oe),ie=(V==null?void 0:V.result)||V;return V!=null&&V.success?(g("info",`${$} launched`,!0),(ie==null?void 0:ie.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ie==null?void 0:ie.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ie==null?void 0:ie.sessionId}):(g("error",`Failed: ${(V==null?void 0:V.error)||(ie==null?void 0:ie.error)}`,!0),(V==null?void 0:V.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&p({cliType:$,argsStr:z,model:X}),{success:!1,sessionId:ie==null?void 0:ie.sessionId})}catch(oe){return N(oe)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${oe.message}`,!0),{success:!1})}finally{m(null)}},[e,g,N,n]),T=l.useCallback(async(I,$,D,U)=>e?I?$.trim()?A({cliType:I,dir:$,argsStr:D,model:U}):(p({cliType:I,argsStr:D,model:U}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,A]),M=l.useCallback(async(I,$,D)=>{if(e&&window.confirm(`Stop ${I}?
97
97
  This will terminate the process.`))try{const U=await n(e,"stop_cli",{cliType:I,dir:$,targetSessionId:D});U!=null&&U.success?g("info",`${I} stopped`,!0):g("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){g("error",`Stop failed: ${U.message}`,!0)}},[e,g,n]),L=l.useCallback(async I=>{try{await n(I.daemonId,"restart_ide",{ideType:I.type}),g("info",`${$t(I.type)} restart initiated`,!0)}catch($){g("error",`Restart failed: ${$.message}`,!0)}},[g,n]),P=l.useCallback(async I=>{if(window.confirm(`Stop ${$t(I.type)}?
98
98
  This will disconnect CDP and optionally kill the process.`))try{const $=await n(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});$!=null&&$.success?g("info",`${$t(I.type)} stopped`,!0):g("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){g("error",`Stop failed: ${$.message}`,!0)}},[g,n]),B=l.useCallback(async()=>{if(e)try{const I=await n(e,"detect_ides",{});g("info",`Found ${((I==null?void 0:I.result)||[]).length} IDE(s)`,!0)}catch(I){g("error",`Detection failed: ${I.message}`,!0)}},[e,g,n]),K=l.useCallback(async I=>{if(!e||!I.trim())return!1;x(!0);try{const $=await n(e,"workspace_add",{path:I.trim()});return $!=null&&$.success?(g("info",`Workspace added: ${I.trim()}`),!0):(g("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return g("error",$.message),!1}finally{x(!1)}},[e,g,n]),F=l.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await n(e,"workspace_remove",{id:I});$!=null&&$.success?g("info","Workspace removed",!0):g("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){g("error",$.message,!0)}finally{x(!1)}}},[e,g,n]),R=l.useCallback(async I=>{var $;if(e){x(!0);try{const D=await n(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(D!=null&&D.success){g("info",I?"Default workspace updated":"Default workspace cleared",!0);const U=typeof D.defaultWorkspacePath=="string"?D.defaultWorkspacePath:"";U&&(($=S.current)==null||$.call(S,U))}else g("error",(D==null?void 0:D.error)||"workspace_set_default failed",!0)}catch(D){g("error",D.message,!0)}finally{x(!1)}}},[e,g,n]),Q=l.useCallback(async I=>{var D;if(!e||!I.trim())return;const $=I.trim();x(!0);try{const U=await n(e,"workspace_set_default",{path:$});U!=null&&U.success?(g("info","Default workspace set from history"),(D=S.current)==null||D.call(S,$)):g("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){g("error",U.message)}finally{x(!1)}},[e,g,n]),E=l.useCallback(async()=>{if(e)try{if(await n(e,"set_machine_nickname",{nickname:b}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(I){g("warn",`Live nickname updated, but account sync failed: ${I.message}`)}g("info",`Nickname set to "${b||"(cleared)"}"`),k(!1)}catch(I){g("error",`Failed: ${I.message}`)}},[e,b,t,g,r,n]);return{logs:i,launchingIde:u,launchingAgentType:d,workspaceBusy:f,launchPick:w,setLaunchPick:p,editingNickname:y,setEditingNickname:k,nicknameInput:b,setNicknameInput:j,addLog:g,handleLaunchIde:C,runLaunchCliCore:A,handleLaunchCli:T,handleStopCli:M,handleRestartIde:L,handleStopIde:P,handleDetectIdes:B,handleWorkspaceAdd:K,handleWorkspaceRemove:F,handleWorkspaceSetDefault:R,handleWorkspaceResumePath:Q,handleSaveNickname:E,setOnDefaultWorkspaceChanged:v}}function YA({machine:e,ideSessions:t,cliSessions:n,acpSessions:r}){var u;const o=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,a=e.availableMem??e.freeMem??e.totalMem,i=o&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-a)/e.totalMem*100))):0,c=((u=e.loadavg)==null?void 0:u[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(kr,{icon:s.jsx(Jd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Ay(e.uptime):"Waiting…"}),s.jsx(kr,{icon:s.jsx(us,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(kr,{icon:s.jsx(Ii,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(kr,{icon:s.jsx(Bf,{size:16}),label:"ACPs",value:`${r.length}`})]}),s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx($l,{value:o?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:o?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx($l,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:o?`${Xo(e.totalMem-a)} / ${Xo(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Xo(e.totalMem)} total`})]})]})]})}function JA(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t;return!n.settings||typeof n.settings!="object"?null:{settings:n.settings,values:n.values&&typeof n.values=="object"?n.values:{}}}function QA(e,t,n){const r=[];for(const[o,a]of Object.entries(e.settings)){const i=n!=null&&n.filterSchema?n.filterSchema(a):a;if(i.length===0)continue;const c=t.find(u=>u.type===o);r.push({type:o,displayName:(c==null?void 0:c.displayName)||o,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function Ia(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function md(e){if(!e||typeof e!="object")return null;if(Ia(e))return e;const t=e,n=t.result;return Ia(n)?n:Ia(t.sourceConfig)?t.sourceConfig:null}function XA(e){const t=e.trim();return t||null}function ZA({machineId:e,providers:t,sendDaemonCommand:n,onClose:r,onCreated:o}){var g;const{t:a}=Le("common"),i=t.filter(N=>N.category==="ide"),[c,u]=l.useState(((g=i[0])==null?void 0:g.type)||""),[h,d]=l.useState(""),[m,f]=l.useState(""),[x,w]=l.useState(!1),[p,y]=l.useState(""),[k,b]=l.useState(!1),j=N=>{const C=N.toLowerCase().replace(/[^a-z0-9-]/g,"");d(C),(!m||m===S(h))&&f(S(C))},S=N=>N.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),v=async()=>{if(!(!h||!m||!c)){w(!0),y("");try{const N=await n(e,"provider_clone",{type:h,name:m,category:"ide",location:"user",cloneFrom:c});N!=null&&N.success||N!=null&&N.created?(b(!0),o==null||o(h)):y((N==null?void 0:N.error)||"Failed to create provider")}catch(N){y((N==null?void 0:N.message)||"Connection failed")}w(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm 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",onClick:r,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:a("machine.providerClone.title")}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:a("machine.providerClone.subtitle")})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:k?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:a("machine.providerClone.createdTitle")}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[a("machine.providerClone.createdDesc",{type:h})," ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",h,"/"]})]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-2",children:a("machine.providerClone.createdRunHint",{type:h})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.baseProvider")}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(N=>s.jsxs("button",{onClick:()=>u(N.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===N.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===N.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:N.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===N.type?"#a78bfa":"var(--text-secondary)"},children:N.displayName})]},N.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.providerTypeId")}),s.jsx("input",{value:h,onChange:N=>j(N.target.value),placeholder:a("machine.providerClone.typeIdPlaceholder"),className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:[a("machine.providerClone.typeIdHint")," ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",h||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.displayName")}),s.jsx("input",{value:m,onChange:N=>f(N.target.value),placeholder:a("machine.providerClone.displayNamePlaceholder"),className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),p&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:p})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:k?s.jsx("button",{onClick:r,className:"machine-btn",children:a("machine.providerClone.close")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:r,className:"machine-btn",children:a("machine.providerClone.cancel")}),s.jsx("button",{onClick:v,disabled:!h||!m||x,className:"machine-btn",style:{background:h&&m?"rgba(34,197,94,0.12)":void 0,borderColor:h&&m?"rgba(34,197,94,0.3)":void 0,color:h&&m?"#86efac":void 0,opacity:!h||!m||x?.4:1},children:a(x?"machine.providerClone.creating":"machine.providerClone.createProvider")})]})})]})})}const fd={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},eT={"user-custom":"bg-violet-500/[0.10] border-violet-500/25 text-violet-300",trusted:"bg-green-500/[0.10] border-green-500/25 text-green-400","trusted-with-scripts":"bg-emerald-500/[0.10] border-emerald-500/25 text-emerald-400","external-safe":"bg-sky-500/[0.10] border-sky-500/25 text-sky-400","external-untrusted":"bg-amber-500/[0.10] border-amber-500/30 text-amber-300"};function tT({trust:e,sourceName:t,description:n}){const r=t&&(e==="external-safe"||e==="external-untrusted")?`${fd[e]} · ${t}`:fd[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${eT[e]}`,title:n,children:r})}function sT(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const bd={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},nT={acp:"bg-violet-500/10 text-violet-300 border-violet-500/20",cli:"bg-blue-500/10 text-blue-300 border-blue-500/20",ide:"bg-green-500/10 text-green-300 border-green-500/20",extension:"bg-yellow-500/10 text-yellow-300 border-yellow-500/20"};function gd(e){if(!e)return"—";const t=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t} — ${n}`:t}function rT(e){return e==="cli"||e==="acp"}function oT({prov:e,providerInfo:t,savingKey:n,onSetSetting:r,onEnableToggle:o,onDetect:a,onResetCommand:i}){const{t:c}=Le("common"),u={detected:c("machine.providerRow.statusDetected"),not_detected:c("machine.providerRow.statusNotDetected"),enabled_unchecked:c("machine.providerRow.statusEnabledUnchecked"),disabled:c("machine.providerRow.statusDisabled")},[h,d]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,f=t==null?void 0:t.machineStatus,x=m&&f==="disabled"?"enabled_unchecked":f||(m?"enabled_unchecked":"disabled"),w=rT(e.category);return s.jsxs(Ss,{padding:"none",children:[s.jsxs("button",{onClick:()=>d(p=>!p),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${nT[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(tT,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),w&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${bd[x]??bd.disabled}`,children:u[x]??x}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[w&&s.jsx("button",{onClick:p=>{p.stopPropagation(),o(e.type,!m)},disabled:n===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${m?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:c(m?"machine.providerRow.disable":"machine.providerRow.enable")}),s.jsx("span",{className:"text-text-muted text-xs",children:h?"▾":"▸"})]})]}),h&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelType")})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelVersion")})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelBinary")})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelStatus")})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelDetails")})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelSource")})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelTrust")})," ",t.trustDescription]}),(()=>{const p=t==null?void 0:t.links;if(!p)return null;const y=Object.entries(p).map(([k,b])=>({k,href:sT(b)})).filter(k=>k.href!==null);return y.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelLinks")})," ",y.map(({k,href:b})=>s.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:k},k))]})})()]}),w&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelDetection")})," ",gd(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelVerification")})," ",gd(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(p=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[p.label||p.key,n===`${e.type}.${p.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:c("machine.providerRow.saving")})]}),p.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:p.description})]}),s.jsx("div",{className:"shrink-0",children:p.type==="boolean"?s.jsx("button",{onClick:()=>void r(e.type,p.key,!(e.values[p.key]??p.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[p.key]??p.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[p.key]??p.default?21:3}})}):p.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[p.key]??p.default??0)||0,min:p.min,max:p.max,onChange:y=>{const k=parseInt(y.target.value)||0;p.min!==void 0&&k<p.min||p.max!==void 0&&k>p.max||r(e.type,p.key,k)},className:"machine-input w-20 text-center text-[11px]"}):p.type==="select"&&p.options?s.jsx("select",{value:String(e.values[p.key]??p.default??""),onChange:y=>void r(e.type,p.key,y.target.value),className:"machine-input text-[11px]",children:p.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",defaultValue:String(e.values[p.key]??p.default??""),onBlur:y=>void r(e.type,p.key,y.target.value),className:"machine-input w-[180px] text-[11px]"})})]},p.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void a(e.type),disabled:!m||n===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${m?"":"opacity-40 cursor-not-allowed"}`,title:m?"Run detection for the configured executable":"Enable provider before detection",children:c("machine.providerRow.detect")}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:c("machine.providerRow.resetCommand")})]})})]})]})}function Fr(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function aT({machineId:e,sendDaemonCommand:t,onChange:n}){const[r,o]=l.useState([]),[a,i]=l.useState([]),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState(!1),[x,w]=l.useState(""),[p,y]=l.useState("main"),[k,b]=l.useState(""),[j,S]=l.useState(!1),[v,g]=l.useState(null),[N,C]=l.useState(null),A=l.useCallback(async()=>{if(e){u(!0),d(null);try{const P=Fr(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){d((P==null?void 0:P.error)||"Failed to load sources");return}o(P.sources||[]),i(P.conflicts||[])}catch(P){d((P==null?void 0:P.message)||String(P))}finally{u(!1)}}},[e,t]);l.useEffect(()=>{A()},[A]);const T=async()=>{if(x.trim()){S(!0),d(null);try{const P=Fr(await t(e,"add_provider_source",{url:x.trim(),ref:p.trim()||"main",...k.trim()?{name:k.trim()}:{}}));P!=null&&P.success?(f(!1),w(""),y("main"),b(""),await A(),n==null||n()):d((P==null?void 0:P.error)||"Failed to add source")}catch(P){d((P==null?void 0:P.message)||String(P))}finally{S(!1)}}},M=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){g(P),d(null);try{const B=Fr(await t(e,"remove_provider_source",{name:P}));B!=null&&B.success?(await A(),n==null||n()):d((B==null?void 0:B.error)||"Failed to remove source")}catch(B){d((B==null?void 0:B.message)||String(B))}finally{g(null)}}},L=async(P,B)=>{C(`${P}:${B}`),d(null);try{const K=Fr(await t(e,"set_active_provider_source",{type:P,sourceName:B}));K!=null&&K.success?(await A(),n==null||n()):d((K==null?void 0:K.error)||"Failed to set active source")}catch(K){d((K==null?void 0:K.message)||String(K))}finally{C(null)}};return s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void A(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>f(!0),className:"machine-btn text-[10px] bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:"+ Add source"})]})]}),h&&s.jsx("div",{className:"mb-2 text-[11px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:h}),r.length===0?s.jsx("div",{className:"text-[11px] text-text-muted italic",children:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.'}):s.jsx("ul",{className:"flex flex-col gap-2",children:r.map(P=>s.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-mono text-[12px] text-text-primary",children:P.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[P.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",P.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void M(P.name),disabled:v===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:v===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([B,K])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[B,":"]})," ",K.length]},B))})]},P.name))}),a.length>0&&s.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[s.jsx("div",{className:"text-[11px] font-semibold text-amber-300 mb-1.5",children:"Conflicts"}),s.jsx("div",{className:"text-[10px] text-text-muted mb-2",children:"Multiple sources expose the same provider type. Pick which source's copy should be active."}),s.jsx("ul",{className:"flex flex-col gap-1.5",children:a.map(P=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[P.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",P.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:P.candidates.map(B=>s.jsxs("button",{type:"button",onClick:()=>void L(P.type,B),disabled:N===`${P.type}:${B}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===B?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:P.active===B?"Active":`Switch active to ${B}`,children:[P.active===B?"● ":"",B]},B))})]},P.type))})]}),m&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:x,onChange:P=>w(P.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[s.jsx("span",{children:"Ref (branch/tag)"}),s.jsx("input",{type:"text",value:p,onChange:P=>y(P.target.value),placeholder:"main",className:"machine-input text-[11px]"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-2",children:[s.jsx("span",{children:"Name (optional, auto-derived from URL)"}),s.jsx("input",{type:"text",value:k,onChange:P=>b(P.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>f(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void T(),disabled:j||!x.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:j?"Cloning…":"Clone + register"})]})]})]})}function iT({machineId:e,providers:t,sendDaemonCommand:n}){var Q;const{t:r}=Le("common"),[o,a]=l.useState([]),[i,c]=l.useState(!1),[u,h]=l.useState(null),[d,m]=l.useState("all"),[f,x]=l.useState(!1),[w,p]=l.useState(!1),[y,k]=l.useState(!1),[b,j]=l.useState(null),[S,v]=l.useState("normal"),[g,N]=l.useState(""),[C,A]=l.useState(!1),T=l.useCallback(async()=>{if(e)try{const E=await n(e,"get_provider_source_config",{}),I=md(E);I&&(j(I),v(I.sourceMode),N(I.explicitProviderDir||""))}catch{}},[e,n]),M=l.useCallback(async()=>{if(e){c(!0);try{const E=await n(e,"get_provider_settings",{}),I=JA(E);if(I){const $=QA(I,t,{filterSchema:D=>D.filter(U=>U.key!=="enabled")});$.sort((D,U)=>D.category.localeCompare(U.category)||D.displayName.localeCompare(U.displayName)),a($)}}catch{}c(!1)}},[e,t,n]);l.useEffect(()=>{o.length===0&&M(),b||T()},[]);const L=async(E,I,$)=>{h(`${E}.${I}`),a(D=>D.map(U=>U.type===E?{...U,values:{...U.values,[I]:$}}:U));try{const D=await n(e,"set_provider_setting",{providerType:E,key:I,value:$});D!=null&&D.success||M()}catch{M()}h(null)},P=async(E,I)=>{await L(E,"enabled",I),await M()},B=async E=>{h(`${E}.detect`);try{await n(e,"detect_provider",{providerType:E})}finally{await M(),h(null)}},K=async E=>{await L(E,"executablePath",""),await L(E,"executableArgs",""),await M()},F=async()=>{A(!0);try{const E=await n(e,"set_provider_source_config",{providerSourceMode:S,providerDir:XA(g)}),I=md(E);I?(j(I),v(I.sourceMode),N(I.explicitProviderDir||"")):await T(),await M()}catch{await T()}A(!1)},R=o.filter(E=>d==="all"||E.category===d);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:r("machine.providers.filter")}),["all","acp","cli","ide","extension"].map(E=>s.jsx("button",{onClick:()=>m(E),className:`machine-btn text-[10px] px-2 py-0.5 ${d===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>p(E=>!E),className:`machine-btn text-[10px] ${w?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:r("machine.providers.sources")}),s.jsx("button",{onClick:()=>x(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:r("machine.providers.create")}),s.jsxs("button",{onClick:M,disabled:i,className:"machine-btn text-[10px]",children:[i?"⏳":"↻"," ",r("machine.providers.refresh")]}),s.jsx("button",{onClick:()=>k(E=>!E),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:r("machine.providers.advanced")})]})]}),w&&s.jsx(aT,{machineId:e,sendDaemonCommand:n,onChange:()=>{M()}}),y&&s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:r("machine.providers.sourceConfigTitle")}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:r("machine.providers.sourceConfigDesc")})]}),s.jsx("button",{onClick:T,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:r("machine.providers.sourceMode")}),s.jsxs("select",{value:S,onChange:E=>v(E.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:r("machine.providers.explicitProviderDir")}),s.jsx("input",{type:"text",value:g,onChange:E=>N(E.target.value),placeholder:r("machine.providers.providerDirPlaceholder"),className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void F(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:r(C?"machine.providers.applying":"machine.providers.applyReload")})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.userRoot")})," ",(b==null?void 0:b.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.upstreamRoot")})," ",(b==null?void 0:b.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.providerRoots")})," ",((Q=b==null?void 0:b.providerRoots)==null?void 0:Q.join(" → "))||"—"]})]})]}),i&&o.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:r("machine.providers.loadingSettings")}):R.length===0?s.jsx(Ss,{padding:"none",className:"px-4.5 py-8 text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:d==="all"?r("machine.providers.noProviders"):r("machine.providers.noFilteredProviders",{filter:d.toUpperCase()})})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:R.map(E=>s.jsx(oT,{prov:E,providerInfo:t.find(I=>I.type===E.type),savingKey:u,onSetSetting:L,onEnableToggle:P,onDetect:B,onResetCommand:K},E.type))}),f&&s.jsx(ZA,{machineId:e,providers:t,sendDaemonCommand:n,onClose:()=>x(!1),onCreated:()=>{x(!1),M()}})]})}const lT=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function cT({count:e,since:t,category:n}){return{count:e,since:t,...n==="all"?{}:{category:n}}}function dT(e,t){return t==="all"?e:e.filter(n=>n.category===t)}function uT(e){return e.trim().toLowerCase()}function Ho(e,t){const n=uT(t);return n?e.some(r=>String(r??"").toLowerCase().includes(n)):!0}function ml(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function jn(e,t=220){const n=ml(e);return n?n.length>t?`${n.slice(0,t)}…`:n:""}function hT(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(n=>{const r=n;return{timestamp:Number(r.ts)||0,level:r.level||"info",message:`[${String(r.category||"daemon")}] ${String(r.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const n=t.trim();return{kind:n?"text":"empty",entries:[],rawText:n}}return{kind:"empty",entries:[],rawText:""}}function pT(e,t){return e.filter(n=>Ho([n.level,n.message],t))}function xd(e){return`${e.timestamp}:${e.level}:${e.message}`}function mT(e,t,n=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(xd(i),i);for(const i of t.entries)r.set(xd(i),i);const o=Array.from(r.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-n),a=o.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:o,kind:"structured",rawText:"",lastTs:a}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function fT(e,t,n=120){if(t.length===0)return e;const r=new Map;for(const o of e)r.set(o.id,o);for(const o of t)r.set(o.id,o);return Array.from(r.values()).sort((o,a)=>o.ts-a.ts).slice(-n)}function bT(e,t){return e.split(`
99
99
  `).map(n=>n.trimEnd()).filter(Boolean).filter(n=>Ho([n],t))}function gT(e,t){return e.filter(n=>Ho([n.level,n.category,n.stage,n.interactionId,ml(n.payload)],t))}function xT(e,t){return e.filter(n=>Ho([n.kind,n.topic,n.interactionId,ml(n.payload)],t))}function yd(e){return e==="warn"||e==="error"}function yT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){return{all:e.length+t.length+n.length+r.length,info:e.filter(o=>o.level!=="debug").length+n.filter(o=>o.level!=="debug").length+r.length,issues:e.filter(o=>yd(o.level)).length+n.filter(o=>yd(o.level)).length}}function vT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const $=await n(
111
111
 
112
112
  `)}function PT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function LT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function RT({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:h,daemonFetchError:d,traceFetchError:m}){const f=dT(r,a),x=pT(e,c),w=bT(t,c),p=gT(f,c),y=xT(o,c),k=PT(x,i),b=i==="all"?w:[],j=LT(p,i),S=i==="issues"?[]:y,v=yT({daemonLogs:x,daemonRawLines:w,trace:p,webEvents:y}),g=AT({daemonLogs:k,daemonRawLines:b,trace:j,webEvents:S}),N=IT(g),C=kT({daemonLoading:u,traceLoading:h,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:x.length,daemonRawLineCount:w.length,traceCount:p.length,webEventCount:y.length});return{filteredDaemonLogs:x,filteredDaemonRawLines:w,filteredTraceEntries:p,filteredWebEvents:y,visibleDaemonLogs:k,visibleDaemonRawLines:b,visibleTraceEntries:j,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:g,diagnosticsSummary:N,sourceStates:C}}function ET(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jp(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function gi(e){return e==="error"?"text-red-300 border-red-500/25 bg-red-500/[0.05]":e==="warn"?"text-amber-200 border-amber-500/25 bg-amber-500/[0.05]":e==="debug"?"text-slate-300 border-slate-500/25 bg-slate-500/[0.05]":"text-text-secondary border-border-subtle bg-bg-primary"}function Ma(e){return e==="good"?"border-emerald-500/20 bg-emerald-500/[0.05]":e==="warning"?"border-amber-500/20 bg-amber-500/[0.05]":e==="danger"?"border-red-500/20 bg-red-500/[0.05]":"border-border-subtle bg-bg-secondary"}function fl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function _T({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${gi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Jp(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:fl(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function $T({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:h,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>o(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>a(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:h,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function BT({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(Ss,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(o=>s.jsxs("button",{onClick:()=>n(o),className:`machine-btn text-[10px] px-2 py-0.5 ${e===o?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",o.toUpperCase(),"+"]},o))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:lT.map(o=>s.jsx("button",{onClick:()=>r(o.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===o.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:o.label},o.value))})]})})}function FT({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,daemonFetchError:i,traceFetchError:c}){var d,m;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",h=i||c?"danger":a?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ma(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:r.trim()?`Filtered by “${r.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ma(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[fl(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Jp(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ma(h)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":a?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ET(o)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function HT({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",fl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function WT({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:h}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[r.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),r.map(d=>s.jsx(_T,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${a.length} visible raw line(s) from file fallback`:`${o.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&o.length===0&&a.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&a.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&o.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&a.map((d,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${m}`)),e.daemonLogKind!=="text"&&o.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${gi(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:h.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${gi(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jn(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:h.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jn(d.payload,360)||"No payload"})]},d.id))]})]})]})}function OT({machineId:e,sendDaemonCommand:t}){const n=wT({machineId:e,sendDaemonCommand:t}),[r,o]=l.useState("info"),[a,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),h=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>RT({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:a,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,a,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const w=d.current?"smooth":"instant";setTimeout(()=>{var p;(p=h.current)==null||p.scrollIntoView({behavior:w}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var p;const w=vT({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!w.trim()){pt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(w)),pt.showToast("Copied visible logs to clipboard.","success")}catch(y){pt.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),x=l.useCallback(async()=>{var p;const w=DT({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(w)),pt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){pt.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx($T,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:a,autoRefresh:n.autoRefresh,onQuickFilterChange:o,onSearchQueryChange:i,onCopyDiagnostics:()=>{x()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(w=>!w),onRefresh:n.refresh,onClear:n.clear}),s.jsx(BT,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(FT,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:a,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx(HT,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(WT,{streams:n,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:a}),s.jsx("div",{ref:h})]})}function UT(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Qp(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function GT(e){var o;const t=[],n=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),c=Qp((a==null?void 0:a.meta)||void 0),u=((o=a==null?void 0:a.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(a):(i==="stopped"||i==="failed")&&(u||c)?n.push(a):r.push(a)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function KT(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Da(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Pa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function La(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Sd(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);if(r<60)return`${r}m ago`;const o=Math.round(r/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function zT(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function qT(e){switch(e){case"running":return"bg-green-500/[0.08] text-green-500";case"starting":return"bg-sky-500/[0.08] text-sky-400";case"stopping":return"bg-orange-500/[0.08] text-orange-400";case"interrupted":return"bg-amber-500/[0.08] text-amber-400";case"failed":return"bg-red-500/[0.08] text-red-500";default:return"bg-bg-glass text-text-muted"}}function VT(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const o=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!o)continue;const a=`${r.providerType}::${r.workspace}::${o}`;t.set(a,(t.get(a)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function YT({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,o]=l.useState(""),[a,i]=l.useState(null),[c,u]=l.useState(!1),h=dS(e,{enabled:!!e,includeSessions:!0,limit:ac,intervalMs:Sw}),d=h.diagnostics,m=h.loading,f=h.applyDiagnostics,x=l.useMemo(()=>UT({diagnostics:d,loading:m,refreshing:c,error:r}),[d,m,c,r]),w=l.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=l.useCallback(async()=>{if(e){u(!0);try{const M=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ac}),L=Pa(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");f(L.diagnostics||L.result||null),o("")}catch(M){const L=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";o(L)}finally{u(!1)}}},[f,e,n]);l.useEffect(()=>{!e||d||m||c||p()},[d,m,e,p,c]);const y=l.useCallback(async(M,L)=>{const P=`${M}:${L.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
113
113
  This will terminate the hosted runtime.`))){i(P);try{const B=await n(e,M,{sessionId:L.sessionId}),K=Pa(B);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Session host action failed");const F=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";pt.showToast(`Session host ${F}: ${L.displayName}`,"success"),await p()}catch(B){const K=B instanceof Error?B.message:"Session host action failed";pt.showToast(K,"warning"),o(K)}finally{i(B=>B===P?null:B)}}},[e,p,n]),k=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
114
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const L=await n(e,"session_host_prune_duplicate_sessions",{}),P=Pa(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},K=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,F=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;pt.showToast(`Pruned ${K} duplicate runtime(s) across ${F} group(s)`,"success"),await p()}catch(L){const P=L instanceof Error?L.message:"Duplicate prune failed";pt.showToast(P,"warning"),o(P)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,p,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,L)=>(L.lastActivityAt||0)-(M.lastActivityAt||0)),[d==null?void 0:d.sessions]),j=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:GT(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),S=j.liveRuntimes,v=j.recoverySnapshots,g=j.inactiveRecords,N=l.useMemo(()=>VT(S),[S]),C=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(M,L)=>{var $;const P=a===`session_host_resume_session:${M.sessionId}`,B=a===`session_host_restart_session:${M.sessionId}`,K=a===`session_host_stop_session:${M.sessionId}`,F=Qp(M.meta),R=w.get(M.sessionId),Q=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",I=KT(L);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qT(M.lifecycle)}`,children:M.lifecycle}),F&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:F})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=M.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:zT(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(zd,{size:11})," ",Q]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Sd(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_resume_session",M)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_restart_session",M)},children:B?"Restarting…":"Restart"}),L==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!a,onClick:()=>{y("session_host_stop_session",M)},children:K?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:J0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:a==="session_host_prune_duplicate_sessions",children:a==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${x.toneClass}`,children:x.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:m||c,children:[s.jsx(Co,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ys,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Sd(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:La(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Ys,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[La(A.timestamp),A.sessionId?` · ${A.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("live")}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:S.map(M=>T(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(M=>T(M,"recovery"))})]}),g.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(M=>T(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:C.map(M=>{var P;const L=b.find(B=>B.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((P=w.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:La(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function JT({machine:e,launchPick:t,actions:n}){const{runLaunchCliCore:r,setLaunchPick:o}=n;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(a=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:a.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:a.label||a.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:a.path})]},a.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function QT(e,t){const n=Oh(e),r=dn(e,t),o=Vi(e,r),a=tr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return o?{visible:!0,showButton:!0,title:a?"Daemon update required":"Version mismatch detected",description:a?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:n,required:a,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ra({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Ea({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function XT({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const c=r.slice(0,6),u=n.slice(0,4),d=QT(e,"0.9.82");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Zs,{size:13}),children:"Current Chats"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const f=hi(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(m)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:jo(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:vn(m)})]},m.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Jd,{size:13}),children:"Recent Launches"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(m=>{const{metaText:f,updatedLabel:x}=ep(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>a(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:m.label}),x&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:x})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},m.id)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Ys,{size:13}),children:"Daemon Update"}),s.jsx(Ea,{className:d.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":d.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[d.description,d.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",d.targetVersion,d.channel?` (${d.channel})`:""]})]}),d.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[s.jsx(Co,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:d.buttonLabel})]}):s.jsx("div",{className:d.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function ZT({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:h,handleWorkspaceSetDefault:d}=a,[m,f]=l.useState(!1),[x,w]=l.useState(""),[p,y]=l.useState([]),[k,b]=l.useState(!1),[j,S]=l.useState(""),v=l.useCallback(async N=>{b(!0),S("");try{const C=await sl(i,e,N);w(C.path),y(C.directories)}catch(C){S(C instanceof Error?C.message:"Could not load folder")}finally{b(!1)}},[e,i]),g=l.useCallback(()=>{f(!0);const N=[...n.map(A=>A.workspace),...r.map(A=>A.workspace),...o.map(A=>A.workspace)],C=tl(t.platform,el(N,t.defaultWorkspacePath,(t.workspaces||[]).map(A=>A.path)));v(C)},[o,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:g,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const C=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(C?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${C?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:xu(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void h(N.id),children:"Remove"})]},N.id)})})]}),m&&s.jsx(rl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:x,directories:p,busy:k,error:j,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await u(N)&&f(!1)})()}})]})}function eI({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(ZT,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i})]})}function tI({onNicknameSynced:e}={}){var ke,xe,Se,pe,G,O,Z,q,me,Te;const{id:t}=Wm(),n=pr(),r=ki(),{sendCommand:o}=yt(),a=In(),i=Dh(),c=nh(),u=c.ides||[],h=c.initialLoaded??!0,d=u.find(_=>_.id===t&&_.type==="adhdev-daemon"),m=u.some(_=>_.type==="adhdev-daemon"),f=t?(ke=c.connectionRetryStatuses)==null?void 0:ke[t]:void 0,x=!!(f!=null&&f.blocked),[w,p]=l.useState("workspace"),[y,k]=l.useState(null);l.useCallback((_,se)=>{k({daemonId:_,workspace:se})},[]);const[,b]=l.useState("ide"),j=l.useRef(null),[S,v]=l.useState(null),g=l.useRef("__home__"),[N,C]=l.useState("__home__"),[A,T]=l.useState(!1),M=l.useRef(null);l.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||a(t,{minFreshMs:3e4}).catch(()=>{})},[a,d,t]),l.useEffect(()=>{if(!t||!d||w!=="overview")return;const _=d.machine;(typeof(_==null?void 0:_.cpus)!="number"||typeof(_==null?void 0:_.totalMem)!="number"||typeof(_==null?void 0:_.arch)!="string"||typeof(_==null?void 0:_.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[w,i,d,t]),cS(t&&w==="overview"?[t]:[],{enabled:w==="overview",intervalMs:vw});const L=()=>{if(m){n("/dashboard",{state:{mobileSection:"machines"}});return}n("/machines")},P=VA({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:M});l.useEffect(()=>pt.onToast(se=>{c.setToasts(ce=>{if(ce.some(je=>je.message===se.message&&se.timestamp-je.timestamp<3e3))return ce;const fe={id:se.id,message:se.message,type:se.type,timestamp:se.timestamp,targetKey:se.targetKey,actions:se.actions};return[...ce.slice(-4),fe]});const ve=se.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(H=>H.id!==se.id)),ve)}),[c]);const B=(d==null?void 0:d.availableProviders)||[],K={};for(const _ of B)K[_.type]=_.icon;const F=d?{id:d.id,hostname:yu(d,{fallbackId:d.id}),platform:((xe=d.machine)==null?void 0:xe.platform)||"unknown",arch:((Se=d.machine)==null?void 0:Se.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((G=d.machine)==null?void 0:G.totalMem)||0,freeMem:(O=d.machine)==null?void 0:O.freeMem,availableMem:(Z=d.machine)==null?void 0:Z.availableMem,loadavg:(q=d.machine)==null?void 0:q.loadavg,uptime:(me=d.machine)==null?void 0:me.uptime,release:((Te=d.machine)==null?void 0:Te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,R=u.filter(_=>_.daemonId===t&&_.type!=="adhdev-daemon").filter(_=>!ir(_)&&!pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:Ey(_.aiAgents||(_.agents||[]).map(se=>({id:se.name,name:se.name,status:se.status,version:se.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:t,lastMessageAt:_.lastMessageAt})),Q=u.filter(_=>_.daemonId===t&&ir(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:t,lastMessageAt:_.lastMessageAt})),E=u.filter(_=>_.daemonId===t&&pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,daemonId:t,lastMessageAt:_.lastMessageAt})),I=d?ts(d,{fallbackId:t}):"",$="workspace",D=r.state,U=D==null?void 0:D.initialMachineTab,Y=D==null?void 0:D.initialWorkspaceCategory;D==null||D.initialWorkspaceId,D==null||D.initialWorkspacePath;const ae=U==="ides"||U==="clis"||U==="acps"?"workspace":U||$,z=U==="ides"?"ide":U==="clis"?"cli":U==="acps"?"acp":Y,X=[...R.map(_=>{var se;return{id:`ide:${_.type}:${_.workspace||""}`,label:((se=_.activeChat)==null?void 0:se.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...Q.map(_=>{var se;return{id:`cli:${_.type}:${_.workspace||""}`,label:((se=_.activeChat)==null?void 0:se.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...E.map(_=>{var se;return{id:`acp:${_.type}:${_.workspace||""}`,label:((se=_.activeChat)==null?void 0:se.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}})].sort((_,se)=>(se.lastLaunchedAt||0)-(_.lastLaunchedAt||0)),de=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace,summaryMetadata:_.summaryMetadata,lastLaunchedAt:_.lastLaunchedAt})):X,re=l.useMemo(()=>{var se;const _=((se=c.connectionStates)==null?void 0:se[t||""])||void 0;return u.filter(ve=>ve.daemonId===t&&ve.type!=="adhdev-daemon").flatMap(ve=>qi(ve,{connectionStates:t&&_?{[t]:_}:void 0,defaultConnectionState:_})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,ce)=>hi(ce)-hi(ve))},[u,c.connectionStates,t]),W=l.useCallback(_=>{const se=zh(_);se&&n(dr(se))},[n]),oe=l.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),v(null)}))},[]),V=l.useCallback(_=>{if(!F)return;const{options:se,selectedKey:ve}=Zh({machine:F,currentWorkspacePath:_.workspace}),ce=async()=>{b(_.kind),p("workspace")};j.current=async()=>{const H=se.find(Ce=>Ce.key===g.current),fe=(H==null?void 0:H.workspacePath)??null,je=(H==null?void 0:H.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await P.handleLaunchIde(_.providerType,fe?{workspace:fe}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await P.runLaunchCliCore({cliType:_.providerType,dir:je?void 0:fe||"",workspaceId:je||void 0,model:_.kind==="acp"&&wu(_.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:_.providerSessionId});return}await ce()},g.current=ve,C(ve),v({title:_.kind==="ide"?uo("restart-ide",_.label):_.providerSessionId?mh(_.label):uo("start-fresh",_.label),description:_.kind==="ide"?ho("restart-ide"):_.providerSessionId?fh():ho("start-fresh"),confirmLabel:_.kind==="ide"?po("restart-ide"):_.providerSessionId?oi(!0):po("start-fresh"),busyLabel:_.kind==="ide"?mo("restart-ide"):_.providerSessionId?ph(!0):mo("start-fresh"),workspaceOptions:se,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[P,F]);if(l.useEffect(()=>{p(ae)},[$,ae,t]),l.useEffect(()=>{z&&b(z)},[z,t]),!F)return h?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Workspace"]}),count:R.length+Q.length+E.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(So,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ef,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:_=>P.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&P.handleSaveNickname(),_.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(F.machineNickname||"")},title:"Click to set nickname",children:I}),x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[F.platform," · ",F.arch]}),s.jsxs("span",{children:[F.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),F.p2p.available&&s.jsxs("span",{children:["P2P ",F.p2p.state==="connected"?"connected":F.p2p.state]}),F.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:F.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(_=>s.jsxs("button",{onClick:()=>p(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${w===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${w===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[w==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(XT,{machineEntry:d,providers:B,recentLaunches:de,currentConversations:re,onUpgradeDaemon:async()=>{try{await o(t,"daemon_upgrade",Uh(d))}catch{}},onOpenRecent:V,onOpenConversation:W}),s.jsx(eI,{machine:F,machineId:t,ideSessions:R,cliSessions:Q,acpSessions:E,actions:P,sendDaemonCommand:o})]}),w==="providers"&&s.jsx(iT,{machineId:t,providers:B,sendDaemonCommand:o}),w==="overview"&&s.jsx(YA,{machine:F,ideSessions:R,cliSessions:Q,acpSessions:E}),w==="session-host"&&s.jsx(YT,{machineId:t,cliSessions:Q,sendDaemonCommand:o}),w==="logs"&&s.jsx(OT,{machineId:t,sendDaemonCommand:o})]})})}),P.launchPick&&F&&s.jsx(JT,{machine:F,launchPick:P.launchPick,actions:P}),S&&s.jsx(Xh,{title:S.title,description:S.description,details:S.details,workspaceOptions:S.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:_=>{g.current=_,C(_)},confirmLabel:S.confirmLabel,busyLabel:S.busyLabel,busy:A,onConfirm:oe,onCancel:()=>{j.current=null,v(null)}}),y&&s.jsx(Yp,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>k(null)}),s.jsx(gh,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(se=>se.filter(ve=>ve.id!==_)),onClickToast:_=>{_.targetKey&&n(dr(_.targetKey))}}),s.jsx("style",{children:`
114
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const L=await n(e,"session_host_prune_duplicate_sessions",{}),P=Pa(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},K=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,F=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;pt.showToast(`Pruned ${K} duplicate runtime(s) across ${F} group(s)`,"success"),await p()}catch(L){const P=L instanceof Error?L.message:"Duplicate prune failed";pt.showToast(P,"warning"),o(P)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,p,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,L)=>(L.lastActivityAt||0)-(M.lastActivityAt||0)),[d==null?void 0:d.sessions]),j=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:GT(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),S=j.liveRuntimes,v=j.recoverySnapshots,g=j.inactiveRecords,N=l.useMemo(()=>VT(S),[S]),C=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(M,L)=>{var $;const P=a===`session_host_resume_session:${M.sessionId}`,B=a===`session_host_restart_session:${M.sessionId}`,K=a===`session_host_stop_session:${M.sessionId}`,F=Qp(M.meta),R=w.get(M.sessionId),Q=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",I=KT(L);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qT(M.lifecycle)}`,children:M.lifecycle}),F&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:F})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=M.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:zT(M.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(zd,{size:11})," ",Q]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Sd(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_resume_session",M)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_restart_session",M)},children:B?"Restarting…":"Restart"}),L==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!a,onClick:()=>{y("session_host_stop_session",M)},children:K?"Stopping…":"Stop"})]})]})},M.sessionId)};return s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:J0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:a==="session_host_prune_duplicate_sessions",children:a==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${x.toneClass}`,children:x.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:m||c,children:[s.jsx(Co,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(Ys,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Sd(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:La(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(Ys,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[La(A.timestamp),A.sessionId?` · ${A.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("live")}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:S.map(M=>T(M,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("recovery")}),v.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:v.map(M=>T(M,"recovery"))})]}),g.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(M=>T(M,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),C.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:C.map(M=>{var P;const L=b.find(B=>B.sessionId===M.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(L==null?void 0:L.displayName)||((P=w.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:La(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function JT({machine:e,launchPick:t,actions:n}){const{runLaunchCliCore:r,setLaunchPick:o}=n;return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/55 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-pick-title",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(a=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),r({cliType:t.cliType,workspaceId:a.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:a.label||a.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:a.path})]},a.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function QT(e,t){const n=Oh(e),r=dn(e,t),o=Vi(e,r),a=tr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return o?{visible:!0,showButton:!0,title:a?"Daemon update required":"Version mismatch detected",description:a?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:n,required:a,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ra({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Ea({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function XT({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const c=r.slice(0,6),u=n.slice(0,4),d=QT(e,"0.9.82");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Zs,{size:13}),children:"Current Chats"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const f=hi(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(m)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:jo(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:vn(m)})]},m.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Jd,{size:13}),children:"Recent Launches"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(m=>{const{metaText:f,updatedLabel:x}=ep(m);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>a(m),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:m.label}),x&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:x})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},m.id)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Ys,{size:13}),children:"Daemon Update"}),s.jsx(Ea,{className:d.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":d.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:d.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[d.description,d.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",d.targetVersion,d.channel?` (${d.channel})`:""]})]}),d.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:o,children:[s.jsx(Co,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:d.buttonLabel})]}):s.jsx("div",{className:d.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function ZT({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:h,handleWorkspaceSetDefault:d}=a,[m,f]=l.useState(!1),[x,w]=l.useState(""),[p,y]=l.useState([]),[k,b]=l.useState(!1),[j,S]=l.useState(""),v=l.useCallback(async N=>{b(!0),S("");try{const C=await sl(i,e,N);w(C.path),y(C.directories)}catch(C){S(C instanceof Error?C.message:"Could not load folder")}finally{b(!1)}},[e,i]),g=l.useCallback(()=>{f(!0);const N=[...n.map(A=>A.workspace),...r.map(A=>A.workspace),...o.map(A=>A.workspace)],C=tl(t.platform,el(N,t.defaultWorkspacePath,(t.workspaces||[]).map(A=>A.path)));v(C)},[o,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:g,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(N=>{const C=N.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(C?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${C?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:xu(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void h(N.id),children:"Remove"})]},N.id)})})]}),m&&s.jsx(rl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:x,directories:p,busy:k,error:j,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await u(N)&&f(!1)})()}})]})}function eI({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(ZT,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i})]})}function tI({onNicknameSynced:e}={}){var ke,xe,Se,pe,G,O,Z,q,me,Te;const{id:t}=Wm(),n=pr(),r=ki(),{sendCommand:o}=yt(),a=In(),i=Dh(),c=nh(),u=c.ides||[],h=c.initialLoaded??!0,d=u.find(_=>_.id===t&&_.type==="adhdev-daemon"),m=u.some(_=>_.type==="adhdev-daemon"),f=t?(ke=c.connectionRetryStatuses)==null?void 0:ke[t]:void 0,x=!!(f!=null&&f.blocked),[w,p]=l.useState("workspace"),[y,k]=l.useState(null);l.useCallback((_,te)=>{k({daemonId:_,workspace:te})},[]);const[,b]=l.useState("ide"),j=l.useRef(null),[S,v]=l.useState(null),g=l.useRef("__home__"),[N,C]=l.useState("__home__"),[A,T]=l.useState(!1),M=l.useRef(null);l.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||a(t,{minFreshMs:3e4}).catch(()=>{})},[a,d,t]),l.useEffect(()=>{if(!t||!d||w!=="overview")return;const _=d.machine;(typeof(_==null?void 0:_.cpus)!="number"||typeof(_==null?void 0:_.totalMem)!="number"||typeof(_==null?void 0:_.arch)!="string"||typeof(_==null?void 0:_.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[w,i,d,t]),cS(t&&w==="overview"?[t]:[],{enabled:w==="overview",intervalMs:vw});const L=()=>{if(m){n("/dashboard",{state:{mobileSection:"machines"}});return}n("/machines")},P=VA({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:M});l.useEffect(()=>pt.onToast(te=>{c.setToasts(ce=>{if(ce.some(je=>je.message===te.message&&te.timestamp-je.timestamp<3e3))return ce;const fe={id:te.id,message:te.message,type:te.type,timestamp:te.timestamp,targetKey:te.targetKey,actions:te.actions};return[...ce.slice(-4),fe]});const ve=te.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(H=>H.id!==te.id)),ve)}),[c]);const B=(d==null?void 0:d.availableProviders)||[],K={};for(const _ of B)K[_.type]=_.icon;const F=d?{id:d.id,hostname:yu(d,{fallbackId:d.id}),platform:((xe=d.machine)==null?void 0:xe.platform)||"unknown",arch:((Se=d.machine)==null?void 0:Se.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((G=d.machine)==null?void 0:G.totalMem)||0,freeMem:(O=d.machine)==null?void 0:O.freeMem,availableMem:(Z=d.machine)==null?void 0:Z.availableMem,loadavg:(q=d.machine)==null?void 0:q.loadavg,uptime:(me=d.machine)==null?void 0:me.uptime,release:((Te=d.machine)==null?void 0:Te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,R=u.filter(_=>_.daemonId===t&&_.type!=="adhdev-daemon").filter(_=>!ir(_)&&!pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:Ey(_.aiAgents||(_.agents||[]).map(te=>({id:te.name,name:te.name,status:te.status,version:te.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:t,lastMessageAt:_.lastMessageAt})),Q=u.filter(_=>_.daemonId===t&&ir(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:t,lastMessageAt:_.lastMessageAt})),E=u.filter(_=>_.daemonId===t&&pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,daemonId:t,lastMessageAt:_.lastMessageAt})),I=d?ts(d,{fallbackId:t}):"",$="workspace",D=r.state,U=D==null?void 0:D.initialMachineTab,Y=D==null?void 0:D.initialWorkspaceCategory;D==null||D.initialWorkspaceId,D==null||D.initialWorkspacePath;const ae=U==="ides"||U==="clis"||U==="acps"?"workspace":U||$,z=U==="ides"?"ide":U==="clis"?"cli":U==="acps"?"acp":Y,X=[...R.map(_=>{var te;return{id:`ide:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...Q.map(_=>{var te;return{id:`cli:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...E.map(_=>{var te;return{id:`acp:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}})].sort((_,te)=>(te.lastLaunchedAt||0)-(_.lastLaunchedAt||0)),de=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace,summaryMetadata:_.summaryMetadata,lastLaunchedAt:_.lastLaunchedAt})):X,re=l.useMemo(()=>{var te;const _=((te=c.connectionStates)==null?void 0:te[t||""])||void 0;return u.filter(ve=>ve.daemonId===t&&ve.type!=="adhdev-daemon").flatMap(ve=>qi(ve,{connectionStates:t&&_?{[t]:_}:void 0,defaultConnectionState:_})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,ce)=>hi(ce)-hi(ve))},[u,c.connectionStates,t]),W=l.useCallback(_=>{const te=zh(_);te&&n(dr(te))},[n]),oe=l.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),v(null)}))},[]),V=l.useCallback(_=>{if(!F)return;const{options:te,selectedKey:ve}=Zh({machine:F,currentWorkspacePath:_.workspace}),ce=async()=>{b(_.kind),p("workspace")};j.current=async()=>{const H=te.find(Ce=>Ce.key===g.current),fe=(H==null?void 0:H.workspacePath)??null,je=(H==null?void 0:H.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await P.handleLaunchIde(_.providerType,fe?{workspace:fe}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await P.runLaunchCliCore({cliType:_.providerType,dir:je?void 0:fe||"",workspaceId:je||void 0,model:_.kind==="acp"&&wu(_.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:_.providerSessionId});return}await ce()},g.current=ve,C(ve),v({title:_.kind==="ide"?uo("restart-ide",_.label):_.providerSessionId?mh(_.label):uo("start-fresh",_.label),description:_.kind==="ide"?ho("restart-ide"):_.providerSessionId?fh():ho("start-fresh"),confirmLabel:_.kind==="ide"?po("restart-ide"):_.providerSessionId?oi(!0):po("start-fresh"),busyLabel:_.kind==="ide"?mo("restart-ide"):_.providerSessionId?ph(!0):mo("start-fresh"),workspaceOptions:te,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[P,F]);if(l.useEffect(()=>{p(ae)},[$,ae,t]),l.useEffect(()=>{z&&b(z)},[z,t]),!F)return h?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Workspace"]}),count:R.length+Q.length+E.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(So,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ef,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:_=>P.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&P.handleSaveNickname(),_.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(F.machineNickname||"")},title:"Click to set nickname",children:I}),x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[F.platform," · ",F.arch]}),s.jsxs("span",{children:[F.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),F.p2p.available&&s.jsxs("span",{children:["P2P ",F.p2p.state==="connected"?"connected":F.p2p.state]}),F.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:F.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(_=>s.jsxs("button",{onClick:()=>p(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${w===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${w===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[w==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(XT,{machineEntry:d,providers:B,recentLaunches:de,currentConversations:re,onUpgradeDaemon:async()=>{try{await o(t,"daemon_upgrade",Uh(d))}catch{}},onOpenRecent:V,onOpenConversation:W}),s.jsx(eI,{machine:F,machineId:t,ideSessions:R,cliSessions:Q,acpSessions:E,actions:P,sendDaemonCommand:o})]}),w==="providers"&&s.jsx(iT,{machineId:t,providers:B,sendDaemonCommand:o}),w==="overview"&&s.jsx(YA,{machine:F,ideSessions:R,cliSessions:Q,acpSessions:E}),w==="session-host"&&s.jsx(YT,{machineId:t,cliSessions:Q,sendDaemonCommand:o}),w==="logs"&&s.jsx(OT,{machineId:t,sendDaemonCommand:o})]})})}),P.launchPick&&F&&s.jsx(JT,{machine:F,launchPick:P.launchPick,actions:P}),S&&s.jsx(Xh,{title:S.title,description:S.description,details:S.details,workspaceOptions:S.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:_=>{g.current=_,C(_)},confirmLabel:S.confirmLabel,busyLabel:S.busyLabel,busy:A,onConfirm:oe,onCancel:()=>{j.current=null,v(null)}}),y&&s.jsx(Yp,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>k(null)}),s.jsx(gh,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(te=>te.filter(ve=>ve.id!==_)),onClickToast:_=>{_.targetKey&&n(dr(_.targetKey))}}),s.jsx("style",{children:`
115
115
  @keyframes toast-in {
116
116
  from { opacity: 0; transform: translateX(40px); }
117
117
  to { opacity: 1; transform: translateX(0); }
118
118
  }
119
- `})]})}function sI({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const o=l.useRef(new Map),a=l.useRef(r);a.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{o.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const u=c.map(h=>ls.subscribe({sendData:n},h,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${h}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const x=o.current.get(h);o.current.set(h,f),x!==void 0&&f>x&&a.current()}));return()=>{for(const h of u)h()}},[i,t,n])}const nI={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Xp=l.createContext(null);function rI(){const e=l.useContext(Xp);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function oI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function aI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function iI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function lI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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"})]})}function cI({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function dI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uI({meshes:e,loading:t,error:n,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:h,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:x,newMeshDaemonId:w,onNewMeshDaemonIdChange:p,newMeshWorkspace:y,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:j,onCreate:S,onCancelCreate:v}){const{t:g}=Le("common");return s.jsxs(gr,{icon:s.jsx(es,{}),title:g("repoMesh.list.title"),subtitle:g("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:g("repoMesh.list.createMesh")}),children:[n&&s.jsx(Gt,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:g("repoMesh.list.createTitle")}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.createOnMachine"),hint:g("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:w,onChange:N=>p(N.target.value),disabled:!o.length,children:o.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noConnectedDaemon")}):o.map(N=>s.jsx("option",{value:N.id,children:dI(N)},N.id))})}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.workspace"),hint:g("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:y,onChange:N=>k(N.target.value),disabled:!w||!b.length,children:w?b.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noRegisteredWorkspaces")}):b.map(N=>s.jsx("option",{value:N.path,children:N.label?`${N.label} · ${N.path}`:N.path},N.id||N.path)):s.jsx("option",{value:"",children:g("repoMesh.list.selectMachineFirst")})})}),s.jsx(Ct,{label:g("repoMesh.list.name"),children:s.jsx(is,{value:u,onChange:N=>h(N.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ct,{label:g("repoMesh.list.remoteUrl"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:f,onChange:N=>x(N.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Ct,{label:g("repoMesh.list.repoIdentity"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:d,onChange:N=>m(N.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:S,disabled:!u.trim()||!f.trim()&&!d.trim()||a.createDaemonPicker&&(!w||!y),children:g("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:g("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:g("repoMesh.list.loading")}):e.length===0?s.jsx(Ro,{icon:s.jsx(es,{}),title:g("repoMesh.list.emptyTitle"),description:o.length>0?g("repoMesh.list.emptyWithDaemons"):g("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:c,children:g("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(N=>{var C;return s.jsx("button",{type:"button",onClick:()=>j(N.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(es,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:N.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:N.repoIdentity||N.repo_identity||g("repoMesh.list.noRepoIdentity")}),(N.defaultBranch||N.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(aI,{size:11}),N.defaultBranch||N.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(N.createdAt||N.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((C=N.nodes)==null?void 0:C.length)??N.nodeCount??0," ",g("repoMesh.list.nodesSuffix")]})]})]})},N.id)})})]})}const hI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],pI=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function mI(){return{nodeId:"",provider:"",model:"",n:""}}function Cd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function fI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function bI(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],o=r.provider.trim();if(!o)return{error:{code:"provider_required",slot:n+1}};const a=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let u;if(c){const h=Number(c);if(!Number.isFinite(h)||h<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(h)}t.push({provider:o,...a?{nodeId:a}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function gI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:o}=Le(),{theme:a}=Ls(),i=l.useMemo(()=>Rs(a),[a]),c=l.useMemo(()=>kh(r),[r]),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState({}),[y,k]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>({nodeId:I.nodeId,machineLabel:I.machineLabel,providers:I.providers,providerPriority:I.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>I.nodeId),[e==null?void 0:e.nodes]),S=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(I=>[I.nodeId,I.machineLabel||I.nodeId])),[e==null?void 0:e.nodes]),v=l.useMemo(()=>{const I={};for(const $ of b)I[$.nodeId]=Cd($);return I},[b]),g=l.useMemo(()=>{const I=[...new Set(b.flatMap(Cd).filter(Boolean))];return[...new Set([...I,...hI])].sort()},[b]),N=!!t&&!!n,C=I=>I&&typeof I=="object"&&"result"in I?I.result:I,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),x(null);try{const I=await n(t,"magi_kind_panel_list",{}),$=C(I);if(($==null?void 0:$.success)===!1)throw new Error($.error||o("meshGraph.magiKind.errorLoad"));h($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),p({})}catch(I){x((I==null?void 0:I.message)||o("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,o]);l.useEffect(()=>{A()},[A]);const T=l.useCallback(I=>{if(w[I])return w[I];const $=u[I];return $?$.map(fI):[]},[w,u]),M=(I,$)=>{p(D=>({...D,[I]:$}))},L=(I,$,D)=>{const U=T(I);M(I,U.map((Y,ae)=>ae===$?{...Y,...D}:Y))},P=I=>{M(I,[...T(I),mI()])},B=(I,$)=>{M(I,T(I).filter((D,U)=>U!==$))},K=l.useCallback(async I=>{if(!t||!n)return;const $=bI(T(I));if("error"in $){const D=$.error,U=D.code==="provider_required"?o("meshGraph.magiKind.errorSlotProvider",{slot:D.slot}):D.code==="replica_min"?o("meshGraph.magiKind.errorSlotReplica",{slot:D.slot}):o("meshGraph.magiKind.errorNoSlot");x(`${I}: ${U}`);return}k(I),x(null);try{const D=await n(t,"magi_kind_panel_set",{kind:I,slots:$.slots}),U=C(D);if((U==null?void 0:U.success)===!1)throw new Error(U.error||o("meshGraph.magiKind.errorSave"));await A()}catch(D){x((D==null?void 0:D.message)||o("meshGraph.magiKind.errorSave"))}finally{k(null)}},[t,n,T,A,o]),F=l.useCallback(async I=>{if(!(!t||!n)&&confirm(o("meshGraph.magiKind.removeConfirm",{kind:I}))){k(I),x(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:I}),D=C($);if((D==null?void 0:D.success)===!1)throw new Error(D.error||o("meshGraph.magiKind.errorRemove"));await A()}catch($){x(($==null?void 0:$.message)||o("meshGraph.magiKind.errorRemove"))}finally{k(null)}}},[t,n,A,o]),R=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,Q="btn btn-primary btn-sm",E="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:o("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:E,onClick:()=>void A(),disabled:d||!N,children:o(d?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:o("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:pI.map(({kind:I,labelKey:$,hint:D})=>{const U=T(I),Y=!!u[I],ae=y===I;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:o($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:D}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?o("meshGraph.magiKind.agentCount",{count:u[I].length}):o("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[U.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:o("meshGraph.magiKind.noAgents")}),U.map((z,X)=>{const de=z.nodeId?v[z.nodeId]??[]:[],re=z.nodeId&&de.length?de:g;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.machine")}),s.jsxs("select",{className:R,value:z.nodeId,onChange:W=>L(I,X,{nodeId:W.target.value}),title:o("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.anyMachine")}),j.map(W=>s.jsx("option",{value:W,children:S[W]??W},W)),z.nodeId&&!j.includes(z.nodeId)&&s.jsx("option",{value:z.nodeId,children:o("meshGraph.magiKind.offlineSuffix",{label:S[z.nodeId]??z.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[o("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:R,value:z.provider,onChange:W=>L(I,X,{provider:W.target.value}),title:o("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.selectProvider")}),re.map(W=>s.jsx("option",{value:W,children:W},W)),z.provider&&!re.includes(z.provider)&&s.jsx("option",{value:z.provider,children:z.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.model")}),(()=>{var V;const W=(z.provider?(V=c.get(z.provider))==null?void 0:V.models:void 0)??[],oe=!!z.model&&W.length>0&&!W.includes(z.model);return W.length>0&&!oe?s.jsxs("select",{className:R,value:W.includes(z.model)?z.model:"",title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value==="__custom__"?" ":ie.target.value}),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.modelDefault")}),W.map(ie=>s.jsx("option",{value:ie,children:ie},ie)),s.jsx("option",{value:"__custom__",children:o("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:R,value:z.model.trim(),placeholder:o("meshGraph.magiKind.modelDefault"),title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value})}),W.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>L(I,X,{model:""}),children:o("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${R} sm:w-16`,value:z.n,placeholder:"1",inputMode:"numeric",title:o("meshGraph.magiKind.copiesTitle"),onChange:W=>L(I,X,{n:W.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>B(I,X),"aria-label":o("meshGraph.magiKind.removeAgent"),title:o("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>P(I),disabled:!N,children:o("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:Q,onClick:()=>void K(I),disabled:ae||!N,children:o(ae?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void F(I),disabled:ae||!N||!Y,title:o(Y?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:o("meshGraph.magiKind.removeBinding")})]})]},I)})})]})}function xI({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:o}=Le(),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(null),p=l.useCallback(async()=>{if(!e||!t){d(o("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const k=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||o("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),w(typeof b.bytes=="number"?b.bytes:null)}catch(k){d((k==null?void 0:k.message)||String(k))}finally{u(!1)}},[e,t,n,r,o]),y=l.useCallback(()=>{const k=!a;i(k),k&&m===null&&!c&&p()},[a,m,c,p]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:y,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(a?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),h&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[h,s.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!c&&!h&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),x!==null&&s.jsxs("span",{children:[(x/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:k=>k.currentTarget.select()})]})]})]})}const yI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function vI(e){const t=yI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function wI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function kI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const SI=["active","paused","completed","abandoned"];function jd(e){return(e.status||"active").toLowerCase()}const CI=8;function jI({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:o}=Le("common"),a=l.useMemo(()=>wI(e),[e]),[i,c]=l.useState({}),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("active"),[y,k]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of a){const M=jd(T);A[M]=(A[M]||0)+1}return A},[a]),j=l.useMemo(()=>w==="all"?a:a.filter(A=>jd(A)===w),[a,w]),S=y?j:j.slice(0,CI),v=j.length-S.length,g=!!t&&a.length>0,N=l.useCallback(async()=>{if(t){m(!0),x(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),T=vI(A),M=Array.isArray(T==null?void 0:T.missions)?T.missions:[],L={};for(const P of M)P.id&&typeof P.goal=="string"&&P.goal&&(L[P.id]=P.goal);c(P=>({...P,...L}))}catch(A){x(A instanceof Error?A.message:o("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,o]),C=l.useCallback(A=>{h(T=>({...T,[A]:!T[A]})),!u[A]&&!i[A]&&N()},[u,i,N]);return a.length===0?null:s.jsxs(bt,{title:o("repoMesh.missions.title"),description:o("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[SI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{p(A),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${w===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{p("all"),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${w==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),j.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.missions.empty",{status:w})}),s.jsx("div",{className:"flex flex-col gap-2",children:S.map(A=>{var F;const T=u[A.id]===!0,M=i[A.id],L=kI(A),P=T&&M?M:L.text,B=T&&!M&&L.truncated,K=((F=A.tasks)==null?void 0:F.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),K>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:o("repoMesh.missions.taskCount",{count:K})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,B&&s.jsx("span",{className:"text-text-muted",children:o("repoMesh.missions.goalUnavailable")})]}),(L.truncated||M)&&g&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>C(A.id),disabled:d,children:o(T?"repoMesh.missions.showLess":d&&!M?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>k(!0),children:o("repoMesh.missions.showMore",{count:v})})]})}const NI=["","low","medium","high"],AI={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Nd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Ad(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function TI(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const _s="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function II({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:o}=Le("common"),[a,i]=l.useState(()=>e.map(Nd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Nd))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),h=l.useMemo(()=>kh(t),[t]),d=l.useMemo(()=>{const b=a.map(Ad).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[a,e]),m=(b,j)=>i(S=>S.map((v,g)=>g===b?{...v,...j}:v)),f=(b,j)=>i(S=>S.map((v,g)=>{var A;if(g!==b)return v;const N=((A=h.get(j))==null?void 0:A.models)??[],C=!v.model||N.length===0||N.includes(v.model);return{...v,provider:j,...C?{}:{model:""}}})),x=b=>i(j=>j.filter((S,v)=>v!==b)),w=()=>i(b=>[...b,TI()]),p=(b,j)=>i(S=>{const v=b+j;if(v<0||v>=S.length)return S;const g=[...S];return[g[b],g[v]]=[g[v],g[b]],g}),y=(b,j)=>i(S=>S.map((v,g)=>{if(g!==b)return v;const N=v.difficulty.includes(j);return{...v,difficulty:N?v.difficulty.filter(C=>C!==j):[...v.difficulty,j]}})),k=()=>r(a.map(Ad).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.slotEditor.empty")}),a.map((b,j)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",j+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===0,onClick:()=>p(j,-1),title:o("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===a.length-1,onClick:()=>p(j,1),title:o("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>x(j),"aria-label":o("repoMesh.slotEditor.removeSlot"),children:s.jsx(At,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.provider")}),u.length>0?s.jsxs("select",{className:_s,value:b.provider,onChange:S=>f(j,S.target.value),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.select")}),u.map(S=>s.jsx("option",{value:S,children:S},S)),b.provider&&!u.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:_s,value:b.provider,placeholder:"claude-cli",onChange:S=>m(j,{provider:S.target.value})})]}),(()=>{var C;const S=h.get(b.provider),v=(S==null?void 0:S.models)??[],g=(C=S==null?void 0:S.thinking)!=null&&C.length?["",...S.thinking]:NI,N=!!b.model&&v.length>0&&!v.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.model")}),v.length>0&&!N?s.jsxs("select",{className:_s,value:v.includes(b.model)?b.model:"",onChange:A=>m(j,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:o("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:_s,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:o("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(j,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(j,{model:""}),children:o("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:_s,value:b.thinkingLevel,onChange:A=>m(j,{thinkingLevel:A.target.value}),children:g.map(A=>s.jsx("option",{value:A,children:A||o("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:ky.map(S=>{const v=b.difficulty.includes(S);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>y(j,S),children:AI[S]},S)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:_s,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:S=>m(j,{capability:S.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:_s,value:b.maxParallel,placeholder:o("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:S=>m(j,{maxParallel:S.target.value})})]})]})]},j)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:w,children:[s.jsx(Mi,{size:13})," ",o("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!n||!d,children:o(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function MI(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function DI(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function PI(e){var u,h,d;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const o=(((u=t.userOverrides)==null?void 0:u.platform)||t.reportedPlatform||"").toString().trim(),a=(((h=t.userOverrides)==null?void 0:h.arch)||t.reportedArch||"").toString().trim();o&&n.push({tag:`os=${o}`,custom:!1}),a&&n.push({tag:`arch=${a}`,custom:!1});const i=Array.isArray((d=t.policy)==null?void 0:d.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&n.push({tag:`worktree=${c}`,custom:!1}),n}function LI(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const RI=["os=","arch=","provider=","worktree=","converge="];function EI({node:e,saving:t,onSave:n}){const{t:r}=Le("common"),o=l.useMemo(()=>PI(e).filter(p=>!p.custom),[e]),a=l.useMemo(()=>LI(e),[e]),[i,c]=l.useState(a),[u,h]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(a),f=(p=>{const y=p.trim();return y?/\s/.test(y)?r("repoMesh.tagEditor.noSpaces"):RI.some(k=>y.toLowerCase().startsWith(k))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(y)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function x(){const p=u.trim();!p||f||(c(y=>[...y,p]),h(""))}function w(p){c(y=>y.filter(k=>k!==p))}return s.jsxs("div",{className:"mt-2",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),o.map(p=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:p.tag},p.tag)),i.map(p=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[p,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>w(p),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:p}),children:"×"})]},p))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:p=>h(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),x())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:x,disabled:t||!u.trim()||!!f,children:r("repoMesh.tagEditor.add")}),d&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&o.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function _I(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function $I(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function BI(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function FI(e){const t=BI(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function HI(e){return e.isLocalWorktree===!0}function WI(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(o=>{var a;return((a=o==null?void 0:o.settings)==null?void 0:a.meshNodeId)===e.id||(o==null?void 0:o.workspace)===e.workspace}).map(o=>{var a;return{id:o.sessionId||o.id||o.instanceId||"unknown",provider:o.providerType||o.cliType||o.acpType||o.type||"unknown",status:o.status||((a=o.activeChat)==null?void 0:a.status)||"unknown"}})}function Td(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function OI(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function UI({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:o,userName:a,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:h,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:x,onNodeSystemPromptDraftChange:w,savingNodeSystemPromptId:p,onSaveNodeSystemPrompt:y,selectedNodeId:k,onSelectNode:b,showAddNode:j,onShowAddNode:S,onCancelAddNode:v,nodeWorkspace:g,onNodeWorkspaceChange:N,nodeProviderPriority:C,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:M,nodeCustomPath:L,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:K,attachableDaemons:F,onAddNode:R,onRemoveNode:Q}){const{t:E}=Le("common"),I=l.useMemo(()=>MI(r),[r]),$=l.useMemo(()=>e.filter(D=>!HI(D)),[e]);return s.jsxs(bt,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:F.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(D=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${D.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{M(D.id),N(""),P(!1),A(cr(wn(D.availableProviders||[]))),S()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Td(D)}),D.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:D.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(D.workspaces||[]).length})})]},D.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:S,children:[s.jsx(lI,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),j&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(At,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Ct,{label:E("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:D=>{var U;M(D.target.value),N(""),P(!1),A(cr(wn(((U=r.find(Y=>Y.id===D.target.value))==null?void 0:U.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(D=>s.jsx("option",{value:D.id,children:Td(D)},D.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Ct,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!L&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(D=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===D.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>N(D.path),children:[s.jsx("span",{className:"font-medium block truncate",children:D.label||D.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:D.path})]},D.id||D.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),N("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:D=>N(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&R()}}),B.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),N("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const D=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],U=`mesh-add-node-workspaces-${o||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:ae=>N(ae.target.value),placeholder:((Y=D[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:D.length>0?U:void 0,autoFocus:!0}),D.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:U,children:D.map(ae=>s.jsx("option",{value:ae.path,children:ae.label||ae.path},ae.id||ae.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:D.slice(0,6).map(ae=>s.jsx("button",{type:"button",onClick:()=>N(ae.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ae.path,children:ae.label||ae.path.split("/").filter(Boolean).pop()||ae.path},ae.id||ae.path))})]})]})})()})}),s.jsx(Ct,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(mk,{value:C,availableProviders:i.addNodeDaemonPicker?K:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:R,disabled:!g.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"btn btn-secondary btn-sm",children:E("repoMesh.nodeList.cancel")})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(Ro,{icon:s.jsx(xn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(D=>{var de;const U=FI(D),Y=_I(D,t),ae=WI(D,n),z=k===D.id,X=D.status||D.machine_status||(Y.length>0||ae.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(z?null:D.id),onKeyDown:i.addNodeDaemonPicker?void 0:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),b(z?null:D.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:D.machine_label||D.machine_nickname||D.hostname||D.workspace}):s.jsx("span",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(cI,{status:X}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:OI(r.find(re=>re.id===String(D.daemon_id||"")),a),machine:D.machine_label||D.daemon_id||D.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx(EI,{node:D,saving:m===D.id,onSave:re=>f(D,re)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:re=>re.stopPropagation(),children:[s.jsx(Ct,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(II,{slots:Array.isArray((de=D.policy)==null?void 0:de.slots)?D.policy.slots:[],availableProviders:DI(D,I),saving:h===D.id,onSave:re=>d(D,re)})}),i.nodeInstruction&&s.jsxs(Ct,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:x[D.id]??"",onChange:re=>{const W=re.target.value;w(D.id,W)},onClick:re=>re.stopPropagation(),disabled:p===D.id,placeholder:E("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:re=>{re.stopPropagation(),y(D)},disabled:p===D.id,children:p===D.id?E("repoMesh.nodeList.saving"):E("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:re=>{re.stopPropagation(),Q(D.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(iI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:re=>re.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",E("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:U.configured?"text-green-400":"text-amber-400",children:U.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",ae.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(D.created_at||D.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Y.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(re=>s.jsx("li",{className:"font-mono",children:$I(re)},re.id))})]}),ae.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:ae.map(re=>s.jsxs("li",{className:"font-mono",children:[re.provider," / ",re.status," / ",re.id]},re.id))})]})]})]})]},D.id)})})]})}function Hr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GI({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:o,launchingCoordinator:a,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:h,hostLabel:d,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:x,onLaunchCoordinator:w}){const{t:p}=Le("common"),y=s.jsx(Ct,{label:p("repoMesh.host.coordinatorProvider"),hint:p("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:r,onChange:j=>o(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),k=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(h)return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:p("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||p("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",p(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[p("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Gt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:p("repoMesh.host.hostOffline")})," ",p("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Ct,{label:p("repoMesh.host.reconnectToCommand"),hint:p("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:f,onChange:j=>x(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.waitForHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:p("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:a||!t,title:t?void 0:p("repoMesh.host.noCommandTarget"),children:p(a?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),k]});const b=e.find(j=>j.id===t);return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("repoMesh.host.descriptionUnset"),children:[s.jsxs(Gt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:p("repoMesh.host.setHostBanner")})," ",p("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Hr(b)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Hr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Ct,{label:p("repoMesh.host.hostDaemon"),hint:p("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:j=>n(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.resolvingHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!t||!c||a,title:t?c?void 0:p("repoMesh.host.attachNodeFirst"):p("repoMesh.host.pickHostFirst"),children:p(a?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:p("repoMesh.host.noDaemonsToHost")}),k]})}function KI({meshId:e,availableCliAgents:t}){const{t:n}=Le(),r=t.find(a=>{const i=a.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||a.name.toLowerCase().includes("hermes")}),o=Kh(r==null?void 0:r.meshCoordinator,{meshId:e});return o?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(fp,{setup:o,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const _a=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],zI=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function qI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function VI(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const YI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function xi(e){return{...YI,...(e==null?void 0:e.policy)||{}}}function JI(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function QI({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:o,displayedMeshStatus:a,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:h,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:x,onSaveCoordinatorPrompt:w,daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:L,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:K,meshQueue:F,userName:R,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_,availableCliAgents:se,features:ve,sendCommand:ce}){var Fe;const{t:H}=Le("common"),fe=xi(e),je=e.nodes||[],Ce=je.some(Ie=>{var Oe;const ye=Number((Oe=Ie.policy)==null?void 0:Oe.schedulingPriority);return Number.isFinite(ye)&&ye!==0}),Be=!fe.schedulingStrategy,Xe=l.useMemo(()=>je.some(Ie=>{var ye;return Array.isArray((ye=Ie.policy)==null?void 0:ye.slots)&&Ie.policy.slots.length>0}),[je]),dt=Be?Xe?"smart":je.length>=2?"spread":null:null,[it,he]=l.useState(!1),$e=!!K&&!!e.id;return s.jsxs(gr,{icon:s.jsx(es,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:H("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(oI,{size:13}),H(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:H("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Gt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),ve.meshHostDaemonSection&&s.jsx(GI,{daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:Ie=>{L(Ie),u()},onLaunchCoordinator:P}),s.jsxs(bt,{title:H("repoMesh.detail.observabilityTitle"),description:H("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>he(!0),disabled:!$e,title:H($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),H("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:H("repoMesh.detail.observabilityHint")})]})]}),s.jsx(UI,{nodes:je,meshQueue:F,activeDaemon:B,daemons:p,selectedMeshId:e.id,userName:R,features:{addNodeDaemonPicker:ve.addNodeDaemonPicker,nodeInstruction:ve.nodeInstruction},coordinatorDaemonId:y,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_}),s.jsxs(bt,{title:H("repoMesh.detail.schedulingTitle"),description:H("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:H("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:zI.map(Ie=>{const Oe=VI(fe.schedulingStrategy,{priorityConfigured:Ce})===Ie.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Oe?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:Ie.value,checked:Oe,disabled:h,onChange:()=>d({schedulingStrategy:qI(Ie.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Ie.label,dt===Ie.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:H("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Ie.description})]})]},Ie.value)})})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),s.jsx(bt,{title:H("repoMesh.detail.visibilityTitle"),description:H("repoMesh.detail.visibilityDescription"),children:s.jsx(Ct,{label:H("repoMesh.detail.visibilityLabel"),hint:H("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Ie=>d({spawnedSessionVisibility:Ie.target.value==="visible"?"visible":"hidden"}),disabled:h,children:[s.jsx("option",{value:"hidden",children:H("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:H("repoMesh.detail.visibilityVisible")})]})})}),a&&s.jsx(bt,{title:H("repoMesh.detail.magiTitle"),description:H("repoMesh.detail.magiDescription"),children:s.jsx(gI,{status:a,daemonId:K,sendDaemonCommand:ce,availableProviders:Q})}),s.jsx(jI,{status:a,daemonId:K,meshId:e.id,sendCommand:ce}),ve.coordinatorPrompt&&s.jsxs(bt,{title:H("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.coordinatorPromptDescription"),children:[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-1",children:H("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Ct,{label:H("repoMesh.detail.overrideLabel"),hint:H("repoMesh.detail.overrideHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:Ie=>f({...m,override:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.overridePlaceholder")}),s.jsx(xI,{daemonId:K,meshId:e.id,cliType:b,sendCommand:ce})]}),s.jsx(Ct,{label:H("repoMesh.detail.appendLabel"),hint:H("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:Ie=>f({...m,append:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:H("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:x,children:H(x?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:x,title:H("repoMesh.detail.clearTitle"),children:H("repoMesh.detail.clear")})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:H("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.userLevelDescription")}),s.jsx(Uk,{daemonId:K||void 0})]})]}),s.jsxs(bt,{title:H("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:H("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",H("repoMesh.detail.requireApprovalBeforePush")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",H("repoMesh.detail.requireApproval")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",H("repoMesh.detail.warnAndContinue")],["block",H("repoMesh.detail.blockTask")],["checkpoint_then_continue",H("repoMesh.detail.checkpointThenContinue")]],val:Ie=>Ie||"warn",parse:Ie=>Ie},{label:H("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",H("repoMesh.detail.requireExplicitApproval")],["enabled",H("repoMesh.detail.allowRefineryPublish")]],val:Ie=>Ie?"enabled":"disabled",parse:Ie=>Ie==="enabled"}].map(({label:Ie,key:ye,opts:Oe,val:ut,parse:at})=>s.jsx(Ct,{label:Ie,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut(fe[ye]),onChange:ht=>d({[ye]:at(ht.target.value)}),disabled:h,children:Oe.map(([ht,J])=>s.jsx("option",{value:ht,children:J},ht))})},ye))}),(()=>{const Ie=fe.autoFastForward&&typeof fe.autoFastForward=="object"?fe.autoFastForward:{},ye=Ie.enabled!==!1,Oe=Ie.remoteNodes===!0,ut=Ie.mode==="continuous"?"continuous":"idle",at=ht=>d({autoFastForward:{...Ie,...ht}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Ct,{label:H("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ye?"enabled":"disabled",onChange:ht=>at({enabled:ht.target.value==="enabled"}),disabled:h,children:[s.jsx("option",{value:"enabled",children:H("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:H("repoMesh.detail.ffDisabled")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.includeRemoteNodes"),hint:H("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Oe?"yes":"no",onChange:ht=>at({remoteNodes:ht.target.value==="yes"}),disabled:h||!ye,children:[s.jsx("option",{value:"no",children:H("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:H("repoMesh.detail.remoteYes")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.detectionMode"),hint:H("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut,onChange:ht=>at({mode:ht.target.value==="continuous"?"continuous":"idle"}),disabled:h||!ye||!Oe,children:[s.jsx("option",{value:"idle",children:H("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:H("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Ct,{label:H("repoMesh.detail.sessionCleanupLabel"),hint:H("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.sessionCleanupOnNodeRemove||"preserve",onChange:Ie=>d({sessionCleanupOnNodeRemove:Ie.target.value}),disabled:h,children:_a.map(Ie=>s.jsx("option",{value:Ie.value,children:Ie.label},Ie.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Fe=_a.find(Ie=>Ie.value===fe.sessionCleanupOnNodeRemove))==null?void 0:Fe.description)||_a[0].description})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),ve.hermesMcpConfig&&s.jsx(KI,{meshId:e.id,availableCliAgents:se}),ve.meshHostDaemonSection&&s.jsxs(Gt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]}),it&&$e&&s.jsx(qp,{activeConv:JI({meshId:e.id,daemonId:K,meshName:e.name}),sendDaemonCommand:ce,onClose:()=>he(!1)})]})}const Un=new Map;function XI({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i}){const c=e.map(I=>I.id).filter(Boolean).sort().join(","),[u,h]=l.useState(()=>Un.get(c)??[]),[d,m]=l.useState(null),[f,x]=l.useState(()=>!Un.has(c)),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),L=l.useMemo(()=>e.find(I=>I.id===C),[e,C]),P=(L==null?void 0:L.workspaces)||[],B=l.useMemo(()=>wn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!a.createDaemonPicker||!i||!C||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(C,{minFreshMs:3e4})).catch(()=>{})},[a.createDaemonPicker,i,C,L]);const K=l.useMemo(()=>e.map(I=>I.id).filter(Boolean).sort().join(","),[e]),F=l.useCallback(async(I=!1)=>{const $=I||Un.has(K);x(D=>$?D:!0);try{if(a.createDaemonPicker){const D=await Promise.allSettled(e.map(async ae=>{if(!ae.id)return[];const z=await n(ae.id,"list_meshes",{}),X=r(z);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");return(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(de=>o(de,ae.id)).filter(de=>de.id)})),U=new Map;for(const ae of D)if(ae.status==="fulfilled")for(const z of ae.value)U.has(z.id)||U.set(z.id,z);const Y=Array.from(U.values());h(Y),Un.set(K,Y),p(null)}else{if(!t)return;const D=await n(t,"list_meshes");if(D!=null&&D.success){const U=(D.meshes||[]).map(Y=>o(Y,t));h(U),Un.set(K,U),p(null)}else p((D==null?void 0:D.error)||"Failed to load meshes")}}catch(D){p((D==null?void 0:D.message)||"Failed to load meshes")}finally{x(!1)}},[K,t,n,r,o,a.createDaemonPicker]);async function R(){var U,Y;const I=a.createDaemonPicker?C:t;if(!I||!b.trim())return;const $=g.trim(),D=S.trim();if(!(!$&&!D))try{const ae={name:b.trim()};$&&(ae.repoRemoteUrl=$),D&&(ae.repoIdentity=D);const z=await n(I,"create_mesh",ae),X=r(z);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Create failed");const de=typeof((U=X==null?void 0:X.mesh)==null?void 0:U.id)=="string"?X.mesh.id:"";if(de&&a.createDaemonPicker&&T){const re=await n(I,"add_mesh_node",{meshId:de,daemonId:I,machineId:L==null?void 0:L.machineId,workspace:T,role:"host",providerPriority:cr(B)}),W=r(re);if((W==null?void 0:W.success)===!1)throw new Error(W.error||"Mesh created but failed to attach workspace")}k(!1),j(""),v(""),N(""),M(""),await F(),(Y=X==null?void 0:X.mesh)!=null&&Y.id&&m(X.mesh.id)}catch(ae){p((ae==null?void 0:ae.message)||"Create failed")}}async function Q(I){var D;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((D=u.find(U=>U.id===I))==null?void 0:D.__sourceDaemonId)||t;try{const U=await n($,"delete_mesh",{meshId:I}),Y=r(U);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");d===I&&m(null),await F()}catch(U){p((U==null?void 0:U.message)||"Delete failed")}}function E(){k(!1),j(""),v(""),N("")}return{meshes:u,setMeshes:h,selectedMeshId:d,setSelectedMeshId:m,loading:f,error:w,setError:p,showCreate:y,setShowCreate:k,createName:b,setCreateName:j,createRepoIdentity:S,setCreateRepoIdentity:v,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:N,newMeshDaemonId:C,setNewMeshDaemonId:A,newMeshWorkspace:T,setNewMeshWorkspace:M,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:F,handleCreate:R,handleDelete:Q,cancelCreate:E}}function ZI({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:o,sendCommand:a,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:h,features:d,loadMeshes:m,loadQueue:f,queueSection:x,setError:w}){const[p,y]=l.useState({}),[k,b]=l.useState(null),[j,S]=l.useState(null),[v,g]=l.useState(!1),[N,C]=l.useState(""),[A,T]=l.useState([]),[M,L]=l.useState(""),[P,B]=l.useState(!1),[K,F]=l.useState(""),[R,Q]=l.useState(!1),[E,I]=l.useState(null),[$,D]=l.useState(!1),[U,Y]=l.useState({override:"",append:""}),[ae,z]=l.useState(!1),[X,de]=l.useState({}),[re,W]=l.useState(null),oe=l.useMemo(()=>o.find(ce=>ce.id===M),[o,M]),V=(oe==null?void 0:oe.workspaces)||[],ie=l.useMemo(()=>wn((oe==null?void 0:oe.availableProviders)||[]),[oe]);async function ke(){const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const H=N.trim();if(H)try{const fe={meshId:t,workspace:H};d.addNodeDaemonPicker&&M&&(fe.daemonId=M,fe.machineId=oe==null?void 0:oe.machineId),fe.providerPriority=kn(A);const je=await a(ce,"add_mesh_node",fe),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Add node failed");g(!1),C(""),T([]),L(""),B(!1),await m(),x||await f(t)}catch(fe){w((fe==null?void 0:fe.message)||"Add node failed")}}async function xe(ce){var Ce;if(!e)return;const H=xi(e),fe=((Ce=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Be=>Be.value===H.sessionCleanupOnNodeRemove))==null?void 0:Ce.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
119
+ `})]})}function sI({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const o=l.useRef(new Map),a=l.useRef(r);a.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{o.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const u=c.map(h=>ls.subscribe({sendData:n},h,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${h}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const x=o.current.get(h);o.current.set(h,f),x!==void 0&&f>x&&a.current()}));return()=>{for(const h of u)h()}},[i,t,n])}const nI={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Xp=l.createContext(null);function rI(){const e=l.useContext(Xp);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function oI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function aI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function iI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function lI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",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"})]})}function cI({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function dI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uI({meshes:e,loading:t,error:n,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:h,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:x,newMeshDaemonId:w,onNewMeshDaemonIdChange:p,newMeshWorkspace:y,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:j,onCreate:S,onCancelCreate:v}){const{t:g}=Le("common");return s.jsxs(gr,{icon:s.jsx(es,{}),title:g("repoMesh.list.title"),subtitle:g("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:g("repoMesh.list.createMesh")}),children:[n&&s.jsx(Gt,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:g("repoMesh.list.createTitle")}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.createOnMachine"),hint:g("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:w,onChange:N=>p(N.target.value),disabled:!o.length,children:o.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noConnectedDaemon")}):o.map(N=>s.jsx("option",{value:N.id,children:dI(N)},N.id))})}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.workspace"),hint:g("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:y,onChange:N=>k(N.target.value),disabled:!w||!b.length,children:w?b.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noRegisteredWorkspaces")}):b.map(N=>s.jsx("option",{value:N.path,children:N.label?`${N.label} · ${N.path}`:N.path},N.id||N.path)):s.jsx("option",{value:"",children:g("repoMesh.list.selectMachineFirst")})})}),s.jsx(Ct,{label:g("repoMesh.list.name"),children:s.jsx(is,{value:u,onChange:N=>h(N.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ct,{label:g("repoMesh.list.remoteUrl"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:f,onChange:N=>x(N.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Ct,{label:g("repoMesh.list.repoIdentity"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:d,onChange:N=>m(N.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:S,disabled:!u.trim()||!f.trim()&&!d.trim()||a.createDaemonPicker&&(!w||!y),children:g("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:g("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:g("repoMesh.list.loading")}):e.length===0?s.jsx(Ro,{icon:s.jsx(es,{}),title:g("repoMesh.list.emptyTitle"),description:o.length>0?g("repoMesh.list.emptyWithDaemons"):g("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:c,children:g("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(N=>{var C;return s.jsx("button",{type:"button",onClick:()=>j(N.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(es,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:N.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:N.repoIdentity||N.repo_identity||g("repoMesh.list.noRepoIdentity")}),(N.defaultBranch||N.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(aI,{size:11}),N.defaultBranch||N.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(N.createdAt||N.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((C=N.nodes)==null?void 0:C.length)??N.nodeCount??0," ",g("repoMesh.list.nodesSuffix")]})]})]})},N.id)})})]})}const hI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],pI=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function mI(){return{nodeId:"",provider:"",model:"",n:""}}function Cd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function fI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function bI(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],o=r.provider.trim();if(!o)return{error:{code:"provider_required",slot:n+1}};const a=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let u;if(c){const h=Number(c);if(!Number.isFinite(h)||h<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(h)}t.push({provider:o,...a?{nodeId:a}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function gI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:o}=Le(),{theme:a}=Ls(),i=l.useMemo(()=>Rs(a),[a]),c=l.useMemo(()=>kh(r),[r]),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState({}),[y,k]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>({nodeId:I.nodeId,machineLabel:I.machineLabel,providers:I.providers,providerPriority:I.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>I.nodeId),[e==null?void 0:e.nodes]),S=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(I=>[I.nodeId,I.machineLabel||I.nodeId])),[e==null?void 0:e.nodes]),v=l.useMemo(()=>{const I={};for(const $ of b)I[$.nodeId]=Cd($);return I},[b]),g=l.useMemo(()=>{const I=[...new Set(b.flatMap(Cd).filter(Boolean))];return[...new Set([...I,...hI])].sort()},[b]),N=!!t&&!!n,C=I=>I&&typeof I=="object"&&"result"in I?I.result:I,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),x(null);try{const I=await n(t,"magi_kind_panel_list",{}),$=C(I);if(($==null?void 0:$.success)===!1)throw new Error($.error||o("meshGraph.magiKind.errorLoad"));h($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),p({})}catch(I){x((I==null?void 0:I.message)||o("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,o]);l.useEffect(()=>{A()},[A]);const T=l.useCallback(I=>{if(w[I])return w[I];const $=u[I];return $?$.map(fI):[]},[w,u]),M=(I,$)=>{p(D=>({...D,[I]:$}))},L=(I,$,D)=>{const U=T(I);M(I,U.map((Y,ae)=>ae===$?{...Y,...D}:Y))},P=I=>{M(I,[...T(I),mI()])},B=(I,$)=>{M(I,T(I).filter((D,U)=>U!==$))},K=l.useCallback(async I=>{if(!t||!n)return;const $=bI(T(I));if("error"in $){const D=$.error,U=D.code==="provider_required"?o("meshGraph.magiKind.errorSlotProvider",{slot:D.slot}):D.code==="replica_min"?o("meshGraph.magiKind.errorSlotReplica",{slot:D.slot}):o("meshGraph.magiKind.errorNoSlot");x(`${I}: ${U}`);return}k(I),x(null);try{const D=await n(t,"magi_kind_panel_set",{kind:I,slots:$.slots}),U=C(D);if((U==null?void 0:U.success)===!1)throw new Error(U.error||o("meshGraph.magiKind.errorSave"));await A()}catch(D){x((D==null?void 0:D.message)||o("meshGraph.magiKind.errorSave"))}finally{k(null)}},[t,n,T,A,o]),F=l.useCallback(async I=>{if(!(!t||!n)&&confirm(o("meshGraph.magiKind.removeConfirm",{kind:I}))){k(I),x(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:I}),D=C($);if((D==null?void 0:D.success)===!1)throw new Error(D.error||o("meshGraph.magiKind.errorRemove"));await A()}catch($){x(($==null?void 0:$.message)||o("meshGraph.magiKind.errorRemove"))}finally{k(null)}}},[t,n,A,o]),R=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,Q="btn btn-primary btn-sm",E="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:o("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:E,onClick:()=>void A(),disabled:d||!N,children:o(d?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:o("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:pI.map(({kind:I,labelKey:$,hint:D})=>{const U=T(I),Y=!!u[I],ae=y===I;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:o($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:D}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?o("meshGraph.magiKind.agentCount",{count:u[I].length}):o("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[U.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:o("meshGraph.magiKind.noAgents")}),U.map((z,X)=>{const de=z.nodeId?v[z.nodeId]??[]:[],re=z.nodeId&&de.length?de:g;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.machine")}),s.jsxs("select",{className:R,value:z.nodeId,onChange:W=>L(I,X,{nodeId:W.target.value}),title:o("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.anyMachine")}),j.map(W=>s.jsx("option",{value:W,children:S[W]??W},W)),z.nodeId&&!j.includes(z.nodeId)&&s.jsx("option",{value:z.nodeId,children:o("meshGraph.magiKind.offlineSuffix",{label:S[z.nodeId]??z.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[o("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:R,value:z.provider,onChange:W=>L(I,X,{provider:W.target.value}),title:o("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.selectProvider")}),re.map(W=>s.jsx("option",{value:W,children:W},W)),z.provider&&!re.includes(z.provider)&&s.jsx("option",{value:z.provider,children:z.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.model")}),(()=>{var V;const W=(z.provider?(V=c.get(z.provider))==null?void 0:V.models:void 0)??[],oe=!!z.model&&W.length>0&&!W.includes(z.model);return W.length>0&&!oe?s.jsxs("select",{className:R,value:W.includes(z.model)?z.model:"",title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value==="__custom__"?" ":ie.target.value}),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.modelDefault")}),W.map(ie=>s.jsx("option",{value:ie,children:ie},ie)),s.jsx("option",{value:"__custom__",children:o("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:R,value:z.model.trim(),placeholder:o("meshGraph.magiKind.modelDefault"),title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value})}),W.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>L(I,X,{model:""}),children:o("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${R} sm:w-16`,value:z.n,placeholder:"1",inputMode:"numeric",title:o("meshGraph.magiKind.copiesTitle"),onChange:W=>L(I,X,{n:W.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>B(I,X),"aria-label":o("meshGraph.magiKind.removeAgent"),title:o("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>P(I),disabled:!N,children:o("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:Q,onClick:()=>void K(I),disabled:ae||!N,children:o(ae?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void F(I),disabled:ae||!N||!Y,title:o(Y?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:o("meshGraph.magiKind.removeBinding")})]})]},I)})})]})}function xI({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:o}=Le(),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(null),p=l.useCallback(async()=>{if(!e||!t){d(o("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const k=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||o("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),w(typeof b.bytes=="number"?b.bytes:null)}catch(k){d((k==null?void 0:k.message)||String(k))}finally{u(!1)}},[e,t,n,r,o]),y=l.useCallback(()=>{const k=!a;i(k),k&&m===null&&!c&&p()},[a,m,c,p]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:y,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(a?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),h&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[h,s.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!c&&!h&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:o("repoMesh.promptPreview.info")}),x!==null&&s.jsxs("span",{children:[(x/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:k=>k.currentTarget.select()})]})]})]})}const yI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function vI(e){const t=yI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function wI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function kI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const SI=["active","paused","completed","abandoned"];function jd(e){return(e.status||"active").toLowerCase()}const CI=8;function jI({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:o}=Le("common"),a=l.useMemo(()=>wI(e),[e]),[i,c]=l.useState({}),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("active"),[y,k]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of a){const M=jd(T);A[M]=(A[M]||0)+1}return A},[a]),j=l.useMemo(()=>w==="all"?a:a.filter(A=>jd(A)===w),[a,w]),S=y?j:j.slice(0,CI),v=j.length-S.length,g=!!t&&a.length>0,N=l.useCallback(async()=>{if(t){m(!0),x(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),T=vI(A),M=Array.isArray(T==null?void 0:T.missions)?T.missions:[],L={};for(const P of M)P.id&&typeof P.goal=="string"&&P.goal&&(L[P.id]=P.goal);c(P=>({...P,...L}))}catch(A){x(A instanceof Error?A.message:o("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,o]),C=l.useCallback(A=>{h(T=>({...T,[A]:!T[A]})),!u[A]&&!i[A]&&N()},[u,i,N]);return a.length===0?null:s.jsxs(bt,{title:o("repoMesh.missions.title"),description:o("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[SI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{p(A),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${w===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{p("all"),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${w==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",a.length]})]}),j.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.missions.empty",{status:w})}),s.jsx("div",{className:"flex flex-col gap-2",children:S.map(A=>{var F;const T=u[A.id]===!0,M=i[A.id],L=kI(A),P=T&&M?M:L.text,B=T&&!M&&L.truncated,K=((F=A.tasks)==null?void 0:F.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),K>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:o("repoMesh.missions.taskCount",{count:K})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,B&&s.jsx("span",{className:"text-text-muted",children:o("repoMesh.missions.goalUnavailable")})]}),(L.truncated||M)&&g&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>C(A.id),disabled:d,children:o(T?"repoMesh.missions.showLess":d&&!M?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>k(!0),children:o("repoMesh.missions.showMore",{count:v})})]})}const NI=["","low","medium","high"],AI={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Nd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Ad(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function TI(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const _s="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function II({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:o}=Le("common"),[a,i]=l.useState(()=>e.map(Nd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Nd))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),h=l.useMemo(()=>kh(t),[t]),d=l.useMemo(()=>{const b=a.map(Ad).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[a,e]),m=(b,j)=>i(S=>S.map((v,g)=>g===b?{...v,...j}:v)),f=(b,j)=>i(S=>S.map((v,g)=>{var A;if(g!==b)return v;const N=((A=h.get(j))==null?void 0:A.models)??[],C=!v.model||N.length===0||N.includes(v.model);return{...v,provider:j,...C?{}:{model:""}}})),x=b=>i(j=>j.filter((S,v)=>v!==b)),w=()=>i(b=>[...b,TI()]),p=(b,j)=>i(S=>{const v=b+j;if(v<0||v>=S.length)return S;const g=[...S];return[g[b],g[v]]=[g[v],g[b]],g}),y=(b,j)=>i(S=>S.map((v,g)=>{if(g!==b)return v;const N=v.difficulty.includes(j);return{...v,difficulty:N?v.difficulty.filter(C=>C!==j):[...v.difficulty,j]}})),k=()=>r(a.map(Ad).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.slotEditor.empty")}),a.map((b,j)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",j+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===0,onClick:()=>p(j,-1),title:o("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:j===a.length-1,onClick:()=>p(j,1),title:o("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>x(j),"aria-label":o("repoMesh.slotEditor.removeSlot"),children:s.jsx(At,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.provider")}),u.length>0?s.jsxs("select",{className:_s,value:b.provider,onChange:S=>f(j,S.target.value),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.select")}),u.map(S=>s.jsx("option",{value:S,children:S},S)),b.provider&&!u.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:_s,value:b.provider,placeholder:"claude-cli",onChange:S=>m(j,{provider:S.target.value})})]}),(()=>{var C;const S=h.get(b.provider),v=(S==null?void 0:S.models)??[],g=(C=S==null?void 0:S.thinking)!=null&&C.length?["",...S.thinking]:NI,N=!!b.model&&v.length>0&&!v.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.model")}),v.length>0&&!N?s.jsxs("select",{className:_s,value:v.includes(b.model)?b.model:"",onChange:A=>m(j,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:o("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:_s,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:o("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(j,{model:A.target.value})}),v.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(j,{model:""}),children:o("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:_s,value:b.thinkingLevel,onChange:A=>m(j,{thinkingLevel:A.target.value}),children:g.map(A=>s.jsx("option",{value:A,children:A||o("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:ky.map(S=>{const v=b.difficulty.includes(S);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>y(j,S),children:AI[S]},S)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:_s,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:S=>m(j,{capability:S.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:_s,value:b.maxParallel,placeholder:o("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:S=>m(j,{maxParallel:S.target.value})})]})]})]},j)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:w,children:[s.jsx(Mi,{size:13})," ",o("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!n||!d,children:o(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function MI(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function DI(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function PI(e){var u,h,d;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const o=(((u=t.userOverrides)==null?void 0:u.platform)||t.reportedPlatform||"").toString().trim(),a=(((h=t.userOverrides)==null?void 0:h.arch)||t.reportedArch||"").toString().trim();o&&n.push({tag:`os=${o}`,custom:!1}),a&&n.push({tag:`arch=${a}`,custom:!1});const i=Array.isArray((d=t.policy)==null?void 0:d.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&n.push({tag:`worktree=${c}`,custom:!1}),n}function LI(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const RI=["os=","arch=","provider=","worktree=","converge="];function EI({node:e,saving:t,onSave:n}){const{t:r}=Le("common"),o=l.useMemo(()=>PI(e).filter(p=>!p.custom),[e]),a=l.useMemo(()=>LI(e),[e]),[i,c]=l.useState(a),[u,h]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(a),f=(p=>{const y=p.trim();return y?/\s/.test(y)?r("repoMesh.tagEditor.noSpaces"):RI.some(k=>y.toLowerCase().startsWith(k))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(y)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function x(){const p=u.trim();!p||f||(c(y=>[...y,p]),h(""))}function w(p){c(y=>y.filter(k=>k!==p))}return s.jsxs("div",{className:"mt-2",onClick:p=>p.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),o.map(p=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:p.tag},p.tag)),i.map(p=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[p,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>w(p),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:p}),children:"×"})]},p))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:p=>h(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),x())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:x,disabled:t||!u.trim()||!!f,children:r("repoMesh.tagEditor.add")}),d&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&o.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function _I(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function $I(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function BI(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function FI(e){const t=BI(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function HI(e){return e.isLocalWorktree===!0}function WI(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(o=>{var a;return((a=o==null?void 0:o.settings)==null?void 0:a.meshNodeId)===e.id||(o==null?void 0:o.workspace)===e.workspace}).map(o=>{var a;return{id:o.sessionId||o.id||o.instanceId||"unknown",provider:o.providerType||o.cliType||o.acpType||o.type||"unknown",status:o.status||((a=o.activeChat)==null?void 0:a.status)||"unknown"}})}function Td(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function OI(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function UI({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:o,userName:a,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:h,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:x,onNodeSystemPromptDraftChange:w,savingNodeSystemPromptId:p,onSaveNodeSystemPrompt:y,selectedNodeId:k,onSelectNode:b,showAddNode:j,onShowAddNode:S,onCancelAddNode:v,nodeWorkspace:g,onNodeWorkspaceChange:N,nodeProviderPriority:C,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:M,nodeCustomPath:L,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:K,attachableDaemons:F,onAddNode:R,onRemoveNode:Q}){const{t:E}=Le("common"),I=l.useMemo(()=>MI(r),[r]),$=l.useMemo(()=>e.filter(D=>!HI(D)),[e]);return s.jsxs(bt,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:F.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(D=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${D.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{M(D.id),N(""),P(!1),A(cr(wn(D.availableProviders||[]))),S()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Td(D)}),D.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:D.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(D.workspaces||[]).length})})]},D.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:S,children:[s.jsx(lI,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),j&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(At,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Ct,{label:E("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:D=>{var U;M(D.target.value),N(""),P(!1),A(cr(wn(((U=r.find(Y=>Y.id===D.target.value))==null?void 0:U.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(D=>s.jsx("option",{value:D.id,children:Td(D)},D.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Ct,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!L&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(D=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===D.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>N(D.path),children:[s.jsx("span",{className:"font-medium block truncate",children:D.label||D.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:D.path})]},D.id||D.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),N("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:D=>N(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&R()}}),B.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),N("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const D=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],U=`mesh-add-node-workspaces-${o||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:ae=>N(ae.target.value),placeholder:((Y=D[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:D.length>0?U:void 0,autoFocus:!0}),D.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:U,children:D.map(ae=>s.jsx("option",{value:ae.path,children:ae.label||ae.path},ae.id||ae.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:D.slice(0,6).map(ae=>s.jsx("button",{type:"button",onClick:()=>N(ae.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ae.path,children:ae.label||ae.path.split("/").filter(Boolean).pop()||ae.path},ae.id||ae.path))})]})]})})()})}),s.jsx(Ct,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(mk,{value:C,availableProviders:i.addNodeDaemonPicker?K:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:R,disabled:!g.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"btn btn-secondary btn-sm",children:E("repoMesh.nodeList.cancel")})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(Ro,{icon:s.jsx(xn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(D=>{var de;const U=FI(D),Y=_I(D,t),ae=WI(D,n),z=k===D.id,X=D.status||D.machine_status||(Y.length>0||ae.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(z?null:D.id),onKeyDown:i.addNodeDaemonPicker?void 0:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),b(z?null:D.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:D.machine_label||D.machine_nickname||D.hostname||D.workspace}):s.jsx("span",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(cI,{status:X}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:OI(r.find(re=>re.id===String(D.daemon_id||"")),a),machine:D.machine_label||D.daemon_id||D.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx(EI,{node:D,saving:m===D.id,onSave:re=>f(D,re)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:re=>re.stopPropagation(),children:[s.jsx(Ct,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(II,{slots:Array.isArray((de=D.policy)==null?void 0:de.slots)?D.policy.slots:[],availableProviders:DI(D,I),saving:h===D.id,onSave:re=>d(D,re)})}),i.nodeInstruction&&s.jsxs(Ct,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:x[D.id]??"",onChange:re=>{const W=re.target.value;w(D.id,W)},onClick:re=>re.stopPropagation(),disabled:p===D.id,placeholder:E("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:re=>{re.stopPropagation(),y(D)},disabled:p===D.id,children:p===D.id?E("repoMesh.nodeList.saving"):E("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:re=>{re.stopPropagation(),Q(D.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(iI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:re=>re.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",E("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:U.configured?"text-green-400":"text-amber-400",children:U.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",ae.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(D.created_at||D.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Y.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(re=>s.jsx("li",{className:"font-mono",children:$I(re)},re.id))})]}),ae.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:ae.map(re=>s.jsxs("li",{className:"font-mono",children:[re.provider," / ",re.status," / ",re.id]},re.id))})]})]})]})]},D.id)})})]})}function Hr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GI({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:o,launchingCoordinator:a,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:h,hostLabel:d,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:x,onLaunchCoordinator:w}){const{t:p}=Le("common"),y=s.jsx(Ct,{label:p("repoMesh.host.coordinatorProvider"),hint:p("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:r,onChange:j=>o(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),k=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(h)return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:p("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||p("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",p(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[p("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Gt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:p("repoMesh.host.hostOffline")})," ",p("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Ct,{label:p("repoMesh.host.reconnectToCommand"),hint:p("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:f,onChange:j=>x(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.waitForHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:p("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:a||!t,title:t?void 0:p("repoMesh.host.noCommandTarget"),children:p(a?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),k]});const b=e.find(j=>j.id===t);return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("repoMesh.host.descriptionUnset"),children:[s.jsxs(Gt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:p("repoMesh.host.setHostBanner")})," ",p("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Hr(b)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Hr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Ct,{label:p("repoMesh.host.hostDaemon"),hint:p("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:j=>n(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.resolvingHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!t||!c||a,title:t?c?void 0:p("repoMesh.host.attachNodeFirst"):p("repoMesh.host.pickHostFirst"),children:p(a?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:p("repoMesh.host.noDaemonsToHost")}),k]})}function KI({meshId:e,availableCliAgents:t}){const{t:n}=Le(),r=t.find(a=>{const i=a.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||a.name.toLowerCase().includes("hermes")}),o=Kh(r==null?void 0:r.meshCoordinator,{meshId:e});return o?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(fp,{setup:o,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const _a=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],zI=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function qI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function VI(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const YI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function xi(e){return{...YI,...(e==null?void 0:e.policy)||{}}}function JI(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function QI({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:o,displayedMeshStatus:a,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:h,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:x,onSaveCoordinatorPrompt:w,daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:L,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:K,meshQueue:F,userName:R,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_,availableCliAgents:te,features:ve,sendCommand:ce}){var Fe;const{t:H}=Le("common"),fe=xi(e),je=e.nodes||[],Ce=je.some(Ie=>{var Oe;const ye=Number((Oe=Ie.policy)==null?void 0:Oe.schedulingPriority);return Number.isFinite(ye)&&ye!==0}),Be=!fe.schedulingStrategy,Xe=l.useMemo(()=>je.some(Ie=>{var ye;return Array.isArray((ye=Ie.policy)==null?void 0:ye.slots)&&Ie.policy.slots.length>0}),[je]),dt=Be?Xe?"smart":je.length>=2?"spread":null:null,[it,he]=l.useState(!1),$e=!!K&&!!e.id;return s.jsxs(gr,{icon:s.jsx(es,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:H("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(oI,{size:13}),H(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:H("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Gt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),ve.meshHostDaemonSection&&s.jsx(GI,{daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:Ie=>{L(Ie),u()},onLaunchCoordinator:P}),s.jsxs(bt,{title:H("repoMesh.detail.observabilityTitle"),description:H("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>he(!0),disabled:!$e,title:H($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),H("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:H("repoMesh.detail.observabilityHint")})]})]}),s.jsx(UI,{nodes:je,meshQueue:F,activeDaemon:B,daemons:p,selectedMeshId:e.id,userName:R,features:{addNodeDaemonPicker:ve.addNodeDaemonPicker,nodeInstruction:ve.nodeInstruction},coordinatorDaemonId:y,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_}),s.jsxs(bt,{title:H("repoMesh.detail.schedulingTitle"),description:H("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:H("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:zI.map(Ie=>{const Oe=VI(fe.schedulingStrategy,{priorityConfigured:Ce})===Ie.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Oe?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:Ie.value,checked:Oe,disabled:h,onChange:()=>d({schedulingStrategy:qI(Ie.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Ie.label,dt===Ie.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:H("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Ie.description})]})]},Ie.value)})})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),s.jsx(bt,{title:H("repoMesh.detail.visibilityTitle"),description:H("repoMesh.detail.visibilityDescription"),children:s.jsx(Ct,{label:H("repoMesh.detail.visibilityLabel"),hint:H("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Ie=>d({spawnedSessionVisibility:Ie.target.value==="visible"?"visible":"hidden"}),disabled:h,children:[s.jsx("option",{value:"hidden",children:H("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:H("repoMesh.detail.visibilityVisible")})]})})}),a&&s.jsx(bt,{title:H("repoMesh.detail.magiTitle"),description:H("repoMesh.detail.magiDescription"),children:s.jsx(gI,{status:a,daemonId:K,sendDaemonCommand:ce,availableProviders:Q})}),s.jsx(jI,{status:a,daemonId:K,meshId:e.id,sendCommand:ce}),ve.coordinatorPrompt&&s.jsxs(bt,{title:H("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.coordinatorPromptDescription"),children:[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-1",children:H("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Ct,{label:H("repoMesh.detail.overrideLabel"),hint:H("repoMesh.detail.overrideHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:Ie=>f({...m,override:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.overridePlaceholder")}),s.jsx(xI,{daemonId:K,meshId:e.id,cliType:b,sendCommand:ce})]}),s.jsx(Ct,{label:H("repoMesh.detail.appendLabel"),hint:H("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:Ie=>f({...m,append:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:H("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:w,disabled:x,children:H(x?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:x,title:H("repoMesh.detail.clearTitle"),children:H("repoMesh.detail.clear")})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:H("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.userLevelDescription")}),s.jsx(Uk,{daemonId:K||void 0})]})]}),s.jsxs(bt,{title:H("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:H("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",H("repoMesh.detail.requireApprovalBeforePush")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",H("repoMesh.detail.requireApproval")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",H("repoMesh.detail.warnAndContinue")],["block",H("repoMesh.detail.blockTask")],["checkpoint_then_continue",H("repoMesh.detail.checkpointThenContinue")]],val:Ie=>Ie||"warn",parse:Ie=>Ie},{label:H("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",H("repoMesh.detail.requireExplicitApproval")],["enabled",H("repoMesh.detail.allowRefineryPublish")]],val:Ie=>Ie?"enabled":"disabled",parse:Ie=>Ie==="enabled"}].map(({label:Ie,key:ye,opts:Oe,val:ut,parse:at})=>s.jsx(Ct,{label:Ie,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut(fe[ye]),onChange:ht=>d({[ye]:at(ht.target.value)}),disabled:h,children:Oe.map(([ht,J])=>s.jsx("option",{value:ht,children:J},ht))})},ye))}),(()=>{const Ie=fe.autoFastForward&&typeof fe.autoFastForward=="object"?fe.autoFastForward:{},ye=Ie.enabled!==!1,Oe=Ie.remoteNodes===!0,ut=Ie.mode==="continuous"?"continuous":"idle",at=ht=>d({autoFastForward:{...Ie,...ht}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Ct,{label:H("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ye?"enabled":"disabled",onChange:ht=>at({enabled:ht.target.value==="enabled"}),disabled:h,children:[s.jsx("option",{value:"enabled",children:H("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:H("repoMesh.detail.ffDisabled")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.includeRemoteNodes"),hint:H("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Oe?"yes":"no",onChange:ht=>at({remoteNodes:ht.target.value==="yes"}),disabled:h||!ye,children:[s.jsx("option",{value:"no",children:H("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:H("repoMesh.detail.remoteYes")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.detectionMode"),hint:H("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut,onChange:ht=>at({mode:ht.target.value==="continuous"?"continuous":"idle"}),disabled:h||!ye||!Oe,children:[s.jsx("option",{value:"idle",children:H("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:H("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(Ct,{label:H("repoMesh.detail.sessionCleanupLabel"),hint:H("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:fe.sessionCleanupOnNodeRemove||"preserve",onChange:Ie=>d({sessionCleanupOnNodeRemove:Ie.target.value}),disabled:h,children:_a.map(Ie=>s.jsx("option",{value:Ie.value,children:Ie.label},Ie.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Fe=_a.find(Ie=>Ie.value===fe.sessionCleanupOnNodeRemove))==null?void 0:Fe.description)||_a[0].description})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),ve.hermesMcpConfig&&s.jsx(KI,{meshId:e.id,availableCliAgents:te}),ve.meshHostDaemonSection&&s.jsxs(Gt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]}),it&&$e&&s.jsx(qp,{activeConv:JI({meshId:e.id,daemonId:K,meshName:e.name}),sendDaemonCommand:ce,onClose:()=>he(!1)})]})}const Un=new Map;function XI({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i}){const c=e.map(I=>I.id).filter(Boolean).sort().join(","),[u,h]=l.useState(()=>Un.get(c)??[]),[d,m]=l.useState(null),[f,x]=l.useState(()=>!Un.has(c)),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),L=l.useMemo(()=>e.find(I=>I.id===C),[e,C]),P=(L==null?void 0:L.workspaces)||[],B=l.useMemo(()=>wn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!a.createDaemonPicker||!i||!C||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(C,{minFreshMs:3e4})).catch(()=>{})},[a.createDaemonPicker,i,C,L]);const K=l.useMemo(()=>e.map(I=>I.id).filter(Boolean).sort().join(","),[e]),F=l.useCallback(async(I=!1)=>{const $=I||Un.has(K);x(D=>$?D:!0);try{if(a.createDaemonPicker){const D=await Promise.allSettled(e.map(async ae=>{if(!ae.id)return[];const z=await n(ae.id,"list_meshes",{}),X=r(z);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");return(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(de=>o(de,ae.id)).filter(de=>de.id)})),U=new Map;for(const ae of D)if(ae.status==="fulfilled")for(const z of ae.value)U.has(z.id)||U.set(z.id,z);const Y=Array.from(U.values());h(Y),Un.set(K,Y),p(null)}else{if(!t)return;const D=await n(t,"list_meshes");if(D!=null&&D.success){const U=(D.meshes||[]).map(Y=>o(Y,t));h(U),Un.set(K,U),p(null)}else p((D==null?void 0:D.error)||"Failed to load meshes")}}catch(D){p((D==null?void 0:D.message)||"Failed to load meshes")}finally{x(!1)}},[K,t,n,r,o,a.createDaemonPicker]);async function R(){var U,Y;const I=a.createDaemonPicker?C:t;if(!I||!b.trim())return;const $=g.trim(),D=S.trim();if(!(!$&&!D))try{const ae={name:b.trim()};$&&(ae.repoRemoteUrl=$),D&&(ae.repoIdentity=D);const z=await n(I,"create_mesh",ae),X=r(z);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Create failed");const de=typeof((U=X==null?void 0:X.mesh)==null?void 0:U.id)=="string"?X.mesh.id:"";if(de&&a.createDaemonPicker&&T){const re=await n(I,"add_mesh_node",{meshId:de,daemonId:I,machineId:L==null?void 0:L.machineId,workspace:T,role:"host",providerPriority:cr(B)}),W=r(re);if((W==null?void 0:W.success)===!1)throw new Error(W.error||"Mesh created but failed to attach workspace")}k(!1),j(""),v(""),N(""),M(""),await F(),(Y=X==null?void 0:X.mesh)!=null&&Y.id&&m(X.mesh.id)}catch(ae){p((ae==null?void 0:ae.message)||"Create failed")}}async function Q(I){var D;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((D=u.find(U=>U.id===I))==null?void 0:D.__sourceDaemonId)||t;try{const U=await n($,"delete_mesh",{meshId:I}),Y=r(U);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");d===I&&m(null),await F()}catch(U){p((U==null?void 0:U.message)||"Delete failed")}}function E(){k(!1),j(""),v(""),N("")}return{meshes:u,setMeshes:h,selectedMeshId:d,setSelectedMeshId:m,loading:f,error:w,setError:p,showCreate:y,setShowCreate:k,createName:b,setCreateName:j,createRepoIdentity:S,setCreateRepoIdentity:v,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:N,newMeshDaemonId:C,setNewMeshDaemonId:A,newMeshWorkspace:T,setNewMeshWorkspace:M,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:F,handleCreate:R,handleDelete:Q,cancelCreate:E}}function ZI({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:o,sendCommand:a,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:h,features:d,loadMeshes:m,loadQueue:f,queueSection:x,setError:w}){const[p,y]=l.useState({}),[k,b]=l.useState(null),[j,S]=l.useState(null),[v,g]=l.useState(!1),[N,C]=l.useState(""),[A,T]=l.useState([]),[M,L]=l.useState(""),[P,B]=l.useState(!1),[K,F]=l.useState(""),[R,Q]=l.useState(!1),[E,I]=l.useState(null),[$,D]=l.useState(!1),[U,Y]=l.useState({override:"",append:""}),[ae,z]=l.useState(!1),[X,de]=l.useState({}),[re,W]=l.useState(null),oe=l.useMemo(()=>o.find(ce=>ce.id===M),[o,M]),V=(oe==null?void 0:oe.workspaces)||[],ie=l.useMemo(()=>wn((oe==null?void 0:oe.availableProviders)||[]),[oe]);async function ke(){const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const H=N.trim();if(H)try{const fe={meshId:t,workspace:H};d.addNodeDaemonPicker&&M&&(fe.daemonId=M,fe.machineId=oe==null?void 0:oe.machineId),fe.providerPriority=kn(A);const je=await a(ce,"add_mesh_node",fe),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Add node failed");g(!1),C(""),T([]),L(""),B(!1),await m(),x||await f(t)}catch(fe){w((fe==null?void 0:fe.message)||"Add node failed")}}async function xe(ce){var Ce;if(!e)return;const H=xi(e),fe=((Ce=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(Be=>Be.value===H.sessionCleanupOnNodeRemove))==null?void 0:Ce.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
- Node removal cleanup policy: ${fe}`))return;const je=e.__sourceDaemonId||n;try{const Be=await a(je,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");j===ce&&S(null),await m(),x||await f(t)}catch(Be){w((Be==null?void 0:Be.message)||"Remove node failed")}}async function Se(ce){if(!e)return;const H={...xi(e),...ce},fe=e.__sourceDaemonId||n;try{D(!0),w(null);const je=await a(fe,"update_mesh",{meshId:e.id,policy:H}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Policy update failed");await m()}catch(je){w((je==null?void 0:je.message)||"Policy update failed")}finally{D(!1)}}async function pe(ce){if(!t)return;const H=(e==null?void 0:e.__sourceDaemonId)||n,fe=p[ce.id]||eM(ce),je=kn(fe),Ce={...ce.policy||{}};delete Ce.provider_priority,je.length?Ce.providerPriority=je:delete Ce.providerPriority;try{b(ce.id),w(null);const Be=await a(H,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:Ce,providerPriority:je}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1){w(Xe.error||"Node policy update failed");return}await m()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{b(null)}}const[G,O]=l.useState(null);async function Z(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n;try{O(ce.id),w(null);const je=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:H}}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1){w(Ce.error||"Node slots update failed");return}await m()}catch(je){w((je==null?void 0:je.message)||"Node slots update failed")}finally{O(null)}}const[q,me]=l.useState(null);async function Te(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n,je=H.map(Ce=>Ce.trim()).filter(Boolean);try{me(ce.id),w(null);const Ce=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:je}),Be=i(Ce);if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node tag update failed");return}await m()}catch(Ce){w((Ce==null?void 0:Ce.message)||"Node tag update failed")}finally{me(null)}}async function _(){if(!n||!t)return;const H={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?H.systemPromptOverride=U.override:delete H.systemPromptOverride,U.append.trim()?H.systemPromptAppend=U.append:delete H.systemPromptAppend,delete H.systemPromptSuffix;try{z(!0),w(null);const fe=await a(n,"update_mesh",{meshId:t,coordinator:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Coordinator prompt save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Coordinator prompt save failed")}finally{z(!1)}}async function se(ce){if(!n||!t)return;const H=(X[ce.id]||"").trim();try{W(ce.id),w(null);const fe=await a(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Node instruction save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Node instruction save failed")}finally{W(null)}}async function ve(){if(e){w(null),I(null);try{Q(!0);const ce=c?await c(r,e.id,e):null,H=u(r,e.id,e,e.nodes||[],ce);if("error"in H)throw new Error(H.error);const fe=await h(H.targetDaemonId,{meshId:e.id,inlineMesh:H.inlineMesh,coordinatorNodeId:H.coordinatorNodeId,cliType:K.trim()||void 0});I(fe.message)}catch(ce){w((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{Q(!1)}}}return{nodeProviderPriorityDrafts:p,setNodeProviderPriorityDrafts:y,savingNodePolicyId:k,selectedNodeId:j,setSelectedNodeId:S,showAddNode:v,setShowAddNode:g,nodeWorkspace:N,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:M,setNodeDaemonId:L,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:V,nodePickerProviders:ie,coordinatorCliType:K,setCoordinatorCliType:F,launchingCoordinator:R,launchResult:E,savingPolicy:$,coordinatorPromptDraft:U,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:re,savingNodeSlotsId:G,savingNodeCapabilitiesId:q,handleAddNode:ke,handleRemoveNode:xe,handleUpdatePolicy:Se,handleUpdateNodeProviderPriority:pe,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:_,handleSaveNodeSystemPrompt:se,handleLaunchCoordinator:ve}}function eM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function tM(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function sM({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:o,resolveCommandTarget:a}){const[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),w=l.useCallback(async y=>{if(!e||!y){c([]);return}try{const k=await n(e,"get_mesh_queue",{meshId:y});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,n]);async function p(y){var k,b;if(y){m(!0),x(null);try{const j=o?await o(t,y.id,y):null,S=a(t,y.id,y,y.nodes||[],j);if("error"in S)throw new Error(S.error);const v=await n(S.targetDaemonId,"get_mesh_queue",{meshId:y.id}),g=r(v);if((g==null?void 0:g.success)===!1)throw new Error(g.error||"Queue load failed");const N=Array.isArray(((k=g==null?void 0:g.result)==null?void 0:k.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue))?((b=g==null?void 0:g.result)==null?void 0:b.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue):[];h(tM(N))}catch(j){x((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:w,handleLoadQueue:p}}function nM(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Zp=new Map;function em(e){return e?Zp.get(e)??null:null}function rM(e,t){!e||!t||Zp.set(e,t)}function oM({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:o}){const[a,i]=l.useState(()=>em(e)),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState("idle"),[x,w]=l.useState(!1),p=l.useRef(!1);async function y(k,b=e,j=!1){if(!(!k||!b))try{u(!j&&a===null),f(j?"settling":"first_paint"),d(null);const S=await t(k,b,{refresh:j,retryProfile:j?"settled":"interactive"});w(nM(S));const v=n(S),g=r&&v?{...v,nodes:(v.nodes??[]).map(N=>r(N,v.meshId??b,""))}:v;if(g){if(o&&!j&&a!==null&&!Cj(Mp(g))){f("settling"),p.current||(p.current=!0,Promise.resolve().then(()=>y(k,b,!0)).finally(()=>{p.current=!1}));return}i(g),rM(b,g),f("settled")}else i(null),d("mesh_status returned an unexpected payload."),f("idle")}catch(S){a||i(null),d((S==null?void 0:S.message)||"Failed to load mesh graph"),f("idle")}finally{u(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:i,graphLoading:c,graphError:h,setGraphError:d,graphProvenance:m,graphBootstrapFallback:x,loadGraph:y}}function aM(e,t,n,r,o){if(!e.length)return"";const a=String(o||"");if(a){const u=e.find(h=>Ws(h.id,a));return u?u.id:a}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(h=>Ws(h.id,c));if(u)return u.id}return""}const iM=7e3,lM=45e3;function cM(){const e=rI(),{sendCommand:t,sendData:n,daemons:r,userName:o,loadMeshStatus:a,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:h,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:f,features:x,gateIncompleteGraph:w}=e,p=In(),y=r[0],k=(y==null?void 0:y.id)||"",b=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[y]),j=l.useMemo(()=>wn((y==null?void 0:y.availableProviders)||[]),[y]),{meshes:S,selectedMeshId:v,setSelectedMeshId:g,loading:N,error:C,setError:A,showCreate:T,setShowCreate:M,createName:L,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:K,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:R,newMeshDaemonId:Q,setNewMeshDaemonId:E,newMeshWorkspace:I,setNewMeshWorkspace:$,createPickerWorkspaces:D,loadMeshes:U,handleCreate:Y,handleDelete:ae,cancelCreate:z}=XI({daemons:r,primaryDaemonId:k,sendCommand:t,unwrapResult:h,normalizeMesh:d,features:x,loadDaemonMetadata:p}),X=S.find(Re=>Re.id===v)||null,{meshGraphStatus:de,setMeshGraphStatus:re,graphLoading:W,graphError:oe,setGraphError:V,loadGraph:ie}=oM({selectedMeshId:v,loadMeshStatus:a,extractStatus:u,normalizeNode:m,gateIncompleteGraph:w}),[ke,xe]=l.useState(""),[Se,pe]=l.useState(""),G=x.meshHostDaemonSection&&ke||k,{meshQueue:O,loadQueue:Z}=sM({primaryDaemonId:k,activeDaemonId:G,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:q,selectedNodeId:me,setSelectedNodeId:Te,showAddNode:_,setShowAddNode:se,nodeWorkspace:ve,setNodeWorkspace:ce,nodeProviderPriority:H,setNodeProviderPriority:fe,nodeDaemonId:je,setNodeDaemonId:Ce,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Fe,launchResult:Ie,savingPolicy:ye,coordinatorPromptDraft:Oe,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:at,nodeSystemPromptDrafts:ht,setNodeSystemPromptDrafts:J,savingNodeSystemPromptId:te,savingNodeSlotsId:le,savingNodeCapabilitiesId:ue,handleAddNode:ge,handleRemoveNode:Ae,handleUpdatePolicy:Pe,handleUpdateNodeSlots:Ne,handleUpdateNodeCapabilities:He,handleSaveCoordinatorPrompt:Ue,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=ZI({selectedMesh:X,selectedMeshId:v,primaryDaemonId:k,activeDaemonId:G,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:x.addNodeDaemonPicker},loadMeshes:U,loadQueue:Z,queueSection:x.queueSection,setError:A}),Ge=l.useMemo(()=>r.find(Re=>Re.id===G)||y,[r,G,y]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),ee=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),be=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>be.find(Re=>Ws(String(Re.daemon_id||Re.daemonId||""),ke)),[be,ke]),ze=x.meshHostDaemonSection?!!we:!0,We=l.useMemo(()=>{if(!x.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=X.meshHost,rt=de!=null&&de.meshId&&String(de.meshId)===String(X.id??"")?de.meshHost:void 0,jt=rt!=null&&rt.hostDaemonId?rt:Re??rt,Ot=String((jt==null?void 0:jt.hostDaemonId)||""),ne=be.find(ys=>ys.role==="host"),Ke=String((jt==null?void 0:jt.hostNodeId)||(ne==null?void 0:ne.id)||""),Ee=Ke?be.find(ys=>String(ys.id)===Ke):void 0,vt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Ot||vt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Mn=r.find(ys=>Ot&&Ws(ys.id,Ot))||(vt?r.find(ys=>Ws(ys.id,vt)):void 0);if(Mn)return{pinned:!0,daemonId:Mn.id,label:dM(Mn),online:!0};const Oo=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Oo,online:!1}},[X,be,r,de,x.meshHostDaemonSection]),tt=We.daemonId,qe=We.online,Ye=l.useMemo(()=>!x.meshHostDaemonSection||!We.pinned?"":!qe&&Se&&r.some(Re=>Re.id===Se)?Se:tt,[x.meshHostDaemonSection,We.pinned,qe,Se,r,tt]),Tt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Wt=zp({status:de,daemonId:G||null,extraDaemonIds:Tt,meshId:v,sendData:n});l.useEffect(()=>{q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,uM(Re)])))},[X]),l.useEffect(()=>{const Re=(X==null?void 0:X.coordinator)||{};ut({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),J(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=x.addNodeDaemonPicker?cr(it):cr(j);_&&H.length===0&&Re.length>0&&fe(Re)},[_,j,it,H.length,x.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));me&&!Re.has(me)&&Te(null)},[X,me]);const ss=l.useMemo(()=>{var Re;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((X==null?void 0:X.id)??"")))return(Re=de.meshHost)==null?void 0:Re.hostDaemonId},[de,X]),Me=l.useMemo(()=>aM(r,be,G,k,ss),[r,be,G,k,ss]);l.useEffect(()=>{if(!x.meshHostDaemonSection)return;if(!r.length&&!We.pinned){xe("");return}const Re=We.pinned?Ye:Me;Re&&!Ws(Re,ke)&&xe(Re)},[r,ke,We.pinned,Ye,Me,x.meshHostDaemonSection]),l.useEffect(()=>{Se&&(qe||!r.some(Re=>Re.id===Se))&&pe("")},[qe,Se,r]),l.useEffect(()=>{if(x.createDaemonPicker){if(!r.length){E("");return}(!Q||!r.some(Re=>Re.id===Q))&&E(r[0].id)}},[r,Q,x.createDaemonPicker]),l.useEffect(()=>{var Re;if(!x.createDaemonPicker||!Q){$("");return}if(!D.length){$("");return}D.some(rt=>rt.path===I)||$(((Re=D[0])==null?void 0:Re.path)||"")},[Q,I,D,x.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!v)return;const Re=Qe.current!==v;if(Qe.current=v,Re){const rt=em(v);re(rt),V(null),ie(G,v,rt!==null)}else V(null),ie(G,v,!0)},[v,G]);const Dt=l.useRef(ie);Dt.current=ie;const It=l.useRef(!1),qt=l.useRef(()=>{});qt.current=()=>{It.current||!v||!G||(It.current=!0,Promise.resolve(Dt.current(G,v,!0)).finally(()=>{It.current=!1}))};const Vt=x.meshStatePushRefresh?lM:iM;sI({daemonIds:l.useMemo(()=>[G,...Tt].filter(Boolean),[G,Tt]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||qt.current()}}),l.useEffect(()=>{if(!v||!G||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&qt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Ot=()=>{Re!==null&&(clearInterval(Re),Re=null)},ne=()=>{document.visibilityState==="visible"?jt():Ot()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",ne),()=>{Ot(),document.removeEventListener("visibilitychange",ne)}},[v,G,Vt]),l.useEffect(()=>{x.queueSection||Z(v)},[v,x.queueSection]);const Yt=l.useMemo(()=>r.map(Re=>Re.id).filter(Boolean).sort().join(","),[r]),xs=l.useRef(!1);return l.useEffect(()=>{U(xs.current),xs.current=!0},[Yt]),k?X?s.jsx(QI,{selectedMesh:X,error:C,onDismissError:()=>A(null),onBack:()=>{g(null),re(null)},onDelete:ae,displayedMeshStatus:Wt,graphLoading:W,graphError:oe,onRefreshGraph:()=>ie(G,v,!0),savingPolicy:ye,onUpdatePolicy:Pe,coordinatorPromptDraft:Oe,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:at,onSaveCoordinatorPrompt:Ue,daemons:r,coordinatorDaemonId:ke,onCoordinatorDaemonIdChange:xe,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Fe,launchResult:Ie,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:We.pinned,hostLabel:We.label,hostOnline:qe,hostRebindDaemonId:Se,onHostRebindDaemonIdChange:Re=>pe(Re),onLaunchCoordinator:_e,activeDaemon:Ge,activeDaemonId:G,meshQueue:O,userName:o,availableCliProviders:j,savingNodeSlotsId:le,onUpdateNodeSlots:Ne,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:He,nodeSystemPromptDrafts:ht,onNodeSystemPromptDraftChange:(Re,rt)=>J(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:te,onSaveNodeSystemPrompt:Ze,selectedNodeId:me,onSelectNode:Te,showAddNode:_,onShowAddNode:()=>se(!0),onCancelAddNode:()=>se(!1),nodeWorkspace:ve,onNodeWorkspaceChange:ce,nodeProviderPriority:H,onNodeProviderPriorityChange:fe,nodeDaemonId:je,onNodeDaemonIdChange:Ce,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:ee,onAddNode:ge,onRemoveNode:Ae,availableCliAgents:b,features:{coordinatorPrompt:x.coordinatorPrompt,meshHostDaemonSection:x.meshHostDaemonSection,hermesMcpConfig:x.hermesMcpConfig,addNodeDaemonPicker:x.addNodeDaemonPicker,nodeInstruction:x.nodeInstruction},sendCommand:t}):s.jsx(uI,{meshes:S,loading:N,error:C,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:x.createDaemonPicker},showCreate:T,onToggleCreate:()=>M(!T),createName:L,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:K,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:Q,onNewMeshDaemonIdChange:E,newMeshWorkspace:I,onNewMeshWorkspaceChange:$,createPickerWorkspaces:D,onSelectMesh:g,onCreate:Y,onCancelCreate:z}):s.jsx(gr,{icon:s.jsx(es,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function dM(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function hM({children:e}){const{sendCommand:t,sendData:n}=yt(),{ides:r}=gs(),o=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:o,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const h=await t(i,"launch_mesh_coordinator",u),d=(h==null?void 0:h.result)??h;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((f=d==null?void 0:d.session)==null?void 0:f.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Hi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:nI}),[t,n,o]);return s.jsx(Xp.Provider,{value:a,children:e})}function bl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function pM(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=bl();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function ms(e,t){return await fetch(pM(e),{credentials:"same-origin",...t})}function tm(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class mM{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(o=>o(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:o,cols:a,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const o=this.runtimeListeners.get(t);o&&(o.delete(n),o.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await ms(`${o.pathname}${o.search}`);if(!a.ok){let c=`Runtime snapshot unavailable (${a.status})`;try{const u=await a.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await a.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(o=>o(n))}}const ps=new mM;function fM(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=bl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Wr=fM(),Id=3e3,bM=3e4;let os=null,gM=0;const wo=new Map;let $s=null,nr=null;function Md(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Gn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function xM(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Sh(e,n||{}),o=os;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++gM}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{wo.delete(a),c(new Error(`WS command timeout: ${t}`))},3e4);wo.set(a,{resolve:h=>{clearTimeout(u),i(h)},reject:h=>{clearTimeout(u),c(h)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yi(e,t){const n=os;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function sm(e,t,n){const r=os;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Sh(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:o.payload}})),!0}catch{return!1}}ps.registerPtyInputSender(sm);class yM{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(os==null?void 0:os.readyState)===WebSocket.OPEN}get connectionState(){return(os==null?void 0:os.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await rr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const o=await fetch(`data:image/jpeg;base64,${r.base64}`).then(a=>a.blob());ps.emitScreenshot(this.daemonId,o)}}catch{}};n(),$s=setInterval(n,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Xt=null;function vM(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new yM(e)),Xt}function wM({children:e}){const t=l.useRef(or()),n=or();t.current=n;const{setUserName:r}=gs(),o=l.useRef(r);o.current=r;const a=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((p,y)=>{c(p),nr==null||nr(p,y)},[]),h=l.useRef(null),d=l.useRef(),m=l.useRef(Id),f=l.useRef(!0),x=l.useRef(!1),w=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,x.current=!1;function p(){var b,j;if(!f.current||((b=h.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=h.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Wr}...`),Gn("connect_attempt",{url:Wr,reason:w.current,delayMs:m.current});let k;try{k=new WebSocket(Wr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),y();return}h.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),m.current=Id,Gn("open",{url:Wr,reason:w.current}),ls.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},os=k,k.onmessage=S=>{var v,g;try{const N=JSON.parse(S.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const C=wo.get(N.requestId);C&&(wo.delete(N.requestId),N.type==="error"?C.reject(new Error(((v=N.data)==null?void 0:v.message)||"Command failed")):C.resolve(N.data));return}if(N.type==="session_output"){const C=N.sessionId||N.cliId||N.cliType;C&&ps.emitSessionOutput(C,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ps.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const C=N.update;C&&ls.publish(C);return}if(N.type==="status"||N.type==="initial_state"){const C=N.data;if(!C)return;const{injectEntries:A,markLoaded:T,getIdes:M}=t.current,L=C.instanceId||"standalone",P=M().find(F=>F.id===L),B=vM(L);ps.register(L,B),ps.setState(L,"connected"),u("connected",L),ps.emitStatus(L,C);const K=ao(C,{daemonId:L,existingDaemon:P,existingEntries:M()});Md("ws_status",{type:N.type,daemonId:L,sessions:(C.sessions||[]).map(F=>({id:F.id,parentId:F.parentId,providerType:F.providerType,kind:F.kind,transport:F.transport,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,title:F.title})),recentLaunches:(C.recentLaunches||[]).map(F=>({id:F.id,providerType:F.providerType,kind:F.kind,workspace:F.workspace,lastLaunchedAt:F.lastLaunchedAt}))}),Md("entries",{daemonId:L,entries:K.filter(F=>F.type!=="adhdev-daemon").map(F=>({id:F.id,type:F.type,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,sessionId:F.sessionId}))}),K.length>0&&A(K,{authoritativeDaemonIds:[L]}),T(),i.current!==L&&((g=a.current)==null||g.call(a),i.current=L,a.current=ls.subscribe({sendData:yi},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},F=>{if(F.topic!=="daemon.metadata")return;const R=t.current.getIdes(),Q=R.find(I=>I.id===L),E=ao(F.status,{daemonId:L,existingDaemon:Q,existingEntries:R,timestamp:F.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),F.userName&&o.current&&o.current(F.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},k.onclose=S=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ps.setState(Xt.daemonId,"disconnected"),u("disconnected"),h.current=null,w.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Gn("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),y())},k.onerror=S=>{x.current||!f.current||(w.current="error",Gn("error",{message:S instanceof Event?"event":String(S),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function y(){if(!f.current)return;clearTimeout(d.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Gn("schedule_reconnect",{reason:w.current,delayMs:k}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,bM),p()},k)}return p(),()=>{var k;f.current=!1,x.current=!0,(k=a.current)==null||k.call(a),a.current=null,i.current=null,clearTimeout(d.current),h.current&&(h.current.onerror=null,h.current.onclose=null,h.current.close(),h.current=null,os=null),Xt&&(Xt.stopScreenshots(),ps.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function kM({children:e}){const[t,n]=l.useState("disconnected"),[r,o]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&o(c)},()=>{nr=null}),[]);const a=l.useMemo(()=>{const i=t==="connected",c=xM(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(of,{connectionOverrides:a,children:s.jsx(wM,{children:e})})}const nm="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Wo=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],hr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],SM=new Set(Wo.map(e=>e.id)),CM=new Set(hr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",t.chat),code:Zr("code",t.code),terminal:Zr("terminal",t.terminal)}}function Zr(e,t){const n=Vs[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?SM:CM).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:n:{preset:o}:n}function eo(e,t){var o;const n=Zr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Wo:hr;return((o=r.find(a=>a.id===n.preset))==null?void 0:o.family)||r[0].family}function jM(e){const t=fs(e),n=eo("chat",t.chat),r=eo("code",t.code),o=eo("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Hs(e,t=document.documentElement){const n=fs(e),r=jM(n);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return n}function vi(e){const t=fs(e);try{localStorage.setItem(nm,JSON.stringify(t))}catch{}return t}function NM(){try{const e=localStorage.getItem(nm);if(e)return fs(JSON.parse(e))}catch{}return Vs}function AM(){return Hs(NM())}function Kn(e,t){var r;const n=e==="chat"?Wo:hr;return((r=n.find(o=>o.id===t))==null?void 0:r.label)||n[0].label}function TM({children:e}){const t=pr(),n=ki(),{t:r}=Le("common"),o=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Kd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(So,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),a=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(qd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Ni,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(Ak,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const IM=[{icon:s.jsx(Is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Yd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(qd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],MM=[{icon:s.jsx($f,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Kd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Nn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Mf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Lf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],DM=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function PM(){const{t:e}=Le("common");return s.jsxs(gr,{icon:s.jsx(Ni,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(bt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(bt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:IM.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ch.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Nh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:jh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(bt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:MM.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:DM.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(Ro,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(zf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function $a(e,t,n){return{...e,[t]:n}}function Ba({surface:e,title:t,description:n,value:r,options:o,onChange:a}){const{t:i}=Le("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Dk,{value:r.preset,onChange:c=>{const u=c.target.value;a(u==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:u})},children:o.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(is,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>a({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:eo(e,r)})]})]})]})}function LM({value:e,savedValue:t,saving:n=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:h}=Le("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:h("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Gt,{variant:"error",children:r}),o&&s.jsx(Gt,{variant:"success",children:o}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ba,{surface:"chat",title:h("standalone.fonts.chat"),description:h("standalone.fonts.chatDescription"),value:e.chat,options:Wo,onChange:m=>a($a(e,"chat",m))}),s.jsx(Ba,{surface:"code",title:h("standalone.fonts.code"),description:h("standalone.fonts.codeDescription"),value:e.code,options:hr,onChange:m=>a($a(e,"code",m))}),s.jsx(Ba,{surface:"terminal",title:h("standalone.fonts.terminal"),description:h("standalone.fonts.terminalDescription"),value:e.terminal,options:hr,onChange:m=>a($a(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:h("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Kn("chat",e.chat.preset)," · Code: ",Kn("code",e.code.preset)," · Terminal: ",Kn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[h("standalone.fonts.defaults")," ",Kn("chat",Vs.chat.preset)," / ",Kn("code",Vs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:h(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:h("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:h("standalone.fonts.resetToDefaults")})]})]})}function RM(){const{t:e}=Le("common"),{ides:t}=gs(),n=t.find(W=>W.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:o}=yt(),{userName:a}=gs(),[i,c]=l.useState(a||""),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(Vs),[w,p]=l.useState(!1),[y,k]=l.useState(""),[b,j]=l.useState(""),[S,v]=l.useState("127.0.0.1"),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),[L,P]=l.useState(""),[B,K]=l.useState(""),[F,R]=l.useState(!1),Q=async()=>{const oe=await(await ms("/auth/session")).json();h(oe)},E=async()=>{const oe=await(await ms("/api/v1/standalone/preferences")).json();m(oe),v(oe.standaloneBindHost);const V=fs(oe.standaloneFontPreferences);x(V),Hs(V),vi(V)};l.useEffect(()=>{a!==void 0&&c(a)},[a]),l.useEffect(()=>{Promise.all([Q(),E()]).catch(W=>{P(W instanceof Error?W.message:String(W))})},[]),l.useEffect(()=>{Hs(f)},[f]);const I=W=>{const oe=W.target.value.trim();n!=null&&n.id&&oe!==a&&o(n.id,"set_user_name",{userName:oe}).catch(console.error)},[$,D]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=W=>{D(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},Y=async()=>{k(""),j(""),p(!0);try{const W=fs(f),oe=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),V=await oe.json();if(!oe.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone font preferences");const ie=fs(V.standaloneFontPreferences);m(V),x(ie),Hs(ie),vi(ie),j(e("standalone.settings.fontsSaved"))}catch(W){k(W instanceof Error?W.message:String(W))}finally{p(!1)}},ae=()=>{const W=fs(d==null?void 0:d.standaloneFontPreferences);k(""),j(""),x(W),Hs(W)},z=()=>{k(""),j(""),x(Vs),Hs(Vs)},X=async()=>{P(""),K(""),R(!0);try{const W=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone network preference");m(oe),v(oe.standaloneBindHost),K(oe.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},de=async()=>{if(P(""),K(""),C.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(C!==T){P(e("standalone.settings.passwordMismatch"));return}R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:C})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save password");h(oe),await E(),N(""),A(""),M(""),K(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),tm()}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},re=async()=>{P(""),K(""),R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to clear password");h(oe),await E(),N(""),A(""),M(""),K(e("standalone.settings.passwordDisabled"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}};return s.jsxs(gr,{icon:s.jsx(So,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Gt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Gt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(bt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(bt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:F,children:e(F?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(bt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&s.jsx(Gt,{variant:"error",children:L}),B&&s.jsx(Gt,{variant:"success",children:B}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:g,onChange:W=>N(W.target.value)}),s.jsx(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:W=>A(W.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:W=>M(W.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:F,children:F?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{re()},disabled:F,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(W=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${W.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:W.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:W.type})]},W.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(Fk,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(oS,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot: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:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(LM,{value:f,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:w,error:y,notice:b,onChange:x,onSave:()=>{Y()},onResetToSaved:ae,onResetToDefaults:z})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ek,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:U})]})}),s.jsx(bt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(If,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:W=>c(W.target.value),onBlur:I,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}const EM=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",_M=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],$M={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function BM({onDone:e}){const{t}=Le("common"),[n,r]=l.useState([]),[o,a]=l.useState(new Set(EM)),[i,c]=l.useState(!0),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("all");l.useEffect(()=>{let g=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{g||r(C.providers??[])}).catch(C=>{g||h(C instanceof Error?C.message:String(C))}).finally(()=>{g||c(!1)}),()=>{g=!0}},[]);const y=n.filter(g=>w==="all"||g.category===w),k=["cli","ide","extension","acp"].map(g=>({category:g,items:y.filter(N=>N.category===g)})).filter(g=>g.items.length>0),b=l.useCallback(g=>{a(N=>{const C=new Set(N);return C.has(g)?C.delete(g):C.add(g),C})},[]),j=l.useCallback(async()=>{if(o.size===0){localStorage.setItem(Yn,"1"),e();return}m(!0);const g=[];for(const N of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));g.push({type:N,ok:!!A.success,error:A.error})}catch(C){g.push({type:N,ok:!1,error:C instanceof Error?C.message:String(C)})}x(g),m(!1),g.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[o,e]),S=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(g=>g.ok)?e():d||S()},[f,d,e,S]);return s.jsx(Du,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(o.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:o.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(ks,{variant:"secondary",size:"sm",onClick:S,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):j()},disabled:d||!f&&o.size===0,children:d?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:_M.map(g=>{const N=g.key==="all"?n.length:n.filter(C=>C.category===g.key).length;return N===0&&g.key!=="all"?null:s.jsxs("button",{onClick:()=>p(g.key),className:`machine-btn text-[10px] px-2 py-0.5 ${w===g.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[g.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},g.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Gt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&y.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&y.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:k.map(g=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:$M[g.category]??g.category}),s.jsx("div",{className:"grid gap-1.5",children:g.items.map(N=>{var L,P;const C=o.has(N.type),A=f==null?void 0:f.find(B=>B.type===N.type),T=((L=N.manifest)==null?void 0:L.icon)??"📦",M=((P=N.manifest)==null?void 0:P.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:C,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),M&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:M})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},g.category))})]})})}function FM(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}wk();Qk();dy();AM();const HM=Bd({baseUrl:"",getToken:bl});function WM({children:e}){const{t}=Le("common"),[n,r]=l.useState(null),[o,a]=l.useState(!0),[i,c]=l.useState(""),[u,h]=l.useState(""),[d,m]=l.useState(!1),f=async()=>{a(!0),h("");try{const p=await(await ms("/auth/session")).json();r(p)}catch(w){h(w instanceof Error?w.message:String(w))}finally{a(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let w=!1;return(async()=>{try{const p=await ms("/api/v1/standalone/preferences");if(!p.ok)return;const y=await p.json();if(w)return;const k=fs(y.standaloneFontPreferences);Hs(k),vi(k)}catch{}})(),()=>{w=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const x=async w=>{w.preventDefault(),m(!0),h("");try{const p=await ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),y=await p.json();if(!p.ok)throw new Error((y==null?void 0:y.error)||"Login failed");r(y),c(""),tm()}catch(p){h(p instanceof Error?p.message:String(p))}finally{m(!1)}};return o?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx(is,{type:"password",value:i,onChange:w=>c(w.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Gt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Gt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function Dd(){const{t:e}=Le("common"),{ides:t,initialLoaded:n}=gs();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(o=>o.daemonMode||o.type==="adhdev-daemon");return r?s.jsx(Wa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Wa,{to:"/dashboard",replace:!0})}function OM(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!FM())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(BM,{onDone:()=>t(!1)}):null}function UM(){const{t:e}=Le("common"),{ides:t}=gs(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:r,hasActivePrompt:o,responseError:a,isSubmitting:i,submit:c,cancel:u,reopen:h}=Lh(n);return o?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:h,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(cu,{promptSession:r,isSubmitting:i,error:a,onSubmit:c,onCancel:u})]}):null}function GM(){const e=l.useMemo(()=>({sendCommand:rr,sendData:yi,sendPtyInput:sm}),[]);return s.jsx(Om,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(cf,{client:HM,children:s.jsx(WM,{children:s.jsx(kM,{children:s.jsx(uf,{value:e,children:s.jsxs(ff,{sendDaemonCommand:rr,children:[s.jsx(UM,{}),s.jsxs(TM,{children:[s.jsx(OM,{}),s.jsxs(Um,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(qA,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(tI,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/about",element:s.jsx(PM,{})}),s.jsx(js,{path:"/settings",element:s.jsx(RM,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(hM,{children:s.jsx(cM,{})})}),s.jsx(js,{path:"*",element:s.jsx(Wa,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}m0({connectionManager:ps});Gm(document.getElementById("root")).render(s.jsx(GM,{}));
121
+ Node removal cleanup policy: ${fe}`))return;const je=e.__sourceDaemonId||n;try{const Be=await a(je,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");j===ce&&S(null),await m(),x||await f(t)}catch(Be){w((Be==null?void 0:Be.message)||"Remove node failed")}}async function Se(ce){if(!e)return;const H={...xi(e),...ce},fe=e.__sourceDaemonId||n;try{D(!0),w(null);const je=await a(fe,"update_mesh",{meshId:e.id,policy:H}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Policy update failed");await m()}catch(je){w((je==null?void 0:je.message)||"Policy update failed")}finally{D(!1)}}async function pe(ce){if(!t)return;const H=(e==null?void 0:e.__sourceDaemonId)||n,fe=p[ce.id]||eM(ce),je=kn(fe),Ce={...ce.policy||{}};delete Ce.provider_priority,je.length?Ce.providerPriority=je:delete Ce.providerPriority;try{b(ce.id),w(null);const Be=await a(H,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:Ce,providerPriority:je}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1){w(Xe.error||"Node policy update failed");return}await m()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{b(null)}}const[G,O]=l.useState(null);async function Z(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n;try{O(ce.id),w(null);const je=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:H}}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1){w(Ce.error||"Node slots update failed");return}await m()}catch(je){w((je==null?void 0:je.message)||"Node slots update failed")}finally{O(null)}}const[q,me]=l.useState(null);async function Te(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n,je=H.map(Ce=>Ce.trim()).filter(Boolean);try{me(ce.id),w(null);const Ce=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:je}),Be=i(Ce);if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node tag update failed");return}await m()}catch(Ce){w((Ce==null?void 0:Ce.message)||"Node tag update failed")}finally{me(null)}}async function _(){if(!n||!t)return;const H={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?H.systemPromptOverride=U.override:delete H.systemPromptOverride,U.append.trim()?H.systemPromptAppend=U.append:delete H.systemPromptAppend,delete H.systemPromptSuffix;try{z(!0),w(null);const fe=await a(n,"update_mesh",{meshId:t,coordinator:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Coordinator prompt save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Coordinator prompt save failed")}finally{z(!1)}}async function te(ce){if(!n||!t)return;const H=(X[ce.id]||"").trim();try{W(ce.id),w(null);const fe=await a(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Node instruction save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Node instruction save failed")}finally{W(null)}}async function ve(){if(e){w(null),I(null);try{Q(!0);const ce=c?await c(r,e.id,e):null,H=u(r,e.id,e,e.nodes||[],ce);if("error"in H)throw new Error(H.error);const fe=await h(H.targetDaemonId,{meshId:e.id,inlineMesh:H.inlineMesh,coordinatorNodeId:H.coordinatorNodeId,cliType:K.trim()||void 0});I(fe.message)}catch(ce){w((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{Q(!1)}}}return{nodeProviderPriorityDrafts:p,setNodeProviderPriorityDrafts:y,savingNodePolicyId:k,selectedNodeId:j,setSelectedNodeId:S,showAddNode:v,setShowAddNode:g,nodeWorkspace:N,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:M,setNodeDaemonId:L,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:V,nodePickerProviders:ie,coordinatorCliType:K,setCoordinatorCliType:F,launchingCoordinator:R,launchResult:E,savingPolicy:$,coordinatorPromptDraft:U,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:re,savingNodeSlotsId:G,savingNodeCapabilitiesId:q,handleAddNode:ke,handleRemoveNode:xe,handleUpdatePolicy:Se,handleUpdateNodeProviderPriority:pe,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:_,handleSaveNodeSystemPrompt:te,handleLaunchCoordinator:ve}}function eM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function tM(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function sM({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:o,resolveCommandTarget:a}){const[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),w=l.useCallback(async y=>{if(!e||!y){c([]);return}try{const k=await n(e,"get_mesh_queue",{meshId:y});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,n]);async function p(y){var k,b;if(y){m(!0),x(null);try{const j=o?await o(t,y.id,y):null,S=a(t,y.id,y,y.nodes||[],j);if("error"in S)throw new Error(S.error);const v=await n(S.targetDaemonId,"get_mesh_queue",{meshId:y.id}),g=r(v);if((g==null?void 0:g.success)===!1)throw new Error(g.error||"Queue load failed");const N=Array.isArray(((k=g==null?void 0:g.result)==null?void 0:k.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue))?((b=g==null?void 0:g.result)==null?void 0:b.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue):[];h(tM(N))}catch(j){x((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:w,handleLoadQueue:p}}function nM(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Zp=new Map;function em(e){return e?Zp.get(e)??null:null}function rM(e,t){!e||!t||Zp.set(e,t)}function oM({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:o}){const[a,i]=l.useState(()=>em(e)),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState("idle"),[x,w]=l.useState(!1),p=l.useRef(!1);async function y(k,b=e,j=!1){if(!(!k||!b))try{u(!j&&a===null),f(j?"settling":"first_paint"),d(null);const S=await t(k,b,{refresh:j,retryProfile:j?"settled":"interactive"});w(nM(S));const v=n(S),g=r&&v?{...v,nodes:(v.nodes??[]).map(N=>r(N,v.meshId??b,""))}:v;if(g){if(o&&!j&&a!==null&&!Cj(Mp(g))){f("settling"),p.current||(p.current=!0,Promise.resolve().then(()=>y(k,b,!0)).finally(()=>{p.current=!1}));return}i(g),rM(b,g),f("settled")}else i(null),d("mesh_status returned an unexpected payload."),f("idle")}catch(S){a||i(null),d((S==null?void 0:S.message)||"Failed to load mesh graph"),f("idle")}finally{u(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:i,graphLoading:c,graphError:h,setGraphError:d,graphProvenance:m,graphBootstrapFallback:x,loadGraph:y}}function aM(e,t,n,r,o){if(!e.length)return"";const a=String(o||"");if(a){const u=e.find(h=>Ws(h.id,a));return u?u.id:a}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(h=>Ws(h.id,c));if(u)return u.id}return""}const iM=7e3,lM=45e3;function cM(){const e=rI(),{sendCommand:t,sendData:n,daemons:r,userName:o,loadMeshStatus:a,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:h,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:f,features:x,gateIncompleteGraph:w}=e,p=In(),y=r[0],k=(y==null?void 0:y.id)||"",b=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[y]),j=l.useMemo(()=>wn((y==null?void 0:y.availableProviders)||[]),[y]),{meshes:S,selectedMeshId:v,setSelectedMeshId:g,loading:N,error:C,setError:A,showCreate:T,setShowCreate:M,createName:L,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:K,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:R,newMeshDaemonId:Q,setNewMeshDaemonId:E,newMeshWorkspace:I,setNewMeshWorkspace:$,createPickerWorkspaces:D,loadMeshes:U,handleCreate:Y,handleDelete:ae,cancelCreate:z}=XI({daemons:r,primaryDaemonId:k,sendCommand:t,unwrapResult:h,normalizeMesh:d,features:x,loadDaemonMetadata:p}),X=S.find(Re=>Re.id===v)||null,{meshGraphStatus:de,setMeshGraphStatus:re,graphLoading:W,graphError:oe,setGraphError:V,loadGraph:ie}=oM({selectedMeshId:v,loadMeshStatus:a,extractStatus:u,normalizeNode:m,gateIncompleteGraph:w}),[ke,xe]=l.useState(""),[Se,pe]=l.useState(""),G=x.meshHostDaemonSection&&ke||k,{meshQueue:O,loadQueue:Z}=sM({primaryDaemonId:k,activeDaemonId:G,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:q,selectedNodeId:me,setSelectedNodeId:Te,showAddNode:_,setShowAddNode:te,nodeWorkspace:ve,setNodeWorkspace:ce,nodeProviderPriority:H,setNodeProviderPriority:fe,nodeDaemonId:je,setNodeDaemonId:Ce,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Fe,launchResult:Ie,savingPolicy:ye,coordinatorPromptDraft:Oe,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:at,nodeSystemPromptDrafts:ht,setNodeSystemPromptDrafts:J,savingNodeSystemPromptId:ee,savingNodeSlotsId:le,savingNodeCapabilitiesId:ue,handleAddNode:ge,handleRemoveNode:Ae,handleUpdatePolicy:Pe,handleUpdateNodeSlots:Ne,handleUpdateNodeCapabilities:He,handleSaveCoordinatorPrompt:Ke,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=ZI({selectedMesh:X,selectedMeshId:v,primaryDaemonId:k,activeDaemonId:G,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:x.addNodeDaemonPicker},loadMeshes:U,loadQueue:Z,queueSection:x.queueSection,setError:A}),Ue=l.useMemo(()=>r.find(Re=>Re.id===G)||y,[r,G,y]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),se=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),be=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>be.find(Re=>Ws(String(Re.daemon_id||Re.daemonId||""),ke)),[be,ke]),ze=x.meshHostDaemonSection?!!we:!0,We=l.useMemo(()=>{if(!x.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=X.meshHost,rt=de!=null&&de.meshId&&String(de.meshId)===String(X.id??"")?de.meshHost:void 0,jt=rt!=null&&rt.hostDaemonId?rt:Re??rt,Ot=String((jt==null?void 0:jt.hostDaemonId)||""),ne=be.find(ys=>ys.role==="host"),Ge=String((jt==null?void 0:jt.hostNodeId)||(ne==null?void 0:ne.id)||""),Ee=Ge?be.find(ys=>String(ys.id)===Ge):void 0,vt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Ot||vt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Mn=r.find(ys=>Ot&&Ws(ys.id,Ot))||(vt?r.find(ys=>Ws(ys.id,vt)):void 0);if(Mn)return{pinned:!0,daemonId:Mn.id,label:dM(Mn),online:!0};const Oo=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Oo,online:!1}},[X,be,r,de,x.meshHostDaemonSection]),tt=We.daemonId,qe=We.online,Ye=l.useMemo(()=>!x.meshHostDaemonSection||!We.pinned?"":!qe&&Se&&r.some(Re=>Re.id===Se)?Se:tt,[x.meshHostDaemonSection,We.pinned,qe,Se,r,tt]),Tt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Wt=zp({status:de,daemonId:G||null,extraDaemonIds:Tt,meshId:v,sendData:n});l.useEffect(()=>{q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,uM(Re)])))},[X]),l.useEffect(()=>{const Re=(X==null?void 0:X.coordinator)||{};ut({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),J(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=x.addNodeDaemonPicker?cr(it):cr(j);_&&H.length===0&&Re.length>0&&fe(Re)},[_,j,it,H.length,x.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));me&&!Re.has(me)&&Te(null)},[X,me]);const ss=l.useMemo(()=>{var Re;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((X==null?void 0:X.id)??"")))return(Re=de.meshHost)==null?void 0:Re.hostDaemonId},[de,X]),Me=l.useMemo(()=>aM(r,be,G,k,ss),[r,be,G,k,ss]);l.useEffect(()=>{if(!x.meshHostDaemonSection)return;if(!r.length&&!We.pinned){xe("");return}const Re=We.pinned?Ye:Me;Re&&!Ws(Re,ke)&&xe(Re)},[r,ke,We.pinned,Ye,Me,x.meshHostDaemonSection]),l.useEffect(()=>{Se&&(qe||!r.some(Re=>Re.id===Se))&&pe("")},[qe,Se,r]),l.useEffect(()=>{if(x.createDaemonPicker){if(!r.length){E("");return}(!Q||!r.some(Re=>Re.id===Q))&&E(r[0].id)}},[r,Q,x.createDaemonPicker]),l.useEffect(()=>{var Re;if(!x.createDaemonPicker||!Q){$("");return}if(!D.length){$("");return}D.some(rt=>rt.path===I)||$(((Re=D[0])==null?void 0:Re.path)||"")},[Q,I,D,x.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!v)return;const Re=Qe.current!==v;if(Qe.current=v,Re){const rt=em(v);re(rt),V(null),ie(G,v,rt!==null)}else V(null),ie(G,v,!0)},[v,G]);const Dt=l.useRef(ie);Dt.current=ie;const It=l.useRef(!1),qt=l.useRef(()=>{});qt.current=()=>{It.current||!v||!G||(It.current=!0,Promise.resolve(Dt.current(G,v,!0)).finally(()=>{It.current=!1}))};const Vt=x.meshStatePushRefresh?lM:iM;sI({daemonIds:l.useMemo(()=>[G,...Tt].filter(Boolean),[G,Tt]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||qt.current()}}),l.useEffect(()=>{if(!v||!G||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&qt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Ot=()=>{Re!==null&&(clearInterval(Re),Re=null)},ne=()=>{document.visibilityState==="visible"?jt():Ot()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",ne),()=>{Ot(),document.removeEventListener("visibilitychange",ne)}},[v,G,Vt]),l.useEffect(()=>{x.queueSection||Z(v)},[v,x.queueSection]);const Yt=l.useMemo(()=>r.map(Re=>Re.id).filter(Boolean).sort().join(","),[r]),xs=l.useRef(!1);return l.useEffect(()=>{U(xs.current),xs.current=!0},[Yt]),k?X?s.jsx(QI,{selectedMesh:X,error:C,onDismissError:()=>A(null),onBack:()=>{g(null),re(null)},onDelete:ae,displayedMeshStatus:Wt,graphLoading:W,graphError:oe,onRefreshGraph:()=>ie(G,v,!0),savingPolicy:ye,onUpdatePolicy:Pe,coordinatorPromptDraft:Oe,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:at,onSaveCoordinatorPrompt:Ke,daemons:r,coordinatorDaemonId:ke,onCoordinatorDaemonIdChange:xe,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Fe,launchResult:Ie,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:We.pinned,hostLabel:We.label,hostOnline:qe,hostRebindDaemonId:Se,onHostRebindDaemonIdChange:Re=>pe(Re),onLaunchCoordinator:_e,activeDaemon:Ue,activeDaemonId:G,meshQueue:O,userName:o,availableCliProviders:j,savingNodeSlotsId:le,onUpdateNodeSlots:Ne,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:He,nodeSystemPromptDrafts:ht,onNodeSystemPromptDraftChange:(Re,rt)=>J(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ze,selectedNodeId:me,onSelectNode:Te,showAddNode:_,onShowAddNode:()=>te(!0),onCancelAddNode:()=>te(!1),nodeWorkspace:ve,onNodeWorkspaceChange:ce,nodeProviderPriority:H,onNodeProviderPriorityChange:fe,nodeDaemonId:je,onNodeDaemonIdChange:Ce,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:se,onAddNode:ge,onRemoveNode:Ae,availableCliAgents:b,features:{coordinatorPrompt:x.coordinatorPrompt,meshHostDaemonSection:x.meshHostDaemonSection,hermesMcpConfig:x.hermesMcpConfig,addNodeDaemonPicker:x.addNodeDaemonPicker,nodeInstruction:x.nodeInstruction},sendCommand:t}):s.jsx(uI,{meshes:S,loading:N,error:C,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:x.createDaemonPicker},showCreate:T,onToggleCreate:()=>M(!T),createName:L,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:K,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:Q,onNewMeshDaemonIdChange:E,newMeshWorkspace:I,onNewMeshWorkspaceChange:$,createPickerWorkspaces:D,onSelectMesh:g,onCreate:Y,onCancelCreate:z}):s.jsx(gr,{icon:s.jsx(es,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function dM(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function hM({children:e}){const{sendCommand:t,sendData:n}=yt(),{ides:r}=gs(),o=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:o,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const h=await t(i,"launch_mesh_coordinator",u),d=(h==null?void 0:h.result)??h;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((f=d==null?void 0:d.session)==null?void 0:f.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Hi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:nI}),[t,n,o]);return s.jsx(Xp.Provider,{value:a,children:e})}function bl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function pM(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=bl();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function ms(e,t){return await fetch(pM(e),{credentials:"same-origin",...t})}function tm(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has("token")&&(e.searchParams.delete("token"),window.history.replaceState({},"",`${e.pathname}${e.search}${e.hash}`))}class mM{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(o=>o(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:o,cols:a,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const o=this.runtimeListeners.get(t);o&&(o.delete(n),o.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await ms(`${o.pathname}${o.search}`);if(!a.ok){let c=`Runtime snapshot unavailable (${a.status})`;try{const u=await a.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await a.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(o=>o(n))}}const ps=new mM;function fM(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=bl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Wr=fM(),Id=3e3,bM=3e4;let os=null,gM=0;const wo=new Map;let $s=null,nr=null;function Md(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Gn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function xM(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Sh(e,n||{}),o=os;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++gM}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{wo.delete(a),c(new Error(`WS command timeout: ${t}`))},3e4);wo.set(a,{resolve:h=>{clearTimeout(u),i(h)},reject:h=>{clearTimeout(u),c(h)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yi(e,t){const n=os;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function sm(e,t,n){const r=os;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Sh(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:o.payload}})),!0}catch{return!1}}ps.registerPtyInputSender(sm);class yM{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(os==null?void 0:os.readyState)===WebSocket.OPEN}get connectionState(){return(os==null?void 0:os.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$s&&(clearInterval($s),$s=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await rr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const o=await fetch(`data:image/jpeg;base64,${r.base64}`).then(a=>a.blob());ps.emitScreenshot(this.daemonId,o)}}catch{}};n(),$s=setInterval(n,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Xt=null;function vM(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new yM(e)),Xt}function wM({children:e}){const t=l.useRef(or()),n=or();t.current=n;const{setUserName:r}=gs(),o=l.useRef(r);o.current=r;const a=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((p,y)=>{c(p),nr==null||nr(p,y)},[]),h=l.useRef(null),d=l.useRef(),m=l.useRef(Id),f=l.useRef(!0),x=l.useRef(!1),w=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,x.current=!1;function p(){var b,j;if(!f.current||((b=h.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=h.current)==null?void 0:j.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Wr}...`),Gn("connect_attempt",{url:Wr,reason:w.current,delayMs:m.current});let k;try{k=new WebSocket(Wr)}catch(S){console.error("[Standalone WS] Failed to create WebSocket:",S),y();return}h.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),m.current=Id,Gn("open",{url:Wr,reason:w.current}),ls.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},os=k,k.onmessage=S=>{var v,g;try{const N=JSON.parse(S.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const C=wo.get(N.requestId);C&&(wo.delete(N.requestId),N.type==="error"?C.reject(new Error(((v=N.data)==null?void 0:v.message)||"Command failed")):C.resolve(N.data));return}if(N.type==="session_output"){const C=N.sessionId||N.cliId||N.cliType;C&&ps.emitSessionOutput(C,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ps.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const C=N.update;C&&ls.publish(C);return}if(N.type==="status"||N.type==="initial_state"){const C=N.data;if(!C)return;const{injectEntries:A,markLoaded:T,getIdes:M}=t.current,L=C.instanceId||"standalone",P=M().find(F=>F.id===L),B=vM(L);ps.register(L,B),ps.setState(L,"connected"),u("connected",L),ps.emitStatus(L,C);const K=ao(C,{daemonId:L,existingDaemon:P,existingEntries:M()});Md("ws_status",{type:N.type,daemonId:L,sessions:(C.sessions||[]).map(F=>({id:F.id,parentId:F.parentId,providerType:F.providerType,kind:F.kind,transport:F.transport,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,title:F.title})),recentLaunches:(C.recentLaunches||[]).map(F=>({id:F.id,providerType:F.providerType,kind:F.kind,workspace:F.workspace,lastLaunchedAt:F.lastLaunchedAt}))}),Md("entries",{daemonId:L,entries:K.filter(F=>F.type!=="adhdev-daemon").map(F=>({id:F.id,type:F.type,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,sessionId:F.sessionId}))}),K.length>0&&A(K,{authoritativeDaemonIds:[L]}),T(),i.current!==L&&((g=a.current)==null||g.call(a),i.current=L,a.current=ls.subscribe({sendData:yi},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},F=>{if(F.topic!=="daemon.metadata")return;const R=t.current.getIdes(),Q=R.find(I=>I.id===L),E=ao(F.status,{daemonId:L,existingDaemon:Q,existingEntries:R,timestamp:F.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),F.userName&&o.current&&o.current(F.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},k.onclose=S=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ps.setState(Xt.daemonId,"disconnected"),u("disconnected"),h.current=null,w.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Gn("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),y())},k.onerror=S=>{x.current||!f.current||(w.current="error",Gn("error",{message:S instanceof Event?"event":String(S),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function y(){if(!f.current)return;clearTimeout(d.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Gn("schedule_reconnect",{reason:w.current,delayMs:k}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,bM),p()},k)}return p(),()=>{var k;f.current=!1,x.current=!0,(k=a.current)==null||k.call(a),a.current=null,i.current=null,clearTimeout(d.current),h.current&&(h.current.onerror=null,h.current.onclose=null,h.current.close(),h.current=null,os=null),Xt&&(Xt.stopScreenshots(),ps.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function kM({children:e}){const[t,n]=l.useState("disconnected"),[r,o]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&o(c)},()=>{nr=null}),[]);const a=l.useMemo(()=>{const i=t==="connected",c=xM(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(of,{connectionOverrides:a,children:s.jsx(wM,{children:e})})}const nm="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Wo=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],hr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],SM=new Set(Wo.map(e=>e.id)),CM=new Set(hr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",t.chat),code:Zr("code",t.code),terminal:Zr("terminal",t.terminal)}}function Zr(e,t){const n=Vs[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?SM:CM).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:n:{preset:o}:n}function eo(e,t){var o;const n=Zr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Wo:hr;return((o=r.find(a=>a.id===n.preset))==null?void 0:o.family)||r[0].family}function jM(e){const t=fs(e),n=eo("chat",t.chat),r=eo("code",t.code),o=eo("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Hs(e,t=document.documentElement){const n=fs(e),r=jM(n);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return n}function vi(e){const t=fs(e);try{localStorage.setItem(nm,JSON.stringify(t))}catch{}return t}function NM(){try{const e=localStorage.getItem(nm);if(e)return fs(JSON.parse(e))}catch{}return Vs}function AM(){return Hs(NM())}function Kn(e,t){var r;const n=e==="chat"?Wo:hr;return((r=n.find(o=>o.id===t))==null?void 0:r.label)||n[0].label}function TM({children:e}){const t=pr(),n=ki(),{t:r}=Le("common"),o=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Kd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(So,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),a=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(qd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Ni,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(Ak,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const IM=[{icon:s.jsx(Is,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Yd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(ar,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(qd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],MM=[{icon:s.jsx($f,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Kd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Nn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Mf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Lf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],DM=[{feature:"Agent chat relay",selfhost:!0,cloud:!0},{feature:"Live IDE screenshots",selfhost:!0,cloud:!0},{feature:"Remote IDE control",selfhost:!0,cloud:!0},{feature:"Multi-IDE monitoring",selfhost:!0,cloud:!0},{feature:"Extension and CLI agents",selfhost:!0,cloud:!0},{feature:"Access from any network",selfhost:!1,cloud:!0},{feature:"WebRTC P2P streaming",selfhost:!1,cloud:!0},{feature:"Mobile push notifications",selfhost:!1,cloud:!0},{feature:"REST API and webhooks",selfhost:!1,cloud:!0},{feature:"Team collaboration",selfhost:!1,cloud:!0},{feature:"Multi-machine burrows",selfhost:!1,cloud:!0},{feature:"SSO, RBAC, audit logs",selfhost:!1,cloud:!0}];function PM(){const{t:e}=Le("common");return s.jsxs(gr,{icon:s.jsx(Ni,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.82"]}),children:[s.jsx(bt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(bt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:IM.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Ch.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Nh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:jh.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(bt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:MM.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(bt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:DM.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(Ro,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(zf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function $a(e,t,n){return{...e,[t]:n}}function Ba({surface:e,title:t,description:n,value:r,options:o,onChange:a}){const{t:i}=Le("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Dk,{value:r.preset,onChange:c=>{const u=c.target.value;a(u==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:u})},children:o.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(is,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>a({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:eo(e,r)})]})]})]})}function LM({value:e,savedValue:t,saving:n=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:h}=Le("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:h("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Gt,{variant:"error",children:r}),o&&s.jsx(Gt,{variant:"success",children:o}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ba,{surface:"chat",title:h("standalone.fonts.chat"),description:h("standalone.fonts.chatDescription"),value:e.chat,options:Wo,onChange:m=>a($a(e,"chat",m))}),s.jsx(Ba,{surface:"code",title:h("standalone.fonts.code"),description:h("standalone.fonts.codeDescription"),value:e.code,options:hr,onChange:m=>a($a(e,"code",m))}),s.jsx(Ba,{surface:"terminal",title:h("standalone.fonts.terminal"),description:h("standalone.fonts.terminalDescription"),value:e.terminal,options:hr,onChange:m=>a($a(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:h("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Kn("chat",e.chat.preset)," · Code: ",Kn("code",e.code.preset)," · Terminal: ",Kn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[h("standalone.fonts.defaults")," ",Kn("chat",Vs.chat.preset)," / ",Kn("code",Vs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:h(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:h("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:h("standalone.fonts.resetToDefaults")})]})]})}function RM(){const{t:e}=Le("common"),{ides:t}=gs(),n=t.find(W=>W.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:o}=yt(),{userName:a}=gs(),[i,c]=l.useState(a||""),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(Vs),[w,p]=l.useState(!1),[y,k]=l.useState(""),[b,j]=l.useState(""),[S,v]=l.useState("127.0.0.1"),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),[L,P]=l.useState(""),[B,K]=l.useState(""),[F,R]=l.useState(!1),Q=async()=>{const oe=await(await ms("/auth/session")).json();h(oe)},E=async()=>{const oe=await(await ms("/api/v1/standalone/preferences")).json();m(oe),v(oe.standaloneBindHost);const V=fs(oe.standaloneFontPreferences);x(V),Hs(V),vi(V)};l.useEffect(()=>{a!==void 0&&c(a)},[a]),l.useEffect(()=>{Promise.all([Q(),E()]).catch(W=>{P(W instanceof Error?W.message:String(W))})},[]),l.useEffect(()=>{Hs(f)},[f]);const I=W=>{const oe=W.target.value.trim();n!=null&&n.id&&oe!==a&&o(n.id,"set_user_name",{userName:oe}).catch(console.error)},[$,D]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=W=>{D(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},Y=async()=>{k(""),j(""),p(!0);try{const W=fs(f),oe=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),V=await oe.json();if(!oe.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone font preferences");const ie=fs(V.standaloneFontPreferences);m(V),x(ie),Hs(ie),vi(ie),j(e("standalone.settings.fontsSaved"))}catch(W){k(W instanceof Error?W.message:String(W))}finally{p(!1)}},ae=()=>{const W=fs(d==null?void 0:d.standaloneFontPreferences);k(""),j(""),x(W),Hs(W)},z=()=>{k(""),j(""),x(Vs),Hs(Vs)},X=async()=>{P(""),K(""),R(!0);try{const W=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone network preference");m(oe),v(oe.standaloneBindHost),K(oe.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},de=async()=>{if(P(""),K(""),C.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(C!==T){P(e("standalone.settings.passwordMismatch"));return}R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:C})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save password");h(oe),await E(),N(""),A(""),M(""),K(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),tm()}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},re=async()=>{P(""),K(""),R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to clear password");h(oe),await E(),N(""),A(""),M(""),K(e("standalone.settings.passwordDisabled"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}};return s.jsxs(gr,{icon:s.jsx(So,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Gt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Gt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(bt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.82"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(bt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="127.0.0.1",onChange:()=>v("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:S==="0.0.0.0",onChange:()=>v("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:F,children:e(F?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(bt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&s.jsx(Gt,{variant:"error",children:L}),B&&s.jsx(Gt,{variant:"success",children:B}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:g,onChange:W=>N(W.target.value)}),s.jsx(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:W=>A(W.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:W=>M(W.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:F,children:F?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{re()},disabled:F,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(W=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${W.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:W.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:W.type})]},W.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(Fk,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(oS,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot: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:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(LM,{value:f,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:w,error:y,notice:b,onChange:x,onSave:()=>{Y()},onResetToSaved:ae,onResetToDefaults:z})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Ek,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:U})]})}),s.jsx(bt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(If,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:W=>c(W.target.value),onBlur:I,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}const EM=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",_M=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],$M={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function BM({onDone:e}){const{t}=Le("common"),[n,r]=l.useState([]),[o,a]=l.useState(new Set(EM)),[i,c]=l.useState(!0),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("all");l.useEffect(()=>{let g=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{g||r(C.providers??[])}).catch(C=>{g||h(C instanceof Error?C.message:String(C))}).finally(()=>{g||c(!1)}),()=>{g=!0}},[]);const y=n.filter(g=>w==="all"||g.category===w),k=["cli","ide","extension","acp"].map(g=>({category:g,items:y.filter(N=>N.category===g)})).filter(g=>g.items.length>0),b=l.useCallback(g=>{a(N=>{const C=new Set(N);return C.has(g)?C.delete(g):C.add(g),C})},[]),j=l.useCallback(async()=>{if(o.size===0){localStorage.setItem(Yn,"1"),e();return}m(!0);const g=[];for(const N of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));g.push({type:N,ok:!!A.success,error:A.error})}catch(C){g.push({type:N,ok:!1,error:C instanceof Error?C.message:String(C)})}x(g),m(!1),g.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[o,e]),S=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(g=>g.ok)?e():d||S()},[f,d,e,S]);return s.jsx(Du,{open:!0,onClose:v,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(o.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:o.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(ks,{variant:"secondary",size:"sm",onClick:S,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):j()},disabled:d||!f&&o.size===0,children:d?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:_M.map(g=>{const N=g.key==="all"?n.length:n.filter(C=>C.category===g.key).length;return N===0&&g.key!=="all"?null:s.jsxs("button",{onClick:()=>p(g.key),className:`machine-btn text-[10px] px-2 py-0.5 ${w===g.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[g.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},g.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Gt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&y.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&y.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:k.map(g=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:$M[g.category]??g.category}),s.jsx("div",{className:"grid gap-1.5",children:g.items.map(N=>{var L,P;const C=o.has(N.type),A=f==null?void 0:f.find(B=>B.type===N.type),T=((L=N.manifest)==null?void 0:L.icon)??"📦",M=((P=N.manifest)==null?void 0:P.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:C,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),M&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:M})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},g.category))})]})})}function FM(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}wk();Qk();dy();AM();const HM=Bd({baseUrl:"",getToken:bl});function WM({children:e}){const{t}=Le("common"),[n,r]=l.useState(null),[o,a]=l.useState(!0),[i,c]=l.useState(""),[u,h]=l.useState(""),[d,m]=l.useState(!1),f=async()=>{a(!0),h("");try{const p=await(await ms("/auth/session")).json();r(p)}catch(w){h(w instanceof Error?w.message:String(w))}finally{a(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let w=!1;return(async()=>{try{const p=await ms("/api/v1/standalone/preferences");if(!p.ok)return;const y=await p.json();if(w)return;const k=fs(y.standaloneFontPreferences);Hs(k),vi(k)}catch{}})(),()=>{w=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const x=async w=>{w.preventDefault(),m(!0),h("");try{const p=await ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),y=await p.json();if(!p.ok)throw new Error((y==null?void 0:y.error)||"Login failed");r(y),c(""),tm()}catch(p){h(p instanceof Error?p.message:String(p))}finally{m(!1)}};return o?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:x,children:[s.jsx(is,{type:"password",value:i,onChange:w=>c(w.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Gt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Gt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function Dd(){const{t:e}=Le("common"),{ides:t,initialLoaded:n}=gs();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(o=>o.daemonMode||o.type==="adhdev-daemon");return r?s.jsx(Wa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Wa,{to:"/dashboard",replace:!0})}function OM(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!FM())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(BM,{onDone:()=>t(!1)}):null}function UM(){const{t:e}=Le("common"),{ides:t}=gs(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:r,hasActivePrompt:o,responseError:a,isSubmitting:i,submit:c,cancel:u,reopen:h}=Lh(n);return o?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:h,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(cu,{promptSession:r,isSubmitting:i,error:a,onSubmit:c,onCancel:u})]}):null}function GM(){const e=l.useMemo(()=>({sendCommand:rr,sendData:yi,sendPtyInput:sm}),[]);return s.jsx(Om,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(cf,{client:HM,children:s.jsx(WM,{children:s.jsx(kM,{children:s.jsx(uf,{value:e,children:s.jsxs(ff,{sendDaemonCommand:rr,children:[s.jsx(UM,{}),s.jsxs(TM,{children:[s.jsx(OM,{}),s.jsxs(Um,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(qA,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(tI,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/about",element:s.jsx(PM,{})}),s.jsx(js,{path:"/settings",element:s.jsx(RM,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(hM,{children:s.jsx(cM,{})})}),s.jsx(js,{path:"*",element:s.jsx(Wa,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}m0({connectionManager:ps});Gm(document.getElementById("root")).render(s.jsx(GM,{}));