@mmmbuto/nexuscrew 0.9.60 → 0.9.61
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.
- package/CHANGELOG.md +5 -0
- package/frontend/dist/assets/{index-D42BJVwr.js → index-VtTd56fc.js} +2 -2
- package/frontend/dist/index.html +1 -1
- package/frontend/dist/version.json +1 -1
- package/lib/fleet/builtin.js +2 -2
- package/lib/fleet/definitions.js +15 -0
- package/lib/notify/owner-ask-scope.js +2 -3
- package/package.json +1 -1
|
@@ -154,7 +154,7 @@ void main() {
|
|
|
154
154
|
\x1B[33m[sessione finita]\x1B[0m\r
|
|
155
155
|
`),onSnapshot:ve=>{try{const Ke=oe.buffer&&oe.buffer.active,et=KM({viewportY:Ke?Ke.viewportY:0,baseY:Ke?Ke.baseY:0},{baseY:Ke?Ke.baseY:0});oe.reset(),oe.write(ve),!et.atBottom&&et.line!==null&&typeof oe.scrollToLine=="function"&&oe.scrollToLine(et.line)}catch{}},onQueued:ve=>H(ve),onLink:ve=>{if(Q.current&&(clearTimeout(Q.current),Q.current=null),ve==="live"){const Ke=se.current!==null&&qM(se.current,Date.now());if(se.current=null,U(!1),Ke)try{oe.write(VM(!0))}catch{}return}se.current===null&&(se.current=Date.now()),Q.current=setTimeout(()=>{Q.current=null,U(!0)},mk().overlayDelayMs||gk)}})}catch(ve){return oe.write(`\r
|
|
156
156
|
\x1B[31m${ve.message}\x1B[0m\r
|
|
157
|
-
`),b&&(b.current=null),qt==null||qt.removeEventListener("blur",wn),(ia=E.current)==null||ia.removeEventListener("paste",Ft,!0),(ul=E.current)==null||ul.removeEventListener("keydown",Xt,!0),()=>{var Ke,et;try{(et=(Ke=$.current)==null?void 0:Ke.dispose)==null||et.call(Ke)}catch{}$.current=null,oe.dispose()}}F.current={term:oe,fit:$e,sock:Jt,setKeyboardGesture:ln};let Qt=null;const ls=oe.onData(ve=>{if(s){Qt&&(Qt.ok=!1);return}const Ke=en&&Date.now()<bn;Xt(),!Qt&&!Ke&&ve.length>=1&&(f&&f.current||v&&v.current)&&(ve=YM(ve,{ctrl:!!(f&&f.current),alt:!!(v&&v.current)}),f&&(f.current=!1),v&&(v.current=!1),g&&g(!1),_&&_(!1));const et=Jt.sendInput(ve);Qt&&(Qt.seen=!0,Qt.ok=Qt.ok&&et)});c&&(c.current=ve=>Jt.sendInput(ve)),h&&(h.current=ve=>Jt.action(ve)),u&&(u.current=JM({isReady:()=>!s&&Jt.isReady(),paste:ve=>{const Ke={seen:!1,ok:!0};Qt=Ke;try{oe.paste(ve)}catch{Ke.ok=!1}finally{Qt=null}return Ke.seen&&Ke.ok},send:ve=>Jt.sendInput(ve)}));const cs=ve=>{Ze.current=ve,st(ve)};let mn=null;const gn=oe.onSelectionChange(()=>{const ve=oe.getSelection();ve?(D(ve),me(!1)):me(!0);const Ke=iT(oe.getSelectionPosition(),oe.cols),et=Ke?m0(Ke.start,Ke.end,oe.cols):null;ie(et),xe.current=et,et||cs(null),!et&&mn&&Ar();let dt=null;if(et&&typeof oe.buffer.active.getLine=="function"){const Nt=[];for(let jt=et.start.row;jt<=et.end.row;jt++){const It=oe.buffer.active.getLine(jt);Nt.push(It?It.translateToString():"")}dt={startRow:et.start.row,endRow:et.end.row,lines:Nt}}De.current=dt,qe(!1)}),qs=oe.onRender(ve=>{var Ke;if((Ke=oe.hasSelection)!=null&&Ke.call(oe)){const et=De.current,dt=ve&&ve.start,Nt=ve&&ve.end;if(et&&Number.isInteger(dt)&&Number.isInteger(Nt)&&typeof oe.buffer.active.getLine=="function"){const jt=Number(oe.buffer.active.viewportY)||0,It=Math.max(jt+dt,et.startRow),nn=Math.min(jt+Nt,et.endRow);for(let Yn=It;Yn<=nn;Yn++){const cn=oe.buffer.active.getLine(Yn);if((cn?cn.translateToString():"")!==et.lines[Yn-et.startRow]){qe(!0);break}}}Ie(jt=>jt+1)}}),Vn=oe.onScroll(()=>{var ve;(ve=oe.hasSelection)!=null&&ve.call(oe)&&Ie(Ke=>Ke+1)});oe.attachCustomKeyEventHandler(ve=>(ve.ctrlKey||ve.metaKey)&&ve.key.toLowerCase()==="c"&&oe.getSelection()?(ve.type==="keydown"&&rg(oe.getSelection()),!1):!0);const bt=E.current;let us=!1;const le=async ve=>{if(!ve.length||us)return;if(s){z({error:p("settings-readonly")});return}us=!0,z({current:0,total:ve.length,name:""});const Ke=await ag({files:ve,token:n,session:t,node:e,paste:!0,onProgress:({index:et,total:dt,name:Nt,state:jt,error:It})=>z({current:et+1,total:dt,name:Nt,...jt==="error"?{error:It}:{}})});us=!1,Ke.errors.length?z({error:Ke.errors.map(et=>`${et.name}: ${et.message}`).join(" · ")}):(z({done:!0,total:Ke.paths.length}),setTimeout(()=>z(null),1600))},re=ve=>{const Ke=ve.clipboardData;if(!vp(Ke))return;const et=y0(Ke);et.length&&(ve.preventDefault(),ve.stopPropagation(),le(et))},Te=ve=>{vp(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation())},Ge=ve=>{vp(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation(),le(y0(ve.dataTransfer)))};bt.addEventListener("paste",re,!0),bt.addEventListener("dragenter",Te,!0),bt.addEventListener("dragover",Te,!0),bt.addEventListener("drop",Ge,!0);const mt=24,q=(ve,Ke)=>{const dt=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),Nt=Math.floor((ve-dt.left)/Math.max(1,dt.width)*oe.cols)+1,jt=Math.floor((Ke-dt.top)/Math.max(1,dt.height)*oe.rows)+1;return{col:Math.max(1,Math.min(oe.cols,Nt)),row:Math.max(1,Math.min(oe.rows,jt))}},ae=(ve,Ke={mode:null,remainder:0},et=null,dt=null)=>{const Nt=E.current,jt=Nt?Nt.getBoundingClientRect().height:mt,It=CT({alternateScreen:oe.buffer.active.type==="alternate",readonly:s,mouseTracking:_t()}),nn=It==="mouse"?"mouse":et||It,Yn=Ke.mode===nn?Ke.remainder+ve:ve,cn=NT({mode:nn,accumulated:Yn,threshold:nn==="page"?jt:mt});for(const Is of RT(cn,dt))Is.kind==="input"?Jt.sendInput(Is.seq):Jt.action(Is.name);return{mode:nn,remainder:cn.remainder}};let je=null,Xe=null,Pe=null,xt=null,gt=!1,Je=!1,Rt={mode:null,remainder:0},rt=null,ze=null,Wt=null,Sn=!1;const Se=750;let Me=0;const Ve=()=>{Wt&&clearTimeout(Wt),Wt=null},ct=(ve,Ke)=>{const dt=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),Nt=Math.max(0,Math.min(oe.cols-1,Math.floor((ve-dt.left)/Math.max(1,dt.width)*oe.cols))),jt=Math.max(0,Math.min(oe.rows-1,Math.floor((Ke-dt.top)/Math.max(1,dt.height)*oe.rows)));return{col:Nt,row:oe.buffer.active.viewportY+jt}},At=()=>{const et=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect().height/Math.max(1,oe.rows),dt=bt.querySelector(".nc-sel-handle"),Nt=dt?dt.getBoundingClientRect().height:0;return-.3*(Nt>0?Nt:et)},Ks=(ve,Ke)=>ct(ve.clientX,ve.clientY+Ke),Vs=ve=>{const et=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),dt=bt.getBoundingClientRect(),Nt=et.width/Math.max(1,oe.cols),jt=et.height/Math.max(1,oe.rows),It=Number(oe.buffer.active.viewportY)||0,nn=Math.max(0,Math.min(oe.rows-1,ve.row-It));A({left:`${et.left-dt.left+ve.col*Nt}px`,top:`${et.top-dt.top+nn*jt}px`,width:`${Nt}px`,height:`${jt}px`})},Zt=ve=>{if(Me=Date.now(),cs("touch"),Ve(),Sn=!1,gt=!1,Je||ve.touches.length!==1){Je=!0,gt=!0,Gt=null,A(null),je=null,Xe=null,Pe=null,xt=null;return}if(G.current){ve.preventDefault(),ve.stopPropagation();const et=ct(ve.touches[0].clientX,ve.touches[0].clientY),dt=oe.buffer.active.getLine(et.row),Nt=Aa({line:dt,col:et.col,side:"start",cols:oe.cols}),jt=g0({line:dt,col:Nt,cols:oe.cols});ze={row:et.row,col:jt.start};const It={row:et.row,col:jt.end};oe.clearSelection(),cs("touch"),ke(!0),Ee("end"),oe.select(jt.start,et.row,jt.end-jt.start+1),Vs(It);return}je=ve.touches[0].clientY,Xe=ve.touches[0].clientX,Pe=Xe,xt=je,Rt={mode:null,remainder:0},rt=null;const Ke={x:Xe,y:je};Wt=setTimeout(()=>{var nn;Wt=null,Sn=!0,gt=!0,Gt=null,G.current=!0,R==null||R(!0);const et=ct(Ke.x,Ke.y),dt=oe.buffer.active.getLine(et.row),Nt=Aa({line:dt,col:et.col,side:"start",cols:oe.cols}),jt=g0({line:dt,col:Nt,cols:oe.cols});ze={row:et.row,col:jt.start};const It={row:et.row,col:jt.end};oe.clearSelection(),cs("touch"),ke(!0),Ee("end"),oe.select(jt.start,et.row,jt.end-jt.start+1),Vs(It);try{(nn=navigator.vibrate)==null||nn.call(navigator,10)}catch{}je=null,Xe=null,rt=null,Rt={mode:null,remainder:0}},tT)},tn=ve=>{if(Sn&&ze&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const dt=ct(ve.touches[0].clientX,ve.touches[0].clientY),Nt=ze.row*oe.cols+ze.col,jt=dt.row*oe.cols+dt.col,It=Nt<=jt?"end":"start",nn=oe.buffer.active.getLine(dt.row),Yn=Aa({line:nn,col:dt.col,side:It,cols:oe.cols}),cn={row:dt.row,col:Yn},Is=cn.row*oe.cols+cn.col,ri=Nt<=Is?ze:cn;Ee(It),oe.select(ri.col,ri.row,Math.abs(Is-Nt)+1),Vs(cn);return}if(G.current&&ze&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const dt=ct(ve.touches[0].clientX,ve.touches[0].clientY),Nt=ze.row*oe.cols+ze.col,jt=dt.row*oe.cols+dt.col,It=Nt<=jt?"end":"start",nn=oe.buffer.active.getLine(dt.row),Yn=Aa({line:nn,col:dt.col,side:It,cols:oe.cols}),cn={row:dt.row,col:Yn},Is=cn.row*oe.cols+cn.col,ri=Nt<=Is?ze:cn;Ee(It),oe.select(ri.col,ri.row,Math.abs(Is-Nt)+1),Vs(cn);return}if(je===null||ve.touches.length!==1)return;ve.preventDefault(),ve.stopPropagation();const Ke=ve.touches[0];if(p0(Pe,xt,Ke.clientX,Ke.clientY)&&(gt=!0,Gt=null,Wt&&Ve()),rt===null&&(Math.abs(Ke.clientY-je)>8||Math.abs(Ke.clientX-Xe)>8)&&(rt=Math.abs(Ke.clientY-je)>Math.abs(Ke.clientX-Xe)),!rt)return;const et=Ke.clientY-je;je=Ke.clientY,Rt=ae(et,Rt,"scroll",q(Ke.clientX,Ke.clientY))},rn=()=>{Ve(),je=null,Xe=null,Pe=null,xt=null,ze=null,Sn=!1,gt=!1,Je=!1,A(null),ke(!1),Rt={mode:null,remainder:0},Me=Date.now()},bi=ve=>{if(Je){Gt=null,Ve(),(!ve.touches||ve.touches.length===0)&&rn();return}const Ke=ve.changedTouches&&ve.changedTouches[0];if(!gt&&!Sn&&!G.current&&Ke){const et={at:Date.now(),x:Ke.clientX,y:Ke.clientY},dt=_T(ne.current,Gt,et);Gt=dt.next,dt.open&&In()}rn()},mo=()=>{Gt=null,rn()};let rr={mode:null,remainder:0};const Vt=ve=>{ve.preventDefault(),ve.stopPropagation(),rr=ae(-ve.deltaY,rr,"scroll",q(ve.clientX,ve.clientY))};bt.addEventListener("touchstart",Zt,{passive:!1}),bt.addEventListener("touchmove",tn,{passive:!1,capture:!0}),bt.addEventListener("touchend",bi,{passive:!0}),bt.addEventListener("touchcancel",mo,{passive:!0});const rl=()=>{typeof window.matchMedia=="function"&&window.matchMedia(og).matches||!G.current&&ne.current==="double-tap"&&In()};bt.addEventListener("dblclick",rl);const ol=ve=>{(G.current||Sn)&&(ve.preventDefault(),ve.stopPropagation())};bt.addEventListener("contextmenu",ol,!0),bt.addEventListener("wheel",Vt,{passive:!1,capture:!0});let Ps=null;const al=ve=>{Date.now()-Me>=Se&&cs("mouse"),QM(ve)&&(ve.preventDefault(),ve.stopPropagation(),Ps={cell:ct(ve.clientX,ve.clientY),clientX:ve.clientX,clientY:ve.clientY,extendFrom:xe.current,dragged:!1})},ll=ve=>{var It;if(!Ps){(It=oe.hasSelection)!=null&&It.call(oe)&&_t()&&(ve.preventDefault(),ve.stopPropagation());return}if(ve.preventDefault(),ve.stopPropagation(),!Ps.dragged&&!p0(Ps.clientX,Ps.clientY,ve.clientX,ve.clientY))return;Ps.dragged=!0;const Ke=Ps.cell,et=ct(ve.clientX,ve.clientY),dt=Ke.row*oe.cols+Ke.col,Nt=et.row*oe.cols+et.col,jt=dt<=Nt?Ke:et;oe.select(jt.col,jt.row,Math.abs(Nt-dt)+1)},cl=ve=>{if(!Ps)return;ve.stopPropagation();const{cell:Ke,extendFrom:et,dragged:dt}=Ps;if(Ps=null,dt||!et)return;const Nt=nT({range:et,cell:Ke,cols:oe.cols});if(!Nt.moved)return;const jt=Nt[Nt.moved],It=oe.buffer.active.getLine(jt.row);jt.col=Aa({line:It,col:jt.col,side:Nt.moved,cols:oe.cols});const nn=v0({start:Nt.start,end:Nt.end},oe.cols);oe.select(nn.col,nn.row,nn.length)};bt.addEventListener("mousedown",al,!0),bt.addEventListener("mousemove",ll,!0),bt.addEventListener("mouseup",cl,!0);let Lr=null,ni={x:0,y:0,type:"touch"};const Ys=()=>{Lr&&(clearInterval(Lr),Lr=null)},Si=(ve,Ke,et)=>{if(!mn||!mn.fixed)return;const dt=mn.fixed,Nt=et==="mouse"?ct(ve,Ke):Ks({clientX:ve,clientY:Ke},At()),jt=oe.buffer.active.getLine(Nt.row),It={row:Nt.row,col:Aa({line:jt,col:Nt.col,side:mn.which,cols:oe.cols})},nn=Math.max(0,Number(oe.buffer.active.baseY||0)+oe.rows-1),Yn=rT({moving:It,fixed:dt,which:mn.which,cols:oe.cols,maxRow:nn}),cn=v0(m0(Yn,dt,oe.cols),oe.cols);oe.select(cn.col,cn.row,cn.length);const Is=Number(oe.buffer.active.viewportY)||0,ri=uT({visibleRow:Yn.row-Is,rows:oe.rows});Ys(),!(ri===0||oe.buffer.active.type==="alternate")&&(Lr=setInterval(()=>{const dl=Number(oe.buffer.active.viewportY)||0;if(oe.scrollLines(ri),(Number(oe.buffer.active.viewportY)||0)===dl){Ys();return}Si(ni.x-mn.offsetX,ni.y-mn.offsetY,ni.type)},130))},si=ve=>{mn&&(ve.preventDefault(),ni={x:ve.clientX,y:ve.clientY,type:ve.pointerType||ni.type},Si(ve.clientX-mn.offsetX,ve.clientY-mn.offsetY,ni.type))},Ar=()=>{mn=null,Ys(),Re(null),window.removeEventListener("pointermove",si),window.removeEventListener("pointerup",ii),window.removeEventListener("pointercancel",ii)},ii=()=>Ar();ee.current={startHandleDrag:(ve,Ke)=>{if(!oe.getSelectionPosition())return;Ke.preventDefault(),Ke.stopPropagation();const et=J.current&&J.current[ve],dt=bt.getBoundingClientRect();mn={which:ve,offsetX:et?Ke.clientX-(dt.left+et.left):0,offsetY:et?Ke.clientY-(dt.top+et.top):0,fixed:xe.current?ve==="start"?xe.current.end:xe.current.start:null},ni={x:Ke.clientX,y:Ke.clientY,type:Ke.pointerType||"touch"},Re(ve),Ee(ve),window.addEventListener("pointermove",si),window.addEventListener("pointerup",ii),window.addEventListener("pointercancel",ii)}};const xi=ve=>{!ZM(ve)||!(F.current&&F.current.term&&F.current.term.getSelection())||(ve.preventDefault(),ve.stopPropagation(),W.current&&W.current())};bt.addEventListener("keydown",xi,!0);const jr=()=>{$e.fit(),Jt.resize(oe.cols,oe.rows)};window.addEventListener("resize",jr);const Gs=window.visualViewport;let or=Gs&&Number(Gs.height);const Wc=()=>{const ve=Gs&&Number(Gs.height);Ut&&ne.current==="double-tap"&&Number.isFinite(or)&&Number.isFinite(ve)&&ve>or+80&&Ot(),or=ve,jr()};Gs&&(Gs.addEventListener("resize",Wc),Gs.addEventListener("scroll",jr));const ys=typeof navigator<"u"?navigator.virtualKeyboard:null,go=()=>{var ve;Ut&&ne.current==="double-tap"&&Number(((ve=ys==null?void 0:ys.boundingRect)==null?void 0:ve.height)||0)===0&&Ot()};(Ci=ys==null?void 0:ys.addEventListener)==null||Ci.call(ys,"geometrychange",go);let vo=null,_o=0;return typeof ResizeObserver<"u"&&(vo=new ResizeObserver(()=>{_o&&cancelAnimationFrame(_o),_o=requestAnimationFrame(jr)}),vo.observe(bt)),()=>{var ve,Ke,et;F.current=null,b&&(b.current=null),Q.current&&(clearTimeout(Q.current),Q.current=null),c&&(c.current=()=>!1),u&&(u.current=()=>!1),h&&(h.current=()=>!1),ls.dispose(),gn.dispose(),qs.dispose(),Vn.dispose(),Ys(),window.removeEventListener("pointermove",si),window.removeEventListener("pointerup",ii),window.removeEventListener("pointercancel",ii),ee.current={startHandleDrag:()=>{}},bt.removeEventListener("touchstart",Zt),bt.removeEventListener("touchmove",tn,{capture:!0}),bt.removeEventListener("touchend",bi),bt.removeEventListener("touchcancel",mo),bt.removeEventListener("dblclick",rl),bt.removeEventListener("contextmenu",ol,!0),Ve(),bt.removeEventListener("wheel",Vt,{capture:!0}),bt.removeEventListener("mousedown",al,!0),bt.removeEventListener("mousemove",ll,!0),bt.removeEventListener("mouseup",cl,!0),bt.removeEventListener("keydown",xi,!0),bt.removeEventListener("paste",re,!0),bt.removeEventListener("dragenter",Te,!0),bt.removeEventListener("dragover",Te,!0),bt.removeEventListener("drop",Ge,!0),window.removeEventListener("resize",jr),Gs&&(Gs.removeEventListener("resize",Wc),Gs.removeEventListener("scroll",jr)),(ve=ys==null?void 0:ys.removeEventListener)==null||ve.call(ys,"geometrychange",go),qt==null||qt.removeEventListener("blur",wn),(Ke=E.current)==null||Ke.removeEventListener("paste",Ft,!0),(et=E.current)==null||et.removeEventListener("keydown",Xt,!0),vo&&vo.disconnect(),_o&&cancelAnimationFrame(_o),Jt.close(),oe.dispose()}},[t,e,n,s,i,c,u,h,f,g,x]),w.useEffect(()=>{const oe=E.current,$e=F.current?F.current.term:null;if(!oe||!$e||!de){nt(null),pe(null),Ne(null);return}const kt=(oe.querySelector(".xterm-screen")||oe).getBoundingClientRect(),St=oe.getBoundingClientRect(),Lt=kt.width/Math.max(1,$e.cols),_t=kt.height/Math.max(1,$e.rows),pt=cT({range:de,viewportY:Number($e.buffer.active.viewportY)||0,rows:$e.rows,cols:$e.cols,cellWidth:Lt,cellHeight:_t,screenLeft:kt.left-St.left,screenTop:kt.top-St.top});nt(pt);let Ut=null;const Gt=de[fe==="end"?"end":"start"].row;typeof $e.buffer.active.getLine=="function"&&(Ut=$e.buffer.active.getLine(Number(Gt)));const Ot=Math.max(16,Math.round(_t*2)),ln=Ut?{...dT({range:de,side:fe,line:Ut,cols:$e.cols}),fontSize:Ot}:null;pe(ln);const In=ue!==null||Ae,qt=pt[fe==="end"?"end":"start"];if(!In||!ln||!qt||!qt.visible){Ne(null);return}const wn=(ln.before+ln.sel+ln.after).length,en=Lt*(Ot/Math.max(1,_t)),bn=Math.min(St.width-8,Math.round(wn*en)+16),Ft=Math.round(Ot*1.25)+12;Ne(aT({anchorLeft:qt.left,anchorTop:qt.top,hostWidth:St.width,hostHeight:St.height,bubbleWidth:bn,bubbleHeight:Ft}))},[de,Le,fe,ue,Ae]);const be=sT(ge),ye=w.useRef({}),ot=(oe,$e)=>{if(ue!==oe)return ye.current[oe]={flip:$e,ts:0},$e;const ut=ye.current[oe]||{flip:$e,ts:0};if(ut.flip===$e)return ye.current[oe]=ut,$e;const kt=Date.now();return kt-ut.ts<lT?ut.flip:(ye.current[oe]={flip:$e,ts:kt},$e)};return l.jsxs("div",{className:`nc-terminal${C?" selecting":""}`,children:[l.jsx("div",{className:"nc-terminal-host",ref:E}),N&&l.jsxs("div",{className:"nc-terminal-link-overlay",children:["riconnessione…",T>0?` (${T} byte in coda)`:""]}),M&&l.jsx("div",{className:"nc-touch-selection-caret",style:M,"aria-hidden":"true"}),de&&Be&&be.handles&&["start","end"].map(oe=>Be[oe].visible&&l.jsx("div",{className:`nc-sel-handle ${oe}${ue===oe?" dragging":""}${ot(oe,Be[oe].flip)?" flip":""}${oT({startLeft:Be.start.left,endLeft:Be.end.left})?" tight":""}`,style:{left:`${Be[oe].left}px`,top:`${Be[oe].top}px`},onPointerDown:$e=>ee.current.startHandleDrag(oe,$e),"aria-hidden":"true"},`nc-sel-handle-${oe}`)),de&&Y&&be.magnifier&&We&&l.jsx("div",{className:`nc-zoom-bubble${We.flipped?" flipped":""}`,style:{left:`${We.left}px`,top:`${We.top}px`},"aria-hidden":"true",children:l.jsxs("pre",{className:"nc-zoom-line",style:{fontSize:`${Y.fontSize}px`},children:[l.jsx("span",{children:Y.before}),l.jsx("span",{className:"nc-zoom-sel",children:Y.sel}),l.jsx("span",{children:Y.after})]})}),j&&l.jsx("div",{className:`nc-upload-state${j.error?" error":""}`,role:"status",children:j.error?j.error:j.done?p("attach-uploaded").replace("{n}",String(j.total||0)):p("attach-upload-progress").replace("{n}",String(j.current||0)).replace("{total}",String(j.total||0))}),(K||C)&&l.jsxs("div",{className:"nc-selection-tools",children:[K?l.jsx("button",{type:"button",onClick:wt,children:P||`${p("copy")} · ${eT(typeof navigator<"u"?navigator.userAgent:"")}`}):l.jsx("span",{children:p("select-drag")}),K&&Z&&l.jsx("span",{className:"nc-selection-held",children:p("selection-held")}),K&&!Z&&He&&l.jsx("span",{className:"nc-selection-changed",children:p("selection-changed")}),l.jsx("button",{type:"button",onClick:()=>{var oe,$e;($e=(oe=F.current)==null?void 0:oe.term)==null||$e.clearSelection(),D(""),me(!1),R==null||R(!1)},children:p("cancel")}),P===p("copy-manual")&&l.jsx("textarea",{readOnly:!0,value:K,onFocus:oe=>oe.target.select()})]})]})}function kc(t,e,n){const s=c=>Number.isInteger(c)&&c>0&&c<65536?c:0;if(t==null)return s(n);if(!Array.isArray(t))return 0;if(t.length===0)return s(n);const i=typeof t[0]=="string"?t[0]:null;return i?s((e&&typeof e=="object"?e:{})[i]):0}const LT=6901;function pv({cellId:t,panelUrl:e,route:n=[],panelPort:s=0,token:i,title:a,requestTimeoutMs:c=4e3}){const[u,h]=w.useState(t&&i?"requesting":"none"),[f,g]=w.useState(""),v=Array.isArray(n)?n.join("\0"):"",_=w.useMemo(()=>Array.isArray(n)?n:[],[v]),b=w.useRef(0),x=w.useCallback(async()=>{if(!t||!i||!e){h("none");return}const D=b.current+=1;h("requesting");const P=new AbortController,O=setTimeout(()=>P.abort(),c);try{const j=await SN(i,_,t,{signal:P.signal});if(clearTimeout(O),D!==b.current)return;if(j.ok){let z="/";try{z=new URL(e).pathname||"/"}catch{}const M=s?`http://127.0.0.1:${s}`:yn(_);g(`${M}/panel/${encodeURIComponent(t)}${z}?ticket=${encodeURIComponent(j.ticket)}`),h("ready")}else h(j.cause)}catch(j){if(clearTimeout(O),D!==b.current)return;h(j&&j.name==="AbortError"?"timeout":"unreachable")}},[t,e,_,s,i,c]),L=w.useCallback(()=>{h(D=>D==="ready"?"loaded":D)},[]),C=w.useCallback(()=>{h(D=>D==="ready"||D==="loaded"?"frame-error":D)},[]),R=w.useRef(null),S=w.useCallback(D=>{D&&(R.current=D,D.onload=L,D.onerror=C)},[L,C]);w.useEffect(()=>{x()},[x]);const E=w.useMemo(()=>{try{return Number(new URL(e).port)===LT}catch{return!1}},[e])&&_.length===0,[F,$]=w.useState(!1),[X,V]=w.useState("");w.useEffect(()=>{const D=P=>{const O=R.current;if(!O||!O.contentWindow||P.source!==O.contentWindow)return;let j=null;try{j=new URL(f,window.location.href).origin}catch{return}!j||P.origin!==j||!P.data||P.data.type!=="nc-panel-unreachable"||h(z=>z==="ready"||z==="loaded"?"unreachable":z)};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[f]);const G=w.useCallback(async()=>{if(!i||F)return;$(!0),V("");let D=!1;try{const P=await T1(i,!0);P&&P.ok===!1&&(V(P.error||"comando fallito"),D=!0)}catch(P){V(String(P&&P.message||P)),D=!0}$(!1),D||x()},[i,F,x]),ne=(D,P=!0,O=null)=>l.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[l.jsx("span",{children:p(D)}),P&&l.jsxs("span",{className:"nc-cellpanel-actions",children:[O,l.jsx("button",{type:"button",title:p("panel-retry"),onClick:()=>x(),children:p("panel-retry")})]})]}),K=E?l.jsx("button",{type:"button",disabled:F,onClick:G,children:p("panel-start-desktop")}):null;return u==="none"||u==="no-panel"?ne("panel-none",!1):u==="requesting"?l.jsx("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:l.jsx("span",{children:p("panel-checking")})}):u==="not-granted"?ne("panel-not-granted",!1):u==="node-refused"?ne("panel-node-refused",!1):u==="unauthorized"?ne("panel-unauthorized",!1):u==="denied"?ne("panel-denied"):u==="timeout"?ne("panel-timeout"):u==="unreachable"?l.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[l.jsxs("span",{children:[p("panel-unreachable"),X?` — ${X}`:""]}),l.jsxs("span",{className:"nc-cellpanel-actions",children:[K,l.jsx("button",{type:"button",title:p("panel-retry"),onClick:()=>x(),children:p("panel-retry")})]})]}):u==="frame-error"?ne("panel-frame-error",!0,K):l.jsxs(l.Fragment,{children:[u==="ready"&&l.jsx("div",{className:"nc-cellpanel-loading",role:"status",children:p("panel-frame-loading")}),l.jsx("iframe",{ref:S,className:"nc-cellpanel nc-cellpanel-frame","data-frame-state":u,src:f,title:a||p("panel"),allowFullScreen:!0})]})}const AT=1800*1e3;function cg(t,e,n=Date.now()){const s=Number(e);if(!Number.isFinite(s)||s<=0)return"";const i=n-s;if(i<0||i>AT)return"";if(i<60*1e3)return`${t("cell-activity")} ${t("cell-activity-now")}`;const a=Math.floor(i/6e4);return a<60?`${t("cell-activity")} ${a}m`:`${t("cell-activity")} ${Math.floor(a/60)}h`}function ug(t,e){if(!e||typeof e!="object")return"";const n=[];return Number.isInteger(e.contextFreePct)&&n.push(`${t("cell-tele-ctx")} ${e.contextFreePct}% ${t("cell-tele-free")}`),Number.isInteger(e.tier5hUsedPct)&&n.push(`${t("cell-tele-5h")} ${e.tier5hUsedPct}%`),Number.isInteger(e.tier7dUsedPct)&&n.push(`${t("cell-tele-7d")} ${e.tier7dUsedPct}%`),n.join(" · ")}function mv({row:t,token:e,panelPort:n=0,liveHost:s=null,onLiveHostApplied:i,source:a,onSourceChange:c,fontSize:u,readOnly:h=!1,chrome:f=!0}){const g=V=>c&&c(V),v=w.useRef(()=>{}),_=w.useRef(()=>!1),b=w.useRef(()=>{}),x=w.useRef(!1),[L,C]=w.useState(!1),[R,S]=w.useState(""),[I,E]=w.useState(!1),F=!!(s&&s.cell&&s.cell===t.cellName),$=async()=>{E(!0);const V=await eh({action:F?"remove":"use",cellId:t.cellName,route:t.route||[],token:e,api:{getLiveHost:G=>Xd(e,G),designateHostCell:(G,ne,K)=>Jd(e,G,ne,K),clearHostCell:(G,ne)=>Qd(e,G,ne)}});E(!1),S(p(V.messageKey).replace("{cell}",V.hostCell||t.cellName)),V.ok&&i&&i({route:t.route||[],hostCell:V.hostCell,revision:V.revision})},X=[["preview",p("cell-peek-preview")],["stream",p("cell-peek-stream")],...t.panelUrl?[["panel",p("cell-peek-panel")]]:[]];return l.jsxs(l.Fragment,{children:[f&&l.jsx("div",{className:"nc-peek-sorgenti",role:"tablist",children:X.map(([V,G])=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===V,className:`nc-peek-sorgente${a===V?" attiva":""}`,onClick:()=>g(V),children:G},V))}),f&&l.jsxs("div",{className:"nc-peek-host",children:[l.jsx("button",{type:"button",className:"nc-peek-host-btn",disabled:I,onClick:$,children:p(F?"live-host-action-remove":"live-host-action-use")}),R&&l.jsx("div",{className:"nc-peek-notice",role:"status",children:R})]}),a==="stream"?l.jsx("div",{className:"nc-peek-stream",children:l.jsx(pc,{session:t.session,node:t.node||void 0,token:e,readonly:h,takeSize:!1,focused:!0,sendRef:v,composerRef:_,actionRef:b,ctrlRef:x,setCtrlArmed:C,fontSize:u},`peek:${t.key}`)}):a==="panel"?l.jsx(pv,{cellId:t.cellName,panelUrl:t.panelUrl,route:t.route||[],panelPort:n,token:e,title:t.cellName}):l.jsxs(l.Fragment,{children:[l.jsx("pre",{className:"nc-peek-testo",children:t.preview||p("cell-peek-vuoto")}),[cg(p,t.activity),ug(p,t.telemetry)].filter(Boolean).join(" · ")&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:[cg(p,t.activity),ug(p,t.telemetry)].filter(Boolean).join(" · ")})]})]})}function wk({row:t,token:e,initialSource:n="preview",panelPort:s=0,onClose:i,liveHost:a=null,onLiveHostApplied:c}){const[u,h]=w.useState(n==="panel"&&!t.panelUrl?"preview":n);return l.jsx(F1,{title:t.cellName,subtitle:[t.nodeLabel,t.subtitle].filter(Boolean).join(" · "),onClose:i,children:l.jsx(mv,{row:t,token:e,panelPort:s,liveHost:a,onLiveHostApplied:c,source:u,onSourceChange:h})})}const Cc="nc_order_journal_v1",jT=50,_p="__corrupt",MT=200,TT=200,PT=["reason","key","position","source","target","note"],IT=["before","after","visible"],bk=t=>String(t).slice(0,TT),DT=t=>Array.isArray(t)?t.slice(0,MT).map(bk):void 0,oh=t=>{try{return t||globalThis.localStorage}catch{return null}};function OT(t){const e={t:Date.now()};for(const n of PT)t[n]!==void 0&&t[n]!==null&&(e[n]=bk(t[n]));for(const n of IT){const s=DT(t[n]);s&&(e[n]=s)}return e}function gv(t,e,n){const s=oh(n);if(!s||e===null||e===void 0)return!1;try{if(s.getItem(t+_p)===e)return!1;s.setItem(t+_p,e)}catch{return!1}return t!==Cc&&Ji({reason:"corrupt-preserved",key:t,note:`${String(e).length} caratteri conservati in ${t}${_p}`},s),!0}function dg(t){const e=oh(t);if(!e)return[];let n=null;try{n=e.getItem(Cc)}catch{return[]}if(n===null)return[];try{const s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return gv(Cc,n,e),[]}function Ji(t,e){const n=oh(e);if(!(!n||!t))try{const s=[...dg(n),OT(t)].slice(-jT);n.setItem(Cc,JSON.stringify(s))}catch{}}function BT(t){const e=oh(t);if(e)try{e.removeItem(Cc)}catch{}}function Rr(t,{parse:e,fallback:n,storage:s}={}){let i=s;try{i=i||globalThis.localStorage}catch{return n()}let a=null;try{a=i.getItem(t)}catch{return n()}if(a==null)return n();try{const c=e(JSON.parse(a));if(c!==void 0)return c}catch{}return gv(t,a,i),n()}function yi(t,e,{storage:n}={}){let s=n;try{s=s||globalThis.localStorage}catch(i){return i}try{const i=s.getItem(t);if(i!=null)try{JSON.parse(i)}catch{gv(t,i,s)}return s.setItem(t,JSON.stringify(e)),null}catch(i){return i instanceof Error?i:new Error(String(i))}}const $T=["all","pinned","active","off","technical"],Jo="nc_sidebar_views_v1",Qo="nc_sidebar_order_v1";function Sk(t){return $T.includes(t)?t:"all"}function zT(t,e=[],n="all"){const s=Sk(n);return s==="technical"?t.technical===!0:t.technical===!0?!1:s==="pinned"?e.includes(t.key):s==="active"?!!t.live:s==="off"?!t.live:!0}function FT(t,e,n=[],s=[]){const i=n.indexOf(t.key),a=n.indexOf(e.key),c=i===-1?Number.MAX_SAFE_INTEGER:i,u=a===-1?Number.MAX_SAFE_INTEGER:a,h=s.indexOf(t.key),f=s.indexOf(e.key),g=h===-1?Number.MAX_SAFE_INTEGER:h,v=f===-1?Number.MAX_SAFE_INTEGER:f;return c-u||g-v||+!!e.live-+!!t.live||+!!e.fresh-+!!t.fresh||Number(e.activity||0)-Number(t.activity||0)||String(t.label||"").localeCompare(String(e.label||""))||String(t.key||"").localeCompare(String(e.key||""))}function uc(t=globalThis.localStorage){return Rr(Qo,{storage:t,fallback:()=>({}),parse:e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const n={};for(const[s,i]of Object.entries(e).slice(0,64)){if(typeof s!="string"||!s||s.length>160||!Array.isArray(i))continue;const a=[...new Set(i.filter(c=>typeof c=="string"&&c&&c.length<=256))].slice(0,128);a.length&&(n[s]=a)}return n}})}function Ii(t,e){return Array.isArray(t==null?void 0:t[e])?t[e]:[]}function HT(t,e=globalThis.localStorage){return yi(Qo,t,{storage:e}),t}function UT(t,e,n,s,i=[]){if(typeof e!="string"||!e||n===s)return t;const a=[...new Set(i.filter(_=>typeof _=="string"&&_))];if(!a.includes(n)||!a.includes(s))return t;const c=Ii(t,e),u=[...c,...a.filter(_=>!c.includes(_))],h=u.indexOf(n),f=u.indexOf(s);u.splice(h,1);const g=u.indexOf(s),v=h<f?g+1:g;return u.splice(v,0,n),{...t,[e]:u}}function _d(t=globalThis.localStorage){return Rr(Jo,{storage:t,fallback:()=>({}),parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0})}function b0(t,e){var n,s;return{open:((n=t==null?void 0:t[e])==null?void 0:n.open)!==!1,filter:Sk((s=t==null?void 0:t[e])==null?void 0:s.filter)}}function WT(t,e=globalThis.localStorage){return yi(Jo,t,{storage:e}),t}function S0(t,e=""){const n=String(e||"").trim().toLocaleLowerCase();return n?[t.label,t.key,t.searchText].filter(Boolean).join(" ").toLocaleLowerCase().includes(n):!0}function co(t=[],e=[],n="all",s=[]){return[...t].filter(i=>zT(i,e,n)).sort((i,a)=>FT(i,a,e,s))}function zn(){return[w.useSyncExternalStore(N5,Cd,Cd),E5]}function Pd({cell:t,token:e,route:n=[],onConfirm:s,onClose:i}){var z,M;zn();const a=!!(t&&t.active),c=Array.isArray(n)?n.join("/"):"",[u,h]=w.useState([]),[f,g]=w.useState(!1);w.useEffect(()=>{let A=!0;return(async()=>{if(e)try{const N=await Qa(e,c?c.split("/"):[]);if(!A)return;if(g(N.provider==="builtin"&&(N.capabilities||[]).includes("edit")),N.provider==="builtin"&&(N.capabilities||[]).includes("definitions")){const U=await Yd(e,c?c.split("/"):[]);if(!A)return;const T=new Map((N.engines||[]).map(H=>[H.id,H]));h((U.engines||[]).map(H=>{var se,Q,Z,me,de,ie,xe;return{id:H.id,label:H.label||H.id,client:((se=H.managed)==null?void 0:se.client)||"",models:[...new Set([...((Q=T.get(H.id))==null?void 0:Q.models)||[],...((Z=H.managedInfo)==null?void 0:Z.models)||[]])].filter(Boolean),defaultModel:((me=H.managed)==null?void 0:me.model)||((de=H.managedInfo)==null?void 0:de.defaultModel)||"",policyDefault:((ie=H.managed)==null?void 0:ie.permissionPolicy)||((xe=H.managed)!=null&&xe.client&&H.managed.client==="claude"?"unsafe":"standard")}}))}}catch{}})(),()=>{A=!1}},[e,c]);const v=(t==null?void 0:t.engine)||((z=u[0])==null?void 0:z.id)||"",_=A=>(t==null?void 0:t.models)&&t.models[A]||"",b=A=>{const N=(t==null?void 0:t.permissionPolicies)&&t.permissionPolicies[A];if(N==="standard"||N==="unsafe")return N;const U=u.find(T=>T.id===A);return U?U.policyDefault:"standard"},[x,L]=w.useState(v),[C,R]=w.useState((t==null?void 0:t.model)||""),S=(t==null?void 0:t.permissionPolicy)==="standard"||(t==null?void 0:t.permissionPolicy)==="unsafe"?t.permissionPolicy:((M=t==null?void 0:t.permissionPolicies)==null?void 0:M[t==null?void 0:t.engine])||"",[I,E]=w.useState(S),[F,$]=w.useState((t==null?void 0:t.boot)??!0),[X,V]=w.useState(!1),[G,ne]=w.useState(null);w.useEffect(()=>{u.length&&(L(A=>A||v),R(A=>A||_((t==null?void 0:t.engine)||v)||""),E(A=>A==="standard"||A==="unsafe"?A:b((t==null?void 0:t.engine)||v)))},[u.length]);const K=w.useMemo(()=>u.find(A=>A.id===x)||null,[u,x]),D=!!(K&&["claude","codex","codex-vl","agy","kimi"].includes(K.client)),P=(K==null?void 0:K.client)==="shell";function O(A){L(A);const N=u.find(U=>U.id===A);R(_(A)||(N==null?void 0:N.defaultModel)||""),E(b(A))}async function j(A){A.preventDefault(),V(!0),ne(null);try{if(a)await s({action:"down",boot:F});else{const N=I==="standard"||I==="unsafe"?I:(K==null?void 0:K.policyDefault)||"standard";await s({action:"up",...f?{engine:x,model:C||"",...D?{permissionPolicy:N}:(K==null?void 0:K.client)==="pi"?{permissionPolicy:"standard"}:{}}:{},boot:F})}i()}catch(N){ne(String(N&&N.message||N)),V(!1)}}return l.jsx("div",{className:"nc-sheet-overlay nc-launch-overlay",onClick:i,children:l.jsxs("form",{className:"nc-sheet nc-power-sheet nc-launch-sheet",onClick:A=>A.stopPropagation(),onSubmit:j,children:[l.jsxs("div",{className:"nc-sheet-head",children:[l.jsx("b",{children:t==null?void 0:t.cell}),l.jsx("span",{className:"nc-sheet-state",children:p(a?"state-on":"state-off")})]}),a?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"nc-power-config",children:[l.jsx("span",{children:p("engine")}),l.jsx("b",{children:(t==null?void 0:t.engine)||"—"}),(t==null?void 0:t.model)&&l.jsxs("small",{children:[p("model"),": ",t.model]}),l.jsx("small",{children:p("power-on-hint")})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:F,onChange:A=>$(A.target.checked)}),p("remove-boot")]})]}):l.jsxs(l.Fragment,{children:[f&&u.length>0?l.jsxs("div",{className:"nc-launch-fields",children:[l.jsxs("label",{className:"nc-field",children:[p("engine"),l.jsx("select",{value:x,onChange:A=>O(A.target.value),children:u.map(A=>l.jsx("option",{value:A.id,children:A.label},A.id))})]}),!P&&l.jsxs("label",{className:"nc-field",children:[p("model"),l.jsx("input",{value:C,list:"nc-launch-models",placeholder:p("model-default"),onChange:A=>R(A.target.value)}),l.jsx("datalist",{id:"nc-launch-models",children:((K==null?void 0:K.models)||[]).map(A=>l.jsx("option",{value:A},A))})]}),D?l.jsxs("label",{className:"nc-field",children:[p("permissions"),l.jsxs("select",{value:I,onChange:A=>E(A.target.value),children:[l.jsx("option",{value:"standard",children:p("fleet-standard-permissions")}),l.jsx("option",{value:"unsafe",children:p("fleet-unsafe-permissions")})]})]}):l.jsx("small",{className:"nc-note",children:p("fleet-standard-permissions")}),D&&I==="unsafe"&&l.jsx("small",{className:"nc-err",children:p("fleet-unsafe-warning")}),l.jsx("small",{className:"nc-note",children:p(P?"fleet-shell-launch-help":"launch-engine-help")})]}):l.jsxs("div",{className:"nc-power-config",children:[l.jsx("span",{children:p("engine")}),l.jsx("b",{children:(t==null?void 0:t.engine)||"—"}),(t==null?void 0:t.model)&&l.jsxs("small",{children:[p("model"),": ",t.model]}),l.jsx("small",{children:p("launch-unavailable-hint")})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:F,onChange:A=>$(A.target.checked)}),p("boot-persist")]})]}),G&&l.jsx("div",{className:"nc-err",children:G}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:i,children:p("cancel")}),l.jsx("button",{type:"submit",className:"nc-btn primary",disabled:X,children:p(X?a?"power-stopping":"power-starting":a?"power-off":"save-and-start")})]})]})})}const x0=/^[a-z0-9-]{1,32}$/;function qa(t,e){const n=Array.isArray(t)?t:[];return n.length?`${n.map(encodeURIComponent).join("/")}:${e}`:String(e)}function qT(t,e,n){const s={};for(const i of Array.isArray(e)?e:[]){const a=Array.isArray(i==null?void 0:i.route)?i.route:typeof(i==null?void 0:i.name)=="string"?[i.name]:[];if(!a.length)continue;const c=a.join("/"),u=i.status==="up"||i.tunnel&&i.tunnel.status==="up",h=i.status==="passive"||i.tunnel&&i.tunnel.status==="passive";!u&&!h&&i.status!=="pending"&&!i.checking&&(s[c]=t&&t[c]||n)}return s}function hg(t,e,n,s=!1){return!t||!Array.isArray(t.cells)?[]:t.cells.map(i=>({...i,route:e,key:`${n}:${i.tmuxSession||i.cell}`,...s?{preserved:!0}:{}}))}function Vl(t,e,n){if(!t)return{};const s=fg(t);return!dc(t,s)||s!=="stale"?{}:{cells:hg(t,e,n,!0),fleetState:"stale",fleetAvailable:!1,cellsPreserved:!0}}function fg(t){return(t==null?void 0:t.fleetState)==="stale"?"stale":(t==null?void 0:t.fleetState)==="disabled"?"disabled":(t==null?void 0:t.available)===!0&&Array.isArray(t.cells)?"available":(t==null?void 0:t.available)===!1?"disabled":"stale"}function dc(t,e){return(e==="available"||e==="stale")&&Array.isArray(t==null?void 0:t.cells)}function k0(t,e){const n=t?e&&e.at:e&&e.lastGoodAt;return Number.isFinite(n)?n:null}function C0({nodes:t,topology:e,remote:n,down:s,fleet:i,aliases:a,pendingReads:c,previousGroups:u}={}){var x,L,C,R;const h=[],f=new Set,g=new Set,v=(S,I)=>!!(c&&(c.has(S)||c.has(`${S}#${I}`))),_=(S,I,E)=>Array.isArray(u)?u.find(F=>F.name===I&&F.instanceId===E&&(Array.isArray(F.route)?F.route.join("/"):"")===S):null;function b(S,I){const E=_(S,I.name,I.instanceId),F=v(S,"sessions"),$=v(S,"fleet"),X=(n==null?void 0:n[S])||(F&&E?{sessions:E.sessionsAvailable?E.sessions:void 0,at:E.verifiedAt,lastGoodAt:E.verifiedAt,...E.sessionsAvailable===!1&&E.cause?{cause:E.cause}:{}}:null),V=(i==null?void 0:i[S])||($&&E?{available:E.fleetAvailable,cells:E.cells,fleetState:E.fleetState,capabilities:E.capabilities,engines:E.engines,provider:E.fleetProvider,cellsPreserved:E.cellsPreserved,...E.fleetState==="stale"&&E.cause?{cause:E.cause}:{}}:null);return(F||$)&&(I.checking=!0,I.sessionsPending=F,I.fleetPending=$),{r:X,f:V,previous:E,pending:F||$,rereading:E&&(F||$)&&!(n!=null&&n[S])&&!(i!=null&&i[S])}}for(const S of Array.isArray(t)?t:[]){if(!S||typeof S.name!="string"||!x0.test(S.name)||S.direction==="inbound"&&S.shared!==!0)continue;const I=[S.name],E=S.name;f.add(E);const F=((x=S.tunnel)==null?void 0:x.status)||"unknown",$=F==="up",X={name:S.name,label:S.label||S.name,originalLabel:S.label||S.name,alias:null,route:I,direct:!0,instanceId:S.nodeId||null,shared:S.shared===!0,stale:S.stale===!0,tunnelStatus:F,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:S.health||null,direction:S.direction||"outbound",roles:S.roles||null,rolesKnown:S.rolesKnown===!0};if(S.nodeId&&g.add(S.nodeId),!S.nodeId&&S.paired===!1){h.push({...X,status:"needs-repair",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(((L=S.health)==null?void 0:L.auth)==="failed"||F==="degraded"&&((C=S.health)==null?void 0:C.status)==="degraded"){h.push({...X,status:"needs-repair",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(F==="passive"||((R=S.health)==null?void 0:R.status)==="passive"){h.push({...X,status:"passive",downSince:null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(!$){h.push({...X,status:"down",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}const{r:V,f:G,previous:ne,pending:K,rereading:D}=b(E,X);if(D){h.push({...ne,checking:!0,sessionsPending:X.sessionsPending,fleetPending:X.fleetPending});continue}const P=!!(V&&!V.error&&Array.isArray(V.sessions)),O=fg(G),j=O==="available"&&dc(G,O),z=dc(G,O);if(K&&!V&&!G){h.push({...X,status:(ne==null?void 0:ne.status)||"pending",pendingRead:!0,verifiedAt:(ne==null?void 0:ne.verifiedAt)??null});continue}if(!P&&!z){h.push({...X,status:K?(ne==null?void 0:ne.status)||"pending":"unreachable",cause:V&&V.cause||null});continue}const M=(P?V.sessions:[]).filter(U=>U&&typeof U.name=="string"&&U.name).map(U=>({...U,node:E,route:I,key:`${E}:${U.name}`})),A=hg(G,I,E),N=new Set(A.map(U=>U.tmuxSession).filter(Boolean));h.push({...X,status:"up",sessions:M,cells:A,unmanaged:M.filter(U=>!N.has(U.name)),fleetAvailable:j,fleetState:O,...G!=null&&G.cellsPreserved?{cellsPreserved:!0}:{},...V!=null&&V.cause||G!=null&&G.cause?{cause:(V==null?void 0:V.cause)||(G==null?void 0:G.cause)}:{},capabilities:G&&G.capabilities||[],engines:G&&G.engines||[],fleetProvider:G&&G.provider||null,sessionsAvailable:P,inventoryPartial:!P,verifiedAt:k0(P,V)})}for(const S of Array.isArray(e)?e:[]){if(!S||!Array.isArray(S.route)||S.route.length<1||S.route.some(N=>!x0.test(N)))continue;const I=S.route.join("/");if(f.has(I)||S.instanceId&&g.has(S.instanceId))continue;S.instanceId&&g.add(S.instanceId);const E=S.label||S.route.join(" › "),F=S.instanceId&&a&&typeof a[S.instanceId]=="string"?a[S.instanceId]:null,$={name:S.name,label:F||E,originalLabel:E,alias:F,route:[...S.route],direct:!1,instanceId:S.instanceId||null,shared:!0,stale:S.stale===!0,tunnelStatus:null,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:S.health||null,lastSeen:S.lastSeen||null};if(S.stale){h.push({...$,status:"offline",downSince:s&&s[I]||S.lastSeen||null,...Vl(i&&i[I],S.route,I)});continue}const{r:X,f:V,previous:G,pending:ne,rereading:K}=b(I,$);if(K){h.push({...G,checking:!0,sessionsPending:$.sessionsPending,fleetPending:$.fleetPending});continue}const D=!!(X&&!X.error&&Array.isArray(X.sessions)),P=fg(V),O=P==="available"&&dc(V,P),j=dc(V,P);if(ne&&!X&&!V){h.push({...$,status:(G==null?void 0:G.status)||"pending",pendingRead:!0,verifiedAt:(G==null?void 0:G.verifiedAt)??null});continue}if(!D&&!j){h.push({...$,status:ne?(G==null?void 0:G.status)||"pending":"unreachable",downSince:s&&s[I]||null,cause:X&&X.cause||null});continue}const z=(D?X.sessions:[]).filter(N=>N&&typeof N.name=="string"&&N.name).map(N=>({...N,node:I,route:S.route,key:`${I}:${N.name}`})),M=hg(V,S.route,I),A=new Set(M.map(N=>N.tmuxSession).filter(Boolean));h.push({...$,status:"up",sessions:z,cells:M,unmanaged:z.filter(N=>!A.has(N.name)),fleetAvailable:O,fleetState:P,...V!=null&&V.cellsPreserved?{cellsPreserved:!0}:{},...X!=null&&X.cause||V!=null&&V.cause?{cause:(X==null?void 0:X.cause)||(V==null?void 0:V.cause)}:{},capabilities:V&&V.capabilities||[],engines:V&&V.engines||[],fleetProvider:V&&V.provider||null,lastSeen:S.lastSeen||null,sessionsAvailable:D,inventoryPartial:!D,verifiedAt:k0(D,X)})}return h.sort((S,I)=>S.label.localeCompare(I.label))}const pg="nc_route_alias_v1",KT="nexuscrew-roster-preferences",E0="nc_pins",VT=/^[a-f0-9]{16,64}$/;let vv=new Map;const YT=t=>Array.isArray(t==null?void 0:t.route)&&t.route.length?t.route.join("/"):String((t==null?void 0:t.name)||"");function yp(t,e=vv){if(t==="local"||typeof t!="string")return t;const n=e.get(t);return n?`id:${n}`:t}const N0=(t,e,n)=>typeof t=="string"&&t.startsWith(`${e}:`)?`${n}:${t.slice(e.length+1)}`:t,R0=t=>[...new Set(t)];function wp(t,e){return Rr(t,{storage:e,fallback:()=>({}),parse:n=>n&&typeof n=="object"&&!Array.isArray(n)?n:void 0})}function ja(t,e=vv){const n={...t||{}};for(const[s,i]of e)t&&t[`id:${i}`]!==void 0&&(n[s]=t[`id:${i}`]);return n}function GT(t,{storage:e=globalThis.localStorage}={}){const n=new Map,s=new Map;for(const L of Array.isArray(t)?t:[]){const C=String((L==null?void 0:L.instanceId)||""),R=YT(L);if(!(VT.test(C)&&R)||n.has(R))continue;n.set(R,C);const S=L.status==="up"&&L.stale!==!0;(!s.has(C)||S&&!s.get(C).up)&&s.set(C,{name:R,up:S})}if(vv=n,!n.size)return!1;const i=wp(pg,e);let a=wp(Qo,e),c=wp(Jo,e),u=Rr(E0,{storage:e,fallback:()=>[],parse:L=>Array.isArray(L)?L:void 0});const h={...i},f={...a},g={...c};let v=[...u];const _={aliases:!1,orders:!1,views:!1,pins:!1};for(const[L,{name:C}]of s){const R=`id:${L}`,S=typeof i[L]=="string"?i[L]:"",I=S&&S!==C&&(!n.has(S)||n.get(S)===L)?S:"";I&&(v=R0([...v,...u.filter(E=>E.startsWith(`${I}:`)).map(E=>N0(E,I,C))]),_.pins=_.pins||v.length!==u.length);for(const[E,F,$]of[[a,f,"orders"],[c,g,"views"]]){const X=E[R]!==void 0?E[R]:I&&E[I]!==void 0?E[I]:E[C];if(X===void 0)continue;let V=X;$==="orders"&&Array.isArray(V)&&(V=R0(V.map(G=>I?N0(G,I,C):G))),JSON.stringify(F[R])!==JSON.stringify(V)&&(F[R]=V,_[$]=!0)}i[L]!==C&&(h[L]=C,_.aliases=!0),I&&Ji({reason:"route-renamed",key:L,note:`${I} -> ${C}`})}const b=[];_.pins&&b.push(yi(E0,v,{storage:e})),_.orders&&b.push(yi(Qo,f,{storage:e})),_.views&&b.push(yi(Jo,g,{storage:e})),_.aliases&&b.push(yi(pg,h,{storage:e}));const x=Object.values(_).some(Boolean);if(x)try{window.dispatchEvent(new Event(KT))}catch{}return x&&b.every(L=>!L)}const xk="nc_last_roster_v1",XT=64,JT=["cell","tmuxSession","engine","model","label","boot"],kk=t=>Rr(xk,{storage:t,fallback:()=>({}),parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0});function Ka(t,e,n=globalThis.localStorage){if(!t)return;const s={...kk(n)};!Array.isArray(e)||!e.length?delete s[t]:s[t]={at:Date.now(),cells:e.slice(0,XT).filter(i=>i&&typeof i.cell=="string").map(i=>Object.fromEntries(JT.filter(a=>i[a]!==void 0&&i[a]!==null).map(a=>[a,i[a]])))},yi(xk,s,{storage:n})}function _v(t,e=globalThis.localStorage){const n=t?kk(e)[t]:null;return!n||!Array.isArray(n.cells)?[]:n.cells.map(s=>({...s,tmux:!1,active:!1,preserved:!0,degraded:!1}))}function Ck(t,e={}){if(!t||typeof t!="object")return null;const n=typeof t.nodeId=="string"?t.nodeId:"";if(!n)return null;const s=typeof t.label=="string"&&t.label.trim()||typeof t.cell=="string"&&t.cell.trim()||n,i=Array.isArray(e.route)?[...e.route]:[];return{kind:"vl",nodeId:n,name:n,label:s,cell:t.cell??null,paired:!!t.pairedAt,online:!!t.online,lastSeen:t.lastSeen??null,generation:t.generation??null,version:t.version??null,health:t.health??null,session:t.session??null,capabilities:Array.isArray(t.capabilities)?t.capabilities:[],inflight:t.inflight??null,lastAck:t.lastAck??null,canManage:!!t.canManage,route:i,isLocal:i.length===0,ownerInstanceId:typeof e.instanceId=="string"?e.instanceId:null,ownerLabel:typeof e.label=="string"&&e.label?e.label:null}}function QT(t){var n;const e=[];for(const s of Array.isArray(t)?t:[]){if(!s||s.kind!=="vl"||!s.nodeId)continue;const i=s.online===!0,a=i&&((n=s.session)==null?void 0:n.attached)===!0,c=s.ownerInstanceId||"local";e.push({kind:"vl",name:`vl-${s.nodeId.slice(0,8)}`,label:s.label,route:Array.isArray(s.route)?[...s.route]:[],instanceId:null,direct:!1,status:i?"up":"offline",downSince:i?null:s.lastSeen??null,sessions:a?[{key:`vl:${c}:${s.nodeId}`,name:s.session.profile,attached:!0}]:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:s.health??null,stale:s.stale===!0,fleetState:s.stale===!0?"stale":null,peer:s})}return e}function Ek(t,e){const n=t&&Array.isArray(t.nodes)?t.nodes:[],s=new Set([e]),i=[];for(const a of n){const c=a&&typeof a.instanceId=="string"?a.instanceId:"";if(!c||s.has(c)||a.stale===!0||!Array.isArray(a.route)||a.route.length===0)continue;s.add(c);const u=typeof a.label=="string"&&a.label||typeof a.name=="string"&&a.name||a.route.join(" › ");i.push({instanceId:c,route:[...a.route],label:u})}return i}const ZT=/fleet\.json/;function yv({fs:t=null,error:e=null}={}){if(e)return{kind:"stale"};if(!t)return{kind:"stale"};if(t.available===!0)return{kind:"data",cells:t.cells||[],capabilities:t.capabilities||[]};const n=typeof t.reason=="string"?t.reason:"";return typeof t.migrationCode=="string"&&t.migrationCode?{kind:"disabled",reason:n||null}:ZT.test(n)?{kind:"stale"}:{kind:"disabled",reason:n||null}}const Nk={baseMs:4e3,capMs:6e4},Rk="peer-assente",Lk="peer-nega",Ak="rotta-inesistente";function bp(t){const e=t&&t.status;return e===403?Lk:e===404?Ak:Rk}function eP(t,{baseMs:e,capMs:n}=Nk){return!Number.isFinite(t)||t<1?0:Math.min(e*2**(t-1),n)}function L0(t,e,n){const s=t&&t[e];return!s||!(s.failures>=1)?!0:n>=s.nextAtMs}function A0(t,e,n,s,i=Nk){const c=(t&&t[e]||{failures:0}).failures+1;return{...t,[e]:{failures:c,cause:n,nextAtMs:s+eP(c,i)}}}function j0(t,e){if(!t||!(e in t))return t;const n={...t};return delete n[e],n}const tP=4e3,wv=600*1e3,jk="nc-sticky-owners-v1";function nP(){try{const t=localStorage.getItem(jk);if(!t)return null;const e=JSON.parse(t);return!e||!Array.isArray(e.nodes)||!Array.isArray(e.topology)?null:e}catch{return null}}function sP(t){try{localStorage.setItem(jk,JSON.stringify(t))}catch{}}function Zu(t,e,n,s,i){if(!e){for(const c of t.values())c.data={...c.data,stale:!0};return t}const a=new Map(n.map(c=>[s(c),c]));for(const[c,u]of t)a.has(c)?(u.data=a.get(c),u.missingSince=null,a.delete(c)):(u.missingSince??(u.missingSince=i),i-u.missingSince>wv?t.delete(c):u.data={...u.data,stale:!0});for(const[c,u]of a)t.set(c,{data:u,missingSince:null});return t}function bv(t,e=!0,n=0){const[s,i]=w.useState([]),a=w.useRef([]),c=w.useRef({}),u=w.useRef({}),h=w.useRef({remote:{},fleet:{}}),f=w.useRef(null),g=w.useRef(null),v=w.useRef(new Map),_=w.useRef(new Map),b=w.useRef(new Set),x=w.useRef(Zd()),L=w.useRef(null);return w.useEffect(()=>{if(!e||!t){i([]);return}let C=!0;const R=f.current!==null&&f.current!==t;f.current!==t&&(f.current=t,u.current={},h.current={remote:{},fleet:{}},v.current.clear(),_.current.clear(),b.current.clear(),c.current={},a.current=[],i([]));const S={instanceId:"",nodes:new Map,topology:new Map},I=R?null:nP();if(I){S.instanceId=I.instanceId||"";for(const $ of I.nodes)S.nodes.set($.name,{data:$,missingSince:null});for(const $ of I.topology)S.topology.set($.route.join("/"),{data:$,missingSince:null})}async function E(){const $=x.current,X=Date.now(),V=$.begin();if(V===null)return;const G=new AbortController;L.current=G;const ne={timeoutMs:S1,signal:G.signal},K=()=>C&&$.isCurrent(V);let D=[],P=[],O={},j="",z=!1,M=!1,A="pending",N="pending";const U={},T={},H=new Set,se=new Set,Q=new Set;let Z=new Map;const me=[],de=()=>{Z=new Map([...P.filter(Ne=>Array.isArray(Ne.route)).map(Ne=>[Ne.route.join("/"),Ne.instanceId]),...D.map(Ne=>[Ne.name,Ne.nodeId])].filter(([,Ne])=>typeof Ne=="string"&&Ne))},ie=Ne=>{const ge=Z.get(Ne),st=ge?_v(`id:${ge}`):[];return st.length?{available:!1,cells:st,fleetState:"stale"}:null},xe=()=>{if(!K()||!j)return!1;const Ne=[],ge=Date.now();for(const[He,qe]of _.current){if(ge-qe.at>wv){_.current.delete(He);continue}const wt=He.slice(3),W=v.current.get(wt);if(qe.ownerInstanceId!=null&&W!==void 0&&W!==qe.ownerInstanceId){_.current.delete(He);continue}const ee=b.current.has(He.slice(3)),J=qe.round!==V||qe.identityUnknown===!0||ee;for(const be of qe.peers)Ne.push({...be,stale:J})}const st=a.current,Ze=C0({nodes:D,topology:P,remote:U,fleet:T,aliases:O,down:c.current,pendingReads:H,previousGroups:st});c.current=qT(c.current,Ze,Math.floor(Date.now()/1e3));const De=[...C0({nodes:D,topology:P,remote:U,fleet:T,aliases:O,down:c.current,pendingReads:H,previousGroups:a.current}),...QT(Ne)];return GT(De),a.current=De,i(De),!0};let Be=[],nt=[];const Le=()=>{var Ne;if(K()&&j){z?Zu(S.nodes,!0,Be,ge=>ge&&ge.name,X):A==="error"&&Zu(S.nodes,!1,Be,ge=>ge&&ge.name,X),M?Zu(S.topology,!0,nt,ge=>Array.isArray(ge&&ge.route)?ge.route.join("/"):"",X):N==="error"&&Zu(S.topology,!1,nt,ge=>Array.isArray(ge&&ge.route)?ge.route.join("/"):"",X),D=[...S.nodes.values()].map(ge=>ge.data),P=[...S.topology.values()].map(ge=>ge.data),de();for(const[ge,st]of Z){const Ze=v.current.get(ge);Ze&&Ze!==st&&(delete h.current.remote[ge],delete h.current.fleet[ge],delete u.current[ge],delete u.current[`vl:${ge}`],delete c.current[ge],_.current.delete(`vl:${ge}`)),v.current.set(ge,st)}for(const ge of v.current.keys())if(!Z.has(ge)){const st=_.current.get(`vl:${ge}`);st&&(st.identityUnknown=!0)}b.current=new Set(P.filter(ge=>!ge.stale&&Array.isArray(ge.route)&&ge.route.length>0&&!Z.has(ge.route.join("/"))).map(ge=>ge.route.join("/")));for(const ge of D){if(((Ne=ge.tunnel)==null?void 0:Ne.status)==="up")continue;const st=h.current.fleet[ge.name];st&&!T[ge.name]&&(T[ge.name]={...st,available:!1,fleetState:"stale"})}for(const ge of P){if(!ge.stale||!Array.isArray(ge.route)||!ge.route.length)continue;const st=ge.route.join("/"),Ze=h.current.fleet[st];Ze&&!T[st]&&(T[st]={...Ze,available:!1,fleetState:"stale"})}(z||M)&&sP({instanceId:S.instanceId,savedAt:X,nodes:[...S.nodes.values()].map(ge=>ge.data),topology:[...S.topology.values()].map(ge=>ge.data)}),Y(),xe()}},Ie=(Ne,ge)=>{K()&&(A=Ne?"success":"error",z=Ne,Be=Ne?ge:[],Le())},ue=(Ne,ge)=>{K()&&(N=Ne?"success":"error",M=Ne,nt=Ne?ge:[],Le())},Re=Ne=>{K()&&(j=Ne&&typeof Ne.instanceId=="string"?Ne.instanceId:"",j&&(S.instanceId!==j||g.current!==j)?(S.instanceId!==j&&(S.nodes.clear(),S.topology.clear()),a.current=[],c.current={},u.current={},h.current={remote:{},fleet:{}},v.current.clear(),_.current.clear(),b.current.clear()):j&&(S.instanceId=j),g.current=j||null,S.instanceId=j,Le())};function fe(){const Ne=[{instanceId:j||null,route:[],label:null},...Ek({nodes:P},j)];for(const ge of Ne){const st=`${ge.instanceId}:${ge.route.join("/")}`;if(Q.has(st))continue;Q.add(st);const Ze=`vl:${ge.route.join("/")}`;me.push((async()=>{if(L0(u.current,Ze,X))try{const De=await j1(t,ge.route,{signal:G.signal});if(!K())return;const He=v.current.get(ge.route.join("/"));if(He!==void 0&&He!==ge.instanceId||b.current.has(ge.route.join("/")))return;u.current=j0(u.current,Ze);const qe=[];for(const wt of De.nodes||[]){const W=Ck(wt,ge);W&&qe.push(W)}_.current.set(Ze,{peers:qe,ownerInstanceId:ge.instanceId??null,at:X,round:V}),xe()}catch(De){if(!K())return;const He=v.current.get(ge.route.join("/"));if(He!==void 0&&He!==ge.instanceId||b.current.has(ge.route.join("/")))return;u.current=A0(u.current,Ze,bp(De),X)}})())}}async function Ee(Ne){const ge=Ne.join("/"),st=h.current.remote[ge]||null;if(!L0(u.current,ge,X)){H.delete(`${ge}#sessions`),H.delete(`${ge}#fleet`);const He=u.current[ge];U[ge]={error:"unreachable",cause:He&&He.cause||null,lastGoodAt:st?st.at:null};const qe=h.current.fleet[ge]||ie(ge);qe&&(T[ge]={...qe,available:!1,fleetState:"stale"});return}H.add(`${ge}#sessions`),H.add(`${ge}#fleet`);const Ze=(async()=>{let He=!1;try{const qe=await Xg(t,Ne,ne);if(!K())return;He=!0,U[ge]={...qe,at:X},h.current.remote[ge]={payload:qe,at:X}}catch(qe){if(!K())return;U[ge]={error:"unreachable",cause:bp(qe),lastGoodAt:st?st.at:null}}finally{H.delete(`${ge}#sessions`)}u.current=He?j0(u.current,ge):A0(u.current,ge,U[ge].cause,X),xe()})(),De=(async()=>{const He=h.current.fleet[ge]||ie(ge);try{const qe=await Qa(t,Ne,ne);if(!K())return;const wt=yv({fs:qe});wt.kind==="data"?(T[ge]={...qe,available:!0,cells:wt.cells,fleetState:"available"},Z.get(ge)&&Ka(`id:${Z.get(ge)}`,wt.cells)):wt.kind==="disabled"?(T[ge]={...qe,available:!1,cells:[],fleetState:"disabled"},Z.get(ge)&&Ka(`id:${Z.get(ge)}`,[])):T[ge]={...He||{},available:!1,cells:Array.isArray(He==null?void 0:He.cells)?He.cells:[],fleetState:"stale",...qe!=null&&qe.reason?{reason:qe.reason}:{}},h.current.fleet[ge]=T[ge]}catch(qe){if(!K())return;T[ge]={...He||{},available:!1,cells:Array.isArray(He==null?void 0:He.cells)?He.cells:[],fleetState:"stale",cause:bp(qe)},h.current.fleet[ge]=T[ge]}H.delete(`${ge}#fleet`),xe()})();await Promise.allSettled([Ze,De])}function Y(){var st,Ze;if(!K()||!j)return;fe();const Ne=new Set(D.map(De=>De.name)),ge=De=>{const He=De.join("/");se.has(He)||(se.add(He),me.push(Ee(De)))};for(const De of D)z&&!De.stale&&((st=De.tunnel)==null?void 0:st.status)==="up"&&(De.nodeId||De.paired!==!1)&&(De.direction!=="inbound"||De.shared===!0)?ge([De.name]):A==="pending"&&!De.stale&&((Ze=De.tunnel)==null?void 0:Ze.status)==="up"&&(H.add(`${De.name}#sessions`),H.add(`${De.name}#fleet`));for(const De of P)if(!De.stale&&Array.isArray(De.route)&&De.route.length>0&&!(De.route.length===1&&Ne.has(De.route[0]))){const He=De.route.join("/");M?ge(De.route):N==="pending"&&(H.add(`${He}#sessions`),H.add(`${He}#fleet`))}}const pe=DN(t,ne).then(Ne=>{Ie(!0,Array.isArray(Ne.nodes)?Ne.nodes:[])},()=>{Ie(!1,[])}),Ae=M1(t,ne).then(Ne=>{ue(!0,Array.isArray(Ne.nodes)?Ne.nodes:[])},()=>{ue(!1,[])}),ke=UN(t,ne).then(Ne=>{K()&&(O=Ne&&typeof Ne.aliasesByInstanceId=="object"?Ne.aliasesByInstanceId:{},xe())},()=>{}),We=Pc(t,[],ne).then(Ne=>{Re(Ne)},()=>{});try{await Promise.allSettled([pe,Ae,ke,We]),await Promise.allSettled(me)}finally{$.isCurrent(V)&&$.end(V)}}E();const F=setInterval(E,tP);return()=>{C=!1,clearInterval(F),x.current.reset(),L.current&&L.current.abort()}},[t,e,n]),s}const M0=52,T0=14;function Gi({position:t,itemKey:e,label:n,onMove:s,onStep:i,canMove:a=()=>!0,scope:c="roster"}){const u=w.useRef(null),h=w.useRef(0),[f,g]=w.useState(!1),v=()=>{var R,S,I,E;const C=u.current;(S=(R=C==null?void 0:C.over)==null?void 0:R.classList)==null||S.remove("nc-roster-over"),(E=(I=C==null?void 0:C.source)==null?void 0:I.classList)==null||E.remove("nc-roster-dragging"),h.current&&cancelAnimationFrame(h.current),h.current=0},_=(C=!1)=>{const R=u.current;if(!R)return;const S=R.target;v(),u.current=null,g(!1);try{R.handle.releasePointerCapture(R.pointerId)}catch{}C&&S&&S!==e&&a(e,S)&&s(e,S)},b=(C,R)=>{var V,G,ne,K,D,P,O,j,z;const S=u.current;if(!S)return;S.x=C,S.y=R;const I=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",E=(G=(V=document.elementFromPoint(C,R))==null?void 0:V.closest)==null?void 0:G.call(V,I),F=c==="node"?(ne=E==null?void 0:E.dataset)==null?void 0:ne.nodeOrderKey:(K=E==null?void 0:E.dataset)==null?void 0:K.rosterKey,X=(c==="node"||((D=E==null?void 0:E.dataset)==null?void 0:D.position)===t)&&F&&F!==e&&a(e,F);S.over!==(X?E:null)&&((O=(P=S.over)==null?void 0:P.classList)==null||O.remove("nc-roster-over"),S.over=X?E:null,(z=(j=S.over)==null?void 0:j.classList)==null||z.add("nc-roster-over")),S.target=X?F:null},x=()=>{const C=u.current;if(!C){h.current=0;return}const R=C.container;if(R){const S=R.getBoundingClientRect(),I=C.y<S.top+M0?-T0:C.y>S.bottom-M0?T0:0;I&&(R.scrollTop+=I,b(C.x,C.y))}h.current=requestAnimationFrame(x)};w.useEffect(()=>{const C=S=>{S.key==="Escape"&&u.current&&(S.preventDefault(),_(!1))},R=()=>_(!1);return window.addEventListener("keydown",C),window.addEventListener("blur",R),()=>{window.removeEventListener("keydown",C),window.removeEventListener("blur",R),v(),u.current=null}},[e,t,c]);const L=C=>{var E;if(C.pointerType==="mouse"&&C.button!==0)return;C.preventDefault(),C.stopPropagation(),C.currentTarget.focus({preventScroll:!0});const R=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",S=C.currentTarget.closest(R),I=C.currentTarget.closest(".nc-side-scroll, .nc-home-scroll, .nc-cell-switcher-list");u.current={pointerId:C.pointerId,handle:C.currentTarget,source:S,container:I,target:null,over:null,x:C.clientX,y:C.clientY},(E=S==null?void 0:S.classList)==null||E.add("nc-roster-dragging");try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}g(!0),h.current=requestAnimationFrame(x)};return l.jsx("button",{type:"button",className:`nc-roster-handle${f?" active":""}`,"aria-label":`${p("reorder")} ${n}`,"aria-keyshortcuts":"ArrowUp ArrowDown",title:p("reorder-help"),onClick:C=>{C.preventDefault(),C.stopPropagation()},onDragStart:C=>C.preventDefault(),onKeyDown:C=>{C.key!=="ArrowUp"&&C.key!=="ArrowDown"||(C.preventDefault(),C.stopPropagation(),i(C.key==="ArrowUp"?-1:1))},onPointerDown:L,onPointerMove:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),b(C.clientX,C.clientY))},onPointerUp:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),_(!0))},onPointerCancel:()=>_(!1),onLostPointerCapture:()=>{u.current&&_(!1)},children:"↕"})}const Mk="nc_pins";function to(){return Rr(Mk,{fallback:()=>[],parse:t=>Array.isArray(t)?t:void 0})}function Sv(t){return yi(Mk,t)}function iP(t,e){const n=t.includes(e)?t.filter(s=>s!==e):[...t,e];return{next:n,error:Sv(n)}}function P0(t,e){if(!Array.isArray(t)||!t.includes(e))return{next:Array.isArray(t)?t:[],error:null};const n=t.filter(s=>s!==e);return{next:n,error:Sv(n)}}function rP(t,e,n){if(!t.includes(e)||!t.includes(n)||e===n)return t;const s=[...t],i=s.indexOf(e),a=s.indexOf(n);s.splice(i,1);const c=s.indexOf(n);return s.splice(i<a?c+1:c,0,e),Sv(s),s}function oP(t,e,n){const s=t.indexOf(e);return[s===-1?1e9:s,-(n||0)]}function aP(t,e){return t[0]-e[0]||t[1]-e[1]}const mg="nexuscrew-roster-preferences",lP=new Set(["nc_pins",Qo,Jo,pg]),Ma=()=>{try{window.dispatchEvent(new Event(mg))}catch{}},cP=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Sp=t=>e=>cP(e,t)?e:t;function xv(){const[t,e]=w.useState(to),[n,s]=w.useState(_d),[i,a]=w.useState(uc),[c,u]=w.useState(null),[h,f]=w.useState(null);w.useEffect(()=>{if(!h)return;const I=setTimeout(()=>f(null),8e3);return()=>clearTimeout(I)},[h]),w.useEffect(()=>{const I=E=>{E&&E.type==="storage"&&E.key&&!lP.has(E.key)||(e(Sp(to())),a(Sp(uc())),s(Sp(_d())))};return window.addEventListener("storage",I),window.addEventListener(mg,I),()=>{window.removeEventListener("storage",I),window.removeEventListener(mg,I)}},[]);const g=I=>{const E=to(),F=iP(E,I);e(F.next),Ji({reason:F.error?"pin-write-failed":"pin",key:I,before:E,after:F.next,note:F.error?String(F.error.message||F.error):void 0}),Ma()},v=I=>{const E=to(),F=P0(E,I);return e(F.next),u(F.error?{key:I,message:F.error.message||String(F.error)}:null),Ji({reason:F.error?"unpin-write-failed":"unpin",key:I,before:E,after:F.next}),Ma(),F.error},_=()=>{if(!c)return;const I=P0(to(),c.key);e(I.next),u(I.error?{...c,message:I.error.message||String(I.error)}:null),Ma()},b=()=>u(null),x=I=>b0(ja(n),I),L=(I,E)=>{const F=_d(),$=yp(I),X=WT({...F,[$]:{...b0(ja(F),I),...E}});s(X),Ma()},C=(I,E)=>t.includes(I)===t.includes(E);function R(I,E,F,$){var A,N;const X=(A=$.find(U=>U.partial))==null?void 0:A.partial;if(X){f({reason:X,position:I,at:Date.now()}),Ji({reason:"reorder-blocked",position:yp(I),source:E,target:F,note:X});return}f(null);const V=to(),G=V.includes(E),ne=V.includes(F);if(G!==ne)return;if(G){const U=rP(V,E,F);e(U),Ji({reason:"move-pin",source:E,target:F,before:V,after:U}),Ma();return}const K=uc(),D=yp(I),P=ja(K),O=((N=$.find(U=>U.key===E))==null?void 0:N.technical)===!0,j=co($,V,O?"technical":"all",Ii(P,I)).map(U=>U.key),z=UT({...K,[D]:Ii(P,I)},D,E,F,j),M={...K,[D]:z[D]};HT(M),Ji({reason:"move",position:D,source:E,target:F,before:Ii(P,I),after:z[D],visible:j}),a(M),Ma()}function S(I,E,F,$){var O;if($.some(j=>j.partial)){R(I,E,E,$);return}const X=to(),V=ja(uc()),G=((O=$.find(j=>j.key===E))==null?void 0:O.technical)===!0,ne=X.includes(E),K=co($,X,G?"technical":"all",Ii(V,I)).map(j=>j.key).filter(j=>X.includes(j)===ne),D=K.indexOf(E),P=K[D+F];D>=0&&P&&R(I,E,P,$)}return{pins:t,views:ja(n),orders:ja(i),togglePin:g,removePin:v,pinError:c,retryPinPersist:_,clearPinError:b,reorderBlocked:h,viewFor:x,updateView:L,canMoveRoster:C,moveRoster:R,stepRoster:S}}const ah="nc_node_order_v1",uP=/^[a-f0-9]{16,64}$/;function Ho(t){if(uP.test(String((t==null?void 0:t.instanceId)||"")))return`id:${t.instanceId}`;const e=Array.isArray(t==null?void 0:t.route)?t.route.filter(n=>typeof n=="string"&&n):[];return e.length?`route:${e.map(encodeURIComponent).join("/")}`:typeof(t==null?void 0:t.name)=="string"&&t.name?`name:${encodeURIComponent(t.name)}`:""}function gg(t=globalThis.localStorage){return Rr(ah,{storage:t,fallback:()=>[],parse:e=>Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&n&&n.length<=192))].slice(0,128):void 0})}function dP(t,e=globalThis.localStorage){return yi(ah,t,{storage:e}),t}function I0(t=[],e=[]){const n=new Map(e.map((s,i)=>[s,i]));return t.map((s,i)=>({group:s,index:i})).sort((s,i)=>{const a=n.has(Ho(s.group))?n.get(Ho(s.group)):Number.MAX_SAFE_INTEGER,c=n.has(Ho(i.group))?n.get(Ho(i.group)):Number.MAX_SAFE_INTEGER;return a-c||s.index-i.index}).map(({group:s})=>s)}function hP(t,e,n,s=[]){if(!e||!n||e===n)return t;const i=s.map(Ho).filter(Boolean);if(!i.includes(e)||!i.includes(n))return t;const a=[...t,...i.filter(f=>!t.includes(f))],c=a.indexOf(e),u=a.indexOf(n);a.splice(c,1);const h=a.indexOf(n);return a.splice(c<u?h+1:h,0,e),a}const vg="nexuscrew-node-preferences";function fP(){try{window.dispatchEvent(new Event(vg))}catch{}}function kv(){const[t,e]=w.useState(gg);w.useEffect(()=>{const a=()=>e(gg());return window.addEventListener("storage",a),window.addEventListener(vg,a),()=>{window.removeEventListener("storage",a),window.removeEventListener(vg,a)}},[]);const n=a=>I0(a,t),s=(a,c,u)=>e(h=>{const f=hP(h,a,c,u);return dP(f),fP(),f});return{order:t,groupsFor:n,moveNode:s,stepNode:(a,c,u)=>{const h=I0(u,t).map(Ho),f=h.indexOf(a),g=h[f+c];f>=0&&g&&s(a,g,u)},nodeKey:Ho}}function Tk({pinError:t,onRetry:e,onDismiss:n}){return t?l.jsxs("div",{className:"nc-pin-error",role:"alert",children:[l.jsx("span",{className:"nc-pin-error-text",children:"★ preferenza non salvata"}),l.jsx("button",{type:"button",className:"nc-pin-error-retry",onClick:e,children:"riprova"}),l.jsx("button",{type:"button",className:"nc-pin-error-close",onClick:n,"aria-label":"chiudi avviso",children:"×"})]}):null}function lh({item:t,pins:e,hostByRoute:n,route:s}){const i=(n||{})[Cs(s)]||{},a=Ed({hostCell:i.hostCell??null,threadStatus:i.threadStatus,pins:e,item:t}),c=I5(a);return{state:a,live:!!c,favorite:a==="favorite",filled:a!=="none",titleKey:c||"pin",action:a===H1?"removePin":"addPin"}}async function Cv({view:t,itemKey:e,togglePin:n,removePin:s}){return t.action==="removePin"?(s(e),{ok:!0}):(n(e),{ok:!0})}function oo({item:t,cellName:e,route:n=[],pins:s=[],hostByRoute:i={}}={}){const a=lh({item:t,pins:s,hostByRoute:i,route:n}),c=(i||{})[Cs(n)]||{};return{pinned:a.favorite,isLive:!!c.hostCell&&c.hostCell===e}}function Ev({isLive:t,pinned:e,canBoot:n,boot:s,alive:i,handlers:a={}}={}){const c=[];return typeof a.onToggleLive=="function"&&c.push({id:"live",kind:"action",on:!!t,labelKey:t?"cell-actions-live-remove":"cell-actions-live-assign",run:a.onToggleLive}),typeof a.onTogglePin=="function"&&c.push({id:"pin",kind:"action",on:!!e,labelKey:e?"cell-actions-unpin":"cell-actions-pin",run:a.onTogglePin}),n&&typeof a.onToggleBoot=="function"&&c.push({id:"boot",kind:"switch",on:!!s,labelKey:"cell-actions-boot",run:()=>a.onToggleBoot(!s)}),i&&typeof a.onWatchLive=="function"&&c.push({id:"watch",kind:"action",on:!1,labelKey:"cell-actions-watch",run:a.onWatchLive}),c}function Pk({items:t=[],busy:e=!1,onRun:n}){return l.jsx("div",{className:"nc-cellactions",role:"menu","aria-busy":e||void 0,children:t.map(s=>{const i=s.descKey?p(s.descKey):s.descText;return l.jsxs("button",{type:"button",role:s.kind==="switch"?"menuitemcheckbox":"menuitem","aria-checked":s.kind==="switch"?s.on?"true":"false":void 0,className:`nc-cellactions-voce${s.on?" on":""}`,disabled:e,"data-cellaction":s.id,onClick:a=>{a.stopPropagation(),n?n(s):s.run()},children:[s.kind==="switch"?l.jsx("span",{className:`nc-cellactions-toggle${s.on?" on":""}`,"aria-hidden":"true"}):null,l.jsxs("span",{className:"nc-cellactions-testo",children:[p(s.labelKey),i?l.jsx("small",{className:"nc-cellactions-desc",children:i}):null]})]},s.id)})})}function Ik({aperto:t,refGuscio:e,onClose:n}){w.useEffect(()=>{const s=a=>{e.current&&!e.current.contains(a.target)&&n()},i=a=>{a.key==="Escape"&&n()};return document.addEventListener("pointerdown",s),document.addEventListener("keydown",i),()=>{document.removeEventListener("pointerdown",s),document.removeEventListener("keydown",i)}},[t,e,n])}function Dk({anchorRect:t,items:e,busy:n,onClose:s}){const i=w.useRef(null);Ik({aperto:!0,refGuscio:i,onClose:s});const a=t?{top:Math.min(t.bottom+6,window.innerHeight-8),left:Math.max(8,Math.min(t.right-210,window.innerWidth-218))}:void 0;return l.jsx("div",{className:"nc-cellactions-popover",style:a,ref:i,"data-testid":"cell-actions-popover",children:l.jsx(Pk,{items:e,busy:n,onRun:c=>{c.run(),s()}})})}function Nv({cellName:t,items:e,busy:n,onClose:s}){const i=w.useRef(null);return Ik({aperto:!0,refGuscio:i,onClose:s}),l.jsx("div",{className:"nc-cellactions-velo","data-testid":"cell-actions-sheet",children:l.jsxs("div",{className:"nc-cellactions-foglio",role:"dialog","aria-modal":"true","aria-label":p("cell-actions-title").replace("{cell}",t||""),ref:i,children:[l.jsxs("div",{className:"nc-cellactions-testa",children:[l.jsx("span",{className:"nc-cellactions-titolo",children:p("cell-actions-title").replace("{cell}",t||"")}),l.jsx("button",{type:"button",className:"nc-cellactions-chiudi",onClick:s,title:p("close"),"aria-label":p("close"),children:"✕"})]}),l.jsx(Pk,{items:e,busy:n,onRun:a=>{a.run(),s()}})]})})}const pP="native",mP="tmux";function gP(t){return typeof t!="string"||!t?null:t.startsWith("codex-vl")?pP:mP}function Va({liveHost:t,cells:e=[],localNodeId:n="",ownerId:s=null}={}){const i=t&&typeof t.hostCell=="string"&&t.hostCell?t.hostCell:null,a=i&&(Array.isArray(e)?e:[]).find(u=>u&&u.cell===i)||null,c=a&&typeof a.engine=="string"&&a.engine?a.engine:null;return{hostCell:i,cell:i,known:!!a,engine:c,mode:gP(c),state:i?Y1(t&&t.threadStatus):_c,remote:!!(s&&n&&s!==n),lease:t&&(t.hostLease||(t.host&&typeof t.host.lease=="string"?t.host.lease:null))||null}}function vP(t){const e=t&&t.state?t.state:_c;return{modeKey:t&&t.mode?`live-host-mode-${t.mode}`:null,stateKey:`live-host-state-${e}`}}function Rv(t){const e=t&&t.state?t.state:_c;return e==="thread-active"?"active":e==="thread-present"?"present":e===_c?"none":e==="thread-unknown"?"unknown":"designated"}function ao(t,e=Math.floor(Date.now()/1e3)){if(!t)return"";const n=e-t;return n<0||n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function Ok(t){const e=t||{};return!(e.sessionsAvailable===!1||typeof e.status=="string"&&e.status!=="up")}function Qi(t){return t.status==="up"&&!Ok(t)?p("node-sessions-unverified"):t.status==="passive"?p("node-passive"):t.status==="down"?t.downSince?p("tunnel-down-since").replace("{t}",ao(t.downSince)):p("tunnel-down"):t.status==="unreachable"?t.cause===Lk?p("peer-cause-nega"):t.cause===Ak?p("peer-cause-rotta"):t.cause===Rk?p("peer-cause-assente"):p("node-unreachable"):t.status==="offline"?t.lastSeen?p("node-offline-seen").replace("{t}",ao(t.lastSeen)):p("node-offline"):t.status==="needs-repair"?p("node-needs-repair"):""}function Bk(t,{passive:e=null}={}){return t?t.status==="passive"?e:t.status==="healthy"?"on":"warn":null}function Id(t){return t&&(t.detail||t.status)||""}const _P="restrict,port-forwarding,permitopen=";function yP(t){const e=t&&typeof t.hint=="string"&&t.hint.trim()||"",n=t&&typeof t.authorizedKeys=="string"&&t.authorizedKeys.trim()||"";if(n){const i=e.indexOf(n);return{note:i>=0?e.slice(0,i).replace(/[:\s]+$/,""):e,line:n}}if(!e)return null;const s=e.indexOf(_P);return s<0?{note:e,line:""}:{note:e.slice(0,s).replace(/[:\s]+$/,""),line:e.slice(s).trim()}}function Dd(t,e,n=globalThis.localStorage){if(!(t!=null&&t.outbox)||t.outbox.count<1)return!1;const s=Number(n.getItem(x1(e))||0);return t.outbox.latest>s}function ch(t,e={},{autorevole:n=!0}={}){const s=t||{},i=`${s.engine||""}${s.key?`·${s.key}`:""}`,a=[i,s.model&&s.model!==i?s.model:""].filter(Boolean).join(" · ");if(!s.tmux)return{working:!1,subtitle:String(a||p("cell-off")).trim()};const c=e.attivita&&typeof e.attivita=="object"?e.attivita.stato:null;if(c==="lavora"||c==="attesa"){const u=p(c==="attesa"?"cell-permission":"cell-working"),h=String(e.status||"").trim(),f=!h||/^working(?:\.{3}|…)?$/i.test(h);return{working:!0,stato:c,subtitle:c==="lavora"&&!f?`${u} · ${h}`:u}}if(c==="ferma")return{working:!1,stato:"ferma",subtitle:p("cell-stopped")};if(!n)return{working:!1,stato:"ignoto",subtitle:[p("cell-unknown"),a].filter(Boolean).join(" · ")};if(e.working===!0){const u=String(e.status||"").trim();return{working:!0,stato:"ignoto",subtitle:!u||/^working(?:\.{3}|…)?$/i.test(u)?p("cell-unknown"):`${p("cell-unknown")} · ${u}`}}return e.working===!1?{working:!1,stato:"ignoto",subtitle:p("cell-unknown")}:{working:!1,stato:"ignoto",subtitle:String(e.preview||s.preview||p("cell-on")).trim()}}function $k(t,e){return[...new Set([t.engine,t.model,t.key,e.preview,t.preview,e.status].filter(Boolean).map(String))].join(" ")}function zk({sessionsOk:t=!0,fleetStale:e=!1,cellCount:n=0}={}){return t?e&&!n?"fleet":null:"sessions"}function Lv(t,e,n,s=globalThis.localStorage,{autorevole:i=!0,fleetStale:a=!1}={}){const c=zk({sessionsOk:i,fleetStale:a,cellCount:Array.isArray(t)?t.length:0});return Fk([...(Array.isArray(t)?t:[]).map(u=>{const h=n.get(u.tmuxSession)||{},f=qa([],u.tmuxSession),g=ch(u,h,{autorevole:i});return{type:"cell",value:u,key:f,label:u.cell,live:!!u.tmux,fresh:Dd(h,f,s),activity:h.activity||0,working:g.working,stato:g.stato,subtitle:g.subtitle,searchText:$k(u,h)}}),...(Array.isArray(e)?e:[]).map(u=>{const h=qa([],u.name);return{type:"session",value:u,key:h,label:u.name,live:!0,technical:u.technical===!0,fresh:Dd(u,h,s),activity:u.activity||0,searchText:`${u.preview||""} ${u.cmd||""}`}})],c)}const Fk=(t,e)=>e?t.map(n=>({...n,partial:e})):t;function mc(t,e=globalThis.localStorage){const n=t||{},s=Array.isArray(n.route)?n.route:[],i=Ok(n),a=new Map((n.sessions||[]).map(h=>[h.name,h])),c=[...(n.cells||[]).map(h=>{const f=a.get(h.tmuxSession)||{},g=qa(s,h.tmuxSession||h.cell),v=ch(h,f,{autorevole:i});return{type:"cell",value:h,key:g,label:h.cell,live:!!h.tmux&&!h.preserved,fresh:Dd(f,g,e),activity:f.activity||h.activity||0,working:v.working,stato:v.stato,subtitle:v.subtitle,searchText:$k(h,f)}}),...(n.unmanaged||[]).map(h=>{const f=qa(s,h.name);return{type:"session",value:h,key:f,label:h.name,live:!0,technical:h.technical===!0,fresh:Dd(h,f,e),activity:h.activity||0,searchText:`${h.preview||""} ${h.cmd||""}`}})],u=zk({sessionsOk:n.sessionsAvailable!==!1,fleetStale:n.fleetState==="stale",cellCount:(n.cells||[]).length});return{route:s,rawItems:Fk(c,u)}}const uh=9,_g=.2,wP=/^[a-z0-9-]{1,32}(?:\/[a-z0-9-]{1,32}){0,3}$/,Ya=/^[a-f0-9]{16,64}$/,yg=t=>wP.test(t)&&new Set(t.split("/")).size===t.split("/").length;function Cr(t){if(typeof t=="string"&&t){const e=t.indexOf(":");if(e<0)return{session:t};const n=t.slice(0,e),s=t.slice(e+1);return!yg(n)||!s?null:{session:s,node:n}}if(t&&typeof t=="object"&&typeof t.session=="string"&&t.session){const e=t.ownerId===void 0?void 0:typeof t.ownerId=="string"&&Ya.test(t.ownerId)?t.ownerId:null;return e===null?null:t.node===void 0||t.node===null||t.node===""?{session:t.session,...e?{ownerId:e}:{}}:typeof t.node=="string"&&yg(t.node)?{session:t.session,node:t.node,...e?{ownerId:e}:{}}:null}return null}function $t(t){const e=Cr(t);return e?e.node?`${e.node}:${e.session}`:e.session:""}const Hk=9,Uk=24,_i=11,Wk=t=>{const e=Number(t);return e>=Hk&&e<=Uk?e:_i};function uo(){return{columns:[]}}function _s(t){return t.columns.flatMap(e=>e.tiles.map(n=>$t(n)))}function bP(t){const e=[],n=Math.max(0,...t.columns.map(s=>s.tiles.length));for(let s=0;s<n;s+=1)for(const i of t.columns)i.tiles[s]&&e.push($t(i.tiles[s]));return e}const Oi=t=>({columns:t.columns.map(e=>({width:e.width,tiles:e.tiles.map(n=>({...n}))}))});function Ec(t,e,n,s){const i=Cr(e);if(!i||_s(t).includes($t(i))||_s(t).length>=uh)return t;const a=Oi(t),c={session:i.session,height:1,fontSize:_i,...s||{}};if(i.node&&(c.node=i.node),i.ownerId&&(c.ownerId=i.ownerId),n==="end")return a.columns.push({width:1,tiles:[c]}),a;if(n&&typeof n.col=="number"&&typeof n.row=="number"&&a.columns[n.col])return a.columns[n.col].tiles.splice(n.row,0,c),a;if(n&&typeof n.col=="number"){const u=Math.max(0,Math.min(a.columns.length,n.col));return a.columns.splice(u,0,{width:1,tiles:[c]}),a}return a.columns.push({width:1,tiles:[c]}),a}function qk(t,e){const n=$t(e);if(!n||_s(t).includes(n)||_s(t).length>=uh)return t;const s=_s(t).length+1,i=Math.ceil(Math.sqrt(s));if(t.columns.length>=i){let g=0;for(let v=1;v<t.columns.length;v+=1)t.columns[v].tiles.length<t.columns[g].tiles.length&&(g=v);return Ec(t,e,{col:g,row:t.columns[g].tiles.length})}const a=[...bP(t),n],c=new Map(t.columns.flatMap(g=>g.tiles.map(v=>[$t(v),v]))),u=Cr(e),h=t.columns.length?t.columns.reduce((g,v)=>g+(Number(v.width)||1),0)/t.columns.length:1,f=Array.from({length:i},(g,v)=>{var _;return{width:((_=t.columns[v])==null?void 0:_.width)||h,tiles:[]}});return a.forEach((g,v)=>{const _=Cr(g);if(!_)return;const b=c.get(g)||(g===n?u:{})||{},x={session:_.session,height:b.height||1,fontSize:b.fontSize||_i};_.node&&(x.node=_.node),b.ownerId&&(x.ownerId=b.ownerId),b.unavailable===!0&&(x.unavailable=!0),b.stale===!0&&(x.stale=!0),f[v%i].tiles.push(x)}),{columns:f.filter(g=>g.tiles.length)}}function Kk(t,e){const n=Cr(e);if(!n)return t;const s=$t(n);if(!s||_s(t).includes(s)||_s(t).length>=uh)return t;const i=e&&typeof e=="object"?e:{},a={height:Math.max(_g,Number(i.height)||1),fontSize:Wk(i.fontSize),...n.ownerId?{ownerId:n.ownerId}:{}};if(!t.columns.length)return Ec(t,n,null,a);let c=0;for(let u=1;u<t.columns.length;u+=1)t.columns[u].tiles.length<t.columns[c].tiles.length&&(c=u);return Ec(t,n,{col:c,row:t.columns[c].tiles.length},a)}function Nc(t,e){const n=$t(e),s=Oi(t);for(const i of s.columns)i.tiles=i.tiles.filter(a=>$t(a)!==n);return s.columns=s.columns.filter(i=>i.tiles.length>0),s}function SP(t,e,n){const s=$t(e);if(!_s(t).includes(s))return t;const i=t.columns.flatMap(a=>a.tiles).find(a=>$t(a)===s);return Ec(Nc(t,s),s,n,{fontSize:i.fontSize,height:i.height,...i.ownerId?{ownerId:i.ownerId}:{},...i.unavailable===!0?{unavailable:!0}:{},...i.stale===!0?{stale:!0}:{}})}function xP(t,e){if(!(e instanceof Map)||e.size===0)return t;let n=!1;const s=Oi(t);for(const i of s.columns)for(const a of i.tiles){const c=e.get($t(a));if(!c)continue;const u=Cr(c);u&&(a.session=u.session,u.node?a.node=u.node:delete a.node,u.ownerId&&(a.ownerId=u.ownerId),n=!0)}return n?Pi(s):t}const Vk=120,Yk=60,hc=[1/3,.5,2/3],wg=16;function Gk(t,e,n,s){if(!(e>0))return .5;const i=Math.max(0,Math.min(.5,n/e));let a=t/e;if(a=Math.max(i,Math.min(1-i,a)),s){for(const c of hc)if(Math.abs(a-c)*e<=wg){a=c;break}}return a}function D0(t,e,n,s,i={}){const a=Oi(t),c=a.columns[e],u=a.columns[e+1];if(!c||!u)return t;const h=a.columns.reduce((_,b)=>_+(Number(b.width)||1),0),f=(Number(c.width)||1)+(Number(u.width)||1),g=(Number(n)||0)*(f/(h||1)),v=i.half===!0?.5:Gk(s,g,i.minPx??Vk,i.snap!==!1);return c.width=f*v,u.width=f*(1-v),a}function O0(t,e,n,s,i,a={}){const c=Oi(t),u=c.columns[e],h=u&&u.tiles[n],f=u&&u.tiles[n+1];if(!h||!f)return t;const g=u.tiles.reduce((x,L)=>x+(Number(L.height)||1),0),v=(Number(h.height)||1)+(Number(f.height)||1),_=(Number(s)||0)*(v/(g||1)),b=a.half===!0?.5:Gk(i,_,a.minPx??Yk,a.snap!==!1);return h.height=v*b,f.height=v*(1-b),c}function kP(t,e,n){if(!e||!n||e===n)return t;const s=Oi(t);let i=null,a=null;for(const f of s.columns)for(let g=0;g<f.tiles.length;g+=1){const v=$t(f.tiles[g]);v===e&&!i?i={col:f,i:g}:v===n&&!a&&(a={col:f,i:g})}if(!i||!a)return t;const c=i.col.tiles[i.i],u=a.col.tiles[a.i],h=f=>{const g={...f};return delete g.height,g};return i.col.tiles[i.i]={...h(u),height:c.height},a.col.tiles[a.i]={...h(c),height:u.height},s}const $c=6,zc=t=>{let{x:e,y:n,w:s,h:i}=t;return s=Math.max(.05,Math.min(1,Number(s)||.3)),i=Math.max(.05,Math.min(1,Number(i)||.3)),e=Math.max(0,Math.min(1-s,Number(e)||0)),n=Math.max(0,Math.min(1-i,Number(n)||0)),{x:e,y:n,w:s,h:i}};function Av(t,e){for(const n of t.columns)for(let s=0;s<n.tiles.length;s+=1)if($t(n.tiles[s])===e)return{tile:n.tiles[s]};return null}function CP(t,e,n){const s=Oi(t),i=$t(e);if(NP(s).length>=$c)return t;const a=Av(s,i);return!a||a.tile.float?t:(a.tile.float=zc(n||{}),s)}function EP(t,e){const n=Oi(t),s=Av(n,$t(e));return!s||!s.tile.float?t:(delete s.tile.float,n)}function B0(t,e,n){const s=Oi(t),i=Av(s,$t(e));return!i||!i.tile.float?t:(i.tile.float=zc(n),s)}function NP(t){return t.columns.flatMap(e=>e.tiles).filter(e=>e.float).map(e=>$t(e))}function Od(t){const e=[],n=[];for(const s of t.columns){const i=[];for(const a of s.tiles)if(a.float){const c={session:a.session,...a.float,fontSize:a.fontSize};a.node&&(c.node=a.node),a.ownerId&&(c.ownerId=a.ownerId),e.push(c)}else i.push(a);i.length&&n.push({width:s.width,tiles:i})}return{grid:{columns:n},floating:e}}const Xk=["x","y","w","h","fontSize"],bg=(t,e)=>Math.abs((Number(t)||0)-(Number(e)||0))<1e-9,Jk=(t,e)=>Xk.every(n=>bg(t[n],e[n]));function RP(t,e,n){if(!t)return n;const s={...n};for(const i of Xk)bg(n[i],t[i])&&!bg(e[i],t[i])&&(s[i]=e[i]);return{...s,...zc(s)}}function LP(t,e,n){const s=h=>new Map((Array.isArray(h)?h:[]).map(f=>[$t(f),f]).filter(([f])=>f)),i=s(t),a=s(e),c=s(n),u=[];for(const[h,f]of c)!a.has(h)&&i.has(h)&&Jk(f,i.get(h))||u.push(a.has(h)?RP(i.get(h),a.get(h),f):f);for(const[h,f]of a)c.has(h)||i.has(h)||u.push(f);return u.slice(0,$c)}function AP(t,e,n,s,i){const a=_=>Array.isArray(_.floating)?_.floating:[],c=(_,b)=>a(_).some(x=>$t(x)===b)?"float":_s(_.grid).includes(b)?"grid":"",u=(_,b)=>_.columns.flatMap(x=>x.tiles).find(x=>$t(x)===b),h=new Set([...a(n),...a(s),...a(i)].map(_=>$t(_)).filter(Boolean));let f=t,g=Array.isArray(e)?e:[];const v=(_,b)=>a(_).find(x=>$t(x)===b);for(const _ of h){const b=c(i,_),x=c(n,_),C=b!==x||b==="float"&&!Jk(v(i,_),v(n,_))?b:c(s,_);if(C!=="grid"&&_s(f).includes(_)&&(f=Nc(f,_)),C!=="float"&&(g=g.filter(R=>$t(R)!==_)),C==="grid"&&!_s(f).includes(_)){const R=u(s.grid,_)||u(i.grid,_)||u(n.grid,_);R&&(f=Kk(f,R))}if(C==="float"&&!g.some(R=>$t(R)===_)){const R=[s,i,n].map(S=>a(S).find(I=>$t(I)===_)).find(Boolean);R&&(g=[...g,R])}}return{grid:f,floating:g.slice(0,$c)}}function jP(t,e){const n=s=>{const{grid:i,floating:a}=Od(s||uo());return JSON.stringify({g:i.columns.map(c=>[c.width,c.tiles.map(u=>[$t(u),u.ownerId||"",u.height,u.fontSize])]),f:a.map(c=>[$t(c),c.ownerId||"",c.x,c.y,c.w,c.h,c.fontSize])})};return n(t)===n(e)}function Sg(t,e){let n=t;for(const s of Array.isArray(e)?e:[]){const i={session:s.session};s.node&&(i.node=s.node),s.ownerId&&(i.ownerId=s.ownerId);const a=$t(i);if(!a||_s(n).includes(a))continue;const c=Oi(n);c.columns.length||c.columns.push({width:1,tiles:[]});let u=0;for(let f=1;f<c.columns.length;f+=1)c.columns[f].tiles.length<c.columns[u].tiles.length&&(u=f);const h={session:i.session,height:1,fontSize:s.fontSize||_i,float:zc(s)};i.node&&(h.node=i.node),i.ownerId&&(h.ownerId=i.ownerId),c.columns[u].tiles.push(h),n=c}return n}function MP(t,e,n,s){if(!(t.columns[e]&&t.columns[e].tiles[n]))return t;const a=Oi(t),c=a.columns[e].tiles[n],u=Number(c.fontSize)||_i;return c.fontSize=Math.max(Hk,Math.min(Uk,u+(Number(s)||0))),a}function TP(t,e,n,s){const i=t.columns[e];if(!i||!i.tiles[n])return null;switch(s){case"left":return{col:e};case"right":return{col:e+1};case"top":return{col:e,row:n};case"bottom":return{col:e,row:n+1};default:return null}}function Pi(t){if(!t||!Array.isArray(t.columns))return uo();const e=t.columns.map(a=>({width:Math.max(_g,Number(a&&a.width)||1),tiles:(Array.isArray(a&&a.tiles)?a.tiles:[]).filter(c=>c&&typeof c.session=="string"&&c.session).filter(c=>c.node==null||typeof c.node=="string"&&yg(c.node)).filter(c=>c.ownerId==null||typeof c.ownerId=="string"&&Ya.test(c.ownerId)).map(c=>{const u={session:c.session,height:Math.max(_g,Number(c.height)||1),fontSize:Wk(c.fontSize)};return c.node!=null&&(u.node=c.node),c.ownerId!=null&&(u.ownerId=c.ownerId),c.float&&(u.float=zc(c.float)),u})})).filter(a=>a.tiles.length>0),n=new Set;let s=0,i=0;for(const a of e)a.tiles=a.tiles.filter(c=>{const u=$t(c);return n.has(u)||(c.float?i>=$c:s>=uh)?!1:(n.add(u),c.float?i+=1:s+=1,!0)});return{columns:e.filter(a=>a.tiles.length>0)}}function PP(t,e){let n=Pi(t);const s=Pi(e),i=new Map;for(const c of s.columns)for(const u of c.tiles)i.set($t(u),u);for(const c of n.columns)for(let u=0;u<c.tiles.length;u+=1){const h=$t(c.tiles[u]);i.has(h)&&(c.tiles[u]=i.get(h))}const a=new Map;for(const c of s.columns){const u=c.tiles.map(h=>$t(h)).sort().join("|");a.has(u)||a.set(u,c.width)}for(const c of n.columns){const u=c.tiles.map(f=>$t(f)).sort().join("|"),h=a.get(u);h!=null&&(c.width=h)}for(const[c,u]of i)_s(n).includes(c)||(n=Kk(n,u));return n}const Qk=/^[a-z0-9-]{1,32}$/,IP=/^[A-Za-z0-9._-]{1,32}$/,DP=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/,OP=320;function xg(t){return typeof t=="string"&&Qk.test(t)}const BP=64;function Ga(t){if(typeof t!="string")return!1;const e=t.trim();return e.length>0&&e.length<=BP&&!/[\x00-\x1f\x7f]/.test(e)}function ho(t){return String(t??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/g,"")||"node"}function Zk(t){if(typeof t!="string"||!t||t.length>OP||t.startsWith("-")||/[\0-\x20\x7f]/.test(t))return!1;if(!t.includes("@"))return/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/.test(t);const e=t.indexOf("@");return e<=0||e!==t.lastIndexOf("@")?!1:IP.test(t.slice(0,e))&&DP.test(t.slice(e+1))}function $0(t){if(t===""||t===null||t===void 0)return null;const e=String(t).trim();if(!/^[0-9]{1,5}$/.test(e))return;const n=Number(e);return Number.isInteger(n)&&n>=1&&n<=65535?n:void 0}function $P({name:t,ssh:e,sshPort:n,remotePort:s}={}){const i=typeof t=="string"?t.trim():t,a=typeof e=="string"?e.trim():e;if(!xg(i))return{ok:!1,error:"err-node-name"};if(!Zk(a))return{ok:!1,error:"err-ssh"};const c=$0(n);if(c===void 0)return{ok:!1,error:"err-ssh-port"};const u=$0(s);if(u===void 0)return{ok:!1,error:"err-node-port"};const h={name:i,ssh:a};return c!==null&&(h.sshPort=c),u!==null&&(h.remotePort=u),{ok:!0,value:h}}function zP(t,e){if(!t||!e||e<t)return null;const n=Math.floor((e-t)/1e3);return n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function kg(t,e){const n=!!(t&&t.status==="up"),s=!!(t&&t.status==="passive");return{up:n,...s?{passive:!0}:{},label:n?"tunnel-up":s?"node-passive":"tunnel-down",since:n?zP(t.since,e):null}}const FP=new Set(["v","instanceId","port","label","invite"]),HP=new Set(["v","instanceId","port","label","invite","name","ssh","sshPort"]);function UP(t){const e=String(t).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("binary"),i=Uint8Array.from(s,a=>a.charCodeAt(0));return typeof TextDecoder<"u"?new TextDecoder().decode(i):Buffer.from(i).toString("utf8")}function WP(t){let e="";try{const c=new URL(String(t));e=new URLSearchParams(c.hash.replace(/^#/,"")).get("pair")||""}catch{return{ok:!1}}if(!e)return{ok:!1};let n;try{n=JSON.parse(UP(e))}catch{return{ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1};const s=n.v===1?FP:n.v===2?HP:null;if(!s)return{ok:!1};for(const c of Object.keys(n))if(!s.has(c))return{ok:!1};if(!/^[a-f0-9]{16,64}$/.test(String(n.instanceId)))return{ok:!1};const i=Number(n.port);if(!Number.isInteger(i)||i<1||i>65535)return{ok:!1};if(typeof n.label!="string")return{ok:!1};if(typeof n.invite!="string"||!n.invite)return{ok:!1};const a={ok:!0,version:n.v,label:n.label,invite:n.invite,instanceId:n.instanceId,port:i};if(n.v===2){if(n.name!==void 0){if(typeof n.name!="string"||!Qk.test(n.name))return{ok:!1};a.name=n.name}if(n.ssh!==void 0){if(!Zk(n.ssh))return{ok:!1};a.ssh=String(n.ssh).trim()}if(n.sshPort!==void 0){const c=Number(n.sshPort);if(!Number.isInteger(c)||c<1||c>65535)return{ok:!1};a.sshPort=c}}return a}function qP(t,e,n=new Set){if(!e||!e.ok)return t;const s={...t},i=(a,c)=>{c==null||c===""||n.has(a)||(s[a]=c)};return i("label",e.label),e.version===2&&(i("name",e.name||(e.ssh?ho(e.label):"")),i("ssh",e.ssh),e.sshPort!==void 0&&i("sshPort",String(e.sshPort))),s}const KP=["KIMI_AUTH_ACTION_REQUIRED","CLIENT_INTERACTION_REQUIRED"],VP=["kimi-code-consent-yes","kimi-code-config-custom-api-key","kimi-cli-login","client-terminal-dialog"];function YP(t){const e=t&&typeof t=="object"?t.actionRequired:null;if(e&&typeof e=="object"&&KP.includes(e.code)&&VP.includes(e.recovery))return{code:e.code,recovery:e.recovery,text:p(`fleet-recovery-${e.recovery}`)};if(t&&typeof t=="object"&&t.vlPromptDegraded===!0)return{code:"VL_PROMPT_DEGRADED",recovery:null,text:p("fleet-vl-prompt-degraded")};if(t&&typeof t=="object"&&t.readinessDegraded===!0){if(t.mcpDegraded&&typeof t.mcpDegraded=="object"){const n=[...Array.isArray(t.mcpDegraded.failed)?t.mcpDegraded.failed:[],...Array.isArray(t.mcpDegraded.pending)?t.mcpDegraded.pending:[]].filter(s=>typeof s=="string"&&s).slice(0,16);if(n.length)return{code:"READINESS_DEGRADED",recovery:null,text:p("fleet-mcp-degraded")+" "+n.join(", ")}}return{code:"READINESS_DEGRADED",recovery:null,text:p("fleet-readiness-degraded")}}return null}function GP(t,e){if(!t)return null;const n=t.status===502&&t.data&&t.data.cause==="upstream-timeout";return t.name==="TimeoutError"||n?{code:"FLEET_ACTION_TIMEOUT",recovery:null,text:p(e==="down"?"fleet-down-slow":"fleet-up-slow")}:t.status===409&&e==="up"&&t.data&&t.data.code==="SESSION_DUPLICATE"?{code:"FLEET_SESSION_DUPLICATE",recovery:null,text:p("fleet-up-duplicate")}:null}async function jv({token:t,powerCell:e,payload:n,onNotice:s,fleetApi:i}){const a=i||{fleetUp:xN,fleetDown:C1},{cell:c}=e,u=Array.isArray(e.route)?e.route:[];try{if(n.action==="up"){const h=await a.fleetUp(t,{cell:c,boot:!!n.boot,...n.engine?{engine:n.engine}:{},...n.model!==void 0?{model:n.model}:{},...n.permissionPolicy?{permissionPolicy:n.permissionPolicy}:{}},u),f=YP(h);f&&s(f.text)}else await a.fleetDown(t,{cell:c,boot:!!n.boot},u);return}catch(h){const f=GP(h,n.action);if(f)return s(f.text),{benign:f.code};throw h}}const XP=1e4;function eC(){const[t,e]=w.useState(null),n=w.useRef(null),s=w.useCallback(i=>{typeof i!="string"||!i||(n.current&&clearTimeout(n.current),e(i),n.current=setTimeout(()=>e(null),XP))},[]);return w.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]),{notice:t,showActionNotice:s}}let Cg={sessions:[],cells:[],nodeGroups:[],localNodeId:"",localFresh:!1,refreshedAt:0};function z0(){return Cg}function tC(t={}){return Cg={sessions:Array.isArray(t.sessions)?t.sessions:[],cells:Array.isArray(t.cells)?t.cells:[],nodeGroups:Array.isArray(t.nodeGroups)?t.nodeGroups:[],localNodeId:typeof t.localNodeId=="string"?t.localNodeId:"",localFresh:t.localFresh===!0,refreshedAt:Number.isFinite(t.refreshedAt)?t.refreshedAt:0},Cg}const Ta=(t,e=[])=>`${e.length?e.join("/"):"local"}:${t}`;function JP({onPick:t,token:e,onSettings:n,onOpenVlSession:s,hostByRoute:i={},onDesignateCell:a,onClearHostCell:c,panelPort:u=0,nodePanelPorts:h=null}){const[f,g]=zn(),v=bv(e),[_,b]=w.useState(null),[x,L]=w.useState(null),[C,R]=w.useState(!0),[S,I]=w.useState(""),[E,F]=w.useState(""),[$,X]=w.useState({bind:"127.0.0.1",port:""}),[V,G]=w.useState(""),[ne,K]=w.useState([]),[D,P]=w.useState([]),[O,j]=w.useState(!1),[z,M]=w.useState(null),[A,N]=w.useState({}),[U,T]=w.useState(new Set),[H,se]=w.useState(null),{notice:Q,showActionNotice:Z}=eC(),[me,de]=w.useState(null),[ie,xe]=w.useState(null),[Be,nt]=w.useState(!1),[Le,Ie]=w.useState(null),[ue,Re]=w.useState(null),[fe,Ee]=w.useState("preview"),[Y,pe]=w.useState(!1),{pins:Ae,orders:ke,togglePin:We,removePin:Ne,pinError:ge,reorderBlocked:st,retryPinPersist:Ze,clearPinError:De,viewFor:He,updateView:qe,canMoveRoster:wt,moveRoster:W,stepRoster:ee}=xv(),J=le=>i[Cs(le)]||{},{groupsFor:be,moveNode:ye,stepNode:ot,nodeKey:oe}=kv(),$e=be(v);w.useEffect(()=>{tC({sessions:_||[],cells:ne,nodeGroups:v,localNodeId:V})},[_,ne,v,V]),w.useEffect(()=>{const le=new Map;for(const re of ne)le.set(Ta(re.cell),!!re.boot);for(const re of v){const Te=re.route||[re.name];for(const Ge of re.cells||[])le.set(Ta(Ge.cell,Te),!!Ge.boot)}N(re=>{let Te=!1;const Ge={...re};for(const[mt,q]of Object.entries(re))le.has(mt)&&le.get(mt)===q&&(delete Ge[mt],Te=!0);return Te?Ge:re})},[ne,v]);function ut(){x5([],e)}w.useEffect(()=>{const re=kd(e,[],Te=>{if(!Te)return;const Ge=Te.sessionsError?null:Te.sessionsJson;Ge&&!Ge.error?(L(null),b(Ge.sessions||[]),R(!0)):Ge?(L(Ge.error),b([]),R(!1)):(L(String(Te.sessionsError)),b([]),R(!1));const mt=yv({fs:Te.fs,error:Te.fleetError});mt.kind==="data"?(Ka("local",mt.cells),K(mt.cells),P(mt.capabilities),j(!1),M(null)):mt.kind==="stale"?(K(q=>q.length?q:_v("local")),j(!0),M(null)):(K([]),Ka("local",[]),P([]),j(!1),M(mt.reason||""))});return qn("/api/config",e).then(Te=>Te.json()).then(Te=>{F(Te.version||""),X({bind:Te.bind||"127.0.0.1",port:Te.port||""}),G(Ya.test(String(Te.instanceId||""))?Te.instanceId:"")}).catch(()=>{}),re},[e]);async function kt(){if(!$.port)return;const le=`http://${$.bind}:${$.port}/#token=${e}`;try{await navigator.clipboard.writeText(le)}catch{}}function St(le,re,Te){const Ge=Ta(le,re);N(mt=>({...mt,[Ge]:!!Te}))}function Lt(le,re=[]){const Te=Ta(le.cell,re);return Object.prototype.hasOwnProperty.call(A,Te)?A[Te]:!!le.boot}async function _t(le,re,Te=[],Ge){const mt=Ta(re.cell,Te),q=typeof Ge=="boolean"?Ge:!Lt(re,Te);St(re.cell,Te,q),T(ae=>new Set(ae).add(mt));try{await E1(e,{cell:re.cell,enabled:q},Te),Te.length||K(ae=>ae.map(je=>je.cell===re.cell?{...je,boot:q}:je))}catch(ae){N(je=>{const Xe={...je};return delete Xe[mt],Xe}),L(String((ae==null?void 0:ae.message)||ae))}finally{T(ae=>{const je=new Set(ae);return je.delete(mt),je})}}const pt=(le,re,Te)=>({onToggleLive:async()=>{const Ge=oo({item:le,cellName:re.cell,route:Te,pins:Ae,hostByRoute:i});nt(!0);const mt=await eh({action:Ge.isLive?"remove":"use",cellId:re.cell,route:Te,token:e});nt(!1),Ie({messageKey:mt.messageKey,ok:mt.ok,cell:mt.hostCell||re.cell})},onTogglePin:()=>Cv({view:lh({item:le,pins:Ae,hostByRoute:i,route:Te}),itemKey:le.key,togglePin:We,removePin:Ne}),onToggleBoot:Ge=>_t(null,re,Te,Ge),onWatchLive:()=>{Ee("stream"),Re(le.key)}});async function Ut(le){if(!H)return;let re=null;try{re=await jv({token:e,powerCell:H,payload:le,onNotice:Z})}catch(Te){throw Z(String(Te&&Te.message||Te)),Te}if(!re){const{cell:Te}=H,Ge=Array.isArray(H.route)?H.route:[];le.action==="up"?St(Te,Ge,!!le.boot):le.boot&&St(Te,Ge,!1)}ut()}const Gt=w.useMemo(()=>{if(!H)return null;const le=(Array.isArray(H.route)?H.route:[]).join("/"),Te=[...ne,...v.flatMap(Ge=>(Ge.cells||[]).map(mt=>({...mt,route:Ge.route||[Ge.name]})))].find(Ge=>Ge.cell===H.cell&&(Array.isArray(Ge.route)?Ge.route.join("/"):"")===le);return Te?{...H,active:!!Te.active}:H},[H,ne,v]);async function Ot(le,re=[]){try{await Yg(e,le,re)}catch{return}ut()}async function ln(le,re,Te=[]){try{await L1(e,le,re,Te)}catch{return}ut()}async function In(le){if(!(!(le!=null&&le.direct)||me)){de(le.name);try{await Jg(e,le.name,le.tunnelStatus==="up"?"down":"up")}catch{}de(null)}}async function qt(le){if(!(le!=null&&le.direct))return;const re=window.prompt(p("rename-node-prompt"),le.label||le.name);if(re===null)return;const Te=String(re).trim();if(!Ga(Te)){window.alert(p("rename-node-invalid"));return}try{await P1(e,le.name,Te)}catch(Ge){window.alert(String((Ge==null?void 0:Ge.message)||Ge))}}const wn=w.useMemo(()=>new Map((_||[]).map(le=>[le.name,le])),[_]),en=w.useMemo(()=>new Set(ne.map(le=>le.tmuxSession)),[ne]),bn=w.useMemo(()=>(_||[]).filter(le=>!en.has(le.name)),[_,en]),Ft=w.useMemo(()=>Lv(ne,bn,wn,void 0,{autorevole:C,fleetStale:O}),[ne,bn,wn,C,O]),Xt=w.useMemo(()=>{const le=new Map;for(const re of Ft)re.type==="cell"&&le.set(re.key,{item:re,route:[],nodeLabel:"",sessions:_||[],cells:ne});for(const re of $e){const Te=Array.isArray(re.route)?re.route:[];if(!Te.length||re.kind==="vl")continue;const{rawItems:Ge}=mc(re);for(const mt of Ge)mt.type==="cell"&&le.set(mt.key,{item:mt,route:Te,nodeLabel:re.label||re.name||"",sessions:re.sessions||[],cells:re.cells||[]})}return le},[Ft,$e,_,ne]),Jt=w.useMemo(()=>{if(!ue)return null;const le=Xt.get(ue);if(!le)return null;const re=le.item.value,Te=(le.sessions||[]).find(Ge=>Ge.name===re.tmuxSession)||{};return{row:{key:le.item.key,cellName:re.cell,subtitle:le.item.subtitle||"",nodeLabel:le.nodeLabel,node:le.route.length?le.route.join("/"):"",session:re.tmuxSession,route:le.route,panelUrl:re.panelUrl||"",telemetry:Te.telemetry||null,preview:Te.preview||re.preview||"",activity:Te.activity||re.activity||0},cells:le.cells||[]}},[ue,Xt]),Qt=He("local"),ls=w.useMemo(()=>co(Ft,Ae,Qt.filter,Ii(ke,"local")).filter(le=>S0(le,S)),[Ft,Ae,Qt.filter,S,ke]),cs=$e.reduce((le,re)=>le+(re.cells||[]).length+(re.unmanaged||[]).filter(Te=>!Te.technical).length,0),mn=co(Ft,Ae,"all",Ii(ke,"local")).length+cs,gn=Ft.filter(le=>le.live).length+$e.reduce((le,re)=>le+mc(re).rawItems.filter(Te=>Te.live).length,0),qs=(_||[]).filter(le=>le.attached).length+$e.reduce((le,re)=>le+(re.sessions||[]).filter(Te=>Te.attached).length,0),Vn=Math.min(qs,gn),bt=$.port?`${$.bind}:${$.port}`:$.bind;function us(le,re=null,Te=Ft){var xt,gt;const Ge=Array.isArray(re==null?void 0:re.route)?re.route:[],mt=Ge.join("/"),q=mt||"local",ae=Ge.length?re==null?void 0:re.instanceId:V,je=(Je,Rt)=>t({session:Je,...mt?{node:mt}:{},...Ya.test(String(ae||""))?{ownerId:ae}:{},...typeof Rt=="string"&&Rt?{cellName:Rt}:{}}),Xe=wt;if(le.type==="cell"){const Je=le.value,Rt=J(Ge),rt=Ed({hostCell:Rt.hostCell??null,threadStatus:Rt.threadStatus,pins:Ae,item:le}),ze=Ge.length?((re==null?void 0:re.sessions)||[]).find(Zt=>Zt.name===Je.tmuxSession):wn.get(Je.tmuxSession),Wt=fm(rt,Rt.hostLease??null),Sn=Je.degraded?p("cell-degraded"):le.subtitle||(Je.tmux?p("cell-idle"):p("cell-off")),Se=Wt?`${Sn} · ${p(Wt)}`:Sn,Me=Ge.length===0||((re==null?void 0:re.capabilities)||[]).includes(Je.active?"down":"up"),Ve=Ge.length===0?D.includes("boot"):((re==null?void 0:re.capabilities)||[]).includes("boot"),ct=Lt(Je,Ge),At=oo({item:le,cellName:Je.cell,route:Ge,pins:Ae,hostByRoute:i}),Ks=!!ie&&ie.itemKey===le.key,Vs=`${p("cell-actions-open")}: ${Je.cell}`;return l.jsxs("div",{className:"nc-mcard","data-roster-key":le.key,"data-position":q,children:[Y&&l.jsx(Gi,{position:q,itemKey:le.key,label:Je.cell,canMove:Xe,onMove:(Zt,tn)=>W(q,Zt,tn,Te),onStep:Zt=>ee(q,le.key,Zt,Te)}),l.jsxs("button",{className:"nc-mcard-main",onClick:()=>Je.tmux&&je(Je.tmuxSession,Je.cell),title:Se,"aria-label":`${Je.cell}, ${Se}`,children:[l.jsx("span",{className:`dot ${Je.degraded?"warn":Je.tmux?`on${le.working?" working":""}`:""}`}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsxs("span",{className:"nc-mcard-nome",children:[l.jsx("b",{children:Je.cell}),At.isLive&&l.jsx("span",{className:"nc-m-live",children:"LIVE"})]}),l.jsx("small",{title:le.subtitle,children:le.subtitle})]})]}),le.activity?l.jsx("span",{className:"nc-rel",children:ao(le.activity)}):null,le.fresh&&((xt=ze==null?void 0:ze.outbox)==null?void 0:xt.count)>0&&l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:ze.outbox.count}),l.jsx("button",{type:"button",className:`nc-act cellmenu${Ks?" on":""}`,title:Vs,"aria-label":Vs,"aria-haspopup":"menu","aria-expanded":Ks?"true":"false",onClick:()=>xe({itemKey:le.key,item:le,cell:Je,route:Ge,canBoot:Ve}),children:"⋯"}),Me&&l.jsx("button",{className:`nc-act power${Je.tmux?" on":""}${Je.degraded?" warn":""}`,onClick:()=>se(Ge.length?{...Je,boot:ct,route:Ge,availableEngines:(re==null?void 0:re.engines)||[]}:{...Je,boot:ct}),title:Je.active?p("power-off"):p("power-on"),"aria-label":`${Je.active?p("power-off"):p("power-on")} ${Je.cell}`,children:l.jsx(Pt,{name:"power",size:16})})]},le.key)}const Pe=le.value;return l.jsxs("div",{className:"nc-mcard","data-roster-key":le.key,"data-position":q,children:[l.jsx(Gi,{position:q,itemKey:le.key,label:Pe.name,canMove:Xe,onMove:(Je,Rt)=>W(q,Je,Rt,Te),onStep:Je=>ee(q,le.key,Je,Te)}),l.jsxs("button",{className:"nc-mcard-main",onClick:()=>je(Pe.name),children:[l.jsx("span",{className:Pe.attached?"dot on":"dot"}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsx("b",{children:Pe.name}),l.jsx("small",{children:Pe.preview?Pe.preview:Pe.cmd?Pe.cmd:p("windows").replace("{n}",String(Pe.windows||0))})]})]}),le.activity?l.jsx("span",{className:"nc-rel",children:ao(le.activity)}):null,le.fresh&&((gt=Pe.outbox)==null?void 0:gt.count)>0&&l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:Pe.outbox.count}),l.jsx("button",{className:`nc-act pin${Ae.includes(le.key)?" on":""}`,"aria-label":`${p("pin")} ${Pe.name}`,title:p("pin"),onClick:()=>We(le.key),children:Ae.includes(le.key)?"★":"☆"}),l.jsx("button",{className:`nc-act technical${Pe.technical?" on":""}`,title:Pe.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${Pe.technical?p("mark-normal"):p("mark-technical")} ${Pe.name}`,onClick:()=>ln(Pe.name,!Pe.technical,Ge),children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),"aria-label":`${p("terminate")} ${Pe.name}`,onClick:()=>{window.confirm(p("terminate-confirm").replace("{name}",Pe.name))&&Ot(Pe.name,Ge)},children:"⋯"})]},le.key)}return l.jsxs("div",{className:"nc-home",children:[l.jsxs("header",{className:"nc-home-head",children:[l.jsxs("div",{className:"nc-wordmark",children:["NexusCrew",l.jsx("span",{className:"nc-cursor"})]}),l.jsxs("div",{className:"nc-home-sub",children:[p("fleet-tmux")," · ",gn," ",p("sessions"),Vn>0&&` · ${Vn} attached`]}),l.jsxs("span",{className:"nc-head-actions",children:[l.jsx("button",{className:`nc-refresh${Y?" on":""}`,onClick:()=>pe(le=>!le),"aria-pressed":Y,title:p("reorder-help"),"aria-label":p("reorder"),children:"↕"}),l.jsx("button",{className:"nc-refresh",onClick:()=>n("nodes",!1),title:p("settings"),children:l.jsx(Pt,{name:"gear",size:18})}),l.jsx("button",{className:"nc-refresh",onClick:ut,title:p("refresh"),children:l.jsx(Pt,{name:"refresh",size:18})})]})]}),l.jsxs("main",{className:"nc-home-scroll",children:[l.jsx(QP,{view:Va({liveHost:i[Cs([])],cells:ne}),notice:Le}),l.jsx(Tk,{pinError:ge,onRetry:Ze,onDismiss:De}),mn>8&&l.jsx("input",{className:"nc-filter",type:"search",placeholder:p("filter-placeholder"),"aria-label":p("filter-placeholder"),value:S,onChange:le=>I(le.target.value)}),x&&l.jsx("div",{className:"nc-err",children:x}),Q&&l.jsx("div",{className:"nc-notice",role:"status",children:Q}),O&&l.jsx("div",{className:"nc-set-hint nc-fleet-stale",role:"status",children:p("fleet-stale")}),st&&l.jsxs("div",{className:"nc-set-hint nc-reorder-blocked",role:"status",children:[p("reorder-blocked")," (",st.reason,")"]}),z!==null&&l.jsxs("div",{className:"nc-set-hint nc-fleet-off",role:"status",children:[p("fleet-off"),z?` (${z})`:""]}),l.jsxs("section",{className:"nc-group","data-position":"local",children:[l.jsx(xp,{label:p("position-local"),count:ls.length,state:Qt,dotClass:"on",onToggle:()=>qe("local",{open:!Qt.open}),onFilter:le=>qe("local",{filter:le})}),Qt.open&&ls.map(le=>us(le,null,Ft)),Qt.open&&_===null&&l.jsx("div",{className:"nc-empty",children:p("loading-fleet")}),Qt.open&&_!==null&&ls.length===0&&!x&&l.jsx("div",{className:"nc-empty",children:S?p("no-match").replace("{q}",S):p("no-sessions-short")})]}),$e.map(le=>{const re=Bk(le.health,{passive:"warn"}),Te=le.fleetState==="stale"?p("fleet-stale"):le.fleetState==="disabled"?p("fleet-off"):"",Ge=le.fleetState==="stale"?"warn":re||(le.status==="up"?"on":le.status==="passive"?"":"warn"),mt=[le.health?Id(le.health):Qi(le),Te].filter(Boolean).join(" · "),ae=(le.route&&le.route.length?le.route:[le.name]).join("/"),je=He(ae);if(le.kind==="vl")return l.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":ae,"data-node-order-key":oe(le),children:[l.jsx(xp,{label:le.label||le.name,count:le.sessions.length,state:je,dotClass:Ge,dotTitle:mt,detail:Qi(le),onToggle:()=>qe(ae,{open:!je.open}),onFilter:Je=>qe(ae,{filter:Je})}),le.status==="up"&&je.open&&le.sessions.map(Je=>l.jsx("div",{className:"nc-mcard nc-vl-session-row",children:l.jsxs("button",{className:"nc-mcard-main",onClick:()=>s&&s(le.peer),"aria-label":`${le.label||le.name}: ${Je.name}`,children:[l.jsx("span",{className:"dot on"}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsx("b",{children:Je.name}),l.jsx("small",{children:p("vl-events-title")})]})]})},Je.key)),le.status==="up"&&je.open&&le.sessions.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]},`nodo-vl-${ae}-${le.name}`);const{rawItems:Xe}=mc(le),Pe=co(Xe,Ae,je.filter,Ii(ke,ae)).filter(Je=>S0(Je,S)),xt=le.direct&&le.health&&le.health.managed!==!1?l.jsx("button",{type:"button",className:`nc-act power${le.tunnelStatus==="up"?" on":""}`,disabled:me===le.name,title:le.tunnelStatus==="up"?p("power-off"):p("power-on"),"aria-label":`${le.tunnelStatus==="up"?p("power-off"):p("power-on")} ${le.label||le.name}`,onClick:()=>In(le),children:l.jsx(Pt,{name:"power",size:15})}):null,gt=l.jsxs("span",{className:"nc-node-actions",children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:oe(le),label:le.label||le.name,onMove:(Je,Rt)=>ye(Je,Rt,v),onStep:Je=>ot(oe(le),Je,v)}),le.direct&&l.jsx("button",{type:"button",className:"nc-node-rename",title:p("rename-node"),"aria-label":`${p("rename-node")} ${le.label||le.name}`,onClick:()=>qt(le),children:"✎"}),xt]});return l.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":ae,"data-node-order-key":oe(le),children:[l.jsx(xp,{label:le.label||le.name,count:Pe.length,state:je,dotClass:Ge,dotTitle:mt,detail:le.status==="up"?[Qi(le),Te].filter(Boolean).join(" · "):le.health&&Id(le.health)||Qi(le),onToggle:()=>qe(ae,{open:!je.open}),onFilter:Je=>qe(ae,{filter:Je}),onRename:le.direct?()=>qt(le):null,action:gt}),le.status==="up"&&je.open&&Pe.map(Je=>us(Je,le,Xe)),le.status==="up"&&je.open&&Pe.length===0&&l.jsx("div",{className:"nc-empty",children:S?p("no-match").replace("{q}",S):p("no-sessions-short")})]},`nodo-${ae}`)}),l.jsxs("footer",{className:"nc-home-foot",onClick:kt,title:p("copy-url"),children:[l.jsxs("span",{className:"nc-home-meta",children:[E&&l.jsxs("span",{className:"nc-home-version",children:["v",E]}),l.jsxs("span",{className:"nc-home-endpoint",children:[bt," · ",p("ssh-only")]})]}),l.jsx("span",{className:"nc-lang",onClick:le=>le.stopPropagation(),children:$1.map((le,re)=>l.jsxs("span",{children:[re>0&&" · ",l.jsx("button",{className:`nc-lang-btn${f===le?" on":""}`,onClick:()=>g(le),title:le,children:le.toUpperCase()})]},le))})]})]}),Gt&&l.jsx(Pd,{cell:Gt,token:e,route:Array.isArray(Gt.route)?Gt.route:[],onConfirm:Ut,onClose:()=>se(null)}),Jt&&l.jsx(wk,{row:Jt.row,token:e,initialSource:fe,panelPort:kc(Jt.row.route||[],h,u),liveHost:Va({liveHost:i[Cs(Jt.row.route||[])],cells:Jt.cells}),onClose:()=>{Re(null),Ee("preview")}}),ie&&(()=>{const{item:le,cell:re,route:Te=[],canBoot:Ge}=ie,mt=oo({item:le,cellName:re.cell,route:Te,pins:Ae,hostByRoute:i}),q=Ev({...mt,canBoot:Ge,boot:Lt(re,Te),alive:!!re.tmux,handlers:pt(le,re,Te)});return l.jsx(Nv,{cellName:re.cell,items:q,busy:Be||U.has(Ta(re.cell,Te)),onClose:()=>xe(null)})})()]})}function QP({view:t,notice:e}){const n=!!(t&&t.cell),s=n?p("live-host-indicator").replace("{cell}",t.cell).replace("{mode}",p(t.mode?`live-host-mode-${t.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${t.state||"none"}`)):p("live-host-indicator-none");return l.jsxs("div",{className:"nc-m-live-strip","data-state":t&&t.state?t.state:"none",title:e?`${s} · ${p(e.messageKey)}`:s,children:[l.jsx("span",{className:`nc-m-live-dot ${Rv(t||{})}`,"aria-hidden":"true"}),l.jsx("span",{className:"nc-m-live-testo",children:n?t.cell:s}),e&&l.jsx("span",{className:`nc-m-live-notice${e.ok?" ok":" ko"}`,role:"status",children:p(e.messageKey).replace("{cell}",e.cell||t.cell||"")})]})}function xp({label:t,count:e,state:n,dotClass:s="",dotTitle:i="",detail:a="",onToggle:c,onFilter:u,onRename:h=null,action:f=null}){return l.jsxs("div",{className:"nc-mobile-position-head",onContextMenu:h?g=>{g.preventDefault(),h()}:void 0,children:[l.jsxs("button",{type:"button",className:"nc-mobile-position-toggle",onClick:c,"aria-expanded":n.open,"aria-label":`${t} · ${p("node-sessions").replace("{n}",String(e))}`,children:[l.jsx("span",{className:"nc-mobile-chevron","aria-hidden":"true",children:n.open?"⌄":"›"}),l.jsx("span",{className:`dot ${s}`,title:i}),l.jsxs("span",{className:"nc-mobile-position-copy",children:[l.jsx("b",{children:t}),l.jsx("small",{children:a||p("node-sessions").replace("{n}",String(e))})]})]}),l.jsxs("select",{className:"nc-mobile-position-filter",value:n.filter,"aria-label":`${t} · ${p("filter-placeholder")}`,title:p(`view-${n.filter}`),onChange:g=>u(g.target.value),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]}),f]})}const F0="",an="\x1B",ZP=[{label:"↑",seq:an+"[A"},{label:"↓",seq:an+"[B"},{label:"PGUP",seq:an+"[5~"},{label:"PGDN",seq:an+"[6~"}],eI=new Set([an+"[A",an+"[B",an+"[C",an+"[D",an+"[5~",an+"[6~"]),tI=350,nI=55;function sI({send:t,action:e,ctrlArmed:n=!1,onCtrl:s,altArmed:i=!1,onAlt:a,onAltConsume:c,onKeyboard:u,selectionMode:h=!1,onSelectionMode:f,onCellSwitcher:g,cellSwitcherOpen:v=!1,keepKeyboardClosed:_=!0,showEnter:b=!0,keybarLayout:x="full",onKeyboardKeep:L}){const[C,R]=w.useState(!1),[S,I]=w.useState(!1),[E,F]=w.useState(!1),$=x==="compact"&&!E,X=w.useRef({delay:null,interval:null}),V=w.useRef(()=>{}),G=()=>{const T=X.current;T.delay!==null&&clearTimeout(T.delay),T.interval!==null&&clearInterval(T.interval),T.delay=null,T.interval=null};V.current=G,w.useEffect(()=>{const T=()=>{document.visibilityState==="hidden"&&V.current()},H=()=>V.current();return window.addEventListener("blur",H),document.addEventListener("visibilitychange",T),()=>{window.removeEventListener("blur",H),document.removeEventListener("visibilitychange",T),V.current()}},[]),w.useEffect(()=>{x!=="compact"&&F(!1)},[x]);const ne=T=>{i?(t(an+T),c&&c()):t(T)},K=(T,{keepOpen:H}={})=>{_&&!H&&lg(),H&&L&&L(),T()},D=(T,H={})=>({onPointerDown:se=>{se.preventDefault(),K(T,H)},onClick:se=>{se.detail===0&&K(T,H)}}),P=(T,H={})=>({onPointerDown:se=>{se.preventDefault(),G(),K(T,H),!i&&(X.current.delay=setTimeout(()=>{X.current.delay=null,T(),X.current.interval=setInterval(T,nI)},tI))},onPointerUp:G,onPointerLeave:G,onPointerCancel:G,onLostPointerCapture:G,onTouchCancel:G,onClick:se=>{se.detail===0&&K(T,H)}}),O=(T,H,se)=>l.jsx("button",{type:"button",...eI.has(H)&&!se?P(()=>ne(H)):D(()=>{ne(H),se&&se()}),children:T},T),j=(T,H)=>l.jsx("button",{type:"button",...D(()=>{e(H),I(!1)}),children:T},T),z=g?l.jsx("button",{type:"button","aria-label":p("fleet-cells"),title:p("fleet-cells"),"aria-expanded":v,...D(g),children:"◫"},"cells"):l.jsx("button",{type:"button",...D(()=>{u&&u()}),children:"⌨"},"kbd"),M=b&&l.jsx("button",{type:"button",className:"nc-enter-key","aria-label":"ENTER",title:"ENTER",...D(()=>ne("\r")),children:l.jsx(Pt,{name:"enter",size:24})}),A=S&&l.jsxs("div",{className:"nc-keymenu",children:[j("←WIN","prev-window"),j("WIN→","next-window"),j("⬅PANE","pane-left"),j("PANE➡","pane-right"),O("SCROLL",F0+"[",()=>{R(!0),I(!1)}),l.jsx("button",{type:"button",className:h?"armed":"",...D(()=>{f==null||f(!h),I(!1)}),children:"SELECT"}),O("⌃C","",()=>I(!1)),O("DETACH",F0+"d",()=>I(!1))]});if(C)return l.jsxs("div",{className:"nc-keybar copy",children:[l.jsx("span",{className:"tag",children:"copy-mode"}),ZP.map(T=>O(T.label,T.seq)),O("ESCI (q)","q",()=>R(!1))]});if($)return l.jsxs("div",{className:"nc-keybar termux",children:[A,l.jsxs("div",{className:`nc-keygrid compact${b?"":" no-enter"}`,children:[l.jsx("div",{className:"nc-keyrows",children:l.jsxs("div",{className:"row",children:[l.jsx("button",{type:"button","aria-label":p("keybar-expand"),title:p("expand"),...D(()=>F(!0)),children:l.jsx(Pt,{name:"chevronUp",size:20})},"expand"),z,l.jsx("button",{type:"button",className:S?"armed":"",...D(()=>I(T=>!T)),children:"☰"},"menu"),O("↑",an+"[A"),O("↓",an+"[B"),O("←",an+"[D"),O("→",an+"[C"),O("PGUP",an+"[5~"),O("PGDN",an+"[6~")]})}),M]})]});const N=x==="compact"&&E,U=N&&l.jsx("button",{type:"button",className:"nc-retract-key","aria-label":p("keybar-retract"),title:p("retract"),...D(()=>F(!1)),children:l.jsx(Pt,{name:"chevronDown",size:20})});return l.jsxs("div",{className:`nc-keybar termux${N?" expanded":""}`,children:[A,l.jsxs("div",{className:`nc-keygrid${b?"":" no-enter"}${N?" expanded":""}`,children:[U,l.jsxs("div",{className:"nc-keyrows",children:[l.jsxs("div",{className:"row",children:[O("ESC",an),l.jsx("button",{type:"button",className:S?"armed":"",...D(()=>I(T=>!T)),children:"☰"},"menu"),O("/","/"),O("—","-"),O("HOME",an+"[H"),O("↑",an+"[A"),O("END",an+"[F"),O("PGUP",an+"[5~")]}),l.jsxs("div",{className:"row",children:[O("⇥"," "),z,l.jsx("button",{type:"button",className:n?"armed":"",...D(()=>{s&&s()},{keepOpen:!0}),children:"CTRL"},"ctrl"),l.jsx("button",{type:"button",className:i?"armed":"",...D(()=>{a&&a()},{keepOpen:!0}),children:"ALT"},"alt"),O("←",an+"[D"),O("↓",an+"[B"),O("→",an+"[C"),O("PGDN",an+"[6~")]})]}),M]})]})}const iI=t=>t>1048576?`${(t/1048576).toFixed(1)}M`:t>1024?`${(t/1024).toFixed(0)}K`:`${t}B`;function Eg({session:t,node:e,token:n,filesEvent:s,onClose:i}){zn();const a=e?`/api/route/${String(e).split("/").map(encodeURIComponent).join("/")}/_`:"/api",c=e?`${e}:${t}`:t,[u,h]=w.useState("outbox"),[f,g]=w.useState({inbox:[],outbox:[]}),[v,_]=w.useState("");async function b(){try{const R=await(await qn(`${a}/files?session=${encodeURIComponent(t)}`,n)).json();if(R.error){_(R.error);return}g(R);const S=R.outbox[0]?R.outbox[0].mtime:0;localStorage.setItem(x1(c),String(S))}catch(C){_(String(C))}}w.useEffect(()=>{b()},[t,e]),w.useEffect(()=>{s&&s.session===t&&b()},[s]);async function x(C){const R=await qn(`${a}/files/download?session=${encodeURIComponent(t)}&box=${u}&name=${encodeURIComponent(C)}`,n);if(!R.ok){const F=await R.json().catch(()=>({}));_(F.error?`errore: ${F.error}`:"errore download");return}const S=await R.blob(),I=URL.createObjectURL(S),E=document.createElement("a");E.href=I,E.download=C,E.click(),URL.revokeObjectURL(I)}async function L(C){const R=await qn(`${a}/files?session=${encodeURIComponent(t)}&box=${u}&name=${encodeURIComponent(C)}`,n,{method:"DELETE"});if(!R.ok){const S=await R.json().catch(()=>({}));_(S.error?`errore: ${S.error}`:"errore delete");return}b()}return l.jsxs("div",{className:"nc-files",children:[l.jsxs("header",{children:[l.jsx("b",{children:e?`${e}:${t}`:t}),l.jsx("button",{onClick:i,title:p("close"),"aria-label":p("close"),children:l.jsx(Pt,{name:"x",size:20})})]}),l.jsxs("nav",{children:[l.jsx("button",{className:u==="outbox"?"on":"",onClick:()=>h("outbox"),children:"outbox"}),l.jsx("button",{className:u==="inbox"?"on":"",onClick:()=>h("inbox"),children:"inbox"})]}),v&&l.jsx("div",{className:"nc-busy",children:v}),l.jsxs("ul",{children:[f[u].map(C=>l.jsxs("li",{children:[l.jsx("span",{className:"name",children:C.name}),l.jsx("small",{children:iI(C.size)}),l.jsx("button",{type:"button",onClick:()=>x(C.name),title:p("files-download"),"aria-label":`${p("files-download")} ${C.name}`,children:l.jsx(Pt,{name:"download",size:18})}),l.jsx("button",{onClick:()=>L(C.name),title:p("delete"),"aria-label":`${p("delete")} ${C.name}`,children:l.jsx(Pt,{name:"trash",size:18})})]},C.name)),f[u].length===0&&l.jsx("li",{className:"empty",children:p("empty-files")})]})]})}const dh="nc_composer_v1",Ng="nc-composer-reset",rI=50,nC=256*1024,sC=512*1024,oI=768*1024,H0=2*1024*1024,iC=720*60*60*1e3,Rg=1;function rC(t){const e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Mv(t){if(t!==void 0)return t;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Bd(){return{version:Rg,cells:{}}}function oC(t){const e=[];for(const s of Array.isArray(t)?t:[]){const i=typeof s=="string"?s:s&&s.text,a=rC(typeof s=="string"?0:s&&s.at);if(!(typeof i!="string"||!i||i.length>nC)&&!(e.length&&e[e.length-1].text===i)&&(e.push({text:i,at:a}),e.length>=rI))break}let n=0;return e.filter(s=>n+s.text.length>oI?!1:(n+=s.text.length,!0))}function $d(t){if(!t||typeof t!="object")return null;const e=typeof t.draft=="string"&&t.draft.length<=sC?t.draft:"",n=oC(t.history),s=rC(t.updatedAt),i=t.expanded===!0;return!e&&!n.length&&!i?null:{draft:e,history:n,expanded:i,updatedAt:s}}function aI(t){let e;try{e=typeof t=="string"?JSON.parse(t):t}catch{return Bd()}if(!e||typeof e!="object"||e.version!==Rg||!e.cells||typeof e.cells!="object")return Bd();const n=Object.create(null);for(const[s,i]of Object.entries(e.cells)){if(!s||typeof s!="string"||s.length>512||s==="__proto__"||s==="constructor"||s==="prototype")continue;const a=$d(i);a&&(n[s]=a)}return{version:Rg,cells:n}}function aC(t){const e=Mv(t);if(!e)return Bd();try{return aI(e.getItem(dh))}catch{return Bd()}}function U0(t){try{return JSON.stringify(t).length}catch{return 1/0}}function lI(t,e,n){for(const[s,i]of Object.entries(t.cells))s!==n&&i.updatedAt>0&&e-i.updatedAt>iC&&delete t.cells[s]}function lC(t,e){return Object.entries(t.cells).filter(([n])=>n!==e).sort((n,s)=>n[1].updatedAt-s[1].updatedAt).map(([n])=>n)}function cI(t,e){for(;U0(t)>H0;){const n=Object.entries(t.cells).filter(([,s])=>s.history.length).sort((s,i)=>s[1].updatedAt-i[1].updatedAt);if(!n.length)break;n[0][1].history.pop()}for(const n of lC(t,e)){if(U0(t)<=H0)break;delete t.cells[n]}}function cC(t,e,n){const s=Mv(t);if(!s)return!1;cI(e,n);const i=()=>(s.setItem(dh,JSON.stringify(e)),!0);try{return i()}catch{for(const c of lC(e,n)){delete e.cells[c];try{return i()}catch{}}return!1}}function Fc(t,e,n,s){const i=aC(e);lI(i,n,t);const a=$d(i.cells[t])||{draft:"",history:[],expanded:!1,updatedAt:0},c=s({...a,history:[...a.history]}),u=$d(c);return u?i.cells[t]={...u,updatedAt:n}:delete i.cells[t],{ok:cC(e,i,t),cell:i.cells[t]||{draft:"",history:[],expanded:!1,updatedAt:n}}}function uI({ownerId:t,node:e,session:n}){const s=String(n||"");if(!s)return"";const i=Ya.test(String(t||""))?String(t):e?`route:${String(e)}`:"local";return`${encodeURIComponent(i)}:${encodeURIComponent(s)}`}function Yl(t,e,n=Date.now()){if(!t)return{draft:"",history:[],expanded:!1,updatedAt:0};const s=aC(e),i=$d(s.cells[t]);return!i||i.updatedAt>0&&n-i.updatedAt>iC?(s.cells[t]&&(delete s.cells[t],cC(e,s,"")),{draft:"",history:[],expanded:!1,updatedAt:0}):{...i,history:[...i.history]}}function W0(t,e,n,s=Date.now()){const i=String(e||"");return!t||i.length>sC?!1:Fc(t,n,s,a=>({...a,draft:i})).ok}function q0(t,e,n=Date.now()){return t?Fc(t,e,n,s=>({...s,draft:""})).ok:!1}function dI(t,e,n,s=Date.now()){return t?Fc(t,n,s,i=>({...i,expanded:!!e})).ok:!1}function hI(t,e,n,s=Date.now()){const i=String(e||"");return!t||!i||i.length>nC?!1:Fc(t,n,s,a=>{const c=a.history.filter(u=>u.text!==i);return c.unshift({text:i,at:s}),{...a,history:oC(c)}}).ok}function fI(t,e,n=Date.now()){return t?Fc(t,e,n,s=>({...s,history:[]})).ok:!1}function pI(t){const e=Mv(t);if(!e)return!1;try{return e.removeItem(dh),!0}catch{return!1}}const mI=300;function gI(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function vI({ownerId:t,node:e,session:n,storage:s=gI()}){const i=w.useMemo(()=>uI({ownerId:t,node:e,session:n}),[t,e,n]),a=w.useMemo(()=>Yl(i,s),[]),[c,u]=w.useState(a.draft),[h,f]=w.useState(a.expanded),[g,v]=w.useState(a.history),[_,b]=w.useState(-1),x=w.useRef(i),L=w.useRef(a.draft),C=w.useRef(null),R=w.useRef(a.updatedAt||0),S=w.useRef(a.draft),I=w.useCallback(()=>{C.current&&clearTimeout(C.current),C.current=null},[]),E=w.useCallback(()=>{I(),W0(x.current,L.current,s)},[I,s]),F=w.useCallback(()=>{I(),C.current=setTimeout(()=>{C.current=null,W0(x.current,L.current,s)},mI)},[I,s]),$=w.useCallback(O=>{const j=String(typeof O=="function"?O(L.current):O||"");L.current=j,R.current=Date.now(),S.current=j,b(-1),u(j),F()},[F]),X=w.useCallback((O,j)=>{I(),L.current=O,R.current=Date.now(),u(O),b(j),F()},[I,F]),V=w.useCallback(()=>{if(!g.length)return!1;const O=Math.min(_+1,g.length-1);return _<0&&(S.current=L.current),X(g[O].text,O),!0},[X,g,_]),G=w.useCallback(()=>{if(_<0)return!1;const O=_-1;return X(O<0?S.current:g[O].text,O),!0},[X,g,_]),ne=w.useCallback(O=>{S.current=L.current;const j=g.findIndex(z=>z.text===O);X(String(O||""),j)},[X,g]),K=w.useCallback(()=>{f(O=>{const j=!O;return dI(x.current,j,s),j})},[s]),D=w.useCallback((O,j,z)=>{if(!O)return;if(hI(O,z,s),!(x.current===O)){Yl(O,s).draft===j&&q0(O,s);return}v(Yl(O,s).history),S.current="",b(-1),L.current===j?(I(),L.current="",R.current=Date.now(),u(""),q0(O,s)):F()},[I,F,s]),P=w.useCallback(()=>{fI(x.current,s),v([]),b(-1),S.current=L.current},[s]);return w.useEffect(()=>{if(x.current===i)return;E(),x.current=i;const O=Yl(i,s);L.current=O.draft,R.current=O.updatedAt||0,S.current=O.draft,u(O.draft),f(O.expanded),v(O.history),b(-1)},[i,E,s]),w.useEffect(()=>{const O=()=>E(),j=()=>{document.visibilityState==="hidden"&&E()};return window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",j),()=>{window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",j),E()}},[E]),w.useEffect(()=>{const O=()=>{I(),L.current="",R.current=0,S.current="",u(""),f(!1),v([]),b(-1)},j=M=>{if(M.key!==dh)return;if(M.newValue==null){O();return}const A=Yl(x.current,s);A.updatedAt<R.current||(I(),L.current=A.draft,R.current=A.updatedAt,S.current=A.draft,u(A.draft),f(A.expanded),v(A.history),b(-1))},z=()=>O();return window.addEventListener("storage",j),window.addEventListener(Ng,z),()=>{window.removeEventListener("storage",j),window.removeEventListener(Ng,z)}},[I,s]),{cellKey:i,text:c,setText:$,expanded:h,toggleExpanded:K,history:g,historyCursor:_,recallPrevious:V,recallNext:G,selectHistory:ne,confirmSubmitted:D,clearHistory:P,flush:E}}function uC({submitText:t,token:e,session:n,node:s,ownerId:i,readonly:a=!1,keepKeyboardClosedOnVoice:c=!0}){zn();const u=s?`/api/route/${String(s).split("/").map(encodeURIComponent).join("/")}/_`:"/api",{cellKey:h,text:f,setText:g,expanded:v,toggleExpanded:_,history:b,historyCursor:x,recallPrevious:L,recallNext:C,selectHistory:R,confirmSubmitted:S,clearHistory:I,flush:E}=vI({ownerId:i,node:s,session:n}),[F,$]=w.useState(!1),[X,V]=w.useState(""),[G,ne]=w.useState(""),[K,D]=w.useState(!1),P=w.useRef(null),O=w.useRef(null),j=w.useRef(null),[z,M]=w.useState(!1),[A,N]=w.useState({left:0,bottom:0}),[U,T]=w.useState(!1),[H,se]=w.useState(!1),Q=w.useRef(null),Z=w.useRef(null),me=w.useRef(null),de=w.useRef(null),ie=w.useRef(null),xe=w.useRef(null),Be=w.useRef(null),nt=w.useRef(null),Le=w.useRef(!1),[Ie,ue]=w.useState(!1),[Re,fe]=w.useState({left:0,bottom:0,width:320}),Ee=w.useRef(`nc-attach-${Math.random().toString(36).slice(2,8)}`);w.useEffect(()=>{let ee=!1;if(s){D(!1);return}return qn(`${u}/voice/status`,e).then(J=>J.json()).then(J=>{ee||D(!!J.serverSttConfigured)}).catch(()=>{ee||D(!1)}),()=>{ee=!0}},[e,u]);const pe=!!(typeof window<"u"&&(window.SpeechRecognition||window.webkitSpeechRecognition)||K);async function Ae(){const ee=j.current&&typeof j.current.value=="string"?j.current.value:f;lg(),ee!==f&&g(ee);const J=ee,be=XM(J);if(!be||H)return;if(a){V(p("settings-readonly"));return}se(!0),V("");let ye=!1;try{ye=!!await t(be)}catch{ye=!1}ye?S(h,J,be):V(p("composer-send-failed")),se(!1)}function ke(){const ee=Q.current&&Q.current.getBoundingClientRect();ee&&N({left:Math.max(6,Math.min(ee.left,window.innerWidth-186)),bottom:window.innerHeight-ee.top+6}),M(!0)}function We(ee){M(!1),ee&&Q.current&&Q.current.focus()}function Ne(){const ee=me.current&&me.current.getBoundingClientRect();if(ee){const J=Math.max(220,Math.min(360,window.innerWidth-12));fe({left:Math.max(6,Math.min(ee.right-J,window.innerWidth-J-6)),bottom:window.innerHeight-ee.top+6,width:J})}ue(!0)}function ge(ee){ue(!1),ee&&me.current&&me.current.focus()}w.useEffect(()=>{if(!z)return;const ee=be=>{be.key==="Escape"&&We(!0)},J=be=>{const ye=Z.current&&Z.current.contains(be.target),ot=Q.current&&Q.current.contains(be.target);!ye&&!ot&&We(!1)};return document.addEventListener("keydown",ee),document.addEventListener("pointerdown",J),()=>{document.removeEventListener("keydown",ee),document.removeEventListener("pointerdown",J)}},[z]),w.useEffect(()=>{if(!Ie)return;const ee=be=>{be.key==="Escape"&&ge(!0)},J=be=>{const ye=de.current&&de.current.contains(be.target),ot=me.current&&me.current.contains(be.target);!ye&&!ot&&ge(!1)};return document.addEventListener("keydown",ee),document.addEventListener("pointerdown",J),()=>{document.removeEventListener("keydown",ee),document.removeEventListener("pointerdown",J)}},[Ie]);function st(ee){if(!(ee.isComposing||Le.current||ee.altKey||ee.ctrlKey||ee.metaKey)){if(ee.key==="ArrowUp"&&ee.currentTarget.selectionStart===0&&ee.currentTarget.selectionEnd===0){L()&&ee.preventDefault();return}ee.key==="ArrowDown"&&x>=0&&ee.currentTarget.selectionStart===f.length&&ee.currentTarget.selectionEnd===f.length&&C()&&ee.preventDefault()}}function Ze(ee){We(!1),ee.current&&ee.current.click()}async function De(ee){if(!ee.length||!n)return;T(!0),V("");const{paths:J,errors:be}=await ag({files:ee,token:e,session:n,node:s,paste:!1});be.length&&V(be.map(ye=>`${ye.name}: ${ye.message}`).join(" · ")),J.length&&g(ye=>ye+(ye&&!ye.endsWith(" ")?" ":"")+J.join(" ")),T(!1)}async function He(ee){var ye;if(!ee.length||!n)return;T(!0),V(""),ne("");const{paths:J,errors:be}=await ag({files:ee,token:e,session:n,node:s,paste:!1});if(be.length&&V(be.map(ot=>`${ot.name}: ${ot.message}`).join(" · ")),J.length){ne(p("attach-inbox-done").replace("{n}",String(J.length)));try{(ye=navigator.vibrate)==null||ye.call(navigator,10)}catch{}setTimeout(()=>ne(""),2500)}T(!1)}function qe(){P.current&&P.current.stop(),O.current&&O.current.stop(),$(!1)}async function wt(){V("");const ee=window.SpeechRecognition||window.webkitSpeechRecognition;if(ee){const J=new ee;J.lang="it-IT",J.continuous=!1,J.interimResults=!0;const be=f?`${f} `:"";J.onresult=ye=>{const ot=Array.from(ye.results).map(oe=>oe[0].transcript).join("");g(be+ot)},J.onend=()=>$(!1),J.onerror=ye=>{V(`voice: ${ye.error||"errore"}`),$(!1)},P.current=J,J.start(),$(!0);return}try{const J=await navigator.mediaDevices.getUserMedia({audio:!0}),be=new MediaRecorder(J),ye=[];be.ondataavailable=ot=>ye.push(ot.data),be.onstop=async()=>{J.getTracks().forEach(ot=>ot.stop()),$(!1),V("trascrivo…");try{const ot=new Blob(ye,{type:be.mimeType||"audio/webm"}),$e=await(await qn(`${u}/voice/transcribe`,e,{method:"POST",headers:{"content-type":"application/octet-stream"},body:ot})).json();$e.error?V($e.error):(V(""),g(ut=>ut+(ut?" ":"")+($e.text||"")))}catch(ot){V(String(ot))}},O.current={stop:()=>be.state!=="inactive"&&be.stop()},be.start(),$(!0)}catch{V("microfono non disponibile"),$(!1)}}function W(){c&&lg(),F?qe():wt()}return l.jsxs("div",{className:"nc-composer",children:[X&&l.jsx("div",{className:"nc-composer-err",children:X}),G&&l.jsx("div",{className:"nc-composer-info",children:G}),l.jsxs("div",{className:"nc-composer-row",children:[n&&l.jsx("button",{ref:Q,className:U?"attach busy":"attach",disabled:U,onClick:()=>z?We(!1):ke(),title:p(U?"attach-uploading":"attach"),"aria-label":p("attach"),"aria-haspopup":"menu","aria-expanded":z,"aria-controls":Ee.current,children:l.jsx(Pt,{name:"attach",size:22})}),z&&l.jsxs("div",{ref:Z,id:Ee.current,role:"menu",className:"nc-attach-menu",style:{left:A.left,bottom:A.bottom},children:[l.jsxs("button",{role:"menuitem",onClick:()=>Ze(ie),children:[l.jsx(Pt,{name:"file",size:18})," ",p("attach-file")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(xe),children:[l.jsx(Pt,{name:"camera",size:18})," ",p("attach-camera")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(Be),children:[l.jsx(Pt,{name:"image",size:18})," ",p("attach-gallery")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(nt),children:[l.jsx(Pt,{name:"folder",size:18})," ",p("attach-inbox")]})]}),l.jsx("button",{ref:me,type:"button",className:"history",onPointerDown:ee=>ee.preventDefault(),onClick:()=>Ie?ge(!1):Ne(),title:p("composer-history-tools"),"aria-label":p("composer-history-tools"),"aria-haspopup":"menu","aria-expanded":Ie,children:l.jsx(Pt,{name:"history",size:21})}),Ie&&l.jsxs("div",{ref:de,role:"menu",className:"nc-composer-history-menu",style:{left:Re.left,bottom:Re.bottom,width:Re.width},children:[l.jsxs("button",{role:"menuitem",className:"nc-composer-history-action",onPointerDown:ee=>ee.preventDefault(),onClick:()=>{_(),ge(!1)},children:[l.jsx(Pt,{name:v?"chevronDown":"chevronUp",size:18}),p(v?"composer-collapse":"composer-expand")]}),l.jsx("div",{className:"nc-composer-history-title",children:p("composer-history")}),b.length===0&&l.jsx("div",{className:"nc-composer-history-empty",children:p("composer-history-empty")}),b.map((ee,J)=>l.jsxs("button",{type:"button",role:"menuitem",className:"nc-composer-history-entry",onPointerDown:be=>be.preventDefault(),onClick:()=>{R(ee.text),ge(!1)},children:[l.jsx("span",{children:ee.text.replace(/\s+/g," ").slice(0,180)}),ee.at>0&&l.jsx("small",{children:new Date(ee.at).toLocaleString()})]},`${ee.at}:${J}`)),b.length>0&&l.jsx("button",{type:"button",role:"menuitem",className:"nc-composer-history-clear",onPointerDown:ee=>ee.preventDefault(),onClick:()=>{I(),ge(!1)},children:p("composer-history-clear")})]}),l.jsx("input",{ref:ie,type:"file",multiple:!0,hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:xe,type:"file",accept:"image/*",capture:"environment",hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:Be,type:"file",accept:"image/*,video/*",multiple:!0,hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:nt,type:"file",multiple:!0,hidden:!0,onChange:ee=>{He(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("textarea",{ref:j,className:v?"expanded":"",rows:v?8:2,value:f,placeholder:p("composer-placeholder"),onChange:ee=>g(ee.target.value),onKeyDown:st,onCompositionStart:()=>{Le.current=!0},onCompositionEnd:()=>{Le.current=!1},onBlur:E}),pe&&l.jsx("button",{type:"button",className:F?"mic on":"mic",title:p("voice"),"aria-label":p("voice"),onPointerDown:ee=>{ee.preventDefault(),W()},onClick:ee=>{ee.detail===0&&W()},children:l.jsx(Pt,{name:"mic",size:22})}),l.jsx("button",{type:"button",className:"go",disabled:H,onPointerDown:ee=>ee.preventDefault(),onClick:Ae,title:p("send"),children:l.jsx(Pt,{name:"enter",size:22})})]})]})}const K0=460,_I=320;function yI({row:t,token:e,panelPort:n=0,anchorRect:s,liveHost:i=null,onLiveHostApplied:a,source:c,onSourceChange:u,onExpand:h,onClose:f,onMouseEnter:g,onMouseLeave:v}){w.useEffect(()=>{const x=L=>{L.key==="Escape"&&f()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[f]);const _=s?Math.max(8,Math.min(s.right+10,window.innerWidth-K0-8)):void 0,b=s?Math.max(8,Math.min(s.top-6,window.innerHeight-_I-8)):void 0;return l.jsxs("div",{className:"nc-peekcloud",style:{left:_,top:b,width:K0},"data-testid":"peek-cloud",onMouseEnter:g,onMouseLeave:v,children:[l.jsxs("div",{className:"nc-peekcloud-testa",children:[l.jsx("b",{className:"nc-peekcloud-nome",children:t.cellName}),[t.nodeLabel,t.subtitle].filter(Boolean).length>0&&l.jsx("span",{className:"nc-peekcloud-sub",children:[t.nodeLabel,t.subtitle].filter(Boolean).join(" · ")}),l.jsx("button",{type:"button",className:"nc-peekcloud-espandi",title:p("cell-peek-expand"),"aria-label":`${p("cell-peek-expand")}: ${t.cellName}`,onClick:()=>h(c),children:"⤢"})]}),l.jsx(mv,{row:t,token:e,panelPort:n,liveHost:i,onLiveHostApplied:a,source:c,onSourceChange:u})]})}function kp(t){return String(t||"?").replace(/^[^a-zA-Z0-9]+/,"").charAt(0).toUpperCase()||"?"}const wI=180,bI=480,Gl=(t,e=[])=>`${e.length?e.join("/"):"local"}:${t}`;function SI({sessions:t=[],cells:e=[],activeSessions:n=[],nodeGroups:s=[],onPick:i,onAddTile:a,onPower:c,onBoot:u,onNodePower:h,onKill:f,onVisibility:g,onNew:v,onNodeRename:_,onSettings:b,onBootError:x,localNodeId:L,fleetCapabilities:C=[],fleetStale:R=!1,fleetOff:S=null,bootSettlement:I=null,localVerified:E=!0,hostByRoute:F={},onDesignateCell:$,onClearHostCell:X,onBootSettlementApplied:V,onOpenVlSession:G,token:ne="",onPeekOpen:K,overlayOpen:D=!1,width:P=240,collapsed:O=!1,onResize:j,onToggleCollapse:z}){const[M,A]=zn(),{pins:N,orders:U,togglePin:T,removePin:H,pinError:se,reorderBlocked:Q,retryPinPersist:Z,clearPinError:me,viewFor:de,updateView:ie,canMoveRoster:xe,moveRoster:Be,stepRoster:nt}=xv(),{groupsFor:Le,moveNode:Ie,stepNode:ue,nodeKey:Re}=kv(),fe=q=>F[Cs(q)]||{},Ee=new Set((e||[]).map(q=>q.tmuxSession)),Y=new Map((t||[]).map(q=>[q.name,q])),pe=(q,ae)=>oP(N,q,ae),Ae=aP,ke=[...e||[]].sort((q,ae)=>Ae(pe(q.tmuxSession,(Y.get(q.tmuxSession)||{}).activity),pe(ae.tmuxSession,(Y.get(ae.tmuxSession)||{}).activity))),We=(t||[]).filter(q=>!Ee.has(q.name)).sort((q,ae)=>Ae(pe(q.name,q.activity),pe(ae.name,ae.activity))||q.name.localeCompare(ae.name)),Ne=new Set(n||[]),[ge,st]=w.useState(null),[Ze,De]=w.useState("preview"),[He,qe]=w.useState(null),wt=w.useRef(null),W=w.useRef(null),ee=w.useRef(null);w.useEffect(()=>{ee.current=ge},[ge]),w.useEffect(()=>()=>{clearTimeout(wt.current),clearTimeout(W.current)},[]);const[J,be]=w.useState(null),[ye,ot]=w.useState(null),[oe,$e]=w.useState(!1),[ut,kt]=w.useState(null),St=(q,ae,je=[],Xe="",Pe=null)=>{const gt=(je.length===0?Y.get(ae.tmuxSession):(Pe||[]).find(Je=>Je&&Je.name===ae.tmuxSession))||{};return{key:q.key,cellName:ae.cell,subtitle:q.subtitle||"",nodeLabel:Xe,node:je.length?je.join("/"):"",session:ae.tmuxSession,route:je,panelUrl:ae.panelUrl||"",telemetry:gt.telemetry||null,preview:gt.preview||ae.preview||"",activity:gt.activity||ae.activity||0}},Lt=(q,ae,je=[],Xe="",Pe="preview")=>xt=>{xt&&xt.stopPropagation(),qe(null),De(Pe),st(q.key),typeof K=="function"&&K()},_t=(q,ae,je)=>{je&&(clearTimeout(W.current),clearTimeout(wt.current),wt.current=setTimeout(()=>{ee.current||qe({itemKey:q.key,routeKey:ae||"",anchorRect:je.getBoundingClientRect(),source:"stream"})},300))},pt=()=>{clearTimeout(wt.current),clearTimeout(W.current),W.current=setTimeout(()=>qe(null),150)},Ut=()=>clearTimeout(W.current),Gt=()=>qe(null),Ot=(q,ae,je,Xe,Pe)=>{if(J&&J.itemKey===q){be(null);return}be({itemKey:q,routeKey:ae||"",canBoot:!!Xe,preserved:!!Pe}),ot(je?je.getBoundingClientRect():null)};w.useEffect(()=>{D&&(st(null),De("preview"))},[D]);const ln=Lv(ke,We,Y,void 0,{autorevole:E,fleetStale:R}),In=co(ln,N,de("local").filter,Ii(U,"local")),wn=Le(s||[]).map(q=>{const ae=(q.route&&q.route.length?q.route:[q.name]).join("/"),je=de(ae);if(q.kind==="vl")return{g:q,nodeRoute:ae,groupView:je,rawItems:[],items:[]};const{rawItems:Xe}=mc(q),Pe=co(Xe,N,je.filter,Ii(U,ae));return{g:q,nodeRoute:ae,groupView:je,rawItems:Xe,items:Pe}}),en=[...In,...wn.flatMap(({items:q,nodeRoute:ae,g:je})=>(q||[]).map(Xe=>({...Xe,nodeRoute:ae,nodeLabel:je.label||je.name})))].filter(q=>q.type==="cell"),bn=ge?en.find(q=>q.key===ge):null,Ft=()=>{if(!He)return null;const q=en.find(Pe=>Pe.key===He.itemKey);if(!q)return null;const ae=q.value,je=q.nodeRoute?s.find(Pe=>(Pe.route||[Pe.name]).join("/")===q.nodeRoute)||{}:null,Xe=q.nodeRoute?je.route||[q.nodeRoute]:[];return l.jsx(yI,{row:St(q,ae,Xe,q.nodeLabel||"",je&&je.sessions),token:ne,anchorRect:He.anchorRect,source:He.source,onSourceChange:Pe=>qe(xt=>xt&&{...xt,source:Pe}),onExpand:Pe=>{qe(null),De(Pe),st(q.key),typeof K=="function"&&K()},onClose:Gt,onMouseEnter:Ut,onMouseLeave:pt})},Xt=(q,ae,je)=>i&&i({session:q,...ae?{node:ae}:{},...Ya.test(String(je||""))?{ownerId:je}:{}}),Jt=async q=>{if(!(q!=null&&q.direct)||!_)return;const ae=window.prompt(p("rename-node-prompt"),q.label||q.name);if(ae!==null)try{await _(q,ae)||window.alert(p("rename-node-invalid"))}catch(je){window.alert(String((je==null?void 0:je.message)||je))}},[Qt,ls]=w.useState({}),[cs,mn]=w.useState(new Set);w.useEffect(()=>{const q=new Map;for(const ae of e||[])q.set(Gl(ae.cell),!!ae.boot);for(const ae of s||[]){const je=ae.route||[ae.name];for(const Xe of ae.cells||[])q.set(Gl(Xe.cell,je),!!Xe.boot)}ls(ae=>{let je=!1;const Xe={...ae};for(const[Pe,xt]of Object.entries(ae))q.has(Pe)&&q.get(Pe)===xt&&(delete Xe[Pe],je=!0);return je?Xe:ae})},[e,s]),w.useEffect(()=>{if(!(I!=null&&I.cell))return;const q=Array.isArray(I.route)?I.route:[],ae=Gl(I.cell,q);ls(je=>({...je,[ae]:!!I.enabled})),V&&V(I.id)},[I,V]);const gn=(q,ae=[])=>{const je=Gl(q.cell,ae);return Object.prototype.hasOwnProperty.call(Qt,je)?Qt[je]:!!q.boot},qs=async(q,ae,je=[],Xe)=>{if(!u)return;const Pe=Gl(ae.cell,je),xt=typeof Xe=="boolean"?Xe:!gn(ae,je);ls(gt=>({...gt,[Pe]:xt})),mn(gt=>new Set(gt).add(Pe));try{await u(ae.cell,xt,je)}catch(gt){ls(Je=>{const Rt={...Je};return delete Rt[Pe],Rt}),x&&x(gt)}finally{mn(gt=>{const Je=new Set(gt);return Je.delete(Pe),Je})}},Vn=(q,ae,je)=>({onToggleLive:async()=>{const Xe=oo({item:q,cellName:ae.cell,route:je,pins:N,hostByRoute:F});$e(!0);const Pe=await eh({action:Xe.isLive?"remove":"use",cellId:ae.cell,route:je,token:ne});$e(!1),kt({messageKey:Pe.messageKey,ok:Pe.ok,cell:Pe.hostCell||ae.cell})},onTogglePin:()=>Cv({view:lh({item:q,pins:N,hostByRoute:F,route:je}),itemKey:q.key,togglePin:T,removePin:H}),onToggleBoot:Xe=>qs(null,ae,je,Xe),onWatchLive:()=>{qe(null),De("stream"),st(q.key),typeof K=="function"&&K()}}),[bt,us]=w.useState(null),le=(q,ae)=>{const je=q.currentTarget.getBoundingClientRect();us({text:ae,y:je.top+je.height/2})},re=()=>us(null),Te=w.useRef(null);w.useEffect(()=>()=>{Te.current&&Te.current()},[]);function Ge(q){q.preventDefault(),q.stopPropagation();const ae=q.clientX,je=P,Xe=xt=>{const gt=Math.max(wI,Math.min(bI,je+(xt.clientX-ae)));j&&j(gt)},Pe=()=>{window.removeEventListener("pointermove",Xe),window.removeEventListener("pointerup",Pe),window.removeEventListener("pointercancel",Pe),window.removeEventListener("blur",Pe),Te.current=null};window.addEventListener("pointermove",Xe),window.addEventListener("pointerup",Pe),window.addEventListener("pointercancel",Pe),window.addEventListener("blur",Pe),Te.current=Pe}const mt=O?{width:48,flex:"0 0 48px"}:{width:P,flex:`0 0 ${P}px`};return O?l.jsxs("aside",{className:"nc-sidebar mini",style:mt,children:[l.jsx("div",{className:"nc-side-head mini",children:l.jsx("button",{className:"nc-collapse-btn",onClick:z,title:p("expand"),children:"⟩"})}),l.jsx("button",{className:"nc-side-gear mini",onClick:()=>b&&b("nodes",!1),title:p("settings"),onMouseEnter:q=>le(q,p("settings")),onMouseLeave:re,children:l.jsx(Pt,{name:"gear",size:16})}),l.jsx("div",{className:"nc-side-scroll mini",children:l.jsxs("div",{className:"nc-side-group mini",children:[de("local").open&&In.map(q=>q.type==="cell"?(()=>{const ae=q.value,je=ae.degraded?"warn":ae.tmux?"on":"",Xe=!!ae.tmux;return l.jsx("button",{type:"button",className:`nc-mini-dot${Ne.has(ae.tmuxSession)?" active":""}`,onMouseEnter:Pe=>{Xe?_t(q,"",Pe.currentTarget):le(Pe,`${ae.cell}: ${q.subtitle}`)},onMouseLeave:()=>{Xe?pt():re()},draggable:Xe,onDragStart:Xe?Pe=>Pe.dataTransfer.setData("text/nc-session",ae.tmuxSession):void 0,onClick:Xe?()=>{qe(null),a&&a(ae.tmuxSession)}:()=>c&&c(ae),onDoubleClick:Xe?()=>Xt(ae.tmuxSession,"",L):void 0,children:l.jsx("span",{className:`nc-dot ${je}${q.working?" working":""}`})},q.key)})():(()=>{const ae=q.value;return l.jsx("button",{type:"button",className:`nc-mini-init${Ne.has(ae.name)?" active":""}`,onMouseEnter:je=>le(je,ae.name),onMouseLeave:re,draggable:!0,onDragStart:je=>je.dataTransfer.setData("text/nc-session",ae.name),onClick:()=>a&&a(ae.name),onDoubleClick:()=>Xt(ae.name,"",L),children:kp(ae.name)},q.key)})()),wn.flatMap(({g:q,nodeRoute:ae,groupView:je,items:Xe})=>q.kind==="vl"?q.status==="up"&&q.sessions.length?q.sessions.map(Pe=>l.jsx("button",{type:"button",className:"nc-mini-init",onMouseEnter:xt=>le(xt,`${q.label||ae}: ${Pe.name}`),onMouseLeave:re,onClick:()=>G&&G(q.peer),children:kp(Pe.name)},Pe.key)):[l.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Pe=>le(Pe,`${q.label||q.name}: ${Qi(q)||p("no-sessions-short")}`),onMouseLeave:re,children:l.jsx("span",{className:`nc-dot${q.status==="up"?" on":" warn"}`})},`nodo-vl-${ae}-${q.name}`)]:q.status==="up"?je.open?Xe.map(Pe=>Pe.type==="cell"?(()=>{const xt=Pe.value,gt=!!xt.tmux;return l.jsx("button",{type:"button",className:`nc-mini-dot${Ne.has(Pe.key)?" active":""}`,onMouseEnter:Je=>{gt?_t(Pe,ae,Je.currentTarget):le(Je,`${q.label||ae}: ${xt.cell} · ${Pe.subtitle}`)},onMouseLeave:()=>{gt?pt():re()},draggable:gt,onDragStart:gt?Je=>Je.dataTransfer.setData("text/nc-session",Pe.key):void 0,onClick:gt?()=>{qe(null),a&&a(Pe.key)}:()=>c&&c({...xt,route:q.route,availableEngines:q.engines||[]}),onDoubleClick:gt?()=>Xt(xt.tmuxSession,ae,q.instanceId):void 0,children:l.jsx("span",{className:`nc-dot ${xt.degraded?"warn":gt?`on${Pe.working?" working":""}`:""}`})},Pe.key)})():(()=>{const xt=Pe.value;return l.jsx("button",{type:"button",className:`nc-mini-init${Ne.has(Pe.key)?" active":""}`,onMouseEnter:gt=>le(gt,`${q.label||ae}: ${xt.name}`),onMouseLeave:re,draggable:!0,onDragStart:gt=>gt.dataTransfer.setData("text/nc-session",Pe.key),onClick:()=>a&&a(Pe.key),onDoubleClick:()=>Xt(xt.name,ae,q.instanceId),children:kp(xt.name)},Pe.key)})()):[]:[l.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Pe=>le(Pe,`${q.label||(q.route||[q.name]).join(" › ")}: ${Qi(q)}`),onMouseLeave:re,children:l.jsx("span",{className:`nc-dot${q.status==="passive"?"":" warn"}`})},`nodo-${(q.route||[q.name]).join("/")}`)])]})}),Ft(),bt&&l.jsx("div",{className:"nc-mini-tip",style:{top:bt.y},children:bt.text})]}):l.jsxs("aside",{className:"nc-sidebar",style:mt,children:[l.jsx("div",{className:"nc-side-live-host",children:l.jsx(xI,{view:Va({liveHost:F[Cs([])],cells:e}),notice:ut})}),l.jsxs("div",{className:"nc-side-head",children:[l.jsx("button",{className:"nc-collapse-btn",onClick:z,title:p("collapse"),children:"⟨"}),l.jsx("span",{className:"nc-side-title",children:p("fleet")}),Q&&l.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:p("reorder-blocked"),"aria-label":p("reorder-blocked"),children:"⇅"}),R&&l.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:p("fleet-stale"),"aria-label":p("fleet-stale"),children:"●"}),S!==null&&l.jsx("span",{className:"nc-side-fleet-off",role:"status",title:`${p("fleet-off")}${S?` (${S})`:""}`,"aria-label":`${p("fleet-off")}${S?` (${S})`:""}`,children:"○"}),l.jsxs("button",{className:"nc-new-btn",onClick:v,title:p("fleet-new-cell"),children:["+ ",p("new")]})]}),l.jsxs("button",{className:"nc-side-gear",onClick:()=>b&&b("nodes",!1),title:p("settings"),children:[l.jsx(Pt,{name:"gear",size:15})," ",p("settings")]}),l.jsx(Tk,{pinError:se,onRetry:Z,onDismiss:me}),l.jsxs("div",{className:"nc-side-scroll",children:[l.jsx(kI,{label:p("position-local"),count:In.length,state:de("local"),onToggle:()=>ie("local",{open:!de("local").open}),onFilter:q=>ie("local",{filter:q})}),de("local").open&&l.jsxs("div",{className:"nc-side-group",children:[In.map(q=>q.type==="cell"?(()=>{var rt;const ae=q.value,je=fe([]),Xe=Ed({hostCell:je.hostCell??null,threadStatus:je.threadStatus,pins:N,item:q}),Pe=ae.degraded?"warn":ae.tmux?"on":"",xt=fm(Xe,je.hostLease??null),gt=ae.degraded?p("cell-degraded"):q.subtitle||(ae.tmux?p("cell-idle"):p("cell-off")),Je=xt?`${gt} · ${p(xt)}`:gt,Rt=!!ae.tmux;return l.jsxs("div",{"data-roster-key":q.key,"data-position":"local",className:`nc-cell${Rt?" live":""}${Ne.has(ae.tmuxSession)?" active":""}`,title:`${ae.cell} · ${q.subtitle}${Je===q.subtitle?"":` · ${Je}`}`,"aria-label":`${ae.cell}, ${q.subtitle}${Je===q.subtitle?"":`, ${Je}`}`,draggable:Rt,onDragStart:Rt?ze=>ze.dataTransfer.setData("text/nc-session",ae.tmuxSession):void 0,onClick:Rt?()=>a&&a(ae.tmuxSession):void 0,onDoubleClick:Rt?()=>Xt(ae.tmuxSession,"",L):void 0,children:[l.jsx(Gi,{position:"local",itemKey:q.key,label:ae.cell,canMove:xe,onMove:(ze,Wt)=>Be("local",ze,Wt,ln),onStep:ze=>nt("local",q.key,ze,ln)}),Rt?l.jsx("button",{type:"button",className:"nc-side-peek",title:p("cell-peek"),"aria-label":`${p("cell-peek")}: ${ae.cell}`,onClick:Lt(q,ae,[],""),onMouseEnter:ze=>_t(q,"",ze.currentTarget),onMouseLeave:pt,children:l.jsx("span",{className:`nc-dot ${Pe}${q.working?" working":""}`})}):l.jsx("span",{className:`nc-dot ${Pe}${q.working?" working":""}`}),l.jsxs("span",{className:"nc-cell-main",children:[l.jsxs("b",{title:ae.cell,children:[ae.cell,oo({item:q,cellName:ae.cell,route:[],pins:N,hostByRoute:F}).isLive&&l.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),l.jsx("small",{title:q.subtitle,children:q.subtitle})]}),q.activity?l.jsx("span",{className:"nc-rel",children:ao(q.activity)}):null,q.fresh&&((rt=(Y.get(ae.tmuxSession)||{}).outbox)==null?void 0:rt.count)>0?l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:Y.get(ae.tmuxSession).outbox.count}):null,l.jsx("button",{type:"button",className:"nc-cellmenu",title:`${p("cell-actions-open")}: ${ae.cell}`,"aria-label":`${p("cell-actions-open")}: ${ae.cell}`,"aria-haspopup":"menu","aria-expanded":J&&J.itemKey===q.key?"true":"false",onClick:ze=>{ze.stopPropagation(),Ot(q.key,"",ze.currentTarget,C.includes("boot")&&!!u,!1)},children:l.jsx("span",{"aria-hidden":"true",children:"⋯"})}),l.jsx("button",{className:`nc-power${ae.tmux?" on":""}${ae.degraded?" warn":""}`,onClick:ze=>{ze.stopPropagation(),c&&c({...ae,boot:gn(ae)})},title:ae.active?p("power-off"):p("power-on"),children:l.jsx(Pt,{name:"power",size:14})})]},q.key)})():(()=>{var je;const ae=q.value;return l.jsxs("div",{"data-roster-key":q.key,"data-position":"local",className:`nc-side-card${Ne.has(ae.name)?" active":""}`,draggable:!0,onDragStart:Xe=>Xe.dataTransfer.setData("text/nc-session",ae.name),onClick:()=>a&&a(ae.name),onDoubleClick:()=>Xt(ae.name,"",L),children:[l.jsx(Gi,{position:"local",itemKey:q.key,label:ae.name,canMove:xe,onMove:(Xe,Pe)=>Be("local",Xe,Pe,ln),onStep:Xe=>nt("local",q.key,Xe,ln)}),l.jsx("span",{className:ae.attached?"nc-dot on":"nc-dot"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:ae.name}),l.jsxs("small",{children:[ae.preview||ae.cmd||p("windows").replace("{n}",String(ae.windows||0)),((je=ae.outbox)==null?void 0:je.count)>0?` · 📦${ae.outbox.count}`:""]})]}),ae.activity?l.jsx("span",{className:"nc-rel",children:ao(ae.activity)}):null,l.jsx("button",{className:`nc-pin${N.includes(q.key)?" on":""}`,title:p("pin"),onClick:Xe=>{Xe.stopPropagation(),T(q.key)},children:N.includes(q.key)?"★":"☆"}),l.jsx("button",{className:`nc-technical${ae.technical?" on":""}`,title:ae.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${ae.technical?p("mark-normal"):p("mark-technical")} ${ae.name}`,onClick:Xe=>{Xe.stopPropagation(),g&&g(ae.name,!ae.technical,[])},children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),onClick:Xe=>{Xe.stopPropagation(),window.confirm(p("terminate-confirm").replace("{name}",ae.name))&&f&&f(ae.name)},children:"⋯"})]},q.key)})()),In.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]}),wn.map(({g:q,nodeRoute:ae,groupView:je,rawItems:Xe,items:Pe})=>{const xt=Bk(q.health),gt=q.fleetState==="stale"?p("fleet-stale"):q.fleetState==="disabled"?p("fleet-off"):"",Je=q.fleetState==="stale"?"warn":xt||(q.status==="up"?"on":q.status==="passive"?"":"warn"),Rt=[q.health?Id(q.health):"",gt].filter(Boolean).join(" · ");return q.kind==="vl"?l.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":Re(q),children:[l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:()=>ie(ae,{open:!je.open}),onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),ie(ae,{open:!je.open}))},children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:Re(q),label:q.label||q.name,onMove:(rt,ze)=>Ie(rt,ze,s||[]),onStep:rt=>ue(Re(q),rt,s||[])}),l.jsx("span",{className:"nc-node-chevron",children:je.open?"⌄":"›"}),l.jsx("span",{className:`nc-dot ${Je}`,title:Rt}),l.jsx("b",{children:q.label||q.name}),l.jsxs("small",{children:[" · ",Qi(q)||[p("node-sessions").replace("{n}",String(q.sessions.length)),gt].filter(Boolean).join(" · ")]})]}),q.status==="up"&&je.open&&l.jsxs("div",{className:"nc-side-group",children:[q.sessions.map(rt=>l.jsxs("div",{className:"nc-side-card nc-vl-session-row",role:"button",tabIndex:0,onClick:()=>G&&G(q.peer),onKeyDown:ze=>{(ze.key==="Enter"||ze.key===" ")&&(ze.preventDefault(),G&&G(q.peer))},children:[l.jsx("span",{className:"nc-dot on"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:rt.name}),l.jsx("small",{children:p("vl-events-title")})]})]},rt.key)),q.sessions.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]})]},`nodo-vl-${ae}-${q.name}`):l.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":Re(q),children:[l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onContextMenu:q.direct&&_?rt=>{rt.preventDefault(),Jt(q)}:void 0,onClick:()=>ie(ae,{open:!je.open}),onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),ie(ae,{open:!je.open}))},children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:Re(q),label:q.label||q.name,onMove:(rt,ze)=>Ie(rt,ze,s||[]),onStep:rt=>ue(Re(q),rt,s||[])}),l.jsx("span",{className:"nc-node-chevron",children:je.open?"⌄":"›"}),l.jsx("span",{className:`nc-dot ${Je}`,title:Rt}),l.jsx("b",{children:q.label||q.name}),l.jsxs("small",{children:[" · ",q.status==="up"?[p("node-sessions").replace("{n}",String(Pe.length)),gt].filter(Boolean).join(" · "):q.health&&Id(q.health)||Qi(q)]}),l.jsxs("select",{className:"nc-node-filter",value:je.filter,title:p(`view-${je.filter}`),onClick:rt=>rt.stopPropagation(),onChange:rt=>ie(ae,{filter:rt.target.value}),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]}),q.direct&&_&&l.jsx("button",{type:"button",className:"nc-node-rename",title:p("rename-node"),"aria-label":`${p("rename-node")} ${q.label||q.name}`,onClick:rt=>{rt.stopPropagation(),Jt(q)},children:"✎"}),q.direct&&q.health&&q.health.managed!==!1&&l.jsx("button",{type:"button",className:`nc-power${q.tunnelStatus==="up"?" on":""}`,title:q.tunnelStatus==="up"?p("power-off"):p("power-on"),onClick:rt=>{rt.stopPropagation(),h&&h(q)},children:l.jsx(Pt,{name:"power",size:14})})]}),(q.status==="up"||q.cellsPreserved)&&je.open&&l.jsxs("div",{className:"nc-side-group",children:[Pe.map(rt=>rt.type==="cell"?(()=>{var Zt;const ze=rt.value,Wt=q.route||[q.name],Sn=fe(Wt),Se=Ed({hostCell:Sn.hostCell??null,threadStatus:Sn.threadStatus,pins:N,item:rt}),Me=fm(Se,Sn.hostLease??null),Ve=!!ze.tmux&&!q.cellsPreserved,ct=ze.degraded?"warn":ze.tmux&&!q.cellsPreserved?"on":"",At=(q.sessions||[]).find(tn=>tn&&tn.name===ze.tmuxSession)||null,Ks=q.cellsPreserved?`${p("fleet-stale")}`:rt.subtitle||(ze.tmux?p("cell-idle"):p("cell-off")),Vs=Me?`${Ks} · ${p(Me)}`:Ks;return l.jsxs("div",{"data-roster-key":rt.key,"data-position":ae,className:`nc-side-card nc-cell${Ve?" live":""}${q.cellsPreserved?" preserved":""}${Ne.has(ze.key)?" active":""}`,title:Vs,draggable:Ve,onDragStart:Ve?tn=>tn.dataTransfer.setData("text/nc-session",ze.key):void 0,onClick:Ve?()=>a&&a(ze.key):void 0,onDoubleClick:Ve?()=>Xt(ze.tmuxSession,ae,q.instanceId):void 0,children:[l.jsx(Gi,{position:ae,itemKey:rt.key,label:ze.cell,canMove:xe,onMove:(tn,rn)=>Be(ae,tn,rn,Xe),onStep:tn=>nt(ae,rt.key,tn,Xe)}),Ve?l.jsx("button",{type:"button",className:"nc-side-peek",title:p("cell-peek"),"aria-label":`${p("cell-peek")}: ${ze.cell}`,onClick:Lt(rt,ze,q.route||[q.name],q.label||q.name),onMouseEnter:tn=>_t(rt,ae,tn.currentTarget),onMouseLeave:pt,children:l.jsx("span",{className:`nc-dot ${ct}${rt.working?" working":""}`})}):l.jsx("span",{className:`nc-dot ${ct}${rt.working?" working":""}`}),l.jsxs("span",{className:"nc-card-main",children:[l.jsxs("b",{children:[ze.cell,oo({item:rt,cellName:ze.cell,route:Wt,pins:N,hostByRoute:F}).isLive&&l.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),l.jsx("small",{title:rt.subtitle,children:rt.subtitle})]}),rt.activity?l.jsx("span",{className:"nc-rel",children:ao(rt.activity)}):null,rt.fresh&&((Zt=(At||{}).outbox)==null?void 0:Zt.count)>0?l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:At.outbox.count}):null,l.jsx("button",{type:"button",className:"nc-cellmenu",title:`${p("cell-actions-open")}: ${ze.cell}`,"aria-label":`${p("cell-actions-open")}: ${ze.cell}`,"aria-haspopup":"menu","aria-expanded":J&&J.itemKey===rt.key?"true":"false",onClick:tn=>{tn.stopPropagation(),Ot(rt.key,ae,tn.currentTarget,u&&(q.capabilities||[]).includes("boot"),!!q.cellsPreserved)},children:l.jsx("span",{"aria-hidden":"true",children:"⋯"})}),(q.capabilities||[]).includes(ze.active?"down":"up")&&l.jsx("button",{className:`nc-power${ze.active?" on":""}${ze.degraded?" warn":""}`,onClick:tn=>{tn.stopPropagation(),c&&c({...ze,boot:gn(ze,q.route||[]),route:q.route,availableEngines:q.engines||[]})},title:ze.active?p("power-off"):p("power-on"),children:l.jsx(Pt,{name:"power",size:14})})]},rt.key)})():(()=>{const ze=rt.value;return l.jsxs("div",{"data-roster-key":rt.key,"data-position":ae,className:`nc-side-card${Ne.has(ze.key)?" active":""}`,draggable:!0,onDragStart:Wt=>Wt.dataTransfer.setData("text/nc-session",ze.key),onClick:()=>a&&a(ze.key),onDoubleClick:()=>Xt(ze.name,ze.node||ae,q.instanceId),children:[l.jsx(Gi,{position:ae,itemKey:rt.key,label:ze.name,canMove:xe,onMove:(Wt,Sn)=>Be(ae,Wt,Sn,Xe),onStep:Wt=>nt(ae,rt.key,Wt,Xe)}),l.jsx("span",{className:ze.attached?"nc-dot on":"nc-dot"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:ze.name}),l.jsx("small",{children:ze.preview?ze.preview:ze.cmd?ze.cmd:p("windows").replace("{n}",String(ze.windows||0))})]}),ze.activity?l.jsx("span",{className:"nc-rel",children:ao(ze.activity)}):null,l.jsx("button",{className:`nc-pin${N.includes(rt.key)?" on":""}`,title:p("pin"),onClick:Wt=>{Wt.stopPropagation(),T(rt.key)},children:N.includes(rt.key)?"★":"☆"}),l.jsx("button",{className:`nc-technical${ze.technical?" on":""}`,title:ze.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${ze.technical?p("mark-normal"):p("mark-technical")} ${ze.name}`,onClick:Wt=>{Wt.stopPropagation(),g&&g(ze.name,!ze.technical,q.route||[])},children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),onClick:Wt=>{Wt.stopPropagation(),window.confirm(p("terminate-confirm").replace("{name}",ze.name))&&f&&f(ze.name,q.route)},children:"⋯"})]},rt.key)})()),Pe.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]})]},`nodo-${(q.route||[q.name]).join("/")}`)})]}),l.jsx("div",{className:"nc-side-lang",children:$1.map((q,ae)=>l.jsxs("span",{children:[ae>0&&" · ",l.jsx("button",{className:`nc-lang-btn${M===q?" on":""}`,onClick:()=>A(q),title:q,children:q.toUpperCase()})]},q))}),l.jsx("div",{className:"nc-side-resize",onPointerDown:Ge,title:""}),bn&&(()=>{const q=bn.value,ae=bn.nodeRoute?s.find(Xe=>(Xe.route||[Xe.name]).join("/")===bn.nodeRoute)||{}:null,je=bn.nodeRoute?ae.route||[bn.nodeRoute]:[];return l.jsx(wk,{row:St(bn,q,je,bn.nodeLabel||"",ae&&ae.sessions),token:ne,initialSource:Ze,onClose:()=>{st(null),De("preview")}})})(),Ft(),J&&(()=>{const q=en.find(Je=>Je.key===J.itemKey);if(!q)return null;const ae=q.value,je=J.routeKey?s.find(Je=>(Je.route||[Je.name]).join("/")===J.routeKey)||{}:null,Xe=J.routeKey?je.route||[J.routeKey]:[],Pe=J.preserved?!1:!!ae.tmux,xt=oo({item:q,cellName:ae.cell,route:Xe,pins:N,hostByRoute:F}),gt=Ev({...xt,canBoot:J.canBoot,boot:gn(ae,Xe),alive:Pe,handlers:Vn(q,ae,Xe)});return l.jsx(Dk,{anchorRect:ye,items:gt,busy:oe,onClose:()=>be(null)})})()]})}function xI({view:t,notice:e}){const n=!!(t&&t.cell),s=n?p("live-host-indicator").replace("{cell}",t.cell).replace("{mode}",p(t.mode?`live-host-mode-${t.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${t.state||"none"}`)):p("live-host-indicator-none");return l.jsxs("div",{className:"nc-live-strip","data-state":t&&t.state?t.state:"none",title:e?`${s} · ${p(e.messageKey)}`:s,children:[l.jsx("span",{className:`nc-live-strip-dot ${Rv(t||{})}`,"aria-hidden":"true"}),l.jsx("span",{className:"nc-live-strip-testo",children:n?t.cell:s}),e&&l.jsx("span",{className:`nc-live-strip-notice${e.ok?" ok":" ko"}`,role:"status",children:p(e.messageKey).replace("{cell}",e.cell||t.cell||"")})]})}function kI({label:t,count:e,state:n,onToggle:s,onFilter:i}){return l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:s,onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s())},children:[l.jsx("span",{className:"nc-node-chevron",children:n.open?"⌄":"›"}),l.jsx("span",{className:"nc-dot on"}),l.jsx("b",{children:t}),l.jsxs("small",{children:[" · ",p("node-sessions").replace("{n}",String(e))]}),l.jsxs("select",{className:"nc-node-filter",value:n.filter,title:p(`view-${n.filter}`),onClick:a=>a.stopPropagation(),onChange:a=>i(a.target.value),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]})]})}const ps={PRESENTE:"presente-verificata",ASSENTE:"assente-verificata",IGNOTA:"ignota"},Cp={OK:"ok",NON_DISPONIBILE:"non-disponibile",RIMOSSO:"rimosso"},ed={LETTURA_NON_VERIFICABILE:"lettura-non-verificabile",OWNER_NON_DISPONIBILE:"owner-non-disponibile",OWNER_RIMOSSO:"owner-rimosso",LOCALE_NON_VERIFICATO:"lettura-locale-non-verificata"},V0={RITORNO:"ritorno-dopo-assenza",IDENTITA:"identita-cambiata"},CI=6e4;function EI(t,e){return!t||!Array.isArray(e)?null:e.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===t)||null}function Y0(t){const e=t&&t.created;return Number.isFinite(e)&&e>0?e:null}function NI({tileKey:t,node:e,nodeGroups:n,sessionsAlive:s,localVerified:i=!0,localIdentita:a=null,lastVerifiedAt:c=null,nowMs:u=0}={}){const h=EI(e,n);let f,g=Cp.OK,v=null,_=null;if(!e)i?!s||s.has(t)?(f=ps.PRESENTE,_=Y0({created:a})):f=ps.ASSENTE:(f=ps.IGNOTA,v=ed.LOCALE_NON_VERIFICATO);else if(!h)f=ps.IGNOTA,g=Cp.RIMOSSO,v=ed.OWNER_RIMOSSO;else if(h.status!=="up")f=ps.IGNOTA,g=Cp.NON_DISPONIBILE,v=h.cause||ed.OWNER_NON_DISPONIBILE;else if(h.inventoryPartial===!0)f=ps.IGNOTA,v=ed.LETTURA_NON_VERIFICABILE;else if(!s||s.has(t)){f=ps.PRESENTE;const x=Array.isArray(h.sessions)?h.sessions.find(L=>L&&L.key===t):null;_=Y0(x)}else f=ps.ASSENTE;const b=f===ps.IGNOTA&&Number.isFinite(c)&&Number.isFinite(u)&&u-c>CI;return{presenza:f,owner:g,causa:v,identita:f===ps.PRESENTE?_:null,verificata:f!==ps.IGNOTA,oltreIlTetto:b}}function dC(){return{presenza:null,identita:null}}function RI(t,e){const n=t&&typeof t=="object"?t:dC();if(!e||e.presenza===ps.IGNOTA)return{runtime:{presenza:n.presenza,identita:n.identita},generazione:0,motivo:null};const s=e.presenza===ps.PRESENTE;let i=null;return s&&(n.presenza===ps.ASSENTE?i=V0.RITORNO:n.presenza===ps.PRESENTE&&n.identita!==null&&e.identita!==null&&n.identita!==e.identita&&(i=V0.IDENTITA)),{runtime:{presenza:e.presenza,identita:s?e.identita===void 0?null:e.identita:null},generazione:i?1:0,motivo:i}}const Tv="nc_input_preferences_v1",Ep="nc-input-preferences",hC=Object.freeze(["double-tap","single-tap","never"]),fC=Object.freeze(["full","compact"]);function LI(){try{return typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1}catch{return!1}}const wr=Object.freeze({terminalKeyboardGesture:"double-tap",keybarKeepsKeyboardClosed:!0,voiceKeepsKeyboardClosed:!0,showKeybarEnter:!0,keybarLayout:"full",showComposer:LI()});function Pv(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{terminalKeyboardGesture:hC.includes(e.terminalKeyboardGesture)?e.terminalKeyboardGesture:wr.terminalKeyboardGesture,keybarKeepsKeyboardClosed:typeof e.keybarKeepsKeyboardClosed=="boolean"?e.keybarKeepsKeyboardClosed:wr.keybarKeepsKeyboardClosed,voiceKeepsKeyboardClosed:typeof e.voiceKeepsKeyboardClosed=="boolean"?e.voiceKeepsKeyboardClosed:wr.voiceKeepsKeyboardClosed,showKeybarEnter:typeof e.showKeybarEnter=="boolean"?e.showKeybarEnter:wr.showKeybarEnter,keybarLayout:fC.includes(e.keybarLayout)?e.keybarLayout:wr.keybarLayout,showComposer:typeof e.showComposer=="boolean"?e.showComposer:wr.showComposer}}function pC(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function G0(t=pC()){if(!t)return{...wr};try{return Pv(JSON.parse(t.getItem(Tv)||"null"))}catch{return{...wr}}}function AI(t,e=pC()){const n=Pv(t);if(e)try{e.setItem(Tv,JSON.stringify(n))}catch{}return n}function Iv(){const[t,e]=w.useState(G0);w.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==Tv&&i.key!==null)return;const a=i!=null&&i.detail?Pv(i.detail):G0();e(a)};return window.addEventListener(Ep,s),window.addEventListener("storage",s),()=>{window.removeEventListener(Ep,s),window.removeEventListener("storage",s)}},[]);const n=w.useCallback(s=>{e(i=>{const a=AI({...i,...s||{}});return window.dispatchEvent(new CustomEvent(Ep,{detail:a})),a})},[]);return[t,n]}function jI({session:t,node:e,ownerId:n,cellName:s,token:i,readonly:a=!1,focused:c,onFocus:u,onClose:h,onOpenSingle:f,onDragTileStart:g,floating:v=!1,minimized:_=!1,takeSize:b=!1,onDetach:x,onReattach:L,onToggleMinimize:C,onFloatDragStart:R,alive:S=!0,sessionAlive:I=S,available:E=!0,stale:F=!1,presence:$=null,fontSize:X=_i,onZoom:V,decks:G=[],currentDeck:ne,onSendToDeck:K,panelUrl:D="",panelCellId:P="",panelPort:O=0}){const[j]=Iv(),z=s||t,M=w.useRef(()=>{}),A=w.useRef(()=>!1),N=w.useRef(()=>{}),U=w.useRef(!1),[T,H]=w.useState(!1),[se,Q]=w.useState(!1),[Z,me]=w.useState(!1),[de,ie]=w.useState(!1),[xe,Be]=w.useState(null),[nt,Le]=w.useState(0),Ie=w.useRef(dC()),ue=e?`${e}:${t}`:t,Re=G.filter(Y=>Y.id!==ne&&Y.available!==!1),fe=$?$.presenza:I?ps.PRESENTE:ps.ASSENTE,Ee=$?$.identita??null:null;return w.useEffect(()=>{const Y=RI(Ie.current,{presenza:fe,identita:Ee});Ie.current=Y.runtime,Y.generazione&&Le(pe=>pe+Y.generazione)},[fe,Ee]),l.jsxs("div",{className:`nc-tile${c?" focused":""}`,onMouseDown:()=>u&&u(ue),children:[l.jsxs("div",{className:`nc-tile-head${v?" nc-float-head":""}`,draggable:!v,onPointerDown:v&&R?Y=>{Y.target&&Y.target.closest&&Y.target.closest(".nc-tile-actions")||R(Y)}:void 0,onDragStart:Y=>{v||(Y.dataTransfer.setData("text/nc-session",ue),Y.dataTransfer.effectAllowed="move",g&&g(ue))},children:[l.jsxs("button",{className:"nc-tile-name",onClick:()=>u&&u(ue),title:e?`${z} · ${e}`:z,children:[l.jsx("span",{className:S?"nc-dot on":"nc-dot"}),l.jsx("b",{children:z})]}),l.jsxs("span",{className:"nc-tile-actions",children:[v?l.jsxs(l.Fragment,{children:[L&&l.jsx("button",{className:"nc-tile-float-btn",onClick:()=>L(ue),title:p("tile-reattach"),"aria-label":p("tile-reattach"),children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("rect",{x:"9",y:"3",width:"12",height:"12",rx:"1"}),l.jsx("path",{d:"M11 21H3v-8M3 21l9-9"})]})}),C&&l.jsx("button",{onClick:()=>C(ue),title:p(_?"tile-restore":"tile-minimize"),"aria-label":p(_?"tile-restore":"tile-minimize"),children:"–"})]}):l.jsxs(l.Fragment,{children:[V&&l.jsx("button",{onClick:()=>V(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:l.jsx(Pt,{name:"zoomOut",size:14})}),V&&l.jsx("button",{onClick:()=>V(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Pt,{name:"zoomIn",size:14})}),K&&Re.length>0&&l.jsxs("select",{className:"nc-tile-deck",title:p("send-to-deck"),value:"",onMouseDown:Y=>Y.stopPropagation(),onChange:Y=>{const pe=Y.target.value;pe&&K(ue,pe),Y.target.value=""},children:[l.jsx("option",{value:"",children:p("send-to-deck")}),Re.map(Y=>l.jsxs("option",{value:Y.id,children:[Y.ownerLabel," · ",Y.name]},Y.id))]}),l.jsx("button",{onClick:()=>Q(Y=>!Y),title:p("composer"),children:"⌨"}),l.jsx("button",{onClick:()=>me(Y=>!Y),title:p("files"),children:"📁"}),D&&l.jsx("button",{onClick:()=>ie(Y=>!Y),title:p("panel"),"aria-pressed":de,children:l.jsx(Pt,{name:"monitor",size:14})}),f&&l.jsx("button",{onClick:()=>f({session:t,node:e,ownerId:n}),title:p("single-view"),children:"↗"})]}),!v&&x&&l.jsx("button",{className:"nc-tile-float-btn",onClick:()=>x(ue),title:p("tile-detach"),"aria-label":p("tile-detach"),children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("rect",{x:"3",y:"9",width:"12",height:"12",rx:"1"}),l.jsx("path",{d:"M13 3h8v8M21 3l-9 9"})]})}),h&&l.jsx("button",{className:"nc-tile-close",onClick:()=>h(ue),title:p("close"),"aria-label":p("close"),children:"✕"})]})]}),l.jsxs("div",{className:"nc-tile-body",children:[$&&$.oltreIlTetto===!0&&l.jsx("div",{className:"nc-tile-unverified",role:"status","data-causa":$.causa||"",children:p("tile-unverified")}),l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:b,focused:c,sendRef:M,composerRef:A,actionRef:N,ctrlRef:U,setCtrlArmed:H,onFiles:Be,fontSize:X,keyboardGesture:j.terminalKeyboardGesture},`${ue}:${nt}`),!E&&l.jsx("div",{className:"nc-tile-unavailable",title:p("deck-owner-unavailable"),children:p("deck-owner-reconnecting")}),E&&F&&l.jsx("div",{className:"nc-tile-stale",title:p("deck-owner-stale"),children:p("deck-owner-stale")}),E&&Z&&l.jsx("div",{className:"nc-tile-files",onMouseDown:Y=>Y.stopPropagation(),children:l.jsx(Eg,{session:t,node:e,token:i,filesEvent:xe,onClose:()=>me(!1)})})]}),E&&se&&l.jsx("div",{className:"nc-tile-composer",onMouseDown:Y=>Y.stopPropagation(),children:l.jsx(uC,{submitText:Y=>A.current(Y),token:i,session:t,node:e,ownerId:n,readonly:a,keepKeyboardClosedOnVoice:j.voiceKeepsKeyboardClosed})}),E&&de&&D&&P&&l.jsx(F1,{title:z,onClose:()=>ie(!1),children:l.jsx(pv,{cellId:P,panelUrl:D,route:e?e.split("/"):[],panelPort:O,token:i,title:z})})]})}function Lg({session:t,node:e,ownerId:n,cells:s,nodeGroups:i}={}){const a=typeof t=="string"?t:"";if(!a)return null;if(e){const u=Array.isArray(i)?i:[];for(const h of u){if(!h||(Array.isArray(h.route)?h.route:[]).join("/")!==e||n&&h.instanceId&&String(n)!==String(h.instanceId))continue;const g=(Array.isArray(h.cells)?h.cells:[]).find(v=>v&&v.tmuxSession===a);if(g)return g}return null}return(Array.isArray(s)?s:[]).find(u=>u&&u.tmuxSession===a)||null}function Rc({session:t,cell:e,node:n,ownerId:s,cells:i,nodeGroups:a}={}){const c=typeof t=="string"?t:"";if(e&&typeof e.cell=="string"&&e.cell)return e.cell;const u=Lg({session:c,node:n,ownerId:s,cells:i,nodeGroups:a});return u&&u.cell?u.cell:c}const X0=.22,J0=.3,mC=(t,e)=>Array.from((t==null?void 0:t.types)||[]).includes(e),Np=t=>mC(t,"text/nc-session"),Q0=t=>{var e;return mC(t,"Files")||(((e=t==null?void 0:t.files)==null?void 0:e.length)||0)>0};function MI(t,e){return t&&Array.isArray(e)?e.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===t):null}function TI(t,e,n){const s=(t-n.left)/(n.width||1),i=(e-n.top)/(n.height||1);return s<X0?"left":s>1-X0?"right":i>=J0&&i<=1-J0?"center":i<.5?"top":"bottom"}const PI=[["left","M15 6l-6 6 6 6",22],["top","M6 15l6-6 6 6",22],["center","M4 8h16M20 8l-3-3M20 8l-3 3M20 16H4M4 16l3-3M4 16l3 3",34],["bottom","M6 9l6 6 6-6",22],["right","M9 6l6 6-6 6",22]];function II({active:t}){return l.jsx("div",{className:"nc-drop-zones","data-testid":"nc-drop-zones","aria-hidden":"true",children:PI.map(([e,n,s])=>l.jsx("div",{className:`nc-drop-zone ${e}${t===e?" on":""}`,"data-zone":e,children:l.jsx("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:n})})},e))})}function Rp(t,e){for(const n of t.columns)for(const s of n.tiles)if($t(s)===e)return s.float||null;return null}function Z0(t,e){for(const n of t.columns)for(const s of n.tiles)if($t(s)===e)return s.fontSize||null;return null}function DI({layout:t,onLayoutChange:e,token:n,readonly:s=!1,sessionsAlive:i,focusSession:a,onFocus:c,onOpenSingle:u,localVerified:h=!0,localIdentities:f=null,localVerifiedAt:g=null,decks:v=[],currentDeck:_,onSendToDeck:b,onResizeEnd:x,cells:L=[],nodeGroups:C=[],panelPort:R=0,nodePanelPorts:S={}}){zn();const I=Date.now(),[E,F]=w.useState(null),[$,X]=w.useState(null),V=w.useRef(null);V.current=$;const[G,ne]=w.useState({z:{},next:1,focus:null,mini:{}}),[K,D]=w.useState(null),P=w.useRef(null);P.current=K;const O=w.useRef(null),j=w.useRef([]),z=w.useRef(null);function M(Y,pe,Ae){const ke=()=>{window.removeEventListener("pointermove",Y),window.removeEventListener("pointerup",We),window.removeEventListener("pointercancel",Ne),window.removeEventListener("blur",Ne)},We=()=>{ke(),z.current=null,pe&&pe()},Ne=()=>{ke(),z.current=null,Ae&&Ae()};window.addEventListener("pointermove",Y),window.addEventListener("pointerup",We),window.addEventListener("pointercancel",Ne),window.addEventListener("blur",Ne),z.current=Ne}w.useEffect(()=>()=>{z.current&&z.current()},[]),w.useEffect(()=>{if(!E&&!K)return;const Y=pe=>{pe.key==="Escape"&&(F(null),K&&z.current&&z.current())};return window.addEventListener("keydown",Y),()=>{window.removeEventListener("keydown",Y)}},[E,K]),w.useEffect(()=>{const Y=()=>F(null);return window.addEventListener("dragend",Y),window.addEventListener("drop",Y),()=>{window.removeEventListener("dragend",Y),window.removeEventListener("drop",Y)}},[]);const A=t.columns.length,N=t.columns.flatMap(Y=>Y.tiles).filter(Y=>Y.float).map(Y=>$t(Y)),U=Y=>!!Y&&Y.tiles.length>0&&Y.tiles.every(pe=>pe.float),T=Y=>E&&E.col===Y&&E.row===void 0,H=!!E&&E.col===A,se=(Y,pe)=>E&&E.col===Y&&E.row===pe&&E.quadrant?` drop-${E.quadrant}`:"";function Q(Y){var We;if(Y.preventDefault(),Q0(Y.dataTransfer)){F(null);return}const pe=Y.dataTransfer.getData("text/nc-session"),Ae=E;if(F(null),!pe||!Ae)return;if(Ae.quadrant==="center"){const Ne=$t(((We=t.columns[Ae.col])==null?void 0:We.tiles[Ae.row])||{});Ne&&Ne!==pe&&e(kP(t,pe,Ne));return}let ke;if(Ae.quadrant){if(ke=TP(t,Ae.col,Ae.row,Ae.quadrant),!ke)return}else ke={col:Ae.col};e(_s(t).includes(pe)?SP(t,pe,ke):Ec(t,pe,ke))}function Z(Y,pe){var ee,J,be;Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const Ae=O.current&&O.current.clientWidth||0,ke=O.current?O.current.getBoundingClientRect():null,We=ke?ke.left:0,Ne=j.current[pe]?j.current[pe].getBoundingClientRect():null,ge=j.current[pe+1]?j.current[pe+1].getBoundingClientRect():null,st=Ne&&ge&&ge.right>Ne.left?Ne.left-(ke?ke.left:0):0,Ze=Number.isFinite(Y.clientX)?Y.clientX:0,De=t.columns[pe].width+(((ee=t.columns[pe+1])==null?void 0:ee.width)||0),He=t.columns.reduce((ye,ot)=>ye+ot.width,0),qe=Ne&&ge&&ge.right>Ne.left?ge.right-Ne.left:Ae*(De/(He||1)),wt=Math.min(Vk,qe/2),W=ye=>{const ot=(Number.isFinite(ye.clientX)?ye.clientX:Ze)-We;let oe=Math.max(wt,Math.min(qe-wt,ot-st)),$e=!1;if(!ye.altKey){for(const ut of hc)if(Math.abs(oe-ut*qe)<=wg){oe=ut*qe,$e=!0;break}}return{border:oe,snapped:$e,alt:ye.altKey===!0}};X({kind:"col",ci:pe,coupleLeft:st,couplePx:qe,live:W(Y),pxOther:O.current&&O.current.clientHeight||0,fsA:((J=t.columns[pe].tiles[0])==null?void 0:J.fontSize)||_i,fsB:((be=t.columns[pe+1].tiles[0])==null?void 0:be.fontSize)||_i}),M(ye=>X(ot=>ot&&{...ot,live:W(ye)}),()=>{var oe,$e;const ye=V.current,ot=((oe=ye==null?void 0:ye.live)==null?void 0:oe.border)??qe/2;X(null),e(D0(t,pe,Ae,ot,{snap:!(($e=ye==null?void 0:ye.live)!=null&&$e.alt)})),x&&x()},()=>X(null))}function me(Y){const pe=O.current&&O.current.clientWidth||0;e(D0(t,Y,pe,Number.NaN,{snap:!0,half:!0})),x&&x()}function de(Y,pe,Ae){var oe;Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const ke=j.current[pe],We=ke&&ke.clientHeight||O.current&&O.current.clientHeight||0,Ne=O.current?O.current.getBoundingClientRect():null,ge=Ne?Ne.top:0,st=ke?ke.getBoundingClientRect():null,Ze=st?st.left-(Ne?Ne.left:0):0,De=st&&st.width>0?st.width:ke&&ke.clientWidth||0,He=Number.isFinite(Y.clientY)?Y.clientY:0,qe=t.columns[pe].tiles,wt=qe[Ae].height+(((oe=qe[Ae+1])==null?void 0:oe.height)||0),W=qe.reduce(($e,ut)=>$e+ut.height,0),ee=qe.slice(0,Ae).reduce(($e,ut)=>$e+ut.height,0),J=(st&&st.height>0?st.top-ge:0)+We*(ee/(W||1)),be=(st&&st.height>0,We*(wt/(W||1))),ye=Math.min(Yk,be/2),ot=$e=>{const ut=(Number.isFinite($e.clientY)?$e.clientY:He)-ge;let kt=Math.max(ye,Math.min(be-ye,ut-J)),St=!1;if(!$e.altKey){for(const Lt of hc)if(Math.abs(kt-Lt*be)<=wg){kt=Lt*be,St=!0;break}}return{border:kt,snapped:St,alt:$e.altKey===!0}};X({kind:"row",ci:pe,ri:Ae,coupleTop:J,couplePx:be,colLeft:Ze,colWidth:De,live:ot(Y),pxOther:ke&&ke.clientWidth||O.current&&O.current.clientWidth||0,fsA:qe[Ae].fontSize||_i,fsB:qe[Ae+1].fontSize||_i}),M($e=>X(ut=>ut&&{...ut,live:ot($e)}),()=>{var kt,St;const $e=V.current,ut=((kt=$e==null?void 0:$e.live)==null?void 0:kt.border)??be/2;X(null),e(O0(t,pe,Ae,We,ut,{snap:!((St=$e==null?void 0:$e.live)!=null&&St.alt)})),x&&x()},()=>X(null))}function ie(Y,pe){const Ae=j.current[Y],ke=Ae&&Ae.clientHeight||O.current&&O.current.clientHeight||0;e(O0(t,Y,pe,ke,Number.NaN,{snap:!0,half:!0})),x&&x()}function xe(Y){e(Nc(t,Y))}const Be={x:.45,y:.12,w:.42,h:.6},nt=8;function Le(Y){ne(pe=>({...pe,z:{...pe.z,[Y]:pe.next},next:pe.next+1,focus:Y})),c&&c(Y)}function Ie(Y){ne(pe=>({...pe,mini:{...pe.mini,[Y]:!pe.mini[Y]}}))}function ue(Y){N.length>=$c||e(CP(t,Y,Be))}function Re(Y,pe){const Ae=[0,1];let ke=!1,We=Y;for(const Ne of[...Ae,...pe])if(Math.abs(Y-Ne)<=nt/window.innerWidth){We=Ne,ke=!0;break}return{v:Math.max(0,Math.min(1,We)),snapped:ke}}function fe(Y,pe){Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const Ae=Rp(t,pe);if(!Ae)return;const ke=Number.isFinite(Y.clientX)?Y.clientX:0,We=Number.isFinite(Y.clientY)?Y.clientY:0,Ne=N.filter(De=>De!==pe).map(De=>Rp(t,De)).filter(Boolean),ge=Ne.flatMap(De=>[De.x,De.x+De.w]),st=Ne.flatMap(De=>[De.y,De.y+De.h]),Ze=De=>{const He=(Number.isFinite(De.clientX)?De.clientX:ke)-ke,qe=(Number.isFinite(De.clientY)?De.clientY:We)-We,wt=Re(Ae.x+He/Math.max(1,window.innerWidth),ge),W=Re(Ae.y+qe/Math.max(1,window.innerHeight),st);return{x:wt.v,y:W.v,w:Ae.w,h:Ae.h,snappedX:wt.snapped,snappedY:W.snapped}};D({key:pe,kind:"move",live:Ze(Y)}),M(De=>D(He=>He&&{...He,live:Ze(De)}),()=>{var He;const De=(He=P.current)==null?void 0:He.live;D(null),De&&e(B0(t,pe,De))},()=>D(null))}function Ee(Y,pe,Ae){Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const ke=Rp(t,pe);if(!ke)return;const We=Number.isFinite(Y.clientX)?Y.clientX:0,Ne=Number.isFinite(Y.clientY)?Y.clientY:0,ge=Math.max(1,window.innerWidth),st=Math.max(1,window.innerHeight);Z0(t,pe);const Ze=De=>{const He=((Number.isFinite(De.clientX)?De.clientX:We)-We)/ge,qe=((Number.isFinite(De.clientY)?De.clientY:Ne)-Ne)/st;let{x:wt,y:W,w:ee,h:J}=ke;return Ae.includes("e")&&(ee=ke.w+He),Ae.includes("s")&&(J=ke.h+qe),Ae.includes("w")&&(wt=ke.x+He,ee=ke.w-He),Ae.includes("n")&&(W=ke.y+qe,J=ke.h-qe),ee=Math.max(.05,Math.min(1-wt,ee)),J=Math.max(.05,Math.min(1-W,J)),{x:wt,y:W,w:ee,h:J}};D({key:pe,kind:"resize",dir:Ae,live:Ze(Y),badge:!0}),M(De=>D(He=>He&&{...He,live:Ze(De)}),()=>{var He;const De=(He=P.current)==null?void 0:He.live;D(null),De&&e(B0(t,pe,De)),x&&x()},()=>D(null))}return l.jsxs("div",{className:`nc-grid${$||K?" gesturing":""}`,ref:O,onDragOver:Y=>{if(Q0(Y.dataTransfer)){Y.preventDefault(),F(null);return}Np(Y.dataTransfer)&&(Y.preventDefault(),E&&E.col===A||F({col:A}))},onDrop:Q,onDragLeave:Y=>{const pe=Y.relatedTarget;(!pe||!(O.current&&O.current.contains(pe)))&&F(null)},children:[t.columns.flatMap((Y,pe)=>{const Ae=[];return Ae.push(l.jsx("div",{className:`nc-col${T(pe)?" drop-newcol":""}${U(Y)?" nc-col-emptyfloat":""}`,ref:ke=>{j.current[pe]=ke},style:{flexGrow:U(Y)?0:Y.width,flexBasis:0},onDragOver:ke=>{Np(ke.dataTransfer)&&(ke.preventDefault(),ke.stopPropagation(),E&&E.col===pe&&E.row===void 0||F({col:pe}))},children:Y.tiles.flatMap((ke,We)=>{const Ne=[],ge=$t(ke),st=MI(ke.node,C),Ze=NI({tileKey:ge,node:ke.node,nodeGroups:C,sessionsAlive:i,localVerified:h,localIdentita:f?f.get(ge):null,lastVerifiedAt:ke.node?(st==null?void 0:st.verifiedAt)??null:g,nowMs:I}),De=ke.unavailable!==!0&&(ke.node?(st==null?void 0:st.status)==="up":Ze.owner==="ok"),He=ke.unavailable!==!0&&Ze.presenza!=="assente-verificata",qe=Lg({session:ke.session,node:ke.node,ownerId:ke.ownerId,cells:L,nodeGroups:C}),wt=Rc({session:ke.session,cell:qe,node:ke.node,ownerId:ke.ownerId,cells:L,nodeGroups:C}),W=typeof(qe==null?void 0:qe.panelUrl)=="string"?qe.panelUrl.trim():"",ee=typeof(qe==null?void 0:qe.cell)=="string"?qe.cell:"",J=ke.float||null,be=!!(J&&G.mini[ge]);return Ne.push(l.jsxs("div",{className:`nc-tile-slot${se(pe,We)}${E&&E.from===ge?" nc-tile-source":""}${J?" nc-float":""}${be?" nc-float-mini":""}`,style:J?{position:"fixed",left:`${J.x*100}%`,top:`${J.y*100}%`,width:`${J.w*100}%`,height:be?"auto":`${J.h*100}%`,zIndex:20+(G.z[ge]||0)}:{flexGrow:ke.height,flexBasis:0},onPointerDown:J?()=>Le(ge):void 0,onDragOver:ye=>{if(!Np(ye.dataTransfer))return;if(J){ye.stopPropagation();return}ye.preventDefault(),ye.stopPropagation();const ot=TI(ye.clientX,ye.clientY,ye.currentTarget.getBoundingClientRect());E&&E.col===pe&&E.row===We&&E.quadrant===ot||F({col:pe,row:We,quadrant:ot,from:E==null?void 0:E.from,ghost:{x:ye.clientX,y:ye.clientY}})},children:[l.jsx(jI,{session:ke.session,node:ke.node,ownerId:ke.ownerId,cellName:wt,token:n,readonly:s,focused:a===ge,onFocus:c,onClose:xe,onOpenSingle:u,floating:!!J,minimized:be,takeSize:!!J,onDetach:J?void 0:ue,onReattach:J?ye=>e(EP(t,ye)):void 0,onToggleMinimize:J?Ie:void 0,onFloatDragStart:J?ye=>fe(ye,ge):void 0,onDragTileStart:J?void 0:ye=>F(ot=>ot?{...ot,from:ye}:{from:ye}),available:ke.unavailable!==!0,stale:ke.stale===!0,alive:De,sessionAlive:He,presence:Ze,fontSize:ke.fontSize,onZoom:ye=>e(MP(t,pe,We,ye)),decks:v,currentDeck:_,onSendToDeck:b,panelUrl:W,panelCellId:ee,panelPort:kc(ke.node?ke.node.split("/"):[],S,R)}),!J&&E&&E.col===pe&&E.row===We&&E.quadrant&&l.jsx(II,{active:E.quadrant}),J&&!be&&["n","s","e","w","se"].map(ye=>l.jsx("div",{className:`nc-float-rz ${ye}`,"data-testid":`float-resize-${ye}`,onPointerDown:ot=>Ee(ot,ge,ye)},`rz-${ye}`))]},ge)),We<Y.tiles.length-1&&Ne.push(l.jsx("div",{className:`nc-divider-h${$&&$.kind==="row"&&$.ci===pe&&$.ri===We?" dragging":""}`,title:p("grid-resize-rows"),onPointerDown:ye=>de(ye,pe,We),onDoubleClick:()=>ie(pe,We)},`h${We}`)),Ne})},`c${pe}`)),pe<A-1&&!U(Y)&&!U(t.columns[pe+1])&&Ae.push(l.jsx("div",{className:`nc-divider-v${$&&$.kind==="col"&&$.ci===pe?" dragging":""}`,title:p("grid-resize-cols"),onPointerDown:ke=>Z(ke,pe),onDoubleClick:()=>me(pe)},`v${pe}`)),Ae}),$&&l.jsx("div",{className:`nc-gesture-shield ${$.kind==="col"?"col":"row"}`,"data-testid":"nc-gesture-shield"}),$&&$.kind==="col"&&hc.map(Y=>l.jsx("div",{className:"nc-gesture-ghost v",style:{left:$.coupleLeft+Y*$.couplePx}},`ghost-v-${Y}`)),$&&$.kind==="row"&&hc.map(Y=>l.jsx("div",{className:"nc-gesture-ghost h",style:{top:$.coupleTop+Y*$.couplePx,left:$.colLeft,width:$.colWidth}},`ghost-h-${Y}`)),$&&$.kind==="col"&&l.jsx("div",{className:`nc-gesture-guide v${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{left:$.coupleLeft+$.live.border}}),$&&$.kind==="row"&&l.jsx("div",{className:`nc-gesture-guide h${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{top:$.coupleTop+$.live.border,left:$.colLeft,width:$.colWidth}}),$&&l.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:$.kind==="col"?{left:$.coupleLeft+$.live.border,top:"50%"}:{top:$.coupleTop+$.live.border,left:"50%"},children:[$.fsA,$.fsB].map((Y,pe)=>{const Ae=pe===0?$.live.border:$.couplePx-$.live.border,ke=Math.max(1,Y*.6),We=Math.max(1,Y*1.2),Ne=$.kind==="col"?`${Math.round(Ae/ke)}×${Math.round($.pxOther/We)}`:`${Math.round($.pxOther/ke)}×${Math.round(Ae/We)}`;return l.jsx("span",{className:"nc-gesture-chip",children:Ne},pe)})}),K&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:`nc-gesture-shield ${K.kind==="resize"?"row":"col"}`,"data-testid":"nc-gesture-shield"}),K.live.snappedX&&l.jsx("div",{className:"nc-float-snap v",style:{left:`${K.live.x*100}%`}}),K.live.snappedY&&l.jsx("div",{className:"nc-float-snap h",style:{top:`${K.live.y*100}%`}}),K.kind==="resize"&&(()=>{const Y=Z0(t,K.key)||_i,pe=Math.max(1,Y*.6),Ae=Math.max(1,Y*1.2);return l.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:{left:`${(K.live.x+K.live.w/2)*100}%`,top:`${(K.live.y+K.live.h)*100}%`},children:l.jsx("span",{className:"nc-gesture-chip",children:`${Math.round(K.live.w*window.innerWidth/pe)}×${Math.round(K.live.h*window.innerHeight/Ae)}`})})})()]}),E&&E.from&&E.ghost&&(()=>{const Y=t.columns.flatMap(Ae=>Ae.tiles).find(Ae=>$t(Ae)===E.from),pe=Y?Rc({session:Y.session,node:Y.node,ownerId:Y.ownerId,cells:L,nodeGroups:C,cell:Lg({session:Y.session,node:Y.node,ownerId:Y.ownerId,cells:L,nodeGroups:C})}):E.from;return l.jsxs("div",{className:"nc-drag-ghost","data-testid":"nc-drag-ghost",style:{left:E.ghost.x,top:E.ghost.y},children:[l.jsxs("div",{className:"nc-drag-ghost-head",children:[l.jsx("span",{className:"nc-dot on"}),l.jsx("b",{children:pe})]}),l.jsx("div",{className:"nc-drag-ghost-body"})]})})(),H&&l.jsx("div",{className:"nc-drop-line-v nc-drop-line-end"}),A===0&&l.jsx("div",{className:"nc-grid-empty",children:p("grid-empty")})]})}const Xi="local",Ws=/^[a-f0-9]{16,64}$/,gC=3,Da=new Map,no=new Map,eS=128;function OI(t){const e=new Set;for(const n of Array.isArray(t)?t:[])!n||!Ws.test(String(n.instanceId||""))||!Array.isArray(n.route)||(e.add(n.instanceId),no.set(n.instanceId,[...n.route]),Da.set(n.instanceId,0));for(const n of[...no.keys()]){if(e.has(n))continue;const s=(Da.get(n)||0)+1;Da.set(n,s),s>gC+32&&(Da.delete(n),no.delete(n))}if(no.size>eS)for(const n of[...no.keys()].slice(0,no.size-eS))Da.delete(n),no.delete(n)}function Vo(t,e){return`${t&&Ws.test(t)?t:Xi}:${e}`}function Hc(t){const e=String(t||""),n=e.indexOf(":");if(n<1)return null;const s=e.slice(0,n),i=e.slice(n+1);return s!==Xi&&!Ws.test(s)||!/^[a-z0-9-]{1,32}$/.test(i)?null:{ownerId:s===Xi?null:s,name:i}}function Lc(t){return Array.isArray(t)&&t.length?t.join("/"):""}function Dv(t){return{columns:Pi(t).columns.map(e=>({width:e.width,tiles:e.tiles.map(n=>({...n}))}))}}function BI(t){const e=new Map;for(const n of Array.isArray(t)?t:[])n&&Ws.test(String(n.instanceId||""))&&Array.isArray(n.route)&&e.set(Lc(n.route),n.instanceId);return e}function $I(t){const e=new Map;for(const n of Array.isArray(t)?t:[])n&&Ws.test(String(n.instanceId||""))&&Array.isArray(n.route)&&e.set(n.instanceId,[...n.route]);return e}function Ag(t,e,n=[]){const s=Dv(t),i=BI(n);for(const a of s.columns)for(const c of a.tiles)c.ownerId||(!c.node&&Ws.test(String(e||""))?c.ownerId=e:c.node&&i.has(c.node)&&(c.ownerId=i.get(c.node)));return s}function Xl(t,e){const n=Hc(t);return!n||!n.ownerId||!e||n.ownerId!==e?t:Vo(null,n.name)}function Ha(t,e,n=[]){const s=Dv(t),i=new Map,a=new Set;for(const c of n)c&&Ws.test(String(c.instanceId||""))&&Array.isArray(c.route)&&(i.set(c.instanceId,[...c.route]),c.stale===!0&&a.add(c.instanceId));for(const c of s.columns)for(const u of c.tiles)if(u.ownerId)if(u.ownerId===e)delete u.node,delete u.unavailable,delete u.stale;else if(i.has(u.ownerId))u.node=Lc(i.get(u.ownerId)),delete u.unavailable,a.has(u.ownerId)?u.stale=!0:delete u.stale;else{const h=Da.get(u.ownerId),f=no.get(u.ownerId);f&&h!==void 0&&h<gC?(u.node=Lc(f),delete u.unavailable,u.stale=!0):(u.unavailable=!0,delete u.stale)}return s}function Jl(t,e,n=[]){const s=Dv(t),i=$I(n);for(const a of s.columns)for(const c of a.tiles)delete c.unavailable,delete c.stale,c.ownerId&&(c.ownerId===e?delete c.node:i.has(c.ownerId)&&(c.node=Lc(i.get(c.ownerId))));return s}function vC(t,e,n=[]){const s=Cr(t);if(!s)return null;if(s.ownerId)return s;if(!s.node)return{...s,...Ws.test(String(e||""))?{ownerId:e}:{}};const i=n.find(a=>Lc(a&&a.route)===s.node);return{...s,...i&&Ws.test(String(i.instanceId||""))?{ownerId:i.instanceId}:{}}}const zI=/^[a-z0-9-]{1,32}$/,ti="main",_C="nc_decks",yC="nc_deck_order_v1",wC=24;function tS(t){return typeof t!="string"?"":t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,32).replace(/-+$/,"")}function Xa(t){return typeof t=="string"&&zI.test(t)}function FI(t){const e=String(t||"").match(/^\/deck\/([^/]+)\/?$/);if(e){let n;try{n=decodeURIComponent(e[1])}catch{n=e[1]}return Xa(n)?n:ti}return ti}function HI(t){const e=String(t||"").match(/^\/deck\/([^/]+)\/([^/]+)\/?$/);if(e){let s,i;try{s=decodeURIComponent(e[1]),i=decodeURIComponent(e[2])}catch{return{id:Vo(null,ti),ownerId:null,name:ti}}if(Ws.test(s)&&Xa(i))return{id:Vo(s,i),ownerId:s,name:i}}const n=FI(t);return{id:Vo(null,n),ownerId:null,name:n}}function Lp(t,e){const n=typeof t=="object"&&t?{ownerId:t.ownerId||null,name:t.name}:Hc(t)||{ownerId:null,name:t},s=Xa(n.name)?n.name:ti,i=n.ownerId?`/deck/${encodeURIComponent(n.ownerId)}/${encodeURIComponent(s)}`:s===ti?"/":`/deck/${encodeURIComponent(s)}`;return e?`${i}#token=${encodeURIComponent(e)}`:i}function bC(t){return t===ti?"nc_grid_v1":`nc_grid_v1__${t}`}function SC(t){const e=[ti];if(Array.isArray(t)){for(const n of t)if(Xa(n)&&n!==ti&&!e.includes(n)&&e.push(n),e.length>=wC)break}return e}function nl(){return typeof localStorage<"u"?localStorage:null}function UI(){const t=nl();if(!t)return[ti];try{return SC(JSON.parse(t.getItem(_C)||"null"))}catch{return[ti]}}function WI(t){const e=nl();if(e)try{e.setItem(_C,JSON.stringify(SC(t)))}catch{}}function Uc(t){return t==="local"||Ws.test(String(t||""))}function hh(t,e){const n=Hc(t);return!!n&&(n.ownerId||"local")===e}function tr(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t).slice(0,64)){if(!Uc(n)||!Array.isArray(s))continue;const i=[...new Set(s.filter(a=>typeof a=="string"&&a.length<=100&&hh(a,n)))].slice(0,wC);i.length&&(e[n]=i)}return e}function Ql(t=nl()){if(!t)return{};try{return tr(JSON.parse(t.getItem(yC)||"null"))}catch{return{}}}function Ap(t,e=nl()){const n=tr(t);if(e)try{e.setItem(yC,JSON.stringify(n))}catch{}return n}function fh(t,e){return Array.isArray(t==null?void 0:t[e])?t[e]:[]}function qI(t,e,n,s,i=[]){if(!Uc(e)||n===s)return tr(t);const a=[...new Set(i.filter(v=>hh(v,e)))];if(!a.includes(n)||!a.includes(s))return tr(t);const c=fh(t,e).filter(v=>a.includes(v)),u=[...c,...a.filter(v=>!c.includes(v))],h=u.indexOf(n),f=u.indexOf(s);u.splice(h,1);const g=u.indexOf(s);return u.splice(h<f?g+1:g,0,n),tr({...t,[e]:u})}function KI(t,e,n,s){if(!Uc(e)||!hh(s,e))return tr(t);const i=fh(t,e);return i.includes(n)?tr({...t,[e]:i.map(a=>a===n?s:a)}):tr(t)}function VI(t,e,n){return Uc(e)?tr({...t,[e]:fh(t,e).filter(s=>s!==n)}):tr(t)}function jp(t,e={},n=[]){const s=new Map,i=new Map;for(const h of Array.isArray(t)?t:[]){const f=h!=null&&h.local?"local":String((h==null?void 0:h.ownerId)||"");!Uc(f)||!hh(h==null?void 0:h.id,f)||(s.has(f)||s.set(f,[]),i.has(f)||i.set(f,i.size),s.get(f).push(h))}const a=new Map;(Array.isArray(n)?n:[]).forEach((h,f)=>{typeof h=="string"&&!a.has(h)&&a.set(h,f)});const c=h=>{if(h==="local")return-1;const f=a.get(`id:${h}`);return f===void 0?Number.MAX_SAFE_INTEGER:f},u=[];for(const h of[...s.keys()].sort((f,g)=>c(f)-c(g)||i.get(f)-i.get(g))){const f=s.get(h),g=fh(e,h),v=new Map(g.map((_,b)=>[_,b]));f.sort((_,b)=>{const x=v.has(_.id)?v.get(_.id):Number.MAX_SAFE_INTEGER,L=v.has(b.id)?v.get(b.id):Number.MAX_SAFE_INTEGER;return x-L}),u.push(...f)}return u}function jg(t){const e=nl();if(!e)return null;try{return JSON.parse(e.getItem(bC(t))||"null")}catch{return null}}function YI(t,e){const n=nl();if(n)try{n.setItem(bC(t),JSON.stringify(e))}catch{}}const Ov="nc_deckbar_collapsed_v1",xC=64;function Bv(t){return t===Xi||Ws.test(String(t||""))}function $v(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;for(const[s,i]of Object.entries(t)){if(n>=xC)break;if(Bv(s)){if(i===!0)e[s]=!0;else if(i===!1)e[s]=!1;else continue;n+=1}}return e}function kC(t,e){return Bv(e)&&Object.prototype.hasOwnProperty.call(t||{},e)?t[e]===!0:!0}function GI(t,e){const n=$v(t);return Bv(e)&&(!Object.prototype.hasOwnProperty.call(n,e)&&Object.keys(n).length>=xC&&delete n[Object.keys(n)[0]],n[e]=!kC(n,e)),n}function CC(){return typeof localStorage<"u"?localStorage:null}function nS(t=CC()){if(!t)return{};try{return $v(JSON.parse(t.getItem(Ov)||"null"))}catch{return{}}}function XI(t,e=CC()){const n=$v(t);if(e)try{e.setItem(Ov,JSON.stringify(n))}catch{}return n}function JI(){const[t,e]=w.useState(nS);w.useEffect(()=>{const i=a=>{(a.key===Ov||a.key===null)&&e(nS())};return window.addEventListener("storage",i),()=>window.removeEventListener("storage",i)},[]);const n=w.useCallback(i=>kC(t,i),[t]),s=w.useCallback(i=>{e(a=>XI(GI(a,i)))},[]);return{collapsed:t,isCollapsed:n,toggle:s}}const zv="nc_deck_presence_v1",sS=3e4,QI=18e4,EC=1e4,NC=32,ZI=/^[A-Za-z0-9_-]{1,64}$/,eD=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),iS="working",tD="on",nD="neutral",sD="warn";function Fv(t){return typeof t=="string"&&ZI.test(t)&&!eD.has(t)}function RC(t){return typeof t=="string"&&Hc(t)!==null}function Hv(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0}function Ja(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;for(const[s,i]of Object.entries(t)){if(n>=NC)break;Fv(s)&&(!i||typeof i!="object"||RC(i.deckId)&&Hv(i.ts)&&(e[s]={deckId:i.deckId,ts:i.ts,focus:i.focus===!0,visible:i.visible===!0},n+=1))}return e}function LC(t,e){const n=Ja(t);if(!Hv(e))return n;const s={};for(const[i,a]of Object.entries(n)){const c=a.visible?sS:QI,u=e-c;a.ts>=u&&a.ts<=e+sS&&(s[i]=a)}return s}function rS(t,e,n,s){if(!Fv(e)||!Hv(s))return Ja(t);const i=LC(t,s);if(!RC(n==null?void 0:n.deckId))return i;if(!Object.prototype.hasOwnProperty.call(i,e)&&Object.keys(i).length>=NC){let a="",c=1/0;for(const[u,h]of Object.entries(i))h.ts<c&&(a=u,c=h.ts);a&&delete i[a]}return i[e]={deckId:n.deckId,ts:s,focus:(n==null?void 0:n.focus)===!0,visible:(n==null?void 0:n.visible)===!0},Ja(i)}function iD(t,e){const n=Ja(t);if(!Fv(e))return n;const s={...n};return delete s[e],s}function rD(t,e){const n=LC(t,e),s={};for(const i of Object.values(n)){const a=i.focus&&i.visible?iS:tD;s[i.deckId]!==iS&&(s[i.deckId]=a)}return s}function AC(){return typeof localStorage<"u"?localStorage:null}function td(t=AC()){if(!t)return{};try{return Ja(JSON.parse(t.getItem(zv)||"null"))}catch{return{}}}function Mp(t,e=AC()){const n=Ja(t);if(e)try{e.setItem(zv,JSON.stringify(n))}catch{}return n}const oD=Math.min(EC,5e3);function aD(){var t,e;try{const n=(e=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:e.call(t);if(n)return`w${n.replaceAll("-","")}`}catch{}return`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,14)}`}const lD=aD();function oS(){const t=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0,e=typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState!=="hidden":!0;return{focus:t,visible:e}}function cD(t,e=!0){const s=w.useRef(lD).current,i=w.useRef(t);i.current=t;const[a,c]=w.useState(()=>({map:{},now:Date.now()})),u=w.useCallback(()=>{c({map:td(),now:Date.now()})},[]);w.useEffect(()=>{if(!e)return;const g=()=>{const C=Date.now(),R=rS(td(),s,{deckId:i.current,...oS()},C);return Mp(R),{map:R,now:C}},v=()=>c(g());v();const _=setInterval(g,EC),b=setInterval(u,oD),x=v,L=C=>{(C.key===zv||C.key===null)&&u()};return window.addEventListener("focus",x),window.addEventListener("blur",x),typeof document<"u"&&document.addEventListener("visibilitychange",x),window.addEventListener("storage",L),()=>{clearInterval(_),clearInterval(b),window.removeEventListener("focus",x),window.removeEventListener("blur",x),typeof document<"u"&&document.removeEventListener("visibilitychange",x),window.removeEventListener("storage",L);try{Mp(iD(td(),s))}catch{}}},[e,s,u]),w.useEffect(()=>{if(!e)return;const g=Date.now(),v=rS(td(),s,{deckId:t,...oS()},g);Mp(v),c({map:v,now:g})},[t,e,s]);const h=w.useMemo(()=>e?rD(a.map,a.now):{},[e,a]);return{dotFor:w.useCallback((g,v=!1)=>e?v?sD:h[g]||nD:null,[h,e]),windowId:s}}const aS=52,lS=18;function uD({ownerKey:t,deckId:e,label:n,onMove:s,onStep:i}){const a=w.useRef(null),c=w.useRef(0),[u,h]=w.useState(!1),f=()=>{var L,C,R,S;const x=a.current;(C=(L=x==null?void 0:x.over)==null?void 0:L.classList)==null||C.remove("nc-deck-over"),(S=(R=x==null?void 0:x.source)==null?void 0:R.classList)==null||S.remove("nc-deck-dragging"),c.current&&cancelAnimationFrame(c.current),c.current=0},g=(x=!1)=>{const L=a.current;if(!L)return;const C=L.target;f(),a.current=null,h(!1);try{L.handle.releasePointerCapture(L.pointerId)}catch{}x&&C&&C!==e&&s(e,C)},v=(x,L)=>{var E,F,$,X,V,G,ne,K;const C=a.current;if(!C)return;C.x=x,C.y=L;const R=(F=(E=document.elementFromPoint(x,L))==null?void 0:E.closest)==null?void 0:F.call(E,"[data-deck-id][data-owner-key]"),S=($=R==null?void 0:R.dataset)==null?void 0:$.deckId,I=((X=R==null?void 0:R.dataset)==null?void 0:X.ownerKey)===t&&S&&S!==e;C.over!==(I?R:null)&&((G=(V=C.over)==null?void 0:V.classList)==null||G.remove("nc-deck-over"),C.over=I?R:null,(K=(ne=C.over)==null?void 0:ne.classList)==null||K.add("nc-deck-over")),C.target=I?S:null},_=()=>{var C,R;const x=a.current;if(!x){c.current=0;return}const L=(R=(C=x.container)==null?void 0:C.getBoundingClientRect)==null?void 0:R.call(C);if(L){const S=x.x<L.left+aS?-lS:x.x>L.right-aS?lS:0;S&&(x.container.scrollLeft+=S,v(x.x,x.y))}c.current=requestAnimationFrame(_)};w.useEffect(()=>{const x=C=>{C.key==="Escape"&&a.current&&(C.preventDefault(),g(!1))},L=()=>g(!1);return window.addEventListener("keydown",x),window.addEventListener("blur",L),()=>{window.removeEventListener("keydown",x),window.removeEventListener("blur",L),f(),a.current=null}},[e,t]);const b=x=>{var R;if(x.pointerType==="mouse"&&x.button!==0)return;x.preventDefault(),x.stopPropagation(),x.currentTarget.focus({preventScroll:!0});const L=x.currentTarget.closest("[data-deck-id][data-owner-key]"),C=x.currentTarget.closest(".nc-deckbar");a.current={pointerId:x.pointerId,handle:x.currentTarget,source:L,container:C,target:null,over:null,x:x.clientX,y:x.clientY},(R=L==null?void 0:L.classList)==null||R.add("nc-deck-dragging");try{x.currentTarget.setPointerCapture(x.pointerId)}catch{}h(!0),c.current=requestAnimationFrame(_)};return l.jsx("button",{type:"button",className:`nc-deck-handle${u?" active":""}`,"aria-label":`${p("reorder")} ${n}`,"aria-keyshortcuts":"ArrowLeft ArrowRight",title:p("reorder-deck-help"),onClick:x=>{x.preventDefault(),x.stopPropagation()},onDragStart:x=>x.preventDefault(),onKeyDown:x=>{x.key!=="ArrowLeft"&&x.key!=="ArrowRight"||(x.preventDefault(),x.stopPropagation(),i(x.key==="ArrowLeft"?-1:1))},onPointerDown:b,onPointerMove:x=>{!a.current||x.pointerId!==a.current.pointerId||(x.preventDefault(),x.stopPropagation(),v(x.clientX,x.clientY))},onPointerUp:x=>{!a.current||x.pointerId!==a.current.pointerId||(x.preventDefault(),x.stopPropagation(),g(!0))},onPointerCancel:()=>g(!1),onLostPointerCapture:()=>{a.current&&g(!1)},children:"↔"})}function dD({decks:t=[],currentDeck:e="local:main",onCreate:n,onRename:s,onDelete:i,onReorder:a,onOpenWindow:c,onNavigate:u,saveState:h="idle",error:f="",sidebarVisible:g,onToggleSidebar:v,conflict:_=!1,onReloadDeck:b=null}){zn();const{isCollapsed:x,toggle:L}=JI(),{dotFor:C}=cD(e),[R,S]=w.useState(null),[I,E]=w.useState(""),[F,$]=w.useState(!1),[X,V]=w.useState(""),[G,ne]=w.useState(""),K=tS(I),D=Xa(K),P=[];for(const A of t){const N=A.local?"local":A.ownerId;let U=P.find(T=>T.key===N);U||(U={key:N,label:A.ownerLabel||(A.local?"Local":N),local:!!A.local,decks:[]},P.push(U)),U.decks.push(A)}const O=async()=>{if(D){$(!0),V("");try{n&&await n(K,R),E(""),S(null)}catch(A){V(String(A.message||A))}$(!1)}},j=A=>{ne(""),c&&c(A.id)||ne(A.id)},z=async A=>{if(!(A.id===e||!u||F||A.available===!1)){$(!0),V("");try{await u(A.id)}catch(N){V(String((N==null?void 0:N.message)||N))}$(!1)}},M=(A,N,U)=>{const T=A.decks.findIndex(se=>se.id===N.id),H=A.decks[T+U];T>=0&&H&&a&&!F&&a(N.id,H.id)};return l.jsxs("div",{className:"nc-deckbar",children:[v&&l.jsx("button",{className:"nc-deck-sidebar-toggle",title:p("toggle-sidebar"),onClick:v,children:g?"◀":"☰"}),l.jsx("span",{className:"nc-deckbar-label",children:p("decks")}),l.jsx("div",{className:"nc-deck-chips",children:P.map(A=>{const N=x(A.key),U=`nc-deck-content-${A.key}`,T=A.local?"Local":A.label,H=A.decks.some(Z=>Z.id===e),se=(A.decks.find(Z=>Z.id===e)||{}).name,Q=p(A.decks.length===1?"owner-deck-count-one":"owner-deck-count-many").replace("{count}",A.decks.length);return l.jsxs("span",{className:`nc-deck-owner-group${N?" collapsed":""}`,"data-owner-key":A.key,"data-collapsed":N?"1":"0",children:[l.jsxs("button",{type:"button",className:"nc-deck-owner-toggle","aria-expanded":!N,"aria-controls":U,title:p(N?"expand-owner":"collapse-owner").replace("{owner}",T),onClick:()=>{!N&&R===A.key&&(E(""),S(null)),L(A.key)},children:[l.jsx("span",{className:"nc-deck-owner-caret","aria-hidden":"true",children:N?"▸":"▾"}),l.jsx("span",{className:"nc-deck-owner",children:T})]}),N&&l.jsxs("span",{className:"nc-deck-summary",title:Q,children:[l.jsx("span",{className:"nc-deck-summary-count",children:A.decks.length}),H&&l.jsxs("span",{className:"nc-deck-summary-current",children:["• ",se]})]}),l.jsxs("span",{id:U,className:"nc-deck-owner-content",hidden:N,children:[A.decks.map(Z=>{const me=C(Z.id,Z.available===!1);return l.jsxs("span",{"data-deck-id":Z.id,"data-owner-key":A.key,className:`nc-deck-chip${Z.id===e?" current":""}${Z.available===!1?" offline":""}`,children:[me&&l.jsx(hD,{state:me}),l.jsx(uD,{ownerKey:A.key,deckId:Z.id,label:`${A.label} · ${Z.name}`,onMove:(de,ie)=>{a&&!F&&a(de,ie)},onStep:de=>M(A,Z,de)}),l.jsxs("button",{className:"nc-deck-open",title:Z.available===!1?`${Z.ownerLabel} offline${Z.refreshFailedAt?" · aggiornamento in ritardo":""}`:Z.id===e?p("deck-current"):`${Z.ownerLabel} · ${Z.name}`,disabled:F||Z.available===!1,onClick:()=>z(Z),children:[Z.name,Z.id===e?" •":""]}),Z.available!==!1&&Z.stale===!0&&Z.refreshFailedAt?l.jsx("span",{className:"nc-deck-stale",title:`${Z.ownerLabel} · ${p("deck-stale")}`,children:p("deck-stale-badge")}):null,l.jsx("button",{className:"nc-deck-mini",disabled:Z.available===!1,title:p("detach-deck"),onClick:()=>j(Z),children:"↗"}),Z.name!==ti&&l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"nc-deck-mini",disabled:Z.available===!1,title:p("rename-deck"),onClick:()=>{const de=(typeof window<"u"?window.prompt(p("rename-deck"),Z.name):"")||"",ie=tS(de);Xa(ie)&&ie!==Z.name&&s&&s(Z.id,ie).catch(xe=>V(String(xe.message||xe)))},children:"✎"}),l.jsx("button",{className:"nc-deck-mini nc-deck-del",disabled:Z.available===!1,title:p("delete-deck"),onClick:()=>{(typeof window>"u"||window.confirm(p("delete-deck-confirm").replace("{name}",`${Z.ownerLabel} · ${Z.name}`)))&&i&&i(Z.id).catch(de=>V(String(de.message||de)))},children:"✕"})]})]},Z.id)}),R===A.key?l.jsxs("span",{className:"nc-deck-add",children:[l.jsx("input",{autoFocus:!0,className:D||!I?"":"invalid",placeholder:p("deck-name"),value:I,onChange:Z=>E(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&O(),Z.key==="Escape"&&(E(""),S(null))}}),I&&D&&K!==I&&l.jsxs("span",{className:"nc-deck-slug",children:["→ ",K]}),l.jsx("button",{className:"nc-deck-ok",disabled:!D||F,onClick:O,children:p("create")}),l.jsx("button",{className:"nc-deck-cancel",onClick:()=>{E(""),S(null)},children:p("cancel")})]}):l.jsxs("button",{className:"nc-deck-newbtn",disabled:F||A.decks.every(Z=>Z.available===!1),title:`${p("new-deck")} · ${A.label}`,onClick:()=>{E(""),S(A.key)},children:["+ ",p("new")]})]})]},A.key)})}),l.jsx("span",{className:`nc-deck-state ${h}`,title:p("deck-autosave"),children:p(h==="saving"?"saving":h==="saved"?"saved":"deck-autosave")}),(X||f)&&l.jsx("span",{className:"nc-deck-error",children:X||f}),_&&b&&l.jsx("button",{className:"nc-deck-reload",onClick:b,children:p("reload")}),G&&l.jsx("button",{className:"nc-deck-fallback",onClick:()=>c&&c(G),children:p("popup-blocked")})]})}function hD({state:t}){if(!t)return null;const e=p(`dot-${t}`);return l.jsx("span",{className:`nc-deck-dot ${t}`,role:"img","aria-label":e,title:e})}var Pa={},Tp,cS;function fD(){return cS||(cS=1,Tp=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Tp}var Pp={},Jr={},uS;function ea(){if(uS)return Jr;uS=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Jr.getSymbolSize=function(s){if(!s)throw new Error('"version" cannot be null or undefined');if(s<1||s>40)throw new Error('"version" should be in range from 1 to 40');return s*4+17},Jr.getSymbolTotalCodewords=function(s){return e[s]},Jr.getBCHDigit=function(n){let s=0;for(;n!==0;)s++,n>>>=1;return s},Jr.setToSJISFunction=function(s){if(typeof s!="function")throw new Error('"toSJISFunc" is not a valid function.');t=s},Jr.isKanjiModeEnabled=function(){return typeof t<"u"},Jr.toSJIS=function(s){return t(s)},Jr}var Ip={},dS;function Uv(){return dS||(dS=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(s){return s&&typeof s.bit<"u"&&s.bit>=0&&s.bit<4},t.from=function(s,i){if(t.isValid(s))return s;try{return e(s)}catch{return i}}})(Ip)),Ip}var Dp,hS;function pD(){if(hS)return Dp;hS=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let s=0;s<n;s++)this.putBit((e>>>n-s-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Dp=t,Dp}var Op,fS;function mD(){if(fS)return Op;fS=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,s,i){const a=e*this.size+n;this.data[a]=s,i&&(this.reservedBit[a]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,s){this.data[e*this.size+n]^=s},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},Op=t,Op}var Bp={},pS;function gD(){return pS||(pS=1,(function(t){const e=ea().getSymbolSize;t.getRowColCoords=function(s){if(s===1)return[];const i=Math.floor(s/7)+2,a=e(s),c=a===145?26:Math.ceil((a-13)/(2*i-2))*2,u=[a-7];for(let h=1;h<i-1;h++)u[h]=u[h-1]-c;return u.push(6),u.reverse()},t.getPositions=function(s){const i=[],a=t.getRowColCoords(s),c=a.length;for(let u=0;u<c;u++)for(let h=0;h<c;h++)u===0&&h===0||u===0&&h===c-1||u===c-1&&h===0||i.push([a[u],a[h]]);return i}})(Bp)),Bp}var $p={},mS;function vD(){if(mS)return $p;mS=1;const t=ea().getSymbolSize,e=7;return $p.getPositions=function(s){const i=t(s);return[[0,0],[i-e,0],[0,i-e]]},$p}var zp={},gS;function _D(){return gS||(gS=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},t.from=function(i){return t.isValid(i)?parseInt(i,10):void 0},t.getPenaltyN1=function(i){const a=i.size;let c=0,u=0,h=0,f=null,g=null;for(let v=0;v<a;v++){u=h=0,f=g=null;for(let _=0;_<a;_++){let b=i.get(v,_);b===f?u++:(u>=5&&(c+=e.N1+(u-5)),f=b,u=1),b=i.get(_,v),b===g?h++:(h>=5&&(c+=e.N1+(h-5)),g=b,h=1)}u>=5&&(c+=e.N1+(u-5)),h>=5&&(c+=e.N1+(h-5))}return c},t.getPenaltyN2=function(i){const a=i.size;let c=0;for(let u=0;u<a-1;u++)for(let h=0;h<a-1;h++){const f=i.get(u,h)+i.get(u,h+1)+i.get(u+1,h)+i.get(u+1,h+1);(f===4||f===0)&&c++}return c*e.N2},t.getPenaltyN3=function(i){const a=i.size;let c=0,u=0,h=0;for(let f=0;f<a;f++){u=h=0;for(let g=0;g<a;g++)u=u<<1&2047|i.get(f,g),g>=10&&(u===1488||u===93)&&c++,h=h<<1&2047|i.get(g,f),g>=10&&(h===1488||h===93)&&c++}return c*e.N3},t.getPenaltyN4=function(i){let a=0;const c=i.data.length;for(let h=0;h<c;h++)a+=i.data[h];return Math.abs(Math.ceil(a*100/c/5)-10)*e.N4};function n(s,i,a){switch(s){case t.Patterns.PATTERN000:return(i+a)%2===0;case t.Patterns.PATTERN001:return i%2===0;case t.Patterns.PATTERN010:return a%3===0;case t.Patterns.PATTERN011:return(i+a)%3===0;case t.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(a/3))%2===0;case t.Patterns.PATTERN101:return i*a%2+i*a%3===0;case t.Patterns.PATTERN110:return(i*a%2+i*a%3)%2===0;case t.Patterns.PATTERN111:return(i*a%3+(i+a)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}}t.applyMask=function(i,a){const c=a.size;for(let u=0;u<c;u++)for(let h=0;h<c;h++)a.isReserved(h,u)||a.xor(h,u,n(i,h,u))},t.getBestMask=function(i,a){const c=Object.keys(t.Patterns).length;let u=0,h=1/0;for(let f=0;f<c;f++){a(f),t.applyMask(f,i);const g=t.getPenaltyN1(i)+t.getPenaltyN2(i)+t.getPenaltyN3(i)+t.getPenaltyN4(i);t.applyMask(f,i),g<h&&(h=g,u=f)}return u}})(zp)),zp}var nd={},vS;function jC(){if(vS)return nd;vS=1;const t=Uv(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return nd.getBlocksCount=function(i,a){switch(a){case t.L:return e[(i-1)*4+0];case t.M:return e[(i-1)*4+1];case t.Q:return e[(i-1)*4+2];case t.H:return e[(i-1)*4+3];default:return}},nd.getTotalCodewordsCount=function(i,a){switch(a){case t.L:return n[(i-1)*4+0];case t.M:return n[(i-1)*4+1];case t.Q:return n[(i-1)*4+2];case t.H:return n[(i-1)*4+3];default:return}},nd}var Fp={},Zl={},_S;function yD(){if(_S)return Zl;_S=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let s=1;for(let i=0;i<255;i++)t[i]=s,e[s]=i,s<<=1,s&256&&(s^=285);for(let i=255;i<512;i++)t[i]=t[i-255]})(),Zl.log=function(s){if(s<1)throw new Error("log("+s+")");return e[s]},Zl.exp=function(s){return t[s]},Zl.mul=function(s,i){return s===0||i===0?0:t[e[s]+e[i]]},Zl}var yS;function wD(){return yS||(yS=1,(function(t){const e=yD();t.mul=function(s,i){const a=new Uint8Array(s.length+i.length-1);for(let c=0;c<s.length;c++)for(let u=0;u<i.length;u++)a[c+u]^=e.mul(s[c],i[u]);return a},t.mod=function(s,i){let a=new Uint8Array(s);for(;a.length-i.length>=0;){const c=a[0];for(let h=0;h<i.length;h++)a[h]^=e.mul(i[h],c);let u=0;for(;u<a.length&&a[u]===0;)u++;a=a.slice(u)}return a},t.generateECPolynomial=function(s){let i=new Uint8Array([1]);for(let a=0;a<s;a++)i=t.mul(i,new Uint8Array([1,e.exp(a)]));return i}})(Fp)),Fp}var Hp,wS;function bD(){if(wS)return Hp;wS=1;const t=wD();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(s){this.degree=s,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(s){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(s.length+this.degree);i.set(s);const a=t.mod(i,this.genPoly),c=this.degree-a.length;if(c>0){const u=new Uint8Array(this.degree);return u.set(a,c),u}return a},Hp=e,Hp}var Up={},Wp={},qp={},bS;function MC(){return bS||(bS=1,qp.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),qp}var Ki={},SS;function TC(){if(SS)return Ki;SS=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const s="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
|
|
157
|
+
`),b&&(b.current=null),qt==null||qt.removeEventListener("blur",wn),(ia=E.current)==null||ia.removeEventListener("paste",Ft,!0),(ul=E.current)==null||ul.removeEventListener("keydown",Xt,!0),()=>{var Ke,et;try{(et=(Ke=$.current)==null?void 0:Ke.dispose)==null||et.call(Ke)}catch{}$.current=null,oe.dispose()}}F.current={term:oe,fit:$e,sock:Jt,setKeyboardGesture:ln};let Qt=null;const ls=oe.onData(ve=>{if(s){Qt&&(Qt.ok=!1);return}const Ke=en&&Date.now()<bn;Xt(),!Qt&&!Ke&&ve.length>=1&&(f&&f.current||v&&v.current)&&(ve=YM(ve,{ctrl:!!(f&&f.current),alt:!!(v&&v.current)}),f&&(f.current=!1),v&&(v.current=!1),g&&g(!1),_&&_(!1));const et=Jt.sendInput(ve);Qt&&(Qt.seen=!0,Qt.ok=Qt.ok&&et)});c&&(c.current=ve=>Jt.sendInput(ve)),h&&(h.current=ve=>Jt.action(ve)),u&&(u.current=JM({isReady:()=>!s&&Jt.isReady(),paste:ve=>{const Ke={seen:!1,ok:!0};Qt=Ke;try{oe.paste(ve)}catch{Ke.ok=!1}finally{Qt=null}return Ke.seen&&Ke.ok},send:ve=>Jt.sendInput(ve)}));const cs=ve=>{Ze.current=ve,st(ve)};let mn=null;const gn=oe.onSelectionChange(()=>{const ve=oe.getSelection();ve?(D(ve),me(!1)):me(!0);const Ke=iT(oe.getSelectionPosition(),oe.cols),et=Ke?m0(Ke.start,Ke.end,oe.cols):null;ie(et),xe.current=et,et||cs(null),!et&&mn&&Ar();let dt=null;if(et&&typeof oe.buffer.active.getLine=="function"){const Nt=[];for(let jt=et.start.row;jt<=et.end.row;jt++){const It=oe.buffer.active.getLine(jt);Nt.push(It?It.translateToString():"")}dt={startRow:et.start.row,endRow:et.end.row,lines:Nt}}De.current=dt,qe(!1)}),qs=oe.onRender(ve=>{var Ke;if((Ke=oe.hasSelection)!=null&&Ke.call(oe)){const et=De.current,dt=ve&&ve.start,Nt=ve&&ve.end;if(et&&Number.isInteger(dt)&&Number.isInteger(Nt)&&typeof oe.buffer.active.getLine=="function"){const jt=Number(oe.buffer.active.viewportY)||0,It=Math.max(jt+dt,et.startRow),nn=Math.min(jt+Nt,et.endRow);for(let Yn=It;Yn<=nn;Yn++){const cn=oe.buffer.active.getLine(Yn);if((cn?cn.translateToString():"")!==et.lines[Yn-et.startRow]){qe(!0);break}}}Ie(jt=>jt+1)}}),Vn=oe.onScroll(()=>{var ve;(ve=oe.hasSelection)!=null&&ve.call(oe)&&Ie(Ke=>Ke+1)});oe.attachCustomKeyEventHandler(ve=>(ve.ctrlKey||ve.metaKey)&&ve.key.toLowerCase()==="c"&&oe.getSelection()?(ve.type==="keydown"&&rg(oe.getSelection()),!1):!0);const bt=E.current;let us=!1;const le=async ve=>{if(!ve.length||us)return;if(s){z({error:p("settings-readonly")});return}us=!0,z({current:0,total:ve.length,name:""});const Ke=await ag({files:ve,token:n,session:t,node:e,paste:!0,onProgress:({index:et,total:dt,name:Nt,state:jt,error:It})=>z({current:et+1,total:dt,name:Nt,...jt==="error"?{error:It}:{}})});us=!1,Ke.errors.length?z({error:Ke.errors.map(et=>`${et.name}: ${et.message}`).join(" · ")}):(z({done:!0,total:Ke.paths.length}),setTimeout(()=>z(null),1600))},re=ve=>{const Ke=ve.clipboardData;if(!vp(Ke))return;const et=y0(Ke);et.length&&(ve.preventDefault(),ve.stopPropagation(),le(et))},Te=ve=>{vp(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation())},Ge=ve=>{vp(ve.dataTransfer)&&(ve.preventDefault(),ve.stopPropagation(),le(y0(ve.dataTransfer)))};bt.addEventListener("paste",re,!0),bt.addEventListener("dragenter",Te,!0),bt.addEventListener("dragover",Te,!0),bt.addEventListener("drop",Ge,!0);const mt=24,q=(ve,Ke)=>{const dt=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),Nt=Math.floor((ve-dt.left)/Math.max(1,dt.width)*oe.cols)+1,jt=Math.floor((Ke-dt.top)/Math.max(1,dt.height)*oe.rows)+1;return{col:Math.max(1,Math.min(oe.cols,Nt)),row:Math.max(1,Math.min(oe.rows,jt))}},ae=(ve,Ke={mode:null,remainder:0},et=null,dt=null)=>{const Nt=E.current,jt=Nt?Nt.getBoundingClientRect().height:mt,It=CT({alternateScreen:oe.buffer.active.type==="alternate",readonly:s,mouseTracking:_t()}),nn=It==="mouse"?"mouse":et||It,Yn=Ke.mode===nn?Ke.remainder+ve:ve,cn=NT({mode:nn,accumulated:Yn,threshold:nn==="page"?jt:mt});for(const Is of RT(cn,dt))Is.kind==="input"?Jt.sendInput(Is.seq):Jt.action(Is.name);return{mode:nn,remainder:cn.remainder}};let je=null,Xe=null,Pe=null,xt=null,gt=!1,Je=!1,Rt={mode:null,remainder:0},rt=null,ze=null,Wt=null,Sn=!1;const Se=750;let Me=0;const Ve=()=>{Wt&&clearTimeout(Wt),Wt=null},ct=(ve,Ke)=>{const dt=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),Nt=Math.max(0,Math.min(oe.cols-1,Math.floor((ve-dt.left)/Math.max(1,dt.width)*oe.cols))),jt=Math.max(0,Math.min(oe.rows-1,Math.floor((Ke-dt.top)/Math.max(1,dt.height)*oe.rows)));return{col:Nt,row:oe.buffer.active.viewportY+jt}},At=()=>{const et=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect().height/Math.max(1,oe.rows),dt=bt.querySelector(".nc-sel-handle"),Nt=dt?dt.getBoundingClientRect().height:0;return-.3*(Nt>0?Nt:et)},Ks=(ve,Ke)=>ct(ve.clientX,ve.clientY+Ke),Vs=ve=>{const et=(bt.querySelector(".xterm-screen")||bt).getBoundingClientRect(),dt=bt.getBoundingClientRect(),Nt=et.width/Math.max(1,oe.cols),jt=et.height/Math.max(1,oe.rows),It=Number(oe.buffer.active.viewportY)||0,nn=Math.max(0,Math.min(oe.rows-1,ve.row-It));A({left:`${et.left-dt.left+ve.col*Nt}px`,top:`${et.top-dt.top+nn*jt}px`,width:`${Nt}px`,height:`${jt}px`})},Zt=ve=>{if(Me=Date.now(),cs("touch"),Ve(),Sn=!1,gt=!1,Je||ve.touches.length!==1){Je=!0,gt=!0,Gt=null,A(null),je=null,Xe=null,Pe=null,xt=null;return}if(G.current){ve.preventDefault(),ve.stopPropagation();const et=ct(ve.touches[0].clientX,ve.touches[0].clientY),dt=oe.buffer.active.getLine(et.row),Nt=Aa({line:dt,col:et.col,side:"start",cols:oe.cols}),jt=g0({line:dt,col:Nt,cols:oe.cols});ze={row:et.row,col:jt.start};const It={row:et.row,col:jt.end};oe.clearSelection(),cs("touch"),ke(!0),Ee("end"),oe.select(jt.start,et.row,jt.end-jt.start+1),Vs(It);return}je=ve.touches[0].clientY,Xe=ve.touches[0].clientX,Pe=Xe,xt=je,Rt={mode:null,remainder:0},rt=null;const Ke={x:Xe,y:je};Wt=setTimeout(()=>{var nn;Wt=null,Sn=!0,gt=!0,Gt=null,G.current=!0,R==null||R(!0);const et=ct(Ke.x,Ke.y),dt=oe.buffer.active.getLine(et.row),Nt=Aa({line:dt,col:et.col,side:"start",cols:oe.cols}),jt=g0({line:dt,col:Nt,cols:oe.cols});ze={row:et.row,col:jt.start};const It={row:et.row,col:jt.end};oe.clearSelection(),cs("touch"),ke(!0),Ee("end"),oe.select(jt.start,et.row,jt.end-jt.start+1),Vs(It);try{(nn=navigator.vibrate)==null||nn.call(navigator,10)}catch{}je=null,Xe=null,rt=null,Rt={mode:null,remainder:0}},tT)},tn=ve=>{if(Sn&&ze&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const dt=ct(ve.touches[0].clientX,ve.touches[0].clientY),Nt=ze.row*oe.cols+ze.col,jt=dt.row*oe.cols+dt.col,It=Nt<=jt?"end":"start",nn=oe.buffer.active.getLine(dt.row),Yn=Aa({line:nn,col:dt.col,side:It,cols:oe.cols}),cn={row:dt.row,col:Yn},Is=cn.row*oe.cols+cn.col,ri=Nt<=Is?ze:cn;Ee(It),oe.select(ri.col,ri.row,Math.abs(Is-Nt)+1),Vs(cn);return}if(G.current&&ze&&ve.touches.length===1){ve.preventDefault(),ve.stopPropagation();const dt=ct(ve.touches[0].clientX,ve.touches[0].clientY),Nt=ze.row*oe.cols+ze.col,jt=dt.row*oe.cols+dt.col,It=Nt<=jt?"end":"start",nn=oe.buffer.active.getLine(dt.row),Yn=Aa({line:nn,col:dt.col,side:It,cols:oe.cols}),cn={row:dt.row,col:Yn},Is=cn.row*oe.cols+cn.col,ri=Nt<=Is?ze:cn;Ee(It),oe.select(ri.col,ri.row,Math.abs(Is-Nt)+1),Vs(cn);return}if(je===null||ve.touches.length!==1)return;ve.preventDefault(),ve.stopPropagation();const Ke=ve.touches[0];if(p0(Pe,xt,Ke.clientX,Ke.clientY)&&(gt=!0,Gt=null,Wt&&Ve()),rt===null&&(Math.abs(Ke.clientY-je)>8||Math.abs(Ke.clientX-Xe)>8)&&(rt=Math.abs(Ke.clientY-je)>Math.abs(Ke.clientX-Xe)),!rt)return;const et=Ke.clientY-je;je=Ke.clientY,Rt=ae(et,Rt,"scroll",q(Ke.clientX,Ke.clientY))},rn=()=>{Ve(),je=null,Xe=null,Pe=null,xt=null,ze=null,Sn=!1,gt=!1,Je=!1,A(null),ke(!1),Rt={mode:null,remainder:0},Me=Date.now()},bi=ve=>{if(Je){Gt=null,Ve(),(!ve.touches||ve.touches.length===0)&&rn();return}const Ke=ve.changedTouches&&ve.changedTouches[0];if(!gt&&!Sn&&!G.current&&Ke){const et={at:Date.now(),x:Ke.clientX,y:Ke.clientY},dt=_T(ne.current,Gt,et);Gt=dt.next,dt.open&&In()}rn()},mo=()=>{Gt=null,rn()};let rr={mode:null,remainder:0};const Vt=ve=>{ve.preventDefault(),ve.stopPropagation(),rr=ae(-ve.deltaY,rr,"scroll",q(ve.clientX,ve.clientY))};bt.addEventListener("touchstart",Zt,{passive:!1}),bt.addEventListener("touchmove",tn,{passive:!1,capture:!0}),bt.addEventListener("touchend",bi,{passive:!0}),bt.addEventListener("touchcancel",mo,{passive:!0});const rl=()=>{typeof window.matchMedia=="function"&&window.matchMedia(og).matches||!G.current&&ne.current==="double-tap"&&In()};bt.addEventListener("dblclick",rl);const ol=ve=>{(G.current||Sn)&&(ve.preventDefault(),ve.stopPropagation())};bt.addEventListener("contextmenu",ol,!0),bt.addEventListener("wheel",Vt,{passive:!1,capture:!0});let Ps=null;const al=ve=>{Date.now()-Me>=Se&&cs("mouse"),QM(ve)&&(ve.preventDefault(),ve.stopPropagation(),Ps={cell:ct(ve.clientX,ve.clientY),clientX:ve.clientX,clientY:ve.clientY,extendFrom:xe.current,dragged:!1})},ll=ve=>{var It;if(!Ps){(It=oe.hasSelection)!=null&&It.call(oe)&&_t()&&(ve.preventDefault(),ve.stopPropagation());return}if(ve.preventDefault(),ve.stopPropagation(),!Ps.dragged&&!p0(Ps.clientX,Ps.clientY,ve.clientX,ve.clientY))return;Ps.dragged=!0;const Ke=Ps.cell,et=ct(ve.clientX,ve.clientY),dt=Ke.row*oe.cols+Ke.col,Nt=et.row*oe.cols+et.col,jt=dt<=Nt?Ke:et;oe.select(jt.col,jt.row,Math.abs(Nt-dt)+1)},cl=ve=>{if(!Ps)return;ve.stopPropagation();const{cell:Ke,extendFrom:et,dragged:dt}=Ps;if(Ps=null,dt||!et)return;const Nt=nT({range:et,cell:Ke,cols:oe.cols});if(!Nt.moved)return;const jt=Nt[Nt.moved],It=oe.buffer.active.getLine(jt.row);jt.col=Aa({line:It,col:jt.col,side:Nt.moved,cols:oe.cols});const nn=v0({start:Nt.start,end:Nt.end},oe.cols);oe.select(nn.col,nn.row,nn.length)};bt.addEventListener("mousedown",al,!0),bt.addEventListener("mousemove",ll,!0),bt.addEventListener("mouseup",cl,!0);let Lr=null,ni={x:0,y:0,type:"touch"};const Ys=()=>{Lr&&(clearInterval(Lr),Lr=null)},Si=(ve,Ke,et)=>{if(!mn||!mn.fixed)return;const dt=mn.fixed,Nt=et==="mouse"?ct(ve,Ke):Ks({clientX:ve,clientY:Ke},At()),jt=oe.buffer.active.getLine(Nt.row),It={row:Nt.row,col:Aa({line:jt,col:Nt.col,side:mn.which,cols:oe.cols})},nn=Math.max(0,Number(oe.buffer.active.baseY||0)+oe.rows-1),Yn=rT({moving:It,fixed:dt,which:mn.which,cols:oe.cols,maxRow:nn}),cn=v0(m0(Yn,dt,oe.cols),oe.cols);oe.select(cn.col,cn.row,cn.length);const Is=Number(oe.buffer.active.viewportY)||0,ri=uT({visibleRow:Yn.row-Is,rows:oe.rows});Ys(),!(ri===0||oe.buffer.active.type==="alternate")&&(Lr=setInterval(()=>{const dl=Number(oe.buffer.active.viewportY)||0;if(oe.scrollLines(ri),(Number(oe.buffer.active.viewportY)||0)===dl){Ys();return}Si(ni.x-mn.offsetX,ni.y-mn.offsetY,ni.type)},130))},si=ve=>{mn&&(ve.preventDefault(),ni={x:ve.clientX,y:ve.clientY,type:ve.pointerType||ni.type},Si(ve.clientX-mn.offsetX,ve.clientY-mn.offsetY,ni.type))},Ar=()=>{mn=null,Ys(),Re(null),window.removeEventListener("pointermove",si),window.removeEventListener("pointerup",ii),window.removeEventListener("pointercancel",ii)},ii=()=>Ar();ee.current={startHandleDrag:(ve,Ke)=>{if(!oe.getSelectionPosition())return;Ke.preventDefault(),Ke.stopPropagation();const et=J.current&&J.current[ve],dt=bt.getBoundingClientRect();mn={which:ve,offsetX:et?Ke.clientX-(dt.left+et.left):0,offsetY:et?Ke.clientY-(dt.top+et.top):0,fixed:xe.current?ve==="start"?xe.current.end:xe.current.start:null},ni={x:Ke.clientX,y:Ke.clientY,type:Ke.pointerType||"touch"},Re(ve),Ee(ve),window.addEventListener("pointermove",si),window.addEventListener("pointerup",ii),window.addEventListener("pointercancel",ii)}};const xi=ve=>{!ZM(ve)||!(F.current&&F.current.term&&F.current.term.getSelection())||(ve.preventDefault(),ve.stopPropagation(),W.current&&W.current())};bt.addEventListener("keydown",xi,!0);const jr=()=>{$e.fit(),Jt.resize(oe.cols,oe.rows)};window.addEventListener("resize",jr);const Gs=window.visualViewport;let or=Gs&&Number(Gs.height);const Wc=()=>{const ve=Gs&&Number(Gs.height);Ut&&ne.current==="double-tap"&&Number.isFinite(or)&&Number.isFinite(ve)&&ve>or+80&&Ot(),or=ve,jr()};Gs&&(Gs.addEventListener("resize",Wc),Gs.addEventListener("scroll",jr));const ys=typeof navigator<"u"?navigator.virtualKeyboard:null,go=()=>{var ve;Ut&&ne.current==="double-tap"&&Number(((ve=ys==null?void 0:ys.boundingRect)==null?void 0:ve.height)||0)===0&&Ot()};(Ci=ys==null?void 0:ys.addEventListener)==null||Ci.call(ys,"geometrychange",go);let vo=null,_o=0;return typeof ResizeObserver<"u"&&(vo=new ResizeObserver(()=>{_o&&cancelAnimationFrame(_o),_o=requestAnimationFrame(jr)}),vo.observe(bt)),()=>{var ve,Ke,et;F.current=null,b&&(b.current=null),Q.current&&(clearTimeout(Q.current),Q.current=null),c&&(c.current=()=>!1),u&&(u.current=()=>!1),h&&(h.current=()=>!1),ls.dispose(),gn.dispose(),qs.dispose(),Vn.dispose(),Ys(),window.removeEventListener("pointermove",si),window.removeEventListener("pointerup",ii),window.removeEventListener("pointercancel",ii),ee.current={startHandleDrag:()=>{}},bt.removeEventListener("touchstart",Zt),bt.removeEventListener("touchmove",tn,{capture:!0}),bt.removeEventListener("touchend",bi),bt.removeEventListener("touchcancel",mo),bt.removeEventListener("dblclick",rl),bt.removeEventListener("contextmenu",ol,!0),Ve(),bt.removeEventListener("wheel",Vt,{capture:!0}),bt.removeEventListener("mousedown",al,!0),bt.removeEventListener("mousemove",ll,!0),bt.removeEventListener("mouseup",cl,!0),bt.removeEventListener("keydown",xi,!0),bt.removeEventListener("paste",re,!0),bt.removeEventListener("dragenter",Te,!0),bt.removeEventListener("dragover",Te,!0),bt.removeEventListener("drop",Ge,!0),window.removeEventListener("resize",jr),Gs&&(Gs.removeEventListener("resize",Wc),Gs.removeEventListener("scroll",jr)),(ve=ys==null?void 0:ys.removeEventListener)==null||ve.call(ys,"geometrychange",go),qt==null||qt.removeEventListener("blur",wn),(Ke=E.current)==null||Ke.removeEventListener("paste",Ft,!0),(et=E.current)==null||et.removeEventListener("keydown",Xt,!0),vo&&vo.disconnect(),_o&&cancelAnimationFrame(_o),Jt.close(),oe.dispose()}},[t,e,n,s,i,c,u,h,f,g,x]),w.useEffect(()=>{const oe=E.current,$e=F.current?F.current.term:null;if(!oe||!$e||!de){nt(null),pe(null),Ne(null);return}const kt=(oe.querySelector(".xterm-screen")||oe).getBoundingClientRect(),St=oe.getBoundingClientRect(),Lt=kt.width/Math.max(1,$e.cols),_t=kt.height/Math.max(1,$e.rows),pt=cT({range:de,viewportY:Number($e.buffer.active.viewportY)||0,rows:$e.rows,cols:$e.cols,cellWidth:Lt,cellHeight:_t,screenLeft:kt.left-St.left,screenTop:kt.top-St.top});nt(pt);let Ut=null;const Gt=de[fe==="end"?"end":"start"].row;typeof $e.buffer.active.getLine=="function"&&(Ut=$e.buffer.active.getLine(Number(Gt)));const Ot=Math.max(16,Math.round(_t*2)),ln=Ut?{...dT({range:de,side:fe,line:Ut,cols:$e.cols}),fontSize:Ot}:null;pe(ln);const In=ue!==null||Ae,qt=pt[fe==="end"?"end":"start"];if(!In||!ln||!qt||!qt.visible){Ne(null);return}const wn=(ln.before+ln.sel+ln.after).length,en=Lt*(Ot/Math.max(1,_t)),bn=Math.min(St.width-8,Math.round(wn*en)+16),Ft=Math.round(Ot*1.25)+12;Ne(aT({anchorLeft:qt.left,anchorTop:qt.top,hostWidth:St.width,hostHeight:St.height,bubbleWidth:bn,bubbleHeight:Ft}))},[de,Le,fe,ue,Ae]);const be=sT(ge),ye=w.useRef({}),ot=(oe,$e)=>{if(ue!==oe)return ye.current[oe]={flip:$e,ts:0},$e;const ut=ye.current[oe]||{flip:$e,ts:0};if(ut.flip===$e)return ye.current[oe]=ut,$e;const kt=Date.now();return kt-ut.ts<lT?ut.flip:(ye.current[oe]={flip:$e,ts:kt},$e)};return l.jsxs("div",{className:`nc-terminal${C?" selecting":""}`,children:[l.jsx("div",{className:"nc-terminal-host",ref:E}),N&&l.jsxs("div",{className:"nc-terminal-link-overlay",children:["riconnessione…",T>0?` (${T} byte in coda)`:""]}),M&&l.jsx("div",{className:"nc-touch-selection-caret",style:M,"aria-hidden":"true"}),de&&Be&&be.handles&&["start","end"].map(oe=>Be[oe].visible&&l.jsx("div",{className:`nc-sel-handle ${oe}${ue===oe?" dragging":""}${ot(oe,Be[oe].flip)?" flip":""}${oT({startLeft:Be.start.left,endLeft:Be.end.left})?" tight":""}`,style:{left:`${Be[oe].left}px`,top:`${Be[oe].top}px`},onPointerDown:$e=>ee.current.startHandleDrag(oe,$e),"aria-hidden":"true"},`nc-sel-handle-${oe}`)),de&&Y&&be.magnifier&&We&&l.jsx("div",{className:`nc-zoom-bubble${We.flipped?" flipped":""}`,style:{left:`${We.left}px`,top:`${We.top}px`},"aria-hidden":"true",children:l.jsxs("pre",{className:"nc-zoom-line",style:{fontSize:`${Y.fontSize}px`},children:[l.jsx("span",{children:Y.before}),l.jsx("span",{className:"nc-zoom-sel",children:Y.sel}),l.jsx("span",{children:Y.after})]})}),j&&l.jsx("div",{className:`nc-upload-state${j.error?" error":""}`,role:"status",children:j.error?j.error:j.done?p("attach-uploaded").replace("{n}",String(j.total||0)):p("attach-upload-progress").replace("{n}",String(j.current||0)).replace("{total}",String(j.total||0))}),(K||C)&&l.jsxs("div",{className:"nc-selection-tools",children:[K?l.jsx("button",{type:"button",onClick:wt,children:P||`${p("copy")} · ${eT(typeof navigator<"u"?navigator.userAgent:"")}`}):l.jsx("span",{children:p("select-drag")}),K&&Z&&l.jsx("span",{className:"nc-selection-held",children:p("selection-held")}),K&&!Z&&He&&l.jsx("span",{className:"nc-selection-changed",children:p("selection-changed")}),l.jsx("button",{type:"button",onClick:()=>{var oe,$e;($e=(oe=F.current)==null?void 0:oe.term)==null||$e.clearSelection(),D(""),me(!1),R==null||R(!1)},children:p("cancel")}),P===p("copy-manual")&&l.jsx("textarea",{readOnly:!0,value:K,onFocus:oe=>oe.target.select()})]})]})}function kc(t,e,n){const s=c=>Number.isInteger(c)&&c>0&&c<65536?c:0;if(t==null)return s(n);if(!Array.isArray(t))return 0;if(t.length===0)return s(n);const i=typeof t[0]=="string"?t[0]:null;return i?s((e&&typeof e=="object"?e:{})[i]):0}const LT=6901;function pv({cellId:t,panelUrl:e,route:n=[],panelPort:s=0,token:i,title:a,requestTimeoutMs:c=4e3}){const[u,h]=w.useState(t&&i?"requesting":"none"),[f,g]=w.useState(""),v=Array.isArray(n)?n.join("\0"):"",_=w.useMemo(()=>Array.isArray(n)?n:[],[v]),b=w.useRef(0),x=w.useCallback(async()=>{if(!t||!i||!e){h("none");return}const D=b.current+=1;h("requesting");const P=new AbortController,O=setTimeout(()=>P.abort(),c);try{const j=await SN(i,_,t,{signal:P.signal});if(clearTimeout(O),D!==b.current)return;if(j.ok){let z="/";try{z=new URL(e).pathname||"/"}catch{}const M=s?`http://127.0.0.1:${s}`:yn(_);g(`${M}/panel/${encodeURIComponent(t)}${z}?ticket=${encodeURIComponent(j.ticket)}`),h("ready")}else h(j.cause)}catch(j){if(clearTimeout(O),D!==b.current)return;h(j&&j.name==="AbortError"?"timeout":"unreachable")}},[t,e,_,s,i,c]),L=w.useCallback(()=>{h(D=>D==="ready"?"loaded":D)},[]),C=w.useCallback(()=>{h(D=>D==="ready"||D==="loaded"?"frame-error":D)},[]),R=w.useRef(null),S=w.useCallback(D=>{D&&(R.current=D,D.onload=L,D.onerror=C)},[L,C]);w.useEffect(()=>{x()},[x]);const E=w.useMemo(()=>{try{return Number(new URL(e).port)===LT}catch{return!1}},[e])&&_.length===0,[F,$]=w.useState(!1),[X,V]=w.useState("");w.useEffect(()=>{const D=P=>{const O=R.current;if(!O||!O.contentWindow||P.source!==O.contentWindow)return;let j=null;try{j=new URL(f,window.location.href).origin}catch{return}!j||P.origin!==j||!P.data||P.data.type!=="nc-panel-unreachable"||h(z=>z==="ready"||z==="loaded"?"unreachable":z)};return window.addEventListener("message",D),()=>window.removeEventListener("message",D)},[f]);const G=w.useCallback(async()=>{if(!i||F)return;$(!0),V("");let D=!1;try{const P=await T1(i,!0);P&&P.ok===!1&&(V(P.error||"comando fallito"),D=!0)}catch(P){V(String(P&&P.message||P)),D=!0}$(!1),D||x()},[i,F,x]),ne=(D,P=!0,O=null)=>l.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[l.jsx("span",{children:p(D)}),P&&l.jsxs("span",{className:"nc-cellpanel-actions",children:[O,l.jsx("button",{type:"button",title:p("panel-retry"),onClick:()=>x(),children:p("panel-retry")})]})]}),K=E?l.jsx("button",{type:"button",disabled:F,onClick:G,children:p("panel-start-desktop")}):null;return u==="none"||u==="no-panel"?ne("panel-none",!1):u==="requesting"?l.jsx("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:l.jsx("span",{children:p("panel-checking")})}):u==="not-granted"?ne("panel-not-granted",!1):u==="node-refused"?ne("panel-node-refused",!1):u==="unauthorized"?ne("panel-unauthorized",!1):u==="denied"?ne("panel-denied"):u==="timeout"?ne("panel-timeout"):u==="unreachable"?l.jsxs("div",{className:"nc-cellpanel nc-cellpanel-msg",role:"status",children:[l.jsxs("span",{children:[p("panel-unreachable"),X?` — ${X}`:""]}),l.jsxs("span",{className:"nc-cellpanel-actions",children:[K,l.jsx("button",{type:"button",title:p("panel-retry"),onClick:()=>x(),children:p("panel-retry")})]})]}):u==="frame-error"?ne("panel-frame-error",!0,K):l.jsxs(l.Fragment,{children:[u==="ready"&&l.jsx("div",{className:"nc-cellpanel-loading",role:"status",children:p("panel-frame-loading")}),l.jsx("iframe",{ref:S,className:"nc-cellpanel nc-cellpanel-frame","data-frame-state":u,src:f,title:a||p("panel"),allowFullScreen:!0})]})}const AT=1800*1e3;function cg(t,e,n=Date.now()){const s=Number(e);if(!Number.isFinite(s)||s<=0)return"";const i=n-s;if(i<0||i>AT)return"";if(i<60*1e3)return`${t("cell-activity")} ${t("cell-activity-now")}`;const a=Math.floor(i/6e4);return a<60?`${t("cell-activity")} ${a}m`:`${t("cell-activity")} ${Math.floor(a/60)}h`}function ug(t,e){if(!e||typeof e!="object")return"";const n=[];return Number.isInteger(e.contextFreePct)&&n.push(`${t("cell-tele-ctx")} ${e.contextFreePct}% ${t("cell-tele-free")}`),Number.isInteger(e.tier5hUsedPct)&&n.push(`${t("cell-tele-5h")} ${e.tier5hUsedPct}%`),Number.isInteger(e.tier7dUsedPct)&&n.push(`${t("cell-tele-7d")} ${e.tier7dUsedPct}%`),n.join(" · ")}function mv({row:t,token:e,panelPort:n=0,liveHost:s=null,onLiveHostApplied:i,source:a,onSourceChange:c,fontSize:u,readOnly:h=!1,chrome:f=!0}){const g=V=>c&&c(V),v=w.useRef(()=>{}),_=w.useRef(()=>!1),b=w.useRef(()=>{}),x=w.useRef(!1),[L,C]=w.useState(!1),[R,S]=w.useState(""),[I,E]=w.useState(!1),F=!!(s&&s.cell&&s.cell===t.cellName),$=async()=>{E(!0);const V=await eh({action:F?"remove":"use",cellId:t.cellName,route:t.route||[],token:e,api:{getLiveHost:G=>Xd(e,G),designateHostCell:(G,ne,K)=>Jd(e,G,ne,K),clearHostCell:(G,ne)=>Qd(e,G,ne)}});E(!1),S(p(V.messageKey).replace("{cell}",V.hostCell||t.cellName)),V.ok&&i&&i({route:t.route||[],hostCell:V.hostCell,revision:V.revision})},X=[["preview",p("cell-peek-preview")],["stream",p("cell-peek-stream")],...t.panelUrl?[["panel",p("cell-peek-panel")]]:[]];return l.jsxs(l.Fragment,{children:[f&&l.jsx("div",{className:"nc-peek-sorgenti",role:"tablist",children:X.map(([V,G])=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===V,className:`nc-peek-sorgente${a===V?" attiva":""}`,onClick:()=>g(V),children:G},V))}),f&&l.jsxs("div",{className:"nc-peek-host",children:[l.jsx("button",{type:"button",className:"nc-peek-host-btn",disabled:I,onClick:$,children:p(F?"live-host-action-remove":"live-host-action-use")}),R&&l.jsx("div",{className:"nc-peek-notice",role:"status",children:R})]}),a==="stream"?l.jsx("div",{className:"nc-peek-stream",children:l.jsx(pc,{session:t.session,node:t.node||void 0,token:e,readonly:h,takeSize:!1,focused:!0,sendRef:v,composerRef:_,actionRef:b,ctrlRef:x,setCtrlArmed:C,fontSize:u},`peek:${t.key}`)}):a==="panel"?l.jsx(pv,{cellId:t.cellName,panelUrl:t.panelUrl,route:t.route||[],panelPort:n,token:e,title:t.cellName}):l.jsxs(l.Fragment,{children:[l.jsx("pre",{className:"nc-peek-testo",children:t.preview||p("cell-peek-vuoto")}),[cg(p,t.activity),ug(p,t.telemetry)].filter(Boolean).join(" · ")&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:[cg(p,t.activity),ug(p,t.telemetry)].filter(Boolean).join(" · ")})]})]})}function wk({row:t,token:e,initialSource:n="preview",panelPort:s=0,onClose:i,liveHost:a=null,onLiveHostApplied:c}){const[u,h]=w.useState(n==="panel"&&!t.panelUrl?"preview":n);return l.jsx(F1,{title:t.cellName,subtitle:[t.nodeLabel,t.subtitle].filter(Boolean).join(" · "),onClose:i,children:l.jsx(mv,{row:t,token:e,panelPort:s,liveHost:a,onLiveHostApplied:c,source:u,onSourceChange:h})})}const Cc="nc_order_journal_v1",jT=50,_p="__corrupt",MT=200,TT=200,PT=["reason","key","position","source","target","note"],IT=["before","after","visible"],bk=t=>String(t).slice(0,TT),DT=t=>Array.isArray(t)?t.slice(0,MT).map(bk):void 0,oh=t=>{try{return t||globalThis.localStorage}catch{return null}};function OT(t){const e={t:Date.now()};for(const n of PT)t[n]!==void 0&&t[n]!==null&&(e[n]=bk(t[n]));for(const n of IT){const s=DT(t[n]);s&&(e[n]=s)}return e}function gv(t,e,n){const s=oh(n);if(!s||e===null||e===void 0)return!1;try{if(s.getItem(t+_p)===e)return!1;s.setItem(t+_p,e)}catch{return!1}return t!==Cc&&Ji({reason:"corrupt-preserved",key:t,note:`${String(e).length} caratteri conservati in ${t}${_p}`},s),!0}function dg(t){const e=oh(t);if(!e)return[];let n=null;try{n=e.getItem(Cc)}catch{return[]}if(n===null)return[];try{const s=JSON.parse(n);if(Array.isArray(s))return s}catch{}return gv(Cc,n,e),[]}function Ji(t,e){const n=oh(e);if(!(!n||!t))try{const s=[...dg(n),OT(t)].slice(-jT);n.setItem(Cc,JSON.stringify(s))}catch{}}function BT(t){const e=oh(t);if(e)try{e.removeItem(Cc)}catch{}}function Rr(t,{parse:e,fallback:n,storage:s}={}){let i=s;try{i=i||globalThis.localStorage}catch{return n()}let a=null;try{a=i.getItem(t)}catch{return n()}if(a==null)return n();try{const c=e(JSON.parse(a));if(c!==void 0)return c}catch{}return gv(t,a,i),n()}function yi(t,e,{storage:n}={}){let s=n;try{s=s||globalThis.localStorage}catch(i){return i}try{const i=s.getItem(t);if(i!=null)try{JSON.parse(i)}catch{gv(t,i,s)}return s.setItem(t,JSON.stringify(e)),null}catch(i){return i instanceof Error?i:new Error(String(i))}}const $T=["all","pinned","active","off","technical"],Jo="nc_sidebar_views_v1",Qo="nc_sidebar_order_v1";function Sk(t){return $T.includes(t)?t:"all"}function zT(t,e=[],n="all"){const s=Sk(n);return s==="technical"?t.technical===!0:t.technical===!0?!1:s==="pinned"?e.includes(t.key):s==="active"?!!t.live:s==="off"?!t.live:!0}function FT(t,e,n=[],s=[]){const i=n.indexOf(t.key),a=n.indexOf(e.key),c=i===-1?Number.MAX_SAFE_INTEGER:i,u=a===-1?Number.MAX_SAFE_INTEGER:a,h=s.indexOf(t.key),f=s.indexOf(e.key),g=h===-1?Number.MAX_SAFE_INTEGER:h,v=f===-1?Number.MAX_SAFE_INTEGER:f;return c-u||g-v||+!!e.live-+!!t.live||+!!e.fresh-+!!t.fresh||Number(e.activity||0)-Number(t.activity||0)||String(t.label||"").localeCompare(String(e.label||""))||String(t.key||"").localeCompare(String(e.key||""))}function uc(t=globalThis.localStorage){return Rr(Qo,{storage:t,fallback:()=>({}),parse:e=>{if(!e||typeof e!="object"||Array.isArray(e))return;const n={};for(const[s,i]of Object.entries(e).slice(0,64)){if(typeof s!="string"||!s||s.length>160||!Array.isArray(i))continue;const a=[...new Set(i.filter(c=>typeof c=="string"&&c&&c.length<=256))].slice(0,128);a.length&&(n[s]=a)}return n}})}function Ii(t,e){return Array.isArray(t==null?void 0:t[e])?t[e]:[]}function HT(t,e=globalThis.localStorage){return yi(Qo,t,{storage:e}),t}function UT(t,e,n,s,i=[]){if(typeof e!="string"||!e||n===s)return t;const a=[...new Set(i.filter(_=>typeof _=="string"&&_))];if(!a.includes(n)||!a.includes(s))return t;const c=Ii(t,e),u=[...c,...a.filter(_=>!c.includes(_))],h=u.indexOf(n),f=u.indexOf(s);u.splice(h,1);const g=u.indexOf(s),v=h<f?g+1:g;return u.splice(v,0,n),{...t,[e]:u}}function _d(t=globalThis.localStorage){return Rr(Jo,{storage:t,fallback:()=>({}),parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0})}function b0(t,e){var n,s;return{open:((n=t==null?void 0:t[e])==null?void 0:n.open)!==!1,filter:Sk((s=t==null?void 0:t[e])==null?void 0:s.filter)}}function WT(t,e=globalThis.localStorage){return yi(Jo,t,{storage:e}),t}function S0(t,e=""){const n=String(e||"").trim().toLocaleLowerCase();return n?[t.label,t.key,t.searchText].filter(Boolean).join(" ").toLocaleLowerCase().includes(n):!0}function co(t=[],e=[],n="all",s=[]){return[...t].filter(i=>zT(i,e,n)).sort((i,a)=>FT(i,a,e,s))}function zn(){return[w.useSyncExternalStore(N5,Cd,Cd),E5]}function Pd({cell:t,token:e,route:n=[],onConfirm:s,onClose:i}){var z,M;zn();const a=!!(t&&t.active),c=Array.isArray(n)?n.join("/"):"",[u,h]=w.useState([]),[f,g]=w.useState(!1);w.useEffect(()=>{let A=!0;return(async()=>{if(e)try{const N=await Qa(e,c?c.split("/"):[]);if(!A)return;if(g(N.provider==="builtin"&&(N.capabilities||[]).includes("edit")),N.provider==="builtin"&&(N.capabilities||[]).includes("definitions")){const U=await Yd(e,c?c.split("/"):[]);if(!A)return;const T=new Map((N.engines||[]).map(H=>[H.id,H]));h((U.engines||[]).map(H=>{var se,Q,Z,me,de,ie,xe;return{id:H.id,label:H.label||H.id,client:((se=H.managed)==null?void 0:se.client)||"",models:[...new Set([...((Q=T.get(H.id))==null?void 0:Q.models)||[],...((Z=H.managedInfo)==null?void 0:Z.models)||[]])].filter(Boolean),defaultModel:((me=H.managed)==null?void 0:me.model)||((de=H.managedInfo)==null?void 0:de.defaultModel)||"",policyDefault:((ie=H.managed)==null?void 0:ie.permissionPolicy)||((xe=H.managed)!=null&&xe.client&&H.managed.client==="claude"?"unsafe":"standard")}}))}}catch{}})(),()=>{A=!1}},[e,c]);const v=(t==null?void 0:t.engine)||((z=u[0])==null?void 0:z.id)||"",_=A=>(t==null?void 0:t.models)&&t.models[A]||"",b=A=>{const N=(t==null?void 0:t.permissionPolicies)&&t.permissionPolicies[A];if(N==="standard"||N==="unsafe")return N;const U=u.find(T=>T.id===A);return U?U.policyDefault:"standard"},[x,L]=w.useState(v),[C,R]=w.useState((t==null?void 0:t.model)||""),S=(t==null?void 0:t.permissionPolicy)==="standard"||(t==null?void 0:t.permissionPolicy)==="unsafe"?t.permissionPolicy:((M=t==null?void 0:t.permissionPolicies)==null?void 0:M[t==null?void 0:t.engine])||"",[I,E]=w.useState(S),[F,$]=w.useState((t==null?void 0:t.boot)??!0),[X,V]=w.useState(!1),[G,ne]=w.useState(null);w.useEffect(()=>{u.length&&(L(A=>A||v),R(A=>A||_((t==null?void 0:t.engine)||v)||""),E(A=>A==="standard"||A==="unsafe"?A:b((t==null?void 0:t.engine)||v)))},[u.length]);const K=w.useMemo(()=>u.find(A=>A.id===x)||null,[u,x]),D=!!(K&&["claude","codex","codex-vl","agy","kimi"].includes(K.client)),P=(K==null?void 0:K.client)==="shell";function O(A){L(A);const N=u.find(U=>U.id===A);R(_(A)||(N==null?void 0:N.defaultModel)||""),E(b(A))}async function j(A){A.preventDefault(),V(!0),ne(null);try{if(a)await s({action:"down",boot:F});else{const N=I==="standard"||I==="unsafe"?I:(K==null?void 0:K.policyDefault)||"standard";await s({action:"up",...f?{engine:x,model:C||"",...D?{permissionPolicy:N}:(K==null?void 0:K.client)==="pi"?{permissionPolicy:"standard"}:{}}:{},boot:F})}i()}catch(N){ne(String(N&&N.message||N)),V(!1)}}return l.jsx("div",{className:"nc-sheet-overlay nc-launch-overlay",onClick:i,children:l.jsxs("form",{className:"nc-sheet nc-power-sheet nc-launch-sheet",onClick:A=>A.stopPropagation(),onSubmit:j,children:[l.jsxs("div",{className:"nc-sheet-head",children:[l.jsx("b",{children:t==null?void 0:t.cell}),l.jsx("span",{className:"nc-sheet-state",children:p(a?"state-on":"state-off")})]}),a?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"nc-power-config",children:[l.jsx("span",{children:p("engine")}),l.jsx("b",{children:(t==null?void 0:t.engine)||"—"}),(t==null?void 0:t.model)&&l.jsxs("small",{children:[p("model"),": ",t.model]}),l.jsx("small",{children:p("power-on-hint")})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:F,onChange:A=>$(A.target.checked)}),p("remove-boot")]})]}):l.jsxs(l.Fragment,{children:[f&&u.length>0?l.jsxs("div",{className:"nc-launch-fields",children:[l.jsxs("label",{className:"nc-field",children:[p("engine"),l.jsx("select",{value:x,onChange:A=>O(A.target.value),children:u.map(A=>l.jsx("option",{value:A.id,children:A.label},A.id))})]}),!P&&l.jsxs("label",{className:"nc-field",children:[p("model"),l.jsx("input",{value:C,list:"nc-launch-models",placeholder:p("model-default"),onChange:A=>R(A.target.value)}),l.jsx("datalist",{id:"nc-launch-models",children:((K==null?void 0:K.models)||[]).map(A=>l.jsx("option",{value:A},A))})]}),D?l.jsxs("label",{className:"nc-field",children:[p("permissions"),l.jsxs("select",{value:I,onChange:A=>E(A.target.value),children:[l.jsx("option",{value:"standard",children:p("fleet-standard-permissions")}),l.jsx("option",{value:"unsafe",children:p("fleet-unsafe-permissions")})]})]}):l.jsx("small",{className:"nc-note",children:p("fleet-standard-permissions")}),D&&I==="unsafe"&&l.jsx("small",{className:"nc-err",children:p("fleet-unsafe-warning")}),l.jsx("small",{className:"nc-note",children:p(P?"fleet-shell-launch-help":"launch-engine-help")})]}):l.jsxs("div",{className:"nc-power-config",children:[l.jsx("span",{children:p("engine")}),l.jsx("b",{children:(t==null?void 0:t.engine)||"—"}),(t==null?void 0:t.model)&&l.jsxs("small",{children:[p("model"),": ",t.model]}),l.jsx("small",{children:p("launch-unavailable-hint")})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:F,onChange:A=>$(A.target.checked)}),p("boot-persist")]})]}),G&&l.jsx("div",{className:"nc-err",children:G}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:i,children:p("cancel")}),l.jsx("button",{type:"submit",className:"nc-btn primary",disabled:X,children:p(X?a?"power-stopping":"power-starting":a?"power-off":"save-and-start")})]})]})})}const x0=/^[a-z0-9-]{1,32}$/;function qa(t,e){const n=Array.isArray(t)?t:[];return n.length?`${n.map(encodeURIComponent).join("/")}:${e}`:String(e)}function qT(t,e,n){const s={};for(const i of Array.isArray(e)?e:[]){const a=Array.isArray(i==null?void 0:i.route)?i.route:typeof(i==null?void 0:i.name)=="string"?[i.name]:[];if(!a.length)continue;const c=a.join("/"),u=i.status==="up"||i.tunnel&&i.tunnel.status==="up",h=i.status==="passive"||i.tunnel&&i.tunnel.status==="passive";!u&&!h&&i.status!=="pending"&&!i.checking&&(s[c]=t&&t[c]||n)}return s}function hg(t,e,n,s=!1){return!t||!Array.isArray(t.cells)?[]:t.cells.map(i=>({...i,route:e,key:`${n}:${i.tmuxSession||i.cell}`,...s?{preserved:!0}:{}}))}function Vl(t,e,n){if(!t)return{};const s=fg(t);return!dc(t,s)||s!=="stale"?{}:{cells:hg(t,e,n,!0),fleetState:"stale",fleetAvailable:!1,cellsPreserved:!0}}function fg(t){return(t==null?void 0:t.fleetState)==="stale"?"stale":(t==null?void 0:t.fleetState)==="disabled"?"disabled":(t==null?void 0:t.available)===!0&&Array.isArray(t.cells)?"available":(t==null?void 0:t.available)===!1?"disabled":"stale"}function dc(t,e){return(e==="available"||e==="stale")&&Array.isArray(t==null?void 0:t.cells)}function k0(t,e){const n=t?e&&e.at:e&&e.lastGoodAt;return Number.isFinite(n)?n:null}function C0({nodes:t,topology:e,remote:n,down:s,fleet:i,aliases:a,pendingReads:c,previousGroups:u}={}){var x,L,C,R;const h=[],f=new Set,g=new Set,v=(S,I)=>!!(c&&(c.has(S)||c.has(`${S}#${I}`))),_=(S,I,E)=>Array.isArray(u)?u.find(F=>F.name===I&&F.instanceId===E&&(Array.isArray(F.route)?F.route.join("/"):"")===S):null;function b(S,I){const E=_(S,I.name,I.instanceId),F=v(S,"sessions"),$=v(S,"fleet"),X=(n==null?void 0:n[S])||(F&&E?{sessions:E.sessionsAvailable?E.sessions:void 0,at:E.verifiedAt,lastGoodAt:E.verifiedAt,...E.sessionsAvailable===!1&&E.cause?{cause:E.cause}:{}}:null),V=(i==null?void 0:i[S])||($&&E?{available:E.fleetAvailable,cells:E.cells,fleetState:E.fleetState,capabilities:E.capabilities,engines:E.engines,provider:E.fleetProvider,cellsPreserved:E.cellsPreserved,...E.fleetState==="stale"&&E.cause?{cause:E.cause}:{}}:null);return(F||$)&&(I.checking=!0,I.sessionsPending=F,I.fleetPending=$),{r:X,f:V,previous:E,pending:F||$,rereading:E&&(F||$)&&!(n!=null&&n[S])&&!(i!=null&&i[S])}}for(const S of Array.isArray(t)?t:[]){if(!S||typeof S.name!="string"||!x0.test(S.name)||S.direction==="inbound"&&S.shared!==!0)continue;const I=[S.name],E=S.name;f.add(E);const F=((x=S.tunnel)==null?void 0:x.status)||"unknown",$=F==="up",X={name:S.name,label:S.label||S.name,originalLabel:S.label||S.name,alias:null,route:I,direct:!0,instanceId:S.nodeId||null,shared:S.shared===!0,stale:S.stale===!0,tunnelStatus:F,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:S.health||null,direction:S.direction||"outbound",roles:S.roles||null,rolesKnown:S.rolesKnown===!0};if(S.nodeId&&g.add(S.nodeId),!S.nodeId&&S.paired===!1){h.push({...X,status:"needs-repair",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(((L=S.health)==null?void 0:L.auth)==="failed"||F==="degraded"&&((C=S.health)==null?void 0:C.status)==="degraded"){h.push({...X,status:"needs-repair",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(F==="passive"||((R=S.health)==null?void 0:R.status)==="passive"){h.push({...X,status:"passive",downSince:null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}if(!$){h.push({...X,status:"down",downSince:s&&s[E]||null,...Vl(i&&(i[E]||i[S.name]),I,E)});continue}const{r:V,f:G,previous:ne,pending:K,rereading:D}=b(E,X);if(D){h.push({...ne,checking:!0,sessionsPending:X.sessionsPending,fleetPending:X.fleetPending});continue}const P=!!(V&&!V.error&&Array.isArray(V.sessions)),O=fg(G),j=O==="available"&&dc(G,O),z=dc(G,O);if(K&&!V&&!G){h.push({...X,status:(ne==null?void 0:ne.status)||"pending",pendingRead:!0,verifiedAt:(ne==null?void 0:ne.verifiedAt)??null});continue}if(!P&&!z){h.push({...X,status:K?(ne==null?void 0:ne.status)||"pending":"unreachable",cause:V&&V.cause||null});continue}const M=(P?V.sessions:[]).filter(U=>U&&typeof U.name=="string"&&U.name).map(U=>({...U,node:E,route:I,key:`${E}:${U.name}`})),A=hg(G,I,E),N=new Set(A.map(U=>U.tmuxSession).filter(Boolean));h.push({...X,status:"up",sessions:M,cells:A,unmanaged:M.filter(U=>!N.has(U.name)),fleetAvailable:j,fleetState:O,...G!=null&&G.cellsPreserved?{cellsPreserved:!0}:{},...V!=null&&V.cause||G!=null&&G.cause?{cause:(V==null?void 0:V.cause)||(G==null?void 0:G.cause)}:{},capabilities:G&&G.capabilities||[],engines:G&&G.engines||[],fleetProvider:G&&G.provider||null,sessionsAvailable:P,inventoryPartial:!P,verifiedAt:k0(P,V)})}for(const S of Array.isArray(e)?e:[]){if(!S||!Array.isArray(S.route)||S.route.length<1||S.route.some(N=>!x0.test(N)))continue;const I=S.route.join("/");if(f.has(I)||S.instanceId&&g.has(S.instanceId))continue;S.instanceId&&g.add(S.instanceId);const E=S.label||S.route.join(" › "),F=S.instanceId&&a&&typeof a[S.instanceId]=="string"?a[S.instanceId]:null,$={name:S.name,label:F||E,originalLabel:E,alias:F,route:[...S.route],direct:!1,instanceId:S.instanceId||null,shared:!0,stale:S.stale===!0,tunnelStatus:null,sessions:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:S.health||null,lastSeen:S.lastSeen||null};if(S.stale){h.push({...$,status:"offline",downSince:s&&s[I]||S.lastSeen||null,...Vl(i&&i[I],S.route,I)});continue}const{r:X,f:V,previous:G,pending:ne,rereading:K}=b(I,$);if(K){h.push({...G,checking:!0,sessionsPending:$.sessionsPending,fleetPending:$.fleetPending});continue}const D=!!(X&&!X.error&&Array.isArray(X.sessions)),P=fg(V),O=P==="available"&&dc(V,P),j=dc(V,P);if(ne&&!X&&!V){h.push({...$,status:(G==null?void 0:G.status)||"pending",pendingRead:!0,verifiedAt:(G==null?void 0:G.verifiedAt)??null});continue}if(!D&&!j){h.push({...$,status:ne?(G==null?void 0:G.status)||"pending":"unreachable",downSince:s&&s[I]||null,cause:X&&X.cause||null});continue}const z=(D?X.sessions:[]).filter(N=>N&&typeof N.name=="string"&&N.name).map(N=>({...N,node:I,route:S.route,key:`${I}:${N.name}`})),M=hg(V,S.route,I),A=new Set(M.map(N=>N.tmuxSession).filter(Boolean));h.push({...$,status:"up",sessions:z,cells:M,unmanaged:z.filter(N=>!A.has(N.name)),fleetAvailable:O,fleetState:P,...V!=null&&V.cellsPreserved?{cellsPreserved:!0}:{},...X!=null&&X.cause||V!=null&&V.cause?{cause:(X==null?void 0:X.cause)||(V==null?void 0:V.cause)}:{},capabilities:V&&V.capabilities||[],engines:V&&V.engines||[],fleetProvider:V&&V.provider||null,lastSeen:S.lastSeen||null,sessionsAvailable:D,inventoryPartial:!D,verifiedAt:k0(D,X)})}return h.sort((S,I)=>S.label.localeCompare(I.label))}const pg="nc_route_alias_v1",KT="nexuscrew-roster-preferences",E0="nc_pins",VT=/^[a-f0-9]{16,64}$/;let vv=new Map;const YT=t=>Array.isArray(t==null?void 0:t.route)&&t.route.length?t.route.join("/"):String((t==null?void 0:t.name)||"");function yp(t,e=vv){if(t==="local"||typeof t!="string")return t;const n=e.get(t);return n?`id:${n}`:t}const N0=(t,e,n)=>typeof t=="string"&&t.startsWith(`${e}:`)?`${n}:${t.slice(e.length+1)}`:t,R0=t=>[...new Set(t)];function wp(t,e){return Rr(t,{storage:e,fallback:()=>({}),parse:n=>n&&typeof n=="object"&&!Array.isArray(n)?n:void 0})}function ja(t,e=vv){const n={...t||{}};for(const[s,i]of e)t&&t[`id:${i}`]!==void 0&&(n[s]=t[`id:${i}`]);return n}function GT(t,{storage:e=globalThis.localStorage}={}){const n=new Map,s=new Map;for(const L of Array.isArray(t)?t:[]){const C=String((L==null?void 0:L.instanceId)||""),R=YT(L);if(!(VT.test(C)&&R)||n.has(R))continue;n.set(R,C);const S=L.status==="up"&&L.stale!==!0;(!s.has(C)||S&&!s.get(C).up)&&s.set(C,{name:R,up:S})}if(vv=n,!n.size)return!1;const i=wp(pg,e);let a=wp(Qo,e),c=wp(Jo,e),u=Rr(E0,{storage:e,fallback:()=>[],parse:L=>Array.isArray(L)?L:void 0});const h={...i},f={...a},g={...c};let v=[...u];const _={aliases:!1,orders:!1,views:!1,pins:!1};for(const[L,{name:C}]of s){const R=`id:${L}`,S=typeof i[L]=="string"?i[L]:"",I=S&&S!==C&&(!n.has(S)||n.get(S)===L)?S:"";I&&(v=R0([...v,...u.filter(E=>E.startsWith(`${I}:`)).map(E=>N0(E,I,C))]),_.pins=_.pins||v.length!==u.length);for(const[E,F,$]of[[a,f,"orders"],[c,g,"views"]]){const X=E[R]!==void 0?E[R]:I&&E[I]!==void 0?E[I]:E[C];if(X===void 0)continue;let V=X;$==="orders"&&Array.isArray(V)&&(V=R0(V.map(G=>I?N0(G,I,C):G))),JSON.stringify(F[R])!==JSON.stringify(V)&&(F[R]=V,_[$]=!0)}i[L]!==C&&(h[L]=C,_.aliases=!0),I&&Ji({reason:"route-renamed",key:L,note:`${I} -> ${C}`})}const b=[];_.pins&&b.push(yi(E0,v,{storage:e})),_.orders&&b.push(yi(Qo,f,{storage:e})),_.views&&b.push(yi(Jo,g,{storage:e})),_.aliases&&b.push(yi(pg,h,{storage:e}));const x=Object.values(_).some(Boolean);if(x)try{window.dispatchEvent(new Event(KT))}catch{}return x&&b.every(L=>!L)}const xk="nc_last_roster_v1",XT=64,JT=["cell","tmuxSession","engine","model","label","boot"],kk=t=>Rr(xk,{storage:t,fallback:()=>({}),parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0});function Ka(t,e,n=globalThis.localStorage){if(!t)return;const s={...kk(n)};!Array.isArray(e)||!e.length?delete s[t]:s[t]={at:Date.now(),cells:e.slice(0,XT).filter(i=>i&&typeof i.cell=="string").map(i=>Object.fromEntries(JT.filter(a=>i[a]!==void 0&&i[a]!==null).map(a=>[a,i[a]])))},yi(xk,s,{storage:n})}function _v(t,e=globalThis.localStorage){const n=t?kk(e)[t]:null;return!n||!Array.isArray(n.cells)?[]:n.cells.map(s=>({...s,tmux:!1,active:!1,preserved:!0,degraded:!1}))}function Ck(t,e={}){if(!t||typeof t!="object")return null;const n=typeof t.nodeId=="string"?t.nodeId:"";if(!n)return null;const s=typeof t.label=="string"&&t.label.trim()||typeof t.cell=="string"&&t.cell.trim()||n,i=Array.isArray(e.route)?[...e.route]:[];return{kind:"vl",nodeId:n,name:n,label:s,cell:t.cell??null,paired:!!t.pairedAt,online:!!t.online,lastSeen:t.lastSeen??null,generation:t.generation??null,version:t.version??null,health:t.health??null,session:t.session??null,capabilities:Array.isArray(t.capabilities)?t.capabilities:[],inflight:t.inflight??null,lastAck:t.lastAck??null,canManage:!!t.canManage,route:i,isLocal:i.length===0,ownerInstanceId:typeof e.instanceId=="string"?e.instanceId:null,ownerLabel:typeof e.label=="string"&&e.label?e.label:null}}function QT(t){var n;const e=[];for(const s of Array.isArray(t)?t:[]){if(!s||s.kind!=="vl"||!s.nodeId)continue;const i=s.online===!0,a=i&&((n=s.session)==null?void 0:n.attached)===!0,c=s.ownerInstanceId||"local";e.push({kind:"vl",name:`vl-${s.nodeId.slice(0,8)}`,label:s.label,route:Array.isArray(s.route)?[...s.route]:[],instanceId:null,direct:!1,status:i?"up":"offline",downSince:i?null:s.lastSeen??null,sessions:a?[{key:`vl:${c}:${s.nodeId}`,name:s.session.profile,attached:!0}]:[],cells:[],unmanaged:[],fleetAvailable:!1,capabilities:[],engines:[],health:s.health??null,stale:s.stale===!0,fleetState:s.stale===!0?"stale":null,peer:s})}return e}function Ek(t,e){const n=t&&Array.isArray(t.nodes)?t.nodes:[],s=new Set([e]),i=[];for(const a of n){const c=a&&typeof a.instanceId=="string"?a.instanceId:"";if(!c||s.has(c)||a.stale===!0||!Array.isArray(a.route)||a.route.length===0)continue;s.add(c);const u=typeof a.label=="string"&&a.label||typeof a.name=="string"&&a.name||a.route.join(" › ");i.push({instanceId:c,route:[...a.route],label:u})}return i}const ZT=/fleet\.json/;function yv({fs:t=null,error:e=null}={}){if(e)return{kind:"stale"};if(!t)return{kind:"stale"};if(t.available===!0)return{kind:"data",cells:t.cells||[],capabilities:t.capabilities||[]};const n=typeof t.reason=="string"?t.reason:"";return typeof t.migrationCode=="string"&&t.migrationCode?{kind:"disabled",reason:n||null}:ZT.test(n)?{kind:"stale"}:{kind:"disabled",reason:n||null}}const Nk={baseMs:4e3,capMs:6e4},Rk="peer-assente",Lk="peer-nega",Ak="rotta-inesistente";function bp(t){const e=t&&t.status;return e===403?Lk:e===404?Ak:Rk}function eP(t,{baseMs:e,capMs:n}=Nk){return!Number.isFinite(t)||t<1?0:Math.min(e*2**(t-1),n)}function L0(t,e,n){const s=t&&t[e];return!s||!(s.failures>=1)?!0:n>=s.nextAtMs}function A0(t,e,n,s,i=Nk){const c=(t&&t[e]||{failures:0}).failures+1;return{...t,[e]:{failures:c,cause:n,nextAtMs:s+eP(c,i)}}}function j0(t,e){if(!t||!(e in t))return t;const n={...t};return delete n[e],n}const tP=4e3,wv=600*1e3,jk="nc-sticky-owners-v1";function nP(){try{const t=localStorage.getItem(jk);if(!t)return null;const e=JSON.parse(t);return!e||!Array.isArray(e.nodes)||!Array.isArray(e.topology)?null:e}catch{return null}}function sP(t){try{localStorage.setItem(jk,JSON.stringify(t))}catch{}}function Zu(t,e,n,s,i){if(!e){for(const c of t.values())c.data={...c.data,stale:!0};return t}const a=new Map(n.map(c=>[s(c),c]));for(const[c,u]of t)a.has(c)?(u.data=a.get(c),u.missingSince=null,a.delete(c)):(u.missingSince??(u.missingSince=i),i-u.missingSince>wv?t.delete(c):u.data={...u.data,stale:!0});for(const[c,u]of a)t.set(c,{data:u,missingSince:null});return t}function bv(t,e=!0,n=0){const[s,i]=w.useState([]),a=w.useRef([]),c=w.useRef({}),u=w.useRef({}),h=w.useRef({remote:{},fleet:{}}),f=w.useRef(null),g=w.useRef(null),v=w.useRef(new Map),_=w.useRef(new Map),b=w.useRef(new Set),x=w.useRef(Zd()),L=w.useRef(null);return w.useEffect(()=>{if(!e||!t){i([]);return}let C=!0;const R=f.current!==null&&f.current!==t;f.current!==t&&(f.current=t,u.current={},h.current={remote:{},fleet:{}},v.current.clear(),_.current.clear(),b.current.clear(),c.current={},a.current=[],i([]));const S={instanceId:"",nodes:new Map,topology:new Map},I=R?null:nP();if(I){S.instanceId=I.instanceId||"";for(const $ of I.nodes)S.nodes.set($.name,{data:$,missingSince:null});for(const $ of I.topology)S.topology.set($.route.join("/"),{data:$,missingSince:null})}async function E(){const $=x.current,X=Date.now(),V=$.begin();if(V===null)return;const G=new AbortController;L.current=G;const ne={timeoutMs:S1,signal:G.signal},K=()=>C&&$.isCurrent(V);let D=[],P=[],O={},j="",z=!1,M=!1,A="pending",N="pending";const U={},T={},H=new Set,se=new Set,Q=new Set;let Z=new Map;const me=[],de=()=>{Z=new Map([...P.filter(Ne=>Array.isArray(Ne.route)).map(Ne=>[Ne.route.join("/"),Ne.instanceId]),...D.map(Ne=>[Ne.name,Ne.nodeId])].filter(([,Ne])=>typeof Ne=="string"&&Ne))},ie=Ne=>{const ge=Z.get(Ne),st=ge?_v(`id:${ge}`):[];return st.length?{available:!1,cells:st,fleetState:"stale"}:null},xe=()=>{if(!K()||!j)return!1;const Ne=[],ge=Date.now();for(const[He,qe]of _.current){if(ge-qe.at>wv){_.current.delete(He);continue}const wt=He.slice(3),W=v.current.get(wt);if(qe.ownerInstanceId!=null&&W!==void 0&&W!==qe.ownerInstanceId){_.current.delete(He);continue}const ee=b.current.has(He.slice(3)),J=qe.round!==V||qe.identityUnknown===!0||ee;for(const be of qe.peers)Ne.push({...be,stale:J})}const st=a.current,Ze=C0({nodes:D,topology:P,remote:U,fleet:T,aliases:O,down:c.current,pendingReads:H,previousGroups:st});c.current=qT(c.current,Ze,Math.floor(Date.now()/1e3));const De=[...C0({nodes:D,topology:P,remote:U,fleet:T,aliases:O,down:c.current,pendingReads:H,previousGroups:a.current}),...QT(Ne)];return GT(De),a.current=De,i(De),!0};let Be=[],nt=[];const Le=()=>{var Ne;if(K()&&j){z?Zu(S.nodes,!0,Be,ge=>ge&&ge.name,X):A==="error"&&Zu(S.nodes,!1,Be,ge=>ge&&ge.name,X),M?Zu(S.topology,!0,nt,ge=>Array.isArray(ge&&ge.route)?ge.route.join("/"):"",X):N==="error"&&Zu(S.topology,!1,nt,ge=>Array.isArray(ge&&ge.route)?ge.route.join("/"):"",X),D=[...S.nodes.values()].map(ge=>ge.data),P=[...S.topology.values()].map(ge=>ge.data),de();for(const[ge,st]of Z){const Ze=v.current.get(ge);Ze&&Ze!==st&&(delete h.current.remote[ge],delete h.current.fleet[ge],delete u.current[ge],delete u.current[`vl:${ge}`],delete c.current[ge],_.current.delete(`vl:${ge}`)),v.current.set(ge,st)}for(const ge of v.current.keys())if(!Z.has(ge)){const st=_.current.get(`vl:${ge}`);st&&(st.identityUnknown=!0)}b.current=new Set(P.filter(ge=>!ge.stale&&Array.isArray(ge.route)&&ge.route.length>0&&!Z.has(ge.route.join("/"))).map(ge=>ge.route.join("/")));for(const ge of D){if(((Ne=ge.tunnel)==null?void 0:Ne.status)==="up")continue;const st=h.current.fleet[ge.name];st&&!T[ge.name]&&(T[ge.name]={...st,available:!1,fleetState:"stale"})}for(const ge of P){if(!ge.stale||!Array.isArray(ge.route)||!ge.route.length)continue;const st=ge.route.join("/"),Ze=h.current.fleet[st];Ze&&!T[st]&&(T[st]={...Ze,available:!1,fleetState:"stale"})}(z||M)&&sP({instanceId:S.instanceId,savedAt:X,nodes:[...S.nodes.values()].map(ge=>ge.data),topology:[...S.topology.values()].map(ge=>ge.data)}),Y(),xe()}},Ie=(Ne,ge)=>{K()&&(A=Ne?"success":"error",z=Ne,Be=Ne?ge:[],Le())},ue=(Ne,ge)=>{K()&&(N=Ne?"success":"error",M=Ne,nt=Ne?ge:[],Le())},Re=Ne=>{K()&&(j=Ne&&typeof Ne.instanceId=="string"?Ne.instanceId:"",j&&(S.instanceId!==j||g.current!==j)?(S.instanceId!==j&&(S.nodes.clear(),S.topology.clear()),a.current=[],c.current={},u.current={},h.current={remote:{},fleet:{}},v.current.clear(),_.current.clear(),b.current.clear()):j&&(S.instanceId=j),g.current=j||null,S.instanceId=j,Le())};function fe(){const Ne=[{instanceId:j||null,route:[],label:null},...Ek({nodes:P},j)];for(const ge of Ne){const st=`${ge.instanceId}:${ge.route.join("/")}`;if(Q.has(st))continue;Q.add(st);const Ze=`vl:${ge.route.join("/")}`;me.push((async()=>{if(L0(u.current,Ze,X))try{const De=await j1(t,ge.route,{signal:G.signal});if(!K())return;const He=v.current.get(ge.route.join("/"));if(He!==void 0&&He!==ge.instanceId||b.current.has(ge.route.join("/")))return;u.current=j0(u.current,Ze);const qe=[];for(const wt of De.nodes||[]){const W=Ck(wt,ge);W&&qe.push(W)}_.current.set(Ze,{peers:qe,ownerInstanceId:ge.instanceId??null,at:X,round:V}),xe()}catch(De){if(!K())return;const He=v.current.get(ge.route.join("/"));if(He!==void 0&&He!==ge.instanceId||b.current.has(ge.route.join("/")))return;u.current=A0(u.current,Ze,bp(De),X)}})())}}async function Ee(Ne){const ge=Ne.join("/"),st=h.current.remote[ge]||null;if(!L0(u.current,ge,X)){H.delete(`${ge}#sessions`),H.delete(`${ge}#fleet`);const He=u.current[ge];U[ge]={error:"unreachable",cause:He&&He.cause||null,lastGoodAt:st?st.at:null};const qe=h.current.fleet[ge]||ie(ge);qe&&(T[ge]={...qe,available:!1,fleetState:"stale"});return}H.add(`${ge}#sessions`),H.add(`${ge}#fleet`);const Ze=(async()=>{let He=!1;try{const qe=await Xg(t,Ne,ne);if(!K())return;He=!0,U[ge]={...qe,at:X},h.current.remote[ge]={payload:qe,at:X}}catch(qe){if(!K())return;U[ge]={error:"unreachable",cause:bp(qe),lastGoodAt:st?st.at:null}}finally{H.delete(`${ge}#sessions`)}u.current=He?j0(u.current,ge):A0(u.current,ge,U[ge].cause,X),xe()})(),De=(async()=>{const He=h.current.fleet[ge]||ie(ge);try{const qe=await Qa(t,Ne,ne);if(!K())return;const wt=yv({fs:qe});wt.kind==="data"?(T[ge]={...qe,available:!0,cells:wt.cells,fleetState:"available"},Z.get(ge)&&Ka(`id:${Z.get(ge)}`,wt.cells)):wt.kind==="disabled"?(T[ge]={...qe,available:!1,cells:[],fleetState:"disabled"},Z.get(ge)&&Ka(`id:${Z.get(ge)}`,[])):T[ge]={...He||{},available:!1,cells:Array.isArray(He==null?void 0:He.cells)?He.cells:[],fleetState:"stale",...qe!=null&&qe.reason?{reason:qe.reason}:{}},h.current.fleet[ge]=T[ge]}catch(qe){if(!K())return;T[ge]={...He||{},available:!1,cells:Array.isArray(He==null?void 0:He.cells)?He.cells:[],fleetState:"stale",cause:bp(qe)},h.current.fleet[ge]=T[ge]}H.delete(`${ge}#fleet`),xe()})();await Promise.allSettled([Ze,De])}function Y(){var st,Ze;if(!K()||!j)return;fe();const Ne=new Set(D.map(De=>De.name)),ge=De=>{const He=De.join("/");se.has(He)||(se.add(He),me.push(Ee(De)))};for(const De of D)z&&!De.stale&&((st=De.tunnel)==null?void 0:st.status)==="up"&&(De.nodeId||De.paired!==!1)&&(De.direction!=="inbound"||De.shared===!0)?ge([De.name]):A==="pending"&&!De.stale&&((Ze=De.tunnel)==null?void 0:Ze.status)==="up"&&(H.add(`${De.name}#sessions`),H.add(`${De.name}#fleet`));for(const De of P)if(!De.stale&&Array.isArray(De.route)&&De.route.length>0&&!(De.route.length===1&&Ne.has(De.route[0]))){const He=De.route.join("/");M?ge(De.route):N==="pending"&&(H.add(`${He}#sessions`),H.add(`${He}#fleet`))}}const pe=DN(t,ne).then(Ne=>{Ie(!0,Array.isArray(Ne.nodes)?Ne.nodes:[])},()=>{Ie(!1,[])}),Ae=M1(t,ne).then(Ne=>{ue(!0,Array.isArray(Ne.nodes)?Ne.nodes:[])},()=>{ue(!1,[])}),ke=UN(t,ne).then(Ne=>{K()&&(O=Ne&&typeof Ne.aliasesByInstanceId=="object"?Ne.aliasesByInstanceId:{},xe())},()=>{}),We=Pc(t,[],ne).then(Ne=>{Re(Ne)},()=>{});try{await Promise.allSettled([pe,Ae,ke,We]),await Promise.allSettled(me)}finally{$.isCurrent(V)&&$.end(V)}}E();const F=setInterval(E,tP);return()=>{C=!1,clearInterval(F),x.current.reset(),L.current&&L.current.abort()}},[t,e,n]),s}const M0=52,T0=14;function Gi({position:t,itemKey:e,label:n,onMove:s,onStep:i,canMove:a=()=>!0,scope:c="roster"}){const u=w.useRef(null),h=w.useRef(0),[f,g]=w.useState(!1),v=()=>{var R,S,I,E;const C=u.current;(S=(R=C==null?void 0:C.over)==null?void 0:R.classList)==null||S.remove("nc-roster-over"),(E=(I=C==null?void 0:C.source)==null?void 0:I.classList)==null||E.remove("nc-roster-dragging"),h.current&&cancelAnimationFrame(h.current),h.current=0},_=(C=!1)=>{const R=u.current;if(!R)return;const S=R.target;v(),u.current=null,g(!1);try{R.handle.releasePointerCapture(R.pointerId)}catch{}C&&S&&S!==e&&a(e,S)&&s(e,S)},b=(C,R)=>{var V,G,ne,K,D,P,O,j,z;const S=u.current;if(!S)return;S.x=C,S.y=R;const I=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",E=(G=(V=document.elementFromPoint(C,R))==null?void 0:V.closest)==null?void 0:G.call(V,I),F=c==="node"?(ne=E==null?void 0:E.dataset)==null?void 0:ne.nodeOrderKey:(K=E==null?void 0:E.dataset)==null?void 0:K.rosterKey,X=(c==="node"||((D=E==null?void 0:E.dataset)==null?void 0:D.position)===t)&&F&&F!==e&&a(e,F);S.over!==(X?E:null)&&((O=(P=S.over)==null?void 0:P.classList)==null||O.remove("nc-roster-over"),S.over=X?E:null,(z=(j=S.over)==null?void 0:j.classList)==null||z.add("nc-roster-over")),S.target=X?F:null},x=()=>{const C=u.current;if(!C){h.current=0;return}const R=C.container;if(R){const S=R.getBoundingClientRect(),I=C.y<S.top+M0?-T0:C.y>S.bottom-M0?T0:0;I&&(R.scrollTop+=I,b(C.x,C.y))}h.current=requestAnimationFrame(x)};w.useEffect(()=>{const C=S=>{S.key==="Escape"&&u.current&&(S.preventDefault(),_(!1))},R=()=>_(!1);return window.addEventListener("keydown",C),window.addEventListener("blur",R),()=>{window.removeEventListener("keydown",C),window.removeEventListener("blur",R),v(),u.current=null}},[e,t,c]);const L=C=>{var E;if(C.pointerType==="mouse"&&C.button!==0)return;C.preventDefault(),C.stopPropagation(),C.currentTarget.focus({preventScroll:!0});const R=c==="node"?"[data-node-order-key]":"[data-roster-key][data-position]",S=C.currentTarget.closest(R),I=C.currentTarget.closest(".nc-side-scroll, .nc-home-scroll, .nc-cell-switcher-list");u.current={pointerId:C.pointerId,handle:C.currentTarget,source:S,container:I,target:null,over:null,x:C.clientX,y:C.clientY},(E=S==null?void 0:S.classList)==null||E.add("nc-roster-dragging");try{C.currentTarget.setPointerCapture(C.pointerId)}catch{}g(!0),h.current=requestAnimationFrame(x)};return l.jsx("button",{type:"button",className:`nc-roster-handle${f?" active":""}`,"aria-label":`${p("reorder")} ${n}`,"aria-keyshortcuts":"ArrowUp ArrowDown",title:p("reorder-help"),onClick:C=>{C.preventDefault(),C.stopPropagation()},onDragStart:C=>C.preventDefault(),onKeyDown:C=>{C.key!=="ArrowUp"&&C.key!=="ArrowDown"||(C.preventDefault(),C.stopPropagation(),i(C.key==="ArrowUp"?-1:1))},onPointerDown:L,onPointerMove:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),b(C.clientX,C.clientY))},onPointerUp:C=>{!u.current||C.pointerId!==u.current.pointerId||(C.preventDefault(),C.stopPropagation(),_(!0))},onPointerCancel:()=>_(!1),onLostPointerCapture:()=>{u.current&&_(!1)},children:"↕"})}const Mk="nc_pins";function to(){return Rr(Mk,{fallback:()=>[],parse:t=>Array.isArray(t)?t:void 0})}function Sv(t){return yi(Mk,t)}function iP(t,e){const n=t.includes(e)?t.filter(s=>s!==e):[...t,e];return{next:n,error:Sv(n)}}function P0(t,e){if(!Array.isArray(t)||!t.includes(e))return{next:Array.isArray(t)?t:[],error:null};const n=t.filter(s=>s!==e);return{next:n,error:Sv(n)}}function rP(t,e,n){if(!t.includes(e)||!t.includes(n)||e===n)return t;const s=[...t],i=s.indexOf(e),a=s.indexOf(n);s.splice(i,1);const c=s.indexOf(n);return s.splice(i<a?c+1:c,0,e),Sv(s),s}function oP(t,e,n){const s=t.indexOf(e);return[s===-1?1e9:s,-(n||0)]}function aP(t,e){return t[0]-e[0]||t[1]-e[1]}const mg="nexuscrew-roster-preferences",lP=new Set(["nc_pins",Qo,Jo,pg]),Ma=()=>{try{window.dispatchEvent(new Event(mg))}catch{}},cP=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Sp=t=>e=>cP(e,t)?e:t;function xv(){const[t,e]=w.useState(to),[n,s]=w.useState(_d),[i,a]=w.useState(uc),[c,u]=w.useState(null),[h,f]=w.useState(null);w.useEffect(()=>{if(!h)return;const I=setTimeout(()=>f(null),8e3);return()=>clearTimeout(I)},[h]),w.useEffect(()=>{const I=E=>{E&&E.type==="storage"&&E.key&&!lP.has(E.key)||(e(Sp(to())),a(Sp(uc())),s(Sp(_d())))};return window.addEventListener("storage",I),window.addEventListener(mg,I),()=>{window.removeEventListener("storage",I),window.removeEventListener(mg,I)}},[]);const g=I=>{const E=to(),F=iP(E,I);e(F.next),Ji({reason:F.error?"pin-write-failed":"pin",key:I,before:E,after:F.next,note:F.error?String(F.error.message||F.error):void 0}),Ma()},v=I=>{const E=to(),F=P0(E,I);return e(F.next),u(F.error?{key:I,message:F.error.message||String(F.error)}:null),Ji({reason:F.error?"unpin-write-failed":"unpin",key:I,before:E,after:F.next}),Ma(),F.error},_=()=>{if(!c)return;const I=P0(to(),c.key);e(I.next),u(I.error?{...c,message:I.error.message||String(I.error)}:null),Ma()},b=()=>u(null),x=I=>b0(ja(n),I),L=(I,E)=>{const F=_d(),$=yp(I),X=WT({...F,[$]:{...b0(ja(F),I),...E}});s(X),Ma()},C=(I,E)=>t.includes(I)===t.includes(E);function R(I,E,F,$){var A,N;const X=(A=$.find(U=>U.partial))==null?void 0:A.partial;if(X){f({reason:X,position:I,at:Date.now()}),Ji({reason:"reorder-blocked",position:yp(I),source:E,target:F,note:X});return}f(null);const V=to(),G=V.includes(E),ne=V.includes(F);if(G!==ne)return;if(G){const U=rP(V,E,F);e(U),Ji({reason:"move-pin",source:E,target:F,before:V,after:U}),Ma();return}const K=uc(),D=yp(I),P=ja(K),O=((N=$.find(U=>U.key===E))==null?void 0:N.technical)===!0,j=co($,V,O?"technical":"all",Ii(P,I)).map(U=>U.key),z=UT({...K,[D]:Ii(P,I)},D,E,F,j),M={...K,[D]:z[D]};HT(M),Ji({reason:"move",position:D,source:E,target:F,before:Ii(P,I),after:z[D],visible:j}),a(M),Ma()}function S(I,E,F,$){var O;if($.some(j=>j.partial)){R(I,E,E,$);return}const X=to(),V=ja(uc()),G=((O=$.find(j=>j.key===E))==null?void 0:O.technical)===!0,ne=X.includes(E),K=co($,X,G?"technical":"all",Ii(V,I)).map(j=>j.key).filter(j=>X.includes(j)===ne),D=K.indexOf(E),P=K[D+F];D>=0&&P&&R(I,E,P,$)}return{pins:t,views:ja(n),orders:ja(i),togglePin:g,removePin:v,pinError:c,retryPinPersist:_,clearPinError:b,reorderBlocked:h,viewFor:x,updateView:L,canMoveRoster:C,moveRoster:R,stepRoster:S}}const ah="nc_node_order_v1",uP=/^[a-f0-9]{16,64}$/;function Ho(t){if(uP.test(String((t==null?void 0:t.instanceId)||"")))return`id:${t.instanceId}`;const e=Array.isArray(t==null?void 0:t.route)?t.route.filter(n=>typeof n=="string"&&n):[];return e.length?`route:${e.map(encodeURIComponent).join("/")}`:typeof(t==null?void 0:t.name)=="string"&&t.name?`name:${encodeURIComponent(t.name)}`:""}function gg(t=globalThis.localStorage){return Rr(ah,{storage:t,fallback:()=>[],parse:e=>Array.isArray(e)?[...new Set(e.filter(n=>typeof n=="string"&&n&&n.length<=192))].slice(0,128):void 0})}function dP(t,e=globalThis.localStorage){return yi(ah,t,{storage:e}),t}function I0(t=[],e=[]){const n=new Map(e.map((s,i)=>[s,i]));return t.map((s,i)=>({group:s,index:i})).sort((s,i)=>{const a=n.has(Ho(s.group))?n.get(Ho(s.group)):Number.MAX_SAFE_INTEGER,c=n.has(Ho(i.group))?n.get(Ho(i.group)):Number.MAX_SAFE_INTEGER;return a-c||s.index-i.index}).map(({group:s})=>s)}function hP(t,e,n,s=[]){if(!e||!n||e===n)return t;const i=s.map(Ho).filter(Boolean);if(!i.includes(e)||!i.includes(n))return t;const a=[...t,...i.filter(f=>!t.includes(f))],c=a.indexOf(e),u=a.indexOf(n);a.splice(c,1);const h=a.indexOf(n);return a.splice(c<u?h+1:h,0,e),a}const vg="nexuscrew-node-preferences";function fP(){try{window.dispatchEvent(new Event(vg))}catch{}}function kv(){const[t,e]=w.useState(gg);w.useEffect(()=>{const a=()=>e(gg());return window.addEventListener("storage",a),window.addEventListener(vg,a),()=>{window.removeEventListener("storage",a),window.removeEventListener(vg,a)}},[]);const n=a=>I0(a,t),s=(a,c,u)=>e(h=>{const f=hP(h,a,c,u);return dP(f),fP(),f});return{order:t,groupsFor:n,moveNode:s,stepNode:(a,c,u)=>{const h=I0(u,t).map(Ho),f=h.indexOf(a),g=h[f+c];f>=0&&g&&s(a,g,u)},nodeKey:Ho}}function Tk({pinError:t,onRetry:e,onDismiss:n}){return t?l.jsxs("div",{className:"nc-pin-error",role:"alert",children:[l.jsx("span",{className:"nc-pin-error-text",children:"★ preferenza non salvata"}),l.jsx("button",{type:"button",className:"nc-pin-error-retry",onClick:e,children:"riprova"}),l.jsx("button",{type:"button",className:"nc-pin-error-close",onClick:n,"aria-label":"chiudi avviso",children:"×"})]}):null}function lh({item:t,pins:e,hostByRoute:n,route:s}){const i=(n||{})[Cs(s)]||{},a=Ed({hostCell:i.hostCell??null,threadStatus:i.threadStatus,pins:e,item:t}),c=I5(a);return{state:a,live:!!c,favorite:a==="favorite",filled:a!=="none",titleKey:c||"pin",action:a===H1?"removePin":"addPin"}}async function Cv({view:t,itemKey:e,togglePin:n,removePin:s}){return t.action==="removePin"?(s(e),{ok:!0}):(n(e),{ok:!0})}function oo({item:t,cellName:e,route:n=[],pins:s=[],hostByRoute:i={}}={}){const a=lh({item:t,pins:s,hostByRoute:i,route:n}),c=(i||{})[Cs(n)]||{};return{pinned:a.favorite,isLive:!!c.hostCell&&c.hostCell===e}}function Ev({isLive:t,pinned:e,canBoot:n,boot:s,alive:i,handlers:a={}}={}){const c=[];return typeof a.onToggleLive=="function"&&c.push({id:"live",kind:"action",on:!!t,labelKey:t?"cell-actions-live-remove":"cell-actions-live-assign",run:a.onToggleLive}),typeof a.onTogglePin=="function"&&c.push({id:"pin",kind:"action",on:!!e,labelKey:e?"cell-actions-unpin":"cell-actions-pin",run:a.onTogglePin}),n&&typeof a.onToggleBoot=="function"&&c.push({id:"boot",kind:"switch",on:!!s,labelKey:"cell-actions-boot",run:()=>a.onToggleBoot(!s)}),i&&typeof a.onWatchLive=="function"&&c.push({id:"watch",kind:"action",on:!1,labelKey:"cell-actions-watch",run:a.onWatchLive}),c}function Pk({items:t=[],busy:e=!1,onRun:n}){return l.jsx("div",{className:"nc-cellactions",role:"menu","aria-busy":e||void 0,children:t.map(s=>{const i=s.descKey?p(s.descKey):s.descText;return l.jsxs("button",{type:"button",role:s.kind==="switch"?"menuitemcheckbox":"menuitem","aria-checked":s.kind==="switch"?s.on?"true":"false":void 0,className:`nc-cellactions-voce${s.on?" on":""}`,disabled:e,"data-cellaction":s.id,onClick:a=>{a.stopPropagation(),n?n(s):s.run()},children:[s.kind==="switch"?l.jsx("span",{className:`nc-cellactions-toggle${s.on?" on":""}`,"aria-hidden":"true"}):null,l.jsxs("span",{className:"nc-cellactions-testo",children:[p(s.labelKey),i?l.jsx("small",{className:"nc-cellactions-desc",children:i}):null]})]},s.id)})})}function Ik({aperto:t,refGuscio:e,onClose:n}){w.useEffect(()=>{const s=a=>{e.current&&!e.current.contains(a.target)&&n()},i=a=>{a.key==="Escape"&&n()};return document.addEventListener("pointerdown",s),document.addEventListener("keydown",i),()=>{document.removeEventListener("pointerdown",s),document.removeEventListener("keydown",i)}},[t,e,n])}function Dk({anchorRect:t,items:e,busy:n,onClose:s}){const i=w.useRef(null);Ik({aperto:!0,refGuscio:i,onClose:s});const a=t?{top:Math.min(t.bottom+6,window.innerHeight-8),left:Math.max(8,Math.min(t.right-210,window.innerWidth-218))}:void 0;return l.jsx("div",{className:"nc-cellactions-popover",style:a,ref:i,"data-testid":"cell-actions-popover",children:l.jsx(Pk,{items:e,busy:n,onRun:c=>{c.run(),s()}})})}function Nv({cellName:t,items:e,busy:n,onClose:s}){const i=w.useRef(null);return Ik({aperto:!0,refGuscio:i,onClose:s}),l.jsx("div",{className:"nc-cellactions-velo","data-testid":"cell-actions-sheet",children:l.jsxs("div",{className:"nc-cellactions-foglio",role:"dialog","aria-modal":"true","aria-label":p("cell-actions-title").replace("{cell}",t||""),ref:i,children:[l.jsxs("div",{className:"nc-cellactions-testa",children:[l.jsx("span",{className:"nc-cellactions-titolo",children:p("cell-actions-title").replace("{cell}",t||"")}),l.jsx("button",{type:"button",className:"nc-cellactions-chiudi",onClick:s,title:p("close"),"aria-label":p("close"),children:"✕"})]}),l.jsx(Pk,{items:e,busy:n,onRun:a=>{a.run(),s()}})]})})}const pP="native",mP="tmux";function gP(t){return typeof t!="string"||!t?null:t.startsWith("codex-vl")?pP:mP}function Va({liveHost:t,cells:e=[],localNodeId:n="",ownerId:s=null}={}){const i=t&&typeof t.hostCell=="string"&&t.hostCell?t.hostCell:null,a=i&&(Array.isArray(e)?e:[]).find(u=>u&&u.cell===i)||null,c=a&&typeof a.engine=="string"&&a.engine?a.engine:null;return{hostCell:i,cell:i,known:!!a,engine:c,mode:gP(c),state:i?Y1(t&&t.threadStatus):_c,remote:!!(s&&n&&s!==n),lease:t&&(t.hostLease||(t.host&&typeof t.host.lease=="string"?t.host.lease:null))||null}}function vP(t){const e=t&&t.state?t.state:_c;return{modeKey:t&&t.mode?`live-host-mode-${t.mode}`:null,stateKey:`live-host-state-${e}`}}function Rv(t){const e=t&&t.state?t.state:_c;return e==="thread-active"?"active":e==="thread-present"?"present":e===_c?"none":e==="thread-unknown"?"unknown":"designated"}function ao(t,e=Math.floor(Date.now()/1e3)){if(!t)return"";const n=e-t;return n<0||n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function Ok(t){const e=t||{};return!(e.sessionsAvailable===!1||typeof e.status=="string"&&e.status!=="up")}function Qi(t){return t.status==="up"&&!Ok(t)?p("node-sessions-unverified"):t.status==="passive"?p("node-passive"):t.status==="down"?t.downSince?p("tunnel-down-since").replace("{t}",ao(t.downSince)):p("tunnel-down"):t.status==="unreachable"?t.cause===Lk?p("peer-cause-nega"):t.cause===Ak?p("peer-cause-rotta"):t.cause===Rk?p("peer-cause-assente"):p("node-unreachable"):t.status==="offline"?t.lastSeen?p("node-offline-seen").replace("{t}",ao(t.lastSeen)):p("node-offline"):t.status==="needs-repair"?p("node-needs-repair"):""}function Bk(t,{passive:e=null}={}){return t?t.status==="passive"?e:t.status==="healthy"?"on":"warn":null}function Id(t){return t&&(t.detail||t.status)||""}const _P="restrict,port-forwarding,permitopen=";function yP(t){const e=t&&typeof t.hint=="string"&&t.hint.trim()||"",n=t&&typeof t.authorizedKeys=="string"&&t.authorizedKeys.trim()||"";if(n){const i=e.indexOf(n);return{note:i>=0?e.slice(0,i).replace(/[:\s]+$/,""):e,line:n}}if(!e)return null;const s=e.indexOf(_P);return s<0?{note:e,line:""}:{note:e.slice(0,s).replace(/[:\s]+$/,""),line:e.slice(s).trim()}}function Dd(t,e,n=globalThis.localStorage){if(!(t!=null&&t.outbox)||t.outbox.count<1)return!1;const s=Number(n.getItem(x1(e))||0);return t.outbox.latest>s}function ch(t,e={},{autorevole:n=!0}={}){const s=t||{},i=`${s.engine||""}${s.key?`·${s.key}`:""}`,a=[i,s.model&&s.model!==i?s.model:""].filter(Boolean).join(" · ");if(!s.tmux)return{working:!1,subtitle:String(a||p("cell-off")).trim()};const c=e.attivita&&typeof e.attivita=="object"?e.attivita.stato:null;if(c==="lavora"||c==="attesa"){const u=p(c==="attesa"?"cell-permission":"cell-working"),h=String(e.status||"").trim(),f=!h||/^working(?:\.{3}|…)?$/i.test(h);return{working:!0,stato:c,subtitle:c==="lavora"&&!f?`${u} · ${h}`:u}}if(c==="ferma")return{working:!1,stato:"ferma",subtitle:p("cell-stopped")};if(!n)return{working:!1,stato:"ignoto",subtitle:[p("cell-unknown"),a].filter(Boolean).join(" · ")};if(e.working===!0){const u=String(e.status||"").trim();return{working:!0,stato:"ignoto",subtitle:!u||/^working(?:\.{3}|…)?$/i.test(u)?p("cell-unknown"):`${p("cell-unknown")} · ${u}`}}return e.working===!1?{working:!1,stato:"ignoto",subtitle:p("cell-unknown")}:{working:!1,stato:"ignoto",subtitle:String(e.preview||s.preview||p("cell-on")).trim()}}function $k(t,e){return[...new Set([t.engine,t.model,t.key,e.preview,t.preview,e.status].filter(Boolean).map(String))].join(" ")}function zk({sessionsOk:t=!0,fleetStale:e=!1,cellCount:n=0}={}){return t?e&&!n?"fleet":null:"sessions"}function Lv(t,e,n,s=globalThis.localStorage,{autorevole:i=!0,fleetStale:a=!1}={}){const c=zk({sessionsOk:i,fleetStale:a,cellCount:Array.isArray(t)?t.length:0});return Fk([...(Array.isArray(t)?t:[]).map(u=>{const h=n.get(u.tmuxSession)||{},f=qa([],u.tmuxSession),g=ch(u,h,{autorevole:i});return{type:"cell",value:u,key:f,label:u.cell,live:!!u.tmux,fresh:Dd(h,f,s),activity:h.activity||0,working:g.working,stato:g.stato,subtitle:g.subtitle,searchText:$k(u,h)}}),...(Array.isArray(e)?e:[]).map(u=>{const h=qa([],u.name);return{type:"session",value:u,key:h,label:u.name,live:!0,technical:u.technical===!0,fresh:Dd(u,h,s),activity:u.activity||0,searchText:`${u.preview||""} ${u.cmd||""}`}})],c)}const Fk=(t,e)=>e?t.map(n=>({...n,partial:e})):t;function mc(t,e=globalThis.localStorage){const n=t||{},s=Array.isArray(n.route)?n.route:[],i=Ok(n),a=new Map((n.sessions||[]).map(h=>[h.name,h])),c=[...(n.cells||[]).map(h=>{const f=a.get(h.tmuxSession)||{},g=qa(s,h.tmuxSession||h.cell),v=ch(h,f,{autorevole:i});return{type:"cell",value:h,key:g,label:h.cell,live:!!h.tmux&&!h.preserved,fresh:Dd(f,g,e),activity:f.activity||h.activity||0,working:v.working,stato:v.stato,subtitle:v.subtitle,searchText:$k(h,f)}}),...(n.unmanaged||[]).map(h=>{const f=qa(s,h.name);return{type:"session",value:h,key:f,label:h.name,live:!0,technical:h.technical===!0,fresh:Dd(h,f,e),activity:h.activity||0,searchText:`${h.preview||""} ${h.cmd||""}`}})],u=zk({sessionsOk:n.sessionsAvailable!==!1,fleetStale:n.fleetState==="stale",cellCount:(n.cells||[]).length});return{route:s,rawItems:Fk(c,u)}}const uh=9,_g=.2,wP=/^[a-z0-9-]{1,32}(?:\/[a-z0-9-]{1,32}){0,3}$/,Ya=/^[a-f0-9]{16,64}$/,yg=t=>wP.test(t)&&new Set(t.split("/")).size===t.split("/").length;function Cr(t){if(typeof t=="string"&&t){const e=t.indexOf(":");if(e<0)return{session:t};const n=t.slice(0,e),s=t.slice(e+1);return!yg(n)||!s?null:{session:s,node:n}}if(t&&typeof t=="object"&&typeof t.session=="string"&&t.session){const e=t.ownerId===void 0?void 0:typeof t.ownerId=="string"&&Ya.test(t.ownerId)?t.ownerId:null;return e===null?null:t.node===void 0||t.node===null||t.node===""?{session:t.session,...e?{ownerId:e}:{}}:typeof t.node=="string"&&yg(t.node)?{session:t.session,node:t.node,...e?{ownerId:e}:{}}:null}return null}function $t(t){const e=Cr(t);return e?e.node?`${e.node}:${e.session}`:e.session:""}const Hk=9,Uk=24,_i=11,Wk=t=>{const e=Number(t);return e>=Hk&&e<=Uk?e:_i};function uo(){return{columns:[]}}function _s(t){return t.columns.flatMap(e=>e.tiles.map(n=>$t(n)))}function bP(t){const e=[],n=Math.max(0,...t.columns.map(s=>s.tiles.length));for(let s=0;s<n;s+=1)for(const i of t.columns)i.tiles[s]&&e.push($t(i.tiles[s]));return e}const Oi=t=>({columns:t.columns.map(e=>({width:e.width,tiles:e.tiles.map(n=>({...n}))}))});function Ec(t,e,n,s){const i=Cr(e);if(!i||_s(t).includes($t(i))||_s(t).length>=uh)return t;const a=Oi(t),c={session:i.session,height:1,fontSize:_i,...s||{}};if(i.node&&(c.node=i.node),i.ownerId&&(c.ownerId=i.ownerId),n==="end")return a.columns.push({width:1,tiles:[c]}),a;if(n&&typeof n.col=="number"&&typeof n.row=="number"&&a.columns[n.col])return a.columns[n.col].tiles.splice(n.row,0,c),a;if(n&&typeof n.col=="number"){const u=Math.max(0,Math.min(a.columns.length,n.col));return a.columns.splice(u,0,{width:1,tiles:[c]}),a}return a.columns.push({width:1,tiles:[c]}),a}function qk(t,e){const n=$t(e);if(!n||_s(t).includes(n)||_s(t).length>=uh)return t;const s=_s(t).length+1,i=Math.ceil(Math.sqrt(s));if(t.columns.length>=i){let g=0;for(let v=1;v<t.columns.length;v+=1)t.columns[v].tiles.length<t.columns[g].tiles.length&&(g=v);return Ec(t,e,{col:g,row:t.columns[g].tiles.length})}const a=[...bP(t),n],c=new Map(t.columns.flatMap(g=>g.tiles.map(v=>[$t(v),v]))),u=Cr(e),h=t.columns.length?t.columns.reduce((g,v)=>g+(Number(v.width)||1),0)/t.columns.length:1,f=Array.from({length:i},(g,v)=>{var _;return{width:((_=t.columns[v])==null?void 0:_.width)||h,tiles:[]}});return a.forEach((g,v)=>{const _=Cr(g);if(!_)return;const b=c.get(g)||(g===n?u:{})||{},x={session:_.session,height:b.height||1,fontSize:b.fontSize||_i};_.node&&(x.node=_.node),b.ownerId&&(x.ownerId=b.ownerId),b.unavailable===!0&&(x.unavailable=!0),b.stale===!0&&(x.stale=!0),f[v%i].tiles.push(x)}),{columns:f.filter(g=>g.tiles.length)}}function Kk(t,e){const n=Cr(e);if(!n)return t;const s=$t(n);if(!s||_s(t).includes(s)||_s(t).length>=uh)return t;const i=e&&typeof e=="object"?e:{},a={height:Math.max(_g,Number(i.height)||1),fontSize:Wk(i.fontSize),...n.ownerId?{ownerId:n.ownerId}:{}};if(!t.columns.length)return Ec(t,n,null,a);let c=0;for(let u=1;u<t.columns.length;u+=1)t.columns[u].tiles.length<t.columns[c].tiles.length&&(c=u);return Ec(t,n,{col:c,row:t.columns[c].tiles.length},a)}function Nc(t,e){const n=$t(e),s=Oi(t);for(const i of s.columns)i.tiles=i.tiles.filter(a=>$t(a)!==n);return s.columns=s.columns.filter(i=>i.tiles.length>0),s}function SP(t,e,n){const s=$t(e);if(!_s(t).includes(s))return t;const i=t.columns.flatMap(a=>a.tiles).find(a=>$t(a)===s);return Ec(Nc(t,s),s,n,{fontSize:i.fontSize,height:i.height,...i.ownerId?{ownerId:i.ownerId}:{},...i.unavailable===!0?{unavailable:!0}:{},...i.stale===!0?{stale:!0}:{}})}function xP(t,e){if(!(e instanceof Map)||e.size===0)return t;let n=!1;const s=Oi(t);for(const i of s.columns)for(const a of i.tiles){const c=e.get($t(a));if(!c)continue;const u=Cr(c);u&&(a.session=u.session,u.node?a.node=u.node:delete a.node,u.ownerId&&(a.ownerId=u.ownerId),n=!0)}return n?Pi(s):t}const Vk=120,Yk=60,hc=[1/3,.5,2/3],wg=16;function Gk(t,e,n,s){if(!(e>0))return .5;const i=Math.max(0,Math.min(.5,n/e));let a=t/e;if(a=Math.max(i,Math.min(1-i,a)),s){for(const c of hc)if(Math.abs(a-c)*e<=wg){a=c;break}}return a}function D0(t,e,n,s,i={}){const a=Oi(t),c=a.columns[e],u=a.columns[e+1];if(!c||!u)return t;const h=a.columns.reduce((_,b)=>_+(Number(b.width)||1),0),f=(Number(c.width)||1)+(Number(u.width)||1),g=(Number(n)||0)*(f/(h||1)),v=i.half===!0?.5:Gk(s,g,i.minPx??Vk,i.snap!==!1);return c.width=f*v,u.width=f*(1-v),a}function O0(t,e,n,s,i,a={}){const c=Oi(t),u=c.columns[e],h=u&&u.tiles[n],f=u&&u.tiles[n+1];if(!h||!f)return t;const g=u.tiles.reduce((x,L)=>x+(Number(L.height)||1),0),v=(Number(h.height)||1)+(Number(f.height)||1),_=(Number(s)||0)*(v/(g||1)),b=a.half===!0?.5:Gk(i,_,a.minPx??Yk,a.snap!==!1);return h.height=v*b,f.height=v*(1-b),c}function kP(t,e,n){if(!e||!n||e===n)return t;const s=Oi(t);let i=null,a=null;for(const f of s.columns)for(let g=0;g<f.tiles.length;g+=1){const v=$t(f.tiles[g]);v===e&&!i?i={col:f,i:g}:v===n&&!a&&(a={col:f,i:g})}if(!i||!a)return t;const c=i.col.tiles[i.i],u=a.col.tiles[a.i],h=f=>{const g={...f};return delete g.height,g};return i.col.tiles[i.i]={...h(u),height:c.height},a.col.tiles[a.i]={...h(c),height:u.height},s}const $c=6,zc=t=>{let{x:e,y:n,w:s,h:i}=t;return s=Math.max(.05,Math.min(1,Number(s)||.3)),i=Math.max(.05,Math.min(1,Number(i)||.3)),e=Math.max(0,Math.min(1-s,Number(e)||0)),n=Math.max(0,Math.min(1-i,Number(n)||0)),{x:e,y:n,w:s,h:i}};function Av(t,e){for(const n of t.columns)for(let s=0;s<n.tiles.length;s+=1)if($t(n.tiles[s])===e)return{tile:n.tiles[s]};return null}function CP(t,e,n){const s=Oi(t),i=$t(e);if(NP(s).length>=$c)return t;const a=Av(s,i);return!a||a.tile.float?t:(a.tile.float=zc(n||{}),s)}function EP(t,e){const n=Oi(t),s=Av(n,$t(e));return!s||!s.tile.float?t:(delete s.tile.float,n)}function B0(t,e,n){const s=Oi(t),i=Av(s,$t(e));return!i||!i.tile.float?t:(i.tile.float=zc(n),s)}function NP(t){return t.columns.flatMap(e=>e.tiles).filter(e=>e.float).map(e=>$t(e))}function Od(t){const e=[],n=[];for(const s of t.columns){const i=[];for(const a of s.tiles)if(a.float){const c={session:a.session,...a.float,fontSize:a.fontSize};a.node&&(c.node=a.node),a.ownerId&&(c.ownerId=a.ownerId),e.push(c)}else i.push(a);i.length&&n.push({width:s.width,tiles:i})}return{grid:{columns:n},floating:e}}const Xk=["x","y","w","h","fontSize"],bg=(t,e)=>Math.abs((Number(t)||0)-(Number(e)||0))<1e-9,Jk=(t,e)=>Xk.every(n=>bg(t[n],e[n]));function RP(t,e,n){if(!t)return n;const s={...n};for(const i of Xk)bg(n[i],t[i])&&!bg(e[i],t[i])&&(s[i]=e[i]);return{...s,...zc(s)}}function LP(t,e,n){const s=h=>new Map((Array.isArray(h)?h:[]).map(f=>[$t(f),f]).filter(([f])=>f)),i=s(t),a=s(e),c=s(n),u=[];for(const[h,f]of c)!a.has(h)&&i.has(h)&&Jk(f,i.get(h))||u.push(a.has(h)?RP(i.get(h),a.get(h),f):f);for(const[h,f]of a)c.has(h)||i.has(h)||u.push(f);return u.slice(0,$c)}function AP(t,e,n,s,i){const a=_=>Array.isArray(_.floating)?_.floating:[],c=(_,b)=>a(_).some(x=>$t(x)===b)?"float":_s(_.grid).includes(b)?"grid":"",u=(_,b)=>_.columns.flatMap(x=>x.tiles).find(x=>$t(x)===b),h=new Set([...a(n),...a(s),...a(i)].map(_=>$t(_)).filter(Boolean));let f=t,g=Array.isArray(e)?e:[];const v=(_,b)=>a(_).find(x=>$t(x)===b);for(const _ of h){const b=c(i,_),x=c(n,_),C=b!==x||b==="float"&&!Jk(v(i,_),v(n,_))?b:c(s,_);if(C!=="grid"&&_s(f).includes(_)&&(f=Nc(f,_)),C!=="float"&&(g=g.filter(R=>$t(R)!==_)),C==="grid"&&!_s(f).includes(_)){const R=u(s.grid,_)||u(i.grid,_)||u(n.grid,_);R&&(f=Kk(f,R))}if(C==="float"&&!g.some(R=>$t(R)===_)){const R=[s,i,n].map(S=>a(S).find(I=>$t(I)===_)).find(Boolean);R&&(g=[...g,R])}}return{grid:f,floating:g.slice(0,$c)}}function jP(t,e){const n=s=>{const{grid:i,floating:a}=Od(s||uo());return JSON.stringify({g:i.columns.map(c=>[c.width,c.tiles.map(u=>[$t(u),u.ownerId||"",u.height,u.fontSize])]),f:a.map(c=>[$t(c),c.ownerId||"",c.x,c.y,c.w,c.h,c.fontSize])})};return n(t)===n(e)}function Sg(t,e){let n=t;for(const s of Array.isArray(e)?e:[]){const i={session:s.session};s.node&&(i.node=s.node),s.ownerId&&(i.ownerId=s.ownerId);const a=$t(i);if(!a||_s(n).includes(a))continue;const c=Oi(n);c.columns.length||c.columns.push({width:1,tiles:[]});let u=0;for(let f=1;f<c.columns.length;f+=1)c.columns[f].tiles.length<c.columns[u].tiles.length&&(u=f);const h={session:i.session,height:1,fontSize:s.fontSize||_i,float:zc(s)};i.node&&(h.node=i.node),i.ownerId&&(h.ownerId=i.ownerId),c.columns[u].tiles.push(h),n=c}return n}function MP(t,e,n,s){if(!(t.columns[e]&&t.columns[e].tiles[n]))return t;const a=Oi(t),c=a.columns[e].tiles[n],u=Number(c.fontSize)||_i;return c.fontSize=Math.max(Hk,Math.min(Uk,u+(Number(s)||0))),a}function TP(t,e,n,s){const i=t.columns[e];if(!i||!i.tiles[n])return null;switch(s){case"left":return{col:e};case"right":return{col:e+1};case"top":return{col:e,row:n};case"bottom":return{col:e,row:n+1};default:return null}}function Pi(t){if(!t||!Array.isArray(t.columns))return uo();const e=t.columns.map(a=>({width:Math.max(_g,Number(a&&a.width)||1),tiles:(Array.isArray(a&&a.tiles)?a.tiles:[]).filter(c=>c&&typeof c.session=="string"&&c.session).filter(c=>c.node==null||typeof c.node=="string"&&yg(c.node)).filter(c=>c.ownerId==null||typeof c.ownerId=="string"&&Ya.test(c.ownerId)).map(c=>{const u={session:c.session,height:Math.max(_g,Number(c.height)||1),fontSize:Wk(c.fontSize)};return c.node!=null&&(u.node=c.node),c.ownerId!=null&&(u.ownerId=c.ownerId),c.float&&(u.float=zc(c.float)),u})})).filter(a=>a.tiles.length>0),n=new Set;let s=0,i=0;for(const a of e)a.tiles=a.tiles.filter(c=>{const u=$t(c);return n.has(u)||(c.float?i>=$c:s>=uh)?!1:(n.add(u),c.float?i+=1:s+=1,!0)});return{columns:e.filter(a=>a.tiles.length>0)}}function PP(t,e){let n=Pi(t);const s=Pi(e),i=new Map;for(const c of s.columns)for(const u of c.tiles)i.set($t(u),u);for(const c of n.columns)for(let u=0;u<c.tiles.length;u+=1){const h=$t(c.tiles[u]);i.has(h)&&(c.tiles[u]=i.get(h))}const a=new Map;for(const c of s.columns){const u=c.tiles.map(h=>$t(h)).sort().join("|");a.has(u)||a.set(u,c.width)}for(const c of n.columns){const u=c.tiles.map(f=>$t(f)).sort().join("|"),h=a.get(u);h!=null&&(c.width=h)}for(const[c,u]of i)_s(n).includes(c)||(n=Kk(n,u));return n}const Qk=/^[a-z0-9-]{1,32}$/,IP=/^[A-Za-z0-9._-]{1,32}$/,DP=/^[A-Za-z0-9][A-Za-z0-9._-]{0,254}$/,OP=320;function xg(t){return typeof t=="string"&&Qk.test(t)}const BP=64;function Ga(t){if(typeof t!="string")return!1;const e=t.trim();return e.length>0&&e.length<=BP&&!/[\x00-\x1f\x7f]/.test(e)}function ho(t){return String(t??"").normalize("NFKD").replace(/[̀-ͯ]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32).replace(/-+$/g,"")||"node"}function Zk(t){if(typeof t!="string"||!t||t.length>OP||t.startsWith("-")||/[\0-\x20\x7f]/.test(t))return!1;if(!t.includes("@"))return/^[A-Za-z0-9][A-Za-z0-9._:-]{0,254}$/.test(t);const e=t.indexOf("@");return e<=0||e!==t.lastIndexOf("@")?!1:IP.test(t.slice(0,e))&&DP.test(t.slice(e+1))}function $0(t){if(t===""||t===null||t===void 0)return null;const e=String(t).trim();if(!/^[0-9]{1,5}$/.test(e))return;const n=Number(e);return Number.isInteger(n)&&n>=1&&n<=65535?n:void 0}function $P({name:t,ssh:e,sshPort:n,remotePort:s}={}){const i=typeof t=="string"?t.trim():t,a=typeof e=="string"?e.trim():e;if(!xg(i))return{ok:!1,error:"err-node-name"};if(!Zk(a))return{ok:!1,error:"err-ssh"};const c=$0(n);if(c===void 0)return{ok:!1,error:"err-ssh-port"};const u=$0(s);if(u===void 0)return{ok:!1,error:"err-node-port"};const h={name:i,ssh:a};return c!==null&&(h.sshPort=c),u!==null&&(h.remotePort=u),{ok:!0,value:h}}function zP(t,e){if(!t||!e||e<t)return null;const n=Math.floor((e-t)/1e3);return n<60?"ora":n<3600?`${Math.floor(n/60)}m`:n<86400?`${Math.floor(n/3600)}h`:`${Math.floor(n/86400)}g`}function kg(t,e){const n=!!(t&&t.status==="up"),s=!!(t&&t.status==="passive");return{up:n,...s?{passive:!0}:{},label:n?"tunnel-up":s?"node-passive":"tunnel-down",since:n?zP(t.since,e):null}}const FP=new Set(["v","instanceId","port","label","invite"]),HP=new Set(["v","instanceId","port","label","invite","name","ssh","sshPort"]);function UP(t){const e=String(t).replace(/-/g,"+").replace(/_/g,"/"),n=e+"=".repeat((4-e.length%4)%4),s=typeof atob=="function"?atob(n):Buffer.from(n,"base64").toString("binary"),i=Uint8Array.from(s,a=>a.charCodeAt(0));return typeof TextDecoder<"u"?new TextDecoder().decode(i):Buffer.from(i).toString("utf8")}function WP(t){let e="";try{const c=new URL(String(t));e=new URLSearchParams(c.hash.replace(/^#/,"")).get("pair")||""}catch{return{ok:!1}}if(!e)return{ok:!1};let n;try{n=JSON.parse(UP(e))}catch{return{ok:!1}}if(!n||typeof n!="object"||Array.isArray(n))return{ok:!1};const s=n.v===1?FP:n.v===2?HP:null;if(!s)return{ok:!1};for(const c of Object.keys(n))if(!s.has(c))return{ok:!1};if(!/^[a-f0-9]{16,64}$/.test(String(n.instanceId)))return{ok:!1};const i=Number(n.port);if(!Number.isInteger(i)||i<1||i>65535)return{ok:!1};if(typeof n.label!="string")return{ok:!1};if(typeof n.invite!="string"||!n.invite)return{ok:!1};const a={ok:!0,version:n.v,label:n.label,invite:n.invite,instanceId:n.instanceId,port:i};if(n.v===2){if(n.name!==void 0){if(typeof n.name!="string"||!Qk.test(n.name))return{ok:!1};a.name=n.name}if(n.ssh!==void 0){if(!Zk(n.ssh))return{ok:!1};a.ssh=String(n.ssh).trim()}if(n.sshPort!==void 0){const c=Number(n.sshPort);if(!Number.isInteger(c)||c<1||c>65535)return{ok:!1};a.sshPort=c}}return a}function qP(t,e,n=new Set){if(!e||!e.ok)return t;const s={...t},i=(a,c)=>{c==null||c===""||n.has(a)||(s[a]=c)};return i("label",e.label),e.version===2&&(i("name",e.name||(e.ssh?ho(e.label):"")),i("ssh",e.ssh),e.sshPort!==void 0&&i("sshPort",String(e.sshPort))),s}const KP=["KIMI_AUTH_ACTION_REQUIRED","CLIENT_INTERACTION_REQUIRED"],VP=["kimi-code-consent-yes","kimi-code-config-custom-api-key","kimi-cli-login","client-terminal-dialog"];function YP(t){const e=t&&typeof t=="object"?t.actionRequired:null;if(e&&typeof e=="object"&&KP.includes(e.code)&&VP.includes(e.recovery))return{code:e.code,recovery:e.recovery,text:p(`fleet-recovery-${e.recovery}`)};if(t&&typeof t=="object"&&t.vlPromptDegraded===!0)return{code:"VL_PROMPT_DEGRADED",recovery:null,text:p("fleet-vl-prompt-degraded")};if(t&&typeof t=="object"&&t.readinessDegraded===!0){if(t.mcpDegraded&&typeof t.mcpDegraded=="object"){const n=[...Array.isArray(t.mcpDegraded.failed)?t.mcpDegraded.failed:[],...Array.isArray(t.mcpDegraded.pending)?t.mcpDegraded.pending:[]].filter(s=>typeof s=="string"&&s).slice(0,16);if(n.length)return{code:"READINESS_DEGRADED",recovery:null,text:p("fleet-mcp-degraded")+" "+n.join(", ")}}return{code:"READINESS_DEGRADED",recovery:null,text:p("fleet-readiness-degraded")}}return null}function GP(t,e){if(!t)return null;const n=t.status===502&&t.data&&t.data.cause==="upstream-timeout";return t.name==="TimeoutError"||n?{code:"FLEET_ACTION_TIMEOUT",recovery:null,text:p(e==="down"?"fleet-down-slow":"fleet-up-slow")}:t.status===409&&e==="up"&&t.data&&t.data.code==="SESSION_DUPLICATE"?{code:"FLEET_SESSION_DUPLICATE",recovery:null,text:p("fleet-up-duplicate")}:null}async function jv({token:t,powerCell:e,payload:n,onNotice:s,fleetApi:i}){const a=i||{fleetUp:xN,fleetDown:C1},{cell:c}=e,u=Array.isArray(e.route)?e.route:[];try{if(n.action==="up"){const h=await a.fleetUp(t,{cell:c,boot:!!n.boot,...n.engine?{engine:n.engine}:{},...n.model!==void 0?{model:n.model}:{},...n.permissionPolicy?{permissionPolicy:n.permissionPolicy}:{}},u),f=YP(h);f&&s(f.text)}else await a.fleetDown(t,{cell:c,boot:!!n.boot},u);return}catch(h){const f=GP(h,n.action);if(f)return s(f.text),{benign:f.code};throw h}}const XP=1e4;function eC(){const[t,e]=w.useState(null),n=w.useRef(null),s=w.useCallback(i=>{typeof i!="string"||!i||(n.current&&clearTimeout(n.current),e(i),n.current=setTimeout(()=>e(null),XP))},[]);return w.useEffect(()=>()=>{n.current&&clearTimeout(n.current)},[]),{notice:t,showActionNotice:s}}let Cg={sessions:[],cells:[],nodeGroups:[],localNodeId:"",localFresh:!1,refreshedAt:0};function z0(){return Cg}function tC(t={}){return Cg={sessions:Array.isArray(t.sessions)?t.sessions:[],cells:Array.isArray(t.cells)?t.cells:[],nodeGroups:Array.isArray(t.nodeGroups)?t.nodeGroups:[],localNodeId:typeof t.localNodeId=="string"?t.localNodeId:"",localFresh:t.localFresh===!0,refreshedAt:Number.isFinite(t.refreshedAt)?t.refreshedAt:0},Cg}const Ta=(t,e=[])=>`${e.length?e.join("/"):"local"}:${t}`;function JP({onPick:t,token:e,onSettings:n,onOpenVlSession:s,hostByRoute:i={},onDesignateCell:a,onClearHostCell:c,panelPort:u=0,nodePanelPorts:h=null}){const[f,g]=zn(),v=bv(e),[_,b]=w.useState(null),[x,L]=w.useState(null),[C,R]=w.useState(!0),[S,I]=w.useState(""),[E,F]=w.useState(""),[$,X]=w.useState({bind:"127.0.0.1",port:""}),[V,G]=w.useState(""),[ne,K]=w.useState([]),[D,P]=w.useState([]),[O,j]=w.useState(!1),[z,M]=w.useState(null),[A,N]=w.useState({}),[U,T]=w.useState(new Set),[H,se]=w.useState(null),{notice:Q,showActionNotice:Z}=eC(),[me,de]=w.useState(null),[ie,xe]=w.useState(null),[Be,nt]=w.useState(!1),[Le,Ie]=w.useState(null),[ue,Re]=w.useState(null),[fe,Ee]=w.useState("preview"),[Y,pe]=w.useState(!1),{pins:Ae,orders:ke,togglePin:We,removePin:Ne,pinError:ge,reorderBlocked:st,retryPinPersist:Ze,clearPinError:De,viewFor:He,updateView:qe,canMoveRoster:wt,moveRoster:W,stepRoster:ee}=xv(),J=le=>i[Cs(le)]||{},{groupsFor:be,moveNode:ye,stepNode:ot,nodeKey:oe}=kv(),$e=be(v);w.useEffect(()=>{tC({sessions:_||[],cells:ne,nodeGroups:v,localNodeId:V})},[_,ne,v,V]),w.useEffect(()=>{const le=new Map;for(const re of ne)le.set(Ta(re.cell),!!re.boot);for(const re of v){const Te=re.route||[re.name];for(const Ge of re.cells||[])le.set(Ta(Ge.cell,Te),!!Ge.boot)}N(re=>{let Te=!1;const Ge={...re};for(const[mt,q]of Object.entries(re))le.has(mt)&&le.get(mt)===q&&(delete Ge[mt],Te=!0);return Te?Ge:re})},[ne,v]);function ut(){x5([],e)}w.useEffect(()=>{const re=kd(e,[],Te=>{if(!Te)return;const Ge=Te.sessionsError?null:Te.sessionsJson;Ge&&!Ge.error?(L(null),b(Ge.sessions||[]),R(!0)):Ge?(L(Ge.error),b([]),R(!1)):(L(String(Te.sessionsError)),b([]),R(!1));const mt=yv({fs:Te.fs,error:Te.fleetError});mt.kind==="data"?(Ka("local",mt.cells),K(mt.cells),P(mt.capabilities),j(!1),M(null)):mt.kind==="stale"?(K(q=>q.length?q:_v("local")),j(!0),M(null)):(K([]),Ka("local",[]),P([]),j(!1),M(mt.reason||""))});return qn("/api/config",e).then(Te=>Te.json()).then(Te=>{F(Te.version||""),X({bind:Te.bind||"127.0.0.1",port:Te.port||""}),G(Ya.test(String(Te.instanceId||""))?Te.instanceId:"")}).catch(()=>{}),re},[e]);async function kt(){if(!$.port)return;const le=`http://${$.bind}:${$.port}/#token=${e}`;try{await navigator.clipboard.writeText(le)}catch{}}function St(le,re,Te){const Ge=Ta(le,re);N(mt=>({...mt,[Ge]:!!Te}))}function Lt(le,re=[]){const Te=Ta(le.cell,re);return Object.prototype.hasOwnProperty.call(A,Te)?A[Te]:!!le.boot}async function _t(le,re,Te=[],Ge){const mt=Ta(re.cell,Te),q=typeof Ge=="boolean"?Ge:!Lt(re,Te);St(re.cell,Te,q),T(ae=>new Set(ae).add(mt));try{await E1(e,{cell:re.cell,enabled:q},Te),Te.length||K(ae=>ae.map(je=>je.cell===re.cell?{...je,boot:q}:je))}catch(ae){N(je=>{const Xe={...je};return delete Xe[mt],Xe}),L(String((ae==null?void 0:ae.message)||ae))}finally{T(ae=>{const je=new Set(ae);return je.delete(mt),je})}}const pt=(le,re,Te)=>({onToggleLive:async()=>{const Ge=oo({item:le,cellName:re.cell,route:Te,pins:Ae,hostByRoute:i});nt(!0);const mt=await eh({action:Ge.isLive?"remove":"use",cellId:re.cell,route:Te,token:e});nt(!1),Ie({messageKey:mt.messageKey,ok:mt.ok,cell:mt.hostCell||re.cell})},onTogglePin:()=>Cv({view:lh({item:le,pins:Ae,hostByRoute:i,route:Te}),itemKey:le.key,togglePin:We,removePin:Ne}),onToggleBoot:Ge=>_t(null,re,Te,Ge),onWatchLive:()=>{Ee("stream"),Re(le.key)}});async function Ut(le){if(!H)return;let re=null;try{re=await jv({token:e,powerCell:H,payload:le,onNotice:Z})}catch(Te){throw Z(String(Te&&Te.message||Te)),Te}if(!re){const{cell:Te}=H,Ge=Array.isArray(H.route)?H.route:[];le.action==="up"?St(Te,Ge,!!le.boot):le.boot&&St(Te,Ge,!1)}ut()}const Gt=w.useMemo(()=>{if(!H)return null;const le=(Array.isArray(H.route)?H.route:[]).join("/"),Te=[...ne,...v.flatMap(Ge=>(Ge.cells||[]).map(mt=>({...mt,route:Ge.route||[Ge.name]})))].find(Ge=>Ge.cell===H.cell&&(Array.isArray(Ge.route)?Ge.route.join("/"):"")===le);return Te?{...H,active:!!Te.active}:H},[H,ne,v]);async function Ot(le,re=[]){try{await Yg(e,le,re)}catch{return}ut()}async function ln(le,re,Te=[]){try{await L1(e,le,re,Te)}catch{return}ut()}async function In(le){if(!(!(le!=null&&le.direct)||me)){de(le.name);try{await Jg(e,le.name,le.tunnelStatus==="up"?"down":"up")}catch{}de(null)}}async function qt(le){if(!(le!=null&&le.direct))return;const re=window.prompt(p("rename-node-prompt"),le.label||le.name);if(re===null)return;const Te=String(re).trim();if(!Ga(Te)){window.alert(p("rename-node-invalid"));return}try{await P1(e,le.name,Te)}catch(Ge){window.alert(String((Ge==null?void 0:Ge.message)||Ge))}}const wn=w.useMemo(()=>new Map((_||[]).map(le=>[le.name,le])),[_]),en=w.useMemo(()=>new Set(ne.map(le=>le.tmuxSession)),[ne]),bn=w.useMemo(()=>(_||[]).filter(le=>!en.has(le.name)),[_,en]),Ft=w.useMemo(()=>Lv(ne,bn,wn,void 0,{autorevole:C,fleetStale:O}),[ne,bn,wn,C,O]),Xt=w.useMemo(()=>{const le=new Map;for(const re of Ft)re.type==="cell"&&le.set(re.key,{item:re,route:[],nodeLabel:"",sessions:_||[],cells:ne});for(const re of $e){const Te=Array.isArray(re.route)?re.route:[];if(!Te.length||re.kind==="vl")continue;const{rawItems:Ge}=mc(re);for(const mt of Ge)mt.type==="cell"&&le.set(mt.key,{item:mt,route:Te,nodeLabel:re.label||re.name||"",sessions:re.sessions||[],cells:re.cells||[]})}return le},[Ft,$e,_,ne]),Jt=w.useMemo(()=>{if(!ue)return null;const le=Xt.get(ue);if(!le)return null;const re=le.item.value,Te=(le.sessions||[]).find(Ge=>Ge.name===re.tmuxSession)||{};return{row:{key:le.item.key,cellName:re.cell,subtitle:le.item.subtitle||"",nodeLabel:le.nodeLabel,node:le.route.length?le.route.join("/"):"",session:re.tmuxSession,route:le.route,panelUrl:re.panelUrl||"",telemetry:Te.telemetry||null,preview:Te.preview||re.preview||"",activity:Te.activity||re.activity||0},cells:le.cells||[]}},[ue,Xt]),Qt=He("local"),ls=w.useMemo(()=>co(Ft,Ae,Qt.filter,Ii(ke,"local")).filter(le=>S0(le,S)),[Ft,Ae,Qt.filter,S,ke]),cs=$e.reduce((le,re)=>le+(re.cells||[]).length+(re.unmanaged||[]).filter(Te=>!Te.technical).length,0),mn=co(Ft,Ae,"all",Ii(ke,"local")).length+cs,gn=Ft.filter(le=>le.live).length+$e.reduce((le,re)=>le+mc(re).rawItems.filter(Te=>Te.live).length,0),qs=(_||[]).filter(le=>le.attached).length+$e.reduce((le,re)=>le+(re.sessions||[]).filter(Te=>Te.attached).length,0),Vn=Math.min(qs,gn),bt=$.port?`${$.bind}:${$.port}`:$.bind;function us(le,re=null,Te=Ft){var xt,gt;const Ge=Array.isArray(re==null?void 0:re.route)?re.route:[],mt=Ge.join("/"),q=mt||"local",ae=Ge.length?re==null?void 0:re.instanceId:V,je=(Je,Rt)=>t({session:Je,...mt?{node:mt}:{},...Ya.test(String(ae||""))?{ownerId:ae}:{},...typeof Rt=="string"&&Rt?{cellName:Rt}:{}}),Xe=wt;if(le.type==="cell"){const Je=le.value,Rt=J(Ge),rt=Ed({hostCell:Rt.hostCell??null,threadStatus:Rt.threadStatus,pins:Ae,item:le}),ze=Ge.length?((re==null?void 0:re.sessions)||[]).find(Zt=>Zt.name===Je.tmuxSession):wn.get(Je.tmuxSession),Wt=fm(rt,Rt.hostLease??null),Sn=Je.degraded?p("cell-degraded"):le.subtitle||(Je.tmux?p("cell-idle"):p("cell-off")),Se=Wt?`${Sn} · ${p(Wt)}`:Sn,Me=Ge.length===0||((re==null?void 0:re.capabilities)||[]).includes(Je.active?"down":"up"),Ve=Ge.length===0?D.includes("boot"):((re==null?void 0:re.capabilities)||[]).includes("boot"),ct=Lt(Je,Ge),At=oo({item:le,cellName:Je.cell,route:Ge,pins:Ae,hostByRoute:i}),Ks=!!ie&&ie.itemKey===le.key,Vs=`${p("cell-actions-open")}: ${Je.cell}`;return l.jsxs("div",{className:"nc-mcard","data-roster-key":le.key,"data-position":q,children:[Y&&l.jsx(Gi,{position:q,itemKey:le.key,label:Je.cell,canMove:Xe,onMove:(Zt,tn)=>W(q,Zt,tn,Te),onStep:Zt=>ee(q,le.key,Zt,Te)}),l.jsxs("button",{className:"nc-mcard-main",onClick:()=>Je.tmux&&je(Je.tmuxSession,Je.cell),title:Se,"aria-label":`${Je.cell}, ${Se}`,children:[l.jsx("span",{className:`dot ${Je.degraded?"warn":Je.tmux?`on${le.working?" working":""}`:""}`}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsxs("span",{className:"nc-mcard-nome",children:[l.jsx("b",{children:Je.cell}),At.isLive&&l.jsx("span",{className:"nc-m-live",children:"LIVE"})]}),l.jsx("small",{title:le.subtitle,children:le.subtitle})]})]}),le.activity?l.jsx("span",{className:"nc-rel",children:ao(le.activity)}):null,le.fresh&&((xt=ze==null?void 0:ze.outbox)==null?void 0:xt.count)>0&&l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:ze.outbox.count}),l.jsx("button",{type:"button",className:`nc-act cellmenu${Ks?" on":""}`,title:Vs,"aria-label":Vs,"aria-haspopup":"menu","aria-expanded":Ks?"true":"false",onClick:()=>xe({itemKey:le.key,item:le,cell:Je,route:Ge,canBoot:Ve}),children:"⋯"}),Me&&l.jsx("button",{className:`nc-act power${Je.tmux?" on":""}${Je.degraded?" warn":""}`,onClick:()=>se(Ge.length?{...Je,boot:ct,route:Ge,availableEngines:(re==null?void 0:re.engines)||[]}:{...Je,boot:ct}),title:Je.active?p("power-off"):p("power-on"),"aria-label":`${Je.active?p("power-off"):p("power-on")} ${Je.cell}`,children:l.jsx(Pt,{name:"power",size:16})})]},le.key)}const Pe=le.value;return l.jsxs("div",{className:"nc-mcard","data-roster-key":le.key,"data-position":q,children:[l.jsx(Gi,{position:q,itemKey:le.key,label:Pe.name,canMove:Xe,onMove:(Je,Rt)=>W(q,Je,Rt,Te),onStep:Je=>ee(q,le.key,Je,Te)}),l.jsxs("button",{className:"nc-mcard-main",onClick:()=>je(Pe.name),children:[l.jsx("span",{className:Pe.attached?"dot on":"dot"}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsx("b",{children:Pe.name}),l.jsx("small",{children:Pe.preview?Pe.preview:Pe.cmd?Pe.cmd:p("windows").replace("{n}",String(Pe.windows||0))})]})]}),le.activity?l.jsx("span",{className:"nc-rel",children:ao(le.activity)}):null,le.fresh&&((gt=Pe.outbox)==null?void 0:gt.count)>0&&l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:Pe.outbox.count}),l.jsx("button",{className:`nc-act pin${Ae.includes(le.key)?" on":""}`,"aria-label":`${p("pin")} ${Pe.name}`,title:p("pin"),onClick:()=>We(le.key),children:Ae.includes(le.key)?"★":"☆"}),l.jsx("button",{className:`nc-act technical${Pe.technical?" on":""}`,title:Pe.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${Pe.technical?p("mark-normal"):p("mark-technical")} ${Pe.name}`,onClick:()=>ln(Pe.name,!Pe.technical,Ge),children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),"aria-label":`${p("terminate")} ${Pe.name}`,onClick:()=>{window.confirm(p("terminate-confirm").replace("{name}",Pe.name))&&Ot(Pe.name,Ge)},children:"⋯"})]},le.key)}return l.jsxs("div",{className:"nc-home",children:[l.jsxs("header",{className:"nc-home-head",children:[l.jsxs("div",{className:"nc-wordmark",children:["NexusCrew",l.jsx("span",{className:"nc-cursor"})]}),l.jsxs("div",{className:"nc-home-sub",children:[p("fleet-tmux")," · ",gn," ",p("sessions"),Vn>0&&` · ${Vn} attached`]}),l.jsxs("span",{className:"nc-head-actions",children:[l.jsx("button",{className:`nc-refresh${Y?" on":""}`,onClick:()=>pe(le=>!le),"aria-pressed":Y,title:p("reorder-help"),"aria-label":p("reorder"),children:"↕"}),l.jsx("button",{className:"nc-refresh",onClick:()=>n("nodes",!1),title:p("settings"),children:l.jsx(Pt,{name:"gear",size:18})}),l.jsx("button",{className:"nc-refresh",onClick:ut,title:p("refresh"),children:l.jsx(Pt,{name:"refresh",size:18})})]})]}),l.jsxs("main",{className:"nc-home-scroll",children:[l.jsx(QP,{view:Va({liveHost:i[Cs([])],cells:ne}),notice:Le}),l.jsx(Tk,{pinError:ge,onRetry:Ze,onDismiss:De}),mn>8&&l.jsx("input",{className:"nc-filter",type:"search",placeholder:p("filter-placeholder"),"aria-label":p("filter-placeholder"),value:S,onChange:le=>I(le.target.value)}),x&&l.jsx("div",{className:"nc-err",children:x}),Q&&l.jsx("div",{className:"nc-notice",role:"status",children:Q}),O&&l.jsx("div",{className:"nc-set-hint nc-fleet-stale",role:"status",children:p("fleet-stale")}),st&&l.jsxs("div",{className:"nc-set-hint nc-reorder-blocked",role:"status",children:[p("reorder-blocked")," (",st.reason,")"]}),z!==null&&l.jsxs("div",{className:"nc-set-hint nc-fleet-off",role:"status",children:[p("fleet-off"),z?` (${z})`:""]}),l.jsxs("section",{className:"nc-group","data-position":"local",children:[l.jsx(xp,{label:p("position-local"),count:ls.length,state:Qt,dotClass:"on",onToggle:()=>qe("local",{open:!Qt.open}),onFilter:le=>qe("local",{filter:le})}),Qt.open&&ls.map(le=>us(le,null,Ft)),Qt.open&&_===null&&l.jsx("div",{className:"nc-empty",children:p("loading-fleet")}),Qt.open&&_!==null&&ls.length===0&&!x&&l.jsx("div",{className:"nc-empty",children:S?p("no-match").replace("{q}",S):p("no-sessions-short")})]}),$e.map(le=>{const re=Bk(le.health,{passive:"warn"}),Te=le.fleetState==="stale"?p("fleet-stale"):le.fleetState==="disabled"?p("fleet-off"):"",Ge=le.fleetState==="stale"?"warn":re||(le.status==="up"?"on":le.status==="passive"?"":"warn"),mt=[le.health?Id(le.health):Qi(le),Te].filter(Boolean).join(" · "),ae=(le.route&&le.route.length?le.route:[le.name]).join("/"),je=He(ae);if(le.kind==="vl")return l.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":ae,"data-node-order-key":oe(le),children:[l.jsx(xp,{label:le.label||le.name,count:le.sessions.length,state:je,dotClass:Ge,dotTitle:mt,detail:Qi(le),onToggle:()=>qe(ae,{open:!je.open}),onFilter:Je=>qe(ae,{filter:Je})}),le.status==="up"&&je.open&&le.sessions.map(Je=>l.jsx("div",{className:"nc-mcard nc-vl-session-row",children:l.jsxs("button",{className:"nc-mcard-main",onClick:()=>s&&s(le.peer),"aria-label":`${le.label||le.name}: ${Je.name}`,children:[l.jsx("span",{className:"dot on"}),l.jsxs("span",{className:"nc-mcard-text",children:[l.jsx("b",{children:Je.name}),l.jsx("small",{children:p("vl-events-title")})]})]})},Je.key)),le.status==="up"&&je.open&&le.sessions.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]},`nodo-vl-${ae}-${le.name}`);const{rawItems:Xe}=mc(le),Pe=co(Xe,Ae,je.filter,Ii(ke,ae)).filter(Je=>S0(Je,S)),xt=le.direct&&le.health&&le.health.managed!==!1?l.jsx("button",{type:"button",className:`nc-act power${le.tunnelStatus==="up"?" on":""}`,disabled:me===le.name,title:le.tunnelStatus==="up"?p("power-off"):p("power-on"),"aria-label":`${le.tunnelStatus==="up"?p("power-off"):p("power-on")} ${le.label||le.name}`,onClick:()=>In(le),children:l.jsx(Pt,{name:"power",size:15})}):null,gt=l.jsxs("span",{className:"nc-node-actions",children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:oe(le),label:le.label||le.name,onMove:(Je,Rt)=>ye(Je,Rt,v),onStep:Je=>ot(oe(le),Je,v)}),le.direct&&l.jsx("button",{type:"button",className:"nc-node-rename",title:p("rename-node"),"aria-label":`${p("rename-node")} ${le.label||le.name}`,onClick:()=>qt(le),children:"✎"}),xt]});return l.jsxs("section",{className:"nc-group nc-node-order-wrap","data-position":ae,"data-node-order-key":oe(le),children:[l.jsx(xp,{label:le.label||le.name,count:Pe.length,state:je,dotClass:Ge,dotTitle:mt,detail:le.status==="up"?[Qi(le),Te].filter(Boolean).join(" · "):le.health&&Id(le.health)||Qi(le),onToggle:()=>qe(ae,{open:!je.open}),onFilter:Je=>qe(ae,{filter:Je}),onRename:le.direct?()=>qt(le):null,action:gt}),le.status==="up"&&je.open&&Pe.map(Je=>us(Je,le,Xe)),le.status==="up"&&je.open&&Pe.length===0&&l.jsx("div",{className:"nc-empty",children:S?p("no-match").replace("{q}",S):p("no-sessions-short")})]},`nodo-${ae}`)}),l.jsxs("footer",{className:"nc-home-foot",onClick:kt,title:p("copy-url"),children:[l.jsxs("span",{className:"nc-home-meta",children:[E&&l.jsxs("span",{className:"nc-home-version",children:["v",E]}),l.jsxs("span",{className:"nc-home-endpoint",children:[bt," · ",p("ssh-only")]})]}),l.jsx("span",{className:"nc-lang",onClick:le=>le.stopPropagation(),children:$1.map((le,re)=>l.jsxs("span",{children:[re>0&&" · ",l.jsx("button",{className:`nc-lang-btn${f===le?" on":""}`,onClick:()=>g(le),title:le,children:le.toUpperCase()})]},le))})]})]}),Gt&&l.jsx(Pd,{cell:Gt,token:e,route:Array.isArray(Gt.route)?Gt.route:[],onConfirm:Ut,onClose:()=>se(null)}),Jt&&l.jsx(wk,{row:Jt.row,token:e,initialSource:fe,panelPort:kc(Jt.row.route||[],h,u),liveHost:Va({liveHost:i[Cs(Jt.row.route||[])],cells:Jt.cells}),onClose:()=>{Re(null),Ee("preview")}}),ie&&(()=>{const{item:le,cell:re,route:Te=[],canBoot:Ge}=ie,mt=oo({item:le,cellName:re.cell,route:Te,pins:Ae,hostByRoute:i}),q=Ev({...mt,canBoot:Ge,boot:Lt(re,Te),alive:!!re.tmux,handlers:pt(le,re,Te)});return l.jsx(Nv,{cellName:re.cell,items:q,busy:Be||U.has(Ta(re.cell,Te)),onClose:()=>xe(null)})})()]})}function QP({view:t,notice:e}){const n=!!(t&&t.cell),s=n?p("live-host-indicator").replace("{cell}",t.cell).replace("{mode}",p(t.mode?`live-host-mode-${t.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${t.state||"none"}`)):p("live-host-indicator-none");return l.jsxs("div",{className:"nc-m-live-strip","data-state":t&&t.state?t.state:"none",title:e?`${s} · ${p(e.messageKey)}`:s,children:[l.jsx("span",{className:`nc-m-live-dot ${Rv(t||{})}`,"aria-hidden":"true"}),l.jsx("span",{className:"nc-m-live-testo",children:n?t.cell:s}),e&&l.jsx("span",{className:`nc-m-live-notice${e.ok?" ok":" ko"}`,role:"status",children:p(e.messageKey).replace("{cell}",e.cell||t.cell||"")})]})}function xp({label:t,count:e,state:n,dotClass:s="",dotTitle:i="",detail:a="",onToggle:c,onFilter:u,onRename:h=null,action:f=null}){return l.jsxs("div",{className:"nc-mobile-position-head",onContextMenu:h?g=>{g.preventDefault(),h()}:void 0,children:[l.jsxs("button",{type:"button",className:"nc-mobile-position-toggle",onClick:c,"aria-expanded":n.open,"aria-label":`${t} · ${p("node-sessions").replace("{n}",String(e))}`,children:[l.jsx("span",{className:"nc-mobile-chevron","aria-hidden":"true",children:n.open?"⌄":"›"}),l.jsx("span",{className:`dot ${s}`,title:i}),l.jsxs("span",{className:"nc-mobile-position-copy",children:[l.jsx("b",{children:t}),l.jsx("small",{children:a||p("node-sessions").replace("{n}",String(e))})]})]}),l.jsxs("select",{className:"nc-mobile-position-filter",value:n.filter,"aria-label":`${t} · ${p("filter-placeholder")}`,title:p(`view-${n.filter}`),onChange:g=>u(g.target.value),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]}),f]})}const F0="",an="\x1B",ZP=[{label:"↑",seq:an+"[A"},{label:"↓",seq:an+"[B"},{label:"PGUP",seq:an+"[5~"},{label:"PGDN",seq:an+"[6~"}],eI=new Set([an+"[A",an+"[B",an+"[C",an+"[D",an+"[5~",an+"[6~"]),tI=350,nI=55;function sI({send:t,action:e,ctrlArmed:n=!1,onCtrl:s,altArmed:i=!1,onAlt:a,onAltConsume:c,onKeyboard:u,selectionMode:h=!1,onSelectionMode:f,onCellSwitcher:g,cellSwitcherOpen:v=!1,keepKeyboardClosed:_=!0,showEnter:b=!0,keybarLayout:x="full",onKeyboardKeep:L}){const[C,R]=w.useState(!1),[S,I]=w.useState(!1),[E,F]=w.useState(!1),$=x==="compact"&&!E,X=w.useRef({delay:null,interval:null}),V=w.useRef(()=>{}),G=()=>{const T=X.current;T.delay!==null&&clearTimeout(T.delay),T.interval!==null&&clearInterval(T.interval),T.delay=null,T.interval=null};V.current=G,w.useEffect(()=>{const T=()=>{document.visibilityState==="hidden"&&V.current()},H=()=>V.current();return window.addEventListener("blur",H),document.addEventListener("visibilitychange",T),()=>{window.removeEventListener("blur",H),document.removeEventListener("visibilitychange",T),V.current()}},[]),w.useEffect(()=>{x!=="compact"&&F(!1)},[x]);const ne=T=>{i?(t(an+T),c&&c()):t(T)},K=(T,{keepOpen:H}={})=>{_&&!H&&lg(),H&&L&&L(),T()},D=(T,H={})=>({onPointerDown:se=>{se.preventDefault(),K(T,H)},onClick:se=>{se.detail===0&&K(T,H)}}),P=(T,H={})=>({onPointerDown:se=>{se.preventDefault(),G(),K(T,H),!i&&(X.current.delay=setTimeout(()=>{X.current.delay=null,T(),X.current.interval=setInterval(T,nI)},tI))},onPointerUp:G,onPointerLeave:G,onPointerCancel:G,onLostPointerCapture:G,onTouchCancel:G,onClick:se=>{se.detail===0&&K(T,H)}}),O=(T,H,se)=>l.jsx("button",{type:"button",...eI.has(H)&&!se?P(()=>ne(H)):D(()=>{ne(H),se&&se()}),children:T},T),j=(T,H)=>l.jsx("button",{type:"button",...D(()=>{e(H),I(!1)}),children:T},T),z=g?l.jsx("button",{type:"button","aria-label":p("fleet-cells"),title:p("fleet-cells"),"aria-expanded":v,...D(g),children:"◫"},"cells"):l.jsx("button",{type:"button",...D(()=>{u&&u()}),children:"⌨"},"kbd"),M=b&&l.jsx("button",{type:"button",className:"nc-enter-key","aria-label":"ENTER",title:"ENTER",...D(()=>ne("\r")),children:l.jsx(Pt,{name:"enter",size:24})}),A=S&&l.jsxs("div",{className:"nc-keymenu",children:[j("←WIN","prev-window"),j("WIN→","next-window"),j("⬅PANE","pane-left"),j("PANE➡","pane-right"),O("SCROLL",F0+"[",()=>{R(!0),I(!1)}),l.jsx("button",{type:"button",className:h?"armed":"",...D(()=>{f==null||f(!h),I(!1)}),children:"SELECT"}),O("⌃C","",()=>I(!1)),O("DETACH",F0+"d",()=>I(!1))]});if(C)return l.jsxs("div",{className:"nc-keybar copy",children:[l.jsx("span",{className:"tag",children:"copy-mode"}),ZP.map(T=>O(T.label,T.seq)),O("ESCI (q)","q",()=>R(!1))]});if($)return l.jsxs("div",{className:"nc-keybar termux",children:[A,l.jsxs("div",{className:`nc-keygrid compact${b?"":" no-enter"}`,children:[l.jsx("div",{className:"nc-keyrows",children:l.jsxs("div",{className:"row",children:[l.jsx("button",{type:"button","aria-label":p("keybar-expand"),title:p("expand"),...D(()=>F(!0)),children:l.jsx(Pt,{name:"chevronUp",size:20})},"expand"),z,l.jsx("button",{type:"button",className:S?"armed":"",...D(()=>I(T=>!T)),children:"☰"},"menu"),O("↑",an+"[A"),O("↓",an+"[B"),O("←",an+"[D"),O("→",an+"[C"),O("PGUP",an+"[5~"),O("PGDN",an+"[6~")]})}),M]})]});const N=x==="compact"&&E,U=N&&l.jsx("button",{type:"button",className:"nc-retract-key","aria-label":p("keybar-retract"),title:p("retract"),...D(()=>F(!1)),children:l.jsx(Pt,{name:"chevronDown",size:20})});return l.jsxs("div",{className:`nc-keybar termux${N?" expanded":""}`,children:[A,l.jsxs("div",{className:`nc-keygrid${b?"":" no-enter"}${N?" expanded":""}`,children:[U,l.jsxs("div",{className:"nc-keyrows",children:[l.jsxs("div",{className:"row",children:[O("ESC",an),l.jsx("button",{type:"button",className:S?"armed":"",...D(()=>I(T=>!T)),children:"☰"},"menu"),O("/","/"),O("—","-"),O("HOME",an+"[H"),O("↑",an+"[A"),O("END",an+"[F"),O("PGUP",an+"[5~")]}),l.jsxs("div",{className:"row",children:[O("⇥"," "),z,l.jsx("button",{type:"button",className:n?"armed":"",...D(()=>{s&&s()},{keepOpen:!0}),children:"CTRL"},"ctrl"),l.jsx("button",{type:"button",className:i?"armed":"",...D(()=>{a&&a()},{keepOpen:!0}),children:"ALT"},"alt"),O("←",an+"[D"),O("↓",an+"[B"),O("→",an+"[C"),O("PGDN",an+"[6~")]})]}),M]})]})}const iI=t=>t>1048576?`${(t/1048576).toFixed(1)}M`:t>1024?`${(t/1024).toFixed(0)}K`:`${t}B`;function Eg({session:t,node:e,token:n,filesEvent:s,onClose:i}){zn();const a=e?`/api/route/${String(e).split("/").map(encodeURIComponent).join("/")}/_`:"/api",c=e?`${e}:${t}`:t,[u,h]=w.useState("outbox"),[f,g]=w.useState({inbox:[],outbox:[]}),[v,_]=w.useState("");async function b(){try{const R=await(await qn(`${a}/files?session=${encodeURIComponent(t)}`,n)).json();if(R.error){_(R.error);return}g(R);const S=R.outbox[0]?R.outbox[0].mtime:0;localStorage.setItem(x1(c),String(S))}catch(C){_(String(C))}}w.useEffect(()=>{b()},[t,e]),w.useEffect(()=>{s&&s.session===t&&b()},[s]);async function x(C){const R=await qn(`${a}/files/download?session=${encodeURIComponent(t)}&box=${u}&name=${encodeURIComponent(C)}`,n);if(!R.ok){const F=await R.json().catch(()=>({}));_(F.error?`errore: ${F.error}`:"errore download");return}const S=await R.blob(),I=URL.createObjectURL(S),E=document.createElement("a");E.href=I,E.download=C,E.click(),URL.revokeObjectURL(I)}async function L(C){const R=await qn(`${a}/files?session=${encodeURIComponent(t)}&box=${u}&name=${encodeURIComponent(C)}`,n,{method:"DELETE"});if(!R.ok){const S=await R.json().catch(()=>({}));_(S.error?`errore: ${S.error}`:"errore delete");return}b()}return l.jsxs("div",{className:"nc-files",children:[l.jsxs("header",{children:[l.jsx("b",{children:e?`${e}:${t}`:t}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:i,title:p("close"),"aria-label":p("close"),children:l.jsx(Pt,{name:"x",size:16})})]}),l.jsxs("nav",{children:[l.jsx("button",{className:u==="outbox"?"on":"",onClick:()=>h("outbox"),children:"outbox"}),l.jsx("button",{className:u==="inbox"?"on":"",onClick:()=>h("inbox"),children:"inbox"})]}),v&&l.jsx("div",{className:"nc-busy",children:v}),l.jsxs("ul",{children:[f[u].map(C=>l.jsxs("li",{children:[l.jsx("span",{className:"name",children:C.name}),l.jsx("small",{children:iI(C.size)}),l.jsx("button",{type:"button",onClick:()=>x(C.name),title:p("files-download"),"aria-label":`${p("files-download")} ${C.name}`,children:l.jsx(Pt,{name:"download",size:18})}),l.jsx("button",{onClick:()=>L(C.name),title:p("delete"),"aria-label":`${p("delete")} ${C.name}`,children:l.jsx(Pt,{name:"trash",size:18})})]},C.name)),f[u].length===0&&l.jsx("li",{className:"empty",children:p("empty-files")})]})]})}const dh="nc_composer_v1",Ng="nc-composer-reset",rI=50,nC=256*1024,sC=512*1024,oI=768*1024,H0=2*1024*1024,iC=720*60*60*1e3,Rg=1;function rC(t){const e=Number(t);return Number.isFinite(e)&&e>0?e:0}function Mv(t){if(t!==void 0)return t;try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Bd(){return{version:Rg,cells:{}}}function oC(t){const e=[];for(const s of Array.isArray(t)?t:[]){const i=typeof s=="string"?s:s&&s.text,a=rC(typeof s=="string"?0:s&&s.at);if(!(typeof i!="string"||!i||i.length>nC)&&!(e.length&&e[e.length-1].text===i)&&(e.push({text:i,at:a}),e.length>=rI))break}let n=0;return e.filter(s=>n+s.text.length>oI?!1:(n+=s.text.length,!0))}function $d(t){if(!t||typeof t!="object")return null;const e=typeof t.draft=="string"&&t.draft.length<=sC?t.draft:"",n=oC(t.history),s=rC(t.updatedAt),i=t.expanded===!0;return!e&&!n.length&&!i?null:{draft:e,history:n,expanded:i,updatedAt:s}}function aI(t){let e;try{e=typeof t=="string"?JSON.parse(t):t}catch{return Bd()}if(!e||typeof e!="object"||e.version!==Rg||!e.cells||typeof e.cells!="object")return Bd();const n=Object.create(null);for(const[s,i]of Object.entries(e.cells)){if(!s||typeof s!="string"||s.length>512||s==="__proto__"||s==="constructor"||s==="prototype")continue;const a=$d(i);a&&(n[s]=a)}return{version:Rg,cells:n}}function aC(t){const e=Mv(t);if(!e)return Bd();try{return aI(e.getItem(dh))}catch{return Bd()}}function U0(t){try{return JSON.stringify(t).length}catch{return 1/0}}function lI(t,e,n){for(const[s,i]of Object.entries(t.cells))s!==n&&i.updatedAt>0&&e-i.updatedAt>iC&&delete t.cells[s]}function lC(t,e){return Object.entries(t.cells).filter(([n])=>n!==e).sort((n,s)=>n[1].updatedAt-s[1].updatedAt).map(([n])=>n)}function cI(t,e){for(;U0(t)>H0;){const n=Object.entries(t.cells).filter(([,s])=>s.history.length).sort((s,i)=>s[1].updatedAt-i[1].updatedAt);if(!n.length)break;n[0][1].history.pop()}for(const n of lC(t,e)){if(U0(t)<=H0)break;delete t.cells[n]}}function cC(t,e,n){const s=Mv(t);if(!s)return!1;cI(e,n);const i=()=>(s.setItem(dh,JSON.stringify(e)),!0);try{return i()}catch{for(const c of lC(e,n)){delete e.cells[c];try{return i()}catch{}}return!1}}function Fc(t,e,n,s){const i=aC(e);lI(i,n,t);const a=$d(i.cells[t])||{draft:"",history:[],expanded:!1,updatedAt:0},c=s({...a,history:[...a.history]}),u=$d(c);return u?i.cells[t]={...u,updatedAt:n}:delete i.cells[t],{ok:cC(e,i,t),cell:i.cells[t]||{draft:"",history:[],expanded:!1,updatedAt:n}}}function uI({ownerId:t,node:e,session:n}){const s=String(n||"");if(!s)return"";const i=Ya.test(String(t||""))?String(t):e?`route:${String(e)}`:"local";return`${encodeURIComponent(i)}:${encodeURIComponent(s)}`}function Yl(t,e,n=Date.now()){if(!t)return{draft:"",history:[],expanded:!1,updatedAt:0};const s=aC(e),i=$d(s.cells[t]);return!i||i.updatedAt>0&&n-i.updatedAt>iC?(s.cells[t]&&(delete s.cells[t],cC(e,s,"")),{draft:"",history:[],expanded:!1,updatedAt:0}):{...i,history:[...i.history]}}function W0(t,e,n,s=Date.now()){const i=String(e||"");return!t||i.length>sC?!1:Fc(t,n,s,a=>({...a,draft:i})).ok}function q0(t,e,n=Date.now()){return t?Fc(t,e,n,s=>({...s,draft:""})).ok:!1}function dI(t,e,n,s=Date.now()){return t?Fc(t,n,s,i=>({...i,expanded:!!e})).ok:!1}function hI(t,e,n,s=Date.now()){const i=String(e||"");return!t||!i||i.length>nC?!1:Fc(t,n,s,a=>{const c=a.history.filter(u=>u.text!==i);return c.unshift({text:i,at:s}),{...a,history:oC(c)}}).ok}function fI(t,e,n=Date.now()){return t?Fc(t,e,n,s=>({...s,history:[]})).ok:!1}function pI(t){const e=Mv(t);if(!e)return!1;try{return e.removeItem(dh),!0}catch{return!1}}const mI=300;function gI(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function vI({ownerId:t,node:e,session:n,storage:s=gI()}){const i=w.useMemo(()=>uI({ownerId:t,node:e,session:n}),[t,e,n]),a=w.useMemo(()=>Yl(i,s),[]),[c,u]=w.useState(a.draft),[h,f]=w.useState(a.expanded),[g,v]=w.useState(a.history),[_,b]=w.useState(-1),x=w.useRef(i),L=w.useRef(a.draft),C=w.useRef(null),R=w.useRef(a.updatedAt||0),S=w.useRef(a.draft),I=w.useCallback(()=>{C.current&&clearTimeout(C.current),C.current=null},[]),E=w.useCallback(()=>{I(),W0(x.current,L.current,s)},[I,s]),F=w.useCallback(()=>{I(),C.current=setTimeout(()=>{C.current=null,W0(x.current,L.current,s)},mI)},[I,s]),$=w.useCallback(O=>{const j=String(typeof O=="function"?O(L.current):O||"");L.current=j,R.current=Date.now(),S.current=j,b(-1),u(j),F()},[F]),X=w.useCallback((O,j)=>{I(),L.current=O,R.current=Date.now(),u(O),b(j),F()},[I,F]),V=w.useCallback(()=>{if(!g.length)return!1;const O=Math.min(_+1,g.length-1);return _<0&&(S.current=L.current),X(g[O].text,O),!0},[X,g,_]),G=w.useCallback(()=>{if(_<0)return!1;const O=_-1;return X(O<0?S.current:g[O].text,O),!0},[X,g,_]),ne=w.useCallback(O=>{S.current=L.current;const j=g.findIndex(z=>z.text===O);X(String(O||""),j)},[X,g]),K=w.useCallback(()=>{f(O=>{const j=!O;return dI(x.current,j,s),j})},[s]),D=w.useCallback((O,j,z)=>{if(!O)return;if(hI(O,z,s),!(x.current===O)){Yl(O,s).draft===j&&q0(O,s);return}v(Yl(O,s).history),S.current="",b(-1),L.current===j?(I(),L.current="",R.current=Date.now(),u(""),q0(O,s)):F()},[I,F,s]),P=w.useCallback(()=>{fI(x.current,s),v([]),b(-1),S.current=L.current},[s]);return w.useEffect(()=>{if(x.current===i)return;E(),x.current=i;const O=Yl(i,s);L.current=O.draft,R.current=O.updatedAt||0,S.current=O.draft,u(O.draft),f(O.expanded),v(O.history),b(-1)},[i,E,s]),w.useEffect(()=>{const O=()=>E(),j=()=>{document.visibilityState==="hidden"&&E()};return window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",j),()=>{window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",j),E()}},[E]),w.useEffect(()=>{const O=()=>{I(),L.current="",R.current=0,S.current="",u(""),f(!1),v([]),b(-1)},j=M=>{if(M.key!==dh)return;if(M.newValue==null){O();return}const A=Yl(x.current,s);A.updatedAt<R.current||(I(),L.current=A.draft,R.current=A.updatedAt,S.current=A.draft,u(A.draft),f(A.expanded),v(A.history),b(-1))},z=()=>O();return window.addEventListener("storage",j),window.addEventListener(Ng,z),()=>{window.removeEventListener("storage",j),window.removeEventListener(Ng,z)}},[I,s]),{cellKey:i,text:c,setText:$,expanded:h,toggleExpanded:K,history:g,historyCursor:_,recallPrevious:V,recallNext:G,selectHistory:ne,confirmSubmitted:D,clearHistory:P,flush:E}}function uC({submitText:t,token:e,session:n,node:s,ownerId:i,readonly:a=!1,keepKeyboardClosedOnVoice:c=!0}){zn();const u=s?`/api/route/${String(s).split("/").map(encodeURIComponent).join("/")}/_`:"/api",{cellKey:h,text:f,setText:g,expanded:v,toggleExpanded:_,history:b,historyCursor:x,recallPrevious:L,recallNext:C,selectHistory:R,confirmSubmitted:S,clearHistory:I,flush:E}=vI({ownerId:i,node:s,session:n}),[F,$]=w.useState(!1),[X,V]=w.useState(""),[G,ne]=w.useState(""),[K,D]=w.useState(!1),P=w.useRef(null),O=w.useRef(null),j=w.useRef(null),[z,M]=w.useState(!1),[A,N]=w.useState({left:0,bottom:0}),[U,T]=w.useState(!1),[H,se]=w.useState(!1),Q=w.useRef(null),Z=w.useRef(null),me=w.useRef(null),de=w.useRef(null),ie=w.useRef(null),xe=w.useRef(null),Be=w.useRef(null),nt=w.useRef(null),Le=w.useRef(!1),[Ie,ue]=w.useState(!1),[Re,fe]=w.useState({left:0,bottom:0,width:320}),Ee=w.useRef(`nc-attach-${Math.random().toString(36).slice(2,8)}`);w.useEffect(()=>{let ee=!1;if(s){D(!1);return}return qn(`${u}/voice/status`,e).then(J=>J.json()).then(J=>{ee||D(!!J.serverSttConfigured)}).catch(()=>{ee||D(!1)}),()=>{ee=!0}},[e,u]);const pe=!!(typeof window<"u"&&(window.SpeechRecognition||window.webkitSpeechRecognition)||K);async function Ae(){const ee=j.current&&typeof j.current.value=="string"?j.current.value:f;lg(),ee!==f&&g(ee);const J=ee,be=XM(J);if(!be||H)return;if(a){V(p("settings-readonly"));return}se(!0),V("");let ye=!1;try{ye=!!await t(be)}catch{ye=!1}ye?S(h,J,be):V(p("composer-send-failed")),se(!1)}function ke(){const ee=Q.current&&Q.current.getBoundingClientRect();ee&&N({left:Math.max(6,Math.min(ee.left,window.innerWidth-186)),bottom:window.innerHeight-ee.top+6}),M(!0)}function We(ee){M(!1),ee&&Q.current&&Q.current.focus()}function Ne(){const ee=me.current&&me.current.getBoundingClientRect();if(ee){const J=Math.max(220,Math.min(360,window.innerWidth-12));fe({left:Math.max(6,Math.min(ee.right-J,window.innerWidth-J-6)),bottom:window.innerHeight-ee.top+6,width:J})}ue(!0)}function ge(ee){ue(!1),ee&&me.current&&me.current.focus()}w.useEffect(()=>{if(!z)return;const ee=be=>{be.key==="Escape"&&We(!0)},J=be=>{const ye=Z.current&&Z.current.contains(be.target),ot=Q.current&&Q.current.contains(be.target);!ye&&!ot&&We(!1)};return document.addEventListener("keydown",ee),document.addEventListener("pointerdown",J),()=>{document.removeEventListener("keydown",ee),document.removeEventListener("pointerdown",J)}},[z]),w.useEffect(()=>{if(!Ie)return;const ee=be=>{be.key==="Escape"&&ge(!0)},J=be=>{const ye=de.current&&de.current.contains(be.target),ot=me.current&&me.current.contains(be.target);!ye&&!ot&&ge(!1)};return document.addEventListener("keydown",ee),document.addEventListener("pointerdown",J),()=>{document.removeEventListener("keydown",ee),document.removeEventListener("pointerdown",J)}},[Ie]);function st(ee){if(!(ee.isComposing||Le.current||ee.altKey||ee.ctrlKey||ee.metaKey)){if(ee.key==="ArrowUp"&&ee.currentTarget.selectionStart===0&&ee.currentTarget.selectionEnd===0){L()&&ee.preventDefault();return}ee.key==="ArrowDown"&&x>=0&&ee.currentTarget.selectionStart===f.length&&ee.currentTarget.selectionEnd===f.length&&C()&&ee.preventDefault()}}function Ze(ee){We(!1),ee.current&&ee.current.click()}async function De(ee){if(!ee.length||!n)return;T(!0),V("");const{paths:J,errors:be}=await ag({files:ee,token:e,session:n,node:s,paste:!1});be.length&&V(be.map(ye=>`${ye.name}: ${ye.message}`).join(" · ")),J.length&&g(ye=>ye+(ye&&!ye.endsWith(" ")?" ":"")+J.join(" ")),T(!1)}async function He(ee){var ye;if(!ee.length||!n)return;T(!0),V(""),ne("");const{paths:J,errors:be}=await ag({files:ee,token:e,session:n,node:s,paste:!1});if(be.length&&V(be.map(ot=>`${ot.name}: ${ot.message}`).join(" · ")),J.length){ne(p("attach-inbox-done").replace("{n}",String(J.length)));try{(ye=navigator.vibrate)==null||ye.call(navigator,10)}catch{}setTimeout(()=>ne(""),2500)}T(!1)}function qe(){P.current&&P.current.stop(),O.current&&O.current.stop(),$(!1)}async function wt(){V("");const ee=window.SpeechRecognition||window.webkitSpeechRecognition;if(ee){const J=new ee;J.lang="it-IT",J.continuous=!1,J.interimResults=!0;const be=f?`${f} `:"";J.onresult=ye=>{const ot=Array.from(ye.results).map(oe=>oe[0].transcript).join("");g(be+ot)},J.onend=()=>$(!1),J.onerror=ye=>{V(`voice: ${ye.error||"errore"}`),$(!1)},P.current=J,J.start(),$(!0);return}try{const J=await navigator.mediaDevices.getUserMedia({audio:!0}),be=new MediaRecorder(J),ye=[];be.ondataavailable=ot=>ye.push(ot.data),be.onstop=async()=>{J.getTracks().forEach(ot=>ot.stop()),$(!1),V("trascrivo…");try{const ot=new Blob(ye,{type:be.mimeType||"audio/webm"}),$e=await(await qn(`${u}/voice/transcribe`,e,{method:"POST",headers:{"content-type":"application/octet-stream"},body:ot})).json();$e.error?V($e.error):(V(""),g(ut=>ut+(ut?" ":"")+($e.text||"")))}catch(ot){V(String(ot))}},O.current={stop:()=>be.state!=="inactive"&&be.stop()},be.start(),$(!0)}catch{V("microfono non disponibile"),$(!1)}}function W(){c&&lg(),F?qe():wt()}return l.jsxs("div",{className:"nc-composer",children:[X&&l.jsx("div",{className:"nc-composer-err",children:X}),G&&l.jsx("div",{className:"nc-composer-info",children:G}),l.jsxs("div",{className:"nc-composer-row",children:[n&&l.jsx("button",{ref:Q,className:U?"attach busy":"attach",disabled:U,onClick:()=>z?We(!1):ke(),title:p(U?"attach-uploading":"attach"),"aria-label":p("attach"),"aria-haspopup":"menu","aria-expanded":z,"aria-controls":Ee.current,children:l.jsx(Pt,{name:"attach",size:22})}),z&&l.jsxs("div",{ref:Z,id:Ee.current,role:"menu",className:"nc-attach-menu",style:{left:A.left,bottom:A.bottom},children:[l.jsxs("button",{role:"menuitem",onClick:()=>Ze(ie),children:[l.jsx(Pt,{name:"file",size:18})," ",p("attach-file")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(xe),children:[l.jsx(Pt,{name:"camera",size:18})," ",p("attach-camera")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(Be),children:[l.jsx(Pt,{name:"image",size:18})," ",p("attach-gallery")]}),l.jsxs("button",{role:"menuitem",onClick:()=>Ze(nt),children:[l.jsx(Pt,{name:"folder",size:18})," ",p("attach-inbox")]})]}),l.jsx("button",{ref:me,type:"button",className:"history",onPointerDown:ee=>ee.preventDefault(),onClick:()=>Ie?ge(!1):Ne(),title:p("composer-history-tools"),"aria-label":p("composer-history-tools"),"aria-haspopup":"menu","aria-expanded":Ie,children:l.jsx(Pt,{name:"history",size:21})}),Ie&&l.jsxs("div",{ref:de,role:"menu",className:"nc-composer-history-menu",style:{left:Re.left,bottom:Re.bottom,width:Re.width},children:[l.jsxs("button",{role:"menuitem",className:"nc-composer-history-action",onPointerDown:ee=>ee.preventDefault(),onClick:()=>{_(),ge(!1)},children:[l.jsx(Pt,{name:v?"chevronDown":"chevronUp",size:18}),p(v?"composer-collapse":"composer-expand")]}),l.jsx("div",{className:"nc-composer-history-title",children:p("composer-history")}),b.length===0&&l.jsx("div",{className:"nc-composer-history-empty",children:p("composer-history-empty")}),b.map((ee,J)=>l.jsxs("button",{type:"button",role:"menuitem",className:"nc-composer-history-entry",onPointerDown:be=>be.preventDefault(),onClick:()=>{R(ee.text),ge(!1)},children:[l.jsx("span",{children:ee.text.replace(/\s+/g," ").slice(0,180)}),ee.at>0&&l.jsx("small",{children:new Date(ee.at).toLocaleString()})]},`${ee.at}:${J}`)),b.length>0&&l.jsx("button",{type:"button",role:"menuitem",className:"nc-composer-history-clear",onPointerDown:ee=>ee.preventDefault(),onClick:()=>{I(),ge(!1)},children:p("composer-history-clear")})]}),l.jsx("input",{ref:ie,type:"file",multiple:!0,hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:xe,type:"file",accept:"image/*",capture:"environment",hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:Be,type:"file",accept:"image/*,video/*",multiple:!0,hidden:!0,onChange:ee=>{De(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("input",{ref:nt,type:"file",multiple:!0,hidden:!0,onChange:ee=>{He(Array.from(ee.target.files||[])),ee.target.value=""}}),l.jsx("textarea",{ref:j,className:v?"expanded":"",rows:v?8:2,value:f,placeholder:p("composer-placeholder"),onChange:ee=>g(ee.target.value),onKeyDown:st,onCompositionStart:()=>{Le.current=!0},onCompositionEnd:()=>{Le.current=!1},onBlur:E}),pe&&l.jsx("button",{type:"button",className:F?"mic on":"mic",title:p("voice"),"aria-label":p("voice"),onPointerDown:ee=>{ee.preventDefault(),W()},onClick:ee=>{ee.detail===0&&W()},children:l.jsx(Pt,{name:"mic",size:22})}),l.jsx("button",{type:"button",className:"go",disabled:H,onPointerDown:ee=>ee.preventDefault(),onClick:Ae,title:p("send"),children:l.jsx(Pt,{name:"enter",size:22})})]})]})}const K0=460,_I=320;function yI({row:t,token:e,panelPort:n=0,anchorRect:s,liveHost:i=null,onLiveHostApplied:a,source:c,onSourceChange:u,onExpand:h,onClose:f,onMouseEnter:g,onMouseLeave:v}){w.useEffect(()=>{const x=L=>{L.key==="Escape"&&f()};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[f]);const _=s?Math.max(8,Math.min(s.right+10,window.innerWidth-K0-8)):void 0,b=s?Math.max(8,Math.min(s.top-6,window.innerHeight-_I-8)):void 0;return l.jsxs("div",{className:"nc-peekcloud",style:{left:_,top:b,width:K0},"data-testid":"peek-cloud",onMouseEnter:g,onMouseLeave:v,children:[l.jsxs("div",{className:"nc-peekcloud-testa",children:[l.jsx("b",{className:"nc-peekcloud-nome",children:t.cellName}),[t.nodeLabel,t.subtitle].filter(Boolean).length>0&&l.jsx("span",{className:"nc-peekcloud-sub",children:[t.nodeLabel,t.subtitle].filter(Boolean).join(" · ")}),l.jsx("button",{type:"button",className:"nc-peekcloud-espandi",title:p("cell-peek-expand"),"aria-label":`${p("cell-peek-expand")}: ${t.cellName}`,onClick:()=>h(c),children:"⤢"})]}),l.jsx(mv,{row:t,token:e,panelPort:n,liveHost:i,onLiveHostApplied:a,source:c,onSourceChange:u})]})}function kp(t){return String(t||"?").replace(/^[^a-zA-Z0-9]+/,"").charAt(0).toUpperCase()||"?"}const wI=180,bI=480,Gl=(t,e=[])=>`${e.length?e.join("/"):"local"}:${t}`;function SI({sessions:t=[],cells:e=[],activeSessions:n=[],nodeGroups:s=[],onPick:i,onAddTile:a,onPower:c,onBoot:u,onNodePower:h,onKill:f,onVisibility:g,onNew:v,onNodeRename:_,onSettings:b,onBootError:x,localNodeId:L,fleetCapabilities:C=[],fleetStale:R=!1,fleetOff:S=null,bootSettlement:I=null,localVerified:E=!0,hostByRoute:F={},onDesignateCell:$,onClearHostCell:X,onBootSettlementApplied:V,onOpenVlSession:G,token:ne="",onPeekOpen:K,overlayOpen:D=!1,width:P=240,collapsed:O=!1,onResize:j,onToggleCollapse:z}){const[M,A]=zn(),{pins:N,orders:U,togglePin:T,removePin:H,pinError:se,reorderBlocked:Q,retryPinPersist:Z,clearPinError:me,viewFor:de,updateView:ie,canMoveRoster:xe,moveRoster:Be,stepRoster:nt}=xv(),{groupsFor:Le,moveNode:Ie,stepNode:ue,nodeKey:Re}=kv(),fe=q=>F[Cs(q)]||{},Ee=new Set((e||[]).map(q=>q.tmuxSession)),Y=new Map((t||[]).map(q=>[q.name,q])),pe=(q,ae)=>oP(N,q,ae),Ae=aP,ke=[...e||[]].sort((q,ae)=>Ae(pe(q.tmuxSession,(Y.get(q.tmuxSession)||{}).activity),pe(ae.tmuxSession,(Y.get(ae.tmuxSession)||{}).activity))),We=(t||[]).filter(q=>!Ee.has(q.name)).sort((q,ae)=>Ae(pe(q.name,q.activity),pe(ae.name,ae.activity))||q.name.localeCompare(ae.name)),Ne=new Set(n||[]),[ge,st]=w.useState(null),[Ze,De]=w.useState("preview"),[He,qe]=w.useState(null),wt=w.useRef(null),W=w.useRef(null),ee=w.useRef(null);w.useEffect(()=>{ee.current=ge},[ge]),w.useEffect(()=>()=>{clearTimeout(wt.current),clearTimeout(W.current)},[]);const[J,be]=w.useState(null),[ye,ot]=w.useState(null),[oe,$e]=w.useState(!1),[ut,kt]=w.useState(null),St=(q,ae,je=[],Xe="",Pe=null)=>{const gt=(je.length===0?Y.get(ae.tmuxSession):(Pe||[]).find(Je=>Je&&Je.name===ae.tmuxSession))||{};return{key:q.key,cellName:ae.cell,subtitle:q.subtitle||"",nodeLabel:Xe,node:je.length?je.join("/"):"",session:ae.tmuxSession,route:je,panelUrl:ae.panelUrl||"",telemetry:gt.telemetry||null,preview:gt.preview||ae.preview||"",activity:gt.activity||ae.activity||0}},Lt=(q,ae,je=[],Xe="",Pe="preview")=>xt=>{xt&&xt.stopPropagation(),qe(null),De(Pe),st(q.key),typeof K=="function"&&K()},_t=(q,ae,je)=>{je&&(clearTimeout(W.current),clearTimeout(wt.current),wt.current=setTimeout(()=>{ee.current||qe({itemKey:q.key,routeKey:ae||"",anchorRect:je.getBoundingClientRect(),source:"stream"})},300))},pt=()=>{clearTimeout(wt.current),clearTimeout(W.current),W.current=setTimeout(()=>qe(null),150)},Ut=()=>clearTimeout(W.current),Gt=()=>qe(null),Ot=(q,ae,je,Xe,Pe)=>{if(J&&J.itemKey===q){be(null);return}be({itemKey:q,routeKey:ae||"",canBoot:!!Xe,preserved:!!Pe}),ot(je?je.getBoundingClientRect():null)};w.useEffect(()=>{D&&(st(null),De("preview"))},[D]);const ln=Lv(ke,We,Y,void 0,{autorevole:E,fleetStale:R}),In=co(ln,N,de("local").filter,Ii(U,"local")),wn=Le(s||[]).map(q=>{const ae=(q.route&&q.route.length?q.route:[q.name]).join("/"),je=de(ae);if(q.kind==="vl")return{g:q,nodeRoute:ae,groupView:je,rawItems:[],items:[]};const{rawItems:Xe}=mc(q),Pe=co(Xe,N,je.filter,Ii(U,ae));return{g:q,nodeRoute:ae,groupView:je,rawItems:Xe,items:Pe}}),en=[...In,...wn.flatMap(({items:q,nodeRoute:ae,g:je})=>(q||[]).map(Xe=>({...Xe,nodeRoute:ae,nodeLabel:je.label||je.name})))].filter(q=>q.type==="cell"),bn=ge?en.find(q=>q.key===ge):null,Ft=()=>{if(!He)return null;const q=en.find(Pe=>Pe.key===He.itemKey);if(!q)return null;const ae=q.value,je=q.nodeRoute?s.find(Pe=>(Pe.route||[Pe.name]).join("/")===q.nodeRoute)||{}:null,Xe=q.nodeRoute?je.route||[q.nodeRoute]:[];return l.jsx(yI,{row:St(q,ae,Xe,q.nodeLabel||"",je&&je.sessions),token:ne,anchorRect:He.anchorRect,source:He.source,onSourceChange:Pe=>qe(xt=>xt&&{...xt,source:Pe}),onExpand:Pe=>{qe(null),De(Pe),st(q.key),typeof K=="function"&&K()},onClose:Gt,onMouseEnter:Ut,onMouseLeave:pt})},Xt=(q,ae,je)=>i&&i({session:q,...ae?{node:ae}:{},...Ya.test(String(je||""))?{ownerId:je}:{}}),Jt=async q=>{if(!(q!=null&&q.direct)||!_)return;const ae=window.prompt(p("rename-node-prompt"),q.label||q.name);if(ae!==null)try{await _(q,ae)||window.alert(p("rename-node-invalid"))}catch(je){window.alert(String((je==null?void 0:je.message)||je))}},[Qt,ls]=w.useState({}),[cs,mn]=w.useState(new Set);w.useEffect(()=>{const q=new Map;for(const ae of e||[])q.set(Gl(ae.cell),!!ae.boot);for(const ae of s||[]){const je=ae.route||[ae.name];for(const Xe of ae.cells||[])q.set(Gl(Xe.cell,je),!!Xe.boot)}ls(ae=>{let je=!1;const Xe={...ae};for(const[Pe,xt]of Object.entries(ae))q.has(Pe)&&q.get(Pe)===xt&&(delete Xe[Pe],je=!0);return je?Xe:ae})},[e,s]),w.useEffect(()=>{if(!(I!=null&&I.cell))return;const q=Array.isArray(I.route)?I.route:[],ae=Gl(I.cell,q);ls(je=>({...je,[ae]:!!I.enabled})),V&&V(I.id)},[I,V]);const gn=(q,ae=[])=>{const je=Gl(q.cell,ae);return Object.prototype.hasOwnProperty.call(Qt,je)?Qt[je]:!!q.boot},qs=async(q,ae,je=[],Xe)=>{if(!u)return;const Pe=Gl(ae.cell,je),xt=typeof Xe=="boolean"?Xe:!gn(ae,je);ls(gt=>({...gt,[Pe]:xt})),mn(gt=>new Set(gt).add(Pe));try{await u(ae.cell,xt,je)}catch(gt){ls(Je=>{const Rt={...Je};return delete Rt[Pe],Rt}),x&&x(gt)}finally{mn(gt=>{const Je=new Set(gt);return Je.delete(Pe),Je})}},Vn=(q,ae,je)=>({onToggleLive:async()=>{const Xe=oo({item:q,cellName:ae.cell,route:je,pins:N,hostByRoute:F});$e(!0);const Pe=await eh({action:Xe.isLive?"remove":"use",cellId:ae.cell,route:je,token:ne});$e(!1),kt({messageKey:Pe.messageKey,ok:Pe.ok,cell:Pe.hostCell||ae.cell})},onTogglePin:()=>Cv({view:lh({item:q,pins:N,hostByRoute:F,route:je}),itemKey:q.key,togglePin:T,removePin:H}),onToggleBoot:Xe=>qs(null,ae,je,Xe),onWatchLive:()=>{qe(null),De("stream"),st(q.key),typeof K=="function"&&K()}}),[bt,us]=w.useState(null),le=(q,ae)=>{const je=q.currentTarget.getBoundingClientRect();us({text:ae,y:je.top+je.height/2})},re=()=>us(null),Te=w.useRef(null);w.useEffect(()=>()=>{Te.current&&Te.current()},[]);function Ge(q){q.preventDefault(),q.stopPropagation();const ae=q.clientX,je=P,Xe=xt=>{const gt=Math.max(wI,Math.min(bI,je+(xt.clientX-ae)));j&&j(gt)},Pe=()=>{window.removeEventListener("pointermove",Xe),window.removeEventListener("pointerup",Pe),window.removeEventListener("pointercancel",Pe),window.removeEventListener("blur",Pe),Te.current=null};window.addEventListener("pointermove",Xe),window.addEventListener("pointerup",Pe),window.addEventListener("pointercancel",Pe),window.addEventListener("blur",Pe),Te.current=Pe}const mt=O?{width:48,flex:"0 0 48px"}:{width:P,flex:`0 0 ${P}px`};return O?l.jsxs("aside",{className:"nc-sidebar mini",style:mt,children:[l.jsx("div",{className:"nc-side-head mini",children:l.jsx("button",{className:"nc-collapse-btn",onClick:z,title:p("expand"),children:"⟩"})}),l.jsx("button",{className:"nc-side-gear mini",onClick:()=>b&&b("nodes",!1),title:p("settings"),onMouseEnter:q=>le(q,p("settings")),onMouseLeave:re,children:l.jsx(Pt,{name:"gear",size:16})}),l.jsx("div",{className:"nc-side-scroll mini",children:l.jsxs("div",{className:"nc-side-group mini",children:[de("local").open&&In.map(q=>q.type==="cell"?(()=>{const ae=q.value,je=ae.degraded?"warn":ae.tmux?"on":"",Xe=!!ae.tmux;return l.jsx("button",{type:"button",className:`nc-mini-dot${Ne.has(ae.tmuxSession)?" active":""}`,onMouseEnter:Pe=>{Xe?_t(q,"",Pe.currentTarget):le(Pe,`${ae.cell}: ${q.subtitle}`)},onMouseLeave:()=>{Xe?pt():re()},draggable:Xe,onDragStart:Xe?Pe=>Pe.dataTransfer.setData("text/nc-session",ae.tmuxSession):void 0,onClick:Xe?()=>{qe(null),a&&a(ae.tmuxSession)}:()=>c&&c(ae),onDoubleClick:Xe?()=>Xt(ae.tmuxSession,"",L):void 0,children:l.jsx("span",{className:`nc-dot ${je}${q.working?" working":""}`})},q.key)})():(()=>{const ae=q.value;return l.jsx("button",{type:"button",className:`nc-mini-init${Ne.has(ae.name)?" active":""}`,onMouseEnter:je=>le(je,ae.name),onMouseLeave:re,draggable:!0,onDragStart:je=>je.dataTransfer.setData("text/nc-session",ae.name),onClick:()=>a&&a(ae.name),onDoubleClick:()=>Xt(ae.name,"",L),children:kp(ae.name)},q.key)})()),wn.flatMap(({g:q,nodeRoute:ae,groupView:je,items:Xe})=>q.kind==="vl"?q.status==="up"&&q.sessions.length?q.sessions.map(Pe=>l.jsx("button",{type:"button",className:"nc-mini-init",onMouseEnter:xt=>le(xt,`${q.label||ae}: ${Pe.name}`),onMouseLeave:re,onClick:()=>G&&G(q.peer),children:kp(Pe.name)},Pe.key)):[l.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Pe=>le(Pe,`${q.label||q.name}: ${Qi(q)||p("no-sessions-short")}`),onMouseLeave:re,children:l.jsx("span",{className:`nc-dot${q.status==="up"?" on":" warn"}`})},`nodo-vl-${ae}-${q.name}`)]:q.status==="up"?je.open?Xe.map(Pe=>Pe.type==="cell"?(()=>{const xt=Pe.value,gt=!!xt.tmux;return l.jsx("button",{type:"button",className:`nc-mini-dot${Ne.has(Pe.key)?" active":""}`,onMouseEnter:Je=>{gt?_t(Pe,ae,Je.currentTarget):le(Je,`${q.label||ae}: ${xt.cell} · ${Pe.subtitle}`)},onMouseLeave:()=>{gt?pt():re()},draggable:gt,onDragStart:gt?Je=>Je.dataTransfer.setData("text/nc-session",Pe.key):void 0,onClick:gt?()=>{qe(null),a&&a(Pe.key)}:()=>c&&c({...xt,route:q.route,availableEngines:q.engines||[]}),onDoubleClick:gt?()=>Xt(xt.tmuxSession,ae,q.instanceId):void 0,children:l.jsx("span",{className:`nc-dot ${xt.degraded?"warn":gt?`on${Pe.working?" working":""}`:""}`})},Pe.key)})():(()=>{const xt=Pe.value;return l.jsx("button",{type:"button",className:`nc-mini-init${Ne.has(Pe.key)?" active":""}`,onMouseEnter:gt=>le(gt,`${q.label||ae}: ${xt.name}`),onMouseLeave:re,draggable:!0,onDragStart:gt=>gt.dataTransfer.setData("text/nc-session",Pe.key),onClick:()=>a&&a(Pe.key),onDoubleClick:()=>Xt(xt.name,ae,q.instanceId),children:kp(xt.name)},Pe.key)})()):[]:[l.jsx("button",{type:"button",className:"nc-mini-dot",onMouseEnter:Pe=>le(Pe,`${q.label||(q.route||[q.name]).join(" › ")}: ${Qi(q)}`),onMouseLeave:re,children:l.jsx("span",{className:`nc-dot${q.status==="passive"?"":" warn"}`})},`nodo-${(q.route||[q.name]).join("/")}`)])]})}),Ft(),bt&&l.jsx("div",{className:"nc-mini-tip",style:{top:bt.y},children:bt.text})]}):l.jsxs("aside",{className:"nc-sidebar",style:mt,children:[l.jsx("div",{className:"nc-side-live-host",children:l.jsx(xI,{view:Va({liveHost:F[Cs([])],cells:e}),notice:ut})}),l.jsxs("div",{className:"nc-side-head",children:[l.jsx("button",{className:"nc-collapse-btn",onClick:z,title:p("collapse"),children:"⟨"}),l.jsx("span",{className:"nc-side-title",children:p("fleet")}),Q&&l.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:p("reorder-blocked"),"aria-label":p("reorder-blocked"),children:"⇅"}),R&&l.jsx("span",{className:"nc-side-fleet-stale",role:"status",title:p("fleet-stale"),"aria-label":p("fleet-stale"),children:"●"}),S!==null&&l.jsx("span",{className:"nc-side-fleet-off",role:"status",title:`${p("fleet-off")}${S?` (${S})`:""}`,"aria-label":`${p("fleet-off")}${S?` (${S})`:""}`,children:"○"}),l.jsxs("button",{className:"nc-new-btn",onClick:v,title:p("fleet-new-cell"),children:["+ ",p("new")]})]}),l.jsxs("button",{className:"nc-side-gear",onClick:()=>b&&b("nodes",!1),title:p("settings"),children:[l.jsx(Pt,{name:"gear",size:15})," ",p("settings")]}),l.jsx(Tk,{pinError:se,onRetry:Z,onDismiss:me}),l.jsxs("div",{className:"nc-side-scroll",children:[l.jsx(kI,{label:p("position-local"),count:In.length,state:de("local"),onToggle:()=>ie("local",{open:!de("local").open}),onFilter:q=>ie("local",{filter:q})}),de("local").open&&l.jsxs("div",{className:"nc-side-group",children:[In.map(q=>q.type==="cell"?(()=>{var rt;const ae=q.value,je=fe([]),Xe=Ed({hostCell:je.hostCell??null,threadStatus:je.threadStatus,pins:N,item:q}),Pe=ae.degraded?"warn":ae.tmux?"on":"",xt=fm(Xe,je.hostLease??null),gt=ae.degraded?p("cell-degraded"):q.subtitle||(ae.tmux?p("cell-idle"):p("cell-off")),Je=xt?`${gt} · ${p(xt)}`:gt,Rt=!!ae.tmux;return l.jsxs("div",{"data-roster-key":q.key,"data-position":"local",className:`nc-cell${Rt?" live":""}${Ne.has(ae.tmuxSession)?" active":""}`,title:`${ae.cell} · ${q.subtitle}${Je===q.subtitle?"":` · ${Je}`}`,"aria-label":`${ae.cell}, ${q.subtitle}${Je===q.subtitle?"":`, ${Je}`}`,draggable:Rt,onDragStart:Rt?ze=>ze.dataTransfer.setData("text/nc-session",ae.tmuxSession):void 0,onClick:Rt?()=>a&&a(ae.tmuxSession):void 0,onDoubleClick:Rt?()=>Xt(ae.tmuxSession,"",L):void 0,children:[l.jsx(Gi,{position:"local",itemKey:q.key,label:ae.cell,canMove:xe,onMove:(ze,Wt)=>Be("local",ze,Wt,ln),onStep:ze=>nt("local",q.key,ze,ln)}),Rt?l.jsx("button",{type:"button",className:"nc-side-peek",title:p("cell-peek"),"aria-label":`${p("cell-peek")}: ${ae.cell}`,onClick:Lt(q,ae,[],""),onMouseEnter:ze=>_t(q,"",ze.currentTarget),onMouseLeave:pt,children:l.jsx("span",{className:`nc-dot ${Pe}${q.working?" working":""}`})}):l.jsx("span",{className:`nc-dot ${Pe}${q.working?" working":""}`}),l.jsxs("span",{className:"nc-cell-main",children:[l.jsxs("b",{title:ae.cell,children:[ae.cell,oo({item:q,cellName:ae.cell,route:[],pins:N,hostByRoute:F}).isLive&&l.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),l.jsx("small",{title:q.subtitle,children:q.subtitle})]}),q.activity?l.jsx("span",{className:"nc-rel",children:ao(q.activity)}):null,q.fresh&&((rt=(Y.get(ae.tmuxSession)||{}).outbox)==null?void 0:rt.count)>0?l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:Y.get(ae.tmuxSession).outbox.count}):null,l.jsx("button",{type:"button",className:"nc-cellmenu",title:`${p("cell-actions-open")}: ${ae.cell}`,"aria-label":`${p("cell-actions-open")}: ${ae.cell}`,"aria-haspopup":"menu","aria-expanded":J&&J.itemKey===q.key?"true":"false",onClick:ze=>{ze.stopPropagation(),Ot(q.key,"",ze.currentTarget,C.includes("boot")&&!!u,!1)},children:l.jsx("span",{"aria-hidden":"true",children:"⋯"})}),l.jsx("button",{className:`nc-power${ae.tmux?" on":""}${ae.degraded?" warn":""}`,onClick:ze=>{ze.stopPropagation(),c&&c({...ae,boot:gn(ae)})},title:ae.active?p("power-off"):p("power-on"),children:l.jsx(Pt,{name:"power",size:14})})]},q.key)})():(()=>{var je;const ae=q.value;return l.jsxs("div",{"data-roster-key":q.key,"data-position":"local",className:`nc-side-card${Ne.has(ae.name)?" active":""}`,draggable:!0,onDragStart:Xe=>Xe.dataTransfer.setData("text/nc-session",ae.name),onClick:()=>a&&a(ae.name),onDoubleClick:()=>Xt(ae.name,"",L),children:[l.jsx(Gi,{position:"local",itemKey:q.key,label:ae.name,canMove:xe,onMove:(Xe,Pe)=>Be("local",Xe,Pe,ln),onStep:Xe=>nt("local",q.key,Xe,ln)}),l.jsx("span",{className:ae.attached?"nc-dot on":"nc-dot"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:ae.name}),l.jsxs("small",{children:[ae.preview||ae.cmd||p("windows").replace("{n}",String(ae.windows||0)),((je=ae.outbox)==null?void 0:je.count)>0?` · 📦${ae.outbox.count}`:""]})]}),ae.activity?l.jsx("span",{className:"nc-rel",children:ao(ae.activity)}):null,l.jsx("button",{className:`nc-pin${N.includes(q.key)?" on":""}`,title:p("pin"),onClick:Xe=>{Xe.stopPropagation(),T(q.key)},children:N.includes(q.key)?"★":"☆"}),l.jsx("button",{className:`nc-technical${ae.technical?" on":""}`,title:ae.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${ae.technical?p("mark-normal"):p("mark-technical")} ${ae.name}`,onClick:Xe=>{Xe.stopPropagation(),g&&g(ae.name,!ae.technical,[])},children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),onClick:Xe=>{Xe.stopPropagation(),window.confirm(p("terminate-confirm").replace("{name}",ae.name))&&f&&f(ae.name)},children:"⋯"})]},q.key)})()),In.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]}),wn.map(({g:q,nodeRoute:ae,groupView:je,rawItems:Xe,items:Pe})=>{const xt=Bk(q.health),gt=q.fleetState==="stale"?p("fleet-stale"):q.fleetState==="disabled"?p("fleet-off"):"",Je=q.fleetState==="stale"?"warn":xt||(q.status==="up"?"on":q.status==="passive"?"":"warn"),Rt=[q.health?Id(q.health):"",gt].filter(Boolean).join(" · ");return q.kind==="vl"?l.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":Re(q),children:[l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:()=>ie(ae,{open:!je.open}),onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),ie(ae,{open:!je.open}))},children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:Re(q),label:q.label||q.name,onMove:(rt,ze)=>Ie(rt,ze,s||[]),onStep:rt=>ue(Re(q),rt,s||[])}),l.jsx("span",{className:"nc-node-chevron",children:je.open?"⌄":"›"}),l.jsx("span",{className:`nc-dot ${Je}`,title:Rt}),l.jsx("b",{children:q.label||q.name}),l.jsxs("small",{children:[" · ",Qi(q)||[p("node-sessions").replace("{n}",String(q.sessions.length)),gt].filter(Boolean).join(" · ")]})]}),q.status==="up"&&je.open&&l.jsxs("div",{className:"nc-side-group",children:[q.sessions.map(rt=>l.jsxs("div",{className:"nc-side-card nc-vl-session-row",role:"button",tabIndex:0,onClick:()=>G&&G(q.peer),onKeyDown:ze=>{(ze.key==="Enter"||ze.key===" ")&&(ze.preventDefault(),G&&G(q.peer))},children:[l.jsx("span",{className:"nc-dot on"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:rt.name}),l.jsx("small",{children:p("vl-events-title")})]})]},rt.key)),q.sessions.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]})]},`nodo-vl-${ae}-${q.name}`):l.jsxs("div",{className:"nc-node-order-wrap","data-node-order-key":Re(q),children:[l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onContextMenu:q.direct&&_?rt=>{rt.preventDefault(),Jt(q)}:void 0,onClick:()=>ie(ae,{open:!je.open}),onKeyDown:rt=>{(rt.key==="Enter"||rt.key===" ")&&(rt.preventDefault(),ie(ae,{open:!je.open}))},children:[l.jsx(Gi,{scope:"node",position:"nodes",itemKey:Re(q),label:q.label||q.name,onMove:(rt,ze)=>Ie(rt,ze,s||[]),onStep:rt=>ue(Re(q),rt,s||[])}),l.jsx("span",{className:"nc-node-chevron",children:je.open?"⌄":"›"}),l.jsx("span",{className:`nc-dot ${Je}`,title:Rt}),l.jsx("b",{children:q.label||q.name}),l.jsxs("small",{children:[" · ",q.status==="up"?[p("node-sessions").replace("{n}",String(Pe.length)),gt].filter(Boolean).join(" · "):q.health&&Id(q.health)||Qi(q)]}),l.jsxs("select",{className:"nc-node-filter",value:je.filter,title:p(`view-${je.filter}`),onClick:rt=>rt.stopPropagation(),onChange:rt=>ie(ae,{filter:rt.target.value}),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]}),q.direct&&_&&l.jsx("button",{type:"button",className:"nc-node-rename",title:p("rename-node"),"aria-label":`${p("rename-node")} ${q.label||q.name}`,onClick:rt=>{rt.stopPropagation(),Jt(q)},children:"✎"}),q.direct&&q.health&&q.health.managed!==!1&&l.jsx("button",{type:"button",className:`nc-power${q.tunnelStatus==="up"?" on":""}`,title:q.tunnelStatus==="up"?p("power-off"):p("power-on"),onClick:rt=>{rt.stopPropagation(),h&&h(q)},children:l.jsx(Pt,{name:"power",size:14})})]}),(q.status==="up"||q.cellsPreserved)&&je.open&&l.jsxs("div",{className:"nc-side-group",children:[Pe.map(rt=>rt.type==="cell"?(()=>{var Zt;const ze=rt.value,Wt=q.route||[q.name],Sn=fe(Wt),Se=Ed({hostCell:Sn.hostCell??null,threadStatus:Sn.threadStatus,pins:N,item:rt}),Me=fm(Se,Sn.hostLease??null),Ve=!!ze.tmux&&!q.cellsPreserved,ct=ze.degraded?"warn":ze.tmux&&!q.cellsPreserved?"on":"",At=(q.sessions||[]).find(tn=>tn&&tn.name===ze.tmuxSession)||null,Ks=q.cellsPreserved?`${p("fleet-stale")}`:rt.subtitle||(ze.tmux?p("cell-idle"):p("cell-off")),Vs=Me?`${Ks} · ${p(Me)}`:Ks;return l.jsxs("div",{"data-roster-key":rt.key,"data-position":ae,className:`nc-side-card nc-cell${Ve?" live":""}${q.cellsPreserved?" preserved":""}${Ne.has(ze.key)?" active":""}`,title:Vs,draggable:Ve,onDragStart:Ve?tn=>tn.dataTransfer.setData("text/nc-session",ze.key):void 0,onClick:Ve?()=>a&&a(ze.key):void 0,onDoubleClick:Ve?()=>Xt(ze.tmuxSession,ae,q.instanceId):void 0,children:[l.jsx(Gi,{position:ae,itemKey:rt.key,label:ze.cell,canMove:xe,onMove:(tn,rn)=>Be(ae,tn,rn,Xe),onStep:tn=>nt(ae,rt.key,tn,Xe)}),Ve?l.jsx("button",{type:"button",className:"nc-side-peek",title:p("cell-peek"),"aria-label":`${p("cell-peek")}: ${ze.cell}`,onClick:Lt(rt,ze,q.route||[q.name],q.label||q.name),onMouseEnter:tn=>_t(rt,ae,tn.currentTarget),onMouseLeave:pt,children:l.jsx("span",{className:`nc-dot ${ct}${rt.working?" working":""}`})}):l.jsx("span",{className:`nc-dot ${ct}${rt.working?" working":""}`}),l.jsxs("span",{className:"nc-card-main",children:[l.jsxs("b",{children:[ze.cell,oo({item:rt,cellName:ze.cell,route:Wt,pins:N,hostByRoute:F}).isLive&&l.jsx("span",{className:"nc-live-bollino",children:"LIVE"})]}),l.jsx("small",{title:rt.subtitle,children:rt.subtitle})]}),rt.activity?l.jsx("span",{className:"nc-rel",children:ao(rt.activity)}):null,rt.fresh&&((Zt=(At||{}).outbox)==null?void 0:Zt.count)>0?l.jsx("span",{className:"nc-badge",title:p("new-files-outbox"),children:At.outbox.count}):null,l.jsx("button",{type:"button",className:"nc-cellmenu",title:`${p("cell-actions-open")}: ${ze.cell}`,"aria-label":`${p("cell-actions-open")}: ${ze.cell}`,"aria-haspopup":"menu","aria-expanded":J&&J.itemKey===rt.key?"true":"false",onClick:tn=>{tn.stopPropagation(),Ot(rt.key,ae,tn.currentTarget,u&&(q.capabilities||[]).includes("boot"),!!q.cellsPreserved)},children:l.jsx("span",{"aria-hidden":"true",children:"⋯"})}),(q.capabilities||[]).includes(ze.active?"down":"up")&&l.jsx("button",{className:`nc-power${ze.active?" on":""}${ze.degraded?" warn":""}`,onClick:tn=>{tn.stopPropagation(),c&&c({...ze,boot:gn(ze,q.route||[]),route:q.route,availableEngines:q.engines||[]})},title:ze.active?p("power-off"):p("power-on"),children:l.jsx(Pt,{name:"power",size:14})})]},rt.key)})():(()=>{const ze=rt.value;return l.jsxs("div",{"data-roster-key":rt.key,"data-position":ae,className:`nc-side-card${Ne.has(ze.key)?" active":""}`,draggable:!0,onDragStart:Wt=>Wt.dataTransfer.setData("text/nc-session",ze.key),onClick:()=>a&&a(ze.key),onDoubleClick:()=>Xt(ze.name,ze.node||ae,q.instanceId),children:[l.jsx(Gi,{position:ae,itemKey:rt.key,label:ze.name,canMove:xe,onMove:(Wt,Sn)=>Be(ae,Wt,Sn,Xe),onStep:Wt=>nt(ae,rt.key,Wt,Xe)}),l.jsx("span",{className:ze.attached?"nc-dot on":"nc-dot"}),l.jsxs("span",{className:"nc-card-main",children:[l.jsx("b",{children:ze.name}),l.jsx("small",{children:ze.preview?ze.preview:ze.cmd?ze.cmd:p("windows").replace("{n}",String(ze.windows||0))})]}),ze.activity?l.jsx("span",{className:"nc-rel",children:ao(ze.activity)}):null,l.jsx("button",{className:`nc-pin${N.includes(rt.key)?" on":""}`,title:p("pin"),onClick:Wt=>{Wt.stopPropagation(),T(rt.key)},children:N.includes(rt.key)?"★":"☆"}),l.jsx("button",{className:`nc-technical${ze.technical?" on":""}`,title:ze.technical?p("mark-normal"):p("mark-technical"),"aria-label":`${ze.technical?p("mark-normal"):p("mark-technical")} ${ze.name}`,onClick:Wt=>{Wt.stopPropagation(),g&&g(ze.name,!ze.technical,q.route||[])},children:"T"}),l.jsx("button",{className:"nc-menu",title:p("terminate"),onClick:Wt=>{Wt.stopPropagation(),window.confirm(p("terminate-confirm").replace("{name}",ze.name))&&f&&f(ze.name,q.route)},children:"⋯"})]},rt.key)})()),Pe.length===0&&l.jsx("div",{className:"nc-empty",children:p("no-sessions-short")})]})]},`nodo-${(q.route||[q.name]).join("/")}`)})]}),l.jsx("div",{className:"nc-side-lang",children:$1.map((q,ae)=>l.jsxs("span",{children:[ae>0&&" · ",l.jsx("button",{className:`nc-lang-btn${M===q?" on":""}`,onClick:()=>A(q),title:q,children:q.toUpperCase()})]},q))}),l.jsx("div",{className:"nc-side-resize",onPointerDown:Ge,title:""}),bn&&(()=>{const q=bn.value,ae=bn.nodeRoute?s.find(Xe=>(Xe.route||[Xe.name]).join("/")===bn.nodeRoute)||{}:null,je=bn.nodeRoute?ae.route||[bn.nodeRoute]:[];return l.jsx(wk,{row:St(bn,q,je,bn.nodeLabel||"",ae&&ae.sessions),token:ne,initialSource:Ze,onClose:()=>{st(null),De("preview")}})})(),Ft(),J&&(()=>{const q=en.find(Je=>Je.key===J.itemKey);if(!q)return null;const ae=q.value,je=J.routeKey?s.find(Je=>(Je.route||[Je.name]).join("/")===J.routeKey)||{}:null,Xe=J.routeKey?je.route||[J.routeKey]:[],Pe=J.preserved?!1:!!ae.tmux,xt=oo({item:q,cellName:ae.cell,route:Xe,pins:N,hostByRoute:F}),gt=Ev({...xt,canBoot:J.canBoot,boot:gn(ae,Xe),alive:Pe,handlers:Vn(q,ae,Xe)});return l.jsx(Dk,{anchorRect:ye,items:gt,busy:oe,onClose:()=>be(null)})})()]})}function xI({view:t,notice:e}){const n=!!(t&&t.cell),s=n?p("live-host-indicator").replace("{cell}",t.cell).replace("{mode}",p(t.mode?`live-host-mode-${t.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${t.state||"none"}`)):p("live-host-indicator-none");return l.jsxs("div",{className:"nc-live-strip","data-state":t&&t.state?t.state:"none",title:e?`${s} · ${p(e.messageKey)}`:s,children:[l.jsx("span",{className:`nc-live-strip-dot ${Rv(t||{})}`,"aria-hidden":"true"}),l.jsx("span",{className:"nc-live-strip-testo",children:n?t.cell:s}),e&&l.jsx("span",{className:`nc-live-strip-notice${e.ok?" ok":" ko"}`,role:"status",children:p(e.messageKey).replace("{cell}",e.cell||t.cell||"")})]})}function kI({label:t,count:e,state:n,onToggle:s,onFilter:i}){return l.jsxs("div",{className:"nc-side-group-title nc-node-title",role:"button",tabIndex:0,onClick:s,onKeyDown:a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),s())},children:[l.jsx("span",{className:"nc-node-chevron",children:n.open?"⌄":"›"}),l.jsx("span",{className:"nc-dot on"}),l.jsx("b",{children:t}),l.jsxs("small",{children:[" · ",p("node-sessions").replace("{n}",String(e))]}),l.jsxs("select",{className:"nc-node-filter",value:n.filter,title:p(`view-${n.filter}`),onClick:a=>a.stopPropagation(),onChange:a=>i(a.target.value),children:[l.jsx("option",{value:"all",children:p("view-all")}),l.jsx("option",{value:"pinned",children:p("view-pinned")}),l.jsx("option",{value:"active",children:p("view-active")}),l.jsx("option",{value:"off",children:p("view-off")}),l.jsx("option",{value:"technical",children:p("view-technical")})]})]})}const ps={PRESENTE:"presente-verificata",ASSENTE:"assente-verificata",IGNOTA:"ignota"},Cp={OK:"ok",NON_DISPONIBILE:"non-disponibile",RIMOSSO:"rimosso"},ed={LETTURA_NON_VERIFICABILE:"lettura-non-verificabile",OWNER_NON_DISPONIBILE:"owner-non-disponibile",OWNER_RIMOSSO:"owner-rimosso",LOCALE_NON_VERIFICATO:"lettura-locale-non-verificata"},V0={RITORNO:"ritorno-dopo-assenza",IDENTITA:"identita-cambiata"},CI=6e4;function EI(t,e){return!t||!Array.isArray(e)?null:e.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===t)||null}function Y0(t){const e=t&&t.created;return Number.isFinite(e)&&e>0?e:null}function NI({tileKey:t,node:e,nodeGroups:n,sessionsAlive:s,localVerified:i=!0,localIdentita:a=null,lastVerifiedAt:c=null,nowMs:u=0}={}){const h=EI(e,n);let f,g=Cp.OK,v=null,_=null;if(!e)i?!s||s.has(t)?(f=ps.PRESENTE,_=Y0({created:a})):f=ps.ASSENTE:(f=ps.IGNOTA,v=ed.LOCALE_NON_VERIFICATO);else if(!h)f=ps.IGNOTA,g=Cp.RIMOSSO,v=ed.OWNER_RIMOSSO;else if(h.status!=="up")f=ps.IGNOTA,g=Cp.NON_DISPONIBILE,v=h.cause||ed.OWNER_NON_DISPONIBILE;else if(h.inventoryPartial===!0)f=ps.IGNOTA,v=ed.LETTURA_NON_VERIFICABILE;else if(!s||s.has(t)){f=ps.PRESENTE;const x=Array.isArray(h.sessions)?h.sessions.find(L=>L&&L.key===t):null;_=Y0(x)}else f=ps.ASSENTE;const b=f===ps.IGNOTA&&Number.isFinite(c)&&Number.isFinite(u)&&u-c>CI;return{presenza:f,owner:g,causa:v,identita:f===ps.PRESENTE?_:null,verificata:f!==ps.IGNOTA,oltreIlTetto:b}}function dC(){return{presenza:null,identita:null}}function RI(t,e){const n=t&&typeof t=="object"?t:dC();if(!e||e.presenza===ps.IGNOTA)return{runtime:{presenza:n.presenza,identita:n.identita},generazione:0,motivo:null};const s=e.presenza===ps.PRESENTE;let i=null;return s&&(n.presenza===ps.ASSENTE?i=V0.RITORNO:n.presenza===ps.PRESENTE&&n.identita!==null&&e.identita!==null&&n.identita!==e.identita&&(i=V0.IDENTITA)),{runtime:{presenza:e.presenza,identita:s?e.identita===void 0?null:e.identita:null},generazione:i?1:0,motivo:i}}const Tv="nc_input_preferences_v1",Ep="nc-input-preferences",hC=Object.freeze(["double-tap","single-tap","never"]),fC=Object.freeze(["full","compact"]);function LI(){try{return typeof window<"u"&&typeof window.matchMedia=="function"?window.matchMedia("(pointer: coarse)").matches:!1}catch{return!1}}const wr=Object.freeze({terminalKeyboardGesture:"double-tap",keybarKeepsKeyboardClosed:!0,voiceKeepsKeyboardClosed:!0,showKeybarEnter:!0,keybarLayout:"full",showComposer:LI()});function Pv(t){const e=t&&typeof t=="object"&&!Array.isArray(t)?t:{};return{terminalKeyboardGesture:hC.includes(e.terminalKeyboardGesture)?e.terminalKeyboardGesture:wr.terminalKeyboardGesture,keybarKeepsKeyboardClosed:typeof e.keybarKeepsKeyboardClosed=="boolean"?e.keybarKeepsKeyboardClosed:wr.keybarKeepsKeyboardClosed,voiceKeepsKeyboardClosed:typeof e.voiceKeepsKeyboardClosed=="boolean"?e.voiceKeepsKeyboardClosed:wr.voiceKeepsKeyboardClosed,showKeybarEnter:typeof e.showKeybarEnter=="boolean"?e.showKeybarEnter:wr.showKeybarEnter,keybarLayout:fC.includes(e.keybarLayout)?e.keybarLayout:wr.keybarLayout,showComposer:typeof e.showComposer=="boolean"?e.showComposer:wr.showComposer}}function pC(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function G0(t=pC()){if(!t)return{...wr};try{return Pv(JSON.parse(t.getItem(Tv)||"null"))}catch{return{...wr}}}function AI(t,e=pC()){const n=Pv(t);if(e)try{e.setItem(Tv,JSON.stringify(n))}catch{}return n}function Iv(){const[t,e]=w.useState(G0);w.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==Tv&&i.key!==null)return;const a=i!=null&&i.detail?Pv(i.detail):G0();e(a)};return window.addEventListener(Ep,s),window.addEventListener("storage",s),()=>{window.removeEventListener(Ep,s),window.removeEventListener("storage",s)}},[]);const n=w.useCallback(s=>{e(i=>{const a=AI({...i,...s||{}});return window.dispatchEvent(new CustomEvent(Ep,{detail:a})),a})},[]);return[t,n]}function jI({session:t,node:e,ownerId:n,cellName:s,token:i,readonly:a=!1,focused:c,onFocus:u,onClose:h,onOpenSingle:f,onDragTileStart:g,floating:v=!1,minimized:_=!1,takeSize:b=!1,onDetach:x,onReattach:L,onToggleMinimize:C,onFloatDragStart:R,alive:S=!0,sessionAlive:I=S,available:E=!0,stale:F=!1,presence:$=null,fontSize:X=_i,onZoom:V,decks:G=[],currentDeck:ne,onSendToDeck:K,panelUrl:D="",panelCellId:P="",panelPort:O=0}){const[j]=Iv(),z=s||t,M=w.useRef(()=>{}),A=w.useRef(()=>!1),N=w.useRef(()=>{}),U=w.useRef(!1),[T,H]=w.useState(!1),[se,Q]=w.useState(!1),[Z,me]=w.useState(!1),[de,ie]=w.useState(!1),[xe,Be]=w.useState(null),[nt,Le]=w.useState(0),Ie=w.useRef(dC()),ue=e?`${e}:${t}`:t,Re=G.filter(Y=>Y.id!==ne&&Y.available!==!1),fe=$?$.presenza:I?ps.PRESENTE:ps.ASSENTE,Ee=$?$.identita??null:null;return w.useEffect(()=>{const Y=RI(Ie.current,{presenza:fe,identita:Ee});Ie.current=Y.runtime,Y.generazione&&Le(pe=>pe+Y.generazione)},[fe,Ee]),l.jsxs("div",{className:`nc-tile${c?" focused":""}`,onMouseDown:()=>u&&u(ue),children:[l.jsxs("div",{className:`nc-tile-head${v?" nc-float-head":""}`,draggable:!v,onPointerDown:v&&R?Y=>{Y.target&&Y.target.closest&&Y.target.closest(".nc-tile-actions")||R(Y)}:void 0,onDragStart:Y=>{v||(Y.dataTransfer.setData("text/nc-session",ue),Y.dataTransfer.effectAllowed="move",g&&g(ue))},children:[l.jsxs("button",{className:"nc-tile-name",onClick:()=>u&&u(ue),title:e?`${z} · ${e}`:z,children:[l.jsx("span",{className:S?"nc-dot on":"nc-dot"}),l.jsx("b",{children:z})]}),l.jsxs("span",{className:"nc-tile-actions",children:[v?l.jsxs(l.Fragment,{children:[L&&l.jsx("button",{className:"nc-tile-float-btn",onClick:()=>L(ue),title:p("tile-reattach"),"aria-label":p("tile-reattach"),children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("rect",{x:"9",y:"3",width:"12",height:"12",rx:"1"}),l.jsx("path",{d:"M11 21H3v-8M3 21l9-9"})]})}),C&&l.jsx("button",{onClick:()=>C(ue),title:p(_?"tile-restore":"tile-minimize"),"aria-label":p(_?"tile-restore":"tile-minimize"),children:"–"})]}):l.jsxs(l.Fragment,{children:[V&&l.jsx("button",{onClick:()=>V(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:l.jsx(Pt,{name:"zoomOut",size:14})}),V&&l.jsx("button",{onClick:()=>V(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Pt,{name:"zoomIn",size:14})}),K&&Re.length>0&&l.jsxs("select",{className:"nc-tile-deck",title:p("send-to-deck"),value:"",onMouseDown:Y=>Y.stopPropagation(),onChange:Y=>{const pe=Y.target.value;pe&&K(ue,pe),Y.target.value=""},children:[l.jsx("option",{value:"",children:p("send-to-deck")}),Re.map(Y=>l.jsxs("option",{value:Y.id,children:[Y.ownerLabel," · ",Y.name]},Y.id))]}),l.jsx("button",{onClick:()=>Q(Y=>!Y),title:p("composer"),children:"⌨"}),l.jsx("button",{onClick:()=>me(Y=>!Y),title:p("files"),children:"📁"}),D&&l.jsx("button",{onClick:()=>ie(Y=>!Y),title:p("panel"),"aria-pressed":de,children:l.jsx(Pt,{name:"monitor",size:14})}),f&&l.jsx("button",{onClick:()=>f({session:t,node:e,ownerId:n}),title:p("single-view"),children:"↗"})]}),!v&&x&&l.jsx("button",{className:"nc-tile-float-btn",onClick:()=>x(ue),title:p("tile-detach"),"aria-label":p("tile-detach"),children:l.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[l.jsx("rect",{x:"3",y:"9",width:"12",height:"12",rx:"1"}),l.jsx("path",{d:"M13 3h8v8M21 3l-9 9"})]})}),h&&l.jsx("button",{className:"nc-tile-close",onClick:()=>h(ue),title:p("close"),"aria-label":p("close"),children:"✕"})]})]}),l.jsxs("div",{className:"nc-tile-body",children:[$&&$.oltreIlTetto===!0&&l.jsx("div",{className:"nc-tile-unverified",role:"status","data-causa":$.causa||"",children:p("tile-unverified")}),l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:b,focused:c,sendRef:M,composerRef:A,actionRef:N,ctrlRef:U,setCtrlArmed:H,onFiles:Be,fontSize:X,keyboardGesture:j.terminalKeyboardGesture},`${ue}:${nt}`),!E&&l.jsx("div",{className:"nc-tile-unavailable",title:p("deck-owner-unavailable"),children:p("deck-owner-reconnecting")}),E&&F&&l.jsx("div",{className:"nc-tile-stale",title:p("deck-owner-stale"),children:p("deck-owner-stale")}),E&&Z&&l.jsx("div",{className:"nc-tile-files",onMouseDown:Y=>Y.stopPropagation(),children:l.jsx(Eg,{session:t,node:e,token:i,filesEvent:xe,onClose:()=>me(!1)})})]}),E&&se&&l.jsx("div",{className:"nc-tile-composer",onMouseDown:Y=>Y.stopPropagation(),children:l.jsx(uC,{submitText:Y=>A.current(Y),token:i,session:t,node:e,ownerId:n,readonly:a,keepKeyboardClosedOnVoice:j.voiceKeepsKeyboardClosed})}),E&&de&&D&&P&&l.jsx(F1,{title:z,onClose:()=>ie(!1),children:l.jsx(pv,{cellId:P,panelUrl:D,route:e?e.split("/"):[],panelPort:O,token:i,title:z})})]})}function Lg({session:t,node:e,ownerId:n,cells:s,nodeGroups:i}={}){const a=typeof t=="string"?t:"";if(!a)return null;if(e){const u=Array.isArray(i)?i:[];for(const h of u){if(!h||(Array.isArray(h.route)?h.route:[]).join("/")!==e||n&&h.instanceId&&String(n)!==String(h.instanceId))continue;const g=(Array.isArray(h.cells)?h.cells:[]).find(v=>v&&v.tmuxSession===a);if(g)return g}return null}return(Array.isArray(s)?s:[]).find(u=>u&&u.tmuxSession===a)||null}function Rc({session:t,cell:e,node:n,ownerId:s,cells:i,nodeGroups:a}={}){const c=typeof t=="string"?t:"";if(e&&typeof e.cell=="string"&&e.cell)return e.cell;const u=Lg({session:c,node:n,ownerId:s,cells:i,nodeGroups:a});return u&&u.cell?u.cell:c}const X0=.22,J0=.3,mC=(t,e)=>Array.from((t==null?void 0:t.types)||[]).includes(e),Np=t=>mC(t,"text/nc-session"),Q0=t=>{var e;return mC(t,"Files")||(((e=t==null?void 0:t.files)==null?void 0:e.length)||0)>0};function MI(t,e){return t&&Array.isArray(e)?e.find(n=>Array.isArray(n==null?void 0:n.route)&&n.route.join("/")===t):null}function TI(t,e,n){const s=(t-n.left)/(n.width||1),i=(e-n.top)/(n.height||1);return s<X0?"left":s>1-X0?"right":i>=J0&&i<=1-J0?"center":i<.5?"top":"bottom"}const PI=[["left","M15 6l-6 6 6 6",22],["top","M6 15l6-6 6 6",22],["center","M4 8h16M20 8l-3-3M20 8l-3 3M20 16H4M4 16l3-3M4 16l3 3",34],["bottom","M6 9l6 6 6-6",22],["right","M9 6l6 6-6 6",22]];function II({active:t}){return l.jsx("div",{className:"nc-drop-zones","data-testid":"nc-drop-zones","aria-hidden":"true",children:PI.map(([e,n,s])=>l.jsx("div",{className:`nc-drop-zone ${e}${t===e?" on":""}`,"data-zone":e,children:l.jsx("svg",{width:s,height:s,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:l.jsx("path",{d:n})})},e))})}function Rp(t,e){for(const n of t.columns)for(const s of n.tiles)if($t(s)===e)return s.float||null;return null}function Z0(t,e){for(const n of t.columns)for(const s of n.tiles)if($t(s)===e)return s.fontSize||null;return null}function DI({layout:t,onLayoutChange:e,token:n,readonly:s=!1,sessionsAlive:i,focusSession:a,onFocus:c,onOpenSingle:u,localVerified:h=!0,localIdentities:f=null,localVerifiedAt:g=null,decks:v=[],currentDeck:_,onSendToDeck:b,onResizeEnd:x,cells:L=[],nodeGroups:C=[],panelPort:R=0,nodePanelPorts:S={}}){zn();const I=Date.now(),[E,F]=w.useState(null),[$,X]=w.useState(null),V=w.useRef(null);V.current=$;const[G,ne]=w.useState({z:{},next:1,focus:null,mini:{}}),[K,D]=w.useState(null),P=w.useRef(null);P.current=K;const O=w.useRef(null),j=w.useRef([]),z=w.useRef(null);function M(Y,pe,Ae){const ke=()=>{window.removeEventListener("pointermove",Y),window.removeEventListener("pointerup",We),window.removeEventListener("pointercancel",Ne),window.removeEventListener("blur",Ne)},We=()=>{ke(),z.current=null,pe&&pe()},Ne=()=>{ke(),z.current=null,Ae&&Ae()};window.addEventListener("pointermove",Y),window.addEventListener("pointerup",We),window.addEventListener("pointercancel",Ne),window.addEventListener("blur",Ne),z.current=Ne}w.useEffect(()=>()=>{z.current&&z.current()},[]),w.useEffect(()=>{if(!E&&!K)return;const Y=pe=>{pe.key==="Escape"&&(F(null),K&&z.current&&z.current())};return window.addEventListener("keydown",Y),()=>{window.removeEventListener("keydown",Y)}},[E,K]),w.useEffect(()=>{const Y=()=>F(null);return window.addEventListener("dragend",Y),window.addEventListener("drop",Y),()=>{window.removeEventListener("dragend",Y),window.removeEventListener("drop",Y)}},[]);const A=t.columns.length,N=t.columns.flatMap(Y=>Y.tiles).filter(Y=>Y.float).map(Y=>$t(Y)),U=Y=>!!Y&&Y.tiles.length>0&&Y.tiles.every(pe=>pe.float),T=Y=>E&&E.col===Y&&E.row===void 0,H=!!E&&E.col===A,se=(Y,pe)=>E&&E.col===Y&&E.row===pe&&E.quadrant?` drop-${E.quadrant}`:"";function Q(Y){var We;if(Y.preventDefault(),Q0(Y.dataTransfer)){F(null);return}const pe=Y.dataTransfer.getData("text/nc-session"),Ae=E;if(F(null),!pe||!Ae)return;if(Ae.quadrant==="center"){const Ne=$t(((We=t.columns[Ae.col])==null?void 0:We.tiles[Ae.row])||{});Ne&&Ne!==pe&&e(kP(t,pe,Ne));return}let ke;if(Ae.quadrant){if(ke=TP(t,Ae.col,Ae.row,Ae.quadrant),!ke)return}else ke={col:Ae.col};e(_s(t).includes(pe)?SP(t,pe,ke):Ec(t,pe,ke))}function Z(Y,pe){var ee,J,be;Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const Ae=O.current&&O.current.clientWidth||0,ke=O.current?O.current.getBoundingClientRect():null,We=ke?ke.left:0,Ne=j.current[pe]?j.current[pe].getBoundingClientRect():null,ge=j.current[pe+1]?j.current[pe+1].getBoundingClientRect():null,st=Ne&&ge&&ge.right>Ne.left?Ne.left-(ke?ke.left:0):0,Ze=Number.isFinite(Y.clientX)?Y.clientX:0,De=t.columns[pe].width+(((ee=t.columns[pe+1])==null?void 0:ee.width)||0),He=t.columns.reduce((ye,ot)=>ye+ot.width,0),qe=Ne&&ge&&ge.right>Ne.left?ge.right-Ne.left:Ae*(De/(He||1)),wt=Math.min(Vk,qe/2),W=ye=>{const ot=(Number.isFinite(ye.clientX)?ye.clientX:Ze)-We;let oe=Math.max(wt,Math.min(qe-wt,ot-st)),$e=!1;if(!ye.altKey){for(const ut of hc)if(Math.abs(oe-ut*qe)<=wg){oe=ut*qe,$e=!0;break}}return{border:oe,snapped:$e,alt:ye.altKey===!0}};X({kind:"col",ci:pe,coupleLeft:st,couplePx:qe,live:W(Y),pxOther:O.current&&O.current.clientHeight||0,fsA:((J=t.columns[pe].tiles[0])==null?void 0:J.fontSize)||_i,fsB:((be=t.columns[pe+1].tiles[0])==null?void 0:be.fontSize)||_i}),M(ye=>X(ot=>ot&&{...ot,live:W(ye)}),()=>{var oe,$e;const ye=V.current,ot=((oe=ye==null?void 0:ye.live)==null?void 0:oe.border)??qe/2;X(null),e(D0(t,pe,Ae,ot,{snap:!(($e=ye==null?void 0:ye.live)!=null&&$e.alt)})),x&&x()},()=>X(null))}function me(Y){const pe=O.current&&O.current.clientWidth||0;e(D0(t,Y,pe,Number.NaN,{snap:!0,half:!0})),x&&x()}function de(Y,pe,Ae){var oe;Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const ke=j.current[pe],We=ke&&ke.clientHeight||O.current&&O.current.clientHeight||0,Ne=O.current?O.current.getBoundingClientRect():null,ge=Ne?Ne.top:0,st=ke?ke.getBoundingClientRect():null,Ze=st?st.left-(Ne?Ne.left:0):0,De=st&&st.width>0?st.width:ke&&ke.clientWidth||0,He=Number.isFinite(Y.clientY)?Y.clientY:0,qe=t.columns[pe].tiles,wt=qe[Ae].height+(((oe=qe[Ae+1])==null?void 0:oe.height)||0),W=qe.reduce(($e,ut)=>$e+ut.height,0),ee=qe.slice(0,Ae).reduce(($e,ut)=>$e+ut.height,0),J=(st&&st.height>0?st.top-ge:0)+We*(ee/(W||1)),be=(st&&st.height>0,We*(wt/(W||1))),ye=Math.min(Yk,be/2),ot=$e=>{const ut=(Number.isFinite($e.clientY)?$e.clientY:He)-ge;let kt=Math.max(ye,Math.min(be-ye,ut-J)),St=!1;if(!$e.altKey){for(const Lt of hc)if(Math.abs(kt-Lt*be)<=wg){kt=Lt*be,St=!0;break}}return{border:kt,snapped:St,alt:$e.altKey===!0}};X({kind:"row",ci:pe,ri:Ae,coupleTop:J,couplePx:be,colLeft:Ze,colWidth:De,live:ot(Y),pxOther:ke&&ke.clientWidth||O.current&&O.current.clientWidth||0,fsA:qe[Ae].fontSize||_i,fsB:qe[Ae+1].fontSize||_i}),M($e=>X(ut=>ut&&{...ut,live:ot($e)}),()=>{var kt,St;const $e=V.current,ut=((kt=$e==null?void 0:$e.live)==null?void 0:kt.border)??be/2;X(null),e(O0(t,pe,Ae,We,ut,{snap:!((St=$e==null?void 0:$e.live)!=null&&St.alt)})),x&&x()},()=>X(null))}function ie(Y,pe){const Ae=j.current[Y],ke=Ae&&Ae.clientHeight||O.current&&O.current.clientHeight||0;e(O0(t,Y,pe,ke,Number.NaN,{snap:!0,half:!0})),x&&x()}function xe(Y){e(Nc(t,Y))}const Be={x:.45,y:.12,w:.42,h:.6},nt=8;function Le(Y){ne(pe=>({...pe,z:{...pe.z,[Y]:pe.next},next:pe.next+1,focus:Y})),c&&c(Y)}function Ie(Y){ne(pe=>({...pe,mini:{...pe.mini,[Y]:!pe.mini[Y]}}))}function ue(Y){N.length>=$c||e(CP(t,Y,Be))}function Re(Y,pe){const Ae=[0,1];let ke=!1,We=Y;for(const Ne of[...Ae,...pe])if(Math.abs(Y-Ne)<=nt/window.innerWidth){We=Ne,ke=!0;break}return{v:Math.max(0,Math.min(1,We)),snapped:ke}}function fe(Y,pe){Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const Ae=Rp(t,pe);if(!Ae)return;const ke=Number.isFinite(Y.clientX)?Y.clientX:0,We=Number.isFinite(Y.clientY)?Y.clientY:0,Ne=N.filter(De=>De!==pe).map(De=>Rp(t,De)).filter(Boolean),ge=Ne.flatMap(De=>[De.x,De.x+De.w]),st=Ne.flatMap(De=>[De.y,De.y+De.h]),Ze=De=>{const He=(Number.isFinite(De.clientX)?De.clientX:ke)-ke,qe=(Number.isFinite(De.clientY)?De.clientY:We)-We,wt=Re(Ae.x+He/Math.max(1,window.innerWidth),ge),W=Re(Ae.y+qe/Math.max(1,window.innerHeight),st);return{x:wt.v,y:W.v,w:Ae.w,h:Ae.h,snappedX:wt.snapped,snappedY:W.snapped}};D({key:pe,kind:"move",live:Ze(Y)}),M(De=>D(He=>He&&{...He,live:Ze(De)}),()=>{var He;const De=(He=P.current)==null?void 0:He.live;D(null),De&&e(B0(t,pe,De))},()=>D(null))}function Ee(Y,pe,Ae){Y.preventDefault(),Y.stopPropagation();try{Y.currentTarget.setPointerCapture&&Y.pointerId!=null&&Y.currentTarget.setPointerCapture(Y.pointerId)}catch{}const ke=Rp(t,pe);if(!ke)return;const We=Number.isFinite(Y.clientX)?Y.clientX:0,Ne=Number.isFinite(Y.clientY)?Y.clientY:0,ge=Math.max(1,window.innerWidth),st=Math.max(1,window.innerHeight);Z0(t,pe);const Ze=De=>{const He=((Number.isFinite(De.clientX)?De.clientX:We)-We)/ge,qe=((Number.isFinite(De.clientY)?De.clientY:Ne)-Ne)/st;let{x:wt,y:W,w:ee,h:J}=ke;return Ae.includes("e")&&(ee=ke.w+He),Ae.includes("s")&&(J=ke.h+qe),Ae.includes("w")&&(wt=ke.x+He,ee=ke.w-He),Ae.includes("n")&&(W=ke.y+qe,J=ke.h-qe),ee=Math.max(.05,Math.min(1-wt,ee)),J=Math.max(.05,Math.min(1-W,J)),{x:wt,y:W,w:ee,h:J}};D({key:pe,kind:"resize",dir:Ae,live:Ze(Y),badge:!0}),M(De=>D(He=>He&&{...He,live:Ze(De)}),()=>{var He;const De=(He=P.current)==null?void 0:He.live;D(null),De&&e(B0(t,pe,De)),x&&x()},()=>D(null))}return l.jsxs("div",{className:`nc-grid${$||K?" gesturing":""}`,ref:O,onDragOver:Y=>{if(Q0(Y.dataTransfer)){Y.preventDefault(),F(null);return}Np(Y.dataTransfer)&&(Y.preventDefault(),E&&E.col===A||F({col:A}))},onDrop:Q,onDragLeave:Y=>{const pe=Y.relatedTarget;(!pe||!(O.current&&O.current.contains(pe)))&&F(null)},children:[t.columns.flatMap((Y,pe)=>{const Ae=[];return Ae.push(l.jsx("div",{className:`nc-col${T(pe)?" drop-newcol":""}${U(Y)?" nc-col-emptyfloat":""}`,ref:ke=>{j.current[pe]=ke},style:{flexGrow:U(Y)?0:Y.width,flexBasis:0},onDragOver:ke=>{Np(ke.dataTransfer)&&(ke.preventDefault(),ke.stopPropagation(),E&&E.col===pe&&E.row===void 0||F({col:pe}))},children:Y.tiles.flatMap((ke,We)=>{const Ne=[],ge=$t(ke),st=MI(ke.node,C),Ze=NI({tileKey:ge,node:ke.node,nodeGroups:C,sessionsAlive:i,localVerified:h,localIdentita:f?f.get(ge):null,lastVerifiedAt:ke.node?(st==null?void 0:st.verifiedAt)??null:g,nowMs:I}),De=ke.unavailable!==!0&&(ke.node?(st==null?void 0:st.status)==="up":Ze.owner==="ok"),He=ke.unavailable!==!0&&Ze.presenza!=="assente-verificata",qe=Lg({session:ke.session,node:ke.node,ownerId:ke.ownerId,cells:L,nodeGroups:C}),wt=Rc({session:ke.session,cell:qe,node:ke.node,ownerId:ke.ownerId,cells:L,nodeGroups:C}),W=typeof(qe==null?void 0:qe.panelUrl)=="string"?qe.panelUrl.trim():"",ee=typeof(qe==null?void 0:qe.cell)=="string"?qe.cell:"",J=ke.float||null,be=!!(J&&G.mini[ge]);return Ne.push(l.jsxs("div",{className:`nc-tile-slot${se(pe,We)}${E&&E.from===ge?" nc-tile-source":""}${J?" nc-float":""}${be?" nc-float-mini":""}`,style:J?{position:"fixed",left:`${J.x*100}%`,top:`${J.y*100}%`,width:`${J.w*100}%`,height:be?"auto":`${J.h*100}%`,zIndex:20+(G.z[ge]||0)}:{flexGrow:ke.height,flexBasis:0},onPointerDown:J?()=>Le(ge):void 0,onDragOver:ye=>{if(!Np(ye.dataTransfer))return;if(J){ye.stopPropagation();return}ye.preventDefault(),ye.stopPropagation();const ot=TI(ye.clientX,ye.clientY,ye.currentTarget.getBoundingClientRect());E&&E.col===pe&&E.row===We&&E.quadrant===ot||F({col:pe,row:We,quadrant:ot,from:E==null?void 0:E.from,ghost:{x:ye.clientX,y:ye.clientY}})},children:[l.jsx(jI,{session:ke.session,node:ke.node,ownerId:ke.ownerId,cellName:wt,token:n,readonly:s,focused:a===ge,onFocus:c,onClose:xe,onOpenSingle:u,floating:!!J,minimized:be,takeSize:!!J,onDetach:J?void 0:ue,onReattach:J?ye=>e(EP(t,ye)):void 0,onToggleMinimize:J?Ie:void 0,onFloatDragStart:J?ye=>fe(ye,ge):void 0,onDragTileStart:J?void 0:ye=>F(ot=>ot?{...ot,from:ye}:{from:ye}),available:ke.unavailable!==!0,stale:ke.stale===!0,alive:De,sessionAlive:He,presence:Ze,fontSize:ke.fontSize,onZoom:ye=>e(MP(t,pe,We,ye)),decks:v,currentDeck:_,onSendToDeck:b,panelUrl:W,panelCellId:ee,panelPort:kc(ke.node?ke.node.split("/"):[],S,R)}),!J&&E&&E.col===pe&&E.row===We&&E.quadrant&&l.jsx(II,{active:E.quadrant}),J&&!be&&["n","s","e","w","se"].map(ye=>l.jsx("div",{className:`nc-float-rz ${ye}`,"data-testid":`float-resize-${ye}`,onPointerDown:ot=>Ee(ot,ge,ye)},`rz-${ye}`))]},ge)),We<Y.tiles.length-1&&Ne.push(l.jsx("div",{className:`nc-divider-h${$&&$.kind==="row"&&$.ci===pe&&$.ri===We?" dragging":""}`,title:p("grid-resize-rows"),onPointerDown:ye=>de(ye,pe,We),onDoubleClick:()=>ie(pe,We)},`h${We}`)),Ne})},`c${pe}`)),pe<A-1&&!U(Y)&&!U(t.columns[pe+1])&&Ae.push(l.jsx("div",{className:`nc-divider-v${$&&$.kind==="col"&&$.ci===pe?" dragging":""}`,title:p("grid-resize-cols"),onPointerDown:ke=>Z(ke,pe),onDoubleClick:()=>me(pe)},`v${pe}`)),Ae}),$&&l.jsx("div",{className:`nc-gesture-shield ${$.kind==="col"?"col":"row"}`,"data-testid":"nc-gesture-shield"}),$&&$.kind==="col"&&hc.map(Y=>l.jsx("div",{className:"nc-gesture-ghost v",style:{left:$.coupleLeft+Y*$.couplePx}},`ghost-v-${Y}`)),$&&$.kind==="row"&&hc.map(Y=>l.jsx("div",{className:"nc-gesture-ghost h",style:{top:$.coupleTop+Y*$.couplePx,left:$.colLeft,width:$.colWidth}},`ghost-h-${Y}`)),$&&$.kind==="col"&&l.jsx("div",{className:`nc-gesture-guide v${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{left:$.coupleLeft+$.live.border}}),$&&$.kind==="row"&&l.jsx("div",{className:`nc-gesture-guide h${$.live.snapped?" snap":""}`,"data-testid":"nc-gesture-guide",style:{top:$.coupleTop+$.live.border,left:$.colLeft,width:$.colWidth}}),$&&l.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:$.kind==="col"?{left:$.coupleLeft+$.live.border,top:"50%"}:{top:$.coupleTop+$.live.border,left:"50%"},children:[$.fsA,$.fsB].map((Y,pe)=>{const Ae=pe===0?$.live.border:$.couplePx-$.live.border,ke=Math.max(1,Y*.6),We=Math.max(1,Y*1.2),Ne=$.kind==="col"?`${Math.round(Ae/ke)}×${Math.round($.pxOther/We)}`:`${Math.round($.pxOther/ke)}×${Math.round(Ae/We)}`;return l.jsx("span",{className:"nc-gesture-chip",children:Ne},pe)})}),K&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:`nc-gesture-shield ${K.kind==="resize"?"row":"col"}`,"data-testid":"nc-gesture-shield"}),K.live.snappedX&&l.jsx("div",{className:"nc-float-snap v",style:{left:`${K.live.x*100}%`}}),K.live.snappedY&&l.jsx("div",{className:"nc-float-snap h",style:{top:`${K.live.y*100}%`}}),K.kind==="resize"&&(()=>{const Y=Z0(t,K.key)||_i,pe=Math.max(1,Y*.6),Ae=Math.max(1,Y*1.2);return l.jsx("div",{className:"nc-gesture-badge","data-testid":"nc-gesture-badge",style:{left:`${(K.live.x+K.live.w/2)*100}%`,top:`${(K.live.y+K.live.h)*100}%`},children:l.jsx("span",{className:"nc-gesture-chip",children:`${Math.round(K.live.w*window.innerWidth/pe)}×${Math.round(K.live.h*window.innerHeight/Ae)}`})})})()]}),E&&E.from&&E.ghost&&(()=>{const Y=t.columns.flatMap(Ae=>Ae.tiles).find(Ae=>$t(Ae)===E.from),pe=Y?Rc({session:Y.session,node:Y.node,ownerId:Y.ownerId,cells:L,nodeGroups:C,cell:Lg({session:Y.session,node:Y.node,ownerId:Y.ownerId,cells:L,nodeGroups:C})}):E.from;return l.jsxs("div",{className:"nc-drag-ghost","data-testid":"nc-drag-ghost",style:{left:E.ghost.x,top:E.ghost.y},children:[l.jsxs("div",{className:"nc-drag-ghost-head",children:[l.jsx("span",{className:"nc-dot on"}),l.jsx("b",{children:pe})]}),l.jsx("div",{className:"nc-drag-ghost-body"})]})})(),H&&l.jsx("div",{className:"nc-drop-line-v nc-drop-line-end"}),A===0&&l.jsx("div",{className:"nc-grid-empty",children:p("grid-empty")})]})}const Xi="local",Ws=/^[a-f0-9]{16,64}$/,gC=3,Da=new Map,no=new Map,eS=128;function OI(t){const e=new Set;for(const n of Array.isArray(t)?t:[])!n||!Ws.test(String(n.instanceId||""))||!Array.isArray(n.route)||(e.add(n.instanceId),no.set(n.instanceId,[...n.route]),Da.set(n.instanceId,0));for(const n of[...no.keys()]){if(e.has(n))continue;const s=(Da.get(n)||0)+1;Da.set(n,s),s>gC+32&&(Da.delete(n),no.delete(n))}if(no.size>eS)for(const n of[...no.keys()].slice(0,no.size-eS))Da.delete(n),no.delete(n)}function Vo(t,e){return`${t&&Ws.test(t)?t:Xi}:${e}`}function Hc(t){const e=String(t||""),n=e.indexOf(":");if(n<1)return null;const s=e.slice(0,n),i=e.slice(n+1);return s!==Xi&&!Ws.test(s)||!/^[a-z0-9-]{1,32}$/.test(i)?null:{ownerId:s===Xi?null:s,name:i}}function Lc(t){return Array.isArray(t)&&t.length?t.join("/"):""}function Dv(t){return{columns:Pi(t).columns.map(e=>({width:e.width,tiles:e.tiles.map(n=>({...n}))}))}}function BI(t){const e=new Map;for(const n of Array.isArray(t)?t:[])n&&Ws.test(String(n.instanceId||""))&&Array.isArray(n.route)&&e.set(Lc(n.route),n.instanceId);return e}function $I(t){const e=new Map;for(const n of Array.isArray(t)?t:[])n&&Ws.test(String(n.instanceId||""))&&Array.isArray(n.route)&&e.set(n.instanceId,[...n.route]);return e}function Ag(t,e,n=[]){const s=Dv(t),i=BI(n);for(const a of s.columns)for(const c of a.tiles)c.ownerId||(!c.node&&Ws.test(String(e||""))?c.ownerId=e:c.node&&i.has(c.node)&&(c.ownerId=i.get(c.node)));return s}function Xl(t,e){const n=Hc(t);return!n||!n.ownerId||!e||n.ownerId!==e?t:Vo(null,n.name)}function Ha(t,e,n=[]){const s=Dv(t),i=new Map,a=new Set;for(const c of n)c&&Ws.test(String(c.instanceId||""))&&Array.isArray(c.route)&&(i.set(c.instanceId,[...c.route]),c.stale===!0&&a.add(c.instanceId));for(const c of s.columns)for(const u of c.tiles)if(u.ownerId)if(u.ownerId===e)delete u.node,delete u.unavailable,delete u.stale;else if(i.has(u.ownerId))u.node=Lc(i.get(u.ownerId)),delete u.unavailable,a.has(u.ownerId)?u.stale=!0:delete u.stale;else{const h=Da.get(u.ownerId),f=no.get(u.ownerId);f&&h!==void 0&&h<gC?(u.node=Lc(f),delete u.unavailable,u.stale=!0):(u.unavailable=!0,delete u.stale)}return s}function Jl(t,e,n=[]){const s=Dv(t),i=$I(n);for(const a of s.columns)for(const c of a.tiles)delete c.unavailable,delete c.stale,c.ownerId&&(c.ownerId===e?delete c.node:i.has(c.ownerId)&&(c.node=Lc(i.get(c.ownerId))));return s}function vC(t,e,n=[]){const s=Cr(t);if(!s)return null;if(s.ownerId)return s;if(!s.node)return{...s,...Ws.test(String(e||""))?{ownerId:e}:{}};const i=n.find(a=>Lc(a&&a.route)===s.node);return{...s,...i&&Ws.test(String(i.instanceId||""))?{ownerId:i.instanceId}:{}}}const zI=/^[a-z0-9-]{1,32}$/,ti="main",_C="nc_decks",yC="nc_deck_order_v1",wC=24;function tS(t){return typeof t!="string"?"":t.normalize("NFKD").replace(/[\u0300-\u036f]/g,"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,32).replace(/-+$/,"")}function Xa(t){return typeof t=="string"&&zI.test(t)}function FI(t){const e=String(t||"").match(/^\/deck\/([^/]+)\/?$/);if(e){let n;try{n=decodeURIComponent(e[1])}catch{n=e[1]}return Xa(n)?n:ti}return ti}function HI(t){const e=String(t||"").match(/^\/deck\/([^/]+)\/([^/]+)\/?$/);if(e){let s,i;try{s=decodeURIComponent(e[1]),i=decodeURIComponent(e[2])}catch{return{id:Vo(null,ti),ownerId:null,name:ti}}if(Ws.test(s)&&Xa(i))return{id:Vo(s,i),ownerId:s,name:i}}const n=FI(t);return{id:Vo(null,n),ownerId:null,name:n}}function Lp(t,e){const n=typeof t=="object"&&t?{ownerId:t.ownerId||null,name:t.name}:Hc(t)||{ownerId:null,name:t},s=Xa(n.name)?n.name:ti,i=n.ownerId?`/deck/${encodeURIComponent(n.ownerId)}/${encodeURIComponent(s)}`:s===ti?"/":`/deck/${encodeURIComponent(s)}`;return e?`${i}#token=${encodeURIComponent(e)}`:i}function bC(t){return t===ti?"nc_grid_v1":`nc_grid_v1__${t}`}function SC(t){const e=[ti];if(Array.isArray(t)){for(const n of t)if(Xa(n)&&n!==ti&&!e.includes(n)&&e.push(n),e.length>=wC)break}return e}function nl(){return typeof localStorage<"u"?localStorage:null}function UI(){const t=nl();if(!t)return[ti];try{return SC(JSON.parse(t.getItem(_C)||"null"))}catch{return[ti]}}function WI(t){const e=nl();if(e)try{e.setItem(_C,JSON.stringify(SC(t)))}catch{}}function Uc(t){return t==="local"||Ws.test(String(t||""))}function hh(t,e){const n=Hc(t);return!!n&&(n.ownerId||"local")===e}function tr(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};for(const[n,s]of Object.entries(t).slice(0,64)){if(!Uc(n)||!Array.isArray(s))continue;const i=[...new Set(s.filter(a=>typeof a=="string"&&a.length<=100&&hh(a,n)))].slice(0,wC);i.length&&(e[n]=i)}return e}function Ql(t=nl()){if(!t)return{};try{return tr(JSON.parse(t.getItem(yC)||"null"))}catch{return{}}}function Ap(t,e=nl()){const n=tr(t);if(e)try{e.setItem(yC,JSON.stringify(n))}catch{}return n}function fh(t,e){return Array.isArray(t==null?void 0:t[e])?t[e]:[]}function qI(t,e,n,s,i=[]){if(!Uc(e)||n===s)return tr(t);const a=[...new Set(i.filter(v=>hh(v,e)))];if(!a.includes(n)||!a.includes(s))return tr(t);const c=fh(t,e).filter(v=>a.includes(v)),u=[...c,...a.filter(v=>!c.includes(v))],h=u.indexOf(n),f=u.indexOf(s);u.splice(h,1);const g=u.indexOf(s);return u.splice(h<f?g+1:g,0,n),tr({...t,[e]:u})}function KI(t,e,n,s){if(!Uc(e)||!hh(s,e))return tr(t);const i=fh(t,e);return i.includes(n)?tr({...t,[e]:i.map(a=>a===n?s:a)}):tr(t)}function VI(t,e,n){return Uc(e)?tr({...t,[e]:fh(t,e).filter(s=>s!==n)}):tr(t)}function jp(t,e={},n=[]){const s=new Map,i=new Map;for(const h of Array.isArray(t)?t:[]){const f=h!=null&&h.local?"local":String((h==null?void 0:h.ownerId)||"");!Uc(f)||!hh(h==null?void 0:h.id,f)||(s.has(f)||s.set(f,[]),i.has(f)||i.set(f,i.size),s.get(f).push(h))}const a=new Map;(Array.isArray(n)?n:[]).forEach((h,f)=>{typeof h=="string"&&!a.has(h)&&a.set(h,f)});const c=h=>{if(h==="local")return-1;const f=a.get(`id:${h}`);return f===void 0?Number.MAX_SAFE_INTEGER:f},u=[];for(const h of[...s.keys()].sort((f,g)=>c(f)-c(g)||i.get(f)-i.get(g))){const f=s.get(h),g=fh(e,h),v=new Map(g.map((_,b)=>[_,b]));f.sort((_,b)=>{const x=v.has(_.id)?v.get(_.id):Number.MAX_SAFE_INTEGER,L=v.has(b.id)?v.get(b.id):Number.MAX_SAFE_INTEGER;return x-L}),u.push(...f)}return u}function jg(t){const e=nl();if(!e)return null;try{return JSON.parse(e.getItem(bC(t))||"null")}catch{return null}}function YI(t,e){const n=nl();if(n)try{n.setItem(bC(t),JSON.stringify(e))}catch{}}const Ov="nc_deckbar_collapsed_v1",xC=64;function Bv(t){return t===Xi||Ws.test(String(t||""))}function $v(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;for(const[s,i]of Object.entries(t)){if(n>=xC)break;if(Bv(s)){if(i===!0)e[s]=!0;else if(i===!1)e[s]=!1;else continue;n+=1}}return e}function kC(t,e){return Bv(e)&&Object.prototype.hasOwnProperty.call(t||{},e)?t[e]===!0:!0}function GI(t,e){const n=$v(t);return Bv(e)&&(!Object.prototype.hasOwnProperty.call(n,e)&&Object.keys(n).length>=xC&&delete n[Object.keys(n)[0]],n[e]=!kC(n,e)),n}function CC(){return typeof localStorage<"u"?localStorage:null}function nS(t=CC()){if(!t)return{};try{return $v(JSON.parse(t.getItem(Ov)||"null"))}catch{return{}}}function XI(t,e=CC()){const n=$v(t);if(e)try{e.setItem(Ov,JSON.stringify(n))}catch{}return n}function JI(){const[t,e]=w.useState(nS);w.useEffect(()=>{const i=a=>{(a.key===Ov||a.key===null)&&e(nS())};return window.addEventListener("storage",i),()=>window.removeEventListener("storage",i)},[]);const n=w.useCallback(i=>kC(t,i),[t]),s=w.useCallback(i=>{e(a=>XI(GI(a,i)))},[]);return{collapsed:t,isCollapsed:n,toggle:s}}const zv="nc_deck_presence_v1",sS=3e4,QI=18e4,EC=1e4,NC=32,ZI=/^[A-Za-z0-9_-]{1,64}$/,eD=new Set([...Object.getOwnPropertyNames(Object.prototype),"prototype"]),iS="working",tD="on",nD="neutral",sD="warn";function Fv(t){return typeof t=="string"&&ZI.test(t)&&!eD.has(t)}function RC(t){return typeof t=="string"&&Hc(t)!==null}function Hv(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0}function Ja(t){if(!t||typeof t!="object"||Array.isArray(t))return{};const e={};let n=0;for(const[s,i]of Object.entries(t)){if(n>=NC)break;Fv(s)&&(!i||typeof i!="object"||RC(i.deckId)&&Hv(i.ts)&&(e[s]={deckId:i.deckId,ts:i.ts,focus:i.focus===!0,visible:i.visible===!0},n+=1))}return e}function LC(t,e){const n=Ja(t);if(!Hv(e))return n;const s={};for(const[i,a]of Object.entries(n)){const c=a.visible?sS:QI,u=e-c;a.ts>=u&&a.ts<=e+sS&&(s[i]=a)}return s}function rS(t,e,n,s){if(!Fv(e)||!Hv(s))return Ja(t);const i=LC(t,s);if(!RC(n==null?void 0:n.deckId))return i;if(!Object.prototype.hasOwnProperty.call(i,e)&&Object.keys(i).length>=NC){let a="",c=1/0;for(const[u,h]of Object.entries(i))h.ts<c&&(a=u,c=h.ts);a&&delete i[a]}return i[e]={deckId:n.deckId,ts:s,focus:(n==null?void 0:n.focus)===!0,visible:(n==null?void 0:n.visible)===!0},Ja(i)}function iD(t,e){const n=Ja(t);if(!Fv(e))return n;const s={...n};return delete s[e],s}function rD(t,e){const n=LC(t,e),s={};for(const i of Object.values(n)){const a=i.focus&&i.visible?iS:tD;s[i.deckId]!==iS&&(s[i.deckId]=a)}return s}function AC(){return typeof localStorage<"u"?localStorage:null}function td(t=AC()){if(!t)return{};try{return Ja(JSON.parse(t.getItem(zv)||"null"))}catch{return{}}}function Mp(t,e=AC()){const n=Ja(t);if(e)try{e.setItem(zv,JSON.stringify(n))}catch{}return n}const oD=Math.min(EC,5e3);function aD(){var t,e;try{const n=(e=(t=globalThis.crypto)==null?void 0:t.randomUUID)==null?void 0:e.call(t);if(n)return`w${n.replaceAll("-","")}`}catch{}return`w${Date.now().toString(36)}${Math.random().toString(36).slice(2,14)}`}const lD=aD();function oS(){const t=typeof document<"u"&&typeof document.hasFocus=="function"?document.hasFocus():!0,e=typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState!=="hidden":!0;return{focus:t,visible:e}}function cD(t,e=!0){const s=w.useRef(lD).current,i=w.useRef(t);i.current=t;const[a,c]=w.useState(()=>({map:{},now:Date.now()})),u=w.useCallback(()=>{c({map:td(),now:Date.now()})},[]);w.useEffect(()=>{if(!e)return;const g=()=>{const C=Date.now(),R=rS(td(),s,{deckId:i.current,...oS()},C);return Mp(R),{map:R,now:C}},v=()=>c(g());v();const _=setInterval(g,EC),b=setInterval(u,oD),x=v,L=C=>{(C.key===zv||C.key===null)&&u()};return window.addEventListener("focus",x),window.addEventListener("blur",x),typeof document<"u"&&document.addEventListener("visibilitychange",x),window.addEventListener("storage",L),()=>{clearInterval(_),clearInterval(b),window.removeEventListener("focus",x),window.removeEventListener("blur",x),typeof document<"u"&&document.removeEventListener("visibilitychange",x),window.removeEventListener("storage",L);try{Mp(iD(td(),s))}catch{}}},[e,s,u]),w.useEffect(()=>{if(!e)return;const g=Date.now(),v=rS(td(),s,{deckId:t,...oS()},g);Mp(v),c({map:v,now:g})},[t,e,s]);const h=w.useMemo(()=>e?rD(a.map,a.now):{},[e,a]);return{dotFor:w.useCallback((g,v=!1)=>e?v?sD:h[g]||nD:null,[h,e]),windowId:s}}const aS=52,lS=18;function uD({ownerKey:t,deckId:e,label:n,onMove:s,onStep:i}){const a=w.useRef(null),c=w.useRef(0),[u,h]=w.useState(!1),f=()=>{var L,C,R,S;const x=a.current;(C=(L=x==null?void 0:x.over)==null?void 0:L.classList)==null||C.remove("nc-deck-over"),(S=(R=x==null?void 0:x.source)==null?void 0:R.classList)==null||S.remove("nc-deck-dragging"),c.current&&cancelAnimationFrame(c.current),c.current=0},g=(x=!1)=>{const L=a.current;if(!L)return;const C=L.target;f(),a.current=null,h(!1);try{L.handle.releasePointerCapture(L.pointerId)}catch{}x&&C&&C!==e&&s(e,C)},v=(x,L)=>{var E,F,$,X,V,G,ne,K;const C=a.current;if(!C)return;C.x=x,C.y=L;const R=(F=(E=document.elementFromPoint(x,L))==null?void 0:E.closest)==null?void 0:F.call(E,"[data-deck-id][data-owner-key]"),S=($=R==null?void 0:R.dataset)==null?void 0:$.deckId,I=((X=R==null?void 0:R.dataset)==null?void 0:X.ownerKey)===t&&S&&S!==e;C.over!==(I?R:null)&&((G=(V=C.over)==null?void 0:V.classList)==null||G.remove("nc-deck-over"),C.over=I?R:null,(K=(ne=C.over)==null?void 0:ne.classList)==null||K.add("nc-deck-over")),C.target=I?S:null},_=()=>{var C,R;const x=a.current;if(!x){c.current=0;return}const L=(R=(C=x.container)==null?void 0:C.getBoundingClientRect)==null?void 0:R.call(C);if(L){const S=x.x<L.left+aS?-lS:x.x>L.right-aS?lS:0;S&&(x.container.scrollLeft+=S,v(x.x,x.y))}c.current=requestAnimationFrame(_)};w.useEffect(()=>{const x=C=>{C.key==="Escape"&&a.current&&(C.preventDefault(),g(!1))},L=()=>g(!1);return window.addEventListener("keydown",x),window.addEventListener("blur",L),()=>{window.removeEventListener("keydown",x),window.removeEventListener("blur",L),f(),a.current=null}},[e,t]);const b=x=>{var R;if(x.pointerType==="mouse"&&x.button!==0)return;x.preventDefault(),x.stopPropagation(),x.currentTarget.focus({preventScroll:!0});const L=x.currentTarget.closest("[data-deck-id][data-owner-key]"),C=x.currentTarget.closest(".nc-deckbar");a.current={pointerId:x.pointerId,handle:x.currentTarget,source:L,container:C,target:null,over:null,x:x.clientX,y:x.clientY},(R=L==null?void 0:L.classList)==null||R.add("nc-deck-dragging");try{x.currentTarget.setPointerCapture(x.pointerId)}catch{}h(!0),c.current=requestAnimationFrame(_)};return l.jsx("button",{type:"button",className:`nc-deck-handle${u?" active":""}`,"aria-label":`${p("reorder")} ${n}`,"aria-keyshortcuts":"ArrowLeft ArrowRight",title:p("reorder-deck-help"),onClick:x=>{x.preventDefault(),x.stopPropagation()},onDragStart:x=>x.preventDefault(),onKeyDown:x=>{x.key!=="ArrowLeft"&&x.key!=="ArrowRight"||(x.preventDefault(),x.stopPropagation(),i(x.key==="ArrowLeft"?-1:1))},onPointerDown:b,onPointerMove:x=>{!a.current||x.pointerId!==a.current.pointerId||(x.preventDefault(),x.stopPropagation(),v(x.clientX,x.clientY))},onPointerUp:x=>{!a.current||x.pointerId!==a.current.pointerId||(x.preventDefault(),x.stopPropagation(),g(!0))},onPointerCancel:()=>g(!1),onLostPointerCapture:()=>{a.current&&g(!1)},children:"↔"})}function dD({decks:t=[],currentDeck:e="local:main",onCreate:n,onRename:s,onDelete:i,onReorder:a,onOpenWindow:c,onNavigate:u,saveState:h="idle",error:f="",sidebarVisible:g,onToggleSidebar:v,conflict:_=!1,onReloadDeck:b=null}){zn();const{isCollapsed:x,toggle:L}=JI(),{dotFor:C}=cD(e),[R,S]=w.useState(null),[I,E]=w.useState(""),[F,$]=w.useState(!1),[X,V]=w.useState(""),[G,ne]=w.useState(""),K=tS(I),D=Xa(K),P=[];for(const A of t){const N=A.local?"local":A.ownerId;let U=P.find(T=>T.key===N);U||(U={key:N,label:A.ownerLabel||(A.local?"Local":N),local:!!A.local,decks:[]},P.push(U)),U.decks.push(A)}const O=async()=>{if(D){$(!0),V("");try{n&&await n(K,R),E(""),S(null)}catch(A){V(String(A.message||A))}$(!1)}},j=A=>{ne(""),c&&c(A.id)||ne(A.id)},z=async A=>{if(!(A.id===e||!u||F||A.available===!1)){$(!0),V("");try{await u(A.id)}catch(N){V(String((N==null?void 0:N.message)||N))}$(!1)}},M=(A,N,U)=>{const T=A.decks.findIndex(se=>se.id===N.id),H=A.decks[T+U];T>=0&&H&&a&&!F&&a(N.id,H.id)};return l.jsxs("div",{className:"nc-deckbar",children:[v&&l.jsx("button",{className:"nc-deck-sidebar-toggle",title:p("toggle-sidebar"),onClick:v,children:g?"◀":"☰"}),l.jsx("span",{className:"nc-deckbar-label",children:p("decks")}),l.jsx("div",{className:"nc-deck-chips",children:P.map(A=>{const N=x(A.key),U=`nc-deck-content-${A.key}`,T=A.local?"Local":A.label,H=A.decks.some(Z=>Z.id===e),se=(A.decks.find(Z=>Z.id===e)||{}).name,Q=p(A.decks.length===1?"owner-deck-count-one":"owner-deck-count-many").replace("{count}",A.decks.length);return l.jsxs("span",{className:`nc-deck-owner-group${N?" collapsed":""}`,"data-owner-key":A.key,"data-collapsed":N?"1":"0",children:[l.jsxs("button",{type:"button",className:"nc-deck-owner-toggle","aria-expanded":!N,"aria-controls":U,title:p(N?"expand-owner":"collapse-owner").replace("{owner}",T),onClick:()=>{!N&&R===A.key&&(E(""),S(null)),L(A.key)},children:[l.jsx("span",{className:"nc-deck-owner-caret","aria-hidden":"true",children:N?"▸":"▾"}),l.jsx("span",{className:"nc-deck-owner",children:T})]}),N&&l.jsxs("span",{className:"nc-deck-summary",title:Q,children:[l.jsx("span",{className:"nc-deck-summary-count",children:A.decks.length}),H&&l.jsxs("span",{className:"nc-deck-summary-current",children:["• ",se]})]}),l.jsxs("span",{id:U,className:"nc-deck-owner-content",hidden:N,children:[A.decks.map(Z=>{const me=C(Z.id,Z.available===!1);return l.jsxs("span",{"data-deck-id":Z.id,"data-owner-key":A.key,className:`nc-deck-chip${Z.id===e?" current":""}${Z.available===!1?" offline":""}`,children:[me&&l.jsx(hD,{state:me}),l.jsx(uD,{ownerKey:A.key,deckId:Z.id,label:`${A.label} · ${Z.name}`,onMove:(de,ie)=>{a&&!F&&a(de,ie)},onStep:de=>M(A,Z,de)}),l.jsxs("button",{className:"nc-deck-open",title:Z.available===!1?`${Z.ownerLabel} offline${Z.refreshFailedAt?" · aggiornamento in ritardo":""}`:Z.id===e?p("deck-current"):`${Z.ownerLabel} · ${Z.name}`,disabled:F||Z.available===!1,onClick:()=>z(Z),children:[Z.name,Z.id===e?" •":""]}),Z.available!==!1&&Z.stale===!0&&Z.refreshFailedAt?l.jsx("span",{className:"nc-deck-stale",title:`${Z.ownerLabel} · ${p("deck-stale")}`,children:p("deck-stale-badge")}):null,l.jsx("button",{className:"nc-deck-mini",disabled:Z.available===!1,title:p("detach-deck"),onClick:()=>j(Z),children:"↗"}),Z.name!==ti&&l.jsxs(l.Fragment,{children:[l.jsx("button",{className:"nc-deck-mini",disabled:Z.available===!1,title:p("rename-deck"),onClick:()=>{const de=(typeof window<"u"?window.prompt(p("rename-deck"),Z.name):"")||"",ie=tS(de);Xa(ie)&&ie!==Z.name&&s&&s(Z.id,ie).catch(xe=>V(String(xe.message||xe)))},children:"✎"}),l.jsx("button",{className:"nc-deck-mini nc-deck-del",disabled:Z.available===!1,title:p("delete-deck"),onClick:()=>{(typeof window>"u"||window.confirm(p("delete-deck-confirm").replace("{name}",`${Z.ownerLabel} · ${Z.name}`)))&&i&&i(Z.id).catch(de=>V(String(de.message||de)))},children:"✕"})]})]},Z.id)}),R===A.key?l.jsxs("span",{className:"nc-deck-add",children:[l.jsx("input",{autoFocus:!0,className:D||!I?"":"invalid",placeholder:p("deck-name"),value:I,onChange:Z=>E(Z.target.value),onKeyDown:Z=>{Z.key==="Enter"&&O(),Z.key==="Escape"&&(E(""),S(null))}}),I&&D&&K!==I&&l.jsxs("span",{className:"nc-deck-slug",children:["→ ",K]}),l.jsx("button",{className:"nc-deck-ok",disabled:!D||F,onClick:O,children:p("create")}),l.jsx("button",{className:"nc-deck-cancel",onClick:()=>{E(""),S(null)},children:p("cancel")})]}):l.jsxs("button",{className:"nc-deck-newbtn",disabled:F||A.decks.every(Z=>Z.available===!1),title:`${p("new-deck")} · ${A.label}`,onClick:()=>{E(""),S(A.key)},children:["+ ",p("new")]})]})]},A.key)})}),l.jsx("span",{className:`nc-deck-state ${h}`,title:p("deck-autosave"),children:p(h==="saving"?"saving":h==="saved"?"saved":"deck-autosave")}),(X||f)&&l.jsx("span",{className:"nc-deck-error",children:X||f}),_&&b&&l.jsx("button",{className:"nc-deck-reload",onClick:b,children:p("reload")}),G&&l.jsx("button",{className:"nc-deck-fallback",onClick:()=>c&&c(G),children:p("popup-blocked")})]})}function hD({state:t}){if(!t)return null;const e=p(`dot-${t}`);return l.jsx("span",{className:`nc-deck-dot ${t}`,role:"img","aria-label":e,title:e})}var Pa={},Tp,cS;function fD(){return cS||(cS=1,Tp=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}),Tp}var Pp={},Jr={},uS;function ea(){if(uS)return Jr;uS=1;let t;const e=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];return Jr.getSymbolSize=function(s){if(!s)throw new Error('"version" cannot be null or undefined');if(s<1||s>40)throw new Error('"version" should be in range from 1 to 40');return s*4+17},Jr.getSymbolTotalCodewords=function(s){return e[s]},Jr.getBCHDigit=function(n){let s=0;for(;n!==0;)s++,n>>>=1;return s},Jr.setToSJISFunction=function(s){if(typeof s!="function")throw new Error('"toSJISFunc" is not a valid function.');t=s},Jr.isKanjiModeEnabled=function(){return typeof t<"u"},Jr.toSJIS=function(s){return t(s)},Jr}var Ip={},dS;function Uv(){return dS||(dS=1,(function(t){t.L={bit:1},t.M={bit:0},t.Q={bit:3},t.H={bit:2};function e(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return t.L;case"m":case"medium":return t.M;case"q":case"quartile":return t.Q;case"h":case"high":return t.H;default:throw new Error("Unknown EC Level: "+n)}}t.isValid=function(s){return s&&typeof s.bit<"u"&&s.bit>=0&&s.bit<4},t.from=function(s,i){if(t.isValid(s))return s;try{return e(s)}catch{return i}}})(Ip)),Ip}var Dp,hS;function pD(){if(hS)return Dp;hS=1;function t(){this.buffer=[],this.length=0}return t.prototype={get:function(e){const n=Math.floor(e/8);return(this.buffer[n]>>>7-e%8&1)===1},put:function(e,n){for(let s=0;s<n;s++)this.putBit((e>>>n-s-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(e){const n=Math.floor(this.length/8);this.buffer.length<=n&&this.buffer.push(0),e&&(this.buffer[n]|=128>>>this.length%8),this.length++}},Dp=t,Dp}var Op,fS;function mD(){if(fS)return Op;fS=1;function t(e){if(!e||e<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=e,this.data=new Uint8Array(e*e),this.reservedBit=new Uint8Array(e*e)}return t.prototype.set=function(e,n,s,i){const a=e*this.size+n;this.data[a]=s,i&&(this.reservedBit[a]=!0)},t.prototype.get=function(e,n){return this.data[e*this.size+n]},t.prototype.xor=function(e,n,s){this.data[e*this.size+n]^=s},t.prototype.isReserved=function(e,n){return this.reservedBit[e*this.size+n]},Op=t,Op}var Bp={},pS;function gD(){return pS||(pS=1,(function(t){const e=ea().getSymbolSize;t.getRowColCoords=function(s){if(s===1)return[];const i=Math.floor(s/7)+2,a=e(s),c=a===145?26:Math.ceil((a-13)/(2*i-2))*2,u=[a-7];for(let h=1;h<i-1;h++)u[h]=u[h-1]-c;return u.push(6),u.reverse()},t.getPositions=function(s){const i=[],a=t.getRowColCoords(s),c=a.length;for(let u=0;u<c;u++)for(let h=0;h<c;h++)u===0&&h===0||u===0&&h===c-1||u===c-1&&h===0||i.push([a[u],a[h]]);return i}})(Bp)),Bp}var $p={},mS;function vD(){if(mS)return $p;mS=1;const t=ea().getSymbolSize,e=7;return $p.getPositions=function(s){const i=t(s);return[[0,0],[i-e,0],[0,i-e]]},$p}var zp={},gS;function _D(){return gS||(gS=1,(function(t){t.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};const e={N1:3,N2:3,N3:40,N4:10};t.isValid=function(i){return i!=null&&i!==""&&!isNaN(i)&&i>=0&&i<=7},t.from=function(i){return t.isValid(i)?parseInt(i,10):void 0},t.getPenaltyN1=function(i){const a=i.size;let c=0,u=0,h=0,f=null,g=null;for(let v=0;v<a;v++){u=h=0,f=g=null;for(let _=0;_<a;_++){let b=i.get(v,_);b===f?u++:(u>=5&&(c+=e.N1+(u-5)),f=b,u=1),b=i.get(_,v),b===g?h++:(h>=5&&(c+=e.N1+(h-5)),g=b,h=1)}u>=5&&(c+=e.N1+(u-5)),h>=5&&(c+=e.N1+(h-5))}return c},t.getPenaltyN2=function(i){const a=i.size;let c=0;for(let u=0;u<a-1;u++)for(let h=0;h<a-1;h++){const f=i.get(u,h)+i.get(u,h+1)+i.get(u+1,h)+i.get(u+1,h+1);(f===4||f===0)&&c++}return c*e.N2},t.getPenaltyN3=function(i){const a=i.size;let c=0,u=0,h=0;for(let f=0;f<a;f++){u=h=0;for(let g=0;g<a;g++)u=u<<1&2047|i.get(f,g),g>=10&&(u===1488||u===93)&&c++,h=h<<1&2047|i.get(g,f),g>=10&&(h===1488||h===93)&&c++}return c*e.N3},t.getPenaltyN4=function(i){let a=0;const c=i.data.length;for(let h=0;h<c;h++)a+=i.data[h];return Math.abs(Math.ceil(a*100/c/5)-10)*e.N4};function n(s,i,a){switch(s){case t.Patterns.PATTERN000:return(i+a)%2===0;case t.Patterns.PATTERN001:return i%2===0;case t.Patterns.PATTERN010:return a%3===0;case t.Patterns.PATTERN011:return(i+a)%3===0;case t.Patterns.PATTERN100:return(Math.floor(i/2)+Math.floor(a/3))%2===0;case t.Patterns.PATTERN101:return i*a%2+i*a%3===0;case t.Patterns.PATTERN110:return(i*a%2+i*a%3)%2===0;case t.Patterns.PATTERN111:return(i*a%3+(i+a)%2)%2===0;default:throw new Error("bad maskPattern:"+s)}}t.applyMask=function(i,a){const c=a.size;for(let u=0;u<c;u++)for(let h=0;h<c;h++)a.isReserved(h,u)||a.xor(h,u,n(i,h,u))},t.getBestMask=function(i,a){const c=Object.keys(t.Patterns).length;let u=0,h=1/0;for(let f=0;f<c;f++){a(f),t.applyMask(f,i);const g=t.getPenaltyN1(i)+t.getPenaltyN2(i)+t.getPenaltyN3(i)+t.getPenaltyN4(i);t.applyMask(f,i),g<h&&(h=g,u=f)}return u}})(zp)),zp}var nd={},vS;function jC(){if(vS)return nd;vS=1;const t=Uv(),e=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],n=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];return nd.getBlocksCount=function(i,a){switch(a){case t.L:return e[(i-1)*4+0];case t.M:return e[(i-1)*4+1];case t.Q:return e[(i-1)*4+2];case t.H:return e[(i-1)*4+3];default:return}},nd.getTotalCodewordsCount=function(i,a){switch(a){case t.L:return n[(i-1)*4+0];case t.M:return n[(i-1)*4+1];case t.Q:return n[(i-1)*4+2];case t.H:return n[(i-1)*4+3];default:return}},nd}var Fp={},Zl={},_S;function yD(){if(_S)return Zl;_S=1;const t=new Uint8Array(512),e=new Uint8Array(256);return(function(){let s=1;for(let i=0;i<255;i++)t[i]=s,e[s]=i,s<<=1,s&256&&(s^=285);for(let i=255;i<512;i++)t[i]=t[i-255]})(),Zl.log=function(s){if(s<1)throw new Error("log("+s+")");return e[s]},Zl.exp=function(s){return t[s]},Zl.mul=function(s,i){return s===0||i===0?0:t[e[s]+e[i]]},Zl}var yS;function wD(){return yS||(yS=1,(function(t){const e=yD();t.mul=function(s,i){const a=new Uint8Array(s.length+i.length-1);for(let c=0;c<s.length;c++)for(let u=0;u<i.length;u++)a[c+u]^=e.mul(s[c],i[u]);return a},t.mod=function(s,i){let a=new Uint8Array(s);for(;a.length-i.length>=0;){const c=a[0];for(let h=0;h<i.length;h++)a[h]^=e.mul(i[h],c);let u=0;for(;u<a.length&&a[u]===0;)u++;a=a.slice(u)}return a},t.generateECPolynomial=function(s){let i=new Uint8Array([1]);for(let a=0;a<s;a++)i=t.mul(i,new Uint8Array([1,e.exp(a)]));return i}})(Fp)),Fp}var Hp,wS;function bD(){if(wS)return Hp;wS=1;const t=wD();function e(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}return e.prototype.initialize=function(s){this.degree=s,this.genPoly=t.generateECPolynomial(this.degree)},e.prototype.encode=function(s){if(!this.genPoly)throw new Error("Encoder not initialized");const i=new Uint8Array(s.length+this.degree);i.set(s);const a=t.mod(i,this.genPoly),c=this.degree-a.length;if(c>0){const u=new Uint8Array(this.degree);return u.set(a,c),u}return a},Hp=e,Hp}var Up={},Wp={},qp={},bS;function MC(){return bS||(bS=1,qp.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}),qp}var Ki={},SS;function TC(){if(SS)return Ki;SS=1;const t="[0-9]+",e="[A-Z $%*+\\-./:]+";let n="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";n=n.replace(/u/g,"\\u");const s="(?:(?![A-Z0-9 $%*+\\-./:]|"+n+`)(?:.|[\r
|
|
158
158
|
]))+`;Ki.KANJI=new RegExp(n,"g"),Ki.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g"),Ki.BYTE=new RegExp(s,"g"),Ki.NUMERIC=new RegExp(t,"g"),Ki.ALPHANUMERIC=new RegExp(e,"g");const i=new RegExp("^"+n+"$"),a=new RegExp("^"+t+"$"),c=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");return Ki.testKanji=function(h){return i.test(h)},Ki.testNumeric=function(h){return a.test(h)},Ki.testAlphanumeric=function(h){return c.test(h)},Ki}var xS;function ta(){return xS||(xS=1,(function(t){const e=MC(),n=TC();t.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},t.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},t.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},t.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},t.MIXED={bit:-1},t.getCharCountIndicator=function(a,c){if(!a.ccBits)throw new Error("Invalid mode: "+a);if(!e.isValid(c))throw new Error("Invalid version: "+c);return c>=1&&c<10?a.ccBits[0]:c<27?a.ccBits[1]:a.ccBits[2]},t.getBestModeForData=function(a){return n.testNumeric(a)?t.NUMERIC:n.testAlphanumeric(a)?t.ALPHANUMERIC:n.testKanji(a)?t.KANJI:t.BYTE},t.toString=function(a){if(a&&a.id)return a.id;throw new Error("Invalid mode")},t.isValid=function(a){return a&&a.bit&&a.ccBits};function s(i){if(typeof i!="string")throw new Error("Param is not a string");switch(i.toLowerCase()){case"numeric":return t.NUMERIC;case"alphanumeric":return t.ALPHANUMERIC;case"kanji":return t.KANJI;case"byte":return t.BYTE;default:throw new Error("Unknown mode: "+i)}}t.from=function(a,c){if(t.isValid(a))return a;try{return s(a)}catch{return c}}})(Wp)),Wp}var kS;function SD(){return kS||(kS=1,(function(t){const e=ea(),n=jC(),s=Uv(),i=ta(),a=MC(),c=7973,u=e.getBCHDigit(c);function h(_,b,x){for(let L=1;L<=40;L++)if(b<=t.getCapacity(L,x,_))return L}function f(_,b){return i.getCharCountIndicator(_,b)+4}function g(_,b){let x=0;return _.forEach(function(L){const C=f(L.mode,b);x+=C+L.getBitsLength()}),x}function v(_,b){for(let x=1;x<=40;x++)if(g(_,x)<=t.getCapacity(x,b,i.MIXED))return x}t.from=function(b,x){return a.isValid(b)?parseInt(b,10):x},t.getCapacity=function(b,x,L){if(!a.isValid(b))throw new Error("Invalid QR Code version");typeof L>"u"&&(L=i.BYTE);const C=e.getSymbolTotalCodewords(b),R=n.getTotalCodewordsCount(b,x),S=(C-R)*8;if(L===i.MIXED)return S;const I=S-f(L,b);switch(L){case i.NUMERIC:return Math.floor(I/10*3);case i.ALPHANUMERIC:return Math.floor(I/11*2);case i.KANJI:return Math.floor(I/13);case i.BYTE:default:return Math.floor(I/8)}},t.getBestVersionForData=function(b,x){let L;const C=s.from(x,s.M);if(Array.isArray(b)){if(b.length>1)return v(b,C);if(b.length===0)return 1;L=b[0]}else L=b;return h(L.mode,L.getLength(),C)},t.getEncodedBits=function(b){if(!a.isValid(b)||b<7)throw new Error("Invalid QR Code version");let x=b<<12;for(;e.getBCHDigit(x)-u>=0;)x^=c<<e.getBCHDigit(x)-u;return b<<12|x}})(Up)),Up}var Kp={},CS;function xD(){if(CS)return Kp;CS=1;const t=ea(),e=1335,n=21522,s=t.getBCHDigit(e);return Kp.getEncodedBits=function(a,c){const u=a.bit<<3|c;let h=u<<10;for(;t.getBCHDigit(h)-s>=0;)h^=e<<t.getBCHDigit(h)-s;return(u<<10|h)^n},Kp}var Vp={},Yp,ES;function kD(){if(ES)return Yp;ES=1;const t=ta();function e(n){this.mode=t.NUMERIC,this.data=n.toString()}return e.getBitsLength=function(s){return 10*Math.floor(s/3)+(s%3?s%3*3+1:0)},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(s){let i,a,c;for(i=0;i+3<=this.data.length;i+=3)a=this.data.substr(i,3),c=parseInt(a,10),s.put(c,10);const u=this.data.length-i;u>0&&(a=this.data.substr(i),c=parseInt(a,10),s.put(c,u*3+1))},Yp=e,Yp}var Gp,NS;function CD(){if(NS)return Gp;NS=1;const t=ta(),e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function n(s){this.mode=t.ALPHANUMERIC,this.data=s}return n.getBitsLength=function(i){return 11*Math.floor(i/2)+6*(i%2)},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(i){let a;for(a=0;a+2<=this.data.length;a+=2){let c=e.indexOf(this.data[a])*45;c+=e.indexOf(this.data[a+1]),i.put(c,11)}this.data.length%2&&i.put(e.indexOf(this.data[a]),6)},Gp=n,Gp}var Xp,RS;function ED(){if(RS)return Xp;RS=1;const t=ta();function e(n){this.mode=t.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}return e.getBitsLength=function(s){return s*8},e.prototype.getLength=function(){return this.data.length},e.prototype.getBitsLength=function(){return e.getBitsLength(this.data.length)},e.prototype.write=function(n){for(let s=0,i=this.data.length;s<i;s++)n.put(this.data[s],8)},Xp=e,Xp}var Jp,LS;function ND(){if(LS)return Jp;LS=1;const t=ta(),e=ea();function n(s){this.mode=t.KANJI,this.data=s}return n.getBitsLength=function(i){return i*13},n.prototype.getLength=function(){return this.data.length},n.prototype.getBitsLength=function(){return n.getBitsLength(this.data.length)},n.prototype.write=function(s){let i;for(i=0;i<this.data.length;i++){let a=e.toSJIS(this.data[i]);if(a>=33088&&a<=40956)a-=33088;else if(a>=57408&&a<=60351)a-=49472;else throw new Error("Invalid SJIS character: "+this.data[i]+`
|
|
159
159
|
Make sure your charset is UTF-8`);a=(a>>>8&255)*192+(a&255),s.put(a,13)}},Jp=n,Jp}var Qp={exports:{}},AS;function RD(){return AS||(AS=1,(function(t){var e={single_source_shortest_paths:function(n,s,i){var a={},c={};c[s]=0;var u=e.PriorityQueue.make();u.push(s,0);for(var h,f,g,v,_,b,x,L,C;!u.empty();){h=u.pop(),f=h.value,v=h.cost,_=n[f]||{};for(g in _)_.hasOwnProperty(g)&&(b=_[g],x=v+b,L=c[g],C=typeof c[g]>"u",(C||L>x)&&(c[g]=x,u.push(g,x),a[g]=f))}if(typeof i<"u"&&typeof c[i]>"u"){var R=["Could not find a path from ",s," to ",i,"."].join("");throw new Error(R)}return a},extract_shortest_path_from_predecessor_list:function(n,s){for(var i=[],a=s;a;)i.push(a),n[a],a=n[a];return i.reverse(),i},find_path:function(n,s,i){var a=e.single_source_shortest_paths(n,s,i);return e.extract_shortest_path_from_predecessor_list(a,i)},PriorityQueue:{make:function(n){var s=e.PriorityQueue,i={},a;n=n||{};for(a in s)s.hasOwnProperty(a)&&(i[a]=s[a]);return i.queue=[],i.sorter=n.sorter||s.default_sorter,i},default_sorter:function(n,s){return n.cost-s.cost},push:function(n,s){var i={value:n,cost:s};this.queue.push(i),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};t.exports=e})(Qp)),Qp.exports}var jS;function LD(){return jS||(jS=1,(function(t){const e=ta(),n=kD(),s=CD(),i=ED(),a=ND(),c=TC(),u=ea(),h=RD();function f(R){return unescape(encodeURIComponent(R)).length}function g(R,S,I){const E=[];let F;for(;(F=R.exec(I))!==null;)E.push({data:F[0],index:F.index,mode:S,length:F[0].length});return E}function v(R){const S=g(c.NUMERIC,e.NUMERIC,R),I=g(c.ALPHANUMERIC,e.ALPHANUMERIC,R);let E,F;return u.isKanjiModeEnabled()?(E=g(c.BYTE,e.BYTE,R),F=g(c.KANJI,e.KANJI,R)):(E=g(c.BYTE_KANJI,e.BYTE,R),F=[]),S.concat(I,E,F).sort(function(X,V){return X.index-V.index}).map(function(X){return{data:X.data,mode:X.mode,length:X.length}})}function _(R,S){switch(S){case e.NUMERIC:return n.getBitsLength(R);case e.ALPHANUMERIC:return s.getBitsLength(R);case e.KANJI:return a.getBitsLength(R);case e.BYTE:return i.getBitsLength(R)}}function b(R){return R.reduce(function(S,I){const E=S.length-1>=0?S[S.length-1]:null;return E&&E.mode===I.mode?(S[S.length-1].data+=I.data,S):(S.push(I),S)},[])}function x(R){const S=[];for(let I=0;I<R.length;I++){const E=R[I];switch(E.mode){case e.NUMERIC:S.push([E,{data:E.data,mode:e.ALPHANUMERIC,length:E.length},{data:E.data,mode:e.BYTE,length:E.length}]);break;case e.ALPHANUMERIC:S.push([E,{data:E.data,mode:e.BYTE,length:E.length}]);break;case e.KANJI:S.push([E,{data:E.data,mode:e.BYTE,length:f(E.data)}]);break;case e.BYTE:S.push([{data:E.data,mode:e.BYTE,length:f(E.data)}])}}return S}function L(R,S){const I={},E={start:{}};let F=["start"];for(let $=0;$<R.length;$++){const X=R[$],V=[];for(let G=0;G<X.length;G++){const ne=X[G],K=""+$+G;V.push(K),I[K]={node:ne,lastCount:0},E[K]={};for(let D=0;D<F.length;D++){const P=F[D];I[P]&&I[P].node.mode===ne.mode?(E[P][K]=_(I[P].lastCount+ne.length,ne.mode)-_(I[P].lastCount,ne.mode),I[P].lastCount+=ne.length):(I[P]&&(I[P].lastCount=ne.length),E[P][K]=_(ne.length,ne.mode)+4+e.getCharCountIndicator(ne.mode,S))}}F=V}for(let $=0;$<F.length;$++)E[F[$]].end=0;return{map:E,table:I}}function C(R,S){let I;const E=e.getBestModeForData(R);if(I=e.from(S,E),I!==e.BYTE&&I.bit<E.bit)throw new Error('"'+R+'" cannot be encoded with mode '+e.toString(I)+`.
|
|
160
160
|
Suggested mode is: `+e.toString(E));switch(I===e.KANJI&&!u.isKanjiModeEnabled()&&(I=e.BYTE),I){case e.NUMERIC:return new n(R);case e.ALPHANUMERIC:return new s(R);case e.KANJI:return new a(R);case e.BYTE:return new i(R)}}t.fromArray=function(S){return S.reduce(function(I,E){return typeof E=="string"?I.push(C(E,null)):E.data&&I.push(C(E.data,E.mode)),I},[])},t.fromString=function(S,I){const E=v(S,u.isKanjiModeEnabled()),F=x(E),$=L(F,I),X=h.find_path($.map,"start","end"),V=[];for(let G=1;G<X.length-1;G++)V.push($.table[X[G]].node);return t.fromArray(b(V))},t.rawSplit=function(S){return t.fromArray(v(S,u.isKanjiModeEnabled()))}})(Vp)),Vp}var MS;function AD(){if(MS)return Pp;MS=1;const t=ea(),e=Uv(),n=pD(),s=mD(),i=gD(),a=vD(),c=_D(),u=jC(),h=bD(),f=SD(),g=xD(),v=ta(),_=LD();function b($,X){const V=$.size,G=a.getPositions(X);for(let ne=0;ne<G.length;ne++){const K=G[ne][0],D=G[ne][1];for(let P=-1;P<=7;P++)if(!(K+P<=-1||V<=K+P))for(let O=-1;O<=7;O++)D+O<=-1||V<=D+O||(P>=0&&P<=6&&(O===0||O===6)||O>=0&&O<=6&&(P===0||P===6)||P>=2&&P<=4&&O>=2&&O<=4?$.set(K+P,D+O,!0,!0):$.set(K+P,D+O,!1,!0))}}function x($){const X=$.size;for(let V=8;V<X-8;V++){const G=V%2===0;$.set(V,6,G,!0),$.set(6,V,G,!0)}}function L($,X){const V=i.getPositions(X);for(let G=0;G<V.length;G++){const ne=V[G][0],K=V[G][1];for(let D=-2;D<=2;D++)for(let P=-2;P<=2;P++)D===-2||D===2||P===-2||P===2||D===0&&P===0?$.set(ne+D,K+P,!0,!0):$.set(ne+D,K+P,!1,!0)}}function C($,X){const V=$.size,G=f.getEncodedBits(X);let ne,K,D;for(let P=0;P<18;P++)ne=Math.floor(P/3),K=P%3+V-8-3,D=(G>>P&1)===1,$.set(ne,K,D,!0),$.set(K,ne,D,!0)}function R($,X,V){const G=$.size,ne=g.getEncodedBits(X,V);let K,D;for(K=0;K<15;K++)D=(ne>>K&1)===1,K<6?$.set(K,8,D,!0):K<8?$.set(K+1,8,D,!0):$.set(G-15+K,8,D,!0),K<8?$.set(8,G-K-1,D,!0):K<9?$.set(8,15-K-1+1,D,!0):$.set(8,15-K-1,D,!0);$.set(G-8,8,1,!0)}function S($,X){const V=$.size;let G=-1,ne=V-1,K=7,D=0;for(let P=V-1;P>0;P-=2)for(P===6&&P--;;){for(let O=0;O<2;O++)if(!$.isReserved(ne,P-O)){let j=!1;D<X.length&&(j=(X[D]>>>K&1)===1),$.set(ne,P-O,j),K--,K===-1&&(D++,K=7)}if(ne+=G,ne<0||V<=ne){ne-=G,G=-G;break}}}function I($,X,V){const G=new n;V.forEach(function(O){G.put(O.mode.bit,4),G.put(O.getLength(),v.getCharCountIndicator(O.mode,$)),O.write(G)});const ne=t.getSymbolTotalCodewords($),K=u.getTotalCodewordsCount($,X),D=(ne-K)*8;for(G.getLengthInBits()+4<=D&&G.put(0,4);G.getLengthInBits()%8!==0;)G.putBit(0);const P=(D-G.getLengthInBits())/8;for(let O=0;O<P;O++)G.put(O%2?17:236,8);return E(G,$,X)}function E($,X,V){const G=t.getSymbolTotalCodewords(X),ne=u.getTotalCodewordsCount(X,V),K=G-ne,D=u.getBlocksCount(X,V),P=G%D,O=D-P,j=Math.floor(G/D),z=Math.floor(K/D),M=z+1,A=j-z,N=new h(A);let U=0;const T=new Array(D),H=new Array(D);let se=0;const Q=new Uint8Array($.buffer);for(let xe=0;xe<D;xe++){const Be=xe<O?z:M;T[xe]=Q.slice(U,U+Be),H[xe]=N.encode(T[xe]),U+=Be,se=Math.max(se,Be)}const Z=new Uint8Array(G);let me=0,de,ie;for(de=0;de<se;de++)for(ie=0;ie<D;ie++)de<T[ie].length&&(Z[me++]=T[ie][de]);for(de=0;de<A;de++)for(ie=0;ie<D;ie++)Z[me++]=H[ie][de];return Z}function F($,X,V,G){let ne;if(Array.isArray($))ne=_.fromArray($);else if(typeof $=="string"){let j=X;if(!j){const z=_.rawSplit($);j=f.getBestVersionForData(z,V)}ne=_.fromString($,j||40)}else throw new Error("Invalid data");const K=f.getBestVersionForData(ne,V);if(!K)throw new Error("The amount of data is too big to be stored in a QR Code");if(!X)X=K;else if(X<K)throw new Error(`
|
|
@@ -166,4 +166,4 @@ Minimum version required to store current data is: `+K+`.
|
|
|
166
166
|
`).filter(i=>i!==""),promptMode:t.promptMode};return t.modelFlag&&(s.model={flag:t.modelFlag,value:t.modelValue||""}),t.promptMode==="flag"&&(s.promptFlag=t.promptFlag),e&&(s.env=Object.fromEntries(t.envRows.filter(i=>!i.remove&&i.key).map(i=>[i.key,i.value]))),VS(s,t,e)}function Qr({children:t,onClose:e,label:n,error:s=""}){const i=w.useRef(null),a=w.useRef(null),c=w.useRef(e);return c.current=e,w.useEffect(()=>{const u=document.activeElement,h=i.current,f=()=>Array.from((h==null?void 0:h.querySelectorAll('button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [href], [tabindex]:not([tabindex="-1"])'))||[]).filter(_=>_.offsetParent!==null),g=requestAnimationFrame(()=>{var _;return(_=f()[0]||h)==null?void 0:_.focus({preventScroll:!0})}),v=_=>{var C;if(_.key==="Escape"){_.preventDefault(),(C=c.current)==null||C.call(c);return}if(_.key!=="Tab")return;const b=f();if(!b.length){_.preventDefault(),h==null||h.focus();return}const x=b[0],L=b[b.length-1];_.shiftKey&&document.activeElement===x?(_.preventDefault(),L.focus()):!_.shiftKey&&document.activeElement===L&&(_.preventDefault(),x.focus())};return document.addEventListener("keydown",v),()=>{cancelAnimationFrame(g),document.removeEventListener("keydown",v),u&&u.isConnected&&typeof u.focus=="function"&&u.focus({preventScroll:!0})}},[]),w.useEffect(()=>{s&&requestAnimationFrame(()=>{var u;return(u=a.current)==null?void 0:u.scrollIntoView({block:"nearest"})})},[s]),l.jsx("div",{className:"nc-fleet-modal",role:"presentation",onMouseDown:u=>{u.target===u.currentTarget&&e()},children:l.jsxs("div",{ref:i,className:"nc-fleet-modal-dialog",role:"dialog","aria-modal":"true","aria-label":n||p("settings"),tabIndex:-1,children:[t,s&&l.jsx("div",{ref:a,className:"nc-err nc-fleet-modal-error",role:"alert","aria-live":"assertive",children:s})]})})}function nm({token:t,targets:e=[],readonly:n=!1,onPower:s,onImport:i}){const[a,c]=w.useState([]),[u,h]=w.useState(0);w.useEffect(()=>{let C=!0;async function R(){const I=[{route:[],label:p("local")}].concat((e||[]).map(F=>({route:Array.isArray(F.route)?F.route:[],label:F.label||(F.route||[]).join(" › ")}))),E=await Promise.all(I.map(async F=>{const $={...F,available:!1,readonly:!1,capabilities:[],provider:null,cells:[],unmanaged:[],err:""};try{const X=await Qa(t,F.route);$.available=!!X.available,$.capabilities=X.capabilities||[],$.provider=X.provider||null,$.cells=(X.cells||[]).map(V=>({...V,route:F.route}));try{$.readonly=!!(await Pc(t,F.route)).readonlyDefault}catch{}try{const V=await Xg(t,F.route),G=new Set($.cells.map(ne=>ne.tmuxSession).filter(Boolean));$.unmanaged=(V.sessions||[]).filter(ne=>ne&&!G.has(ne.name))}catch{}}catch(X){$.err=String(X&&X.message||X)}return $}));C&&c(E)}R();const S=setInterval(R,6e3);return()=>{C=!1,clearInterval(S)}},[t,e,u]);const f=(C,R)=>Array.isArray(C.capabilities)&&C.capabilities.includes(R)&&!n&&!C.readonly,g=()=>h(C=>C+1),v=(C,R)=>{s&&s({...C,route:R})},_=(C,R)=>{s&&s({...C,route:R})},b=async(C,R)=>{try{await tc(t,C.cell,R)}catch{}g()},x=async(C,R)=>{if(window.confirm(p("fleet-remove-cell").replace("{id}",C.cell))){try{await R1(t,C.cell,!0,R)}catch{}g()}},L=async(C,R)=>{if(window.confirm(p("terminate-confirm").replace("{name}",C.name))){try{await Yg(t,C.name,R)}catch{}g()}};return l.jsxs("div",{className:"nc-fleet-inventory",children:[l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:p("fleet-inventory")}),l.jsx("small",{children:p("fleet-inventory-help")})]}),a.map(C=>{const R=C.route.length?C.route.join("/"):"local";return l.jsxs("div",{className:"nc-fleet-pos",children:[l.jsxs("div",{className:"nc-fleet-pos-title",children:[l.jsx("span",{className:`dot ${C.available?"on":"warn"}`}),l.jsx("b",{children:C.label}),l.jsx("small",{children:C.available?`${C.cells.length} ${p("fleet-cells")} · ${C.unmanaged.length} ${p("fleet-tmux")}`:C.err||p("fleet-not-available")})]}),C.cells.map(S=>l.jsxs("div",{className:"nc-fleet-item nc-fleet-cell",children:[l.jsxs("span",{children:[l.jsx("b",{children:S.cell}),l.jsx("small",{children:`${S.engine||""}${S.key?`·${S.key}`:""}${S.active?"":` · ${p("cell-off")}`}`})]}),l.jsxs("span",{className:"nc-fleet-cell-actions",children:[S.active&&f(C,"down")&&l.jsx("button",{className:"nc-btn ghost",title:p("power-off"),onClick:()=>_(S,C.route),children:p("stop")}),!S.active&&f(C,"up")&&l.jsx("button",{className:"nc-btn ghost",title:p("power-on"),onClick:()=>v(S,C.route),children:p("start")}),f(C,"restart")&&S.active&&l.jsx("button",{className:"nc-btn ghost",title:p("restart"),onClick:()=>b(S,C.route),children:p("restart")}),f(C,"remove")&&l.jsx("button",{className:"nc-btn danger",title:p("delete"),onClick:()=>x(S,C.route),children:"×"})]})]},`${R}:${S.cell}`)),C.unmanaged.map(S=>l.jsxs("div",{className:"nc-fleet-item nc-fleet-unmanaged",children:[l.jsxs("span",{children:[l.jsx("b",{children:S.name}),l.jsx("small",{children:p("fleet-tmux")})]}),l.jsxs("span",{className:"nc-fleet-cell-actions",children:[f(C,"import")&&i&&l.jsx("button",{className:"nc-btn ghost",title:p("import-as-cell"),onClick:()=>i(S,C.route),children:p("import-as-cell")}),l.jsx("button",{className:"nc-btn danger",title:p("terminate"),onClick:()=>L(S,C.route),children:"×"})]})]},`${R}:u:${S.name}`)),C.available&&C.cells.length===0&&C.unmanaged.length===0&&l.jsx("div",{className:"nc-empty",children:p("fleet-inventory-empty")})]},R)})]})}function F3({cells:t=[],engines:e=[],models:n=[],busy:s,canRestore:i=!1,onRestore:a,onClose:c}){const[u,h]=w.useState("export"),[f,g]=w.useState([]),[v,_]=w.useState(()=>new Set(t.map(z=>z.id))),[b,x]=w.useState(()=>new Set(e.map(z=>z.id))),[L,C]=w.useState([]),[R,S]=w.useState([]),[I,E]=w.useState(""),F=new Set(e.map(z=>z.id)),$=new Set(t.map(z=>z.id)),X=(z,M)=>z(A=>{const N=new Set(A);return N.has(M)?N.delete(M):N.add(M),N}),V=()=>{const z=P3(t,v,e,b,new Date,n);if(z.ok===!1){E(p(`fleet-backup-${z.error}`));return}const M=t.filter(H=>v.has(H.id)).length,A=e.filter(H=>b.has(H.id)).length;if(z.cells.length!==M){E(p("fleet-backup-invalid-cell"));return}if(z.engines.length!==A){E(p("fleet-backup-invalid-engine"));return}if(!z.cells.length&&!z.engines.length){E(p("fleet-backup-select-one"));return}const N=new Blob([`${JSON.stringify(z,null,2)}
|
|
167
167
|
`],{type:"application/json"}),U=URL.createObjectURL(N),T=document.createElement("a");T.href=U,T.download=`nexuscrew-fleet-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(T),T.click(),T.remove(),setTimeout(()=>URL.revokeObjectURL(U),0),E("")},G=async z=>{if(E(""),C([]),S([]),!!z){if(z.size>1024*1024){E(p("fleet-backup-too-large"));return}try{const M=I3(await z.text());if(!M.ok){E(p(`fleet-backup-${M.error}`));return}g(Array.isArray(M.models)?M.models:[]);const A=new Set(M.engines.map(N=>N.id));S(M.engines.map(N=>({engine:N,exists:F.has(N.id),selected:!F.has(N.id)}))),C(M.cells.map(N=>{const U=F.has(N.engine)||A.has(N.engine),T=$.has(N.id);return{cell:N,engine:U?N.engine:"",selected:U&&!T,exists:T}}))}catch(M){E(String(M.message||M))}}},ne=(z,M)=>C(A=>A.map((N,U)=>U===z?{...N,...M}:N)),K=(z,M)=>S(A=>A.map((N,U)=>U===z?{...N,...M}:N)),D=new Set([...F,...R.filter(z=>z.selected).map(z=>z.engine.id)]),P=L.filter(z=>z.selected&&z.engine&&D.has(z.engine)),O=R.filter(z=>z.selected),j=[...new Map([...e.map(z=>[z.id,z.label||z.id]),...R.filter(z=>z.selected).map(z=>[z.engine.id,z.engine.label||z.engine.id])]).entries()];return l.jsxs("div",{className:"nc-set-form nc-fleet-form nc-backup-dialog",children:[l.jsx("b",{children:p("fleet-backup")}),l.jsx("small",{children:p("fleet-backup-help")}),l.jsxs("div",{className:"nc-set-tabs nc-backup-tabs",children:[l.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="export"?" on":""}`,onClick:()=>{h("export"),E("")},children:p("fleet-backup-export")}),l.jsx("button",{type:"button",className:`nc-set-tabbtn${u==="import"?" on":""}`,disabled:!i,title:i?"":p("fleet-backup-restore-unavailable"),onClick:()=>{h("import"),E("")},children:p("fleet-backup-import")})]}),u==="export"?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{_(new Set(t.map(z=>z.id))),x(new Set(e.map(z=>z.id)))},children:p("select-all")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{_(new Set),x(new Set)},children:p("select-none")})]}),l.jsxs("div",{className:"nc-backup-list",children:[l.jsx("b",{children:p("fleet-engines")}),e.map(z=>{var M;return l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:b.has(z.id),onChange:()=>X(x,z.id)}),l.jsxs("span",{children:[l.jsx("b",{children:z.label||z.id}),l.jsxs("small",{children:[z.id,(M=z.envKeys)!=null&&M.length?` · ${z.envKeys.length} ${p("fleet-backup-env-names")}`:""]})]})]},z.id)}),l.jsx("b",{children:p("fleet-cells")}),t.map(z=>l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:v.has(z.id),onChange:()=>X(_,z.id)}),l.jsxs("span",{children:[l.jsx("b",{children:z.id}),l.jsxs("small",{children:[z.engine," · ",p("fleet-system-prompt")," ",(z.prompt||"").length," ",p("characters")]})]})]},z.id)),!t.length&&!e.length&&l.jsx("div",{className:"nc-empty",children:p("fleet-backup-empty")})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:!v.size&&!b.size,onClick:V,children:p("fleet-backup-download")})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{type:"file",accept:"application/json,.json",disabled:s,onChange:z=>G(z.target.files&&z.target.files[0])}),l.jsx("small",{children:p("fleet-backup-import-help")}),!!(L.length||R.length)&&l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{S(z=>z.map(M=>({...M,selected:!0}))),C(z=>z.map(M=>({...M,selected:!!M.engine})))},children:p("select-all")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{S(z=>z.map(M=>({...M,selected:!1}))),C(z=>z.map(M=>({...M,selected:!1})))},children:p("select-none")})]}),l.jsxs("div",{className:"nc-backup-list",children:[!!R.length&&l.jsx("b",{children:p("fleet-engines")}),R.map((z,M)=>{var A;return l.jsx("div",{className:"nc-backup-import-row",children:l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:z.selected,onChange:N=>K(M,{selected:N.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:z.engine.label||z.engine.id}),l.jsxs("small",{children:[z.engine.id," · ",z.exists?p("fleet-backup-overwrite"):p("fleet-backup-new"),(A=z.engine.envKeys)!=null&&A.length?` · ${p("fleet-backup-env-values-required")}`:""]})]})]})},z.engine.id)}),!!L.length&&l.jsx("b",{children:p("fleet-cells")}),L.map((z,M)=>l.jsxs("div",{className:"nc-backup-import-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:z.selected,disabled:!z.engine||!D.has(z.engine),onChange:A=>ne(M,{selected:A.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:z.cell.id}),l.jsxs("small",{children:[z.exists?p("fleet-backup-overwrite"):p("fleet-backup-new")," · ",p("fleet-system-prompt")," ",z.cell.systemPrompt.length," ",p("characters")]})]})]}),l.jsxs("select",{value:z.engine,onChange:A=>ne(M,{engine:A.target.value,selected:!!A.target.value}),children:[l.jsx("option",{value:"",children:p("fleet-backup-engine-missing")}),j.map(([A,N])=>l.jsx("option",{value:A,children:N},A))]})]},z.cell.id))]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:s||!P.length&&!O.length,onClick:()=>a({engineRows:R,cellRows:L,models:f}),children:p("fleet-backup-restore")})]})]}),I&&l.jsx("div",{className:"nc-err",children:I})]})}function H3({state:t,setState:e,busy:n,onSave:s,catalog:i}){var R;const a=t.form,c=S=>e({...t,form:{...a,...S}}),u=a.envRows||[],h=[...new Map(i.map(S=>[S.client,S.clientLabel||S.client])).entries()],f=i.filter(S=>S.client===a.client),g=Ac(i,a),v=typeof(g==null?void 0:g.credentialEnv)=="string"?g.credentialEnv:"",_=Array.isArray(g==null?void 0:g.credentialUsedBy)?g.credentialUsedBy:[],b=(g==null?void 0:g.credentialSource)||"missing",x=!!(g!=null&&g.credentialEnv)||a.credentialProfile==="a"||a.credentialProfile==="p",L=!!v&&t.mode==="new"&&(g==null?void 0:g.authConfigured)!==!0&&!a.credentialValue&&!a.allowMissingCredential,C=S=>{S&&c({client:S.client,provider:S.provider,credentialProfile:S.credentialProfile||"",managedModel:S.model||"",protocol:S.protocol||"",permissionPolicy:S.permissionPolicyDefault||"standard",credentialSourcePolicy:"auto",rc:!!S.rc,displayName:S.custom?p("fleet-custom-provider-default"):"",baseUrl:S.custom?"":S.endpoint||"",envKey:S.defaultEnvKey||"",providerId:"nexuscrew-custom",credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,...t.mode==="new"?{id:S.id,label:""}:{}})};return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsx("b",{children:t.mode==="new"?p("fleet-new-engine"):`${p("edit")} ${a.id}`}),l.jsx("input",{value:a.id,disabled:t.mode!=="new",placeholder:"id",onChange:S=>c({id:S.target.value})}),l.jsx("input",{value:a.label,placeholder:p("label"),onChange:S=>c({label:S.target.value})}),l.jsxs("select",{value:a.kind,disabled:t.mode!=="new",onChange:S=>c({kind:S.target.value}),children:[l.jsx("option",{value:"managed",children:p("fleet-managed")}),l.jsx("option",{value:"custom",children:p("fleet-custom")})]}),a.kind==="managed"?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("select",{value:a.client,disabled:t.mode!=="new",onChange:S=>C(i.find(I=>I.client===S.target.value&&I.default)||i.find(I=>I.client===S.target.value)),children:h.map(([S,I])=>l.jsx("option",{value:S,children:I},S))}),l.jsx("select",{value:((R=Ac(i,a))==null?void 0:R.id)||"",disabled:t.mode!=="new",onChange:S=>C(i.find(I=>I.id===S.target.value)),children:f.map(S=>l.jsx("option",{value:S.id,children:S.label},S.id))})]}),a.client!=="shell"&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.managedModel,list:"nc-managed-models",placeholder:p(g!=null&&g.requiresModel?"fleet-model-required":"fleet-model-default"),onChange:S=>c({managedModel:S.target.value})}),l.jsx("datalist",{id:"nc-managed-models",children:[...(g==null?void 0:g.models)||[],...a.modelOptions||[]].filter((S,I,E)=>S&&E.indexOf(S)===I).map(S=>l.jsx("option",{value:S},S))})]}),g!=null&&g.supportsUnsafe?l.jsxs("select",{value:a.permissionPolicy,onChange:S=>c({permissionPolicy:S.target.value}),children:[l.jsx("option",{value:"standard",children:p("fleet-standard-permissions")}),l.jsx("option",{value:"unsafe",children:p("fleet-unsafe-permissions")})]}):l.jsx("small",{children:p("fleet-standard-permissions")}),(g==null?void 0:g.supportsUnsafe)&&a.permissionPolicy==="unsafe"&&l.jsx("small",{className:"nc-err",children:p("fleet-unsafe-warning")}),x&&l.jsxs("select",{"aria-label":p("fleet-credential-source-policy"),value:a.credentialSourcePolicy||"auto",onChange:S=>c({credentialSourcePolicy:S.target.value}),children:[l.jsx("option",{value:"auto",children:p("fleet-credential-source-policy-auto")}),l.jsx("option",{value:"nexuscrew-store",children:p("fleet-credential-source-policy-nexuscrew-store")}),l.jsx("option",{value:"environment",children:p("fleet-credential-source-policy-environment")})]}),(g==null?void 0:g.credentialEnv)===!0&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.envKey,placeholder:p("fleet-api-key-env"),onChange:S=>c({envKey:S.target.value})}),l.jsx("small",{children:p("fleet-custom-secret-help")})]}),v&&l.jsxs("section",{className:"nc-fleet-key","aria-label":p("fleet-key-section"),children:[l.jsxs("div",{className:"nc-fleet-key-head",children:[l.jsx("b",{children:p("fleet-key-section")}),l.jsx("span",{children:p(`fleet-credential-source-${b}`)})]}),l.jsxs("label",{className:"nc-field",children:[p("fleet-key-variable"),l.jsx("input",{value:v,readOnly:!0,"aria-label":p("fleet-key-variable")})]}),l.jsx("small",{children:_.length?p("fleet-key-used-by").replace("{engines}",_.join(", ")):p("fleet-key-used-by-none")}),_.length>0&&l.jsx("small",{children:p("fleet-key-shared-impact").replace("{key}",v).replace("{engines}",_.join(", "))}),l.jsxs("div",{className:"nc-fleet-key-input",children:[l.jsx("input",{type:a.credentialReveal?"text":"password",value:a.credentialValue||"","aria-label":p("fleet-key-value").replace("{key}",v),autoComplete:"new-password",spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:g!=null&&g.authConfigured||t.mode==="edit"?p("fleet-key-blank-keeps"):p("fleet-key-enter"),onChange:S=>c({credentialValue:S.target.value,allowMissingCredential:S.target.value?!1:a.allowMissingCredential})}),l.jsx("button",{type:"button",className:"nc-btn ghost","aria-label":p(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal"),onClick:()=>c({credentialReveal:!a.credentialReveal}),children:p(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal")})]}),l.jsx("small",{children:p("fleet-key-local-help")}),t.mode==="new"&&(g==null?void 0:g.authConfigured)!==!0&&!a.credentialValue&&l.jsxs("label",{className:"nc-check nc-fleet-key-missing",children:[l.jsx("input",{type:"checkbox",checked:!!a.allowMissingCredential,onChange:S=>c({allowMissingCredential:S.target.checked})}),p("fleet-key-create-missing")]}),(g==null?void 0:g.notice)&&l.jsx("small",{className:"nc-fleet-provider-notice",children:p(`fleet-provider-notice-${g.notice}`)})]}),(g==null?void 0:g.notice)&&!v&&l.jsx("small",{className:"nc-fleet-provider-notice",children:p(`fleet-provider-notice-${g.notice}`)}),a.provider==="custom"&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.displayName,placeholder:p("fleet-provider-display"),onChange:S=>c({displayName:S.target.value})}),l.jsx("input",{value:a.baseUrl,placeholder:"https://api.example.com/v1",onChange:S=>c({baseUrl:S.target.value})}),((g==null?void 0:g.protocols)||[]).length>1&&l.jsx("select",{value:a.protocol,onChange:S=>c({protocol:S.target.value}),children:g.protocols.map(S=>l.jsx("option",{value:S,children:S},S))}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:a.envKey,placeholder:p("fleet-api-key-env"),onChange:S=>c({envKey:S.target.value})}),l.jsx("input",{value:a.providerId,placeholder:p("fleet-provider-id"),onChange:S=>c({providerId:S.target.value})})]}),l.jsxs("small",{children:[a.protocol," · ",p("fleet-custom-secret-help")]})]}),l.jsx("small",{children:p(a.client==="shell"?"fleet-shell-engine-help":"fleet-managed-help")})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.command,placeholder:p("command-path"),onChange:S=>c({command:S.target.value})}),l.jsx("textarea",{value:a.argsText,placeholder:p("args-lines"),onChange:S=>c({argsText:S.target.value})}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:a.rc,onChange:S=>c({rc:S.target.checked})})," ",p("fleet-remote-control")]}),l.jsxs("select",{value:a.promptMode,onChange:S=>c({promptMode:S.target.value}),children:[l.jsx("option",{value:"send-keys",children:"send-keys"}),l.jsx("option",{value:"flag",children:"flag"})]}),a.promptMode==="flag"&&l.jsx("input",{value:a.promptFlag,placeholder:"prompt flag",onChange:S=>c({promptFlag:S.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:a.modelFlag,placeholder:"model flag",onChange:S=>c({modelFlag:S.target.value})}),l.jsx("input",{value:a.modelValue,placeholder:"model default",onChange:S=>c({modelValue:S.target.value})})]}),l.jsx("small",{children:p("env-write-only")}),u.map((S,I)=>l.jsxs("div",{className:"nc-fleet-env",children:[l.jsx("input",{value:S.key,disabled:S.configured,placeholder:"ENV_KEY",onChange:E=>{const F=u.slice();F[I]={...S,key:E.target.value},c({envRows:F})}}),l.jsx("input",{type:"password",value:S.value,placeholder:S.configured?"•••••• (unchanged)":"value",onChange:E=>{const F=u.slice();F[I]={...S,value:E.target.value},c({envRows:F})}}),l.jsx("button",{className:"nc-btn danger",onClick:()=>c({envRows:u.filter((E,F)=>F!==I)}),children:"×"})]},`${S.key}-${I}`)),l.jsx("button",{className:"nc-btn ghost",onClick:()=>c({envRows:[...u,{key:"",value:"",configured:!1}]}),children:"+ env"})]}),l.jsx("input",{value:a.panelUrl||"",maxLength:512,placeholder:p("fleet-panel-url"),onChange:S=>c({panelUrl:S.target.value})}),l.jsx("small",{children:p("fleet-panel-url-help")}),a.panelUrl&&!Yv(a.panelUrl)&&l.jsx("small",{className:"nc-err",children:p("fleet-panel-url-invalid")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>e(null),children:p("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:n||!a.id||L||a.kind==="custom"&&!a.command||a.kind==="managed"&&(g==null?void 0:g.requiresModel)&&!a.managedModel||a.kind==="managed"&&(g==null?void 0:g.credentialEnv)===!0&&!a.envKey||a.kind==="managed"&&a.provider==="custom"&&(!a.displayName||!a.baseUrl||!a.envKey||!a.providerId),onClick:s,children:p("save")})]})]})}function U3({state:t,setState:e,busy:n,onSave:s,onTest:i,profiles:a=[],canTest:c=!0}){const[u,h]=w.useState(null),[f,g]=w.useState(!1),v=t.form,_=C=>e({...t,form:{...v,...C}}),b=/^[^\x00-\x1f\x7f]{1,128}$/.test(v.id||""),x=!!(v.id||"").trim()&&!!(v.engine||"").trim()&&b,L=async()=>{h(null),g(!0);try{h(await i(v.engine,v.id))}catch(C){h({outcome:"unverified",detail:String(C&&C.message||C)})}g(!1)};return l.jsxs("div",{className:"nc-fleet-form",children:[l.jsxs("label",{className:"nc-field",children:[p("model-editor-engine"),l.jsxs("select",{value:v.engine||"",disabled:n||t.mode==="edit",onChange:C=>{h(null),_({engine:C.target.value})},children:[l.jsx("option",{value:"",children:"—"}),a.map(C=>l.jsx("option",{value:C.id,children:C.label?`${C.id} · ${C.label}`:C.id},C.id))]})]}),l.jsxs("label",{className:"nc-field",children:[p("model-editor-id"),l.jsx("input",{value:v.id||"",disabled:n||t.mode==="edit",placeholder:"qwen3.9-max",onChange:C=>{h(null),_({id:C.target.value})}})]}),l.jsx("small",{className:"nc-set-hint",children:p("model-editor-id-help")}),l.jsxs("label",{className:"nc-field",children:[p("model-editor-context"),l.jsx("input",{inputMode:"numeric",value:v.contextWindow||"",disabled:n,onChange:C=>_({contextWindow:C.target.value.replace(/[^0-9]/g,"").slice(0,9)})})]}),l.jsxs("label",{className:"nc-field",children:[p("model-editor-max-tokens"),l.jsx("input",{inputMode:"numeric",value:v.maxTokens||"",disabled:n,onChange:C=>_({maxTokens:C.target.value.replace(/[^0-9]/g,"").slice(0,9)})})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:v.reasoning===!0,disabled:n,onChange:C=>_({reasoning:C.target.checked})})," ",p("model-editor-reasoning")]}),l.jsxs("div",{className:"nc-set-row",children:[c&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||f||!x,onClick:L,children:p(f?"model-test-running":"model-test")}),u&&l.jsxs("span",{className:`nc-model-test ${u.outcome}`,children:[p(`model-test-${u.outcome}`),u.outcome==="ok"&&Number.isInteger(u.latencyMs)?` · ${u.latencyMs}ms`:""]})]}),u&&u.detail&&l.jsx("small",{className:"nc-set-hint",children:u.detail}),u&&u.outcome==="unverified"&&l.jsx("small",{className:"nc-set-hint",children:p("model-test-unverified-help")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>e(null),children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||!x,onClick:()=>s(v),children:p("save")})]})]})}function W3({token:t,route:e,targets:n=[],location:s,setLocation:i,state:a,setState:c,engines:u,mcpServers:h=[],managedCatalog:f=[],busy:g,onSave:v}){var O,j,z;const[_,b]=w.useState(null),[x,L]=w.useState(""),C=a.form,R=M=>c({...a,form:{...C,...M}}),S=u.find(M=>M.id===C.engine),I=((O=S==null?void 0:S.managed)==null?void 0:O.client)==="shell",E=((j=S==null?void 0:S.managed)==null?void 0:j.client)||"",F=((z=f.find(M=>M.client===E))==null?void 0:z.mcpManaged)!==!1,$=M=>{var U,T,H,se;const A=u.find(Q=>Q.id===M),N={...C.commands||{}};((U=S==null?void 0:S.managed)==null?void 0:U.client)==="shell"&&(C.command?N[C.engine]=C.command:delete N[C.engine]),R({engine:M,model:((T=C.models)==null?void 0:T[M])||((H=A==null?void 0:A.managed)==null?void 0:H.model)||((se=A==null?void 0:A.model)==null?void 0:se.value)||"",commands:N,command:N[M]||""})},X=M=>{const A={...C.commands||{}};M?A[C.engine]=M:delete A[C.engine],R({command:M,commands:A})},V=I&&/[|&;<>()`$*?{}\[\]~]/.test(C.command||""),G=[...new Set([...h||[],...Array.isArray(C.mcp)?C.mcp:[]])].sort(),ne=Array.isArray(C.mcp)?C.mcp.length?"some":"none":"all",K=M=>{var A;return R({mcp:M==="all"?void 0:M==="none"?[]:(A=C.mcp)!=null&&A.length?C.mcp:[...G]})},D=M=>{const A=Array.isArray(C.mcp)?C.mcp:[];R({mcp:A.includes(M)?A.filter(N=>N!==M):[...A,M].sort()})},P=async M=>{try{const A=await Gg(t,M,e);b(A),R({cwd:A.path}),L("")}catch(A){L(String(A.message||A))}};return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsx("b",{children:a.mode==="new"?p("fleet-new-cell"):`${p("edit")} ${C.id}`}),a.mode==="new"&&l.jsxs("label",{className:"nc-field",children:[p("location"),l.jsx("span",{className:"nc-req",children:" *"}),l.jsxs("select",{value:s,onChange:M=>{i(M.target.value),R({engine:""})},children:[l.jsx("option",{value:"",children:p("local")}),n.map(M=>l.jsxs("option",{value:M.route.join("/"),disabled:M.status&&M.status!=="up",children:[M.label,M.status&&M.status!=="up"?` · ${p("node-offline")}`:""]},M.route.join("/")))]})]}),l.jsx("input",{value:C.id,disabled:a.mode!=="new",placeholder:"id",onChange:M=>R({id:M.target.value})}),l.jsx("input",{value:C.label||"",maxLength:64,placeholder:p("fleet-cell-label"),onChange:M=>R({label:M.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:C.cwd,placeholder:p("cwd"),onChange:M=>R({cwd:M.target.value})}),l.jsx("button",{className:"nc-btn ghost",onClick:()=>_?b(null):P(C.cwd),children:p("browse")})]}),_&&l.jsxs("div",{className:"nc-fs",children:[l.jsx("div",{className:"nc-fs-path",children:_.path}),l.jsxs("div",{className:"nc-fs-list",children:[_.parent&&l.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>P(_.parent),children:["↑ ",p("fs-parent")]}),(_.dirs||[]).map(M=>l.jsxs("button",{className:"nc-fs-item",onClick:()=>P(`${_.path.replace(/\/$/,"")}/${M}`),children:["📁 ",M]},M))]})]}),x&&l.jsx("div",{className:"nc-err",children:x}),l.jsx("select",{value:C.engine,onChange:M=>$(M.target.value),children:u.map(M=>l.jsx("option",{value:M.id,children:M.label},M.id))}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:!!C.boot,onChange:M=>R({boot:M.target.checked})})," ",p("fleet-boot")]}),l.jsx("input",{value:C.panelUrl||"",maxLength:512,placeholder:p("fleet-panel-url"),onChange:M=>R({panelUrl:M.target.value})}),l.jsx("small",{children:p("fleet-panel-url-help")}),C.panelUrl&&!Yv(C.panelUrl)&&l.jsx("small",{className:"nc-err",children:p("fleet-panel-url-invalid")}),I?l.jsxs(l.Fragment,{children:[l.jsx("input",{value:C.command||"",maxLength:4096,placeholder:p("fleet-shell-command-placeholder"),onChange:M=>X(M.target.value)}),l.jsx("small",{children:C.command?p("fleet-shell-command-help"):p("fleet-shell-interactive")}),V&&l.jsx("small",{className:"nc-note",children:p("fleet-shell-command-metachar")})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{value:C.model||"",list:"nc-cell-models",placeholder:p("fleet-model-override"),onChange:M=>R({model:M.target.value})}),l.jsx("datalist",{id:"nc-cell-models",children:((S==null?void 0:S.availableModels)||[]).map(M=>l.jsx("option",{value:M},M))}),l.jsx("textarea",{value:C.prompt||"",placeholder:p("cell-prompt"),onChange:M=>R({prompt:M.target.value})}),l.jsx("small",{children:p("cell-prompt-help")}),l.jsxs("label",{className:"nc-field",children:[p("cell-mcp"),l.jsxs("select",{value:ne,onChange:M=>K(M.target.value),children:[l.jsx("option",{value:"all",children:p("cell-mcp-all")}),l.jsx("option",{value:"none",children:p("cell-mcp-none")}),l.jsx("option",{value:"some",children:p("cell-mcp-some")})]})]}),!F&&l.jsx("small",{className:"nc-note",children:p("cell-mcp-inert")}),ne==="some"&&l.jsx("div",{className:"nc-fleet-mcp-list",children:G.map(M=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:(C.mcp||[]).includes(M),onChange:()=>D(M)})," ",M]},M))}),l.jsx("small",{children:p("cell-mcp-help")})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>c(null),children:p("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:g||!C.id||!C.cwd||!C.engine,onClick:v,children:p("save")})]})]})}function YS({token:t,route:e=[],state:n,setState:s,busy:i,onSave:a}){const[c,u]=w.useState(null),[h,f]=w.useState([]),[g,v]=w.useState(""),_=Array.isArray(e)?e.join("/"):"";w.useEffect(()=>{let R=!0;return Yd(t,_?_.split("/"):[]).then(S=>{R&&(f(S.engines||[]),v(""))}).catch(S=>{R&&(f([]),v(String(S.message||S)))}),()=>{R=!1}},[t,_]);const b=n.form,x=R=>s({...n,form:{...b,...R}}),L=async R=>{try{const S=await Gg(t,R,e);u(S),x({cwd:S.path})}catch{}},C=!b.id&&b.tmuxSession?b.tmuxSession.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32):b.id;return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsxs("b",{children:[p("import-as-cell")," · ",b.tmuxSession]}),l.jsx("small",{children:p("import-help")}),l.jsx("input",{value:b.tmuxSession,disabled:!0,placeholder:"tmux session",readOnly:!0}),l.jsx("input",{value:b.id,placeholder:p("name"),onChange:R=>x({id:R.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:b.cwd,placeholder:p("cwd"),onChange:R=>x({cwd:R.target.value})}),l.jsx("button",{className:"nc-btn ghost",type:"button",onClick:()=>c?u(null):L(b.cwd),children:p("browse")})]}),c&&l.jsxs("div",{className:"nc-fs",children:[l.jsx("div",{className:"nc-fs-path",children:c.path}),l.jsxs("div",{className:"nc-fs-list",children:[c.parent&&l.jsxs("button",{className:"nc-fs-item nc-fs-nav",onClick:()=>L(c.parent),children:["↑ ",p("fs-parent")]}),(c.dirs||[]).map(R=>l.jsxs("button",{className:"nc-fs-item",onClick:()=>L(`${c.path.replace(/\/$/,"")}/${R}`),children:["📁 ",R]},R))]})]}),l.jsxs("select",{value:b.engine,onChange:R=>x({engine:R.target.value}),children:[l.jsx("option",{value:"",children:p("import-engine-required")}),h.map(R=>l.jsx("option",{value:R.id,children:R.label},R.id))]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:!!b.boot,onChange:R=>x({boot:R.target.checked})})," ",p("fleet-boot")]}),(n.err||g)&&l.jsx("div",{className:"nc-err",children:n.err||g}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>s(null),children:p("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:i||!b.tmuxSession||!b.engine||!h.length,onClick:a,children:p(C?"import-as-cell":"save")})]})]})}function id(t){const e=$o(t);return e===null?`~/${t}`:e?`~/${e}`:"~"}function q3(t){if(!t||typeof t.path!="string"||typeof t.home!="string")return"";const{path:e,home:n}=t;return!n||e===n||!e.startsWith(n+"/")?"":e.slice(n.length+1).replace(/\/+$/,"")}function K3({token:t,route:e,cell:n,busy:s=!1,onSaved:i,onClose:a}){const[c,u]=w.useState(""),[h,f]=w.useState(null),[g,v]=w.useState(!1),[_,b]=w.useState(""),x=typeof(n==null?void 0:n.cwdSuggestion)=="string"&&$o(n.cwdSuggestion)!==null?$o(n.cwdSuggestion):null,[L,C]=w.useState(x),R=n==null?void 0:n.id,S=s||g,I=async G=>{const ne=$o(G);if(ne===null){f({rel:"",dirs:[],loading:!1,err:p("fleet-cwd-repair-invalid")});return}f({rel:ne,dirs:[],loading:!0,err:""});try{const K=await Gg(t,ne,e),D=q3(K);f({rel:D,dirs:Array.isArray(K.dirs)?K.dirs:[],loading:!1,err:""})}catch(K){f({rel:ne,dirs:[],loading:!1,err:String(K&&K.message||K)})}},E=G=>{if(!h)return;const ne=h.rel?`${h.rel}/${G}`:G;I(ne)},F=()=>{h!=null&&h.rel&&I(h.rel.split("/").slice(0,-1).join("/"))},$=()=>{h&&(u(h.rel||""),f(null),b(""),C(null))},X=()=>{L!==null&&(u(L),C(null),b(""))},V=async()=>{if(S)return;const G=$o(c);if(G===null){b(p("fleet-cwd-repair-invalid"));return}const ne=id(G);let K=!0;try{K=window.confirm(p("fleet-cwd-repair-confirm").replace("{id}",String(R||"")).replace("{path}",ne))}catch{K=!1}if(K){v(!0),b(""),C(null);try{const D=await N1(t,R,{cwdRel:G},e);i==null||i(D)}catch(D){const P=D&&D.data||{};if(P.code==="unportable-cwd"){b(p("fleet-cwd-repair-unportable"));const O=Array.isArray(P.cells)?P.cells.find(z=>z&&z.id===R):null,j=O&&typeof O.suggestion=="string"?O.suggestion:null;j!==null&&$o(j)!==null&&C(j)}else b(String(D&&D.message||D))}finally{v(!1)}}};return l.jsxs("div",{className:"nc-set-form nc-fleet-form nc-cwd-repair",children:[l.jsx("b",{children:p("fleet-cwd-repair-title").replace("{id}",String(R||""))}),l.jsx("small",{className:"nc-set-info",children:p("fleet-cwd-repair-help")}),l.jsx("small",{className:"nc-cwd-no-source",children:p("fleet-cwd-repair-no-source-path")}),l.jsxs("label",{className:"nc-field",children:[p("cwd"),l.jsxs("div",{className:"nc-cwd-rel-row",children:[l.jsx("span",{className:"nc-cwd-rel-prefix",children:"~/"}),l.jsx("input",{value:c,placeholder:p("fleet-cwd-repair-placeholder"),autoComplete:"off",spellCheck:"false",autoCapitalize:"none",onChange:G=>u(G.target.value)}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:S,onClick:()=>h?f(null):I(""),children:p(h?"close":"fleet-cwd-repair-browse")})]})]}),l.jsx("div",{className:"nc-cwd-preview",children:p("fleet-cwd-repair-preview").replace("{path}",id(c))}),h&&l.jsxs("div",{className:"nc-fs",children:[l.jsx("div",{className:"nc-fs-path",children:id(h.rel)}),l.jsxs("div",{className:"nc-fs-list",children:[h.rel&&l.jsxs("button",{type:"button",className:"nc-fs-item nc-fs-nav",onClick:F,children:["↑ ",p("fs-parent")]}),h.loading&&l.jsx("div",{className:"nc-fs-empty",children:"…"}),!h.loading&&h.dirs.length===0&&l.jsx("div",{className:"nc-fs-empty",children:p("fleet-cwd-repair-fs-empty")}),!h.loading&&h.dirs.map(G=>l.jsxs("button",{type:"button",className:"nc-fs-item",onClick:()=>E(G),children:["📁 ",G]},G))]}),h.err&&l.jsx("div",{className:"nc-err",children:h.err}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{type:"button",className:"nc-btn primary",disabled:S||h.loading||!!h.err,onClick:$,children:p("fleet-cwd-repair-use-current")})})]}),_&&l.jsx("div",{className:"nc-err",role:"alert",children:_}),L!==null&&l.jsxs("div",{className:"nc-cwd-suggestion",role:"status",children:[l.jsx("span",{children:p("fleet-cwd-repair-suggestion")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:X,children:p("fleet-cwd-repair-use-suggestion").replace("{path}",id(L))})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:g,onClick:a,children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:S,onClick:V,children:g?"…":p("save")})]})]})}function V3({token:t,readonly:e,targets:n=[],startNewCell:s=!1,initialLocation:i=""}){const[a,c]=w.useState({engines:[],cells:[],managedCatalog:[]}),[u,h]=w.useState({available:!1,capabilities:[]}),[f,g]=w.useState(!1),[v,_]=w.useState(null),[b,x]=w.useState(null),[L,C]=w.useState({}),[R,S]=w.useState(null),[I,E]=w.useState(!1),[F,$]=w.useState(""),[X,V]=w.useState(""),[G,ne]=w.useState(i),[K,D]=w.useState(!1),[P,O]=w.useState(null),[j,z]=w.useState(null),[M,A]=w.useState(null),[N,U]=w.useState(!1),[T,H]=w.useState([]),[se,Q]=w.useState(null),[Z,me]=w.useState("manage"),de=w.useRef(!1),ie=G?G.split("/"):[],xe=w.useCallback(async()=>{try{const W=await Qa(t,ie);h(W);try{const ee=await Pc(t,ie);D(!!ee.readonlyDefault)}catch{D(!1)}if(W.provider==="builtin"&&(W.capabilities||[]).includes("definitions")){const ee=await Yd(t,ie),J=new Map((W.engines||[]).map(be=>[be.id,be]));if(ee.engines=(ee.engines||[]).map(be=>{var ye;return{...be,availableModels:((ye=J.get(be.id))==null?void 0:ye.models)||[]}}),c(ee),(W.capabilities||[]).includes("credentials"))try{H((await kN(t,ie)).credentials||[])}catch{H([])}else H([])}$("")}catch(W){$(String(W.message||W))}finally{g(!0)}},[t,G]);w.useEffect(()=>{document.visibilityState!=="hidden"&&xe()},[xe]),v3(xe,5e3);const Be=new Set((u.cells||[]).filter(W=>W.active).map(W=>W.cell)),nt=u.provider==="builtin"&&(u.capabilities||[]).includes("edit"),Le=(u.capabilities||[]).includes("restore");w.useEffect(()=>{!s||de.current||!nt||!a.engines.length||(de.current=!0,S({mode:"new",form:KS(a.engines[0].id)}))},[s,nt,a.engines]);const Ie=async W=>{E(!0),$(""),V("");try{await W(),await xe()}catch(ee){$(String(ee.message||ee))}E(!1)},ue=async(W,ee)=>{const J=await jN(t,W,ee,ie);return C(be=>({...be,[`${W}::${ee}`]:J})),J},Re=W=>Ie(async()=>{const ee={id:String(W.id||"").trim(),engine:String(W.engine||"").trim()};for(const J of["contextWindow","maxTokens"]){const be=String(W[J]||"").trim();be&&(ee[J]=Number(be))}W.reasoning===!0&&(ee.reasoning=!0),await LN(t,ee,ie),x(null),await xe()}),fe=()=>Ie(async()=>{var Lt;const W=v.mode==="new",ee=v.form,J=a.managedCatalog||[],be=ee.kind==="managed"?Ac(J,ee):null,ye=typeof(be==null?void 0:be.credentialEnv)=="string"?be.credentialEnv:"",ot=ye&&ee.credentialValue||"",oe=z3(ee,W,J);!W&&v.form.kind==="custom"&&!v.form.modelFlag&&(oe.model=null),!W&&v.form.kind==="custom"&&v.form.promptMode!=="flag"&&(oe.promptFlag=null);let $e;if(W)$e=await EN(t,oe,ie);else{const _t=v.original,pt=new Set(v.form.envRows.filter(Ot=>!Ot.remove).map(Ot=>Ot.key)),Ut=(_t.envKeys||[]).filter(Ot=>!pt.has(Ot)),Gt=Object.fromEntries(v.form.envRows.filter(Ot=>!Ot.remove&&Ot.key&&(!Ot.configured||Ot.value!=="")).map(Ot=>[Ot.key,Ot.value]));$e=await NN(t,_t.id,oe,v.form.kind==="custom"?{set:Gt,remove:Ut}:void 0,ie)}let ut=null;if(ye&&ot)try{ut=await Tw(t,ye,ot,ie),H(ut.credentials||[])}catch{throw await xe(),W&&_({mode:"edit",original:{...oe,id:ee.id},form:{...ee,credentialReveal:!1}}),new Error(p(W?"fleet-key-partial-create":"fleet-key-partial-edit"))}await xe(),_(null),V(p("fleet-saved"));const kt=((Lt=((ut==null?void 0:ut.credentials)||[]).find(_t=>_t.envKey===ye))==null?void 0:Lt.activeCells)||[],St=[...new Set([...($e==null?void 0:$e.activeCells)||[],...kt])];if(St.length&&window.confirm(p("fleet-restart-confirm").replace("{cells}",St.join(", "))))for(const _t of St)await tc(t,_t,ie)}),Ee=()=>Ie(async()=>{var kt,St,Lt,_t,pt,Ut;const W=R.mode==="new",ee=R.form,J={...W?{id:ee.id}:{},cwd:ee.cwd,engine:ee.engine,boot:!!ee.boot},be={...ee.commands||{}},ye=a.engines.find(Gt=>Gt.id===ee.engine);((kt=ye==null?void 0:ye.managed)==null?void 0:kt.client)==="shell"&&typeof ee.command=="string"&&ee.command.length?be[ee.engine]=ee.command:((St=ye==null?void 0:ye.managed)==null?void 0:St.client)==="shell"&&delete be[ee.engine],(Object.keys(be).length||!W)&&(J.commands=be);const ot=(ee.label||"").trim();W?ot&&(J.label=ot):J.label=ot||null;const oe=(ee.panelUrl||"").trim();W?oe&&(J.panelUrl=oe):J.panelUrl=oe||null,W?Array.isArray(ee.mcp)&&(J.mcp=ee.mcp):J.mcp=Array.isArray(ee.mcp)?ee.mcp:null,W?(((Lt=ye==null?void 0:ye.managed)==null?void 0:Lt.client)!=="shell"&&ee.model&&(J.model=ee.model),((_t=ye==null?void 0:ye.managed)==null?void 0:_t.client)!=="shell"&&ee.prompt&&(J.prompt=ee.prompt)):(J.model=((pt=ye==null?void 0:ye.managed)==null?void 0:pt.client)==="shell"?null:ee.model||null,((Ut=ye==null?void 0:ye.managed)==null?void 0:Ut.client)!=="shell"&&(J.prompt=ee.prompt||null));const $e=W?await MN(t,J,ie):await N1(t,R.original.id,J,ie),ut=W?ee.id:R.original.id;S(null),V(p("fleet-saved")),!W&&($e!=null&&$e.active)&&window.confirm(p("fleet-restart-confirm").replace("{cells}",ut))&&await tc(t,ut,ie)}),Y=e||K,pe=u.capabilities||[],Ae=ie.length>0&&Y,ke=W=>T.find(ee=>{var J;return(J=ee.engines)==null?void 0:J.includes(W.id)})||null,We=()=>Ie(async()=>{var J;const W=await Tw(t,se.envKey,se.value,ie);H(W.credentials||[]),Q(null),V(p("fleet-credential-saved"));const ee=((J=(W.credentials||[]).find(be=>be.envKey===se.envKey))==null?void 0:J.activeCells)||[];if(ee.length&&window.confirm(p("fleet-restart-confirm").replace("{cells}",ee.join(", "))))for(const be of ee)await tc(t,be,ie)}),Ne=W=>Ie(async()=>{if(!window.confirm(p("fleet-credential-remove-confirm").replace("{key}",W.envKey)))return;const ee=await CN(t,W.envKey,ie);H(ee.credentials||[]),V(p("fleet-credential-removed"))}),ge=W=>O({...W,route:Array.isArray(W==null?void 0:W.route)?W.route:ie}),st=async W=>{if(!P)return;const ee={...P,cell:P.cell||P.id};try{await jv({token:t,powerCell:ee,payload:W,onNotice:V})}catch(J){throw $(String(J&&J.message||J)),J}},Ze=(W,ee)=>{$(""),z({mode:"new",route:Array.isArray(ee)?ee:ie,form:{tmuxSession:W.name,id:"",engine:"",cwd:"",boot:!1},err:""})},De=()=>Ie(async()=>{const W=j.form;if(!W.engine){z({...j,err:p("import-engine-required")});return}await TN(t,{tmuxSession:W.tmuxSession,id:W.id||void 0,engine:W.engine,cwd:W.cwd||void 0,boot:!!W.boot},W.route||ie),z(null),V(p("fleet-saved"))}),He=({engineRows:W=[],cellRows:ee=[],models:J=[]})=>Ie(async()=>{const be=W.filter(_t=>_t.selected),ye=be.map(_t=>XC(_t.engine));if(ye.some(_t=>!_t))throw new Error(p("fleet-backup-invalid-engine"));const ot=be.filter(_t=>_t.exists).map(_t=>_t.engine.id);if(ot.length&&!window.confirm(p("fleet-backup-confirm-engine-overwrite").replace("{engines}",ot.join(", "))))return;const oe=[...new Set([...a.engines.map(_t=>_t.id),...ye.map(_t=>_t.id)])],$e=[];for(const _t of ee.filter(pt=>pt.selected)){const pt=D3(_t.cell,_t.engine,oe);if(!pt)throw new Error(`${_t.cell.id}: ${p("fleet-backup-engine-missing")}`);$e.push(pt)}const ut=ee.filter(_t=>_t.selected&&_t.exists).map(_t=>_t.cell.id);if(ut.length&&!window.confirm(p("fleet-backup-confirm-overwrite").replace("{cells}",ut.join(", "))))return;const kt=ye.length?await IN(t,ye,ot.length>0,ie,J):{needsRestart:[]},St=$e.length?await PN(t,$e,ie):{needsRestart:[]},Lt=[...new Set([...kt.needsRestart||[],...St.needsRestart||[]])];U(!1),V(`${p("fleet-backup-restored").replace("{n}",String($e.length))}${ye.length?` · ${ye.length} ${p("fleet-engines").toLowerCase()}`:""}${Lt.length?` · ${p("fleet-backup-needs-restart").replace("{cells}",Lt.join(", "))}`:""}`)}),qe=l.jsxs("label",{className:"nc-field",children:[p("location"),l.jsxs("select",{value:G,onChange:W=>{ne(W.target.value),_(null),S(null),$(""),V(""),D(!1),g(!1),h({available:!1,capabilities:[]}),c({engines:[],cells:[],managedCatalog:[]}),H([]),Q(null)},children:[l.jsx("option",{value:"",children:p("local")}),n.map(W=>l.jsxs("option",{value:W.route.join("/"),disabled:W.status&&W.status!=="up",children:[W.label,W.status&&W.status!=="up"?` · ${p("node-offline")}`:""]},W.route.join("/")))]})]}),wt=l.jsxs("div",{className:"nc-fleet-view-tabs",role:"tablist","aria-label":p("tab-fleet"),children:[l.jsx("button",{type:"button",role:"tab","aria-selected":Z==="manage",className:`nc-set-tabbtn${Z==="manage"?" on":""}`,onClick:()=>me("manage"),children:p("fleet-manage-location")}),l.jsx("button",{type:"button",role:"tab","aria-selected":Z==="overview",className:`nc-set-tabbtn${Z==="overview"?" on":""}`,onClick:()=>me("overview"),children:p("fleet-network-overview")})]});return f?nt?l.jsxs("div",{className:"nc-set-tab nc-fleet-editor",children:[wt,Z==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(nm,{token:t,targets:n,readonly:e,onPower:ge,onImport:Ze})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-manage-help")}),qe,l.jsxs("div",{className:"nc-set-row nc-fleet-backup-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>{$(""),U(!0)},children:p("fleet-backup")}),l.jsx("small",{children:p("fleet-backup-help")})]}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:p("fleet-cells")}),l.jsx("span",{className:"nc-fleet-head-actions",children:l.jsxs("button",{className:"nc-btn primary",disabled:Y||I||!a.engines.length,onClick:()=>{var W;$(""),S({mode:"new",form:KS((W=a.engines[0])==null?void 0:W.id)})},children:["+ ",p("add")]})})]}),a.cells.map(W=>{const ee=Be.has(W.id),J=W.needsRepair===!0;return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:W.id}),W.label?l.jsxs("small",{className:"nc-fleet-label",children:[" ",W.label]}):null,l.jsxs("small",{children:[W.engine," · ",J?l.jsx("span",{className:"nc-fleet-tag nc-fleet-tag-warn",children:p("fleet-cwd-needs-repair")}):W.cwd,ee?` · ${p("service-active")}`:` · ${p("cell-off")}`]})]}),l.jsxs("span",{children:[ee&&pe.includes("down")&&l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>Ie(()=>C1(t,{cell:W.id},ie)),children:p("stop")}),!ee&&pe.includes("up")&&l.jsx("button",{className:"nc-btn primary",disabled:Y||I,onClick:()=>ge({cell:W.id,id:W.id,engine:W.engine,model:W.model,models:W.models,permissionPolicies:W.permissionPolicies,active:!1,boot:W.boot}),children:p("start")}),ee&&pe.includes("restart")&&l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>Ie(()=>tc(t,W.id,ie)),children:p("restart")}),J?l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>{$(""),A(W)},children:p("fleet-cwd-repair")}):l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>{var be;$(""),S({mode:"edit",original:W,form:{...W,commands:{...W.commands||{}},command:((be=W.commands)==null?void 0:be[W.engine])||""}})},children:p("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:Y||I,onClick:()=>Ie(async()=>{window.confirm(p("fleet-remove-cell").replace("{id}",W.id))&&await R1(t,W.id,!0,ie)}),children:"×"})]})]},W.id)}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:p("fleet-engines")}),l.jsxs("button",{className:"nc-btn primary",disabled:Y||I,onClick:()=>{$(""),_({mode:"new",form:O3()})},children:["+ ",p("add")]})]}),a.engines.map(W=>{var J,be;const ee=ke(W);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:W.label}),l.jsx("small",{children:W.managed?`${W.id} · ${W.managed.client} / ${W.managed.provider} · ${(J=W.managedInfo)!=null&&J.configured?p("fleet-ready"):((be=W.managedInfo)==null?void 0:be.reason)||p("fleet-not-ready")}`:`${W.id} · ${W.command}`}),ee&&l.jsxs("small",{children:[ee.envKey," · ",p(`fleet-credential-source-${ee.source||"missing"}`)]})]}),l.jsxs("span",{children:[ee&&l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>{$(""),Q({envKey:ee.envKey,value:""})},children:ee.configured?p("fleet-credential-change"):p("fleet-credential-set")}),(ee==null?void 0:ee.source)==="local"&&l.jsx("button",{className:"nc-btn danger",disabled:Y||I,onClick:()=>Ne(ee),children:p("fleet-credential-forget")}),l.jsx("button",{className:"nc-btn ghost",disabled:Y||I,onClick:()=>{$(""),_({mode:"edit",original:W,form:$3(W)})},children:p("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:Y||I,onClick:()=>Ie(async()=>{window.confirm(p("fleet-remove-engine").replace("{id}",W.id))&&await RN(t,W.id,ie)}),children:"×"})]})]},W.id)}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:p("fleet-models")}),l.jsxs("button",{className:"nc-btn primary",disabled:Y||I,onClick:()=>{$(""),x({mode:"new",form:{id:"",engine:""}})},children:["+ ",p("add")]})]}),!(a.models||[]).length&&l.jsx("small",{className:"nc-set-hint",children:p("fleet-no-models")}),(a.models||[]).map(W=>{const ee=`${W.engine}::${W.id}`,J=L[ee],be=(a.engines||[]).some(ye=>ye.managed&&ye.managed.model===W.id);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:W.id}),l.jsxs("small",{children:[W.engine,W.contextWindow?` · ${W.contextWindow}`:"",be?` · ${p("model-in-use")}`:""]}),J&&l.jsxs("small",{className:`nc-model-test ${J.outcome}`,children:[p(`model-test-${J.outcome}`),J.outcome==="ok"&&Number.isInteger(J.latencyMs)?` · ${J.latencyMs}ms`:""]})]}),l.jsxs("span",{children:[pe.includes("model-test")&&l.jsx("button",{className:"nc-btn ghost",disabled:I||Ae,onClick:()=>Ie(()=>ue(W.engine,W.id)),children:p("model-test")}),l.jsx("button",{className:"nc-btn danger",disabled:Y||I,onClick:()=>Ie(()=>AN(t,W.id,W.engine,ie)),children:"×"})]})]},ee)})]}),b&&l.jsx(Qr,{onClose:()=>x(null),label:p("fleet-models"),error:F,children:l.jsx(U3,{state:b,setState:x,busy:I,onSave:Re,onTest:ue,profiles:a.managedCatalog||[],canTest:pe.includes("model-test")&&!Ae})}),v&&l.jsx(Qr,{onClose:()=>_(null),label:p("fleet-new-engine"),error:F,children:l.jsx(H3,{state:v,setState:_,busy:I,onSave:fe,catalog:a.managedCatalog||[]})}),R&&l.jsx(Qr,{onClose:()=>S(null),label:p("fleet-new-cell"),error:F,children:l.jsx(W3,{token:t,route:ie,targets:n,location:G,setLocation:ne,state:R,setState:S,engines:a.engines,mcpServers:a.mcpServers||[],managedCatalog:a.managedCatalog||[],busy:I,onSave:Ee})}),M&&l.jsx(Qr,{onClose:()=>A(null),label:p("fleet-cwd-repair-title").replace("{id}",M.id),error:"",children:l.jsx(K3,{token:t,route:ie,cell:M,busy:I,onSaved:async()=>{A(null),V(p("fleet-cwd-repaired")),await xe()},onClose:()=>A(null)})}),X&&l.jsx("div",{className:"nc-set-note",children:X}),F&&l.jsx("div",{className:"nc-err",children:F}),N&&l.jsx(Qr,{onClose:()=>U(!1),label:p("fleet-backup"),error:F,children:l.jsx(F3,{cells:a.cells,engines:a.engines,models:a.models||[],busy:I,canRestore:Le,onRestore:He,onClose:()=>U(!1)})}),se&&l.jsx(Qr,{onClose:()=>Q(null),label:p("fleet-credential-title"),error:F,children:l.jsxs("div",{className:"nc-fleet-form nc-credential-form",children:[l.jsx("b",{children:p("fleet-credential-title")}),l.jsx("small",{children:p("fleet-credential-help")}),l.jsxs("label",{className:"nc-field",children:[se.envKey,l.jsx("input",{type:"password",autoComplete:"off",spellCheck:"false",autoCapitalize:"none",value:se.value,onChange:W=>Q({...se,value:W.target.value})})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>Q(null),children:p("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:I||!se.value,onClick:We,children:p("save")})]})]})}),j&&l.jsx(Qr,{onClose:()=>z(null),label:p("import-as-cell"),error:F,children:l.jsx(YS,{token:t,route:j.route||ie,state:j,setState:z,busy:I,onSave:De})}),P&&l.jsx(Pd,{cell:P,token:t,route:Array.isArray(P.route)?P.route:ie,onConfirm:async W=>{try{await st(W)}finally{xe()}},onClose:()=>O(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[wt,Z==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(nm,{token:t,targets:n,readonly:e,onPower:ge,onImport:Ze})]}):l.jsxs(l.Fragment,{children:[qe,l.jsxs("div",{className:"nc-set-info",children:[p(F?"fleet-editor-load-error":"fleet-editor-unavailable"),!F&&u.reason?` ${u.reason}`:""]})]}),F&&l.jsx("div",{className:"nc-err",children:F}),j&&l.jsx(Qr,{onClose:()=>z(null),label:p("import-as-cell"),error:F,children:l.jsx(YS,{token:t,route:j.route||ie,state:j,setState:z,busy:I,onSave:De})}),P&&l.jsx(Pd,{cell:P,token:t,route:Array.isArray(P.route)?P.route:ie,onConfirm:async W=>{try{await st(W)}finally{xe()}},onClose:()=>O(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[wt,Z==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(nm,{token:t,targets:n,readonly:e,onPower:ge,onImport:Ze})]}):l.jsxs(l.Fragment,{children:[qe,l.jsx("div",{className:"nc-set-info",children:p("fleet-editor-loading")})]})]})}const QC="nc_bar_files_button",ZC="nc_bar_keyboard_button",eE="nc_bar_panel_button";function Xv(t,e){try{const n=localStorage.getItem(t);if(n==="on")return!0;if(n==="off")return!1}catch{}return e}function Jv(t,e){try{localStorage.setItem(t,e?"on":"off")}catch{}}function tE(){return Xv(QC,!0)}function nE(t){Jv(QC,t)}function sE(){return Xv(ZC,!0)}function Y3(t){Jv(ZC,t)}function iE(){return Xv(eE,!1)}function G3(t){Jv(eE,t)}const Qv="nc_notification_speech_v1",rd="nc-notification-speech",Tg="nc-notification-speech-preview",X3=320,J3=2,Q3=3e4,Z3=1e4,e6=6e4,t6=64,GS=Object.freeze({enabled:!1}),n6=Object.freeze({it:"it-IT",en:"en-US",es:"es-ES"}),s6=Object.freeze({it:new Set(["che","con","correzione","della","delle","difetto","il","lavoro","nessun","non","per","pronto","pubblicata","pubblicato","rilascio","sono","stato","tutti","verificata","verificato","versione","completata","completato","riepilogo"]),en:new Set(["all","and","completed","fix","for","issue","no","published","ready","release","summary","the","verified","version","with","work"]),es:new Set(["con","correccion","defecto","el","esta","para","publicada","publicado","resumen","sin","todos","trabajo","verificada","verificado","version","y"])}),Zv=new WeakSet;function e_(t){return{enabled:(t&&typeof t=="object"&&!Array.isArray(t)?t:{}).enabled===!0}}function rE(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function XS(t=rE()){if(!t)return{...GS};try{return e_(JSON.parse(t.getItem(Qv)||"null"))}catch{return{...GS}}}function i6(t,e=rE()){const n=e_(t);if(e)try{e.setItem(Qv,JSON.stringify(n))}catch{}return n}function sl(){try{return typeof window<"u"?window:null}catch{return null}}function jc(t=sl()){try{return!!(t&&t.speechSynthesis&&typeof t.speechSynthesis.speak=="function"&&typeof t.SpeechSynthesisUtterance=="function")}catch{return!1}}function oE(t=sl()){return!!(t&&(typeof t=="object"||typeof t=="function")&&Zv.has(t))}function Pg(t=sl()){t&&(typeof t=="object"||typeof t=="function")&&Zv.delete(t)}function Ua(t){const e=String(t||"").trim().toLowerCase().split("-")[0];return n6[e]||""}function mh(t){return String(t||"").normalize("NFC").replace(/[\p{Cc}\p{Cf}]+/gu," ").replace(/\s+/g," ").trim()}function r6(t){const e=mh(t).normalize("NFD").replace(new RegExp("\\p{M}+","gu"),"").toLowerCase(),n=new Set(e.match(new RegExp("\\p{L}+","gu"))||[]);if(n.size<4)return"";const s=Object.entries(s6).map(([i,a])=>({lang:i,score:[...n].reduce((c,u)=>c+(a.has(u)?1:0),0)})).sort((i,a)=>a.score-i.score);return s[0].score>=3&&s[0].score-s[1].score>=2?s[0].lang:""}function o6(t,e){const n=Ua(t&&t.lang);return n||Ua(r6(t&&t.body))||Ua(e)}function aE(t){try{const e=t&&t.speechSynthesis&&t.speechSynthesis.getVoices;return typeof e=="function"?Array.from(e.call(t.speechSynthesis)||[]).filter(Boolean):[]}catch{return[]}}function lE(t,e){const n=Ua(e);if(!n)return null;const s=Array.from(t||[]).filter(u=>u&&typeof u.lang=="string"&&u.lang.trim()),i=s.filter(u=>u.lang.trim().toLowerCase()===n.toLowerCase()),a=n.slice(0,2).toLowerCase(),c=s.filter(u=>u.lang.trim().toLowerCase().split("-")[0]===a);return i.find(u=>u.default===!0)||i[0]||c.find(u=>u.default===!0)||c[0]||null}function JS(t){return mh(t).replace(/\bBearer\s+\S+/gi,"Bearer [redacted]").replace(/\b(?:sk|hf|zai|xox[baprs]|gh[pousr]|npm)[_-][A-Za-z0-9._-]{8,}\b/gi,"[redacted]").replace(/\b(?:token|password|secret|credential|api[_-]?key)\s*[=:]\s*(?:"[^"]*"|'[^']*'|\S+)/gi,"[redacted]").replace(/\b[A-Z][A-Z0-9_]{2,}\s*=\s*(?:"[^"]*"|'[^']*'|\S+)/g,"[redacted]").replace(/(?:\/home\/[^/\s]+|\/Users\/[^/\s]+|\/data\/(?:data|user\/\d+)\/[^/\s]+)(?:\/[^\s]*)?/g,"[private path]").replace(/\b[A-Za-z]:\\Users\\[^\\\s]+(?:\\[^\s]*)?/g,"[private path]")}function a6(t,e=X3){const n=JS(t&&t.title),s=JS(t&&t.body),i=[n,s&&s!==n?s:""].filter(Boolean).join(". "),a=Array.from(i);return a.length<=e?i:`${a.slice(0,Math.max(0,e-1)).join("").trimEnd()}…`}function l6(t){try{return!!(t&&t.visibilityState==="visible"&&typeof t.hasFocus=="function"&&t.hasFocus())}catch{return!1}}function cE(t=sl()){if(!jc(t))return!1;try{return t.speechSynthesis.cancel(),!0}catch{return!1}}function c6(t){try{t&&typeof t.dispatchEvent=="function"&&typeof t.Event=="function"&&t.dispatchEvent(new t.Event(Tg))}catch{}}function u6(t,e,n=sl(),s={}){var f;if(Pg(n),!jc(n))return Promise.resolve(!1);const i=mh(t);if(!i||(f=s.signal)!=null&&f.aborted)return Promise.resolve(!1);const a=Number.isFinite(s.timeoutMs)&&s.timeoutMs>0?s.timeoutMs:Z3,c=s.setTimer||((g,v)=>setTimeout(g,v)),u=s.clearTimer||(g=>clearTimeout(g)),h=s.signal;return c6(n),new Promise(g=>{let v=!1,_=!1,b=null,x=null;const L=C=>{if(!v){if(v=!0,h&&x&&h.removeEventListener("abort",x),b!==null&&u(b),C!==!0)try{n.speechSynthesis.cancel()}catch{}else Zv.add(n);g(C)}};x=()=>L("no-activation"),h&&h.addEventListener("abort",x,{once:!0});try{n.speechSynthesis.cancel();const C=new n.SpeechSynthesisUtterance(i);C.lang=Ua(e);const R=lE(aE(n),C.lang);R&&(C.voice=R),C.onstart=()=>{_=!0},C.onend=()=>L(_?!0:"no-activation"),C.onerror=()=>L("voice-error"),b=c(()=>L("timeout"),a),n.speechSynthesis.speak(C)}catch{L("no-activation")}})}function d6(t={}){const e=t.scope||sl(),n=t.document||e&&e.document,s=Number.isInteger(t.maxPending)&&t.maxPending>=0?t.maxPending:J3,i=Number.isFinite(t.watchdogMs)&&t.watchdogMs>0?t.watchdogMs:Q3,a=Number.isFinite(t.dedupWindowMs)&&t.dedupWindowMs>0?t.dedupWindowMs:e6,c=Number.isInteger(t.maxDedup)&&t.maxDedup>0?t.maxDedup:t6,u=t.now||Date.now,h=t.setTimer||((K,D)=>setTimeout(K,D)),f=t.clearTimer||(K=>clearTimeout(K)),g=t.isPrimed||(()=>oE(e)),v=e&&e.speechSynthesis;let _=null,b=null,x=[],L=[],C=()=>{};const R=new Map,S=()=>{L=aE(e)};if(S(),v&&typeof v.addEventListener=="function")v.addEventListener("voiceschanged",S),C=()=>v.removeEventListener("voiceschanged",S);else if(v&&"onvoiceschanged"in v){const K=v.onvoiceschanged,D=(...P)=>{S(),typeof K=="function"&&K.apply(v,P)};v.onvoiceschanged=D,C=()=>{v.onvoiceschanged===D&&(v.onvoiceschanged=K)}}const I=K=>{if(K&&typeof K.id=="string"&&K.id)return`id:${K.id}`;const D=Number(K&&K.ts),P=mh(K&&K.title);return Number.isFinite(D)&&P?`frame:${D}:${P}`:""},E=K=>{if(!K)return!0;const D=u();for(const[P,O]of R)D-O>=a&&R.delete(P);if(R.has(K))return!1;for(R.set(K,D);R.size>c;)R.delete(R.keys().next().value);return!0},F=()=>{b!==null&&f(b),b=null},$=()=>{F(),_&&(_.onend=null,_.onerror=null,_=null),cE(e)},X=K=>{if(!jc(e))return x=[],"unsupported";let D;try{D=new e.SpeechSynthesisUtterance(K.text),D.lang=Ua(K.lang);const O=lE(L,D.lang);O&&(D.voice=O)}catch{return x=[],"error"}_=D;const P=()=>{if(_!==D)return;F(),_=null,D.onend=null,D.onerror=null;const O=x.shift();O&&X(O)};D.onend=P,D.onerror=P;try{return b=h(()=>{if(_!==D)return;_=null,D.onend=null,D.onerror=null;try{e.speechSynthesis.cancel()}catch{}F();const O=x.shift();O&&X(O)},i),e.speechSynthesis.speak(D),"speaking"}catch{return P(),"error"}},V=(K,D)=>{if(!jc(e))return"unsupported";const P=a6(K);if(!P)return"empty";if(!E(I(K)))return"duplicate";if(!l6(n))return"inactive";if(!g())return"unprimed";const O={text:P,lang:D};return K&&K.urgency==="high"?(x=[],$(),X(O)):_?s===0?"dropped":(x.length>=s&&x.shift(),x.push(O),"queued"):X(O)},G=()=>{x=[],$()};return{enqueue:V,stop:G,dispose:()=>{G(),C(),C=()=>{}}}}function uE(){const[t,e]=w.useState(XS);w.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==Qv&&i.key!==null)return;const a=(i==null?void 0:i.type)===rd?e_(i.detail):XS();e(a)};return window.addEventListener(rd,s),window.addEventListener("storage",s),()=>{window.removeEventListener(rd,s),window.removeEventListener("storage",s)}},[]);const n=w.useCallback(s=>{const i=i6({enabled:s===!0});return e(i),window.dispatchEvent(new CustomEvent(rd,{detail:i})),i.enabled},[]);return[t.enabled,n]}const t_="nc_storage_persist_v1",h6=1440*60*1e3;function Ig(t=globalThis.localStorage){return Rr(t_,{storage:t,fallback:()=>null,parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0})}async function f6({manager:t=(s=>(s=globalThis.navigator)==null?void 0:s.storage)(),ls:e=globalThis.localStorage,now:n=Date.now}={}){const i=Ig(e),a=n();let c;try{if(!t||typeof t.persist!="function")c={at:a,status:"unsupported"};else if(typeof t.persisted=="function"&&await t.persisted())c={at:a,status:"persistent"};else{if(i&&i.status==="denied"&&a-i.at<h6)return i;c={at:a,status:await t.persist()?"persistent":"denied"}}}catch(u){c={at:a,status:"error",note:String((u==null?void 0:u.message)||u).slice(0,120)}}return(!i||i.status!==c.status)&&Ji({reason:"storage-persist",note:c.status}),yi(t_,c,{storage:e}),c}const p6=t=>{try{return new Date(t).toLocaleString()}catch{return String(t)}},sm=t=>Array.isArray(t)?t.join(", "):"";function m6(){zn();const[t,e]=w.useState(()=>dg()),[n,s]=w.useState(()=>Ig()),[i,a]=w.useState(!1);w.useEffect(()=>{const f=()=>{e(dg()),s(Ig())};return window.addEventListener("storage",f),window.addEventListener("nexuscrew-roster-preferences",f),()=>{window.removeEventListener("storage",f),window.removeEventListener("nexuscrew-roster-preferences",f)}},[]);const c=async()=>{try{await navigator.clipboard.writeText(JSON.stringify(t,null,2)),a(!0),setTimeout(()=>a(!1),1500)}catch{}},u=()=>{BT(),e([])},h=[...t].reverse();return l.jsxs("div",{className:"nc-set-form nc-prefs-journal",children:[l.jsx("div",{className:"nc-sheet-label",children:p("prefs-journal")}),l.jsxs("div",{"data-testid":"persist-status",className:"nc-set-hint","data-key":t_,children:[p("prefs-persist"),": ",n?n.status:p("prefs-persist-unknown")]}),!h.length&&l.jsx("div",{className:"nc-set-hint",children:p("prefs-journal-empty")}),l.jsx("div",{className:"nc-journal-list",style:{maxHeight:220,overflow:"auto"},children:h.map((f,g)=>l.jsxs("div",{"data-testid":"journal-row",className:"nc-set-hint",style:{overflowWrap:"anywhere"},children:[l.jsx("b",{children:f.reason})," · ",p6(f.t),f.position?` · ${f.position}`:"",f.key?` · ${f.key}`:"",f.note?` · ${f.note}`:"",f.before?l.jsxs("div",{children:[p("prefs-before"),": ",sm(f.before)]}):null,f.after?l.jsxs("div",{children:[p("prefs-after"),": ",sm(f.after)]}):null,f.visible?l.jsxs("div",{children:[p("prefs-visible"),": ",sm(f.visible)]}):null]},`${f.t}-${g}`))}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,disabled:!t.length,children:p(i?"copied":"prefs-journal-copy")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:u,disabled:!t.length,children:p("prefs-journal-clear")})]})]})}const n_="nc_device_id_v1",dE="nc_prefs_sync_v1",g6="nexuscrew-roster-preferences",s_=/^[a-f0-9]{32}$/,v6=192,_6=256,QS=128,hE="nexuscrew-preferences",Uo=t=>t&&typeof t=="object"&&!Array.isArray(t),wd=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e&&!/[\u0000-\u001f\u007f]/.test(t),im=(t,e=_6)=>Array.isArray(t)&&t.length<=e&&t.every(n=>wd(n,v6));function il(t){if(!Uo(t)||Object.keys(t).some(n=>!["pins","orders","views","nodeOrder"].includes(n)))return null;const e={pins:[],orders:{},views:{},nodeOrder:[]};if(t.pins!==void 0){if(!im(t.pins))return null;e.pins=[...new Set(t.pins)]}if(t.nodeOrder!==void 0){if(!im(t.nodeOrder,128))return null;e.nodeOrder=[...new Set(t.nodeOrder)]}if(t.orders!==void 0){if(!Uo(t.orders)||Object.keys(t.orders).length>QS)return null;for(const[n,s]of Object.entries(t.orders)){if(!wd(n,96)||!im(s))return null;e.orders[n]=[...new Set(s)]}}if(t.views!==void 0){if(!Uo(t.views)||Object.keys(t.views).length>QS)return null;for(const[n,s]of Object.entries(t.views)){if(!wd(n,96)||!Uo(s))return null;const i={};if(s.open!==void 0){if(typeof s.open!="boolean")return null;i.open=s.open}if(s.filter!==void 0){if(!wd(s.filter,16))return null;i.filter=s.filter}e.views[n]=i}}return e}const Dg=t=>!t||!(t.pins||[]).length&&!(t.nodeOrder||[]).length&&!Object.keys(t.orders||{}).length&&!Object.keys(t.views||{}).length;function i_(t){const e={pins:to(),orders:uc(t),views:_d(t),nodeOrder:gg(t)};return il(e)||{pins:[],orders:{},views:{},nodeOrder:[]}}const Og=t=>Array.isArray(t)?`[${t.map(Og).join(",")}]`:Uo(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Og(t[e])}`).join(",")}}`:JSON.stringify(t),bd=t=>{const e=Og(il(t)||{});let n=2166136261;for(let s=0;s<e.length;s+=1)n^=e.charCodeAt(s),n=Math.imul(n,16777619);return(n>>>0).toString(16)},rm=["nc_pins",Qo,Jo,ah];function r_(t,{storage:e,note:n="restore"}={}){const s=il(t);if(!s)return new Error("preferenze non valide");let i=e;try{i=i||globalThis.localStorage}catch(u){return u}const a={};for(const u of rm)try{a[u]=i.getItem(u)}catch{a[u]=null}const c={nc_pins:s.pins,[Qo]:s.orders,[Jo]:s.views,[ah]:s.nodeOrder};for(const u of rm){const h=yi(u,c[u],{storage:e});if(h){for(const f of rm)try{a[f]===null||a[f]===void 0?i.removeItem(f):i.setItem(f,a[f])}catch{}return Ji({reason:"prefs-restore-failed",key:u,note:String(h&&h.message||h).slice(0,120)}),h}}Ji({reason:"prefs-restore",note:n,after:s.pins});try{window.dispatchEvent(new Event(g6))}catch{}return null}const fE=t=>({status:"error",code:"storage-write-failed",note:String(t&&t.message||t).slice(0,120)}),o_=t=>{try{return t||globalThis.localStorage}catch{return null}},gh=t=>{var e;try{const n=(e=o_(t))==null?void 0:e.getItem(n_);return s_.test(n||"")?n:""}catch{return""}},pE=(t,e)=>{var n;try{(n=o_(e))==null||n.setItem(n_,t)}catch{}};function y6(t,e){s_.test(t||"")&&!gh(e)&&pE(t,e)}const w6=gh,b6=t=>Rr(dE,{storage:t,fallback:()=>null,parse:e=>Uo(e)?e:void 0}),Fd=(t,e,n)=>yi(dE,{revision:t,hash:bd(e),at:Date.now()},{storage:n});function mE(t){return async(e,n,{headers:s={},body:i}={})=>qn(n,t,{method:e,headers:{...i?{"content-type":"application/json"}:{},...s},body:i,timeoutMs:8e3})}async function ZS(t,e){let n=gh(e);if(!n){const s=await t("POST","/api/prefs/devices");if(s.status!==201)throw Object.assign(new Error(`device ${s.status}`),{status:s.status});if(n=(await s.json()).deviceId,!s_.test(n||""))throw new Error("device non valido");pE(n,e)}return n}async function Bg(t,e,n,s,i){const a=await t("PUT","/api/prefs",{headers:{"x-nc-device":e,"if-match":`"${s}"`},body:JSON.stringify({data:n})});if(a.status===200){const u=await a.json();return Fd(u.revision,n,i),{status:"uploaded",revision:u.revision}}const c=await a.json().catch(()=>({}));return a.status===409&&c.current?{status:"conflict",revision:c.current.revision,conflict:{local:n,server:il(c.current.data)||null,revision:c.current.revision,deviceId:e}}:{status:"error",code:c.code||`http-${a.status}`}}async function S6({request:t,token:e,storage:n}={}){var i;const s=t||mE(e);try{let a=await ZS(s,n),c=await s("GET","/api/prefs",{headers:{"x-nc-device":a}});if(c.status===404){try{(i=o_(n))==null||i.removeItem(n_)}catch{}a=await ZS(s,n),c=await s("GET","/api/prefs",{headers:{"x-nc-device":a}})}if(c.status!==200)return{status:"error",code:`http-${c.status}`};const u=await c.json(),h=i_(n),f=il(u.data);if(!f)return Dg(h)?{status:"synced",revision:u.revision}:Bg(s,a,h,u.revision,n);if(Dg(h)){const v=r_(f,{storage:n});return v?fE(v):(Fd(u.revision,f,n),{status:"restored",revision:u.revision})}if(bd(h)===bd(f))return Fd(u.revision,h,n),{status:"synced",revision:u.revision};const g=b6(n);return g&&g.revision===u.revision&&g.hash!==bd(h)?Bg(s,a,h,u.revision,n):{status:"conflict",revision:u.revision,conflict:{local:h,server:f,revision:u.revision,deviceId:a}}}catch(a){return{status:"offline",note:String((a==null?void 0:a.message)||a).slice(0,120)}}}async function x6(t,e,{request:n,token:s,storage:i}={}){if(!e)return{status:"error",code:"no-conflict"};const a=n||mE(s);try{if(t==="server"){if(!e.server)return{status:"error",code:"no-server-copy"};const c=r_(e.server,{storage:i,note:"restore-from-server"});return c?fE(c):(Fd(e.revision,e.server,i),{status:"restored",revision:e.revision})}return await Bg(a,e.deviceId||gh(i),e.local,e.revision,i)}catch(c){return{status:"offline",note:String((c==null?void 0:c.message)||c).slice(0,120)}}}function k6(t){return JSON.stringify({kind:hE,version:1,exportedAt:new Date().toISOString(),data:i_(t)},null,2)}function C6(t,{storage:e}={}){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:"not-json"}}if(!Uo(n)||n.kind!==hE||n.version!==1)return{ok:!1,reason:"wrong-kind"};const s=il(n.data);if(!s)return{ok:!1,reason:"bad-schema"};const i=r_(s,{storage:e,note:"import"});return i?{ok:!1,reason:"storage-write-failed",note:String(i&&i.message||i).slice(0,120)}:{ok:!0,data:s}}const Hd={status:"idle"};let kr=Hd;const $g=new Set,Ud=t=>{kr=t,$g.forEach(e=>e(t))};let zg=null,Mc=0;const E6=t=>{const e=t||null;zg!==e&&(zg=e,Mc+=1,kr!==Hd&&Ud(Hd))},gE=()=>{const[t,e]=w.useState(kr);return w.useEffect(()=>($g.add(e),e(kr),()=>{$g.delete(e)}),[]),t};async function vE(t,e){var i;if(kr.status!=="conflict")return;const n=Mc;if(zg!==(t||null)||((i=kr.conflict)==null?void 0:i.deviceId)!==w6()){Ud(Hd);try{window.dispatchEvent(new Event("nexuscrew-roster-preferences"))}catch{}return}const s=await x6(e,kr.conflict,{token:t});n===Mc&&Ud({...s,at:Date.now()})}const N6=1500,R6=3e3,e1="nexuscrew-roster-preferences";function L6(t){w.useEffect(()=>{if(E6(t),!t)return;let n=null,s=!0;const i=async()=>{if(!s||kr.status==="conflict")return;const u=Mc,h=await S6({token:t});s&&u===Mc&&Ud({...h,at:Date.now()})},a=u=>{clearTimeout(n),n=setTimeout(i,u)},c=()=>{kr.status!=="conflict"&&a(R6)};return a(N6),window.addEventListener(e1,c),window.addEventListener("storage",c),()=>{s=!1,clearTimeout(n),window.removeEventListener(e1,c),window.removeEventListener("storage",c)}},[t]);const e=w.useCallback(n=>vE(t,n),[t]);return{state:gE(),resolve:e}}const A6=t=>typeof t.text=="function"?t.text():new Promise((e,n)=>{const s=new FileReader;s.onload=()=>e(String(s.result||"")),s.onerror=()=>n(s.error),s.readAsText(t)});function j6({token:t=""}){zn();const e=gE(),n=w.useRef(null),s=h=>vE(t,h),[i,a]=w.useState(null),c=()=>{try{const h=URL.createObjectURL(new Blob([k6()],{type:"application/json"})),f=document.createElement("a");f.href=h,f.download="nexuscrew-preferences.json",document.body.appendChild(f),f.click(),f.remove(),setTimeout(()=>URL.revokeObjectURL(h),1e3),a({ok:!0,text:p("prefs-export-done")})}catch(h){a({ok:!1,text:String((h==null?void 0:h.message)||h)})}},u=async h=>{const f=h.target.files&&h.target.files[0];if(h.target.value="",!f)return;let g="";try{g=await A6(f)}catch(_){a({ok:!1,text:String((_==null?void 0:_.message)||_)});return}if(!Dg(i_())&&!window.confirm(p("prefs-import-confirm")))return;const v=C6(g);a(v.ok?{ok:!0,text:p("prefs-import-done")}:{ok:!1,text:p(v.reason==="not-json"||v.reason==="wrong-kind"?"prefs-import-wrong":v.reason==="storage-write-failed"?"prefs-import-storage":"prefs-import-bad")})};return l.jsxs("div",{className:"nc-set-form nc-prefs-backup",children:[l.jsx("div",{className:"nc-sheet-label",children:p("prefs-backup")}),l.jsxs("div",{"data-testid":"sync-status",className:"nc-set-hint",children:[p("prefs-sync"),": ",e.status,e.revision!==void 0?` (r${e.revision})`:"",e.code?` · ${e.code}`:"",e.note?` · ${e.note}`:""]}),e.status==="conflict"&&l.jsxs("div",{className:"nc-set-confirm",role:"group","aria-label":p("prefs-conflict"),children:[l.jsx("div",{children:p("prefs-conflict")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>s("local"),children:p("prefs-keep-local")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>s("server"),children:p("prefs-use-server")})]})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:p("prefs-export")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>n.current&&n.current.click(),children:p("prefs-import")}),l.jsx("input",{ref:n,type:"file",accept:"application/json,.json","aria-label":p("prefs-import"),style:{display:"none"},onChange:u})]}),i&&l.jsx("div",{className:i.ok?"nc-set-note":"nc-err",role:i.ok?"status":"alert",children:i.text})]})}function M6({text:t}){const[e,n]=w.useState(!1),s=async()=>{try{await navigator.clipboard.writeText(t),n(!0),setTimeout(()=>n(!1),1500)}catch{}};return l.jsxs("div",{className:"nc-set-copyline",children:[l.jsx("code",{children:t}),l.jsxs("button",{type:"button",className:"nc-btn ghost",onClick:s,children:[l.jsx(Pt,{name:"copy",size:14})," ",p(e?"copied":"copy")]})]})}function T6({value:t}){const[e,n]=w.useState("");return w.useEffect(()=>{let s=!0;return ID.toDataURL(t,{margin:1,width:220}).then(i=>{s&&n(i)}).catch(()=>{}),()=>{s=!1}},[t]),e?l.jsx("img",{src:e,width:"220",height:"220",alt:"NexusCrew pairing QR"}):null}function P6({token:t,nodes:e,roster:n,settings:s,readonly:i,refresh:a,refreshAliases:c,vlUnavailable:u=[],accessRevision:h=null}){const[f,g]=w.useState(null),[v,_]=w.useState(null),[b,x]=w.useState(null),[L,C]=w.useState({ssh:"",sshPort:"",name:""}),[R,S]=w.useState(""),[I,E]=w.useState(""),[F,$]=w.useState(!1),[X,V]=w.useState(null),G=Date.now(),ne=s&&s.deviceName||"",K=(e||[]).filter(N=>N&&N.direction==="outbound"&&N.name&&N.ssh),D=K.find(N=>N.name===R)||K[0]||null,P=D?kg(D.tunnel,G):null,O=D!=null&&D.shared?P!=null&&P.up?"share-local-active":"share-local-pending":P!=null&&P.up?"share-local-private":"share-local-private-down",j=[{key:"peer-group-hubs",rows:(e||[]).filter(N=>N.kind!=="transitive"&&N.kind!=="vl"&&N.relation!=="client")},{key:"peer-group-clients",rows:(e||[]).filter(N=>N.kind!=="transitive"&&N.kind!=="vl"&&N.relation==="client")},{key:"peer-group-routed",rows:(e||[]).filter(N=>N.kind==="transitive")},{key:"peer-group-vl",rows:(e||[]).filter(N=>N.kind==="vl")}],z=X&&(e||[]).find(N=>`${N.kind||"direct"}:${N.nodeId||N.name}`===X)||null,M=async N=>{if(D){g(null),_(`${D.name}:share`);try{const U=await KN(t,D.name,N);await a(),U&&U.reversePoolPending===!0&&g(`${D.name}: ${p("share-reverse-pool-pending")}`)}catch(U){const T=U!=null&&U.data&&U.data.shared===!1?U.data:null;if(T)try{await a()}catch{}const H=U!=null&&U.data&&typeof U.data.hint=="string"?U.data.hint:"",se=(T==null?void 0:T.revoked)===!0&&(T==null?void 0:T.localReconcilePending)===!0?p("share-off-local-reconcile-pending"):(T==null?void 0:T.revoked)===!1&&(T==null?void 0:T.reconcilePending)===!0?p("share-off-hub-reconcile-pending"):"",Q=U!=null&&U.data&&U.data.reversePoolPending===!0?p("share-reverse-pool-pending"):"",Z=U!=null&&U.data&&typeof U.data.code=="string"?U.data.code:"",me=U!=null&&U.data&&typeof U.data.detail=="string"?U.data.detail.trim():"",de=me&&me!==String(U.message||"")?me:"";g(`${D.name}: ${String(U.message||U)}${Z?` [${Z}]`:""}${de?` — ${de}`:""}${H?` — ${H}`:""}${se?` — ${se}`:""}${Q?` — ${Q}`:""}`)}_(null)}},A=async()=>{g(null);const N=ho(L.name||I||ne||"NexusCrew"),U=$P({name:N,ssh:L.ssh,sshPort:L.sshPort});if(!U.ok){g(p(U.error));return}_("invite");try{x(await HN(t,{...I||ne?{label:I||ne}:{},name:N,ssh:U.value.ssh,...U.value.sshPort?{sshPort:U.value.sshPort}:{}}))}catch(T){g(String(T.message||T))}_(null)};return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-sheet-label",children:p("peer-inventory-title")}),(e||[]).length===0&&l.jsx("div",{className:"nc-empty",children:p("no-nodes")}),j.map(N=>N.rows.length>0&&l.jsxs("div",{className:"nc-peer-group",children:[l.jsxs("div",{className:"nc-peer-group-title",children:[p(N.key)," ",l.jsx("span",{children:N.rows.length})]}),N.rows.map(U=>{const T=VD(U);if(!T)return null;const H=`${U.kind||"direct"}:${U.nodeId||U.name}`,se=T.routed?{up:T.reach.up,since:null}:kg(U.tunnel,G);return l.jsxs("button",{type:"button",className:`nc-set-node nc-node-row${T.routed?" routed":""}`,"aria-label":`${T.title} — ${p("node-detail-open")}`,onClick:()=>V(H),children:[l.jsx("span",{className:`nc-dot ${T.reach.up?"on":""}`}),l.jsxs("span",{className:"nc-node-row-text",children:[l.jsx("b",{children:T.title}),l.jsxs("small",{children:[T.routed?T.routeLabel:`${T.subtitle} · ${p(T.exposure.shortKey)}`,!T.routed&&T.exposure.shortKey==="visibility-selected"?` (${T.exposure.count})`:""]})]}),l.jsxs("span",{className:`nc-set-tunnel${T.reach.up?" up":""}`,children:[p(T.reach.key),se.since?` · ${se.since}`:""]}),l.jsx("span",{className:"nc-node-row-more",children:l.jsx(Pt,{name:"chevronDown",size:14})})]},H)})]},N.key)),u.length>0&&l.jsxs("div",{className:"nc-err",children:[p("vl-owners-unavailable"),": ",u.map(N=>N.label||N.route.join("/")).join(", ")]}),z&&l.jsx(g3,{node:z,nodes:e||[],token:t,readonly:i,refresh:a,onClose:()=>V(null),peerAccessRevision:h}),(n||[]).some(N=>!N.direct&&N.instanceId)&&l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("routed-node-aliases")}),l.jsx("small",{className:"nc-set-hint",children:p("routed-node-aliases-help")}),(n||[]).filter(N=>!N.direct&&N.instanceId).map(N=>l.jsxs("div",{className:"nc-set-node",children:[l.jsxs("div",{className:"nc-set-node-head",children:[l.jsx("span",{className:`nc-dot ${N.status==="up"?"on":""}`}),l.jsx("b",{children:N.label||N.name}),l.jsx("small",{children:(N.route||[]).join(" › ")})]}),l.jsxs("div",{className:"nc-set-node-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!v,onClick:async()=>{const U=window.prompt(p("node-local-alias"),N.alias||"");if(U!=null){if(U.trim()&&!Ga(U.normalize("NFC"))){g(p("err-label"));return}_(`${N.instanceId}:alias`),g(null);try{U.trim()?await WN(t,N.instanceId,U):await Dw(t,N.instanceId),c()}catch(T){g(String(T.message||T))}_(null)}},children:p("alias-on-device")}),N.alias&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!v,onClick:async()=>{_(`${N.instanceId}:alias-reset`),g(null);try{await Dw(t,N.instanceId),c()}catch(U){g(String(U.message||U))}_(null)},children:p("reset-alias")})]})]},N.instanceId))]}),D&&l.jsxs("div",{className:"nc-set-form nc-local-share",children:[l.jsx("div",{className:"nc-sheet-label",children:p("share-local-heading")}),K.length>1&&l.jsxs("label",{className:"nc-field",children:[p("share-local-hub"),l.jsx("select",{value:D.name,disabled:i||!!v,onChange:N=>S(N.target.value),children:K.map(N=>l.jsx("option",{value:N.name,children:N.label||N.name},N.name))})]}),l.jsxs("label",{className:"nc-check nc-node-share",children:[l.jsx("input",{type:"checkbox",checked:D.shared===!0,disabled:i||!!v,onChange:N=>M(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("share-local-through").replace("{device}",ne||p("local")).replace("{hub}",D.label||D.name)}),l.jsx("small",{children:p(D.shared?"share-node-on-desc":"share-node-off-desc")})]})]}),l.jsx("div",{className:`nc-set-test${D.shared&&(P!=null&&P.up)?" ok":P!=null&&P.up?"":" ko"}`,children:p(O)}),!(P!=null&&P.up)&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!v,onClick:()=>M(D.shared===!0),children:p("share-local-reconnect")})]}),l.jsx(IC,{token:t,deviceDefault:ne,localNodeId:s&&s.nodeId||"",localNameDefault:s&&s.localName||"",readonly:i,onSuccess:a}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("invite-node")}),l.jsx("small",{className:"nc-set-hint",children:p("invite-v2-hint")}),l.jsxs("div",{className:"nc-set-info nc-invite-endpoint",children:[p("invite-target-local"),": ",l.jsx("b",{children:ne||p("invite-target-this")})]}),l.jsxs("label",{className:"nc-field",children:[p("invite-endpoint-label"),l.jsx("input",{placeholder:"user@host",value:L.ssh,disabled:i,onChange:N=>C({...L,ssh:N.target.value})}),l.jsx("small",{className:"nc-set-hint",children:p("invite-endpoint-needed")})]}),K.length>0&&l.jsx("small",{className:"nc-set-hint nc-invite-hub-hint",children:p("invite-hub-only")}),F&&l.jsxs("div",{className:"nc-invite-advanced",children:[l.jsxs("label",{className:"nc-field",children:[p("node-ssh-port-label"),l.jsx("input",{inputMode:"numeric",placeholder:"22",value:L.sshPort,disabled:i,onChange:N=>C({...L,sshPort:N.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),l.jsxs("label",{className:"nc-field",children:[p("device-name-label"),l.jsx("input",{placeholder:ne||"NexusCrew",value:I,disabled:i,onChange:N=>E(N.target.value)}),l.jsx("small",{className:"nc-set-hint",children:p("device-name-hint")})]}),l.jsxs("label",{className:"nc-field",children:[p("node-name-label"),l.jsx("input",{placeholder:ho(I||ne||p("node-name-ph")),value:L.name,disabled:i,onChange:N=>C({...L,name:N.target.value?ho(N.target.value):""})})]})]}),l.jsxs("div",{className:"nc-set-row nc-invite-actions",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:i||!!v||!L.ssh.trim(),onClick:A,children:p("create-pairing-link")}),l.jsxs("button",{type:"button",className:"nc-btn ghost",disabled:!!v,onClick:()=>$(N=>!N),children:[F?"▾":"▸"," ",p("pair-advanced")]})]}),b&&l.jsxs(l.Fragment,{children:[l.jsx(T6,{value:b.pairingUrl}),l.jsx(M6,{text:b.pairingUrl}),l.jsx("div",{className:"nc-set-info",children:p("invite-next-steps")})]})]}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function I6({token:t,readonly:e}){const[n,s]=w.useState("idle"),[i,a]=w.useState(()=>zC()),[c,u]=w.useState(!1),[h,f]=w.useState(null);w.useEffect(()=>{let _=!1;return FC().then(b=>{_||s(b)}),()=>{_=!0}},[]);const g=async()=>{f(null),u(!0);try{n==="subscribed"?(await HS(t),s("idle")):(await HC(t),s("subscribed"))}catch(_){const b=String(_.message||_);b==="push-denied"?(s("denied"),f(p("push-denied"))):b==="push-unsupported"?(s("unsupported"),f(p("push-unsupported"))):f(b==="push-disabled-local"?p("push-local-disabled"):b)}u(!1)},v=async()=>{const _=a3({enabled:i.enabled!==!1});if(a(_),f(null),_.enabled===!1&&n==="subscribed"){u(!0);try{await HS(t),s("idle")}catch{}u(!1)}};return n==="unsupported"?l.jsx("div",{className:"nc-set-info",children:p("push-unsupported")}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:v,disabled:c,children:i.enabled===!1?p("push-local-on"):p("push-local-off")}),l.jsx("span",{className:"nc-set-info",children:i.enabled===!1?p("push-local-off-note"):p("push-local-help")})]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||c||n==="denied",title:e?p("settings-readonly"):"",onClick:g,children:p(n==="subscribed"?"push-disable":"push-enable")}),l.jsx("span",{className:"nc-set-info",children:p(n==="subscribed"?"push-on":n==="denied"?"push-denied":"push-off")})]}),h&&l.jsx("div",{className:"nc-err",children:h})]})}function D6(){const[t,e]=uE(),[n,s]=w.useState(""),[i,a]=w.useState(""),[c,u]=w.useState(!1),[h,f]=w.useState(oE),g=w.useRef(0),v=w.useRef(!1),_=w.useRef(null),b=jc();w.useEffect(()=>()=>{var C;g.current+=1,v.current&&((C=_.current)==null||C.abort(),_.current=null,v.current=!1,Pg())},[]);const x=async()=>{const C=g.current+=1,R=typeof AbortController=="function"?new AbortController:null;s(""),a(""),u(!0),f(!1),v.current=!0,_.current=R;const S=await u6(p("notification-speech-preview"),Cd(),void 0,R?{signal:R.signal}:{});return C!==g.current||(_.current=null,v.current=!1,u(!1),f(S===!0),S===!0?a(p("notification-speech-preview-ok")):s(p(S==="voice-error"?"notification-speech-preview-voice-error":S==="timeout"?"notification-speech-preview-timeout":"notification-speech-preview-failed"))),S},L=C=>{var R;if(e(C),s(""),a(""),C)x();else{g.current+=1;const S=v.current;(R=_.current)==null||R.abort(),_.current=null,v.current=!1,u(!1),f(!1),Pg(),S||cE()}};return l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("notification-speech-enable"),checked:t,disabled:!b,onChange:C=>L(C.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("notification-speech-enable")}),l.jsx("small",{children:p("notification-speech-help")})]})]}),b?l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!t||c,onClick:()=>{x()},children:p(c?"notification-speech-testing":"notification-speech-test")})}):l.jsx("div",{className:"nc-set-info",children:p("notification-speech-unsupported")}),t&&!h&&!c&&!n&&l.jsx("div",{className:"nc-set-info",children:p("notification-speech-needs-test")}),i&&l.jsx("div",{className:"nc-set-info",role:"status",children:i}),n&&l.jsx("div",{className:"nc-err",children:n})]})}function O6({token:t,readonly:e,nodes:n=[],settings:s=null}){const[i,a]=w.useState(null),[c,u]=w.useState([]),[h,f]=w.useState({name:"",mode:"primary-failover",targets:[]}),[g,v]=w.useState(null),[_,b]=w.useState(!1),[x,L]=w.useState(null),[C,R]=w.useState(""),S=w.useCallback(async()=>{try{const[M,A]=await Promise.all([YN(t),QN(t)]);a(M),u(Array.isArray(A==null?void 0:A.groups)?A.groups:[]),R("")}catch(M){R(String(M.message||M))}},[t]);w.useEffect(()=>{S()},[S]);const I=async M=>{b(!0),L(null),R("");try{a(await GN(t,M))}catch(A){R(String(A.message||A))}b(!1)},E=async()=>{b(!0),L(null),R("");try{L({kind:"test",...await XN(t)})}catch(M){R(String(M.message||M))}b(!1)},F=async()=>{b(!0),L(null),R("");try{L({kind:"stop",...await JN(t)})}catch(M){R(String(M.message||M))}b(!1)},$=[],X=new Set,V=(M,A)=>{const N=typeof M=="string"?M.toLowerCase():"";!/^[a-f0-9]{32}$/.test(N)||X.has(N)||(X.add(N),$.push({id:N,label:A||N}))};V(s==null?void 0:s.nodeId,p("audio-group-local"));for(const M of n||[])V((M==null?void 0:M.nodeId)||(M==null?void 0:M.instanceId),(M==null?void 0:M.label)||(M==null?void 0:M.name)||(M==null?void 0:M.nodeId));for(const M of h.targets)V(M,`${M} (${p("audio-group-unavailable-target")})`);const G=(M=null)=>{R(""),M?(v(M.name),f({name:M.name,mode:M.mode,targets:[...M.targets||[]]})):(v(null),f({name:"",mode:"primary-failover",targets:[]}))},ne=(M,A)=>f(N=>({...N,targets:A?[...new Set([...N.targets,M])]:N.targets.filter(U=>U!==M)})),K=async()=>{const M=h.name.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(M)||h.targets.length<1){R(p("audio-group-invalid"));return}b(!0),R("");try{const A=await ZN(t,M,{targets:h.targets,mode:h.mode}),N=A==null?void 0:A.group;if(!N||!N.name)throw new Error(p("audio-group-save-failed"));u(U=>[...U.filter(T=>T.name!==N.name),N].sort((T,H)=>T.name.localeCompare(H.name))),G(null)}catch(A){R(String(A.message||A))}b(!1)},D=async M=>{b(!0),R("");try{await e5(t,M),u(A=>A.filter(N=>N.name!==M)),g===M&&G(null)}catch(A){R(String(A.message||A))}b(!1)},P=(i==null?void 0:i.installed)===!0,O=(i==null?void 0:i.liveness)==="ready",j=(i==null?void 0:i.consent)===!0&&P&&O,z=x?x.kind==="stop"?p(x.stopped?"audio-stop-stopped":"audio-stop-idle"):x.status==="accepted"||x.status==="spoken"?p("audio-test-accepted"):x.status==="unknown"?p("audio-test-unknown"):`${p("audio-test-refused")}${x.reason?` (${x.reason})`:""}`:"";return l.jsxs("div",{className:"nc-set-tab nc-audio-settings",children:[l.jsxs("div",{className:"nc-set-info",children:[l.jsx("b",{children:p("audio-title")}),l.jsx("br",{}),p("audio-help")]}),i?l.jsxs(l.Fragment,{children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("audio-consent"),checked:i.consent===!0,disabled:e||_,onChange:M=>{I(M.target.checked)}}),l.jsxs("span",{children:[l.jsx("b",{children:p("audio-consent")}),l.jsx("small",{children:p("audio-consent-help")})]})]}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("audio-capability")}),l.jsxs("div",{className:"nc-set-info",children:[p("audio-adapter"),": ",i.adapter||p("audio-adapter-none"),l.jsx("br",{}),p("audio-installed"),": ",p(P?"audio-installed-yes":"audio-installed-no"),l.jsx("br",{}),p("audio-liveness"),": ",p(O?"audio-liveness-ready":"audio-liveness-unavailable"),Array.isArray(i.languages)&&i.languages.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),p("audio-languages"),": ",i.languages.join(", ")]})]}),i.limits&&l.jsxs("small",{className:"nc-set-hint",children:[p("audio-limits"),": ",i.limits]})]}),!i.consent&&l.jsx("div",{className:"nc-set-info",children:p("audio-test-needs-consent")}),!P&&l.jsx("div",{className:"nc-set-info",children:p("audio-unavailable")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:e||_||!j,title:e?p("settings-readonly"):"",onClick:()=>{E()},children:p(_?"audio-testing":"audio-test")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>{F()},children:p(_?"audio-stopping":"audio-stop")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>{S()},children:p("refresh")})]}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("audio-groups-title")}),l.jsx("small",{className:"nc-set-hint",children:p("audio-groups-help")}),c.length===0&&l.jsx("div",{className:"nc-set-info",children:p("audio-groups-empty")}),c.map(M=>{var A;return l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("span",{children:[l.jsx("b",{children:M.name})," ",l.jsxs("small",{children:["· ",M.mode==="fanout"?p("audio-group-fanout"):p("audio-group-primary")," · ",((A=M.targets)==null?void 0:A.length)||0]})]}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>G(M),children:p("audio-group-edit")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>{D(M.name)},children:p("audio-group-delete")})]},M.name)}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>G(null),children:p("audio-group-new")})}),l.jsxs("label",{className:"nc-field",children:[p("audio-group-name"),l.jsx("input",{"aria-label":p("audio-group-name"),value:h.name,maxLength:"32",disabled:e||_,onChange:M=>f(A=>({...A,name:M.target.value}))})]}),l.jsxs("label",{className:"nc-field",children:[p("audio-group-mode"),l.jsxs("select",{"aria-label":p("audio-group-mode"),value:h.mode,disabled:e||_,onChange:M=>f(A=>({...A,mode:M.target.value})),children:[l.jsx("option",{value:"primary-failover",children:p("audio-group-primary")}),l.jsx("option",{value:"fanout",children:p("audio-group-fanout")})]})]}),l.jsx("div",{className:"nc-set-info",children:p("audio-group-targets")}),$.length===0?l.jsx("small",{className:"nc-set-hint",children:p("audio-group-no-targets")}):$.map(M=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:h.targets.includes(M.id),disabled:e||_,onChange:A=>ne(M.id,A.target.checked)}),l.jsxs("span",{children:[M.label,l.jsx("small",{children:M.id})]})]},M.id)),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:e||_,onClick:()=>{K()},children:p("audio-group-save")}),g&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>G(null),children:p("audio-group-cancel")})]})]})]}):l.jsx("div",{className:"nc-set-info",children:p("audio-loading")}),z&&l.jsx("div",{className:"nc-set-note",role:"status",children:z}),C&&l.jsx("div",{className:"nc-err",children:C})]})}function B6(){const[t,e]=Iv(),[n,s]=w.useState(tE),[i,a]=w.useState(sE),[c,u]=w.useState(iE);return l.jsxs("div",{className:"nc-set-tab nc-input-settings",children:[l.jsx("div",{className:"nc-set-info",children:p("input-settings-local")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-field",children:[p("terminal-keyboard-gesture"),l.jsx("select",{"aria-label":p("terminal-keyboard-gesture"),value:t.terminalKeyboardGesture,onChange:h=>e({terminalKeyboardGesture:h.target.value}),children:hC.map(h=>l.jsx("option",{value:h,children:p(`terminal-keyboard-${h}`)},h))}),l.jsx("small",{children:p("terminal-keyboard-gesture-help")})]}),l.jsxs("label",{className:"nc-field",children:[p("keybar-layout"),l.jsx("select",{"aria-label":p("keybar-layout"),value:t.keybarLayout,onChange:h=>e({keybarLayout:h.target.value}),children:fC.map(h=>l.jsx("option",{value:h,children:p(`keybar-layout-${h}`)},h))}),l.jsx("small",{children:p("keybar-layout-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.showComposer,onChange:h=>e({showComposer:h.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-menu-keyboard")}),l.jsx("small",{children:p("bar-menu-keyboard-desc")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:n,onChange:h=>{s(h.target.checked),nE(h.target.checked)}}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-menu-files")}),l.jsx("small",{children:p("bar-menu-files-setting-desc")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:i,onChange:h=>{a(h.target.checked),Y3(h.target.checked)}}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-keyboard-button")}),l.jsx("small",{children:p("bar-keyboard-button-desc")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:c,onChange:h=>{u(h.target.checked),G3(h.target.checked)}}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-panel-button")}),l.jsx("small",{children:p("bar-panel-button-desc")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.keybarKeepsKeyboardClosed,onChange:h=>e({keybarKeepsKeyboardClosed:h.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:p("keybar-ime-lock")}),l.jsx("small",{children:p("keybar-ime-lock-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.voiceKeepsKeyboardClosed,onChange:h=>e({voiceKeepsKeyboardClosed:h.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:p("voice-ime-lock")}),l.jsx("small",{children:p("voice-ime-lock-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.showKeybarEnter,onChange:h=>e({showKeybarEnter:h.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:p("keybar-enter-show")}),l.jsx("small",{children:p("keybar-enter-show-help")})]})]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>e(wr),children:p("input-settings-reset")})})]})}function $6({token:t,roster:e=[],readonly:n}){const s=[{key:"local",route:[],label:p("diagnostics-local"),status:"up"},...e.filter(j=>Array.isArray(j.route)&&j.route.length).map(j=>({key:j.route.join("/"),route:j.route,label:j.label||j.name,status:j.status}))],[i,a]=w.useState("local"),c=s.find(j=>j.key===i)||s[0],[u,h]=w.useState(null),[f,g]=w.useState([]),[v,_]=w.useState(""),[b,x]=w.useState(!1),[L,C]=w.useState(!0),[R,S]=w.useState(900),[I,E]=w.useState("all"),[F,$]=w.useState(""),X=w.useRef(0),V=w.useRef(null),G=w.useCallback(async()=>{try{const j=await i5(t,c.route);if(h(j),_(""),!b){const z=await r5(t,{after:X.current,limit:200},c.route);Array.isArray(z.records)&&z.records.length&&(X.current=z.cursor,g(M=>[...M,...z.records].slice(-500)))}}catch(j){_(j&&j.status===404?p("diagnostics-unsupported"):String(j.message||j))}},[t,c.key,b]);w.useEffect(()=>{X.current=0,g([]),h(null),_("")},[c.key]),w.useEffect(()=>{let j=null,z=!0;const M=()=>{!z||document.visibilityState==="hidden"||G()},A=()=>{j&&clearInterval(j),j=document.visibilityState==="hidden"?null:setInterval(M,2e3),document.visibilityState!=="hidden"&&M()};return document.addEventListener("visibilitychange",A),A(),()=>{z=!1,j&&clearInterval(j),document.removeEventListener("visibilitychange",A)}},[G]),w.useEffect(()=>{L&&V.current&&(V.current.scrollTop=V.current.scrollHeight)},[f,L]);const ne=f.filter(j=>(I==="all"||j.level===I)&&(!F||String(j.component||"").toLowerCase().includes(F.toLowerCase()))),K=ne.map(j=>`${j.ts} ${j.level.toUpperCase()} ${j.component} ${j.code} ${j.message}${Object.keys(j.meta||{}).length?` ${JSON.stringify(j.meta)}`:""}`).join(`
|
|
168
168
|
`),D=async j=>{_("");try{const z=await j();h(z),await G()}catch(z){_(String(z.message||z))}},P=async()=>{try{await navigator.clipboard.writeText(K)}catch{_(p("copy-manual"))}},O=()=>{try{const j=new Blob([`${JSON.stringify(ne,null,2)}
|
|
169
|
-
`],{type:"application/json"}),z=URL.createObjectURL(j),M=document.createElement("a");M.href=z,M.download="nexuscrew-diagnostics.json",M.click(),URL.revokeObjectURL(z)}catch{_(p("diagnostics-export-failed"))}};return l.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[l.jsxs("label",{className:"nc-field",children:[p("diagnostics-target"),l.jsx("select",{value:c.key,onChange:j=>a(j.target.value),children:s.map(j=>l.jsxs("option",{value:j.key,children:[j.label,j.status!=="up"?` · ${j.status}`:""]},j.key))})]}),l.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[l.jsx("div",{className:"nc-sheet-label",children:p("diagnostics-verbose")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("select",{"aria-label":p("diagnostics-duration"),value:R,onChange:j=>S(Number(j.target.value)),disabled:n,children:[300,900,1800,3600].map(j=>l.jsxs("option",{value:j,children:[j/60," min"]},j))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(u==null?void 0:u.verbose)===!0,onClick:()=>D(()=>Ow(t,!0,R,c.route)),children:p("enable")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(u==null?void 0:u.verbose)!==!0,onClick:()=>D(()=>Ow(t,!1,R,c.route)),children:p("stop")})]}),l.jsx("small",{className:"nc-set-hint",children:u!=null&&u.verbose?p("diagnostics-expires").replace("{time}",new Date(u.expiresAt).toLocaleTimeString()):p("diagnostics-off")})]}),l.jsxs("div",{className:"nc-diag-filters",children:[l.jsxs("select",{"aria-label":p("diagnostics-level"),value:I,onChange:j=>E(j.target.value),children:[l.jsx("option",{value:"all",children:p("diagnostics-all-levels")}),["debug","info","warn","error"].map(j=>l.jsx("option",{value:j,children:j},j))]}),l.jsx("input",{"aria-label":p("diagnostics-component"),placeholder:p("diagnostics-component"),value:F,onChange:j=>$(j.target.value)})]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:b,onChange:j=>x(j.target.checked)})," ",p("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:L,onChange:j=>C(j.target.checked)})," ",p("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:V,className:"nc-diag-log","aria-label":p("diagnostics-log"),children:K||p("diagnostics-empty")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:P,children:p("copy")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:O,children:p("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(p("diagnostics-clear-confirm"))&&D(async()=>{const j=await o5(t,c.route);return X.current=0,g([]),j})},children:p("diagnostics-clear")})]}),v&&l.jsx("div",{className:"nc-err",children:v})]})}function z6(){typeof window<"u"&&window.location&&typeof window.location.reload=="function"&&window.location.reload()}function F6({token:t,settings:e,readonly:n,refresh:s,roster:i,section:a,setSection:c}){const[u,h]=w.useState(xc),[f,g]=w.useState(null),[v,_]=w.useState(null),[b,x]=w.useState(!1),[L,C]=w.useState(!1),[R,S]=w.useState(null),[I,E]=w.useState(!1),[F,$]=w.useState(!1),[X,V]=w.useState(null);w.useEffect(()=>{S(e&&e.update||null),E(!!(e&&e.autoUpdate===!0)),$(!!(e&&e.alternateScreen))},[e]);const G=async()=>{g(null),_(null),C(!0);try{const N=await zN(t);_(N.note||"ok"),x(!1)}catch(N){g(String(N.message||N))}C(!1)},ne=async()=>{g(null),_(null),C(!0);try{const N=await t5(t);_(`${N.note||"ok"}${N.target?` (${N.target})`:""}`)}catch(N){g(String(N.message||N))}C(!1)},K=async N=>{g(null),_(null),C(!0);try{await xd(t,{autoUpdate:N}),E(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},D=async N=>{g(null),_(null),C(!0);try{await xd(t,{alternateScreen:N}),$(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},P=w.useCallback(async()=>{if(t)try{V(await $N(t))}catch{V(null)}},[t]);w.useEffect(()=>{P()},[P]);const O=async N=>{g(null),_(null),C(!0);try{if(!N&&X&&X.running&&!window.confirm(p("ai-desktop-confirm-stop"))){C(!1);return}const U=await T1(t,N);U&&U.ok===!1&&g(U.error||"comando fallito"),await P(),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},j=async()=>{g(null),_(null),C(!0);try{S(await n5(t))}catch(N){g(String(N.message||N))}C(!1)},z=async()=>{g(null),_(null),C(!0);try{const N=await s5(t);S(N),_(p("npm-update-restarting"))}catch(N){g(String(N.message||N))}C(!1)},M=()=>{window.confirm(p("composer-clear-confirm"))&&(g(null),pI()?(window.dispatchEvent(new Event(Ng)),_(p("composer-clear-done"))):g(p("composer-clear-failed")))},A=e&&e.service;return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-system-tabs",role:"tablist","aria-label":p("tab-system"),children:["general","diagnostics"].map(N=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===N,className:`nc-set-tabbtn${a===N?" on":""}`,onClick:()=>c(N),children:p(`system-${N}`)},N))}),a==="general"&&l.jsxs(l.Fragment,{children:[l.jsxs("section",{className:"nc-system-group",children:[l.jsx("div",{className:"nc-set-info",children:p("input-settings-local")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:u===fo,onChange:N=>{const U=fk(N.target.checked?fo:po);h(U),z6()}}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-menu-renderer")}),l.jsx("small",{children:p("bar-menu-renderer-desc")})]})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-this-node")}),e&&l.jsxs("div",{className:"nc-set-info",children:["v",e.version," · ",e.platform," · :",e.port,l.jsx("br",{}),A&&A.installed?p("service-installed"):p("service-missing"),A&&A.installed?` · ${A.active?p("service-active"):p("service-inactive")}`:"",A?` · boot ${A.boot?"on":"off"}`:""]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L,title:n?p("settings-readonly"):"",onClick:ne,children:p("service-regenerate")})}),l.jsx(I6,{token:t,readonly:n}),l.jsx(D6,{})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-updates")}),l.jsxs("div",{className:"nc-set-form nc-update-settings",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:I,disabled:n||L||R&&!R.supported,onChange:N=>K(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("npm-auto-update")}),l.jsx("small",{children:p("npm-auto-update-help")})]})]}),R&&l.jsxs("div",{className:"nc-set-info",children:[p("npm-update-current")," v",R.current,R.latest?` · ${p("npm-update-latest")} v${R.latest}`:""," · ",p(R.supported?R.phase==="idle"&&R.checked!==!0?"npm-update-never":`npm-update-${R.phase}`:"unsupported")]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L||!R||!R.supported,onClick:j,children:p("npm-update-check")}),R&&R.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||L||R.phase==="installing",onClick:z,children:p("npm-update-install")})]}),R&&R.lastError&&l.jsx("div",{className:"nc-err",children:R.lastError})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("ai-desktop-title")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("ai-desktop"),disabled:n||L,checked:!!(X&&X.desired),onChange:N=>O(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("ai-desktop")}),l.jsx("small",{children:p("ai-desktop-help")})]})]}),X&&!X.desired&&X.running&&l.jsx("div",{className:"nc-set-info",children:p("ai-desktop-stop-pending")})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-security")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L,title:n?p("settings-readonly"):"",onClick:()=>{g(null),_(null),x(!0)},children:p("token-rotate")})})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-local-data")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("composer-clear-data")}),l.jsx("small",{className:"nc-set-hint",children:p("composer-clear-data-help")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:M,children:p("composer-clear-data")})})]})]})]}),a==="diagnostics"&&l.jsxs("section",{className:"nc-system-group nc-system-diagnostics",children:[l.jsx("h3",{children:p("system-diagnostics")}),l.jsxs("div",{className:"nc-set-form nc-alternate-screen-settings",children:[l.jsx("div",{className:"nc-sheet-label",children:p("system-terminal")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("alternate-screen"),checked:F,disabled:n||L,onChange:N=>D(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("alternate-screen")}),l.jsx("small",{children:p("alternate-screen-help")})]})]})]}),l.jsx(j6,{token:t}),l.jsx(m6,{}),l.jsx($6,{token:t,roster:i,readonly:n})]}),b&&l.jsxs("div",{className:"nc-set-confirm",children:[l.jsx("div",{children:p("token-rotate-explain")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:L,onClick:()=>x(!1),children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:L,onClick:G,children:p("confirm")})]})]}),v&&l.jsx("div",{className:"nc-set-note",children:v}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function H6({token:t,onClose:e,initialTab:n="nodes",initialLocation:s="",startNewCell:i=!1}){zn();const a=n==="diagnostics"?"diagnostics":"general",[c,u]=w.useState(n==="diagnostics"?"system":n),h=w.useRef(null),f=w.useRef(null),[g,v]=w.useState({start:!1,end:!1}),[_,b]=w.useState(a),[x,L]=w.useState(null),[C,R]=w.useState([]),[S,I]=w.useState(null),[E,F]=w.useState([]),[$,X]=w.useState(!1),[V,G]=w.useState(null),[ne,K]=w.useState(0),D=bv(t,!0,ne),P=w.useCallback(()=>{const T=h.current;if(!T)return;const H=T.scrollWidth>T.clientWidth+1,se={start:H&&T.scrollLeft>1,end:H&&T.scrollLeft+T.clientWidth<T.scrollWidth-1};v(Q=>Q.start===se.start&&Q.end===se.end?Q:se)},[]);w.useEffect(()=>{const T=h.current;if(!T)return;const H=typeof ResizeObserver=="function"?new ResizeObserver(P):null;return H==null||H.observe(T),window.addEventListener("resize",P),P(),()=>{H==null||H.disconnect(),window.removeEventListener("resize",P)}},[P]),w.useEffect(()=>{var H,se;(se=(H=f.current)==null?void 0:H.scrollIntoView)==null||se.call(H,{behavior:"smooth",block:"nearest",inline:"nearest"});const T=window.requestAnimationFrame?window.requestAnimationFrame(P):setTimeout(P,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(T):clearTimeout(T)}},[c,P]);const O=w.useRef(Zd()),j=w.useRef(null),z=w.useRef([]),M=w.useRef(new Map),A=w.useRef({token:null,instanceId:null}),N=w.useCallback((T,H)=>{if(!T.isCurrent(H))return;const se=z.current,Q=[],Z=new Set;for(const me of M.current.values())for(const de of me){const ie=Array.isArray(de.route)&&de.route.length?de.route.join("/"):"local",xe=`${de.ownerInstanceId}:${ie}:${de.nodeId||de.name||de.label||""}`;Z.has(xe)||(Z.add(xe),Q.push(de))}R([...se,...Q])},[]),U=w.useCallback(async()=>{const T=O.current,H=T.begin();if(H===null)return;const se=new AbortController;j.current=se;const Q={timeoutMs:S1,signal:se.signal};try{const Z=A1(t,Q).then(ie=>{T.isCurrent(H)&&(L(ie),G(null))}).catch(ie=>{T.isCurrent(H)&&G(String((ie==null?void 0:ie.message)||ie))}),me=ON(t,Q).then(ie=>{if(!T.isCurrent(H))return;const xe=ie.peers||[];z.current=xe,I(Number.isInteger(ie.accessRevision)?ie.accessRevision:null),N(T,H)}).catch(ie=>{T.isCurrent(H)&&G(String((ie==null?void 0:ie.message)||ie))}),de=(async()=>{const[ie,xe]=await Promise.all([Pc(t,[],Q).then(ue=>ue).catch(()=>null),M1(t,Q).then(ue=>ue).catch(()=>null)]);if(!T.isCurrent(H))return;const Be=ie&&typeof ie.instanceId=="string"?ie.instanceId:"";if(!Be)return;A.current.instanceId!==Be&&(M.current.clear(),A.current.instanceId=Be);const nt=[{instanceId:Be||null,route:[],label:null},...Ek(xe,Be)],Le=ue=>`${ue.instanceId}:${ue.route.join("/")}`;if(xe){const ue=new Set(nt.map(Le));for(const Re of M.current.keys())ue.has(Re)||M.current.delete(Re)}if(!xe)for(const[ue,Re]of M.current)Re.some(fe=>fe.route.length)&&M.current.set(ue,Re.map(fe=>({...fe,stale:!0,online:!1,canManage:!1,capabilities:[]})));const Ie=new Map;F([]),N(T,H),await Promise.allSettled(nt.map(async ue=>{const Re=Le(ue);try{const fe=await j1(t,ue.route,{signal:se.signal});if(!T.isCurrent(H))return;const Ee=(fe.nodes||[]).map(Y=>Ck(Y,ue)).filter(Boolean);M.current.set(Re,Ee),Ie.delete(Re)}catch(fe){if(!T.isCurrent(H))return;if((fe==null?void 0:fe.status)===403||(fe==null?void 0:fe.status)===404)M.current.delete(Re);else{const Y=M.current.get(Re);Y&&M.current.set(Re,Y.map(pe=>({...pe,stale:!0,online:!1,canManage:!1,capabilities:[]})))}ue.route.length>0&&Ie.set(Re,{instanceId:ue.instanceId,label:ue.label,route:ue.route,failure:/timeout/i.test(String((fe==null?void 0:fe.message)||fe))?"timeout":"unreachable"})}T.isCurrent(H)&&(F([...Ie.values()]),N(T,H))}))})();await Promise.allSettled([Z,me,de])}finally{j.current===se&&(j.current=null),T.end(H)}},[t,N]);return w.useEffect(()=>{A.current.token!==t&&(A.current={token:t,instanceId:null},z.current=[],M.current.clear(),R([]),F([]),I(null)),U();const T=setInterval(U,5e3);return()=>{clearInterval(T),O.current.reset(),j.current&&j.current.abort()}},[U]),w.useEffect(()=>{let T=!1;return qn("/api/config",t).then(H=>H.json()).then(H=>{T||X(!!H.readonlyDefault)}).catch(()=>{}),()=>{T=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:T=>T.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(Pt,{name:"gear",size:18}),l.jsx("b",{children:p("settings")}),l.jsx("button",{type:"button",className:"nc-set-close",onClick:e,title:p("close"),children:l.jsx(Pt,{name:"x",size:18})})]}),$&&l.jsx("div",{className:"nc-set-readonly",children:p("settings-readonly")}),V&&l.jsx("div",{className:"nc-err",children:V}),l.jsx("div",{className:`nc-set-tabs-wrap${g.start?" has-start-overflow":""}${g.end?" has-end-overflow":""}`,children:l.jsx("div",{className:"nc-set-tabs",ref:h,onScroll:P,children:["nodes","fleet","audio","input","system"].map(T=>l.jsx("button",{ref:c===T?f:null,type:"button",className:`nc-set-tabbtn${c===T?" on":""}`,onClick:()=>u(T),children:p(`tab-${T}`)},T))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(P6,{token:t,nodes:C,roster:D,settings:x,readonly:$,vlUnavailable:E,accessRevision:S,refresh:U,refreshAliases:()=>K(T=>T+1)}),c==="fleet"&&l.jsx(V3,{token:t,readonly:$,startNewCell:i,initialLocation:s,targets:D.map(T=>({route:T.route,label:T.label||T.name,status:T.status}))}),c==="audio"&&l.jsx(O6,{token:t,readonly:$,nodes:C,settings:x}),c==="input"&&l.jsx(B6,{}),c==="system"&&l.jsx(F6,{token:t,settings:x,readonly:$,refresh:U,roster:D,section:_,setSection:b})]})]})})}function U6({token:t,initialPair:e,deviceDefault:n="",localNodeId:s="",localNameDefault:i="",deviceNameNeeded:a=!1,deviceNameSuggestion:c="",onPairDone:u,onDone:h}){zn();const[f,g]=w.useState(e?"pair":"welcome"),[v,_]=w.useState(!1),[b,x]=w.useState(null),[L,C]=w.useState(c||""),[R,S]=w.useState(null),I=async()=>{_(!0),x(null);try{const E={wizardDone:!0};a&&L.trim()&&(E.deviceName=L.trim()),await xd(t,E),u&&u(),h()}catch(E){x(String(E.message||E)),_(!1)}};return l.jsx("div",{className:"nc-wiz-overlay",children:l.jsxs("div",{className:"nc-wiz",children:[l.jsxs("div",{className:"nc-wiz-head",children:[l.jsx("b",{children:p("wizard-title")}),l.jsx("small",{children:p("hydra-simple")})]}),f==="welcome"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:p("local-ready")}),a&&l.jsx("div",{className:"nc-wiz-done",children:p("wizard-device-name")}),a&&l.jsxs("label",{className:"nc-field",children:[l.jsx("span",{children:p("device-name-label")}),l.jsx("input",{value:L,onChange:E=>C(E.target.value),maxLength:64,"data-testid":"wizard-device-name-input"})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:v,onClick:I,children:p("local-only")}),l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:()=>g("pair"),children:p("add-node")})]})]}),f==="pair"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx(IC,{token:t,initial:e||"",autoStart:!!e,deviceDefault:a&&L.trim()?L.trim():n,localNodeId:s,localNameDefault:i,onBusyChange:_,onSuccess:async E=>{S(E&&E.authorizedKeys?{line:E.authorizedKeys,note:E.authorizedKeysNote||""}:null),u&&u(),g("done")}}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn ghost",disabled:v,onClick:()=>{u&&u(),g("welcome")},children:p("back")})})]}),f==="done"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:p("node-connected")}),R&&l.jsx(Wv,{line:R.line,note:R.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:I,children:p("finish")})})]}),b&&l.jsx("div",{className:"nc-err",children:b})]})})}function W6({token:t,suggestion:e="",onSaved:n,onLater:s}){zn();const[i,a]=w.useState(e||""),[c,u]=w.useState(!1),[h,f]=w.useState(null),g=async()=>{const v=i.trim();if(v){u(!0),f(null);try{await xd(t,{deviceName:v}),n&&n(v)}catch(_){f(String(_.message||_)),u(!1)}}};return l.jsx("div",{className:"nc-wiz-overlay",role:"dialog","aria-label":p("device-name-ask-title"),"data-testid":"device-name-ask",children:l.jsxs("div",{className:"nc-wiz",children:[l.jsx("div",{className:"nc-wiz-head",children:l.jsx("b",{children:p("device-name-ask-title")})}),l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("p",{className:"nc-wiz-done",children:p("device-name-ask-text")}),l.jsxs("label",{className:"nc-field",children:[l.jsx("span",{children:p("device-name-label")}),l.jsx("input",{value:i,onChange:v=>a(v.target.value),maxLength:64,"data-testid":"device-name-input"})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c,onClick:s,children:p("device-name-later")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:c||!i.trim(),onClick:g,children:p("device-name-save")})]})]}),h&&l.jsx("div",{className:"nc-err",children:h})]})})}const q6=50;function K6(t){if(Number.isFinite(t))return t;const e=typeof t=="string"?Date.parse(t):NaN;return Number.isFinite(e)?e:0}function V6(t,e){return`${String(t)}|${String(e)}`}function t1(t,e){if(!t||typeof t!="object")return null;const n=t.frame&&typeof t.frame=="object"?t.frame:t;if(n.type!=="notify"||!t.eventId||typeof n.askId=="string"&&n.askId)return null;const s=typeof n.title=="string"?n.title:"",i=typeof n.body=="string"?n.body:"";return!s&&!i?null:{key:V6(e,t.eventId),ownerId:String(e),eventId:String(t.eventId),title:s,body:i,urgency:n.urgency==="high"?"high":"normal",ts:K6(t.ts)}}function n1(t){return[...t].sort((e,n)=>n.ts-e.ts).slice(0,q6)}function Y6(t,e,n){const s=new Map;for(const i of t||[])s.set(i.key,i);for(const i of e||[])i&&s.set(i.key,i);return[...s.values()]}function G6(t,e,n){if(typeof EventSource>"u"||!t)return()=>{};const s=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return s.onopen=()=>{typeof n=="function"&&n()},s.onmessage=i=>{try{const a=JSON.parse(i.data);a&&typeof a=="object"&&typeof a.type=="string"&&e(a)}catch{}},()=>{try{s.close()}catch{}}}const X6=6e3,J6=12e3,Zn=(t,e,n)=>`${e||""}:${n||t}`,Q6=(t,e)=>{const n=t&&t[e];return n?n.stale===!0||n.error===!0?"degraded":"live":"missing"},_E=600*1e3,Fg=new Map,Yo=t=>Object.hasOwn(t,"ownerAskTs")?t.ownerAskTs:t.ownerAskId||t.originNode?null:t.ts;function yE(t,e){Fg.set(t,e?{at:Date.now(),local:!0,ts:Yo(e),fingerprint:e.question===void 0?null:JSON.stringify([e.question,e.options||[],e.session])}:{at:Date.now()})}function wE(t){const e=Zn(t.id,t.ownerId,t.ownerAskId),n=Fg.get(e);if(n===void 0)return!1;if(n.local){const s=Yo(t);return!(n.ts&&s&&n.ts!==s)&&(n.fingerprint===null||n.fingerprint===JSON.stringify([t.question,t.options||[],t.session]))}return Date.now()-n.at>_E?(Fg.delete(e),!1):!0}function Sd(t,e){const n=new Map(t.map(s=>[Zn(s.id,s.ownerId,s.ownerAskId),s]));for(const s of e||[]){if(!s||!s.id||wE(s))continue;const i=Zn(s.id,s.ownerId,s.ownerAskId),a=n.get(i),c=Yo(s),u=a&&Yo(a);(!a||Number.isSafeInteger(c)&&c>0&&Number.isSafeInteger(u)&&u>0&&c>u)&&n.set(i,s)}return[...n.values()]}function Z6(t,e){const n=Sd([],t.filter(a=>a.imported)),s=new Set(n.map(a=>Zn(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!s.has(Zn(a.id,a.ownerId,a.ownerAskId))&&!wE(a)),...n]}function e4({n:t,onClose:e}){return l.jsxs("div",{className:`nc-ntf-toast${t.urgency==="high"?" high":""}`,role:"status","aria-live":"polite",children:[l.jsxs("div",{className:"nc-ntf-toast-txt",children:[l.jsx("b",{children:t.title}),t.body&&l.jsx("small",{children:t.body}),t.session&&l.jsx("span",{className:"nc-ntf-from",children:t.session}),t.ownerId&&l.jsx("span",{className:"nc-ntf-from",children:p("feed-owner")})]}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:e,title:p("close"),children:l.jsx(Pt,{name:"x",size:14})})]})}function t4({ask:t,token:e,onAnswered:n,onDismiss:s,askReplyAccess:i=!1,feedViewState:a="live",initialUncertainRid:c=null,canDismissLocal:u=!1,canDismissRemote:h=!1,capabilityStatus:f="loading",onRefused:g=()=>{}}){const[v,_]=w.useState(""),[b,x]=w.useState(!1),[L,C]=w.useState(null),[R,S]=w.useState(!1),[I,E]=w.useState(c),[F,$]=w.useState(!1),[X,V]=w.useState(!1),G=w.useRef(null);w.useEffect(()=>{c&&E(c)},[c]);const ne=R||b||!!I||X||!!t.ownerId&&(["loading","unsupported"].includes(f)||!u&&!h),K=!!t.ownerId&&u===!0,D=async j=>{const z=String(j||"").trim();if(!(!z||b||R||I||X)){C(null),x(!0);try{if(t.ownerId){const M=t.ownerAskId||t.id,A=await u5(e,{ownerId:t.ownerId,askId:M,text:z,requestId:G.current||(G.current=crypto.randomUUID())});if(A&&A.uncertain){const N=A.reason==="delivery-unknown-block"&&!A.originalRequestId;E(N?null:A.originalRequestId||A.requestId||G.current),V(N);return}if(!A||A.status!=="committed"){G.current=null,g(),C(p("ask-reconcile"));return}n(t.id,t.ownerId,t.ownerAskId)}else await l5(e,t.id,z),n(t.id)}catch(M){C(String(M.message||M)),t.ownerId&&!M.status?E(G.current):G.current=null,g()}finally{x(!1)}}},P=async()=>{if(!ne){C(null),S(!0);try{let j;if(K){if(j=await m5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),(j==null?void 0:j.dismissed)!==!0||j.scope!=="local"||!["pending","blocked"].includes(j.ownerSync))throw new Error(p("ask-dismiss-unconfirmed"))}else t.ownerId?await p5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}):await c5(e,t.id);yE(Zn(t.id,t.ownerId,t.ownerAskId),K?t:null),s(t.id,t.ownerId,t.ownerAskId,j)}catch(j){C(String(j&&j.message||j)),g()}finally{S(!1)}}},O=p(I||X?"ask-uncertain":K?"ask-dismiss-local":a==="degraded"?"ask-dismiss-stale":"ask-dismiss");return l.jsxs("div",{className:"nc-ask-card",children:[l.jsxs("div",{className:"nc-ask-head",children:[l.jsx("span",{className:"nc-ntf-from",children:t.session}),t.ownerId&&l.jsx("span",{className:"nc-ntf-from",children:p("feed-owner")}),l.jsxs("code",{className:"nc-ask-id",children:["#",t.id]}),l.jsx("button",{type:"button",className:"nc-ask-dismiss",title:O,"aria-label":O,disabled:ne,onClick:P,children:l.jsx(Pt,{name:"x",size:14})})]}),l.jsx("div",{className:"nc-ask-q",children:t.question}),t.ownerId&&i===!1&&l.jsx("small",{className:"nc-set-hint",children:p(f==="loading"?"ask-capability-loading":f==="unsupported"?"ask-capability-unsupported":f==="unreachable"?"ask-capability-unreachable":"ask-remote-readonly")}),t.ownerId&&i!==!1&&a==="degraded"&&l.jsx("small",{className:"nc-set-hint",children:p("ask-feed-stale")}),(I||X)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:p("ask-uncertain")}),X&&!I&&l.jsx("div",{className:"nc-err",children:p("ask-reconcile")}),I&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:F,onClick:async()=>{$(!0);try{const j=await d5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id,requestId:I});(j==null?void 0:j.state)==="committed"?n(t.id,t.ownerId,t.ownerAskId):(j==null?void 0:j.state)==="failed"&&(E(null),G.current=null,g())}catch(j){C(String(j.message||j)),g()}finally{$(!1)}},children:p("ask-verify")})]}),(!t.ownerId||i===!0)&&!I&&!X&&l.jsxs(l.Fragment,{children:[Array.isArray(t.options)&&t.options.length>0&&l.jsx("div",{className:"nc-ask-opts",children:t.options.map(j=>l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:b||R,onClick:()=>D(j),children:j},j))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:p("ask-reply-ph"),value:v,disabled:b||R,onChange:j=>_(j.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:b||R||!v.trim(),onClick:()=>D(v),children:p("send")})]})]}),L&&l.jsx("div",{className:"nc-err",children:L})]})}function n4({token:t}){const[e]=zn(),[n]=uE(),[s,i]=w.useState([]),[a,c]=w.useState([]),[u,h]=w.useState(null),[f,g]=w.useState([]),[v,_]=w.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),[b,x]=w.useState({}),L=w.useRef(new Map),C=w.useRef(0),[R,S]=w.useState(0),I=w.useRef(new Map),E=w.useRef(0),F=w.useRef(new Map),$=w.useRef(new Map),X=w.useRef(new Map),V=Q=>(Q||[]).filter(Z=>{const me=I.current.get(Zn(Z.id,Z.ownerId,Z.ownerAskId));if(!me)return!0;if(Date.now()-me.at>_E)return I.current.delete(Zn(Z.id,Z.ownerId,Z.ownerAskId)),!0;const de=Yo(Z);return Number.isSafeInteger(de)&&de>0&&Number.isSafeInteger(me.ts)&&me.ts>0?de!==me.ts:me.fingerprint!==null&&me.fingerprint!==void 0&&me.fingerprint!==JSON.stringify([Z.question,Z.options||[],Z.session])}),G=w.useRef(a);G.current=a;const ne=w.useCallback((Q=!1)=>{if(!t)return;const Z=new Set;for(const me of G.current){if(!me.ownerId)continue;const de=me.ownerAskId||me.id,ie=`${me.ownerId}|${de}`;Z.add(ie);const xe=L.current.get(ie);if(xe&&(!Q||xe.pending))continue;const Be=new AbortController,nt=C.current,Le={controller:Be,pending:!0};L.current.set(ie,Le),x(Ie=>({...Ie,[ie]:{canReply:!1,status:"loading"}})),h5(t,{ownerId:me.ownerId,askId:de},{signal:Be.signal}).then(Ie=>{if(nt!==C.current||Be.signal.aborted||L.current.get(ie)!==Le)return;const ue=Ie&&Ie.ownerId===me.ownerId&&Ie.askId===de&&typeof Ie.canReply=="boolean"&&(!Ie.canReply||Ie.status==="open");x(Re=>({...Re,[ie]:ue?Ie:{canReply:!1,status:"unreachable"}}))}).catch(()=>{nt===C.current&&!Be.signal.aborted&&L.current.get(ie)===Le&&x(Ie=>({...Ie,[ie]:{canReply:!1,status:"unreachable"}}))}).finally(()=>{Le.pending=!1})}for(const[me,de]of L.current)Z.has(me)||(de.controller.abort(),L.current.delete(me))},[t]);w.useEffect(()=>{C.current++;for(const Q of L.current.values())Q.controller.abort();return L.current.clear(),x({}),()=>{C.current++;for(const Q of L.current.values())Q.controller.abort();L.current.clear()}},[t]),w.useEffect(()=>{ne()},[a,ne]);const K=w.useRef(!1);w.useEffect(()=>{v&&(K.current&&ne(!0),K.current=!0)},[v,ne]);const D=w.useRef(0),P=w.useRef(null);P.current||(P.current=d6());const O=w.useRef({enabled:n,lang:e});O.current={enabled:n,lang:e};const j=w.useCallback(Q=>{i(Z=>Z.filter(me=>me.key!==Q))},[]),z=w.useCallback(Q=>{if(Q.askId&&Q.ownerId){const de=Number.isSafeInteger(Q.ownerAskTs)&&Q.ownerAskTs>0?Q.ownerAskTs:Q.ownerAskFingerprint;if(de){const ie=JSON.stringify([Q.ownerId,Q.ownerAskId||Q.askId,de]),xe=Date.now();for(const[Be,nt]of X.current)xe-nt>1440*60*1e3&&X.current.delete(Be);if(X.current.has(ie))return;X.current.set(ie,xe),X.current.size>4096&&X.current.delete(X.current.keys().next().value)}}const Z=`t${D.current+=1}`;i(de=>[...de.slice(-3),{...Q,key:Z}]),setTimeout(()=>j(Z),Q.urgency==="high"?J6:X6);const me=O.current;if(me.enabled)try{P.current.enqueue(Q,o6(Q,me.lang))}catch{}},[j]);w.useEffect(()=>{n||P.current.stop()},[n]),w.useEffect(()=>{const Q=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&P.current.stop()},Z=()=>P.current.stop();return document.addEventListener("visibilitychange",Q),window.addEventListener("blur",Q),window.addEventListener(Tg,Z),()=>{document.removeEventListener("visibilitychange",Q),window.removeEventListener("blur",Q),window.removeEventListener(Tg,Z),typeof P.current.dispose=="function"?P.current.dispose():P.current.stop()}},[]);const M=Q=>{if(Q.ownerAskId||!Q.ownerId)return Q;const Z=G.current.filter(de=>de.ownerId===Q.ownerId&&(de.id===Q.id||de.ownerAskId===Q.id)),me=new Set(Z.map(de=>de.ownerAskId||de.id));return me.size>1?null:{...Q,ownerAskId:me.size===1?[...me][0]:Q.id}},A=(Q,Z)=>{const me=G.current.find(ie=>Zn(ie.id,ie.ownerId,ie.ownerAskId)===Q),de=me&&Yo(me);return Number.isSafeInteger(Z==null?void 0:Z.ownerAskTs)&&Z.ownerAskTs>0&&Number.isSafeInteger(de)&&de>0&&Z.ownerAskTs!==de},N=(Q,Z,me,de)=>{const ie=Zn(Q,Z,me);(de==null?void 0:de.scope)==="local"&&["pending","blocked"].includes(de.ownerSync)&&h(de.ownerSync);const xe=G.current.find(Le=>Zn(Le.id,Le.ownerId,Le.ownerAskId)===ie),Be=xe&&Yo(xe);if(A(ie,de))return;const nt=xe||(de==null?void 0:de.askGeneration);I.current.set(ie,{at:Date.now(),ts:xe?Be:de==null?void 0:de.ownerAskTs,fingerprint:nt&&nt.question!==void 0?JSON.stringify([nt.question,nt.options||[],nt.session]):null}),F.current.delete(ie),I.current.size>4096&&I.current.delete(I.current.keys().next().value),c(Le=>Le.filter(Ie=>Zn(Ie.id,Ie.ownerId,Ie.ownerAskId)!==ie))};w.useEffect(()=>{if(!t)return;const Q=G6(t,Z=>{if(Z.type==="feed-state-changed"){S(me=>me+1);return}if(Z.type==="notify"&&Z.ownerId&&Z.eventId){const me=t1(Z,Z.ownerId);me&&g(de=>n1(Y6(de,[me],null)))}if(Z.type==="notify")z(Z);else if(Z.type==="ask"&&Z.ask&&Z.ask.id){const me=Zn(Z.ask.id,Z.ask.ownerId,Z.ask.ownerAskId);F.current.set(me,++E.current),F.current.size>4096&&F.current.delete(F.current.keys().next().value),c(de=>Sd(de,V([Z.ask])))}else if(Z.type==="ask-answered"&&Z.id){const me=M(Z);me&&N(me.id,me.ownerId,me.ownerAskId,Z)}else if(Z.type==="ask-dismissed"&&(Z.id||Z.ownerAskId)){const me=M(Z);if(!me)return;const de=Zn(me.id,me.ownerId,me.ownerAskId);if(A(de,Z))return;const ie=Z.scope==="local"&&G.current.find(xe=>Zn(xe.id,xe.ownerId,xe.ownerAskId)===de);yE(de,Z.scope==="local"?ie||{...Z.askGeneration,ownerAskTs:Z.ownerAskTs}:null),N(me.id,me.ownerId,me.ownerAskId,Z)}},()=>{ne(!0),S(Z=>Z+1)});return()=>{Q()}},[t,z,ne]),w.useEffect(()=>{let Q=!0;const Z=E.current;return t&&a5(t).then(me=>{Q&&c(de=>Sd(Z6(de,V((me.asks||[]).filter(ie=>!ie.ownerId||($.current.get(ie.ownerId)||0)<=Z))),V(de.filter(ie=>(F.current.get(Zn(ie.id,ie.ownerId,ie.ownerAskId))||0)>Z))))}).catch(()=>{}),()=>{Q=!1}},[t,R]);const[U,T]=w.useState({});w.useEffect(()=>{if(!t)return;let Q=!0;return f5(t).then(Z=>{if(!Q)return;const me={};for(const de of Z&&Z.attempts||[])de&&de.state==="uncertain"&&de.ownerId&&de.askId&&de.requestId&&(me[de.ownerId+"|"+de.askId]=de.requestId);T(me)}).catch(()=>{}),()=>{Q=!1}},[t]);const[H,se]=w.useState({});return w.useEffect(()=>{let Q=!0;const Z=E.current;return g5(t).then(me=>{if(!Q)return;const de={},ie=[],xe=new Map,Be=new Set;for(const Le of me&&me.views||[]){de[Le.ownerId]={stale:Le.stale===!0,error:!!Le.lastError},Be.add(Le.ownerId);for(const Ie of Le.asks||[])Ie&&Ie.id&&ie.push({...Ie,ownerId:Le.ownerId,imported:!0});for(const Ie of Le.notifications||[]){const ue=t1(Ie,Le.ownerId);ue&&xe.set(ue.key,ue)}}se(de);const nt=new Set((me&&me.views||[]).filter(Le=>{const Ie=typeof Le.cursor=="string"&&/^([1-9]\d*):(\d+)$/.exec(Le.cursor);return Le.stale===!1&&Number.isSafeInteger(Le.viewEpoch)&&Le.viewEpoch>0&&Ie&&Number(Ie[1])===Le.viewEpoch&&Number.isSafeInteger(Number(Ie[2]))&&!Le.lastError&&!Le.error&&Le.resyncRequired!==!0&&Array.isArray(Le.asks)&&Le.asks.length<100}).map(Le=>Le.ownerId));for(const Le of nt)$.current.delete(Le),$.current.set(Le,++E.current),$.current.size>4096&&$.current.delete($.current.keys().next().value);c(Le=>Sd(Le.filter(Ie=>!nt.has(Ie.ownerId)||(F.current.get(Zn(Ie.id,Ie.ownerId,Ie.ownerAskId))||0)>Z),V(ie))),g(Le=>{const Ie=[];for(const ue of Le)Be.has(ue.ownerId)&&Ie.push(ue);for(const ue of xe.values())Ie.push({...ue,key:ue.key});return n1(Ie)})}).catch(()=>{}),()=>{Q=!1}},[t,R]),l.jsxs(l.Fragment,{children:[u&&l.jsx("div",{className:"nc-ntf-toasts",children:l.jsxs("div",{className:"nc-ntf-toast",role:"status",children:[l.jsx("div",{className:"nc-ntf-toast-txt",children:p(u==="blocked"?"ask-dismiss-local-blocked":"ask-dismiss-local-pending")}),l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("close"),onClick:()=>h(null),children:l.jsx(Pt,{name:"x",size:14})})]})}),s.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:s.map(Q=>l.jsx(e4,{n:Q,onClose:()=>j(Q.key)},Q.key))}),(a.length>0||f.length>0)&&!v&&l.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>_(!0),title:p("asks-title"),children:["? ",l.jsx("span",{className:"nc-ask-count",children:a.length+f.length})]}),(a.length>0||f.length>0)&&v&&l.jsxs("div",{className:"nc-ask-panel",children:[l.jsxs("div",{className:"nc-ask-panel-head",children:[l.jsx("b",{children:p("asks-title")}),l.jsx("span",{className:"nc-ask-count",children:a.length}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>_(!1),title:p("close"),children:l.jsx(Pt,{name:"x",size:16})})]}),l.jsxs("div",{className:"nc-ask-panel-body",children:[a.map(Q=>{var Z,me,de,ie,xe,Be;return l.jsx(t4,{ask:Q,token:t,askReplyAccess:!Q.ownerId||((Z=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:Z.canReply)===!0,canDismissLocal:((me=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:me.canDismissLocal)===!0,canDismissRemote:((de=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:de.canDismissRemote)===!0||((ie=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:ie.canDismissRemote)===void 0&&((xe=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:xe.canReply)===!0,capabilityStatus:((Be=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:Be.status)||"loading",onRefused:()=>ne(!0),feedViewState:Q.ownerId?Q6(H,Q.ownerId):"live",initialUncertainRid:Q.ownerId&&U[Q.ownerId+"|"+(Q.ownerAskId||Q.id)]||null,onAnswered:N,onDismiss:N},Zn(Q.id,Q.ownerId,Q.ownerAskId))}),f.length>0&&l.jsxs("div",{className:"nc-remote-notices",children:[l.jsx("div",{className:"nc-remote-notices-head",children:l.jsx("b",{children:p("remote-notices-title")})}),f.map(Q=>l.jsxs("div",{className:"nc-remote-notice"+(Q.urgency==="high"?" nc-remote-notice-high":""),children:[Q.title?l.jsx("b",{children:Q.title}):null,Q.body?l.jsx("div",{children:Q.body}):null,l.jsxs("div",{className:"nc-remote-notice-meta",children:[Q.ownerId.slice(0,8)," · ",new Date(Q.ts||Date.now()).toLocaleString()]})]},Q.key))]})]})]})]})}const bE="nc_fontsize",SE=9,xE=24;function Hg(t=globalThis.localStorage){const e=Number(t.getItem(bE));return e>=SE&&e<=xE?e:13}function kE(t,e=globalThis.localStorage){const n=Math.max(SE,Math.min(xE,t));return e.setItem(bE,String(n)),n}const s4=4e3;async function i4(t){const e=await qn("/api/sessions",t);if((e==null?void 0:e.ok)===!1)throw new Error(`HTTP ${e.status}`);const n=await e.json();if(!Array.isArray(n==null?void 0:n.sessions))throw new Error("invalid sessions payload");return n.sessions}async function om(t,e=[]){var u;const[n,s]=await Promise.allSettled([e.length?Xg(t,e):i4(t),Qa(t,e)]),i=n.status==="fulfilled"&&Array.isArray((u=n.value)==null?void 0:u.sessions)?n.value.sessions:Array.isArray(n.value)?n.value:null,a=s.status==="fulfilled"?s.value:null,c=(a==null?void 0:a.available)===!0&&Array.isArray(a.cells)?a.cells:null;return{sessions:i,cells:c,fresh:Array.isArray(i)&&Array.isArray(c)}}function CE(t,e,n){return n===!0&&(t==null?void 0:t.degraded)!==!0&&(t==null?void 0:t.active)===!0&&t.tmux!==!1&&!!t.tmuxSession&&(e||[]).some(s=>(s==null?void 0:s.name)===t.tmuxSession)}function r4(t){const e=new Map((t.sessions||[]).map(i=>[i.name,i])),n=[],s=(i,a,c,u=[],h="")=>{const f=new Map((a||[]).map(g=>[g.name,g]));for(const g of i||[]){const v=f.get(g.tmuxSession)||{},_=ch(g,v),b=CE(g,a,c);n.push({key:qa(u,g.tmuxSession||g.cell),session:g.tmuxSession,route:u,cellName:g.cell,label:g.cell,node:u.length?u.join("/"):"",nodeLabel:h,live:b,selectable:b,verified:c===!0,working:_.working,degraded:!!g.degraded,active:g.active===!0,activity:v.activity||g.activity||0,subtitle:_.subtitle,preview:v.preview||g.preview||"",telemetry:v.telemetry||null,panelUrl:g.panelUrl||""})}};s(t.cells,[...e.values()],t.localFresh===!0);for(const i of t.nodeGroups||[]){const a=Array.isArray(i.route)?i.route:[];i.kind==="vl"||!a.length||s(i.cells,i.sessions,i.switcherFresh===!0,a,i.label||i.name||"")}return n}function o4(t){const e=new Map,n=Array.isArray(t.sessions)?t.sessions:[],s=Array.isArray(t.cells)?t.cells:[],i=new Map(n.map(c=>[c.name,c])),a=new Set(s.map(c=>c.tmuxSession).filter(Boolean));e.set("local",Lv(s,n.filter(c=>!a.has(c.name)),i));for(const c of t.nodeGroups||[]){const u=Array.isArray(c.route)?c.route:[];if(c.kind==="vl"||!u.length)continue;const h=Array.isArray(c.cells)?c.cells:[],f=Array.isArray(c.sessions)?c.sessions:[],g=new Set(h.map(v=>v.tmuxSession).filter(Boolean));e.set(u.join("/"),mc({...c,route:u,cells:h,sessions:f,unmanaged:f.filter(v=>!g.has(v.name))}).rawItems)}return e}function a4(t,e,n,s){return[...new Set(t.map(a=>a.node||"local"))].flatMap(a=>{const c=t.filter(g=>(g.node||"local")===a),u=new Map((e.get(a)||[]).map(g=>[g.key,g])),h=new Map(c.map(g=>[g.key,g])),f=c.map(g=>{const v=u.get(g.key);return{...g,label:(v==null?void 0:v.label)||g.label,live:(v==null?void 0:v.live)??g.live,fresh:(v==null?void 0:v.fresh)===!0,activity:(v==null?void 0:v.activity)??g.activity}});return co(f,n,"all",Ii(s,a)).map(g=>h.get(g.key))})}function l4({token:t,current:e,onPick:n,onClose:s,panelPort:i=0,nodePanelPorts:a={},localNodeLabel:c="",hostByRoute:u={},onDesignateCell:h,onClearHostCell:f,onLiveHostApplied:g,sideKey:v=null,onToggleSide:_,pollMs:b=s4}){const[x,L]=w.useState(z0),[C,R]=w.useState(!1),[S,I]=w.useState(!1),[E,F]=w.useState(""),[$,X]=w.useState(null),V="stream",[G,ne]=w.useState(Hg),K=W=>ne(ee=>kE(ee+W)),[D,P]=w.useState(null),[O,j]=w.useState(!1),[z,M]=w.useState(""),A=w.useRef(null),N=w.useRef(null),U=w.useMemo(()=>r4(x),[x]),T=w.useMemo(()=>o4(x),[x]),{pins:H,orders:se,togglePin:Q,removePin:Z,pinError:me,canMoveRoster:de,moveRoster:ie,stepRoster:xe}=xv(),Be=w.useMemo(()=>a4(U,T,H,se),[U,T,H,se]),nt=w.useMemo(()=>C?Be:Be.filter(W=>W.selectable||W.degraded&&W.active),[Be,C]),Le=w.useMemo(()=>$?nt.find(W=>W.key===$&&W.selectable):null,[nt,$]);w.useEffect(()=>{$&&!nt.some(W=>W.key===$&&W.selectable)&&X(null)},[nt,$]);const Ie=w.useMemo(()=>D?U.find(W=>W.key===D.key):null,[U,D]),ue=!!(D&&Ie);w.useEffect(()=>{me&&me.message&&F(me.message)},[me]),w.useEffect(()=>{var J;const W=document.activeElement;(J=N.current)==null||J.focus();const ee=be=>{be.key==="Escape"&&!ue&&s()};return document.addEventListener("keydown",ee),()=>{var be;document.removeEventListener("keydown",ee),(be=W==null?void 0:W.focus)==null||be.call(W)}},[s,ue]),w.useEffect(()=>{let W=!0,ee=!1;const J=async()=>{if(ee)return;ee=!0;const ye=z0(),ot=Array.isArray(ye.nodeGroups)?ye.nodeGroups:[],oe=om(t),$e=pt=>pt.kind!=="vl"&&Array.isArray(pt.route)&&pt.route.length>0,ut=await Promise.all(ot.filter($e).map(async pt=>({group:pt,result:await om(t,pt.route)}))),kt=await oe;if(!W)return;const St=new Map(ut.map(({group:pt,result:Ut})=>[JSON.stringify(pt.route||[]),Ut])),Lt=ot.map(pt=>{if(!$e(pt))return{...pt,switcherFresh:!1};const Ut=St.get(JSON.stringify(pt.route||[]));return Ut?{...pt,sessions:Ut.sessions||pt.sessions||[],cells:Ut.cells||pt.cells||[],switcherFresh:Ut.fresh}:{...pt,switcherFresh:!1}}),_t=tC({...ye,sessions:kt.sessions||ye.sessions||[],cells:kt.cells||ye.cells||[],localFresh:kt.fresh,nodeGroups:Lt,refreshedAt:Date.now()});L(_t),I(!0),ee=!1};J();const be=setInterval(J,b);return()=>{W=!1,clearInterval(be)}},[t,b]);const[Re,fe]=w.useState(""),Ee={getLiveHost:W=>Xd(t,W),designateHostCell:(W,ee,J)=>Jd(t,W,ee,J),clearHostCell:(W,ee)=>Qd(t,W,ee)},Y=W=>(u[Cs(W)]||{}).hostCell||null,pe=async(W,ee)=>{fe(W.key);const J=await eh({action:ee?"remove":"use",cellId:W.cellName,route:W.route||[],api:Ee});fe(""),F(p(J.messageKey).replace("{cell}",J.hostCell||W.cellName)),J.ok&&g&&g({route:W.route||[],hostCell:J.hostCell,revision:J.revision})},Ae=W=>W.degraded?p("cell-degraded"):W.verified?W.selectable?W.working?p("cell-working"):p("cell-idle"):p("cell-off"):p("cell-switcher-not-confirmed"),ke=async W=>{if(F(""),!W.selectable){F(W.verified?p("cell-switcher-not-active"):p("cell-switcher-not-confirmed"));return}M(W.key);try{const ee=await om(t,W.route),J=(ee.cells||[]).find(be=>(be==null?void 0:be.cell)===W.cellName&&(be==null?void 0:be.tmuxSession)===W.session);if(ee.fresh!==!0){F(p("cell-switcher-verify-failed"));return}if(!CE(J,ee.sessions,ee.fresh)){F(p("cell-switcher-not-active"));return}n({session:W.session,...W.node?{node:W.node}:{},cellName:W.cellName}),s()}catch{F(p("cell-switcher-verify-failed"))}finally{M("")}},We=W=>{if(!W.selectable){ke(W);return}if($===W.key){ke(W);return}X(W.key)},Ne=w.useRef(null),ge=8,st=W=>{const ee=Ne.current;if(W.isPrimary===!1){ee&&ee.state==="open"&&(ee.state="invalid");return}if(ee&&ee.state==="open"&&(ee.id!==W.pointerId||ee.row!==W.currentTarget)){ee.state="invalid";return}Ne.current={id:W.pointerId,row:W.currentTarget,x:W.clientX,y:W.clientY,maxDelta:0,state:"open"}},Ze=W=>{const ee=Ne.current;!ee||ee.state!=="open"||ee.id!==W.pointerId||(ee.maxDelta=Math.max(ee.maxDelta,Math.hypot(W.clientX-ee.x,W.clientY-ee.y)),ee.maxDelta>ge&&(ee.state="invalid"))},De=W=>{const ee=Ne.current;!ee||ee.id!==W.pointerId||ee.state!=="open"||(ee.state=ee.maxDelta<=ge?"tap":"invalid")},He=W=>{const ee=Ne.current;ee&&ee.id===W.pointerId&&(ee.state="invalid")},qe=W=>{const ee=Ne.current;return Ne.current=null,W.detail===0?!0:!ee||ee.state==="invalid"||ee.row!==W.currentTarget?!1:Math.hypot(W.clientX-ee.x,W.clientY-ee.y)<=ge},wt=W=>({onToggleLive:()=>pe(W,Y(W.route||[])===W.cellName),onTogglePin:()=>Cv({view:lh({item:{key:W.key,value:{cell:W.cellName}},pins:H,hostByRoute:u,route:W.route||[]}),itemKey:W.key,togglePin:Q,removePin:Z})});return l.jsxs("div",{className:"nc-cell-switcher-backdrop",onClick:s,children:[Le&&l.jsxs("div",{className:"nc-cell-switcher-anteprima","data-testid":"cell-switcher-anteprima",onClick:W=>W.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-anteprima-testa",children:[l.jsxs("b",{children:[p("cell-switcher-preview-word")," ",Le.cellName]}),l.jsx("small",{children:p("cell-switcher-preview-readonly")}),l.jsxs("span",{className:"nc-cell-switcher-anteprima-zoom",children:[l.jsx("button",{type:"button",onClick:()=>K(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:"−"}),l.jsxs("span",{"data-testid":"cell-switcher-fontsize",children:[G," px"]}),l.jsx("button",{type:"button",onClick:()=>K(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:"+"})]})]}),l.jsx(mv,{row:Le,token:t,source:V,chrome:!1,panelPort:kc(Le.route||[],a,i),liveHost:Va({liveHost:u[Cs(Le.route||[])],cells:x.cells||[]}),onLiveHostApplied:g,fontSize:G,readOnly:!0})]}),l.jsxs("aside",{ref:A,className:`nc-cell-switcher${Le?" with-anteprima":""}`,role:"dialog","aria-label":p("fleet-cells"),tabIndex:-1,onClick:W=>W.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-controls",children:[l.jsx("b",{children:p("cell-switcher-title")}),c&&l.jsx("small",{className:"nc-cell-switcher-node",children:c}),l.jsxs("div",{className:"nc-cell-switcher-filter",role:"group","aria-label":p("cell-switcher-filter"),children:[l.jsx("button",{type:"button",className:C?"":"on","aria-pressed":!C,onClick:()=>{F(""),R(!1)},children:p("cell-switcher-show-active")}),l.jsx("button",{type:"button",className:C?"on":"","aria-pressed":C,onClick:()=>{F(""),R(!0)},children:p("cell-switcher-show-all")})]}),l.jsx("button",{type:"button",className:`nc-cell-switcher-reorder${O?" on":""}`,"aria-pressed":O,title:p("reorder-help"),"aria-label":p("reorder"),onClick:()=>{F(""),j(W=>!W)},children:"↕"}),l.jsx("button",{ref:N,type:"button",className:"nc-cell-switcher-close","aria-label":p("cell-switcher-close"),title:p("cell-switcher-close"),onClick:s,children:"×"})]}),!Le&&l.jsx("div",{className:"nc-cell-switcher-hint",children:p("cell-switcher-tap-hint")}),l.jsxs("div",{className:"nc-cell-switcher-list",children:[(()=>{const W=Va({liveHost:u[Cs([])],cells:x.cells||[]});if(!W||!W.cell)return null;const{modeKey:ee}=vP(W);return l.jsx("div",{className:"nc-cell-switcher-live-strip","data-testid":"cell-switcher-live-strip",children:p("cell-switcher-live-strip").replace("{cell}",W.cell).replace("{mode}",p(ee||"live-host-mode-unknown"))})})(),!S&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-refreshing")}),S&&nt.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-empty-active")}),nt.map((W,ee)=>{const J=(e==null?void 0:e.session)===W.session&&((e==null?void 0:e.node)||"")===W.node,be=!!D&&D.key===W.key,ye=v!=null&&v===W.key,ot=Ae(W),oe=cg(p,W.activity),$e=ug(p,W.telemetry),ut=[oe,$e].filter(Boolean).join(" · "),kt=W.node||"local",St=ee>0?nt[ee-1].node||"local":null,Lt=kt!==St,_t=T.get(kt)||U.filter(pt=>(pt.node||"local")===kt);return l.jsxs(w.Fragment,{children:[Lt&&l.jsx("div",{className:"nc-cell-switcher-position",children:p("cell-switcher-group").replace("{node}",W.nodeLabel||c||p("cell-switcher-group-local"))}),l.jsxs("div",{className:`nc-cell-switcher-row${J?" current":""}${$===W.key?" selected":""}${ye?" side":""}${W.selectable?"":" off"}`,"data-roster-key":W.key,"data-position":kt,children:[O&&l.jsx(Gi,{position:kt,itemKey:W.key,label:W.cellName,canMove:de,onMove:(pt,Ut)=>ie(kt,pt,Ut,_t),onStep:pt=>xe(kt,W.key,pt,_t)}),l.jsx("span",{className:"nc-cell-switcher-peek",children:l.jsx("span",{className:`nc-cell-switcher-dot${W.degraded?" warn":W.live?` on${W.working?" working":""}`:""}`})}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":J?"true":void 0,"aria-disabled":!W.selectable,"data-selected":$===W.key?"true":void 0,disabled:z===W.key,onPointerDown:st,onPointerMove:Ze,onPointerUp:De,onPointerCancel:He,onClick:pt=>{qe(pt)&&We(W)},children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsxs("span",{className:"nc-cell-switcher-nameline",children:[l.jsx("b",{children:W.cellName}),J&&l.jsx("span",{className:"nc-cell-switcher-here",children:p("cell-switcher-here")}),$===W.key&&l.jsx("span",{className:"nc-cell-switcher-taptwo",children:p("cell-switcher-two-taps")})]}),l.jsxs("span",{className:"nc-cell-switcher-stateline",children:[l.jsx("small",{className:"nc-cell-switcher-state",children:ot}),ut&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:ut})]})]})}),_&&l.jsx("button",{type:"button",className:`nc-cell-switcher-side${ye?" on":""}`,title:p(ye?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-label":p(ye?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-pressed":ye?"true":"false",disabled:J||!W.selectable,onClick:pt=>{pt.stopPropagation(),!J&&W.selectable&&_(W)},children:l.jsx(Pt,{name:"splitView",size:20})}),l.jsx("button",{type:"button",className:`nc-cell-switcher-menu${be?" on":""}`,title:`${p("cell-actions-open")}: ${W.cellName}`,"aria-label":`${p("cell-actions-open")}: ${W.cellName}`,"aria-haspopup":"menu","aria-expanded":be?"true":"false",onClick:pt=>{pt.stopPropagation(),P({key:W.key})},children:"⋯"})]})]},W.key)})]}),E&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:E}),ue&&(()=>{const W=Ie,ee=Ev({...oo({item:{key:W.key,value:{cell:W.cellName}},cellName:W.cellName,route:W.route||[],pins:H,hostByRoute:u}),canBoot:!1,alive:W.selectable,handlers:wt(W)});return l.jsx(Nv,{cellName:W.cellName,items:ee,busy:Re===W.key,onClose:()=>P(null)})})()]})]})}const c4=2e3;function u4(t){if(t.kind==="gap")return`${p("vl-events-gap")} ${t.count||"?"}`;if(t.kind==="truncate")return p("vl-events-truncated");if(t.kind==="turn_end")return p("vl-events-turn-end");if(t.kind==="done")return p("vl-events-done");if(t.kind==="writer_epoch")return p("vl-events-writer-epoch");if(t.kind==="tool_start")return`${p("vl-events-tool")} ${t.name||""}`.trim();if(t.kind==="tool_end"){const e=t.isError?p("vl-events-tool-failed"):p("vl-events-tool-ok");return`${p("vl-events-tool")} ${t.name||""} — ${e}`.trim()}return t.kind==="usage"?t.text||p("vl-events-usage"):t.text||""}function d4({token:t,nodeId:e,route:n=[]}){const[s,i]=w.useState([]),[a,c]=w.useState(!1),u=w.useRef(0),h=w.useRef(!1);return w.useEffect(()=>{let f=!0;u.current=0,h.current=!1,i([]);const g=async()=>{if(!h.current){h.current=!0;try{const b=await BN(t,e,u.current,n);if(!f)return;c(!1);const L=(Array.isArray(b==null?void 0:b.events)?b.events:[]).filter(C=>Number.isSafeInteger(C==null?void 0:C.seq)&&C.seq>u.current);L.length&&(i(C=>C.concat(L).slice(-500)),u.current=L[L.length-1].seq),Number.isSafeInteger(b==null?void 0:b.cursor)&&b.cursor>u.current&&(u.current=b.cursor)}catch{f&&c(!0)}finally{h.current=!1}}},v=()=>{g().catch(()=>{})};v();const _=setInterval(v,c4);return()=>{f=!1,clearInterval(_)}},[t,e,JSON.stringify(n)]),l.jsxs("div",{className:"nc-vl-events",children:[a&&l.jsx("div",{className:"nc-set-hint nc-vl-events-stale",children:p("vl-events-stale")}),s.length===0&&!a&&l.jsx("small",{className:"nc-set-hint","data-testid":"vl-events-empty",children:p("vl-events-empty")}),s.length>0&&l.jsx("ol",{className:"nc-vl-events-list",children:s.map(f=>l.jsx("li",{"data-testid":`vl-ev-${f.seq}`,className:`nc-vl-ev nc-vl-ev-${f.kind}${f.isError?" error":""}${f.kind==="gap"?" gap":""}`,children:u4(f)},`${f.seq}-${f.kind}`))})]})}function s1({peer:t,token:e,onBack:n}){var s;return zn(),t?l.jsxs("section",{className:"nc-vl-session-view",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:n,title:p("back"),children:[l.jsx(Pt,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:p("back")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:t.label,children:t.label}),((s=t.session)==null?void 0:s.profile)&&l.jsxs("small",{className:"nc-bar-sub",children:[t.session.profile," · ",p("vl-events-title")]})]}),l.jsx("span",{className:"nc-bar-right"})]}),l.jsx("div",{className:"nc-vl-session-body",children:l.jsx(d4,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Wd="nc_dual_side";function Ug(t,e){return!t||!e?!1:t.session===e.session&&(t.node||"")===(e.node||"")}function h4(t,e,n){return!n||!n.session||t&&Ug(t,n)?e:e&&Ug(e,n)?null:{session:n.session,...n.node?{node:n.node}:{},...n.ownerId?{ownerId:n.ownerId}:{}}}function f4(){try{const t=JSON.parse(localStorage.getItem(Wd)||"null");return!t||!t.main||!t.side||!t.main.session||!t.side.session?null:t}catch{return null}}function p4(t,e){try{if(!t||!e||!t.session||!e.session){localStorage.removeItem(Wd);return}const n=s=>({session:s.session,...s.node?{node:s.node}:{}});localStorage.setItem(Wd,JSON.stringify({main:n(t),side:n(e)}))}catch{}}function i1(){try{localStorage.removeItem(Wd)}catch{}}const m4=.2;function od(t){return Math.max(m4,t)}function g4(){try{if(typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches)return!0}catch{}try{return Number(globalThis.navigator&&globalThis.navigator.maxTouchPoints)>0}catch{return!1}}function v4({onSubmit:t,reason:e=""}){zn();const[n,s]=w.useState(""),[i,a]=w.useState(g4),c=n.trim(),u=h=>{h&&h.preventDefault&&h.preventDefault(),c&&t(c,i)};return l.jsxs("form",{className:"nc-auth",onSubmit:u,children:[l.jsx("p",{children:p("auth-prompt")}),e==="invalid"&&l.jsx("p",{className:"nc-auth-error",role:"alert",children:p("auth-invalid")}),l.jsx("input",{type:"text",value:n,placeholder:"token","aria-label":"token",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:h=>s(h.target.value)}),l.jsxs("label",{children:[l.jsx("input",{type:"checkbox",checked:i,onChange:h=>a(h.target.checked)})," ",p("remember-device")]}),l.jsx("button",{type:"submit",disabled:!c,children:"ok"})]})}const am=t=>_s(Pi(t)).length===0;function za(t,e){return Array.isArray(t)?t.flatMap(n=>{var c;const s={session:n.session,height:1,fontSize:n.fontSize};n.node&&(s.node=n.node),n.ownerId&&(s.ownerId=n.ownerId);const i=(c=e({columns:[{width:1,tiles:[s]}]}).columns[0])==null?void 0:c.tiles[0];if(!i)return[];const a={session:i.session,x:n.x,y:n.y,w:n.w,h:n.h,fontSize:n.fontSize};return i.node&&(a.node=i.node),i.ownerId&&(a.ownerId=i.ownerId),[a]}):[]}function r1(t,e){return t.length?t:Array.isArray(e.floating)&&e.floating.length?[]:void 0}function _4(t,e,n,s,i){const a=c=>za(c&&c.floating,u=>Ha(u,s,i));return LP(a(t),a(e),n)}function o1(t,e,n,s,i,a){const c=v=>Ha(v,i,a),u=v=>za(v&&v.floating,c),{grid:h,floating:f}=Od(n),g=AP(s(h),_4(t,e,f,i,a),{grid:t?c(t.layout):uo(),floating:u(t)},{grid:c(e.layout),floating:u(e)},{grid:h,floating:f});return Sg(g.grid,g.floating)}const lm=t=>Array.isArray(t)?t.join("/"):"",y4="nc-decks-cache-v1",EE=t=>`${y4}:${t}`;function w4(t){if(!t)return[];try{const e=localStorage.getItem(EE(t));if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)&&n.every(s=>s&&typeof s.id=="string"&&typeof s.name=="string")?n:[]}catch{return[]}}function b4(t,e){if(t)try{localStorage.setItem(EE(t),JSON.stringify(e))}catch{}}function S4(t){const e=new Set,n=[];for(const s of Array.isArray(t)?t:[])!s||!Ws.test(String(s.instanceId||""))||!Array.isArray(s.route)||!s.route.length||e.has(s.instanceId)||(e.add(s.instanceId),n.push({instanceId:s.instanceId,route:[...s.route],label:String(s.label||s.name||s.route.join(" › ")),status:s.status||"offline",stale:s.stale===!0,checking:s.checking===!0}));return n.sort((s,i)=>s.label.localeCompare(i.label))}function ec(t){return{instanceId:t.ownerId,route:t.ownerRoute||[],label:t.ownerLabel,status:t.available===!1?"offline":"up"}}function Do(t,e,n,s=!1,i=!0){const a=e.instanceId;return{...t,id:Vo(s?null:a,t.name),ownerId:a,ownerRoute:s?[]:[...e.route],ownerLabel:s?"Local":e.label,local:s,available:i,ownerTopology:Array.isArray(n)?n:[],layout:Ag(t.layout,a,n)}}function x4(t,e,n,s,i=[],a=[]){const[c,u]=w.useState([]),[h,f]=w.useState(!1),[g,v]=w.useState("idle"),[_,b]=w.useState(""),[x,L]=w.useState(!1),[C,R]=w.useState(""),S=w.useRef([]),I=w.useRef([]),E=w.useRef([]),F=w.useRef(new Map),$=w.useRef(""),X=w.useRef(e),V=w.useRef(n),G=w.useRef(!1),ne=w.useRef(!0),K=w.useRef(""),D=w.useMemo(()=>S4(i),[i]),P=D.map(ue=>`${ue.instanceId}:${lm(ue.route)}`).join("|"),O=D.map(ue=>`${ue.instanceId}:${ue.status??""}:${ue.checking?"checking":"settled"}`).join("|"),j=w.useRef(new Map(D.map(ue=>[ue.instanceId,ue.checking?"pending":ue.status])));I.current=D,E.current=a,V.current=n,X.current=e,S.current=c;const z=w.useCallback(ue=>Ha(ue.layout,$.current,I.current),[]),M=w.useCallback(()=>Xl(X.current,$.current),[]),A=w.useCallback(ue=>(Array.isArray(ue)?ue:[]).find(Re=>Re.id===M()),[M]),N=w.useCallback((ue,Re=!0,fe)=>{const Ee=fe===void 0?M():Xl(fe,$.current),Y=jp(ue,Ql(),E.current),pe=S.current.some(ke=>ke.id===Ee);S.current=Y,u(Y),b4($.current,Y.map(ke=>{if(!ke.refreshFailedAt)return ke;const We={...ke};return delete We.refreshFailedAt,We}));const Ae=Y.find(ke=>ke.id===Ee);if(Re&&Ae){ne.current=!0;const ke=Sg(z(Ae),za(Ae.floating,We=>Ha(We,$.current,I.current)));s(ke),Ae.local&&YI(Ae.name,Pi(ke))}else pe&&!Ae&&(ne.current=!0,s(uo()),b("deck non più condiviso dal nodo owner"));WI(Y.filter(ke=>ke.local).map(ke=>ke.name))},[s,z]),U=w.useCallback(async ue=>{let Re=await zu(t);const fe=Re.decks.find(Ee=>Ee.name==="main");if(Re.decks.length===1&&fe&&fe.revision===0&&am(fe.layout)){const Ee=UI(),Y=Pi(jg("main")||uo());if(!am(Y)){const pe=Ag(Y,ue,[]);Re.decks[0]=await Fu(t,"main",pe,0,[])}for(const pe of Ee.filter(Ae=>Ae!=="main"))try{let Ae=await Bw(t,pe,[]);const ke=Pi(jg(pe)||uo());am(ke)||(Ae=await Fu(t,pe,Ag(ke,ue,[]),Ae.revision,[]))}catch{}Re=await zu(t)}return Re},[t]),T=w.useCallback((ue,Re)=>{const fe=new Map(Re.map(pe=>[pe.id,pe])),Ee=new Set,Y=[];for(const pe of S.current){if(pe.local||pe.ownerId!==ue.instanceId){Y.push(pe);continue}const Ae=fe.get(pe.id);Ae&&(Y.push(Ae),Ee.add(pe.id))}for(const pe of Re)Ee.has(pe.id)||Y.push(pe);N(Y,!1)},[N]),H=w.useCallback(async ue=>{try{const[Re,fe]=await Promise.all([zu(t,ue.route),Iw(t,ue.route).catch(()=>({nodes:[]}))]);T(ue,Re.decks.map(Ee=>Do(Ee,ue,fe.nodes,!1,!0)))}catch(Re){if(Re&&(Re.status===403||Re.status===404)){T(ue,[]);return}const fe=S.current.filter(Ee=>!Ee.local&&Ee.ownerId===ue.instanceId).map(Ee=>({...Ee,stale:!0,refreshFailedAt:Date.now(),ownerRoute:[...ue.route],ownerLabel:ue.label}));T(ue,fe)}},[t,T]),se=w.useCallback(async({migrate:ue=!1}={})=>{const Re=await Pc(t,[]),fe=Ws.test(String(Re.instanceId||""))?Re.instanceId:"";if(!fe)throw new Error("instanceId locale non disponibile");$.current=fe,R(fe);const[Ee,Y]=await Promise.all([ue?U(fe):zu(t),Iw(t,[]).catch(()=>({nodes:[]}))]),pe={instanceId:fe,route:[],label:"Local"},Ae=Ee.decks.map(Ze=>Do(Ze,pe,Y.nodes,!0,!0)),ke=new Map(I.current.map(Ze=>[Ze.instanceId,Ze])),We=S.current.length?S.current:w4(fe),Ne=F.current,ge=Date.now(),st=We.filter(Ze=>!Ze.local).flatMap(Ze=>{const De=ke.get(Ze.ownerId);if(!De){const wt=Ne.get(Ze.ownerId);return wt===void 0?(Ne.set(Ze.ownerId,ge),[{...Ze,available:!1,stale:!0}]):ge-wt>wv?[]:[{...Ze,available:!1,stale:!0}]}Ne.delete(Ze.ownerId);const He=De.status==="up",qe=De.status==="pending"||De.checking===!0;return[{...Ze,available:qe?Ze.available:He?Ze.available!==!1:!1,stale:De.stale===!0,ownerRoute:[...De.route],ownerLabel:De.label}]});return setTimeout(()=>{for(const Ze of ke.values())Ze.status==="up"&&!Ze.checking&&H(Ze)},0),[...Ae,...st]},[t,U,H,P]);w.useEffect(()=>{if(!t)return;let ue=!1;const Re=K.current!==t;return K.current=t,se({migrate:Re}).then(fe=>{if(ue)return;const Ee=A(S.current),Y=A(fe),pe=Y&&(!Ee||Y.revision>Ee.revision||Ee.available!==Y.available||lm(Ee.ownerRoute)!==lm(Y.ownerRoute));N(fe,Re||!!pe&&!G.current),f(!0),Y&&b("")}).catch(fe=>{ue||(f(!0),b(String(fe.message||fe)))}),()=>{ue=!0}},[N,se,P,t,A]),w.useEffect(()=>{if(!S.current.length)return;const ue=jp(S.current,Ql(),a);(ue.length!==S.current.length||ue.some((fe,Ee)=>fe.id!==S.current[Ee].id))&&(S.current=ue,u(ue))},[a]),w.useEffect(()=>{const ue=j.current,Re=new Map;for(const fe of I.current){if(fe.checking||fe.status==="pending"){Re.set(fe.instanceId,ue.get(fe.instanceId)||"pending");continue}fe.status==="up"&&ue.get(fe.instanceId)!=="up"&&H(fe),Re.set(fe.instanceId,fe.status)}j.current=Re},[O,H]);const Q=w.useCallback(async(ue,Re=!0)=>{if(!h||!G.current)return!0;const fe=ue===void 0?M():Xl(ue,$.current),Ee=S.current.find(Y=>Y.id===fe);if(!Ee)return b(`deck inesistente: ${fe}`),!1;if(Ee.available===!1)return b(`nodo owner offline: ${Ee.ownerLabel}`),!1;v("saving");try{const{grid:Y,floating:pe}=Od(V.current),Ae=Jl(Pi(Y),Ee.ownerId,Ee.ownerTopology),ke=za(pe,ge=>Jl(ge,Ee.ownerId,Ee.ownerTopology)),We=await Fu(t,Ee.name,Ae,Ee.revision,Ee.ownerRoute,r1(ke,Ee)),Ne=Do(We,ec(Ee),Ee.ownerTopology,Ee.local,!0);return N(S.current.map(ge=>ge.id===fe?Ne:ge),!1),G.current=!1,v("saved"),b(""),L(!1),setTimeout(()=>v("idle"),1500),!0}catch(Y){if(Re&&Y.status===409&&Y.data&&Y.data.current){const pe=S.current.find(Ae=>Ae.id===fe);if(pe){const Ae=Do(Y.data.current,ec(pe),pe.ownerTopology,pe.local,!0),ke=o1(pe,Ae,V.current,We=>We,$.current,I.current);return jP(ke,V.current)||(V.current=ke,ne.current=!0,s(ke)),N(S.current.map(We=>We.id===fe?Ae:We),!1),G.current=!0,Q(fe,!1)}}return v("error"),b(String(Y.message||Y)),Y.status===409&&L(!0),!1}},[h,t,N,s]),Z=w.useCallback(async()=>{try{const ue=await se();G.current=!1,L(!1),N(ue,!0),b("")}catch(ue){b(String(ue.message||ue))}},[se,N]);w.useEffect(()=>{if(!h)return;const ue=ne.current&&!G.current;if(ne.current=!1,ue)return;G.current=!0,v("saving");const Re=setTimeout(Q,650);return()=>clearTimeout(Re)},[n,h,Q]),w.useEffect(()=>{if(!h)return;const ue=()=>{if(!G.current)return;const Re=S.current.find(Ae=>Ae.id===M());if(!Re||Re.available===!1)return;const{grid:fe,floating:Ee}=Od(V.current),Y=Jl(Pi(fe),Re.ownerId,Re.ownerTopology),pe=za(Ee,Ae=>Jl(Ae,Re.ownerId,Re.ownerTopology));v5(t,Re.name,Y,Re.revision,Re.ownerRoute,r1(pe,Re))};return window.addEventListener("pagehide",ue),window.addEventListener("beforeunload",ue),()=>{window.removeEventListener("pagehide",ue),window.removeEventListener("beforeunload",ue)}},[h,t,M]),w.useEffect(()=>{if(!h)return;const ue=setInterval(async()=>{try{const Re=await se(),fe=A(S.current),Ee=A(Re),Y=!!(Ee&&fe&&Ee.revision>fe.revision),pe=!!(Ee&&(!fe||Y||fe.available!==Ee.available));if(Y&&G.current&&Ee){const Ae=o1(fe,Ee,V.current,ke=>PP(z(Ee),ke),$.current,I.current);N(Re,!1),s(Ae);return}N(Re,pe&&!G.current)}catch{}},5e3);return()=>clearInterval(ue)},[h,se,N,z,s]);const me=w.useCallback(ue=>{s(Re=>{const fe=ue(Re);return fe!==Re&&(ne.current=!0),fe})},[]),de=async(ue,Re=null)=>{const fe=Re===Xi?S.current.find(pe=>pe.local):Re?S.current.find(pe=>pe.ownerId===Re):null;if(!fe||fe.available===!1)throw new Error("nodo owner non disponibile");const Ee=await Bw(t,ue,fe.ownerRoute),Y=Do(Ee,ec(fe),fe.ownerTopology,fe.local,!0);return N([...S.current,Y],!1),Y},ie=async(ue,Re)=>{const fe=S.current.find(ke=>ke.id===ue);if(!fe)throw new Error("deck inesistente");if(Xl(ue,$.current)===M()&&G.current&&!await Q(ue))throw new Error(`salvataggio di "${fe.name}" fallito: rinomina annullata`);const Ee=S.current.find(ke=>ke.id===ue);if(!Ee)throw new Error("deck inesistente");const Y=await _5(t,Ee.name,Re,Ee.revision,Ee.ownerRoute),pe=Do(Y,ec(Ee),Ee.ownerTopology,Ee.local,!0),Ae=Ee.local?Xi:Ee.ownerId;return Ap(KI(Ql(),Ae,ue,pe.id)),N(S.current.map(ke=>ke.id===ue?pe:ke),!1),pe},xe=async ue=>{const Re=S.current.find(Ee=>Ee.id===ue);if(!Re)throw new Error("deck inesistente");Xl(ue,$.current)===M()&&(G.current=!1),await y5(t,Re.name,Re.revision,Re.ownerRoute);const fe=Re.local?Xi:Re.ownerId;Ap(VI(Ql(),fe,ue)),N(S.current.filter(Ee=>Ee.id!==ue),!1)},Be=(ue,Re)=>{const fe=S.current.find(We=>We.id===ue),Ee=S.current.find(We=>We.id===Re);if(!fe||!Ee)return!1;const Y=fe.local?Xi:fe.ownerId,pe=Ee.local?Xi:Ee.ownerId;if(Y!==pe)return!1;const Ae=S.current.filter(We=>(We.local?Xi:We.ownerId)===Y).map(We=>We.id),ke=Ap(qI(Ql(),Y,ue,Re,Ae));return N(jp(S.current,ke),!1),!0},nt=async(ue,Re)=>{const fe=S.current.find(We=>We.id===ue);if(!fe)throw new Error("deck inesistente");if(fe.available===!1)throw new Error(`nodo owner offline: ${fe.ownerLabel}`);const Ee=vC(Re,$.current,I.current);if(!Ee)throw new Error("riferimento sessione non valido");const Y=z(fe),pe=Jl(qk(Y,Ee),fe.ownerId,fe.ownerTopology),Ae=await Fu(t,fe.name,pe,fe.revision,fe.ownerRoute),ke=Do(Ae,ec(fe),fe.ownerTopology,fe.local,!0);return N(S.current.map(We=>We.id===ue?ke:We),!1),ke},Le=w.useCallback(ue=>Sg(z(ue),za(ue.floating,Re=>Ha(Re,$.current,I.current))),[z]);return{decks:c,records:c,localNodeId:C,ready:h,saveState:g,error:_,setError:b,conflict:x,reloadCurrent:Z,saveNow:Q,select:async ue=>{if(G.current&&!await Q(M()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const Re=S.current.find(fe=>fe.id===ue);if(!Re)throw new Error(`deck inesistente: ${ue}`);return G.current=!1,ne.current=!0,Le(Re)},add:de,rename:ie,remove:xe,reorder:Be,addTileTo:nt,viewUpdate:me,vistaMaterializzata:Le,localMainId:Vo(null,"main"),parseDeckId:Hc}}const k4="/sw.js",Wg="nc-sw-update";let Tc=null,qd=!1,Kd=null,NE=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),RE=!1;function a_(){typeof window<"u"&&window.dispatchEvent(new Event(Wg))}function l_(){const t=Kd||(qd?{kind:"reload",version:"",browserVersion:""}:null);NE=Object.freeze({needed:!!t,kind:(t==null?void 0:t.kind)||null,version:(t==null?void 0:t.version)||"",browserVersion:(t==null?void 0:t.browserVersion)||""})}function a1(){return NE}function C4(t){return typeof window>"u"?()=>{}:(window.addEventListener(Wg,t),()=>window.removeEventListener(Wg,t))}function c_(t){qd!==t&&(qd=t,l_(),a_())}const ad="nc-auto-reload",Vd="nc-reload";function u_(){try{return typeof location<"u"?location:null}catch{return null}}function LE(){try{return typeof history<"u"?history:null}catch{return null}}function E4(t){const e=t===void 0?u_():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Vd)}catch{return null}}function N4(t,{location:e,history:n}={}){const s=e===void 0?u_():e,i=n===void 0?LE():n;if(!s||!i||typeof i.replaceState!="function")return!1;try{const a=new URLSearchParams(s.search||"");return a.set(Vd,t),i.replaceState(i.state??null,"",`${s.pathname||"/"}?${a.toString()}${s.hash||""}`),!0}catch{return!1}}function R4({location:t,history:e}={}){const n=t===void 0?u_():t,s=e===void 0?LE():e;if(!n||!s||typeof s.replaceState!="function")return!1;try{const i=new URLSearchParams(n.search||"");if(!i.has(Vd))return!1;i.delete(Vd);const a=i.toString();return s.replaceState(s.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const AE="nc-update-dismissed";function jE(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function L4(t,e,n){return[t,e,n].map(s=>s||"").join("|")}let qg=null;function A4(t,e,n){const s=n;return t&&e&&t!==e&&t!==s?{kind:"install",version:t,browserVersion:s}:e&&s&&e!==s?{kind:"stale",version:e,browserVersion:s}:null}function j4(t,e){if(!t)return!1;try{return t.getItem(AE)===e}catch{return!1}}function M4(t={}){const e=t.storage===void 0?jE():t.storage;if(qg&&e)try{e.setItem(AE,qg)}catch{}qd=!1,Kd=null,l_(),a_()}function T4(t,e,n,s={}){const i=s.storage===void 0?jE():s.storage,a=n,c=L4(t,e,a);qg=c;const u=A4(t,e,a);let h=j4(i,c)?null:u;if(h&&h.kind==="stale"){const g=`${e}|${a}`,v=E4(s.location)===g;let _=!1;if(!v&&i&&i.getItem(ad)!==g){try{i.setItem(ad,g)}catch{}_=i.getItem(ad)===g}_&&(N4(g,{location:s.location,history:s.history}),(s.applyImpl||ME)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Kd);if(Kd=h,l_(),f||a_(),!u){try{i&&i.removeItem(ad)}catch{}R4({location:s.location,history:s.history})}}const P4=1200;async function l1(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,P4))])}catch{}}async function ME(){try{Tc&&await Tc.update()}catch{}typeof location<"u"&&(await l1(location.pathname),await l1("/version.json"),location.reload())}function I4(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&c_(!0)})}function D4(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{RE&&location.reload()}),navigator.serviceWorker.register(k4).then(t=>{Tc=t,t.waiting&&c_(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&I4(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function O4(){RE=!0,c_(!1);const t=Tc&&Tc.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function B4({hash:t="",origin:e="",pathname:n="",search:s=""}={}){const i=String(t||"").replace(/^#/,""),a=`${n||""}${s||""}`;if(!i)return{token:"",pair:"",device:"",nextUrl:a};const c=new URLSearchParams(i),u=c.get("token")||"",h=c.get("device")||"",f=/^[a-f0-9]{32}$/.test(h)?h:"",g=c.get("pair")||"",v=g?`${e||""}${n||""}#pair=${g}`:"";return{token:u,pair:v,device:f,nextUrl:a}}const TE="nc_side_w",c1="nc_side_min",$4=240,u1=new Set(["absent","present","active","unknown"]);function z4(){const t=Number(localStorage.getItem(TE));return t>=180&&t<=480?t:$4}function F4(){const t={token:"",pair:""};try{const{token:e,pair:n,device:s,nextUrl:i}=B4({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e&&(t.token=e,b1(e,{remember:!0})),s&&y6(s),n){t.pair=n;try{sessionStorage.setItem("nc_pair",n)}catch{}}if(location.hash)try{history.replaceState(null,"",i)}catch{}}catch{}if(t.token||(t.token=_N()),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function d1(t){try{return Pi(jg(t))}catch{return uo()}}function h1(t){if(!t)return"";const e=Math.floor(Date.now()/1e3)-t;return e<0||e<60?"ora":e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}g`}function H4({showComposer:t,showFiles:e,showPanel:n,hasPanel:s,rendererKind:i,filesSetting:a=null,handlers:c={}}={}){const u=[];return typeof c.onToggleComposer=="function"&&u.push({id:"keyboard",kind:"switch",on:!!t,labelKey:"bar-menu-keyboard",descKey:"bar-menu-keyboard-desc",run:c.onToggleComposer}),typeof c.onToggleFiles=="function"&&u.push(a===null?{id:"files",kind:"switch",on:!!e,labelKey:"bar-menu-files",descKey:"bar-menu-files-desc",run:c.onToggleFiles}:{id:"files",kind:"switch",on:!!a,labelKey:"bar-menu-files",descKey:"bar-menu-files-setting-desc",run:c.onToggleFiles}),s&&typeof c.onTogglePanel=="function"&&u.push({id:"panel",kind:"switch",on:!!n,labelKey:"bar-menu-panel",descKey:"bar-menu-panel-desc",run:c.onTogglePanel}),typeof c.onSwitchRenderer=="function"&&u.push({id:"renderer",kind:"switch",on:i==="webgl",labelKey:"bar-menu-renderer",descKey:"bar-menu-renderer-desc",run:c.onSwitchRenderer}),u}function U4(t,e){if(!t||!t.tmux)return"";const n=ch(t,e||{});return n.stato==="lavora"?p("cell-working"):n.stato==="attesa"?p("cell-permission"):n.stato==="ferma"?p("cell-idle"):""}function f1({session:t,node:e,ownerId:n,cellName:s,token:i,readonly:a=!1,panelPort:c=0,onBack:u,onCellSwitcher:h,cellSwitcherOpen:f=!1,liveHost:g=null,side:v=null,onSideClose:_=null,onSideGone:b=null}){var le;zn();const[x]=Iv(),L=vk(),[C,R]=w.useState(!1),[S,I]=w.useState(null),[E,F]=w.useState(()=>x.showComposer),[$,X]=w.useState(Hg),[V,G]=w.useState(()=>xc()),ne=()=>{fk(OM(xc())),typeof window<"u"&&window.location.reload()},[K,D]=w.useState(s||t),[P,O]=w.useState(""),[j,z]=w.useState(""),[M,A]=w.useState(""),[N,U]=w.useState(!1),[T,H]=w.useState(!1),se=!!v&&T,[Q,Z]=w.useState(!1),[me,de]=w.useState({v:{main:1,side:1},h:{main:1,side:1}}),[ie,xe]=w.useState(()=>window.matchMedia("(orientation: landscape)").matches);w.useEffect(()=>{const re=window.matchMedia("(orientation: landscape)"),Te=Ge=>xe(Ge.matches);return re.addEventListener("change",Te),()=>re.removeEventListener("change",Te)},[]);const Be=ie?me.h:me.v,nt=w.useRef(Be);nt.current=Be;const[Le,Ie]=w.useState(null),[ue,Re]=w.useState(!0),fe=w.useRef(()=>{}),Ee=w.useRef(()=>!1),Y=w.useRef(()=>{}),pe=w.useRef(!1),Ae=w.useRef(!1),ke=w.useRef(null),We=w.useRef(null),[Ne,ge]=w.useState(null),st=w.useCallback(re=>ge({source:"main",ev:re}),[]),Ze=w.useCallback(re=>ge({source:"side",ev:re}),[]),De=!!v&&(Ne==null?void 0:Ne.source)==="side",He=re=>{H(re),St((re?pe:ut).current),pt((re?Ae:Lt).current)},qe=v?`${v.node||""}:${v.session}`:"";w.useEffect(()=>{H(!1),Z(!1),de({v:{main:1,side:1},h:{main:1,side:1}}),Ie(null),ge(re=>re&&re.source==="side"?null:re)},[qe]);const wt=w.useMemo(()=>{const re=new Map;return Te=>{if(re.has(Te))return re.get(Te);let Ge=Te*.6;try{const mt=document.createElement("span");mt.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-family:courier-new,courier,monospace;",mt.style.fontSize=`${Te}px`,mt.textContent="0".repeat(20),document.body.appendChild(mt);const q=mt.getBoundingClientRect().width;document.body.removeChild(mt),Number.isFinite(q)&&q>0&&(Ge=q/20)}catch{}return re.set(Te,Ge),Ge}},[]),W=Math.max(.01,Be.main+Be.side),ee=((le=We.current)==null?void 0:le.clientWidth)||window.innerWidth,J=Math.max(0,ee-12)*(Math.min(Be.main,Be.side)/W)-26,be=!!v&&ie&&J/wt(Math.max(1,$))<40,ye=re=>X(Te=>kE(Te+re));w.useEffect(()=>{f||X(Hg())},[f]);const ot=w.useRef(()=>{}),oe=w.useRef(()=>!1),$e=w.useRef(()=>{}),ut=w.useRef(!1),[kt,St]=w.useState(!1),Lt=w.useRef(!1),[_t,pt]=w.useState(!1),Ut=w.useRef(null),[Gt,Ot]=w.useState(!1),ln=()=>{const re=se?pe:ut;re.current=!re.current,St(re.current)},In=()=>{const re=se?Ae:Lt;re.current=!re.current,pt(re.current)};w.useEffect(()=>{D(s||t),U(!1)},[s,t]);const qt=re=>{const Te=!re||re.sessionsError?null:re.sessionsJson;let Ge=null;Te&&Array.isArray(Te.sessions)&&(Ge=Te.sessions.find(je=>je.name===t));const mt=!re||re.fleetError?null:re.fs;let q=null;mt&&mt.available&&Array.isArray(mt.cells)&&(q=mt.cells.find(je=>je.tmuxSession===t)),D(Rc({session:t,cell:q||(s?{cell:s}:null)})),z(typeof(q==null?void 0:q.panelUrl)=="string"?q.panelUrl.trim():""),A(typeof(q==null?void 0:q.cell)=="string"?q.cell:"");let ae="";q?ae=[`${q.engine}${q.key?`·${q.key}`:""}`,U4(q,Ge)].filter(Boolean).join(" · "):Ge&&(ae=Ge.attached?`attached · ${h1(Ge.activity)}`:Ge.activity?h1(Ge.activity):""),O(ae),Re(!!(Ge||q))},wn=w.useRef(qt);wn.current=qt,w.useEffect(()=>{const re=e?e.split("/"):[],Te=Ge=>wn.current(Ge);return Te(nc(re)),kd(i,re,Te)},[e,i]),w.useEffect(()=>{wn.current(nc(e?e.split("/"):[]))},[t,s]);const en=w.useRef(b);en.current=b;const bn=re=>{var Xe;if(!v)return;const Te=!re||re.sessionsError?null:re.sessionsJson;let Ge=null,mt=!1;Te&&Array.isArray(Te.sessions)&&(mt=!0,Ge=Te.sessions.find(Pe=>Pe.name===v.session));const q=!re||re.fleetError?null:re.fs;let ae=null,je=!1;q&&q.available&&Array.isArray(q.cells)&&(je=!0,ae=q.cells.find(Pe=>Pe.tmuxSession===v.session)),Ie({title:Rc({session:v.session,cell:ae}),present:!!(Ge||ae)}),(mt||je)&&!Ge&&!ae&&((Xe=en.current)==null||Xe.call(en))},Ft=w.useRef(bn);Ft.current=bn,w.useEffect(()=>{if(!v){Ie(null);return}const re=v.node?v.node.split("/"):[],Te=Ge=>Ft.current(Ge);return Te(nc(re)),kd(i,re,Te)},[v,v==null?void 0:v.node,i]),w.useEffect(()=>{v&&Ft.current(nc(v.node?v.node.split("/"):[]))},[v==null?void 0:v.session]);const Xt=se?"side":"main",Jt=()=>ge(re=>re&&re.source===Xt?null:{source:Xt,ev:null}),[Qt,ls]=w.useState(tE),[cs]=w.useState(sE),[mn]=w.useState(iE),gn=H4({showComposer:E,showFiles:(Ne==null?void 0:Ne.source)===Xt,showPanel:N,hasPanel:!!j,rendererKind:V,filesSetting:L?null:Qt,handlers:{onToggleComposer:()=>F(re=>!re),onToggleFiles:L?Jt:()=>ls(re=>(nE(!re),!re)),onTogglePanel:()=>U(re=>!re),onSwitchRenderer:ne}}),qs=re=>{re.preventDefault();const Te=We.current;if(!Te)return;const Ge=(xt,gt)=>de(Je=>({...Je,[ie?"h":"v"]:{main:xt,side:gt}}));if(ie){const xt=re.clientX,gt=nt.current,Je=Te.clientWidth||1,Rt=Q?-1:1,rt=Wt=>{const Sn=gt.main+gt.side,Se=(Wt.clientX-xt)/Je*Sn*Rt,Me=od(gt.main+Se);Ge(Me,od(Sn-Me))},ze=()=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",ze),window.removeEventListener("pointercancel",ze),window.removeEventListener("blur",ze)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",ze),window.addEventListener("pointercancel",ze),window.addEventListener("blur",ze);return}const mt=re.clientY,q=nt.current,ae=Te.clientHeight||1,je=Q?-1:1,Xe=xt=>{const gt=q.main+q.side,Je=(xt.clientY-mt)/ae*gt*je,Rt=od(q.main+Je);Ge(Rt,od(gt-Rt))},Pe=()=>{window.removeEventListener("pointermove",Xe),window.removeEventListener("pointerup",Pe),window.removeEventListener("pointercancel",Pe),window.removeEventListener("blur",Pe)};window.addEventListener("pointermove",Xe),window.addEventListener("pointerup",Pe),window.addEventListener("pointercancel",Pe),window.addEventListener("blur",Pe)},Vn=v&&l.jsxs("div",{className:`nc-dual-pane${se?"":" foco"}${be&&se?" nascosto":""}`,"data-testid":"pane-main",style:{flexGrow:Be.main,flexBasis:ie?0:void 0},onPointerDown:()=>He(!1),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${ue?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:K}),!se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),be&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",(Le==null?void 0:Le.title)||v.session),"aria-label":p("dual-go-to").replace("{cell}",(Le==null?void 0:Le.title)||v.session),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),He(!se)},children:[l.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("rect",{x:"3.5",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),l.jsx("span",{className:`nc-dual-dot${Le!=null&&Le.present?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:!0,focused:!se,sendRef:ot,composerRef:oe,actionRef:$e,ctrlRef:ut,setCtrlArmed:St,altRef:Lt,setAltArmed:pt,keyboardRef:Ut,onFiles:st,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:G})})]},"pane-main"),bt=v&&l.jsxs("div",{className:`nc-dual-pane${se?" foco":""}${be&&!se?" nascosto":""}`,"data-testid":"pane-side",style:{flexGrow:Be.side,flexBasis:ie?0:void 0},onPointerDown:()=>He(!0),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${Le!=null&&Le.present?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:Le?Le.title:v.session}),se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),l.jsxs("span",{className:"nc-dual-tasti",children:[l.jsx("button",{type:"button",title:p("dual-swap"),"aria-label":p("dual-swap"),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),Z(Te=>!Te)},children:ie?"⇆":"⇅"}),l.jsx("button",{type:"button",title:p("dual-close"),"aria-label":p("dual-close"),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),_==null||_()},children:"✕"})]}),be&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",K),"aria-label":p("dual-go-to").replace("{cell}",K),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),He(!se)},children:[l.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("rect",{x:"12",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),l.jsx("span",{className:`nc-dual-dot${ue?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(pc,{session:v.session,node:v.node,token:i,readonly:a,takeSize:!1,focused:se,sendRef:fe,composerRef:Ee,actionRef:Y,ctrlRef:pe,setCtrlArmed:St,altRef:Ae,setAltArmed:pt,keyboardRef:ke,onFiles:Ze,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture})})]},"pane-side"),us=l.jsx("div",{className:"nc-dual-handle","data-testid":"dual-handle",role:"separator","aria-orientation":ie?"vertical":"horizontal",onPointerDown:qs},"dual-handle");return l.jsxs("div",{className:"nc-app",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:u,title:p("sessions"),children:[l.jsx(Pt,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:p("sessions")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:e?`${K} · ${e}`:K,children:K}),g&&g.cell&&g.cell===s?l.jsx("span",{className:`nc-live-host-dot ${Rv(g)} nc-live-host-dot-header`,"data-testid":"live-host-header-dot",title:p("live-host-indicator").replace("{cell}",g.cell).replace("{mode}",p(g.mode?`live-host-mode-${g.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${g.state}`))}):null,P&&l.jsx("small",{className:"nc-bar-sub",children:P})]}),l.jsxs("span",{className:"nc-bar-right",children:[l.jsx("button",{onClick:()=>ye(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:l.jsx(Pt,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>ye(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Pt,{name:"zoomIn",size:18})}),Qt&&l.jsx("button",{type:"button",onClick:Jt,title:p("bar-menu-files"),"aria-label":p("bar-menu-files"),"aria-pressed":(Ne==null?void 0:Ne.source)===Xt?"true":"false",children:l.jsx(Pt,{name:"folder",size:18})}),cs&&l.jsx("button",{type:"button",onClick:()=>F(re=>!re),title:p("bar-menu-keyboard"),"aria-label":p("bar-menu-keyboard"),"aria-pressed":E?"true":"false",children:l.jsx(Pt,{name:"keyboard",size:18})}),j&&mn&&l.jsx("button",{type:"button",onClick:()=>U(re=>!re),title:p("bar-menu-panel"),"aria-label":p("bar-menu-panel"),"aria-pressed":N?"true":"false",children:l.jsx(Pt,{name:"monitor",size:18})}),l.jsx("button",{type:"button",className:`nc-bar-menu${C?" on":""}`,title:p("bar-menu-open"),"aria-label":p("bar-menu-open"),"aria-haspopup":"menu","aria-expanded":C?"true":"false",onClick:re=>{C||I(re.currentTarget.getBoundingClientRect()),R(Te=>!Te)},children:"⋯"})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[v?l.jsx("div",{className:`nc-dual${ie?" row":""}`,ref:We,children:be?Q?[bt,Vn]:[Vn,bt]:Q?[bt,us,Vn]:[Vn,us,bt]}):l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:!0,sendRef:ot,composerRef:oe,actionRef:$e,ctrlRef:ut,setCtrlArmed:St,altRef:Lt,setAltArmed:pt,keyboardRef:Ut,onFiles:st,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:G}),N&&j&&M&&l.jsx(pv,{cellId:M,panelUrl:j,route:e?e.split("/"):[],panelPort:c,token:i,title:K})]}),l.jsx(sI,{onKeyboard:()=>F(re=>!re),onCellSwitcher:h,cellSwitcherOpen:f,send:re=>(se?fe:ot).current(re),action:re=>(se?Y:$e).current(re),ctrlArmed:kt,onCtrl:ln,altArmed:_t,onAlt:In,onAltConsume:()=>{const re=se?Ae:Lt;re.current=!1,pt(!1)},onKeyboardKeep:()=>{var re,Te;return(Te=(re=se?ke:Ut).current)==null?void 0:Te.call(re)},selectionMode:Gt,onSelectionMode:Ot,keepKeyboardClosed:x.keybarKeepsKeyboardClosed,showEnter:x.showKeybarEnter,keybarLayout:x.keybarLayout}),E&&l.jsx(uC,{submitText:re=>(se?Ee:oe).current(re),token:i,session:se?v.session:t,node:se?v.node:e,ownerId:se?v.ownerId:n,readonly:a,keepKeyboardClosedOnVoice:x.voiceKeepsKeyboardClosed}),Ne&&(De?l.jsx(Eg,{session:v.session,node:v.node,token:i,filesEvent:Ne.ev,onClose:()=>ge(null)}):Ne.source==="main"?l.jsx(Eg,{session:t,node:e,token:i,filesEvent:Ne.ev,onClose:()=>ge(null)}):null),C&&(L?l.jsx(Dk,{anchorRect:S,items:gn,onClose:()=>R(!1)}):l.jsx(Nv,{cellName:K,items:gn,onClose:()=>R(!1)}))]})}function W4(){zn();const[t]=w.useState(F4),[e,n]=w.useState(t.token),[s,i]=w.useState(!1);L6(s?"":e);const a=w.useRef(t.token);a.current=e,w.useEffect(()=>{const Se=Me=>{Me&&Me.detail&&Me.detail.token===a.current&&i(!0)};return window.addEventListener(um,Se),()=>window.removeEventListener(um,Se)},[]);const c=w.useCallback((Se,Me)=>{const Ve=b1(Se,{remember:Me});if(!Ve.ok||Me&&Ve.where!=="local")try{window.dispatchEvent(new CustomEvent(dm))}catch{}i(!1),n(Se)},[]),[u,h]=w.useState(t.pair||""),f=w.useCallback(()=>{h("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),g=vk(),[v]=w.useState(()=>HI(typeof location<"u"?location.pathname:"/")),[_,b]=w.useState(v.id),x=_===Vo(null,ti),[L,C]=w.useState(null),R=Se=>{const Me=Cr(Se);C(Me?{...Me,...typeof(Se==null?void 0:Se.cellName)=="string"&&Se.cellName?{cellName:Se.cellName}:{}}:null)},[S,I]=w.useState(null);w.useEffect(()=>{const Se=f4();I(Se&&L&&Ug(Se.main,L)?Se.side:null)},[L]);const E=Se=>{const Me=L?{session:L.session,node:L.node}:null,Ve=h4(Me,S,Se);I(Ve),Ve?p4(Me,Ve):i1()},F=()=>{I(null),i1()},[$,X]=w.useState([]),[V,G]=w.useState(!0),[ne,K]=w.useState(null),[D,P]=w.useState([]),[O,j]=w.useState([]),[z,M]=w.useState(!1),[A,N]=w.useState(null),[U,T]=w.useState(()=>v.ownerId?uo():d1(v.name)),[H,se]=w.useState(null),[Q,Z]=w.useState(null),me=Se=>Z(Cr(Se)),[de,ie]=w.useState(null),xe=bv(e,g),Be=w.useMemo(()=>(xe||[]).filter(Se=>Se.instanceId).map(Se=>({instanceId:Se.instanceId,route:Se.route,label:Se.label,status:Se.status,stale:Se.stale===!0,checking:Se.checking===!0})),[xe]),{order:nt}=kv(),Le=x4(e,_,U,T,Be,nt),{notice:Ie,showActionNotice:ue}=eC(),Re=Le.decks;w.useEffect(()=>{const Se=new Map;for(const Me of xe||[]){const Ve=(Me.route||[Me.name]).join("/"),ct=new Set((Me.sessions||[]).map(At=>At.name));for(const At of Me.cells||[])!At.cell||!At.tmuxSession||At.cell===At.tmuxSession||ct.has(At.cell)||Se.set(`${Ve}:${At.cell}`,`${Ve}:${At.tmuxSession}`)}T(Me=>xP(Me,Se))},[xe]),w.useEffect(()=>{Le.localNodeId&&v.ownerId&&v.ownerId===Le.localNodeId&&T(Se=>Se.columns.some(Me=>Me.tiles.length)?Se:d1(v.name))},[Le.localNodeId]),w.useEffect(()=>{Le.localNodeId&&(OI(Be),Le.viewUpdate(Se=>{const Me=Ha(Se,Le.localNodeId,Be);return JSON.stringify(Me)===JSON.stringify(Se)?Se:Me}))},[Be,Le.localNodeId,Le.viewUpdate]);const[fe,Ee]=w.useState(null),[Y,pe]=w.useState(null),Ae=w.useRef(0),[ke,We]=w.useState(!1),[Ne,ge]=w.useState(z4),[st,Ze]=w.useState(!x),[De,He]=w.useState(()=>x?localStorage.getItem(c1)==="1":!0),[qe,wt]=w.useState(!1),[W,ee]=w.useState("nodes"),[J,be]=w.useState(!1),[ye,ot]=w.useState(""),[oe,$e]=w.useState(!1),ut=(Se="nodes",Me=!1,Ve="")=>{ee(Se),be(Me),ot(Ve),wt(!0)},[kt,St]=w.useState(!1),[Lt,_t]=w.useState(null),[pt,Ut]=w.useState({deviceDefault:"",localNodeId:"",localNameDefault:"",deviceNameNeeded:!1,deviceNameSuggestion:""}),[Gt,Ot]=w.useState(""),[ln,In]=w.useState(!1),[qt,wn]=w.useState(0),[en,bn]=w.useState({});w.useEffect(()=>{try{localStorage.setItem(TE,String(Ne))}catch{}},[Ne]),w.useEffect(()=>{try{localStorage.setItem(c1,De?"1":"")}catch{}},[De]),w.useEffect(()=>{if(!e)return;let Se=!1;return Promise.all([A1(e),qn("/api/config",e).then(Me=>Me.json())]).then(([Me,Ve])=>{if(!Se){if(Ut({deviceDefault:Me.deviceName||"",localNodeId:Me.nodeId||"",localNameDefault:Me.localName||"",deviceNameNeeded:Me.deviceNameNeeded===!0,deviceNameSuggestion:Me.deviceNameSuggestion||""}),Ot(Me.deviceName||""),In(!!Ve.readonlyDefault),FM(Ve.terminal),wn(Number.isInteger(Ve.panelPort)?Ve.panelPort:0),bn(Ve.nodePanelPorts&&typeof Ve.nodePanelPorts=="object"&&!Array.isArray(Ve.nodePanelPorts)?Ve.nodePanelPorts:{}),Me.firstRun===!0&&!Ve.readonlyDefault)St(!0);else if(u)St(!0);else if(Me.deviceNameNeeded===!0&&!Ve.readonlyDefault){let ct=!1;try{ct=sessionStorage.getItem("nc_device_ask_later")==="1"}catch{}ct||_t({suggestion:Me.deviceNameSuggestion||""})}}}).catch(()=>{}),()=>{Se=!0}},[e,u]);const[Ft,Xt]=w.useState({}),Jt=w.useCallback(({route:Se,hostCell:Me,revision:Ve})=>{const ct=Cs(Se);Xt(At=>({...At,[ct]:{hostCell:Me||null,hostLease:null,hostRevision:Number.isInteger(Ve)?Ve:(At[ct]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Qt=Se=>{const Me=Cs(Se),Ve=Se.length?((xe||[]).find(ct=>Cs(Array.isArray(ct.route)?ct.route:[])===Me)||{}).cells||[]:D;return Va({liveHost:Ft[Me]||null,cells:Ve,localNodeId:Le.localNodeId,ownerId:Se.length?Me:Le.localNodeId})},ls=w.useRef(xe);w.useEffect(()=>{ls.current=xe},[xe]);const cs=w.useRef(null);cs.current||(cs.current=Zd());const mn=3500;w.useEffect(()=>{let Se=!1;const Me=async()=>{const ct=cs.current,At=ct.begin();if(At!==null)try{const Ks=[[],...(ls.current||[]).filter(Zt=>Zt.kind!=="vl"&&Zt.status==="up").map(Zt=>Array.isArray(Zt.route)&&Zt.route.length?Zt.route:[Zt.name])],Vs=await Promise.all(Ks.map(async Zt=>{const tn=Cs(Zt);try{const rn=await Xd(e,Zt,{timeoutMs:mn});return[tn,{hostCell:rn&&typeof rn.hostCell=="string"?rn.hostCell:null,hostLease:rn&&rn.host&&typeof rn.host.lease=="string"?rn.host.lease:null,hostRevision:Number.isInteger(rn&&rn.revision)?rn.revision:0,threadStatus:rn&&u1.has(rn.threadStatus)?rn.threadStatus:"unknown"}]}catch{return[tn,{error:!0}]}}));if(Se||!ct.isCurrent(At))return;Xt(Zt=>{let tn=!1;const rn={...Zt};for(const bi of Vs){if(!bi)continue;const[mo,rr]=bi;rn[mo]=rr.error?{...Zt[mo]||{},threadStatus:"unknown"}:rr,tn=!0}return tn?rn:Zt})}finally{ct.end(At)}};Me();const Ve=setInterval(Me,4e3);return()=>{Se=!0,clearInterval(Ve),cs.current.reset()}},[e]),w.useEffect(()=>{if(!g)return;const Se=Me=>{if(!Me)return;const Ve=Me.sessionsError?null:Me.sessionsJson;Ve&&!Ve.error?(X(Ve.sessions||[]),G(!0),K(Me.at)):G(!1);const ct=yv({fs:Me.fs,error:Me.fleetError});ct.kind==="data"?(Ka("local",ct.cells),P(ct.cells),j(ct.capabilities),M(!1),N(null)):ct.kind==="stale"?(P(At=>At.length?At:_v("local")),M(!0),N(null)):(P([]),Ka("local",[]),j([]),M(!1),N(ct.reason||""))};return Se(nc([])),kd(e,[],Se)},[g,e]);const gn=w.useCallback(async(Se,Me=[])=>{const Ve=Cs(Me),ct=Ft[Ve]&&Ft[Ve].hostRevision||0;try{const At=await Jd(e,Se,ct,Me);return Xt(Ks=>({...Ks,[Ve]:{hostCell:At.hostCell||null,hostLease:At.host&&typeof At.host.lease=="string"?At.host.lease:null,hostRevision:Number.isInteger(At.revision)?At.revision:ct,threadStatus:u1.has(At.threadStatus)?At.threadStatus:"unknown"}})),{ok:!0}}catch(At){return{ok:!1,error:At}}},[e,Ft]),qs=w.useCallback(async(Se,Me=[])=>{const Ve=await gn(Se,Me);return Ve.ok||window.alert(p(pm(Ve.error))),Ve.ok},[gn]),Vn=w.useCallback(async(Se=[])=>{const Me=Cs(Se),Ve=Ft[Me]&&Ft[Me].hostRevision||0;try{const ct=await Qd(e,Ve,Se);return Xt(At=>({...At,[Me]:{hostCell:ct.hostCell||null,hostLease:null,hostRevision:Number.isInteger(ct.revision)?ct.revision:Ve,threadStatus:"unknown"}})),{ok:!0}}catch(ct){return{ok:!1,error:ct}}},[e,Ft]),bt=w.useCallback(async(Se=[])=>{const Me=await Vn(Se);return Me.ok||window.alert(p(pm(Me.error))),Me.ok},[Vn]);w.useEffect(()=>{let Se=!1;const Me=()=>{qn("/api/config",e).then(ct=>ct.json()).then(ct=>{Se||T4(ct.version,ct.uiVersion,"0.9.60")}).catch(()=>{})};Me();const Ve=setInterval(Me,6e4);return()=>{Se=!0,clearInterval(Ve)}},[e]);const us=new Set([...$.map(Se=>Se.name),...xe.flatMap(Se=>Se.sessions.map(Me=>Me.key))]),le=w.useMemo(()=>{const Se=new Map;for(const Me of $)Me&&typeof Me.name=="string"&&Number.isFinite(Me.created)&&Se.set(Me.name,Me.created);return Se},[$]),re=_s(U),Te=Se=>T(Me=>{const Ve=vC(Se,Le.localNodeId,Be)||Se,ct=qk(Me,Ve);return ct===Me&&_s(Me).length>=9&&Le.setError(p("grid-full")),ct}),Ge=async(Se,Me=[])=>{try{await Yg(e,Se,Me)}catch{return}const Ve=Me.length?`${Me.join("/")}:${Se}`:Se;T(ct=>Nc(ct,Ve)),poll()},mt=async(Se,Me,Ve=[])=>{try{await L1(e,Se,Me,Ve)}catch{return}poll()},q=async(Se,Me,Ve=[])=>{await E1(e,{cell:Se,enabled:!!Me},Ve),poll()},ae=async Se=>{if(!fe)return;const{cell:Me}=fe,Ve=Array.isArray(fe.route)?fe.route:[];if(!await jv({token:e,powerCell:fe,payload:Se,onNotice:ue})){const At=Se.action==="up"?!!Se.boot:Se.boot?!1:!!fe.boot;pe({id:++Ae.current,cell:Me,route:Ve,enabled:At})}poll()},je=w.useCallback(Se=>{pe(Me=>(Me==null?void 0:Me.id)===Se?null:Me)},[]),Xe=async Se=>{if(!(!(Se!=null&&Se.direct)||ke)){We(!0);try{await Jg(e,Se.name,Se.tunnelStatus==="up"?"down":"up")}finally{We(!1)}}},Pe=async(Se,Me)=>{const Ve=String(Me||"").trim();return!(Se!=null&&Se.direct)||!Ga(Ve)?!1:(await P1(e,Se.name,Ve),!0)},xt=Se=>{const Me=Re.find(Ve=>Ve.id===Se);if(!Me)return!1;try{const Ve=window.open(Lp(Me,e),"_blank");return Ve&&(Ve.opener=null),!!Ve}catch{return!1}},gt=async Se=>{if(!Se||Se===_)return;const Me=await Le.select(Se),Ve=Le.records.find(ct=>ct.id===Se);b(Se),T(Me),se(null),Z(null);try{history.replaceState(null,"",Lp(Ve||Se,null))}catch{}},Je=async(Se,Me)=>{const Ve=await Le.add(Se,Me);await gt(Ve.id)},Rt=async(Se,Me)=>{const Ve=await Le.rename(Se,Me);if(Se===_){b(Ve.id),T(Le.vistaMaterializzata(Ve)),se(null),Z(null);try{history.replaceState(null,"",Lp(Ve,null))}catch{}}},rt=async Se=>{await Le.remove(Se),Se===_&&await gt(Le.localMainId)},ze=async(Se,Me)=>{!Me||Me===_||(await Le.addTileTo(Me,Se),T(Ve=>Nc(Ve,Se)))};if(!e||s)return l.jsx(v4,{onSubmit:c,reason:s?"invalid":""});const Wt=l.jsxs(l.Fragment,{children:[qe&&l.jsx(H6,{token:e,initialTab:W,initialLocation:ye,startNewCell:J,onClose:()=>{wt(!1),be(!1),ot("")}}),kt&&l.jsx(U6,{token:e,initialPair:u,...pt,onPairDone:f,onDone:()=>St(!1)}),Lt&&l.jsx(W6,{token:e,suggestion:Lt.suggestion,onSaved:Se=>{Ot(Se),Ut(Me=>({...Me,deviceDefault:Se,deviceNameNeeded:!1})),_t(null)},onLater:()=>{try{sessionStorage.setItem("nc_device_ask_later","1")}catch{}_t(null)}}),l.jsx(n4,{token:e})]});if(!g)return de?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(s1,{peer:de,token:e,onBack:()=>ie(null)})}),Wt]}):L?l.jsxs(l.Fragment,{children:[l.jsx(f1,{session:L.session,node:L.node,ownerId:L.ownerId,cellName:L.cellName,token:e,readonly:ln,liveHost:Qt(L.node?L.node.split("/"):[]),panelPort:kc(L.node?L.node.split("/"):[],en,qt),side:S,onSideClose:F,onSideGone:F,onBack:()=>C(null),onCellSwitcher:()=>$e(!0),cellSwitcherOpen:oe}),oe&&l.jsx(l4,{token:e,current:L,localNodeLabel:Gt,panelPort:qt,nodePanelPorts:en,hostByRoute:Ft,onDesignateCell:gn,onClearHostCell:Vn,onLiveHostApplied:Jt,sideKey:S?qa(S.node?S.node.split("/"):[],S.session):null,onToggleSide:E,onPick:Se=>{R(Se),$e(!1)},onClose:()=>$e(!1)}),Wt]}):l.jsxs(l.Fragment,{children:[l.jsx(JP,{onPick:R,token:e,onSettings:ut,onOpenVlSession:ie,panelPort:qt,nodePanelPorts:en,hostByRoute:Ft,onDesignateCell:qs,onClearHostCell:bt}),Wt]});const Sn=x||!st;return l.jsxs("div",{className:"nc-workspace",children:[Sn&&l.jsx(SI,{sessions:$,cells:D,localVerified:V,activeSessions:re,nodeGroups:xe,token:e,onPeekOpen:()=>$e(!1),overlayOpen:oe,fleetCapabilities:O,fleetStale:z,fleetOff:A,bootSettlement:Y,onBootSettlementApplied:je,localNodeId:Le.localNodeId,hostByRoute:Ft,onDesignateCell:qs,onClearHostCell:bt,onPick:me,onAddTile:Te,onPower:Ee,onBoot:q,onBootError:Se=>Le.setError(String((Se==null?void 0:Se.message)||Se)),onNodePower:Xe,onNodeRename:Pe,onKill:Ge,onVisibility:mt,onNew:()=>ut("fleet",!0),onSettings:ut,onOpenVlSession:ie,width:Ne,collapsed:De,onResize:ge,onToggleCollapse:()=>He(Se=>!Se)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(dD,{decks:Re,currentDeck:_,onCreate:Je,onRename:Rt,onDelete:rt,onReorder:Le.reorder,onOpenWindow:xt,onNavigate:gt,saveState:Le.saveState,error:Le.error,conflict:Le.conflict,onReloadDeck:Le.reloadCurrent,sidebarVisible:Sn,onToggleSidebar:x?null:()=>Ze(Se=>!Se)}),Ie&&l.jsx("div",{className:"nc-notice nc-deck-notice",role:"status",title:Ie,children:Ie}),l.jsx(DI,{layout:U,onLayoutChange:T,onResizeEnd:()=>{Le.saveNow()},token:e,readonly:ln,sessionsAlive:us,localVerified:V,localIdentities:le,localVerifiedAt:ne,focusSession:H,onFocus:se,onOpenSingle:me,decks:Re,currentDeck:_,onSendToDeck:ze,cells:D,nodeGroups:xe,panelPort:qt,nodePanelPorts:en})]}),de&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(s1,{peer:de,token:e,onBack:()=>ie(null)})}),Q&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(f1,{session:Q.session,node:Q.node,ownerId:Q.ownerId,cellName:Rc({session:Q.session,node:Q.node,ownerId:Q.ownerId,cells:D,nodeGroups:xe}),token:e,readonly:ln,liveHost:Qt(Q.node?Q.node.split("/"):[]),panelPort:kc(Q.node?Q.node.split("/"):[],en,qt),onBack:()=>Z(null)})}),fe&&l.jsx(Pd,{cell:fe,token:e,route:Array.isArray(fe.route)?fe.route:[],onConfirm:ae,onClose:()=>Ee(null)}),Wt]})}function q4(t){return t.kind==="install"?p("update-installed-restart").replace("{v}",t.version):t.kind==="stale"?p("update-stale").replace("{ui}",t.version).replace("{browser}",t.browserVersion):p("update-available").replace("{v}",t.version).replace(" "," ").trim()}function K4(){zn();const t=w.useSyncExternalStore(C4,a1,a1);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:q4(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:ME,children:p("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:O4,children:p("reload")}),l.jsx("button",{className:"nc-update-close",onClick:M4,"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}function V4(){zn();const[t,e]=w.useState(!1);return w.useEffect(()=>{const n=()=>e(!0);return window.addEventListener(dm,n),()=>window.removeEventListener(dm,n)},[]),t?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:p("auth-not-remembered")}),l.jsx("button",{className:"nc-update-close",onClick:()=>e(!1),"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}D4();f6();gN.createRoot(document.getElementById("root")).render(l.jsxs(cN.StrictMode,{children:[l.jsx(W4,{}),l.jsx(K4,{}),l.jsx(V4,{})]}));
|
|
169
|
+
`],{type:"application/json"}),z=URL.createObjectURL(j),M=document.createElement("a");M.href=z,M.download="nexuscrew-diagnostics.json",M.click(),URL.revokeObjectURL(z)}catch{_(p("diagnostics-export-failed"))}};return l.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[l.jsxs("label",{className:"nc-field",children:[p("diagnostics-target"),l.jsx("select",{value:c.key,onChange:j=>a(j.target.value),children:s.map(j=>l.jsxs("option",{value:j.key,children:[j.label,j.status!=="up"?` · ${j.status}`:""]},j.key))})]}),l.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[l.jsx("div",{className:"nc-sheet-label",children:p("diagnostics-verbose")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("select",{"aria-label":p("diagnostics-duration"),value:R,onChange:j=>S(Number(j.target.value)),disabled:n,children:[300,900,1800,3600].map(j=>l.jsxs("option",{value:j,children:[j/60," min"]},j))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(u==null?void 0:u.verbose)===!0,onClick:()=>D(()=>Ow(t,!0,R,c.route)),children:p("enable")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(u==null?void 0:u.verbose)!==!0,onClick:()=>D(()=>Ow(t,!1,R,c.route)),children:p("stop")})]}),l.jsx("small",{className:"nc-set-hint",children:u!=null&&u.verbose?p("diagnostics-expires").replace("{time}",new Date(u.expiresAt).toLocaleTimeString()):p("diagnostics-off")})]}),l.jsxs("div",{className:"nc-diag-filters",children:[l.jsxs("select",{"aria-label":p("diagnostics-level"),value:I,onChange:j=>E(j.target.value),children:[l.jsx("option",{value:"all",children:p("diagnostics-all-levels")}),["debug","info","warn","error"].map(j=>l.jsx("option",{value:j,children:j},j))]}),l.jsx("input",{"aria-label":p("diagnostics-component"),placeholder:p("diagnostics-component"),value:F,onChange:j=>$(j.target.value)})]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:b,onChange:j=>x(j.target.checked)})," ",p("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:L,onChange:j=>C(j.target.checked)})," ",p("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:V,className:"nc-diag-log","aria-label":p("diagnostics-log"),children:K||p("diagnostics-empty")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:P,children:p("copy")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:O,children:p("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(p("diagnostics-clear-confirm"))&&D(async()=>{const j=await o5(t,c.route);return X.current=0,g([]),j})},children:p("diagnostics-clear")})]}),v&&l.jsx("div",{className:"nc-err",children:v})]})}function z6(){typeof window<"u"&&window.location&&typeof window.location.reload=="function"&&window.location.reload()}function F6({token:t,settings:e,readonly:n,refresh:s,roster:i,section:a,setSection:c}){const[u,h]=w.useState(xc),[f,g]=w.useState(null),[v,_]=w.useState(null),[b,x]=w.useState(!1),[L,C]=w.useState(!1),[R,S]=w.useState(null),[I,E]=w.useState(!1),[F,$]=w.useState(!1),[X,V]=w.useState(null);w.useEffect(()=>{S(e&&e.update||null),E(!!(e&&e.autoUpdate===!0)),$(!!(e&&e.alternateScreen))},[e]);const G=async()=>{g(null),_(null),C(!0);try{const N=await zN(t);_(N.note||"ok"),x(!1)}catch(N){g(String(N.message||N))}C(!1)},ne=async()=>{g(null),_(null),C(!0);try{const N=await t5(t);_(`${N.note||"ok"}${N.target?` (${N.target})`:""}`)}catch(N){g(String(N.message||N))}C(!1)},K=async N=>{g(null),_(null),C(!0);try{await xd(t,{autoUpdate:N}),E(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},D=async N=>{g(null),_(null),C(!0);try{await xd(t,{alternateScreen:N}),$(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},P=w.useCallback(async()=>{if(t)try{V(await $N(t))}catch{V(null)}},[t]);w.useEffect(()=>{P()},[P]);const O=async N=>{g(null),_(null),C(!0);try{if(!N&&X&&X.running&&!window.confirm(p("ai-desktop-confirm-stop"))){C(!1);return}const U=await T1(t,N);U&&U.ok===!1&&g(U.error||"comando fallito"),await P(),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},j=async()=>{g(null),_(null),C(!0);try{S(await n5(t))}catch(N){g(String(N.message||N))}C(!1)},z=async()=>{g(null),_(null),C(!0);try{const N=await s5(t);S(N),_(p("npm-update-restarting"))}catch(N){g(String(N.message||N))}C(!1)},M=()=>{window.confirm(p("composer-clear-confirm"))&&(g(null),pI()?(window.dispatchEvent(new Event(Ng)),_(p("composer-clear-done"))):g(p("composer-clear-failed")))},A=e&&e.service;return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-system-tabs",role:"tablist","aria-label":p("tab-system"),children:["general","diagnostics"].map(N=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===N,className:`nc-set-tabbtn${a===N?" on":""}`,onClick:()=>c(N),children:p(`system-${N}`)},N))}),a==="general"&&l.jsxs(l.Fragment,{children:[l.jsxs("section",{className:"nc-system-group",children:[l.jsx("div",{className:"nc-set-info",children:p("input-settings-local")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:u===fo,onChange:N=>{const U=fk(N.target.checked?fo:po);h(U),z6()}}),l.jsxs("span",{children:[l.jsx("b",{children:p("bar-menu-renderer")}),l.jsx("small",{children:p("bar-menu-renderer-desc")})]})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-this-node")}),e&&l.jsxs("div",{className:"nc-set-info",children:["v",e.version," · ",e.platform," · :",e.port,l.jsx("br",{}),A&&A.installed?p("service-installed"):p("service-missing"),A&&A.installed?` · ${A.active?p("service-active"):p("service-inactive")}`:"",A?` · boot ${A.boot?"on":"off"}`:""]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L,title:n?p("settings-readonly"):"",onClick:ne,children:p("service-regenerate")})}),l.jsx(I6,{token:t,readonly:n}),l.jsx(D6,{})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-updates")}),l.jsxs("div",{className:"nc-set-form nc-update-settings",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:I,disabled:n||L||R&&!R.supported,onChange:N=>K(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("npm-auto-update")}),l.jsx("small",{children:p("npm-auto-update-help")})]})]}),R&&l.jsxs("div",{className:"nc-set-info",children:[p("npm-update-current")," v",R.current,R.latest?` · ${p("npm-update-latest")} v${R.latest}`:""," · ",p(R.supported?R.phase==="idle"&&R.checked!==!0?"npm-update-never":`npm-update-${R.phase}`:"unsupported")]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L||!R||!R.supported,onClick:j,children:p("npm-update-check")}),R&&R.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||L||R.phase==="installing",onClick:z,children:p("npm-update-install")})]}),R&&R.lastError&&l.jsx("div",{className:"nc-err",children:R.lastError})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("ai-desktop-title")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("ai-desktop"),disabled:n||L,checked:!!(X&&X.desired),onChange:N=>O(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("ai-desktop")}),l.jsx("small",{children:p("ai-desktop-help")})]})]}),X&&!X.desired&&X.running&&l.jsx("div",{className:"nc-set-info",children:p("ai-desktop-stop-pending")})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-security")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||L,title:n?p("settings-readonly"):"",onClick:()=>{g(null),_(null),x(!0)},children:p("token-rotate")})})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:p("system-local-data")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:p("composer-clear-data")}),l.jsx("small",{className:"nc-set-hint",children:p("composer-clear-data-help")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:M,children:p("composer-clear-data")})})]})]})]}),a==="diagnostics"&&l.jsxs("section",{className:"nc-system-group nc-system-diagnostics",children:[l.jsx("h3",{children:p("system-diagnostics")}),l.jsxs("div",{className:"nc-set-form nc-alternate-screen-settings",children:[l.jsx("div",{className:"nc-sheet-label",children:p("system-terminal")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":p("alternate-screen"),checked:F,disabled:n||L,onChange:N=>D(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("alternate-screen")}),l.jsx("small",{children:p("alternate-screen-help")})]})]})]}),l.jsx(j6,{token:t}),l.jsx(m6,{}),l.jsx($6,{token:t,roster:i,readonly:n})]}),b&&l.jsxs("div",{className:"nc-set-confirm",children:[l.jsx("div",{children:p("token-rotate-explain")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:L,onClick:()=>x(!1),children:p("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:L,onClick:G,children:p("confirm")})]})]}),v&&l.jsx("div",{className:"nc-set-note",children:v}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function H6({token:t,onClose:e,initialTab:n="nodes",initialLocation:s="",startNewCell:i=!1}){zn();const a=n==="diagnostics"?"diagnostics":"general",[c,u]=w.useState(n==="diagnostics"?"system":n),h=w.useRef(null),f=w.useRef(null),[g,v]=w.useState({start:!1,end:!1}),[_,b]=w.useState(a),[x,L]=w.useState(null),[C,R]=w.useState([]),[S,I]=w.useState(null),[E,F]=w.useState([]),[$,X]=w.useState(!1),[V,G]=w.useState(null),[ne,K]=w.useState(0),D=bv(t,!0,ne),P=w.useCallback(()=>{const T=h.current;if(!T)return;const H=T.scrollWidth>T.clientWidth+1,se={start:H&&T.scrollLeft>1,end:H&&T.scrollLeft+T.clientWidth<T.scrollWidth-1};v(Q=>Q.start===se.start&&Q.end===se.end?Q:se)},[]);w.useEffect(()=>{const T=h.current;if(!T)return;const H=typeof ResizeObserver=="function"?new ResizeObserver(P):null;return H==null||H.observe(T),window.addEventListener("resize",P),P(),()=>{H==null||H.disconnect(),window.removeEventListener("resize",P)}},[P]),w.useEffect(()=>{var H,se;(se=(H=f.current)==null?void 0:H.scrollIntoView)==null||se.call(H,{behavior:"smooth",block:"nearest",inline:"nearest"});const T=window.requestAnimationFrame?window.requestAnimationFrame(P):setTimeout(P,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(T):clearTimeout(T)}},[c,P]);const O=w.useRef(Zd()),j=w.useRef(null),z=w.useRef([]),M=w.useRef(new Map),A=w.useRef({token:null,instanceId:null}),N=w.useCallback((T,H)=>{if(!T.isCurrent(H))return;const se=z.current,Q=[],Z=new Set;for(const me of M.current.values())for(const de of me){const ie=Array.isArray(de.route)&&de.route.length?de.route.join("/"):"local",xe=`${de.ownerInstanceId}:${ie}:${de.nodeId||de.name||de.label||""}`;Z.has(xe)||(Z.add(xe),Q.push(de))}R([...se,...Q])},[]),U=w.useCallback(async()=>{const T=O.current,H=T.begin();if(H===null)return;const se=new AbortController;j.current=se;const Q={timeoutMs:S1,signal:se.signal};try{const Z=A1(t,Q).then(ie=>{T.isCurrent(H)&&(L(ie),G(null))}).catch(ie=>{T.isCurrent(H)&&G(String((ie==null?void 0:ie.message)||ie))}),me=ON(t,Q).then(ie=>{if(!T.isCurrent(H))return;const xe=ie.peers||[];z.current=xe,I(Number.isInteger(ie.accessRevision)?ie.accessRevision:null),N(T,H)}).catch(ie=>{T.isCurrent(H)&&G(String((ie==null?void 0:ie.message)||ie))}),de=(async()=>{const[ie,xe]=await Promise.all([Pc(t,[],Q).then(ue=>ue).catch(()=>null),M1(t,Q).then(ue=>ue).catch(()=>null)]);if(!T.isCurrent(H))return;const Be=ie&&typeof ie.instanceId=="string"?ie.instanceId:"";if(!Be)return;A.current.instanceId!==Be&&(M.current.clear(),A.current.instanceId=Be);const nt=[{instanceId:Be||null,route:[],label:null},...Ek(xe,Be)],Le=ue=>`${ue.instanceId}:${ue.route.join("/")}`;if(xe){const ue=new Set(nt.map(Le));for(const Re of M.current.keys())ue.has(Re)||M.current.delete(Re)}if(!xe)for(const[ue,Re]of M.current)Re.some(fe=>fe.route.length)&&M.current.set(ue,Re.map(fe=>({...fe,stale:!0,online:!1,canManage:!1,capabilities:[]})));const Ie=new Map;F([]),N(T,H),await Promise.allSettled(nt.map(async ue=>{const Re=Le(ue);try{const fe=await j1(t,ue.route,{signal:se.signal});if(!T.isCurrent(H))return;const Ee=(fe.nodes||[]).map(Y=>Ck(Y,ue)).filter(Boolean);M.current.set(Re,Ee),Ie.delete(Re)}catch(fe){if(!T.isCurrent(H))return;if((fe==null?void 0:fe.status)===403||(fe==null?void 0:fe.status)===404)M.current.delete(Re);else{const Y=M.current.get(Re);Y&&M.current.set(Re,Y.map(pe=>({...pe,stale:!0,online:!1,canManage:!1,capabilities:[]})))}ue.route.length>0&&Ie.set(Re,{instanceId:ue.instanceId,label:ue.label,route:ue.route,failure:/timeout/i.test(String((fe==null?void 0:fe.message)||fe))?"timeout":"unreachable"})}T.isCurrent(H)&&(F([...Ie.values()]),N(T,H))}))})();await Promise.allSettled([Z,me,de])}finally{j.current===se&&(j.current=null),T.end(H)}},[t,N]);return w.useEffect(()=>{A.current.token!==t&&(A.current={token:t,instanceId:null},z.current=[],M.current.clear(),R([]),F([]),I(null)),U();const T=setInterval(U,5e3);return()=>{clearInterval(T),O.current.reset(),j.current&&j.current.abort()}},[U]),w.useEffect(()=>{let T=!1;return qn("/api/config",t).then(H=>H.json()).then(H=>{T||X(!!H.readonlyDefault)}).catch(()=>{}),()=>{T=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:T=>T.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(Pt,{name:"gear",size:18}),l.jsx("b",{children:p("settings")}),l.jsx("button",{type:"button",className:"nc-set-close",onClick:e,title:p("close"),children:l.jsx(Pt,{name:"x",size:18})})]}),$&&l.jsx("div",{className:"nc-set-readonly",children:p("settings-readonly")}),V&&l.jsx("div",{className:"nc-err",children:V}),l.jsx("div",{className:`nc-set-tabs-wrap${g.start?" has-start-overflow":""}${g.end?" has-end-overflow":""}`,children:l.jsx("div",{className:"nc-set-tabs",ref:h,onScroll:P,children:["nodes","fleet","audio","input","system"].map(T=>l.jsx("button",{ref:c===T?f:null,type:"button",className:`nc-set-tabbtn${c===T?" on":""}`,onClick:()=>u(T),children:p(`tab-${T}`)},T))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(P6,{token:t,nodes:C,roster:D,settings:x,readonly:$,vlUnavailable:E,accessRevision:S,refresh:U,refreshAliases:()=>K(T=>T+1)}),c==="fleet"&&l.jsx(V3,{token:t,readonly:$,startNewCell:i,initialLocation:s,targets:D.map(T=>({route:T.route,label:T.label||T.name,status:T.status}))}),c==="audio"&&l.jsx(O6,{token:t,readonly:$,nodes:C,settings:x}),c==="input"&&l.jsx(B6,{}),c==="system"&&l.jsx(F6,{token:t,settings:x,readonly:$,refresh:U,roster:D,section:_,setSection:b})]})]})})}function U6({token:t,initialPair:e,deviceDefault:n="",localNodeId:s="",localNameDefault:i="",deviceNameNeeded:a=!1,deviceNameSuggestion:c="",onPairDone:u,onDone:h}){zn();const[f,g]=w.useState(e?"pair":"welcome"),[v,_]=w.useState(!1),[b,x]=w.useState(null),[L,C]=w.useState(c||""),[R,S]=w.useState(null),I=async()=>{_(!0),x(null);try{const E={wizardDone:!0};a&&L.trim()&&(E.deviceName=L.trim()),await xd(t,E),u&&u(),h()}catch(E){x(String(E.message||E)),_(!1)}};return l.jsx("div",{className:"nc-wiz-overlay",children:l.jsxs("div",{className:"nc-wiz",children:[l.jsxs("div",{className:"nc-wiz-head",children:[l.jsx("b",{children:p("wizard-title")}),l.jsx("small",{children:p("hydra-simple")})]}),f==="welcome"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:p("local-ready")}),a&&l.jsx("div",{className:"nc-wiz-done",children:p("wizard-device-name")}),a&&l.jsxs("label",{className:"nc-field",children:[l.jsx("span",{children:p("device-name-label")}),l.jsx("input",{value:L,onChange:E=>C(E.target.value),maxLength:64,"data-testid":"wizard-device-name-input"})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:v,onClick:I,children:p("local-only")}),l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:()=>g("pair"),children:p("add-node")})]})]}),f==="pair"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx(IC,{token:t,initial:e||"",autoStart:!!e,deviceDefault:a&&L.trim()?L.trim():n,localNodeId:s,localNameDefault:i,onBusyChange:_,onSuccess:async E=>{S(E&&E.authorizedKeys?{line:E.authorizedKeys,note:E.authorizedKeysNote||""}:null),u&&u(),g("done")}}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn ghost",disabled:v,onClick:()=>{u&&u(),g("welcome")},children:p("back")})})]}),f==="done"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:p("node-connected")}),R&&l.jsx(Wv,{line:R.line,note:R.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:I,children:p("finish")})})]}),b&&l.jsx("div",{className:"nc-err",children:b})]})})}function W6({token:t,suggestion:e="",onSaved:n,onLater:s}){zn();const[i,a]=w.useState(e||""),[c,u]=w.useState(!1),[h,f]=w.useState(null),g=async()=>{const v=i.trim();if(v){u(!0),f(null);try{await xd(t,{deviceName:v}),n&&n(v)}catch(_){f(String(_.message||_)),u(!1)}}};return l.jsx("div",{className:"nc-wiz-overlay",role:"dialog","aria-label":p("device-name-ask-title"),"data-testid":"device-name-ask",children:l.jsxs("div",{className:"nc-wiz",children:[l.jsx("div",{className:"nc-wiz-head",children:l.jsx("b",{children:p("device-name-ask-title")})}),l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("p",{className:"nc-wiz-done",children:p("device-name-ask-text")}),l.jsxs("label",{className:"nc-field",children:[l.jsx("span",{children:p("device-name-label")}),l.jsx("input",{value:i,onChange:v=>a(v.target.value),maxLength:64,"data-testid":"device-name-input"})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:c,onClick:s,children:p("device-name-later")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:c||!i.trim(),onClick:g,children:p("device-name-save")})]})]}),h&&l.jsx("div",{className:"nc-err",children:h})]})})}const q6=50;function K6(t){if(Number.isFinite(t))return t;const e=typeof t=="string"?Date.parse(t):NaN;return Number.isFinite(e)?e:0}function V6(t,e){return`${String(t)}|${String(e)}`}function t1(t,e){if(!t||typeof t!="object")return null;const n=t.frame&&typeof t.frame=="object"?t.frame:t;if(n.type!=="notify"||!t.eventId||typeof n.askId=="string"&&n.askId)return null;const s=typeof n.title=="string"?n.title:"",i=typeof n.body=="string"?n.body:"";return!s&&!i?null:{key:V6(e,t.eventId),ownerId:String(e),eventId:String(t.eventId),title:s,body:i,urgency:n.urgency==="high"?"high":"normal",ts:K6(t.ts)}}function n1(t){return[...t].sort((e,n)=>n.ts-e.ts).slice(0,q6)}function Y6(t,e,n){const s=new Map;for(const i of t||[])s.set(i.key,i);for(const i of e||[])i&&s.set(i.key,i);return[...s.values()]}function G6(t,e,n){if(typeof EventSource>"u"||!t)return()=>{};const s=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return s.onopen=()=>{typeof n=="function"&&n()},s.onmessage=i=>{try{const a=JSON.parse(i.data);a&&typeof a=="object"&&typeof a.type=="string"&&e(a)}catch{}},()=>{try{s.close()}catch{}}}const X6=6e3,J6=12e3,Zn=(t,e,n)=>`${e||""}:${n||t}`,Q6=(t,e)=>{const n=t&&t[e];return n?n.stale===!0||n.error===!0?"degraded":"live":"missing"},_E=600*1e3,Fg=new Map,Yo=t=>Object.hasOwn(t,"ownerAskTs")?t.ownerAskTs:t.ownerAskId||t.originNode?null:t.ts;function yE(t,e){Fg.set(t,e?{at:Date.now(),local:!0,ts:Yo(e),fingerprint:e.question===void 0?null:JSON.stringify([e.question,e.options||[],e.session])}:{at:Date.now()})}function wE(t){const e=Zn(t.id,t.ownerId,t.ownerAskId),n=Fg.get(e);if(n===void 0)return!1;if(n.local){const s=Yo(t);return!(n.ts&&s&&n.ts!==s)&&(n.fingerprint===null||n.fingerprint===JSON.stringify([t.question,t.options||[],t.session]))}return Date.now()-n.at>_E?(Fg.delete(e),!1):!0}function Sd(t,e){const n=new Map(t.map(s=>[Zn(s.id,s.ownerId,s.ownerAskId),s]));for(const s of e||[]){if(!s||!s.id||wE(s))continue;const i=Zn(s.id,s.ownerId,s.ownerAskId),a=n.get(i),c=Yo(s),u=a&&Yo(a);(!a||Number.isSafeInteger(c)&&c>0&&Number.isSafeInteger(u)&&u>0&&c>u)&&n.set(i,s)}return[...n.values()]}function Z6(t,e){const n=Sd([],t.filter(a=>a.imported)),s=new Set(n.map(a=>Zn(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!s.has(Zn(a.id,a.ownerId,a.ownerAskId))&&!wE(a)),...n]}function e4({n:t,onClose:e}){return l.jsxs("div",{className:`nc-ntf-toast${t.urgency==="high"?" high":""}`,role:"status","aria-live":"polite",children:[l.jsxs("div",{className:"nc-ntf-toast-txt",children:[l.jsx("b",{children:t.title}),t.body&&l.jsx("small",{children:t.body}),t.session&&l.jsx("span",{className:"nc-ntf-from",children:t.session}),t.ownerId&&l.jsx("span",{className:"nc-ntf-from",children:p("feed-owner")})]}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:e,title:p("close"),children:l.jsx(Pt,{name:"x",size:14})})]})}function t4({ask:t,token:e,onAnswered:n,onDismiss:s,askReplyAccess:i=!1,feedViewState:a="live",initialUncertainRid:c=null,canDismissLocal:u=!1,canDismissRemote:h=!1,capabilityStatus:f="loading",onRefused:g=()=>{}}){const[v,_]=w.useState(""),[b,x]=w.useState(!1),[L,C]=w.useState(null),[R,S]=w.useState(!1),[I,E]=w.useState(c),[F,$]=w.useState(!1),[X,V]=w.useState(!1),G=w.useRef(null);w.useEffect(()=>{c&&E(c)},[c]);const ne=R||b||!!I||X||!!t.ownerId&&(["loading","unsupported"].includes(f)||!u&&!h),K=!!t.ownerId&&u===!0,D=async j=>{const z=String(j||"").trim();if(!(!z||b||R||I||X)){C(null),x(!0);try{if(t.ownerId){const M=t.ownerAskId||t.id,A=await u5(e,{ownerId:t.ownerId,askId:M,text:z,requestId:G.current||(G.current=crypto.randomUUID())});if(A&&A.uncertain){const N=A.reason==="delivery-unknown-block"&&!A.originalRequestId;E(N?null:A.originalRequestId||A.requestId||G.current),V(N);return}if(!A||A.status!=="committed"){G.current=null,g(),C(p("ask-reconcile"));return}n(t.id,t.ownerId,t.ownerAskId)}else await l5(e,t.id,z),n(t.id)}catch(M){C(String(M.message||M)),t.ownerId&&!M.status?E(G.current):G.current=null,g()}finally{x(!1)}}},P=async()=>{if(!ne){C(null),S(!0);try{let j;if(K){if(j=await m5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),(j==null?void 0:j.dismissed)!==!0||j.scope!=="local"||!["pending","blocked"].includes(j.ownerSync))throw new Error(p("ask-dismiss-unconfirmed"))}else t.ownerId?await p5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}):await c5(e,t.id);yE(Zn(t.id,t.ownerId,t.ownerAskId),K?t:null),s(t.id,t.ownerId,t.ownerAskId,j)}catch(j){C(String(j&&j.message||j)),g()}finally{S(!1)}}},O=p(I||X?"ask-uncertain":K?"ask-dismiss-local":a==="degraded"?"ask-dismiss-stale":"ask-dismiss");return l.jsxs("div",{className:"nc-ask-card",children:[l.jsxs("div",{className:"nc-ask-head",children:[l.jsx("span",{className:"nc-ntf-from",children:t.session}),t.ownerId&&l.jsx("span",{className:"nc-ntf-from",children:p("feed-owner")}),l.jsxs("code",{className:"nc-ask-id",children:["#",t.id]}),l.jsx("button",{type:"button",className:"nc-ask-dismiss",title:O,"aria-label":O,disabled:ne,onClick:P,children:l.jsx(Pt,{name:"x",size:14})})]}),l.jsx("div",{className:"nc-ask-q",children:t.question}),t.ownerId&&i===!1&&l.jsx("small",{className:"nc-set-hint",children:p(f==="loading"?"ask-capability-loading":f==="unsupported"?"ask-capability-unsupported":f==="unreachable"?"ask-capability-unreachable":"ask-remote-readonly")}),t.ownerId&&i!==!1&&a==="degraded"&&l.jsx("small",{className:"nc-set-hint",children:p("ask-feed-stale")}),(I||X)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:p("ask-uncertain")}),X&&!I&&l.jsx("div",{className:"nc-err",children:p("ask-reconcile")}),I&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:F,onClick:async()=>{$(!0);try{const j=await d5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id,requestId:I});(j==null?void 0:j.state)==="committed"?n(t.id,t.ownerId,t.ownerAskId):(j==null?void 0:j.state)==="failed"&&(E(null),G.current=null,g())}catch(j){C(String(j.message||j)),g()}finally{$(!1)}},children:p("ask-verify")})]}),(!t.ownerId||i===!0)&&!I&&!X&&l.jsxs(l.Fragment,{children:[Array.isArray(t.options)&&t.options.length>0&&l.jsx("div",{className:"nc-ask-opts",children:t.options.map(j=>l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:b||R,onClick:()=>D(j),children:j},j))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:p("ask-reply-ph"),value:v,disabled:b||R,onChange:j=>_(j.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:b||R||!v.trim(),onClick:()=>D(v),children:p("send")})]})]}),L&&l.jsx("div",{className:"nc-err",children:L})]})}function n4({token:t}){const[e]=zn(),[n]=uE(),[s,i]=w.useState([]),[a,c]=w.useState([]),[u,h]=w.useState(null),[f,g]=w.useState([]),[v,_]=w.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),[b,x]=w.useState({}),L=w.useRef(new Map),C=w.useRef(0),[R,S]=w.useState(0),I=w.useRef(new Map),E=w.useRef(0),F=w.useRef(new Map),$=w.useRef(new Map),X=w.useRef(new Map),V=Q=>(Q||[]).filter(Z=>{const me=I.current.get(Zn(Z.id,Z.ownerId,Z.ownerAskId));if(!me)return!0;if(Date.now()-me.at>_E)return I.current.delete(Zn(Z.id,Z.ownerId,Z.ownerAskId)),!0;const de=Yo(Z);return Number.isSafeInteger(de)&&de>0&&Number.isSafeInteger(me.ts)&&me.ts>0?de!==me.ts:me.fingerprint!==null&&me.fingerprint!==void 0&&me.fingerprint!==JSON.stringify([Z.question,Z.options||[],Z.session])}),G=w.useRef(a);G.current=a;const ne=w.useCallback((Q=!1)=>{if(!t)return;const Z=new Set;for(const me of G.current){if(!me.ownerId)continue;const de=me.ownerAskId||me.id,ie=`${me.ownerId}|${de}`;Z.add(ie);const xe=L.current.get(ie);if(xe&&(!Q||xe.pending))continue;const Be=new AbortController,nt=C.current,Le={controller:Be,pending:!0};L.current.set(ie,Le),x(Ie=>({...Ie,[ie]:{canReply:!1,status:"loading"}})),h5(t,{ownerId:me.ownerId,askId:de},{signal:Be.signal}).then(Ie=>{if(nt!==C.current||Be.signal.aborted||L.current.get(ie)!==Le)return;const ue=Ie&&Ie.ownerId===me.ownerId&&Ie.askId===de&&typeof Ie.canReply=="boolean"&&(!Ie.canReply||Ie.status==="open");x(Re=>({...Re,[ie]:ue?Ie:{canReply:!1,status:"unreachable"}}))}).catch(()=>{nt===C.current&&!Be.signal.aborted&&L.current.get(ie)===Le&&x(Ie=>({...Ie,[ie]:{canReply:!1,status:"unreachable"}}))}).finally(()=>{Le.pending=!1})}for(const[me,de]of L.current)Z.has(me)||(de.controller.abort(),L.current.delete(me))},[t]);w.useEffect(()=>{C.current++;for(const Q of L.current.values())Q.controller.abort();return L.current.clear(),x({}),()=>{C.current++;for(const Q of L.current.values())Q.controller.abort();L.current.clear()}},[t]),w.useEffect(()=>{ne()},[a,ne]);const K=w.useRef(!1);w.useEffect(()=>{v&&(K.current&&ne(!0),K.current=!0)},[v,ne]);const D=w.useRef(0),P=w.useRef(null);P.current||(P.current=d6());const O=w.useRef({enabled:n,lang:e});O.current={enabled:n,lang:e};const j=w.useCallback(Q=>{i(Z=>Z.filter(me=>me.key!==Q))},[]),z=w.useCallback(Q=>{if(Q.askId&&Q.ownerId){const de=Number.isSafeInteger(Q.ownerAskTs)&&Q.ownerAskTs>0?Q.ownerAskTs:Q.ownerAskFingerprint;if(de){const ie=JSON.stringify([Q.ownerId,Q.ownerAskId||Q.askId,de]),xe=Date.now();for(const[Be,nt]of X.current)xe-nt>1440*60*1e3&&X.current.delete(Be);if(X.current.has(ie))return;X.current.set(ie,xe),X.current.size>4096&&X.current.delete(X.current.keys().next().value)}}const Z=`t${D.current+=1}`;i(de=>[...de.slice(-3),{...Q,key:Z}]),setTimeout(()=>j(Z),Q.urgency==="high"?J6:X6);const me=O.current;if(me.enabled)try{P.current.enqueue(Q,o6(Q,me.lang))}catch{}},[j]);w.useEffect(()=>{n||P.current.stop()},[n]),w.useEffect(()=>{const Q=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&P.current.stop()},Z=()=>P.current.stop();return document.addEventListener("visibilitychange",Q),window.addEventListener("blur",Q),window.addEventListener(Tg,Z),()=>{document.removeEventListener("visibilitychange",Q),window.removeEventListener("blur",Q),window.removeEventListener(Tg,Z),typeof P.current.dispose=="function"?P.current.dispose():P.current.stop()}},[]);const M=Q=>{if(Q.ownerAskId||!Q.ownerId)return Q;const Z=G.current.filter(de=>de.ownerId===Q.ownerId&&(de.id===Q.id||de.ownerAskId===Q.id)),me=new Set(Z.map(de=>de.ownerAskId||de.id));return me.size>1?null:{...Q,ownerAskId:me.size===1?[...me][0]:Q.id}},A=(Q,Z)=>{const me=G.current.find(ie=>Zn(ie.id,ie.ownerId,ie.ownerAskId)===Q),de=me&&Yo(me);return Number.isSafeInteger(Z==null?void 0:Z.ownerAskTs)&&Z.ownerAskTs>0&&Number.isSafeInteger(de)&&de>0&&Z.ownerAskTs!==de},N=(Q,Z,me,de)=>{const ie=Zn(Q,Z,me);(de==null?void 0:de.scope)==="local"&&["pending","blocked"].includes(de.ownerSync)&&h(de.ownerSync);const xe=G.current.find(Le=>Zn(Le.id,Le.ownerId,Le.ownerAskId)===ie),Be=xe&&Yo(xe);if(A(ie,de))return;const nt=xe||(de==null?void 0:de.askGeneration);I.current.set(ie,{at:Date.now(),ts:xe?Be:de==null?void 0:de.ownerAskTs,fingerprint:nt&&nt.question!==void 0?JSON.stringify([nt.question,nt.options||[],nt.session]):null}),F.current.delete(ie),I.current.size>4096&&I.current.delete(I.current.keys().next().value),c(Le=>Le.filter(Ie=>Zn(Ie.id,Ie.ownerId,Ie.ownerAskId)!==ie))};w.useEffect(()=>{if(!t)return;const Q=G6(t,Z=>{if(Z.type==="feed-state-changed"){S(me=>me+1);return}if(Z.type==="notify"&&Z.ownerId&&Z.eventId){const me=t1(Z,Z.ownerId);me&&g(de=>n1(Y6(de,[me],null)))}if(Z.type==="notify")z(Z);else if(Z.type==="ask"&&Z.ask&&Z.ask.id){const me=Zn(Z.ask.id,Z.ask.ownerId,Z.ask.ownerAskId);F.current.set(me,++E.current),F.current.size>4096&&F.current.delete(F.current.keys().next().value),c(de=>Sd(de,V([Z.ask])))}else if(Z.type==="ask-answered"&&Z.id){const me=M(Z);me&&N(me.id,me.ownerId,me.ownerAskId,Z)}else if(Z.type==="ask-dismissed"&&(Z.id||Z.ownerAskId)){const me=M(Z);if(!me)return;const de=Zn(me.id,me.ownerId,me.ownerAskId);if(A(de,Z))return;const ie=Z.scope==="local"&&G.current.find(xe=>Zn(xe.id,xe.ownerId,xe.ownerAskId)===de);yE(de,Z.scope==="local"?ie||{...Z.askGeneration,ownerAskTs:Z.ownerAskTs}:null),N(me.id,me.ownerId,me.ownerAskId,Z)}},()=>{ne(!0),S(Z=>Z+1)});return()=>{Q()}},[t,z,ne]),w.useEffect(()=>{let Q=!0;const Z=E.current;return t&&a5(t).then(me=>{Q&&c(de=>Sd(Z6(de,V((me.asks||[]).filter(ie=>!ie.ownerId||($.current.get(ie.ownerId)||0)<=Z))),V(de.filter(ie=>(F.current.get(Zn(ie.id,ie.ownerId,ie.ownerAskId))||0)>Z))))}).catch(()=>{}),()=>{Q=!1}},[t,R]);const[U,T]=w.useState({});w.useEffect(()=>{if(!t)return;let Q=!0;return f5(t).then(Z=>{if(!Q)return;const me={};for(const de of Z&&Z.attempts||[])de&&de.state==="uncertain"&&de.ownerId&&de.askId&&de.requestId&&(me[de.ownerId+"|"+de.askId]=de.requestId);T(me)}).catch(()=>{}),()=>{Q=!1}},[t]);const[H,se]=w.useState({});return w.useEffect(()=>{let Q=!0;const Z=E.current;return g5(t).then(me=>{if(!Q)return;const de={},ie=[],xe=new Map,Be=new Set;for(const Le of me&&me.views||[]){de[Le.ownerId]={stale:Le.stale===!0,error:!!Le.lastError},Be.add(Le.ownerId);for(const Ie of Le.asks||[])Ie&&Ie.id&&ie.push({...Ie,ownerId:Le.ownerId,imported:!0});for(const Ie of Le.notifications||[]){const ue=t1(Ie,Le.ownerId);ue&&xe.set(ue.key,ue)}}se(de);const nt=new Set((me&&me.views||[]).filter(Le=>{const Ie=typeof Le.cursor=="string"&&/^([1-9]\d*):(\d+)$/.exec(Le.cursor);return Le.stale===!1&&Number.isSafeInteger(Le.viewEpoch)&&Le.viewEpoch>0&&Ie&&Number(Ie[1])===Le.viewEpoch&&Number.isSafeInteger(Number(Ie[2]))&&!Le.lastError&&!Le.error&&Le.resyncRequired!==!0&&Array.isArray(Le.asks)&&Le.asks.length<100}).map(Le=>Le.ownerId));for(const Le of nt)$.current.delete(Le),$.current.set(Le,++E.current),$.current.size>4096&&$.current.delete($.current.keys().next().value);c(Le=>Sd(Le.filter(Ie=>!nt.has(Ie.ownerId)||(F.current.get(Zn(Ie.id,Ie.ownerId,Ie.ownerAskId))||0)>Z),V(ie))),g(Le=>{const Ie=[];for(const ue of Le)Be.has(ue.ownerId)&&Ie.push(ue);for(const ue of xe.values())Ie.push({...ue,key:ue.key});return n1(Ie)})}).catch(()=>{}),()=>{Q=!1}},[t,R]),l.jsxs(l.Fragment,{children:[u&&l.jsx("div",{className:"nc-ntf-toasts",children:l.jsxs("div",{className:"nc-ntf-toast",role:"status",children:[l.jsx("div",{className:"nc-ntf-toast-txt",children:p(u==="blocked"?"ask-dismiss-local-blocked":"ask-dismiss-local-pending")}),l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("close"),onClick:()=>h(null),children:l.jsx(Pt,{name:"x",size:14})})]})}),s.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:s.map(Q=>l.jsx(e4,{n:Q,onClose:()=>j(Q.key)},Q.key))}),(a.length>0||f.length>0)&&!v&&l.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>_(!0),title:p("asks-title"),children:["? ",l.jsx("span",{className:"nc-ask-count",children:a.length+f.length})]}),(a.length>0||f.length>0)&&v&&l.jsxs("div",{className:"nc-ask-panel",children:[l.jsxs("div",{className:"nc-ask-panel-head",children:[l.jsx("b",{children:p("asks-title")}),l.jsx("span",{className:"nc-ask-count",children:a.length}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>_(!1),title:p("close"),children:l.jsx(Pt,{name:"x",size:16})})]}),l.jsxs("div",{className:"nc-ask-panel-body",children:[a.map(Q=>{var Z,me,de,ie,xe,Be;return l.jsx(t4,{ask:Q,token:t,askReplyAccess:!Q.ownerId||((Z=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:Z.canReply)===!0,canDismissLocal:((me=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:me.canDismissLocal)===!0,canDismissRemote:((de=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:de.canDismissRemote)===!0||((ie=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:ie.canDismissRemote)===void 0&&((xe=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:xe.canReply)===!0,capabilityStatus:((Be=b[Q.ownerId+"|"+(Q.ownerAskId||Q.id)])==null?void 0:Be.status)||"loading",onRefused:()=>ne(!0),feedViewState:Q.ownerId?Q6(H,Q.ownerId):"live",initialUncertainRid:Q.ownerId&&U[Q.ownerId+"|"+(Q.ownerAskId||Q.id)]||null,onAnswered:N,onDismiss:N},Zn(Q.id,Q.ownerId,Q.ownerAskId))}),f.length>0&&l.jsxs("div",{className:"nc-remote-notices",children:[l.jsx("div",{className:"nc-remote-notices-head",children:l.jsx("b",{children:p("remote-notices-title")})}),f.map(Q=>l.jsxs("div",{className:"nc-remote-notice"+(Q.urgency==="high"?" nc-remote-notice-high":""),children:[Q.title?l.jsx("b",{children:Q.title}):null,Q.body?l.jsx("div",{children:Q.body}):null,l.jsxs("div",{className:"nc-remote-notice-meta",children:[Q.ownerId.slice(0,8)," · ",new Date(Q.ts||Date.now()).toLocaleString()]})]},Q.key))]})]})]})]})}const bE="nc_fontsize",SE=9,xE=24;function Hg(t=globalThis.localStorage){const e=Number(t.getItem(bE));return e>=SE&&e<=xE?e:13}function kE(t,e=globalThis.localStorage){const n=Math.max(SE,Math.min(xE,t));return e.setItem(bE,String(n)),n}const s4=4e3;async function i4(t){const e=await qn("/api/sessions",t);if((e==null?void 0:e.ok)===!1)throw new Error(`HTTP ${e.status}`);const n=await e.json();if(!Array.isArray(n==null?void 0:n.sessions))throw new Error("invalid sessions payload");return n.sessions}async function om(t,e=[]){var u;const[n,s]=await Promise.allSettled([e.length?Xg(t,e):i4(t),Qa(t,e)]),i=n.status==="fulfilled"&&Array.isArray((u=n.value)==null?void 0:u.sessions)?n.value.sessions:Array.isArray(n.value)?n.value:null,a=s.status==="fulfilled"?s.value:null,c=(a==null?void 0:a.available)===!0&&Array.isArray(a.cells)?a.cells:null;return{sessions:i,cells:c,fresh:Array.isArray(i)&&Array.isArray(c)}}function CE(t,e,n){return n===!0&&(t==null?void 0:t.degraded)!==!0&&(t==null?void 0:t.active)===!0&&t.tmux!==!1&&!!t.tmuxSession&&(e||[]).some(s=>(s==null?void 0:s.name)===t.tmuxSession)}function r4(t){const e=new Map((t.sessions||[]).map(i=>[i.name,i])),n=[],s=(i,a,c,u=[],h="")=>{const f=new Map((a||[]).map(g=>[g.name,g]));for(const g of i||[]){const v=f.get(g.tmuxSession)||{},_=ch(g,v),b=CE(g,a,c);n.push({key:qa(u,g.tmuxSession||g.cell),session:g.tmuxSession,route:u,cellName:g.cell,label:g.cell,node:u.length?u.join("/"):"",nodeLabel:h,live:b,selectable:b,verified:c===!0,working:_.working,degraded:!!g.degraded,active:g.active===!0,activity:v.activity||g.activity||0,subtitle:_.subtitle,preview:v.preview||g.preview||"",telemetry:v.telemetry||null,panelUrl:g.panelUrl||""})}};s(t.cells,[...e.values()],t.localFresh===!0);for(const i of t.nodeGroups||[]){const a=Array.isArray(i.route)?i.route:[];i.kind==="vl"||!a.length||s(i.cells,i.sessions,i.switcherFresh===!0,a,i.label||i.name||"")}return n}function o4(t){const e=new Map,n=Array.isArray(t.sessions)?t.sessions:[],s=Array.isArray(t.cells)?t.cells:[],i=new Map(n.map(c=>[c.name,c])),a=new Set(s.map(c=>c.tmuxSession).filter(Boolean));e.set("local",Lv(s,n.filter(c=>!a.has(c.name)),i));for(const c of t.nodeGroups||[]){const u=Array.isArray(c.route)?c.route:[];if(c.kind==="vl"||!u.length)continue;const h=Array.isArray(c.cells)?c.cells:[],f=Array.isArray(c.sessions)?c.sessions:[],g=new Set(h.map(v=>v.tmuxSession).filter(Boolean));e.set(u.join("/"),mc({...c,route:u,cells:h,sessions:f,unmanaged:f.filter(v=>!g.has(v.name))}).rawItems)}return e}function a4(t,e,n,s){return[...new Set(t.map(a=>a.node||"local"))].flatMap(a=>{const c=t.filter(g=>(g.node||"local")===a),u=new Map((e.get(a)||[]).map(g=>[g.key,g])),h=new Map(c.map(g=>[g.key,g])),f=c.map(g=>{const v=u.get(g.key);return{...g,label:(v==null?void 0:v.label)||g.label,live:(v==null?void 0:v.live)??g.live,fresh:(v==null?void 0:v.fresh)===!0,activity:(v==null?void 0:v.activity)??g.activity}});return co(f,n,"all",Ii(s,a)).map(g=>h.get(g.key))})}function l4({token:t,current:e,onPick:n,onClose:s,panelPort:i=0,nodePanelPorts:a={},localNodeLabel:c="",hostByRoute:u={},onDesignateCell:h,onClearHostCell:f,onLiveHostApplied:g,sideKey:v=null,onToggleSide:_,pollMs:b=s4}){const[x,L]=w.useState(z0),[C,R]=w.useState(!1),[S,I]=w.useState(!1),[E,F]=w.useState(""),[$,X]=w.useState(null),V="stream",[G,ne]=w.useState(Hg),K=W=>ne(ee=>kE(ee+W)),[D,P]=w.useState(null),[O,j]=w.useState(!1),[z,M]=w.useState(""),A=w.useRef(null),N=w.useRef(null),U=w.useMemo(()=>r4(x),[x]),T=w.useMemo(()=>o4(x),[x]),{pins:H,orders:se,togglePin:Q,removePin:Z,pinError:me,canMoveRoster:de,moveRoster:ie,stepRoster:xe}=xv(),Be=w.useMemo(()=>a4(U,T,H,se),[U,T,H,se]),nt=w.useMemo(()=>C?Be:Be.filter(W=>W.selectable||W.degraded&&W.active),[Be,C]),Le=w.useMemo(()=>$?nt.find(W=>W.key===$&&W.selectable):null,[nt,$]);w.useEffect(()=>{$&&!nt.some(W=>W.key===$&&W.selectable)&&X(null)},[nt,$]);const Ie=w.useMemo(()=>D?U.find(W=>W.key===D.key):null,[U,D]),ue=!!(D&&Ie);w.useEffect(()=>{me&&me.message&&F(me.message)},[me]),w.useEffect(()=>{var J;const W=document.activeElement;(J=N.current)==null||J.focus();const ee=be=>{be.key==="Escape"&&!ue&&s()};return document.addEventListener("keydown",ee),()=>{var be;document.removeEventListener("keydown",ee),(be=W==null?void 0:W.focus)==null||be.call(W)}},[s,ue]),w.useEffect(()=>{let W=!0,ee=!1;const J=async()=>{if(ee)return;ee=!0;const ye=z0(),ot=Array.isArray(ye.nodeGroups)?ye.nodeGroups:[],oe=om(t),$e=pt=>pt.kind!=="vl"&&Array.isArray(pt.route)&&pt.route.length>0,ut=await Promise.all(ot.filter($e).map(async pt=>({group:pt,result:await om(t,pt.route)}))),kt=await oe;if(!W)return;const St=new Map(ut.map(({group:pt,result:Ut})=>[JSON.stringify(pt.route||[]),Ut])),Lt=ot.map(pt=>{if(!$e(pt))return{...pt,switcherFresh:!1};const Ut=St.get(JSON.stringify(pt.route||[]));return Ut?{...pt,sessions:Ut.sessions||pt.sessions||[],cells:Ut.cells||pt.cells||[],switcherFresh:Ut.fresh}:{...pt,switcherFresh:!1}}),_t=tC({...ye,sessions:kt.sessions||ye.sessions||[],cells:kt.cells||ye.cells||[],localFresh:kt.fresh,nodeGroups:Lt,refreshedAt:Date.now()});L(_t),I(!0),ee=!1};J();const be=setInterval(J,b);return()=>{W=!1,clearInterval(be)}},[t,b]);const[Re,fe]=w.useState(""),Ee={getLiveHost:W=>Xd(t,W),designateHostCell:(W,ee,J)=>Jd(t,W,ee,J),clearHostCell:(W,ee)=>Qd(t,W,ee)},Y=W=>(u[Cs(W)]||{}).hostCell||null,pe=async(W,ee)=>{fe(W.key);const J=await eh({action:ee?"remove":"use",cellId:W.cellName,route:W.route||[],api:Ee});fe(""),F(p(J.messageKey).replace("{cell}",J.hostCell||W.cellName)),J.ok&&g&&g({route:W.route||[],hostCell:J.hostCell,revision:J.revision})},Ae=W=>W.degraded?p("cell-degraded"):W.verified?W.selectable?W.working?p("cell-working"):p("cell-idle"):p("cell-off"):p("cell-switcher-not-confirmed"),ke=async W=>{if(F(""),!W.selectable){F(W.verified?p("cell-switcher-not-active"):p("cell-switcher-not-confirmed"));return}M(W.key);try{const ee=await om(t,W.route),J=(ee.cells||[]).find(be=>(be==null?void 0:be.cell)===W.cellName&&(be==null?void 0:be.tmuxSession)===W.session);if(ee.fresh!==!0){F(p("cell-switcher-verify-failed"));return}if(!CE(J,ee.sessions,ee.fresh)){F(p("cell-switcher-not-active"));return}n({session:W.session,...W.node?{node:W.node}:{},cellName:W.cellName}),s()}catch{F(p("cell-switcher-verify-failed"))}finally{M("")}},We=W=>{if(!W.selectable){ke(W);return}if($===W.key){ke(W);return}X(W.key)},Ne=w.useRef(null),ge=8,st=W=>{const ee=Ne.current;if(W.isPrimary===!1){ee&&ee.state==="open"&&(ee.state="invalid");return}if(ee&&ee.state==="open"&&(ee.id!==W.pointerId||ee.row!==W.currentTarget)){ee.state="invalid";return}Ne.current={id:W.pointerId,row:W.currentTarget,x:W.clientX,y:W.clientY,maxDelta:0,state:"open"}},Ze=W=>{const ee=Ne.current;!ee||ee.state!=="open"||ee.id!==W.pointerId||(ee.maxDelta=Math.max(ee.maxDelta,Math.hypot(W.clientX-ee.x,W.clientY-ee.y)),ee.maxDelta>ge&&(ee.state="invalid"))},De=W=>{const ee=Ne.current;!ee||ee.id!==W.pointerId||ee.state!=="open"||(ee.state=ee.maxDelta<=ge?"tap":"invalid")},He=W=>{const ee=Ne.current;ee&&ee.id===W.pointerId&&(ee.state="invalid")},qe=W=>{const ee=Ne.current;return Ne.current=null,W.detail===0?!0:!ee||ee.state==="invalid"||ee.row!==W.currentTarget?!1:Math.hypot(W.clientX-ee.x,W.clientY-ee.y)<=ge},wt=W=>({onToggleLive:()=>pe(W,Y(W.route||[])===W.cellName),onTogglePin:()=>Cv({view:lh({item:{key:W.key,value:{cell:W.cellName}},pins:H,hostByRoute:u,route:W.route||[]}),itemKey:W.key,togglePin:Q,removePin:Z})});return l.jsxs("div",{className:"nc-cell-switcher-backdrop",onClick:s,children:[Le&&l.jsxs("div",{className:"nc-cell-switcher-anteprima","data-testid":"cell-switcher-anteprima",onClick:W=>W.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-anteprima-testa",children:[l.jsxs("b",{children:[p("cell-switcher-preview-word")," ",Le.cellName]}),l.jsx("small",{children:p("cell-switcher-preview-readonly")}),l.jsxs("span",{className:"nc-cell-switcher-anteprima-zoom",children:[l.jsx("button",{type:"button",onClick:()=>K(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:"−"}),l.jsxs("span",{"data-testid":"cell-switcher-fontsize",children:[G," px"]}),l.jsx("button",{type:"button",onClick:()=>K(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:"+"})]})]}),l.jsx(mv,{row:Le,token:t,source:V,chrome:!1,panelPort:kc(Le.route||[],a,i),liveHost:Va({liveHost:u[Cs(Le.route||[])],cells:x.cells||[]}),onLiveHostApplied:g,fontSize:G,readOnly:!0})]}),l.jsxs("aside",{ref:A,className:`nc-cell-switcher${Le?" with-anteprima":""}`,role:"dialog","aria-label":p("fleet-cells"),tabIndex:-1,onClick:W=>W.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-controls",children:[l.jsx("b",{children:p("cell-switcher-title")}),c&&l.jsx("small",{className:"nc-cell-switcher-node",children:c}),l.jsxs("div",{className:"nc-cell-switcher-filter",role:"group","aria-label":p("cell-switcher-filter"),children:[l.jsx("button",{type:"button",className:C?"":"on","aria-pressed":!C,onClick:()=>{F(""),R(!1)},children:p("cell-switcher-show-active")}),l.jsx("button",{type:"button",className:C?"on":"","aria-pressed":C,onClick:()=>{F(""),R(!0)},children:p("cell-switcher-show-all")})]}),l.jsx("button",{type:"button",className:`nc-cell-switcher-reorder${O?" on":""}`,"aria-pressed":O,title:p("reorder-help"),"aria-label":p("reorder"),onClick:()=>{F(""),j(W=>!W)},children:"↕"}),l.jsx("button",{ref:N,type:"button",className:"nc-cell-switcher-close","aria-label":p("cell-switcher-close"),title:p("cell-switcher-close"),onClick:s,children:"×"})]}),!Le&&l.jsx("div",{className:"nc-cell-switcher-hint",children:p("cell-switcher-tap-hint")}),l.jsxs("div",{className:"nc-cell-switcher-list",children:[(()=>{const W=Va({liveHost:u[Cs([])],cells:x.cells||[]});if(!W||!W.cell)return null;const{modeKey:ee}=vP(W);return l.jsx("div",{className:"nc-cell-switcher-live-strip","data-testid":"cell-switcher-live-strip",children:p("cell-switcher-live-strip").replace("{cell}",W.cell).replace("{mode}",p(ee||"live-host-mode-unknown"))})})(),!S&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-refreshing")}),S&&nt.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-empty-active")}),nt.map((W,ee)=>{const J=(e==null?void 0:e.session)===W.session&&((e==null?void 0:e.node)||"")===W.node,be=!!D&&D.key===W.key,ye=v!=null&&v===W.key,ot=Ae(W),oe=cg(p,W.activity),$e=ug(p,W.telemetry),ut=[oe,$e].filter(Boolean).join(" · "),kt=W.node||"local",St=ee>0?nt[ee-1].node||"local":null,Lt=kt!==St,_t=T.get(kt)||U.filter(pt=>(pt.node||"local")===kt);return l.jsxs(w.Fragment,{children:[Lt&&l.jsx("div",{className:"nc-cell-switcher-position",children:p("cell-switcher-group").replace("{node}",W.nodeLabel||c||p("cell-switcher-group-local"))}),l.jsxs("div",{className:`nc-cell-switcher-row${J?" current":""}${$===W.key?" selected":""}${ye?" side":""}${W.selectable?"":" off"}`,"data-roster-key":W.key,"data-position":kt,children:[O&&l.jsx(Gi,{position:kt,itemKey:W.key,label:W.cellName,canMove:de,onMove:(pt,Ut)=>ie(kt,pt,Ut,_t),onStep:pt=>xe(kt,W.key,pt,_t)}),l.jsx("span",{className:"nc-cell-switcher-peek",children:l.jsx("span",{className:`nc-cell-switcher-dot${W.degraded?" warn":W.live?` on${W.working?" working":""}`:""}`})}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":J?"true":void 0,"aria-disabled":!W.selectable,"data-selected":$===W.key?"true":void 0,disabled:z===W.key,onPointerDown:st,onPointerMove:Ze,onPointerUp:De,onPointerCancel:He,onClick:pt=>{qe(pt)&&We(W)},children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsxs("span",{className:"nc-cell-switcher-nameline",children:[l.jsx("b",{children:W.cellName}),J&&l.jsx("span",{className:"nc-cell-switcher-here",children:p("cell-switcher-here")}),$===W.key&&l.jsx("span",{className:"nc-cell-switcher-taptwo",children:p("cell-switcher-two-taps")})]}),l.jsxs("span",{className:"nc-cell-switcher-stateline",children:[l.jsx("small",{className:"nc-cell-switcher-state",children:ot}),ut&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:ut})]})]})}),_&&l.jsx("button",{type:"button",className:`nc-cell-switcher-side${ye?" on":""}`,title:p(ye?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-label":p(ye?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-pressed":ye?"true":"false",disabled:J||!W.selectable,onClick:pt=>{pt.stopPropagation(),!J&&W.selectable&&_(W)},children:l.jsx(Pt,{name:"splitView",size:20})}),l.jsx("button",{type:"button",className:`nc-cell-switcher-menu${be?" on":""}`,title:`${p("cell-actions-open")}: ${W.cellName}`,"aria-label":`${p("cell-actions-open")}: ${W.cellName}`,"aria-haspopup":"menu","aria-expanded":be?"true":"false",onClick:pt=>{pt.stopPropagation(),P({key:W.key})},children:"⋯"})]})]},W.key)})]}),E&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:E}),ue&&(()=>{const W=Ie,ee=Ev({...oo({item:{key:W.key,value:{cell:W.cellName}},cellName:W.cellName,route:W.route||[],pins:H,hostByRoute:u}),canBoot:!1,alive:W.selectable,handlers:wt(W)});return l.jsx(Nv,{cellName:W.cellName,items:ee,busy:Re===W.key,onClose:()=>P(null)})})()]})]})}const c4=2e3;function u4(t){if(t.kind==="gap")return`${p("vl-events-gap")} ${t.count||"?"}`;if(t.kind==="truncate")return p("vl-events-truncated");if(t.kind==="turn_end")return p("vl-events-turn-end");if(t.kind==="done")return p("vl-events-done");if(t.kind==="writer_epoch")return p("vl-events-writer-epoch");if(t.kind==="tool_start")return`${p("vl-events-tool")} ${t.name||""}`.trim();if(t.kind==="tool_end"){const e=t.isError?p("vl-events-tool-failed"):p("vl-events-tool-ok");return`${p("vl-events-tool")} ${t.name||""} — ${e}`.trim()}return t.kind==="usage"?t.text||p("vl-events-usage"):t.text||""}function d4({token:t,nodeId:e,route:n=[]}){const[s,i]=w.useState([]),[a,c]=w.useState(!1),u=w.useRef(0),h=w.useRef(!1);return w.useEffect(()=>{let f=!0;u.current=0,h.current=!1,i([]);const g=async()=>{if(!h.current){h.current=!0;try{const b=await BN(t,e,u.current,n);if(!f)return;c(!1);const L=(Array.isArray(b==null?void 0:b.events)?b.events:[]).filter(C=>Number.isSafeInteger(C==null?void 0:C.seq)&&C.seq>u.current);L.length&&(i(C=>C.concat(L).slice(-500)),u.current=L[L.length-1].seq),Number.isSafeInteger(b==null?void 0:b.cursor)&&b.cursor>u.current&&(u.current=b.cursor)}catch{f&&c(!0)}finally{h.current=!1}}},v=()=>{g().catch(()=>{})};v();const _=setInterval(v,c4);return()=>{f=!1,clearInterval(_)}},[t,e,JSON.stringify(n)]),l.jsxs("div",{className:"nc-vl-events",children:[a&&l.jsx("div",{className:"nc-set-hint nc-vl-events-stale",children:p("vl-events-stale")}),s.length===0&&!a&&l.jsx("small",{className:"nc-set-hint","data-testid":"vl-events-empty",children:p("vl-events-empty")}),s.length>0&&l.jsx("ol",{className:"nc-vl-events-list",children:s.map(f=>l.jsx("li",{"data-testid":`vl-ev-${f.seq}`,className:`nc-vl-ev nc-vl-ev-${f.kind}${f.isError?" error":""}${f.kind==="gap"?" gap":""}`,children:u4(f)},`${f.seq}-${f.kind}`))})]})}function s1({peer:t,token:e,onBack:n}){var s;return zn(),t?l.jsxs("section",{className:"nc-vl-session-view",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:n,title:p("back"),children:[l.jsx(Pt,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:p("back")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:t.label,children:t.label}),((s=t.session)==null?void 0:s.profile)&&l.jsxs("small",{className:"nc-bar-sub",children:[t.session.profile," · ",p("vl-events-title")]})]}),l.jsx("span",{className:"nc-bar-right"})]}),l.jsx("div",{className:"nc-vl-session-body",children:l.jsx(d4,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Wd="nc_dual_side";function Ug(t,e){return!t||!e?!1:t.session===e.session&&(t.node||"")===(e.node||"")}function h4(t,e,n){return!n||!n.session||t&&Ug(t,n)?e:e&&Ug(e,n)?null:{session:n.session,...n.node?{node:n.node}:{},...n.ownerId?{ownerId:n.ownerId}:{}}}function f4(){try{const t=JSON.parse(localStorage.getItem(Wd)||"null");return!t||!t.main||!t.side||!t.main.session||!t.side.session?null:t}catch{return null}}function p4(t,e){try{if(!t||!e||!t.session||!e.session){localStorage.removeItem(Wd);return}const n=s=>({session:s.session,...s.node?{node:s.node}:{}});localStorage.setItem(Wd,JSON.stringify({main:n(t),side:n(e)}))}catch{}}function i1(){try{localStorage.removeItem(Wd)}catch{}}const m4=.2;function od(t){return Math.max(m4,t)}function g4(){try{if(typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches)return!0}catch{}try{return Number(globalThis.navigator&&globalThis.navigator.maxTouchPoints)>0}catch{return!1}}function v4({onSubmit:t,reason:e=""}){zn();const[n,s]=w.useState(""),[i,a]=w.useState(g4),c=n.trim(),u=h=>{h&&h.preventDefault&&h.preventDefault(),c&&t(c,i)};return l.jsxs("form",{className:"nc-auth",onSubmit:u,children:[l.jsx("p",{children:p("auth-prompt")}),e==="invalid"&&l.jsx("p",{className:"nc-auth-error",role:"alert",children:p("auth-invalid")}),l.jsx("input",{type:"text",value:n,placeholder:"token","aria-label":"token",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off",spellCheck:!1,onChange:h=>s(h.target.value)}),l.jsxs("label",{children:[l.jsx("input",{type:"checkbox",checked:i,onChange:h=>a(h.target.checked)})," ",p("remember-device")]}),l.jsx("button",{type:"submit",disabled:!c,children:"ok"})]})}const am=t=>_s(Pi(t)).length===0;function za(t,e){return Array.isArray(t)?t.flatMap(n=>{var c;const s={session:n.session,height:1,fontSize:n.fontSize};n.node&&(s.node=n.node),n.ownerId&&(s.ownerId=n.ownerId);const i=(c=e({columns:[{width:1,tiles:[s]}]}).columns[0])==null?void 0:c.tiles[0];if(!i)return[];const a={session:i.session,x:n.x,y:n.y,w:n.w,h:n.h,fontSize:n.fontSize};return i.node&&(a.node=i.node),i.ownerId&&(a.ownerId=i.ownerId),[a]}):[]}function r1(t,e){return t.length?t:Array.isArray(e.floating)&&e.floating.length?[]:void 0}function _4(t,e,n,s,i){const a=c=>za(c&&c.floating,u=>Ha(u,s,i));return LP(a(t),a(e),n)}function o1(t,e,n,s,i,a){const c=v=>Ha(v,i,a),u=v=>za(v&&v.floating,c),{grid:h,floating:f}=Od(n),g=AP(s(h),_4(t,e,f,i,a),{grid:t?c(t.layout):uo(),floating:u(t)},{grid:c(e.layout),floating:u(e)},{grid:h,floating:f});return Sg(g.grid,g.floating)}const lm=t=>Array.isArray(t)?t.join("/"):"",y4="nc-decks-cache-v1",EE=t=>`${y4}:${t}`;function w4(t){if(!t)return[];try{const e=localStorage.getItem(EE(t));if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)&&n.every(s=>s&&typeof s.id=="string"&&typeof s.name=="string")?n:[]}catch{return[]}}function b4(t,e){if(t)try{localStorage.setItem(EE(t),JSON.stringify(e))}catch{}}function S4(t){const e=new Set,n=[];for(const s of Array.isArray(t)?t:[])!s||!Ws.test(String(s.instanceId||""))||!Array.isArray(s.route)||!s.route.length||e.has(s.instanceId)||(e.add(s.instanceId),n.push({instanceId:s.instanceId,route:[...s.route],label:String(s.label||s.name||s.route.join(" › ")),status:s.status||"offline",stale:s.stale===!0,checking:s.checking===!0}));return n.sort((s,i)=>s.label.localeCompare(i.label))}function ec(t){return{instanceId:t.ownerId,route:t.ownerRoute||[],label:t.ownerLabel,status:t.available===!1?"offline":"up"}}function Do(t,e,n,s=!1,i=!0){const a=e.instanceId;return{...t,id:Vo(s?null:a,t.name),ownerId:a,ownerRoute:s?[]:[...e.route],ownerLabel:s?"Local":e.label,local:s,available:i,ownerTopology:Array.isArray(n)?n:[],layout:Ag(t.layout,a,n)}}function x4(t,e,n,s,i=[],a=[]){const[c,u]=w.useState([]),[h,f]=w.useState(!1),[g,v]=w.useState("idle"),[_,b]=w.useState(""),[x,L]=w.useState(!1),[C,R]=w.useState(""),S=w.useRef([]),I=w.useRef([]),E=w.useRef([]),F=w.useRef(new Map),$=w.useRef(""),X=w.useRef(e),V=w.useRef(n),G=w.useRef(!1),ne=w.useRef(!0),K=w.useRef(""),D=w.useMemo(()=>S4(i),[i]),P=D.map(ue=>`${ue.instanceId}:${lm(ue.route)}`).join("|"),O=D.map(ue=>`${ue.instanceId}:${ue.status??""}:${ue.checking?"checking":"settled"}`).join("|"),j=w.useRef(new Map(D.map(ue=>[ue.instanceId,ue.checking?"pending":ue.status])));I.current=D,E.current=a,V.current=n,X.current=e,S.current=c;const z=w.useCallback(ue=>Ha(ue.layout,$.current,I.current),[]),M=w.useCallback(()=>Xl(X.current,$.current),[]),A=w.useCallback(ue=>(Array.isArray(ue)?ue:[]).find(Re=>Re.id===M()),[M]),N=w.useCallback((ue,Re=!0,fe)=>{const Ee=fe===void 0?M():Xl(fe,$.current),Y=jp(ue,Ql(),E.current),pe=S.current.some(ke=>ke.id===Ee);S.current=Y,u(Y),b4($.current,Y.map(ke=>{if(!ke.refreshFailedAt)return ke;const We={...ke};return delete We.refreshFailedAt,We}));const Ae=Y.find(ke=>ke.id===Ee);if(Re&&Ae){ne.current=!0;const ke=Sg(z(Ae),za(Ae.floating,We=>Ha(We,$.current,I.current)));s(ke),Ae.local&&YI(Ae.name,Pi(ke))}else pe&&!Ae&&(ne.current=!0,s(uo()),b("deck non più condiviso dal nodo owner"));WI(Y.filter(ke=>ke.local).map(ke=>ke.name))},[s,z]),U=w.useCallback(async ue=>{let Re=await zu(t);const fe=Re.decks.find(Ee=>Ee.name==="main");if(Re.decks.length===1&&fe&&fe.revision===0&&am(fe.layout)){const Ee=UI(),Y=Pi(jg("main")||uo());if(!am(Y)){const pe=Ag(Y,ue,[]);Re.decks[0]=await Fu(t,"main",pe,0,[])}for(const pe of Ee.filter(Ae=>Ae!=="main"))try{let Ae=await Bw(t,pe,[]);const ke=Pi(jg(pe)||uo());am(ke)||(Ae=await Fu(t,pe,Ag(ke,ue,[]),Ae.revision,[]))}catch{}Re=await zu(t)}return Re},[t]),T=w.useCallback((ue,Re)=>{const fe=new Map(Re.map(pe=>[pe.id,pe])),Ee=new Set,Y=[];for(const pe of S.current){if(pe.local||pe.ownerId!==ue.instanceId){Y.push(pe);continue}const Ae=fe.get(pe.id);Ae&&(Y.push(Ae),Ee.add(pe.id))}for(const pe of Re)Ee.has(pe.id)||Y.push(pe);N(Y,!1)},[N]),H=w.useCallback(async ue=>{try{const[Re,fe]=await Promise.all([zu(t,ue.route),Iw(t,ue.route).catch(()=>({nodes:[]}))]);T(ue,Re.decks.map(Ee=>Do(Ee,ue,fe.nodes,!1,!0)))}catch(Re){if(Re&&(Re.status===403||Re.status===404)){T(ue,[]);return}const fe=S.current.filter(Ee=>!Ee.local&&Ee.ownerId===ue.instanceId).map(Ee=>({...Ee,stale:!0,refreshFailedAt:Date.now(),ownerRoute:[...ue.route],ownerLabel:ue.label}));T(ue,fe)}},[t,T]),se=w.useCallback(async({migrate:ue=!1}={})=>{const Re=await Pc(t,[]),fe=Ws.test(String(Re.instanceId||""))?Re.instanceId:"";if(!fe)throw new Error("instanceId locale non disponibile");$.current=fe,R(fe);const[Ee,Y]=await Promise.all([ue?U(fe):zu(t),Iw(t,[]).catch(()=>({nodes:[]}))]),pe={instanceId:fe,route:[],label:"Local"},Ae=Ee.decks.map(Ze=>Do(Ze,pe,Y.nodes,!0,!0)),ke=new Map(I.current.map(Ze=>[Ze.instanceId,Ze])),We=S.current.length?S.current:w4(fe),Ne=F.current,ge=Date.now(),st=We.filter(Ze=>!Ze.local).flatMap(Ze=>{const De=ke.get(Ze.ownerId);if(!De){const wt=Ne.get(Ze.ownerId);return wt===void 0?(Ne.set(Ze.ownerId,ge),[{...Ze,available:!1,stale:!0}]):ge-wt>wv?[]:[{...Ze,available:!1,stale:!0}]}Ne.delete(Ze.ownerId);const He=De.status==="up",qe=De.status==="pending"||De.checking===!0;return[{...Ze,available:qe?Ze.available:He?Ze.available!==!1:!1,stale:De.stale===!0,ownerRoute:[...De.route],ownerLabel:De.label}]});return setTimeout(()=>{for(const Ze of ke.values())Ze.status==="up"&&!Ze.checking&&H(Ze)},0),[...Ae,...st]},[t,U,H,P]);w.useEffect(()=>{if(!t)return;let ue=!1;const Re=K.current!==t;return K.current=t,se({migrate:Re}).then(fe=>{if(ue)return;const Ee=A(S.current),Y=A(fe),pe=Y&&(!Ee||Y.revision>Ee.revision||Ee.available!==Y.available||lm(Ee.ownerRoute)!==lm(Y.ownerRoute));N(fe,Re||!!pe&&!G.current),f(!0),Y&&b("")}).catch(fe=>{ue||(f(!0),b(String(fe.message||fe)))}),()=>{ue=!0}},[N,se,P,t,A]),w.useEffect(()=>{if(!S.current.length)return;const ue=jp(S.current,Ql(),a);(ue.length!==S.current.length||ue.some((fe,Ee)=>fe.id!==S.current[Ee].id))&&(S.current=ue,u(ue))},[a]),w.useEffect(()=>{const ue=j.current,Re=new Map;for(const fe of I.current){if(fe.checking||fe.status==="pending"){Re.set(fe.instanceId,ue.get(fe.instanceId)||"pending");continue}fe.status==="up"&&ue.get(fe.instanceId)!=="up"&&H(fe),Re.set(fe.instanceId,fe.status)}j.current=Re},[O,H]);const Q=w.useCallback(async(ue,Re=!0)=>{if(!h||!G.current)return!0;const fe=ue===void 0?M():Xl(ue,$.current),Ee=S.current.find(Y=>Y.id===fe);if(!Ee)return b(`deck inesistente: ${fe}`),!1;if(Ee.available===!1)return b(`nodo owner offline: ${Ee.ownerLabel}`),!1;v("saving");try{const{grid:Y,floating:pe}=Od(V.current),Ae=Jl(Pi(Y),Ee.ownerId,Ee.ownerTopology),ke=za(pe,ge=>Jl(ge,Ee.ownerId,Ee.ownerTopology)),We=await Fu(t,Ee.name,Ae,Ee.revision,Ee.ownerRoute,r1(ke,Ee)),Ne=Do(We,ec(Ee),Ee.ownerTopology,Ee.local,!0);return N(S.current.map(ge=>ge.id===fe?Ne:ge),!1),G.current=!1,v("saved"),b(""),L(!1),setTimeout(()=>v("idle"),1500),!0}catch(Y){if(Re&&Y.status===409&&Y.data&&Y.data.current){const pe=S.current.find(Ae=>Ae.id===fe);if(pe){const Ae=Do(Y.data.current,ec(pe),pe.ownerTopology,pe.local,!0),ke=o1(pe,Ae,V.current,We=>We,$.current,I.current);return jP(ke,V.current)||(V.current=ke,ne.current=!0,s(ke)),N(S.current.map(We=>We.id===fe?Ae:We),!1),G.current=!0,Q(fe,!1)}}return v("error"),b(String(Y.message||Y)),Y.status===409&&L(!0),!1}},[h,t,N,s]),Z=w.useCallback(async()=>{try{const ue=await se();G.current=!1,L(!1),N(ue,!0),b("")}catch(ue){b(String(ue.message||ue))}},[se,N]);w.useEffect(()=>{if(!h)return;const ue=ne.current&&!G.current;if(ne.current=!1,ue)return;G.current=!0,v("saving");const Re=setTimeout(Q,650);return()=>clearTimeout(Re)},[n,h,Q]),w.useEffect(()=>{if(!h)return;const ue=()=>{if(!G.current)return;const Re=S.current.find(Ae=>Ae.id===M());if(!Re||Re.available===!1)return;const{grid:fe,floating:Ee}=Od(V.current),Y=Jl(Pi(fe),Re.ownerId,Re.ownerTopology),pe=za(Ee,Ae=>Jl(Ae,Re.ownerId,Re.ownerTopology));v5(t,Re.name,Y,Re.revision,Re.ownerRoute,r1(pe,Re))};return window.addEventListener("pagehide",ue),window.addEventListener("beforeunload",ue),()=>{window.removeEventListener("pagehide",ue),window.removeEventListener("beforeunload",ue)}},[h,t,M]),w.useEffect(()=>{if(!h)return;const ue=setInterval(async()=>{try{const Re=await se(),fe=A(S.current),Ee=A(Re),Y=!!(Ee&&fe&&Ee.revision>fe.revision),pe=!!(Ee&&(!fe||Y||fe.available!==Ee.available));if(Y&&G.current&&Ee){const Ae=o1(fe,Ee,V.current,ke=>PP(z(Ee),ke),$.current,I.current);N(Re,!1),s(Ae);return}N(Re,pe&&!G.current)}catch{}},5e3);return()=>clearInterval(ue)},[h,se,N,z,s]);const me=w.useCallback(ue=>{s(Re=>{const fe=ue(Re);return fe!==Re&&(ne.current=!0),fe})},[]),de=async(ue,Re=null)=>{const fe=Re===Xi?S.current.find(pe=>pe.local):Re?S.current.find(pe=>pe.ownerId===Re):null;if(!fe||fe.available===!1)throw new Error("nodo owner non disponibile");const Ee=await Bw(t,ue,fe.ownerRoute),Y=Do(Ee,ec(fe),fe.ownerTopology,fe.local,!0);return N([...S.current,Y],!1),Y},ie=async(ue,Re)=>{const fe=S.current.find(ke=>ke.id===ue);if(!fe)throw new Error("deck inesistente");if(Xl(ue,$.current)===M()&&G.current&&!await Q(ue))throw new Error(`salvataggio di "${fe.name}" fallito: rinomina annullata`);const Ee=S.current.find(ke=>ke.id===ue);if(!Ee)throw new Error("deck inesistente");const Y=await _5(t,Ee.name,Re,Ee.revision,Ee.ownerRoute),pe=Do(Y,ec(Ee),Ee.ownerTopology,Ee.local,!0),Ae=Ee.local?Xi:Ee.ownerId;return Ap(KI(Ql(),Ae,ue,pe.id)),N(S.current.map(ke=>ke.id===ue?pe:ke),!1),pe},xe=async ue=>{const Re=S.current.find(Ee=>Ee.id===ue);if(!Re)throw new Error("deck inesistente");Xl(ue,$.current)===M()&&(G.current=!1),await y5(t,Re.name,Re.revision,Re.ownerRoute);const fe=Re.local?Xi:Re.ownerId;Ap(VI(Ql(),fe,ue)),N(S.current.filter(Ee=>Ee.id!==ue),!1)},Be=(ue,Re)=>{const fe=S.current.find(We=>We.id===ue),Ee=S.current.find(We=>We.id===Re);if(!fe||!Ee)return!1;const Y=fe.local?Xi:fe.ownerId,pe=Ee.local?Xi:Ee.ownerId;if(Y!==pe)return!1;const Ae=S.current.filter(We=>(We.local?Xi:We.ownerId)===Y).map(We=>We.id),ke=Ap(qI(Ql(),Y,ue,Re,Ae));return N(jp(S.current,ke),!1),!0},nt=async(ue,Re)=>{const fe=S.current.find(We=>We.id===ue);if(!fe)throw new Error("deck inesistente");if(fe.available===!1)throw new Error(`nodo owner offline: ${fe.ownerLabel}`);const Ee=vC(Re,$.current,I.current);if(!Ee)throw new Error("riferimento sessione non valido");const Y=z(fe),pe=Jl(qk(Y,Ee),fe.ownerId,fe.ownerTopology),Ae=await Fu(t,fe.name,pe,fe.revision,fe.ownerRoute),ke=Do(Ae,ec(fe),fe.ownerTopology,fe.local,!0);return N(S.current.map(We=>We.id===ue?ke:We),!1),ke},Le=w.useCallback(ue=>Sg(z(ue),za(ue.floating,Re=>Ha(Re,$.current,I.current))),[z]);return{decks:c,records:c,localNodeId:C,ready:h,saveState:g,error:_,setError:b,conflict:x,reloadCurrent:Z,saveNow:Q,select:async ue=>{if(G.current&&!await Q(M()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const Re=S.current.find(fe=>fe.id===ue);if(!Re)throw new Error(`deck inesistente: ${ue}`);return G.current=!1,ne.current=!0,Le(Re)},add:de,rename:ie,remove:xe,reorder:Be,addTileTo:nt,viewUpdate:me,vistaMaterializzata:Le,localMainId:Vo(null,"main"),parseDeckId:Hc}}const k4="/sw.js",Wg="nc-sw-update";let Tc=null,qd=!1,Kd=null,NE=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),RE=!1;function a_(){typeof window<"u"&&window.dispatchEvent(new Event(Wg))}function l_(){const t=Kd||(qd?{kind:"reload",version:"",browserVersion:""}:null);NE=Object.freeze({needed:!!t,kind:(t==null?void 0:t.kind)||null,version:(t==null?void 0:t.version)||"",browserVersion:(t==null?void 0:t.browserVersion)||""})}function a1(){return NE}function C4(t){return typeof window>"u"?()=>{}:(window.addEventListener(Wg,t),()=>window.removeEventListener(Wg,t))}function c_(t){qd!==t&&(qd=t,l_(),a_())}const ad="nc-auto-reload",Vd="nc-reload";function u_(){try{return typeof location<"u"?location:null}catch{return null}}function LE(){try{return typeof history<"u"?history:null}catch{return null}}function E4(t){const e=t===void 0?u_():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Vd)}catch{return null}}function N4(t,{location:e,history:n}={}){const s=e===void 0?u_():e,i=n===void 0?LE():n;if(!s||!i||typeof i.replaceState!="function")return!1;try{const a=new URLSearchParams(s.search||"");return a.set(Vd,t),i.replaceState(i.state??null,"",`${s.pathname||"/"}?${a.toString()}${s.hash||""}`),!0}catch{return!1}}function R4({location:t,history:e}={}){const n=t===void 0?u_():t,s=e===void 0?LE():e;if(!n||!s||typeof s.replaceState!="function")return!1;try{const i=new URLSearchParams(n.search||"");if(!i.has(Vd))return!1;i.delete(Vd);const a=i.toString();return s.replaceState(s.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const AE="nc-update-dismissed";function jE(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function L4(t,e,n){return[t,e,n].map(s=>s||"").join("|")}let qg=null;function A4(t,e,n){const s=n;return t&&e&&t!==e&&t!==s?{kind:"install",version:t,browserVersion:s}:e&&s&&e!==s?{kind:"stale",version:e,browserVersion:s}:null}function j4(t,e){if(!t)return!1;try{return t.getItem(AE)===e}catch{return!1}}function M4(t={}){const e=t.storage===void 0?jE():t.storage;if(qg&&e)try{e.setItem(AE,qg)}catch{}qd=!1,Kd=null,l_(),a_()}function T4(t,e,n,s={}){const i=s.storage===void 0?jE():s.storage,a=n,c=L4(t,e,a);qg=c;const u=A4(t,e,a);let h=j4(i,c)?null:u;if(h&&h.kind==="stale"){const g=`${e}|${a}`,v=E4(s.location)===g;let _=!1;if(!v&&i&&i.getItem(ad)!==g){try{i.setItem(ad,g)}catch{}_=i.getItem(ad)===g}_&&(N4(g,{location:s.location,history:s.history}),(s.applyImpl||ME)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Kd);if(Kd=h,l_(),f||a_(),!u){try{i&&i.removeItem(ad)}catch{}R4({location:s.location,history:s.history})}}const P4=1200;async function l1(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,P4))])}catch{}}async function ME(){try{Tc&&await Tc.update()}catch{}typeof location<"u"&&(await l1(location.pathname),await l1("/version.json"),location.reload())}function I4(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&c_(!0)})}function D4(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{RE&&location.reload()}),navigator.serviceWorker.register(k4).then(t=>{Tc=t,t.waiting&&c_(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&I4(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function O4(){RE=!0,c_(!1);const t=Tc&&Tc.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function B4({hash:t="",origin:e="",pathname:n="",search:s=""}={}){const i=String(t||"").replace(/^#/,""),a=`${n||""}${s||""}`;if(!i)return{token:"",pair:"",device:"",nextUrl:a};const c=new URLSearchParams(i),u=c.get("token")||"",h=c.get("device")||"",f=/^[a-f0-9]{32}$/.test(h)?h:"",g=c.get("pair")||"",v=g?`${e||""}${n||""}#pair=${g}`:"";return{token:u,pair:v,device:f,nextUrl:a}}const TE="nc_side_w",c1="nc_side_min",$4=240,u1=new Set(["absent","present","active","unknown"]);function z4(){const t=Number(localStorage.getItem(TE));return t>=180&&t<=480?t:$4}function F4(){const t={token:"",pair:""};try{const{token:e,pair:n,device:s,nextUrl:i}=B4({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e&&(t.token=e,b1(e,{remember:!0})),s&&y6(s),n){t.pair=n;try{sessionStorage.setItem("nc_pair",n)}catch{}}if(location.hash)try{history.replaceState(null,"",i)}catch{}}catch{}if(t.token||(t.token=_N()),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function d1(t){try{return Pi(jg(t))}catch{return uo()}}function h1(t){if(!t)return"";const e=Math.floor(Date.now()/1e3)-t;return e<0||e<60?"ora":e<3600?`${Math.floor(e/60)}m`:e<86400?`${Math.floor(e/3600)}h`:`${Math.floor(e/86400)}g`}function H4({showComposer:t,showFiles:e,showPanel:n,hasPanel:s,rendererKind:i,filesSetting:a=null,handlers:c={}}={}){const u=[];return typeof c.onToggleComposer=="function"&&u.push({id:"keyboard",kind:"switch",on:!!t,labelKey:"bar-menu-keyboard",descKey:"bar-menu-keyboard-desc",run:c.onToggleComposer}),typeof c.onToggleFiles=="function"&&u.push(a===null?{id:"files",kind:"switch",on:!!e,labelKey:"bar-menu-files",descKey:"bar-menu-files-desc",run:c.onToggleFiles}:{id:"files",kind:"switch",on:!!a,labelKey:"bar-menu-files",descKey:"bar-menu-files-setting-desc",run:c.onToggleFiles}),s&&typeof c.onTogglePanel=="function"&&u.push({id:"panel",kind:"switch",on:!!n,labelKey:"bar-menu-panel",descKey:"bar-menu-panel-desc",run:c.onTogglePanel}),typeof c.onSwitchRenderer=="function"&&u.push({id:"renderer",kind:"switch",on:i==="webgl",labelKey:"bar-menu-renderer",descKey:"bar-menu-renderer-desc",run:c.onSwitchRenderer}),u}function U4(t,e){if(!t||!t.tmux)return"";const n=ch(t,e||{});return n.stato==="lavora"?p("cell-working"):n.stato==="attesa"?p("cell-permission"):n.stato==="ferma"?p("cell-idle"):""}function f1({session:t,node:e,ownerId:n,cellName:s,token:i,readonly:a=!1,panelPort:c=0,onBack:u,onCellSwitcher:h,cellSwitcherOpen:f=!1,liveHost:g=null,side:v=null,onSideClose:_=null,onSideGone:b=null}){var le;zn();const[x]=Iv(),L=vk(),[C,R]=w.useState(!1),[S,I]=w.useState(null),[E,F]=w.useState(()=>x.showComposer),[$,X]=w.useState(Hg),[V,G]=w.useState(()=>xc()),ne=()=>{fk(OM(xc())),typeof window<"u"&&window.location.reload()},[K,D]=w.useState(s||t),[P,O]=w.useState(""),[j,z]=w.useState(""),[M,A]=w.useState(""),[N,U]=w.useState(!1),[T,H]=w.useState(!1),se=!!v&&T,[Q,Z]=w.useState(!1),[me,de]=w.useState({v:{main:1,side:1},h:{main:1,side:1}}),[ie,xe]=w.useState(()=>window.matchMedia("(orientation: landscape)").matches);w.useEffect(()=>{const re=window.matchMedia("(orientation: landscape)"),Te=Ge=>xe(Ge.matches);return re.addEventListener("change",Te),()=>re.removeEventListener("change",Te)},[]);const Be=ie?me.h:me.v,nt=w.useRef(Be);nt.current=Be;const[Le,Ie]=w.useState(null),[ue,Re]=w.useState(!0),fe=w.useRef(()=>{}),Ee=w.useRef(()=>!1),Y=w.useRef(()=>{}),pe=w.useRef(!1),Ae=w.useRef(!1),ke=w.useRef(null),We=w.useRef(null),[Ne,ge]=w.useState(null),st=w.useCallback(re=>ge({source:"main",ev:re}),[]),Ze=w.useCallback(re=>ge({source:"side",ev:re}),[]),De=!!v&&(Ne==null?void 0:Ne.source)==="side",He=re=>{H(re),St((re?pe:ut).current),pt((re?Ae:Lt).current)},qe=v?`${v.node||""}:${v.session}`:"";w.useEffect(()=>{H(!1),Z(!1),de({v:{main:1,side:1},h:{main:1,side:1}}),Ie(null),ge(re=>re&&re.source==="side"?null:re)},[qe]);const wt=w.useMemo(()=>{const re=new Map;return Te=>{if(re.has(Te))return re.get(Te);let Ge=Te*.6;try{const mt=document.createElement("span");mt.style.cssText="position:absolute;visibility:hidden;white-space:pre;font-family:courier-new,courier,monospace;",mt.style.fontSize=`${Te}px`,mt.textContent="0".repeat(20),document.body.appendChild(mt);const q=mt.getBoundingClientRect().width;document.body.removeChild(mt),Number.isFinite(q)&&q>0&&(Ge=q/20)}catch{}return re.set(Te,Ge),Ge}},[]),W=Math.max(.01,Be.main+Be.side),ee=((le=We.current)==null?void 0:le.clientWidth)||window.innerWidth,J=Math.max(0,ee-12)*(Math.min(Be.main,Be.side)/W)-26,be=!!v&&ie&&J/wt(Math.max(1,$))<40,ye=re=>X(Te=>kE(Te+re));w.useEffect(()=>{f||X(Hg())},[f]);const ot=w.useRef(()=>{}),oe=w.useRef(()=>!1),$e=w.useRef(()=>{}),ut=w.useRef(!1),[kt,St]=w.useState(!1),Lt=w.useRef(!1),[_t,pt]=w.useState(!1),Ut=w.useRef(null),[Gt,Ot]=w.useState(!1),ln=()=>{const re=se?pe:ut;re.current=!re.current,St(re.current)},In=()=>{const re=se?Ae:Lt;re.current=!re.current,pt(re.current)};w.useEffect(()=>{D(s||t),U(!1)},[s,t]);const qt=re=>{const Te=!re||re.sessionsError?null:re.sessionsJson;let Ge=null;Te&&Array.isArray(Te.sessions)&&(Ge=Te.sessions.find(je=>je.name===t));const mt=!re||re.fleetError?null:re.fs;let q=null;mt&&mt.available&&Array.isArray(mt.cells)&&(q=mt.cells.find(je=>je.tmuxSession===t)),D(Rc({session:t,cell:q||(s?{cell:s}:null)})),z(typeof(q==null?void 0:q.panelUrl)=="string"?q.panelUrl.trim():""),A(typeof(q==null?void 0:q.cell)=="string"?q.cell:"");let ae="";q?ae=[`${q.engine}${q.key?`·${q.key}`:""}`,U4(q,Ge)].filter(Boolean).join(" · "):Ge&&(ae=Ge.attached?`attached · ${h1(Ge.activity)}`:Ge.activity?h1(Ge.activity):""),O(ae),Re(!!(Ge||q))},wn=w.useRef(qt);wn.current=qt,w.useEffect(()=>{const re=e?e.split("/"):[],Te=Ge=>wn.current(Ge);return Te(nc(re)),kd(i,re,Te)},[e,i]),w.useEffect(()=>{wn.current(nc(e?e.split("/"):[]))},[t,s]);const en=w.useRef(b);en.current=b;const bn=re=>{var Xe;if(!v)return;const Te=!re||re.sessionsError?null:re.sessionsJson;let Ge=null,mt=!1;Te&&Array.isArray(Te.sessions)&&(mt=!0,Ge=Te.sessions.find(Pe=>Pe.name===v.session));const q=!re||re.fleetError?null:re.fs;let ae=null,je=!1;q&&q.available&&Array.isArray(q.cells)&&(je=!0,ae=q.cells.find(Pe=>Pe.tmuxSession===v.session)),Ie({title:Rc({session:v.session,cell:ae}),present:!!(Ge||ae)}),(mt||je)&&!Ge&&!ae&&((Xe=en.current)==null||Xe.call(en))},Ft=w.useRef(bn);Ft.current=bn,w.useEffect(()=>{if(!v){Ie(null);return}const re=v.node?v.node.split("/"):[],Te=Ge=>Ft.current(Ge);return Te(nc(re)),kd(i,re,Te)},[v,v==null?void 0:v.node,i]),w.useEffect(()=>{v&&Ft.current(nc(v.node?v.node.split("/"):[]))},[v==null?void 0:v.session]);const Xt=se?"side":"main",Jt=()=>ge(re=>re&&re.source===Xt?null:{source:Xt,ev:null}),[Qt,ls]=w.useState(tE),[cs]=w.useState(sE),[mn]=w.useState(iE),gn=H4({showComposer:E,showFiles:(Ne==null?void 0:Ne.source)===Xt,showPanel:N,hasPanel:!!j,rendererKind:V,filesSetting:L?null:Qt,handlers:{onToggleComposer:()=>F(re=>!re),onToggleFiles:L?Jt:()=>ls(re=>(nE(!re),!re)),onTogglePanel:()=>U(re=>!re),onSwitchRenderer:ne}}),qs=re=>{re.preventDefault();const Te=We.current;if(!Te)return;const Ge=(xt,gt)=>de(Je=>({...Je,[ie?"h":"v"]:{main:xt,side:gt}}));if(ie){const xt=re.clientX,gt=nt.current,Je=Te.clientWidth||1,Rt=Q?-1:1,rt=Wt=>{const Sn=gt.main+gt.side,Se=(Wt.clientX-xt)/Je*Sn*Rt,Me=od(gt.main+Se);Ge(Me,od(Sn-Me))},ze=()=>{window.removeEventListener("pointermove",rt),window.removeEventListener("pointerup",ze),window.removeEventListener("pointercancel",ze),window.removeEventListener("blur",ze)};window.addEventListener("pointermove",rt),window.addEventListener("pointerup",ze),window.addEventListener("pointercancel",ze),window.addEventListener("blur",ze);return}const mt=re.clientY,q=nt.current,ae=Te.clientHeight||1,je=Q?-1:1,Xe=xt=>{const gt=q.main+q.side,Je=(xt.clientY-mt)/ae*gt*je,Rt=od(q.main+Je);Ge(Rt,od(gt-Rt))},Pe=()=>{window.removeEventListener("pointermove",Xe),window.removeEventListener("pointerup",Pe),window.removeEventListener("pointercancel",Pe),window.removeEventListener("blur",Pe)};window.addEventListener("pointermove",Xe),window.addEventListener("pointerup",Pe),window.addEventListener("pointercancel",Pe),window.addEventListener("blur",Pe)},Vn=v&&l.jsxs("div",{className:`nc-dual-pane${se?"":" foco"}${be&&se?" nascosto":""}`,"data-testid":"pane-main",style:{flexGrow:Be.main,flexBasis:ie?0:void 0},onPointerDown:()=>He(!1),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${ue?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:K}),!se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),be&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",(Le==null?void 0:Le.title)||v.session),"aria-label":p("dual-go-to").replace("{cell}",(Le==null?void 0:Le.title)||v.session),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),He(!se)},children:[l.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("rect",{x:"3.5",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),l.jsx("span",{className:`nc-dual-dot${Le!=null&&Le.present?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:!0,focused:!se,sendRef:ot,composerRef:oe,actionRef:$e,ctrlRef:ut,setCtrlArmed:St,altRef:Lt,setAltArmed:pt,keyboardRef:Ut,onFiles:st,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:G})})]},"pane-main"),bt=v&&l.jsxs("div",{className:`nc-dual-pane${se?" foco":""}${be&&!se?" nascosto":""}`,"data-testid":"pane-side",style:{flexGrow:Be.side,flexBasis:ie?0:void 0},onPointerDown:()=>He(!0),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${Le!=null&&Le.present?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:Le?Le.title:v.session}),se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),l.jsxs("span",{className:"nc-dual-tasti",children:[l.jsx("button",{type:"button",title:p("dual-swap"),"aria-label":p("dual-swap"),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),Z(Te=>!Te)},children:ie?"⇆":"⇅"}),l.jsx("button",{type:"button",title:p("dual-close"),"aria-label":p("dual-close"),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),_==null||_()},children:"✕"})]}),be&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",K),"aria-label":p("dual-go-to").replace("{cell}",K),onPointerDown:re=>re.stopPropagation(),onClick:re=>{re.stopPropagation(),He(!se)},children:[l.jsxs("svg",{viewBox:"0 0 24 24",width:"14",height:"14","aria-hidden":"true",focusable:"false",children:[l.jsx("rect",{x:"3.5",y:"6",width:"17",height:"12",rx:"1.5",fill:"none",stroke:"currentColor",strokeWidth:"1.5"}),l.jsx("rect",{x:"12",y:"6",width:"8.5",height:"12",fill:"currentColor"})]}),l.jsx("span",{className:`nc-dual-dot${ue?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(pc,{session:v.session,node:v.node,token:i,readonly:a,takeSize:!1,focused:se,sendRef:fe,composerRef:Ee,actionRef:Y,ctrlRef:pe,setCtrlArmed:St,altRef:Ae,setAltArmed:pt,keyboardRef:ke,onFiles:Ze,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture})})]},"pane-side"),us=l.jsx("div",{className:"nc-dual-handle","data-testid":"dual-handle",role:"separator","aria-orientation":ie?"vertical":"horizontal",onPointerDown:qs},"dual-handle");return l.jsxs("div",{className:"nc-app",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:u,title:p("sessions"),children:[l.jsx(Pt,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:p("sessions")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:e?`${K} · ${e}`:K,children:K}),g&&g.cell&&g.cell===s?l.jsx("span",{className:`nc-live-host-dot ${Rv(g)} nc-live-host-dot-header`,"data-testid":"live-host-header-dot",title:p("live-host-indicator").replace("{cell}",g.cell).replace("{mode}",p(g.mode?`live-host-mode-${g.mode}`:"live-host-mode-unknown")).replace("{state}",p(`live-host-state-${g.state}`))}):null,P&&l.jsx("small",{className:"nc-bar-sub",children:P})]}),l.jsxs("span",{className:"nc-bar-right",children:[l.jsx("button",{onClick:()=>ye(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:l.jsx(Pt,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>ye(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Pt,{name:"zoomIn",size:18})}),Qt&&l.jsx("button",{type:"button",onClick:Jt,title:p("bar-menu-files"),"aria-label":p("bar-menu-files"),"aria-pressed":(Ne==null?void 0:Ne.source)===Xt?"true":"false",children:l.jsx(Pt,{name:"folder",size:18})}),cs&&l.jsx("button",{type:"button",onClick:()=>F(re=>!re),title:p("bar-menu-keyboard"),"aria-label":p("bar-menu-keyboard"),"aria-pressed":E?"true":"false",children:l.jsx(Pt,{name:"keyboard",size:18})}),j&&mn&&l.jsx("button",{type:"button",onClick:()=>U(re=>!re),title:p("bar-menu-panel"),"aria-label":p("bar-menu-panel"),"aria-pressed":N?"true":"false",children:l.jsx(Pt,{name:"monitor",size:18})}),l.jsx("button",{type:"button",className:`nc-bar-menu${C?" on":""}`,title:p("bar-menu-open"),"aria-label":p("bar-menu-open"),"aria-haspopup":"menu","aria-expanded":C?"true":"false",onClick:re=>{C||I(re.currentTarget.getBoundingClientRect()),R(Te=>!Te)},children:"⋯"})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[v?l.jsx("div",{className:`nc-dual${ie?" row":""}`,ref:We,children:be?Q?[bt,Vn]:[Vn,bt]:Q?[bt,us,Vn]:[Vn,us,bt]}):l.jsx(pc,{session:t,node:e,token:i,readonly:a,takeSize:!0,sendRef:ot,composerRef:oe,actionRef:$e,ctrlRef:ut,setCtrlArmed:St,altRef:Lt,setAltArmed:pt,keyboardRef:Ut,onFiles:st,fontSize:$,selectionMode:Gt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:G}),N&&j&&M&&l.jsx(pv,{cellId:M,panelUrl:j,route:e?e.split("/"):[],panelPort:c,token:i,title:K})]}),l.jsx(sI,{onKeyboard:()=>F(re=>!re),onCellSwitcher:h,cellSwitcherOpen:f,send:re=>(se?fe:ot).current(re),action:re=>(se?Y:$e).current(re),ctrlArmed:kt,onCtrl:ln,altArmed:_t,onAlt:In,onAltConsume:()=>{const re=se?Ae:Lt;re.current=!1,pt(!1)},onKeyboardKeep:()=>{var re,Te;return(Te=(re=se?ke:Ut).current)==null?void 0:Te.call(re)},selectionMode:Gt,onSelectionMode:Ot,keepKeyboardClosed:x.keybarKeepsKeyboardClosed,showEnter:x.showKeybarEnter,keybarLayout:x.keybarLayout}),E&&l.jsx(uC,{submitText:re=>(se?Ee:oe).current(re),token:i,session:se?v.session:t,node:se?v.node:e,ownerId:se?v.ownerId:n,readonly:a,keepKeyboardClosedOnVoice:x.voiceKeepsKeyboardClosed}),Ne&&(De?l.jsx(Eg,{session:v.session,node:v.node,token:i,filesEvent:Ne.ev,onClose:()=>ge(null)}):Ne.source==="main"?l.jsx(Eg,{session:t,node:e,token:i,filesEvent:Ne.ev,onClose:()=>ge(null)}):null),C&&(L?l.jsx(Dk,{anchorRect:S,items:gn,onClose:()=>R(!1)}):l.jsx(Nv,{cellName:K,items:gn,onClose:()=>R(!1)}))]})}function W4(){zn();const[t]=w.useState(F4),[e,n]=w.useState(t.token),[s,i]=w.useState(!1);L6(s?"":e);const a=w.useRef(t.token);a.current=e,w.useEffect(()=>{const Se=Me=>{Me&&Me.detail&&Me.detail.token===a.current&&i(!0)};return window.addEventListener(um,Se),()=>window.removeEventListener(um,Se)},[]);const c=w.useCallback((Se,Me)=>{const Ve=b1(Se,{remember:Me});if(!Ve.ok||Me&&Ve.where!=="local")try{window.dispatchEvent(new CustomEvent(dm))}catch{}i(!1),n(Se)},[]),[u,h]=w.useState(t.pair||""),f=w.useCallback(()=>{h("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),g=vk(),[v]=w.useState(()=>HI(typeof location<"u"?location.pathname:"/")),[_,b]=w.useState(v.id),x=_===Vo(null,ti),[L,C]=w.useState(null),R=Se=>{const Me=Cr(Se);C(Me?{...Me,...typeof(Se==null?void 0:Se.cellName)=="string"&&Se.cellName?{cellName:Se.cellName}:{}}:null)},[S,I]=w.useState(null);w.useEffect(()=>{const Se=f4();I(Se&&L&&Ug(Se.main,L)?Se.side:null)},[L]);const E=Se=>{const Me=L?{session:L.session,node:L.node}:null,Ve=h4(Me,S,Se);I(Ve),Ve?p4(Me,Ve):i1()},F=()=>{I(null),i1()},[$,X]=w.useState([]),[V,G]=w.useState(!0),[ne,K]=w.useState(null),[D,P]=w.useState([]),[O,j]=w.useState([]),[z,M]=w.useState(!1),[A,N]=w.useState(null),[U,T]=w.useState(()=>v.ownerId?uo():d1(v.name)),[H,se]=w.useState(null),[Q,Z]=w.useState(null),me=Se=>Z(Cr(Se)),[de,ie]=w.useState(null),xe=bv(e,g),Be=w.useMemo(()=>(xe||[]).filter(Se=>Se.instanceId).map(Se=>({instanceId:Se.instanceId,route:Se.route,label:Se.label,status:Se.status,stale:Se.stale===!0,checking:Se.checking===!0})),[xe]),{order:nt}=kv(),Le=x4(e,_,U,T,Be,nt),{notice:Ie,showActionNotice:ue}=eC(),Re=Le.decks;w.useEffect(()=>{const Se=new Map;for(const Me of xe||[]){const Ve=(Me.route||[Me.name]).join("/"),ct=new Set((Me.sessions||[]).map(At=>At.name));for(const At of Me.cells||[])!At.cell||!At.tmuxSession||At.cell===At.tmuxSession||ct.has(At.cell)||Se.set(`${Ve}:${At.cell}`,`${Ve}:${At.tmuxSession}`)}T(Me=>xP(Me,Se))},[xe]),w.useEffect(()=>{Le.localNodeId&&v.ownerId&&v.ownerId===Le.localNodeId&&T(Se=>Se.columns.some(Me=>Me.tiles.length)?Se:d1(v.name))},[Le.localNodeId]),w.useEffect(()=>{Le.localNodeId&&(OI(Be),Le.viewUpdate(Se=>{const Me=Ha(Se,Le.localNodeId,Be);return JSON.stringify(Me)===JSON.stringify(Se)?Se:Me}))},[Be,Le.localNodeId,Le.viewUpdate]);const[fe,Ee]=w.useState(null),[Y,pe]=w.useState(null),Ae=w.useRef(0),[ke,We]=w.useState(!1),[Ne,ge]=w.useState(z4),[st,Ze]=w.useState(!x),[De,He]=w.useState(()=>x?localStorage.getItem(c1)==="1":!0),[qe,wt]=w.useState(!1),[W,ee]=w.useState("nodes"),[J,be]=w.useState(!1),[ye,ot]=w.useState(""),[oe,$e]=w.useState(!1),ut=(Se="nodes",Me=!1,Ve="")=>{ee(Se),be(Me),ot(Ve),wt(!0)},[kt,St]=w.useState(!1),[Lt,_t]=w.useState(null),[pt,Ut]=w.useState({deviceDefault:"",localNodeId:"",localNameDefault:"",deviceNameNeeded:!1,deviceNameSuggestion:""}),[Gt,Ot]=w.useState(""),[ln,In]=w.useState(!1),[qt,wn]=w.useState(0),[en,bn]=w.useState({});w.useEffect(()=>{try{localStorage.setItem(TE,String(Ne))}catch{}},[Ne]),w.useEffect(()=>{try{localStorage.setItem(c1,De?"1":"")}catch{}},[De]),w.useEffect(()=>{if(!e)return;let Se=!1;return Promise.all([A1(e),qn("/api/config",e).then(Me=>Me.json())]).then(([Me,Ve])=>{if(!Se){if(Ut({deviceDefault:Me.deviceName||"",localNodeId:Me.nodeId||"",localNameDefault:Me.localName||"",deviceNameNeeded:Me.deviceNameNeeded===!0,deviceNameSuggestion:Me.deviceNameSuggestion||""}),Ot(Me.deviceName||""),In(!!Ve.readonlyDefault),FM(Ve.terminal),wn(Number.isInteger(Ve.panelPort)?Ve.panelPort:0),bn(Ve.nodePanelPorts&&typeof Ve.nodePanelPorts=="object"&&!Array.isArray(Ve.nodePanelPorts)?Ve.nodePanelPorts:{}),Me.firstRun===!0&&!Ve.readonlyDefault)St(!0);else if(u)St(!0);else if(Me.deviceNameNeeded===!0&&!Ve.readonlyDefault){let ct=!1;try{ct=sessionStorage.getItem("nc_device_ask_later")==="1"}catch{}ct||_t({suggestion:Me.deviceNameSuggestion||""})}}}).catch(()=>{}),()=>{Se=!0}},[e,u]);const[Ft,Xt]=w.useState({}),Jt=w.useCallback(({route:Se,hostCell:Me,revision:Ve})=>{const ct=Cs(Se);Xt(At=>({...At,[ct]:{hostCell:Me||null,hostLease:null,hostRevision:Number.isInteger(Ve)?Ve:(At[ct]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Qt=Se=>{const Me=Cs(Se),Ve=Se.length?((xe||[]).find(ct=>Cs(Array.isArray(ct.route)?ct.route:[])===Me)||{}).cells||[]:D;return Va({liveHost:Ft[Me]||null,cells:Ve,localNodeId:Le.localNodeId,ownerId:Se.length?Me:Le.localNodeId})},ls=w.useRef(xe);w.useEffect(()=>{ls.current=xe},[xe]);const cs=w.useRef(null);cs.current||(cs.current=Zd());const mn=3500;w.useEffect(()=>{let Se=!1;const Me=async()=>{const ct=cs.current,At=ct.begin();if(At!==null)try{const Ks=[[],...(ls.current||[]).filter(Zt=>Zt.kind!=="vl"&&Zt.status==="up").map(Zt=>Array.isArray(Zt.route)&&Zt.route.length?Zt.route:[Zt.name])],Vs=await Promise.all(Ks.map(async Zt=>{const tn=Cs(Zt);try{const rn=await Xd(e,Zt,{timeoutMs:mn});return[tn,{hostCell:rn&&typeof rn.hostCell=="string"?rn.hostCell:null,hostLease:rn&&rn.host&&typeof rn.host.lease=="string"?rn.host.lease:null,hostRevision:Number.isInteger(rn&&rn.revision)?rn.revision:0,threadStatus:rn&&u1.has(rn.threadStatus)?rn.threadStatus:"unknown"}]}catch{return[tn,{error:!0}]}}));if(Se||!ct.isCurrent(At))return;Xt(Zt=>{let tn=!1;const rn={...Zt};for(const bi of Vs){if(!bi)continue;const[mo,rr]=bi;rn[mo]=rr.error?{...Zt[mo]||{},threadStatus:"unknown"}:rr,tn=!0}return tn?rn:Zt})}finally{ct.end(At)}};Me();const Ve=setInterval(Me,4e3);return()=>{Se=!0,clearInterval(Ve),cs.current.reset()}},[e]),w.useEffect(()=>{if(!g)return;const Se=Me=>{if(!Me)return;const Ve=Me.sessionsError?null:Me.sessionsJson;Ve&&!Ve.error?(X(Ve.sessions||[]),G(!0),K(Me.at)):G(!1);const ct=yv({fs:Me.fs,error:Me.fleetError});ct.kind==="data"?(Ka("local",ct.cells),P(ct.cells),j(ct.capabilities),M(!1),N(null)):ct.kind==="stale"?(P(At=>At.length?At:_v("local")),M(!0),N(null)):(P([]),Ka("local",[]),j([]),M(!1),N(ct.reason||""))};return Se(nc([])),kd(e,[],Se)},[g,e]);const gn=w.useCallback(async(Se,Me=[])=>{const Ve=Cs(Me),ct=Ft[Ve]&&Ft[Ve].hostRevision||0;try{const At=await Jd(e,Se,ct,Me);return Xt(Ks=>({...Ks,[Ve]:{hostCell:At.hostCell||null,hostLease:At.host&&typeof At.host.lease=="string"?At.host.lease:null,hostRevision:Number.isInteger(At.revision)?At.revision:ct,threadStatus:u1.has(At.threadStatus)?At.threadStatus:"unknown"}})),{ok:!0}}catch(At){return{ok:!1,error:At}}},[e,Ft]),qs=w.useCallback(async(Se,Me=[])=>{const Ve=await gn(Se,Me);return Ve.ok||window.alert(p(pm(Ve.error))),Ve.ok},[gn]),Vn=w.useCallback(async(Se=[])=>{const Me=Cs(Se),Ve=Ft[Me]&&Ft[Me].hostRevision||0;try{const ct=await Qd(e,Ve,Se);return Xt(At=>({...At,[Me]:{hostCell:ct.hostCell||null,hostLease:null,hostRevision:Number.isInteger(ct.revision)?ct.revision:Ve,threadStatus:"unknown"}})),{ok:!0}}catch(ct){return{ok:!1,error:ct}}},[e,Ft]),bt=w.useCallback(async(Se=[])=>{const Me=await Vn(Se);return Me.ok||window.alert(p(pm(Me.error))),Me.ok},[Vn]);w.useEffect(()=>{let Se=!1;const Me=()=>{qn("/api/config",e).then(ct=>ct.json()).then(ct=>{Se||T4(ct.version,ct.uiVersion,"0.9.61")}).catch(()=>{})};Me();const Ve=setInterval(Me,6e4);return()=>{Se=!0,clearInterval(Ve)}},[e]);const us=new Set([...$.map(Se=>Se.name),...xe.flatMap(Se=>Se.sessions.map(Me=>Me.key))]),le=w.useMemo(()=>{const Se=new Map;for(const Me of $)Me&&typeof Me.name=="string"&&Number.isFinite(Me.created)&&Se.set(Me.name,Me.created);return Se},[$]),re=_s(U),Te=Se=>T(Me=>{const Ve=vC(Se,Le.localNodeId,Be)||Se,ct=qk(Me,Ve);return ct===Me&&_s(Me).length>=9&&Le.setError(p("grid-full")),ct}),Ge=async(Se,Me=[])=>{try{await Yg(e,Se,Me)}catch{return}const Ve=Me.length?`${Me.join("/")}:${Se}`:Se;T(ct=>Nc(ct,Ve)),poll()},mt=async(Se,Me,Ve=[])=>{try{await L1(e,Se,Me,Ve)}catch{return}poll()},q=async(Se,Me,Ve=[])=>{await E1(e,{cell:Se,enabled:!!Me},Ve),poll()},ae=async Se=>{if(!fe)return;const{cell:Me}=fe,Ve=Array.isArray(fe.route)?fe.route:[];if(!await jv({token:e,powerCell:fe,payload:Se,onNotice:ue})){const At=Se.action==="up"?!!Se.boot:Se.boot?!1:!!fe.boot;pe({id:++Ae.current,cell:Me,route:Ve,enabled:At})}poll()},je=w.useCallback(Se=>{pe(Me=>(Me==null?void 0:Me.id)===Se?null:Me)},[]),Xe=async Se=>{if(!(!(Se!=null&&Se.direct)||ke)){We(!0);try{await Jg(e,Se.name,Se.tunnelStatus==="up"?"down":"up")}finally{We(!1)}}},Pe=async(Se,Me)=>{const Ve=String(Me||"").trim();return!(Se!=null&&Se.direct)||!Ga(Ve)?!1:(await P1(e,Se.name,Ve),!0)},xt=Se=>{const Me=Re.find(Ve=>Ve.id===Se);if(!Me)return!1;try{const Ve=window.open(Lp(Me,e),"_blank");return Ve&&(Ve.opener=null),!!Ve}catch{return!1}},gt=async Se=>{if(!Se||Se===_)return;const Me=await Le.select(Se),Ve=Le.records.find(ct=>ct.id===Se);b(Se),T(Me),se(null),Z(null);try{history.replaceState(null,"",Lp(Ve||Se,null))}catch{}},Je=async(Se,Me)=>{const Ve=await Le.add(Se,Me);await gt(Ve.id)},Rt=async(Se,Me)=>{const Ve=await Le.rename(Se,Me);if(Se===_){b(Ve.id),T(Le.vistaMaterializzata(Ve)),se(null),Z(null);try{history.replaceState(null,"",Lp(Ve,null))}catch{}}},rt=async Se=>{await Le.remove(Se),Se===_&&await gt(Le.localMainId)},ze=async(Se,Me)=>{!Me||Me===_||(await Le.addTileTo(Me,Se),T(Ve=>Nc(Ve,Se)))};if(!e||s)return l.jsx(v4,{onSubmit:c,reason:s?"invalid":""});const Wt=l.jsxs(l.Fragment,{children:[qe&&l.jsx(H6,{token:e,initialTab:W,initialLocation:ye,startNewCell:J,onClose:()=>{wt(!1),be(!1),ot("")}}),kt&&l.jsx(U6,{token:e,initialPair:u,...pt,onPairDone:f,onDone:()=>St(!1)}),Lt&&l.jsx(W6,{token:e,suggestion:Lt.suggestion,onSaved:Se=>{Ot(Se),Ut(Me=>({...Me,deviceDefault:Se,deviceNameNeeded:!1})),_t(null)},onLater:()=>{try{sessionStorage.setItem("nc_device_ask_later","1")}catch{}_t(null)}}),l.jsx(n4,{token:e})]});if(!g)return de?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(s1,{peer:de,token:e,onBack:()=>ie(null)})}),Wt]}):L?l.jsxs(l.Fragment,{children:[l.jsx(f1,{session:L.session,node:L.node,ownerId:L.ownerId,cellName:L.cellName,token:e,readonly:ln,liveHost:Qt(L.node?L.node.split("/"):[]),panelPort:kc(L.node?L.node.split("/"):[],en,qt),side:S,onSideClose:F,onSideGone:F,onBack:()=>C(null),onCellSwitcher:()=>$e(!0),cellSwitcherOpen:oe}),oe&&l.jsx(l4,{token:e,current:L,localNodeLabel:Gt,panelPort:qt,nodePanelPorts:en,hostByRoute:Ft,onDesignateCell:gn,onClearHostCell:Vn,onLiveHostApplied:Jt,sideKey:S?qa(S.node?S.node.split("/"):[],S.session):null,onToggleSide:E,onPick:Se=>{R(Se),$e(!1)},onClose:()=>$e(!1)}),Wt]}):l.jsxs(l.Fragment,{children:[l.jsx(JP,{onPick:R,token:e,onSettings:ut,onOpenVlSession:ie,panelPort:qt,nodePanelPorts:en,hostByRoute:Ft,onDesignateCell:qs,onClearHostCell:bt}),Wt]});const Sn=x||!st;return l.jsxs("div",{className:"nc-workspace",children:[Sn&&l.jsx(SI,{sessions:$,cells:D,localVerified:V,activeSessions:re,nodeGroups:xe,token:e,onPeekOpen:()=>$e(!1),overlayOpen:oe,fleetCapabilities:O,fleetStale:z,fleetOff:A,bootSettlement:Y,onBootSettlementApplied:je,localNodeId:Le.localNodeId,hostByRoute:Ft,onDesignateCell:qs,onClearHostCell:bt,onPick:me,onAddTile:Te,onPower:Ee,onBoot:q,onBootError:Se=>Le.setError(String((Se==null?void 0:Se.message)||Se)),onNodePower:Xe,onNodeRename:Pe,onKill:Ge,onVisibility:mt,onNew:()=>ut("fleet",!0),onSettings:ut,onOpenVlSession:ie,width:Ne,collapsed:De,onResize:ge,onToggleCollapse:()=>He(Se=>!Se)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(dD,{decks:Re,currentDeck:_,onCreate:Je,onRename:Rt,onDelete:rt,onReorder:Le.reorder,onOpenWindow:xt,onNavigate:gt,saveState:Le.saveState,error:Le.error,conflict:Le.conflict,onReloadDeck:Le.reloadCurrent,sidebarVisible:Sn,onToggleSidebar:x?null:()=>Ze(Se=>!Se)}),Ie&&l.jsx("div",{className:"nc-notice nc-deck-notice",role:"status",title:Ie,children:Ie}),l.jsx(DI,{layout:U,onLayoutChange:T,onResizeEnd:()=>{Le.saveNow()},token:e,readonly:ln,sessionsAlive:us,localVerified:V,localIdentities:le,localVerifiedAt:ne,focusSession:H,onFocus:se,onOpenSingle:me,decks:Re,currentDeck:_,onSendToDeck:ze,cells:D,nodeGroups:xe,panelPort:qt,nodePanelPorts:en})]}),de&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(s1,{peer:de,token:e,onBack:()=>ie(null)})}),Q&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(f1,{session:Q.session,node:Q.node,ownerId:Q.ownerId,cellName:Rc({session:Q.session,node:Q.node,ownerId:Q.ownerId,cells:D,nodeGroups:xe}),token:e,readonly:ln,liveHost:Qt(Q.node?Q.node.split("/"):[]),panelPort:kc(Q.node?Q.node.split("/"):[],en,qt),onBack:()=>Z(null)})}),fe&&l.jsx(Pd,{cell:fe,token:e,route:Array.isArray(fe.route)?fe.route:[],onConfirm:ae,onClose:()=>Ee(null)}),Wt]})}function q4(t){return t.kind==="install"?p("update-installed-restart").replace("{v}",t.version):t.kind==="stale"?p("update-stale").replace("{ui}",t.version).replace("{browser}",t.browserVersion):p("update-available").replace("{v}",t.version).replace(" "," ").trim()}function K4(){zn();const t=w.useSyncExternalStore(C4,a1,a1);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:q4(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:ME,children:p("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:O4,children:p("reload")}),l.jsx("button",{className:"nc-update-close",onClick:M4,"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}function V4(){zn();const[t,e]=w.useState(!1);return w.useEffect(()=>{const n=()=>e(!0);return window.addEventListener(dm,n),()=>window.removeEventListener(dm,n)},[]),t?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:p("auth-not-remembered")}),l.jsx("button",{className:"nc-update-close",onClick:()=>e(!1),"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}D4();f6();gN.createRoot(document.getElementById("root")).render(l.jsxs(cN.StrictMode,{children:[l.jsx(W4,{}),l.jsx(K4,{}),l.jsx(V4,{})]}));
|