@mmmbuto/nexuscrew 0.9.65 → 0.9.66

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.
@@ -166,4 +166,4 @@ Minimum version required to store current data is: `+G+`.
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]))),XS(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 rm({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 T=[{route:[],label:p("local")}].concat((e||[]).map(H=>({route:Array.isArray(H.route)?H.route:[],label:H.label||(H.route||[]).join(" › ")}))),E=await Promise.all(T.map(async H=>{const F={...H,available:!1,readonly:!1,capabilities:[],provider:null,cells:[],unmanaged:[],err:""};try{const X=await Qa(t,H.route);F.available=!!X.available,F.capabilities=X.capabilities||[],F.provider=X.provider||null,F.cells=(X.cells||[]).map(V=>({...V,route:H.route}));try{F.readonly=!!(await Oc(t,H.route)).readonlyDefault}catch{}try{const V=await nv(t,H.route),Y=new Set(F.cells.map(ne=>ne.tmuxSession).filter(Boolean));F.unmanaged=(V.sessions||[]).filter(ne=>ne&&!Y.has(ne.name))}catch{}}catch(X){F.err=String(X&&X.message||X)}return F}));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 T1(t,C.cell,!0,R)}catch{}g()}},L=async(C,R)=>{if(window.confirm(p("terminate-confirm").replace("{name}",C.name))){try{await ev(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 X3({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($=>$.id))),[b,x]=w.useState(()=>new Set(e.map($=>$.id))),[L,C]=w.useState([]),[R,S]=w.useState([]),[T,E]=w.useState(""),H=new Set(e.map($=>$.id)),F=new Set(t.map($=>$.id)),X=($,A)=>$(j=>{const N=new Set(j);return N.has(A)?N.delete(A):N.add(A),N}),V=()=>{const $=U3(t,v,e,b,new Date,n);if($.ok===!1){E(p(`fleet-backup-${$.error}`));return}const A=t.filter(W=>v.has(W.id)).length,j=e.filter(W=>b.has(W.id)).length;if($.cells.length!==A){E(p("fleet-backup-invalid-cell"));return}if($.engines.length!==j){E(p("fleet-backup-invalid-engine"));return}if(!$.cells.length&&!$.engines.length){E(p("fleet-backup-select-one"));return}const N=new Blob([`${JSON.stringify($,null,2)}
167
167
  `],{type:"application/json"}),U=URL.createObjectURL(N),D=document.createElement("a");D.href=U,D.download=`nexuscrew-fleet-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild(D),D.click(),D.remove(),setTimeout(()=>URL.revokeObjectURL(U),0),E("")},Y=async $=>{if(E(""),C([]),S([]),!!$){if($.size>1024*1024){E(p("fleet-backup-too-large"));return}try{const A=W3(await $.text());if(!A.ok){E(p(`fleet-backup-${A.error}`));return}g(Array.isArray(A.models)?A.models:[]);const j=new Set(A.engines.map(N=>N.id));S(A.engines.map(N=>({engine:N,exists:H.has(N.id),selected:!H.has(N.id)}))),C(A.cells.map(N=>{const U=H.has(N.engine)||j.has(N.engine),D=F.has(N.id);return{cell:N,engine:U?N.engine:"",selected:U&&!D,exists:D}}))}catch(A){E(String(A.message||A))}}},ne=($,A)=>C(j=>j.map((N,U)=>U===$?{...N,...A}:N)),G=($,A)=>S(j=>j.map((N,U)=>U===$?{...N,...A}:N)),I=new Set([...H,...R.filter($=>$.selected).map($=>$.engine.id)]),P=L.filter($=>$.selected&&$.engine&&I.has($.engine)),B=R.filter($=>$.selected),M=[...new Map([...e.map($=>[$.id,$.label||$.id]),...R.filter($=>$.selected).map($=>[$.engine.id,$.engine.label||$.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($=>$.id))),x(new Set(e.map($=>$.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($=>{var A;return l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:b.has($.id),onChange:()=>X(x,$.id)}),l.jsxs("span",{children:[l.jsx("b",{children:$.label||$.id}),l.jsxs("small",{children:[$.id,(A=$.envKeys)!=null&&A.length?` · ${$.envKeys.length} ${p("fleet-backup-env-names")}`:""]})]})]},$.id)}),l.jsx("b",{children:p("fleet-cells")}),t.map($=>l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:v.has($.id),onChange:()=>X(_,$.id)}),l.jsxs("span",{children:[l.jsx("b",{children:$.id}),l.jsxs("small",{children:[$.engine," · ",p("fleet-system-prompt")," ",($.prompt||"").length," ",p("characters")]})]})]},$.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:$=>Y($.target.files&&$.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($=>$.map(A=>({...A,selected:!0}))),C($=>$.map(A=>({...A,selected:!!A.engine})))},children:p("select-all")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{S($=>$.map(A=>({...A,selected:!1}))),C($=>$.map(A=>({...A,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(($,A)=>{var j;return l.jsx("div",{className:"nc-backup-import-row",children:l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:$.selected,onChange:N=>G(A,{selected:N.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:$.engine.label||$.engine.id}),l.jsxs("small",{children:[$.engine.id," · ",$.exists?p("fleet-backup-overwrite"):p("fleet-backup-new"),(j=$.engine.envKeys)!=null&&j.length?` · ${p("fleet-backup-env-values-required")}`:""]})]})]})},$.engine.id)}),!!L.length&&l.jsx("b",{children:p("fleet-cells")}),L.map(($,A)=>l.jsxs("div",{className:"nc-backup-import-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:$.selected,disabled:!$.engine||!I.has($.engine),onChange:j=>ne(A,{selected:j.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:$.cell.id}),l.jsxs("small",{children:[$.exists?p("fleet-backup-overwrite"):p("fleet-backup-new")," · ",p("fleet-system-prompt")," ",$.cell.systemPrompt.length," ",p("characters")]})]})]}),l.jsxs("select",{value:$.engine,onChange:j=>ne(A,{engine:j.target.value,selected:!!j.target.value}),children:[l.jsx("option",{value:"",children:p("fleet-backup-engine-missing")}),M.map(([j,N])=>l.jsx("option",{value:j,children:N},j))]})]},$.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&&!B.length,onClick:()=>a({engineRows:R,cellRows:L,models:f}),children:p("fleet-backup-restore")})]})]}),T&&l.jsx("div",{className:"nc-err",children:T})]})}function J3({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=Tc(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(T=>T.client===S.target.value&&T.default)||i.find(T=>T.client===S.target.value)),children:h.map(([S,T])=>l.jsx("option",{value:S,children:T},S))}),l.jsx("select",{value:((R=Tc(i,a))==null?void 0:R.id)||"",disabled:t.mode!=="new",onChange:S=>C(i.find(T=>T.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,T,E)=>S&&E.indexOf(S)===T).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,T)=>l.jsxs("div",{className:"nc-fleet-env",children:[l.jsx("input",{value:S.key,disabled:S.configured,placeholder:"ENV_KEY",onChange:E=>{const H=u.slice();H[T]={...S,key:E.target.value},c({envRows:H})}}),l.jsx("input",{type:"password",value:S.value,placeholder:S.configured?"•••••• (unchanged)":"value",onChange:E=>{const H=u.slice();H[T]={...S,value:E.target.value},c({envRows:H})}}),l.jsx("button",{className:"nc-btn danger",onClick:()=>c({envRows:u.filter((E,H)=>H!==T)}),children:"×"})]},`${S.key}-${T}`)),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&&!Zv(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 Q3({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 Z3({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 B,M,$;const[_,b]=w.useState(null),[x,L]=w.useState(""),C=a.form,R=A=>c({...a,form:{...C,...A}}),S=u.find(A=>A.id===C.engine),T=((B=S==null?void 0:S.managed)==null?void 0:B.client)==="shell",E=((M=S==null?void 0:S.managed)==null?void 0:M.client)||"",H=(($=f.find(A=>A.client===E))==null?void 0:$.mcpManaged)!==!1,F=A=>{var U,D,W,se;const j=u.find(me=>me.id===A),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:A,model:((D=C.models)==null?void 0:D[A])||((W=j==null?void 0:j.managed)==null?void 0:W.model)||((se=j==null?void 0:j.model)==null?void 0:se.value)||"",commands:N,command:N[A]||""})},X=A=>{const j={...C.commands||{}};A?j[C.engine]=A:delete j[C.engine],R({command:A,commands:j})},V=T&&/[|&;<>()`$*?{}\[\]~]/.test(C.command||""),Y=[...new Set([...h||[],...Array.isArray(C.mcp)?C.mcp:[]])].sort(),ne=Array.isArray(C.mcp)?C.mcp.length?"some":"none":"all",G=A=>{var j;return R({mcp:A==="all"?void 0:A==="none"?[]:(j=C.mcp)!=null&&j.length?C.mcp:[...Y]})},I=A=>{const j=Array.isArray(C.mcp)?C.mcp:[];R({mcp:j.includes(A)?j.filter(N=>N!==A):[...j,A].sort()})},P=async A=>{try{const j=await tv(t,A,e);b(j),R({cwd:j.path}),L("")}catch(j){L(String(j.message||j))}};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:A=>{i(A.target.value),R({engine:""})},children:[l.jsx("option",{value:"",children:p("local")}),n.map(A=>l.jsxs("option",{value:A.route.join("/"),disabled:A.status&&A.status!=="up",children:[A.label,A.status&&A.status!=="up"?` · ${p("node-offline")}`:""]},A.route.join("/")))]})]}),l.jsx("input",{value:C.id,disabled:a.mode!=="new",placeholder:"id",onChange:A=>R({id:A.target.value})}),l.jsx("input",{value:C.label||"",maxLength:64,placeholder:p("fleet-cell-label"),onChange:A=>R({label:A.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:C.cwd,placeholder:p("cwd"),onChange:A=>R({cwd:A.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(A=>l.jsxs("button",{className:"nc-fs-item",onClick:()=>P(`${_.path.replace(/\/$/,"")}/${A}`),children:["📁 ",A]},A))]})]}),x&&l.jsx("div",{className:"nc-err",children:x}),l.jsx("select",{value:C.engine,onChange:A=>F(A.target.value),children:u.map(A=>l.jsx("option",{value:A.id,children:A.label},A.id))}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:!!C.boot,onChange:A=>R({boot:A.target.checked})})," ",p("fleet-boot")]}),l.jsx("input",{value:C.panelUrl||"",maxLength:512,placeholder:p("fleet-panel-url"),onChange:A=>R({panelUrl:A.target.value})}),l.jsx("small",{children:p("fleet-panel-url-help")}),C.panelUrl&&!Zv(C.panelUrl)&&l.jsx("small",{className:"nc-err",children:p("fleet-panel-url-invalid")}),T?l.jsxs(l.Fragment,{children:[l.jsx("input",{value:C.command||"",maxLength:4096,placeholder:p("fleet-shell-command-placeholder"),onChange:A=>X(A.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:A=>R({model:A.target.value})}),l.jsx("datalist",{id:"nc-cell-models",children:((S==null?void 0:S.availableModels)||[]).map(A=>l.jsx("option",{value:A},A))}),l.jsx("textarea",{value:C.prompt||"",placeholder:p("cell-prompt"),onChange:A=>R({prompt:A.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:A=>G(A.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")})]})]}),!H&&l.jsx("small",{className:"nc-note",children:p("cell-mcp-inert")}),ne==="some"&&l.jsx("div",{className:"nc-fleet-mcp-list",children:Y.map(A=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:(C.mcp||[]).includes(A),onChange:()=>I(A)})," ",A]},A))}),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 JS({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 Xd(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 tv(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 ad(t){const e=$o(t);return e===null?`~/${t}`:e?`~/${e}`:"~"}function e6(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 t6({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,T=async Y=>{const ne=$o(Y);if(ne===null){f({rel:"",dirs:[],loading:!1,err:p("fleet-cwd-repair-invalid")});return}f({rel:ne,dirs:[],loading:!0,err:""});try{const G=await tv(t,ne,e),I=e6(G);f({rel:I,dirs:Array.isArray(G.dirs)?G.dirs:[],loading:!1,err:""})}catch(G){f({rel:ne,dirs:[],loading:!1,err:String(G&&G.message||G)})}},E=Y=>{if(!h)return;const ne=h.rel?`${h.rel}/${Y}`:Y;T(ne)},H=()=>{h!=null&&h.rel&&T(h.rel.split("/").slice(0,-1).join("/"))},F=()=>{h&&(u(h.rel||""),f(null),b(""),C(null))},X=()=>{L!==null&&(u(L),C(null),b(""))},V=async()=>{if(S)return;const Y=$o(c);if(Y===null){b(p("fleet-cwd-repair-invalid"));return}const ne=ad(Y);let G=!0;try{G=window.confirm(p("fleet-cwd-repair-confirm").replace("{id}",String(R||"")).replace("{path}",ne))}catch{G=!1}if(G){v(!0),b(""),C(null);try{const I=await M1(t,R,{cwdRel:Y},e);i==null||i(I)}catch(I){const P=I&&I.data||{};if(P.code==="unportable-cwd"){b(p("fleet-cwd-repair-unportable"));const B=Array.isArray(P.cells)?P.cells.find($=>$&&$.id===R):null,M=B&&typeof B.suggestion=="string"?B.suggestion:null;M!==null&&$o(M)!==null&&C(M)}else b(String(I&&I.message||I))}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:Y=>u(Y.target.value)}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:S,onClick:()=>h?f(null):T(""),children:p(h?"close":"fleet-cwd-repair-browse")})]})]}),l.jsx("div",{className:"nc-cwd-preview",children:p("fleet-cwd-repair-preview").replace("{path}",ad(c))}),h&&l.jsxs("div",{className:"nc-fs",children:[l.jsx("div",{className:"nc-fs-path",children:ad(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:H,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(Y=>l.jsxs("button",{type:"button",className:"nc-fs-item",onClick:()=>E(Y),children:["📁 ",Y]},Y))]}),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:F,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}",ad(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 n6({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),[T,E]=w.useState(!1),[H,F]=w.useState(""),[X,V]=w.useState(""),[Y,ne]=w.useState(i),[G,I]=w.useState(!1),[P,B]=w.useState(null),[M,$]=w.useState(null),[A,j]=w.useState(null),[N,U]=w.useState(!1),[D,W]=w.useState([]),[se,me]=w.useState(null),[pe,Ie]=w.useState("manage"),J=w.useRef(!1),te=Y?Y.split("/"):[],ge=w.useCallback(async()=>{try{const re=await Qa(t,te);h(re);try{const le=await Oc(t,te);I(!!le.readonlyDefault)}catch{I(!1)}if(re.provider==="builtin"&&(re.capabilities||[]).includes("definitions")){const le=await Xd(t,te),O=new Map((re.engines||[]).map(de=>[de.id,de]));if(le.engines=(le.engines||[]).map(de=>{var ye;return{...de,availableModels:((ye=O.get(de.id))==null?void 0:ye.models)||[]}}),c(le),(re.capabilities||[]).includes("credentials"))try{W((await jN(t,te)).credentials||[])}catch{W([])}else W([])}F("")}catch(re){F(String(re.message||re))}finally{g(!0)}},[t,Y]);w.useEffect(()=>{document.visibilityState!=="hidden"&&ge()},[ge]),E3(ge,5e3);const Se=new Set((u.cells||[]).filter(re=>re.active).map(re=>re.cell)),Be=u.provider==="builtin"&&(u.capabilities||[]).includes("edit"),je=(u.capabilities||[]).includes("restore");w.useEffect(()=>{!s||J.current||!Be||!a.engines.length||(J.current=!0,S({mode:"new",form:GS(a.engines[0].id)}))},[s,Be,a.engines]);const ze=async re=>{E(!0),F(""),V("");try{await re(),await ge()}catch(le){F(String(le.message||le))}E(!1)},Q=async(re,le)=>{const O=await BN(t,re,le,te);return C(de=>({...de,[`${re}::${le}`]:O})),O},ve=re=>ze(async()=>{const le={id:String(re.id||"").trim(),engine:String(re.engine||"").trim()};for(const O of["contextWindow","maxTokens"]){const de=String(re[O]||"").trim();de&&(le[O]=Number(de))}re.reasoning===!0&&(le.reasoning=!0),await DN(t,le,te),x(null),await ge()}),Z=()=>ze(async()=>{var St;const re=v.mode==="new",le=v.form,O=a.managedCatalog||[],de=le.kind==="managed"?Tc(O,le):null,ye=typeof(de==null?void 0:de.credentialEnv)=="string"?de.credentialEnv:"",We=ye&&le.credentialValue||"",ie=G3(le,re,O);!re&&v.form.kind==="custom"&&!v.form.modelFlag&&(ie.model=null),!re&&v.form.kind==="custom"&&v.form.promptMode!=="flag"&&(ie.promptFlag=null);let Pe;if(re)Pe=await TN(t,ie,te);else{const _t=v.original,Pt=new Set(v.form.envRows.filter(Ot=>!Ot.remove).map(Ot=>Ot.key)),Kt=(_t.envKeys||[]).filter(Ot=>!Pt.has(Ot)),Mt=Object.fromEntries(v.form.envRows.filter(Ot=>!Ot.remove&&Ot.key&&(!Ot.configured||Ot.value!=="")).map(Ot=>[Ot.key,Ot.value]));Pe=await PN(t,_t.id,ie,v.form.kind==="custom"?{set:Mt,remove:Kt}:void 0,te)}let ft=null;if(ye&&We)try{ft=await Bw(t,ye,We,te),W(ft.credentials||[])}catch{throw await ge(),re&&_({mode:"edit",original:{...ie,id:le.id},form:{...le,credentialReveal:!1}}),new Error(p(re?"fleet-key-partial-create":"fleet-key-partial-edit"))}await ge(),_(null),V(p("fleet-saved"));const It=((St=((ft==null?void 0:ft.credentials)||[]).find(_t=>_t.envKey===ye))==null?void 0:St.activeCells)||[],bt=[...new Set([...(Pe==null?void 0:Pe.activeCells)||[],...It])];if(bt.length&&window.confirm(p("fleet-restart-confirm").replace("{cells}",bt.join(", "))))for(const _t of bt)await tc(t,_t,te)}),we=()=>ze(async()=>{var It,bt,St,_t,Pt,Kt;const re=R.mode==="new",le=R.form,O={...re?{id:le.id}:{},cwd:le.cwd,engine:le.engine,boot:!!le.boot},de={...le.commands||{}},ye=a.engines.find(Mt=>Mt.id===le.engine);((It=ye==null?void 0:ye.managed)==null?void 0:It.client)==="shell"&&typeof le.command=="string"&&le.command.length?de[le.engine]=le.command:((bt=ye==null?void 0:ye.managed)==null?void 0:bt.client)==="shell"&&delete de[le.engine],(Object.keys(de).length||!re)&&(O.commands=de);const We=(le.label||"").trim();re?We&&(O.label=We):O.label=We||null;const ie=(le.panelUrl||"").trim();re?ie&&(O.panelUrl=ie):O.panelUrl=ie||null,re?Array.isArray(le.mcp)&&(O.mcp=le.mcp):O.mcp=Array.isArray(le.mcp)?le.mcp:null,re?(((St=ye==null?void 0:ye.managed)==null?void 0:St.client)!=="shell"&&le.model&&(O.model=le.model),((_t=ye==null?void 0:ye.managed)==null?void 0:_t.client)!=="shell"&&le.prompt&&(O.prompt=le.prompt)):(O.model=((Pt=ye==null?void 0:ye.managed)==null?void 0:Pt.client)==="shell"?null:le.model||null,((Kt=ye==null?void 0:ye.managed)==null?void 0:Kt.client)!=="shell"&&(O.prompt=le.prompt||null));const Pe=re?await $N(t,O,te):await M1(t,R.original.id,O,te),ft=re?le.id:R.original.id;S(null),V(p("fleet-saved")),!re&&(Pe!=null&&Pe.active)&&window.confirm(p("fleet-restart-confirm").replace("{cells}",ft))&&await tc(t,ft,te)}),K=e||G,fe=u.capabilities||[],Re=te.length>0&&K,Ee=re=>D.find(le=>{var O;return(O=le.engines)==null?void 0:O.includes(re.id)})||null,Ke=()=>ze(async()=>{var O;const re=await Bw(t,se.envKey,se.value,te);W(re.credentials||[]),me(null),V(p("fleet-credential-saved"));const le=((O=(re.credentials||[]).find(de=>de.envKey===se.envKey))==null?void 0:O.activeCells)||[];if(le.length&&window.confirm(p("fleet-restart-confirm").replace("{cells}",le.join(", "))))for(const de of le)await tc(t,de,te)}),Je=re=>ze(async()=>{if(!window.confirm(p("fleet-credential-remove-confirm").replace("{key}",re.envKey)))return;const le=await MN(t,re.envKey,te);W(le.credentials||[]),V(p("fleet-credential-removed"))}),at=re=>B({...re,route:Array.isArray(re==null?void 0:re.route)?re.route:te}),Oe=async re=>{if(!P)return;const le={...P,cell:P.cell||P.id};try{await Dv({token:t,powerCell:le,payload:re,onNotice:V})}catch(O){throw F(String(O&&O.message||O)),O}},_e=(re,le)=>{F(""),$({mode:"new",route:Array.isArray(le)?le:te,form:{tmuxSession:re.name,id:"",engine:"",cwd:"",boot:!1},err:""})},$e=()=>ze(async()=>{const re=M.form;if(!re.engine){$({...M,err:p("import-engine-required")});return}await zN(t,{tmuxSession:re.tmuxSession,id:re.id||void 0,engine:re.engine,cwd:re.cwd||void 0,boot:!!re.boot},re.route||te),$(null),V(p("fleet-saved"))}),tt=({engineRows:re=[],cellRows:le=[],models:O=[]})=>ze(async()=>{const de=re.filter(_t=>_t.selected),ye=de.map(_t=>sE(_t.engine));if(ye.some(_t=>!_t))throw new Error(p("fleet-backup-invalid-engine"));const We=de.filter(_t=>_t.exists).map(_t=>_t.engine.id);if(We.length&&!window.confirm(p("fleet-backup-confirm-engine-overwrite").replace("{engines}",We.join(", "))))return;const ie=[...new Set([...a.engines.map(_t=>_t.id),...ye.map(_t=>_t.id)])],Pe=[];for(const _t of le.filter(Pt=>Pt.selected)){const Pt=q3(_t.cell,_t.engine,ie);if(!Pt)throw new Error(`${_t.cell.id}: ${p("fleet-backup-engine-missing")}`);Pe.push(Pt)}const ft=le.filter(_t=>_t.selected&&_t.exists).map(_t=>_t.cell.id);if(ft.length&&!window.confirm(p("fleet-backup-confirm-overwrite").replace("{cells}",ft.join(", "))))return;const It=ye.length?await HN(t,ye,We.length>0,te,O):{needsRestart:[]},bt=Pe.length?await FN(t,Pe,te):{needsRestart:[]},St=[...new Set([...It.needsRestart||[],...bt.needsRestart||[]])];U(!1),V(`${p("fleet-backup-restored").replace("{n}",String(Pe.length))}${ye.length?` · ${ye.length} ${p("fleet-engines").toLowerCase()}`:""}${St.length?` · ${p("fleet-backup-needs-restart").replace("{cells}",St.join(", "))}`:""}`)}),Fe=l.jsxs("label",{className:"nc-field",children:[p("location"),l.jsxs("select",{value:Y,onChange:re=>{ne(re.target.value),_(null),S(null),F(""),V(""),I(!1),g(!1),h({available:!1,capabilities:[]}),c({engines:[],cells:[],managedCatalog:[]}),W([]),me(null)},children:[l.jsx("option",{value:"",children:p("local")}),n.map(re=>l.jsxs("option",{value:re.route.join("/"),disabled:re.status&&re.status!=="up",children:[re.label,re.status&&re.status!=="up"?` · ${p("node-offline")}`:""]},re.route.join("/")))]})]}),it=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":pe==="manage",className:`nc-set-tabbtn${pe==="manage"?" on":""}`,onClick:()=>Ie("manage"),children:p("fleet-manage-location")}),l.jsx("button",{type:"button",role:"tab","aria-selected":pe==="overview",className:`nc-set-tabbtn${pe==="overview"?" on":""}`,onClick:()=>Ie("overview"),children:p("fleet-network-overview")})]});return f?Be?l.jsxs("div",{className:"nc-set-tab nc-fleet-editor",children:[it,pe==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(rm,{token:t,targets:n,readonly:e,onPower:at,onImport:_e})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-manage-help")}),Fe,l.jsxs("div",{className:"nc-set-row nc-fleet-backup-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>{F(""),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:K||T||!a.engines.length,onClick:()=>{var re;F(""),S({mode:"new",form:GS((re=a.engines[0])==null?void 0:re.id)})},children:["+ ",p("add")]})})]}),a.cells.map(re=>{const le=Se.has(re.id),O=re.needsRepair===!0;return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:re.id}),re.label?l.jsxs("small",{className:"nc-fleet-label",children:[" ",re.label]}):null,l.jsxs("small",{children:[re.engine," · ",O?l.jsx("span",{className:"nc-fleet-tag nc-fleet-tag-warn",children:p("fleet-cwd-needs-repair")}):re.cwd,le?` · ${p("service-active")}`:` · ${p("cell-off")}`]})]}),l.jsxs("span",{children:[le&&fe.includes("down")&&l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>ze(()=>A1(t,{cell:re.id},te)),children:p("stop")}),!le&&fe.includes("up")&&l.jsx("button",{className:"nc-btn primary",disabled:K||T,onClick:()=>at({cell:re.id,id:re.id,engine:re.engine,model:re.model,models:re.models,permissionPolicies:re.permissionPolicies,active:!1,boot:re.boot}),children:p("start")}),le&&fe.includes("restart")&&l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>ze(()=>tc(t,re.id,te)),children:p("restart")}),O?l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>{F(""),j(re)},children:p("fleet-cwd-repair")}):l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>{var de;F(""),S({mode:"edit",original:re,form:{...re,commands:{...re.commands||{}},command:((de=re.commands)==null?void 0:de[re.engine])||""}})},children:p("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:K||T,onClick:()=>ze(async()=>{window.confirm(p("fleet-remove-cell").replace("{id}",re.id))&&await T1(t,re.id,!0,te)}),children:"×"})]})]},re.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:K||T,onClick:()=>{F(""),_({mode:"new",form:K3()})},children:["+ ",p("add")]})]}),a.engines.map(re=>{var O,de;const le=Ee(re);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:re.label}),l.jsx("small",{children:re.managed?`${re.id} · ${re.managed.client} / ${re.managed.provider} · ${(O=re.managedInfo)!=null&&O.configured?p("fleet-ready"):((de=re.managedInfo)==null?void 0:de.reason)||p("fleet-not-ready")}`:`${re.id} · ${re.command}`}),le&&l.jsxs("small",{children:[le.envKey," · ",p(`fleet-credential-source-${le.source||"missing"}`)]})]}),l.jsxs("span",{children:[le&&l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>{F(""),me({envKey:le.envKey,value:""})},children:le.configured?p("fleet-credential-change"):p("fleet-credential-set")}),(le==null?void 0:le.source)==="local"&&l.jsx("button",{className:"nc-btn danger",disabled:K||T,onClick:()=>Je(le),children:p("fleet-credential-forget")}),l.jsx("button",{className:"nc-btn ghost",disabled:K||T,onClick:()=>{F(""),_({mode:"edit",original:re,form:Y3(re)})},children:p("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:K||T,onClick:()=>ze(async()=>{window.confirm(p("fleet-remove-engine").replace("{id}",re.id))&&await IN(t,re.id,te)}),children:"×"})]})]},re.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:K||T,onClick:()=>{F(""),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(re=>{const le=`${re.engine}::${re.id}`,O=L[le],de=(a.engines||[]).some(ye=>ye.managed&&ye.managed.model===re.id);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:re.id}),l.jsxs("small",{children:[re.engine,re.contextWindow?` · ${re.contextWindow}`:"",de?` · ${p("model-in-use")}`:""]}),O&&l.jsxs("small",{className:`nc-model-test ${O.outcome}`,children:[p(`model-test-${O.outcome}`),O.outcome==="ok"&&Number.isInteger(O.latencyMs)?` · ${O.latencyMs}ms`:""]})]}),l.jsxs("span",{children:[fe.includes("model-test")&&l.jsx("button",{className:"nc-btn ghost",disabled:T||Re,onClick:()=>ze(()=>Q(re.engine,re.id)),children:p("model-test")}),l.jsx("button",{className:"nc-btn danger",disabled:K||T,onClick:()=>ze(()=>ON(t,re.id,re.engine,te)),children:"×"})]})]},le)})]}),b&&l.jsx(Qr,{onClose:()=>x(null),label:p("fleet-models"),error:H,children:l.jsx(Q3,{state:b,setState:x,busy:T,onSave:ve,onTest:Q,profiles:a.managedCatalog||[],canTest:fe.includes("model-test")&&!Re})}),v&&l.jsx(Qr,{onClose:()=>_(null),label:p("fleet-new-engine"),error:H,children:l.jsx(J3,{state:v,setState:_,busy:T,onSave:Z,catalog:a.managedCatalog||[]})}),R&&l.jsx(Qr,{onClose:()=>S(null),label:p("fleet-new-cell"),error:H,children:l.jsx(Z3,{token:t,route:te,targets:n,location:Y,setLocation:ne,state:R,setState:S,engines:a.engines,mcpServers:a.mcpServers||[],managedCatalog:a.managedCatalog||[],busy:T,onSave:we})}),A&&l.jsx(Qr,{onClose:()=>j(null),label:p("fleet-cwd-repair-title").replace("{id}",A.id),error:"",children:l.jsx(t6,{token:t,route:te,cell:A,busy:T,onSaved:async()=>{j(null),V(p("fleet-cwd-repaired")),await ge()},onClose:()=>j(null)})}),X&&l.jsx("div",{className:"nc-set-note",children:X}),H&&l.jsx("div",{className:"nc-err",children:H}),N&&l.jsx(Qr,{onClose:()=>U(!1),label:p("fleet-backup"),error:H,children:l.jsx(X3,{cells:a.cells,engines:a.engines,models:a.models||[],busy:T,canRestore:je,onRestore:tt,onClose:()=>U(!1)})}),se&&l.jsx(Qr,{onClose:()=>me(null),label:p("fleet-credential-title"),error:H,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:re=>me({...se,value:re.target.value})})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>me(null),children:p("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:T||!se.value,onClick:Ke,children:p("save")})]})]})}),M&&l.jsx(Qr,{onClose:()=>$(null),label:p("import-as-cell"),error:H,children:l.jsx(JS,{token:t,route:M.route||te,state:M,setState:$,busy:T,onSave:$e})}),P&&l.jsx(Dd,{cell:P,token:t,route:Array.isArray(P.route)?P.route:te,onConfirm:async re=>{try{await Oe(re)}finally{ge()}},onClose:()=>B(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[it,pe==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(rm,{token:t,targets:n,readonly:e,onPower:at,onImport:_e})]}):l.jsxs(l.Fragment,{children:[Fe,l.jsxs("div",{className:"nc-set-info",children:[p(H?"fleet-editor-load-error":"fleet-editor-unavailable"),!H&&u.reason?` ${u.reason}`:""]})]}),H&&l.jsx("div",{className:"nc-err",children:H}),M&&l.jsx(Qr,{onClose:()=>$(null),label:p("import-as-cell"),error:H,children:l.jsx(JS,{token:t,route:M.route||te,state:M,setState:$,busy:T,onSave:$e})}),P&&l.jsx(Dd,{cell:P,token:t,route:Array.isArray(P.route)?P.route:te,onConfirm:async re=>{try{await Oe(re)}finally{ge()}},onClose:()=>B(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[it,pe==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:p("fleet-overview-help")}),l.jsx(rm,{token:t,targets:n,readonly:e,onPower:at,onImport:_e})]}):l.jsxs(l.Fragment,{children:[Fe,l.jsx("div",{className:"nc-set-info",children:p("fleet-editor-loading")})]})]})}const rE="nc_bar_files_button",oE="nc_bar_keyboard_button",aE="nc_bar_panel_button";function t_(t,e){try{const n=localStorage.getItem(t);if(n==="on")return!0;if(n==="off")return!1}catch{}return e}function n_(t,e){try{localStorage.setItem(t,e?"on":"off")}catch{}}function lE(){return t_(rE,!0)}function cE(t){n_(rE,t)}function uE(){return t_(oE,!0)}function s6(t){n_(oE,t)}function dE(){return t_(aE,!1)}function i6(t){n_(aE,t)}const s_="nc_notification_speech_v1",ld="nc-notification-speech",$g="nc-notification-speech-preview",r6=320,o6=2,a6=3e4,l6=1e4,c6=6e4,u6=64,QS=Object.freeze({enabled:!1}),d6=Object.freeze({it:"it-IT",en:"en-US",es:"es-ES"}),h6=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"])}),i_=new WeakSet;function r_(t){return{enabled:(t&&typeof t=="object"&&!Array.isArray(t)?t:{}).enabled===!0}}function hE(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function ZS(t=hE()){if(!t)return{...QS};try{return r_(JSON.parse(t.getItem(s_)||"null"))}catch{return{...QS}}}function f6(t,e=hE()){const n=r_(t);if(e)try{e.setItem(s_,JSON.stringify(n))}catch{}return n}function sl(){try{return typeof window<"u"?window:null}catch{return null}}function Pc(t=sl()){try{return!!(t&&t.speechSynthesis&&typeof t.speechSynthesis.speak=="function"&&typeof t.SpeechSynthesisUtterance=="function")}catch{return!1}}function fE(t=sl()){return!!(t&&(typeof t=="object"||typeof t=="function")&&i_.has(t))}function zg(t=sl()){t&&(typeof t=="object"||typeof t=="function")&&i_.delete(t)}function Wa(t){const e=String(t||"").trim().toLowerCase().split("-")[0];return d6[e]||""}function _h(t){return String(t||"").normalize("NFC").replace(/[\p{Cc}\p{Cf}]+/gu," ").replace(/\s+/g," ").trim()}function p6(t){const e=_h(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(h6).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 m6(t,e){const n=Wa(t&&t.lang);return n||Wa(p6(t&&t.body))||Wa(e)}function pE(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 mE(t,e){const n=Wa(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 e1(t){return _h(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 g6(t,e=r6){const n=e1(t&&t.title),s=e1(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 v6(t){try{return!!(t&&t.visibilityState==="visible"&&typeof t.hasFocus=="function"&&t.hasFocus())}catch{return!1}}function gE(t=sl()){if(!Pc(t))return!1;try{return t.speechSynthesis.cancel(),!0}catch{return!1}}function _6(t){try{t&&typeof t.dispatchEvent=="function"&&typeof t.Event=="function"&&t.dispatchEvent(new t.Event($g))}catch{}}function y6(t,e,n=sl(),s={}){var f;if(zg(n),!Pc(n))return Promise.resolve(!1);const i=_h(t);if(!i||(f=s.signal)!=null&&f.aborted)return Promise.resolve(!1);const a=Number.isFinite(s.timeoutMs)&&s.timeoutMs>0?s.timeoutMs:l6,c=s.setTimer||((g,v)=>setTimeout(g,v)),u=s.clearTimer||(g=>clearTimeout(g)),h=s.signal;return _6(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 i_.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=Wa(e);const R=mE(pE(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 w6(t={}){const e=t.scope||sl(),n=t.document||e&&e.document,s=Number.isInteger(t.maxPending)&&t.maxPending>=0?t.maxPending:o6,i=Number.isFinite(t.watchdogMs)&&t.watchdogMs>0?t.watchdogMs:a6,a=Number.isFinite(t.dedupWindowMs)&&t.dedupWindowMs>0?t.dedupWindowMs:c6,c=Number.isInteger(t.maxDedup)&&t.maxDedup>0?t.maxDedup:u6,u=t.now||Date.now,h=t.setTimer||((G,I)=>setTimeout(G,I)),f=t.clearTimer||(G=>clearTimeout(G)),g=t.isPrimed||(()=>fE(e)),v=e&&e.speechSynthesis;let _=null,b=null,x=[],L=[],C=()=>{};const R=new Map,S=()=>{L=pE(e)};if(S(),v&&typeof v.addEventListener=="function")v.addEventListener("voiceschanged",S),C=()=>v.removeEventListener("voiceschanged",S);else if(v&&"onvoiceschanged"in v){const G=v.onvoiceschanged,I=(...P)=>{S(),typeof G=="function"&&G.apply(v,P)};v.onvoiceschanged=I,C=()=>{v.onvoiceschanged===I&&(v.onvoiceschanged=G)}}const T=G=>{if(G&&typeof G.id=="string"&&G.id)return`id:${G.id}`;const I=Number(G&&G.ts),P=_h(G&&G.title);return Number.isFinite(I)&&P?`frame:${I}:${P}`:""},E=G=>{if(!G)return!0;const I=u();for(const[P,B]of R)I-B>=a&&R.delete(P);if(R.has(G))return!1;for(R.set(G,I);R.size>c;)R.delete(R.keys().next().value);return!0},H=()=>{b!==null&&f(b),b=null},F=()=>{H(),_&&(_.onend=null,_.onerror=null,_=null),gE(e)},X=G=>{if(!Pc(e))return x=[],"unsupported";let I;try{I=new e.SpeechSynthesisUtterance(G.text),I.lang=Wa(G.lang);const B=mE(L,I.lang);B&&(I.voice=B)}catch{return x=[],"error"}_=I;const P=()=>{if(_!==I)return;H(),_=null,I.onend=null,I.onerror=null;const B=x.shift();B&&X(B)};I.onend=P,I.onerror=P;try{return b=h(()=>{if(_!==I)return;_=null,I.onend=null,I.onerror=null;try{e.speechSynthesis.cancel()}catch{}H();const B=x.shift();B&&X(B)},i),e.speechSynthesis.speak(I),"speaking"}catch{return P(),"error"}},V=(G,I)=>{if(!Pc(e))return"unsupported";const P=g6(G);if(!P)return"empty";if(!E(T(G)))return"duplicate";if(!v6(n))return"inactive";if(!g())return"unprimed";const B={text:P,lang:I};return G&&G.urgency==="high"?(x=[],F(),X(B)):_?s===0?"dropped":(x.length>=s&&x.shift(),x.push(B),"queued"):X(B)},Y=()=>{x=[],F()};return{enqueue:V,stop:Y,dispose:()=>{Y(),C(),C=()=>{}}}}function vE(){const[t,e]=w.useState(ZS);w.useEffect(()=>{const s=i=>{if((i==null?void 0:i.type)==="storage"&&i.key!==s_&&i.key!==null)return;const a=(i==null?void 0:i.type)===ld?r_(i.detail):ZS();e(a)};return window.addEventListener(ld,s),window.addEventListener("storage",s),()=>{window.removeEventListener(ld,s),window.removeEventListener("storage",s)}},[]);const n=w.useCallback(s=>{const i=f6({enabled:s===!0});return e(i),window.dispatchEvent(new CustomEvent(ld,{detail:i})),i.enabled},[]);return[t.enabled,n]}const o_="nc_storage_persist_v1",b6=1440*60*1e3;function Fg(t=globalThis.localStorage){return Rr(o_,{storage:t,fallback:()=>null,parse:e=>e&&typeof e=="object"&&!Array.isArray(e)?e:void 0})}async function S6({manager:t=(s=>(s=globalThis.navigator)==null?void 0:s.storage)(),ls:e=globalThis.localStorage,now:n=Date.now}={}){const i=Fg(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<b6)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}),wi(o_,c,{storage:e}),c}const x6=t=>{try{return new Date(t).toLocaleString()}catch{return String(t)}},om=t=>Array.isArray(t)?t.join(", "):"";function k6(){$n();const[t,e]=w.useState(()=>gg()),[n,s]=w.useState(()=>Fg()),[i,a]=w.useState(!1);w.useEffect(()=>{const f=()=>{e(gg()),s(Fg())};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=()=>{GT(),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":o_,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})," · ",x6(f.t),f.position?` · ${f.position}`:"",f.key?` · ${f.key}`:"",f.note?` · ${f.note}`:"",f.before?l.jsxs("div",{children:[p("prefs-before"),": ",om(f.before)]}):null,f.after?l.jsxs("div",{children:[p("prefs-after"),": ",om(f.after)]}):null,f.visible?l.jsxs("div",{children:[p("prefs-visible"),": ",om(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 a_="nc_device_id_v1",_E="nc_prefs_sync_v1",C6="nexuscrew-roster-preferences",l_=/^[a-f0-9]{32}$/,E6=192,N6=256,t1=128,yE="nexuscrew-preferences",Uo=t=>t&&typeof t=="object"&&!Array.isArray(t),xd=(t,e)=>typeof t=="string"&&t.length>0&&t.length<=e&&!/[\u0000-\u001f\u007f]/.test(t),am=(t,e=N6)=>Array.isArray(t)&&t.length<=e&&t.every(n=>xd(n,E6));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(!am(t.pins))return null;e.pins=[...new Set(t.pins)]}if(t.nodeOrder!==void 0){if(!am(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>t1)return null;for(const[n,s]of Object.entries(t.orders)){if(!xd(n,96)||!am(s))return null;e.orders[n]=[...new Set(s)]}}if(t.views!==void 0){if(!Uo(t.views)||Object.keys(t.views).length>t1)return null;for(const[n,s]of Object.entries(t.views)){if(!xd(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(!xd(s.filter,16))return null;i.filter=s.filter}e.views[n]=i}}return e}const Hg=t=>!t||!(t.pins||[]).length&&!(t.nodeOrder||[]).length&&!Object.keys(t.orders||{}).length&&!Object.keys(t.views||{}).length;function c_(t){const e={pins:to(),orders:dc(t),views:bd(t),nodeOrder:Sg(t)};return il(e)||{pins:[],orders:{},views:{},nodeOrder:[]}}const Ug=t=>Array.isArray(t)?`[${t.map(Ug).join(",")}]`:Uo(t)?`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${Ug(t[e])}`).join(",")}}`:JSON.stringify(t),kd=t=>{const e=Ug(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)},lm=["nc_pins",Qo,Jo,uh];function u_(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 lm)try{a[u]=i.getItem(u)}catch{a[u]=null}const c={nc_pins:s.pins,[Qo]:s.orders,[Jo]:s.views,[uh]:s.nodeOrder};for(const u of lm){const h=wi(u,c[u],{storage:e});if(h){for(const f of lm)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(C6))}catch{}return null}const wE=t=>({status:"error",code:"storage-write-failed",note:String(t&&t.message||t).slice(0,120)}),d_=t=>{try{return t||globalThis.localStorage}catch{return null}},yh=t=>{var e;try{const n=(e=d_(t))==null?void 0:e.getItem(a_);return l_.test(n||"")?n:""}catch{return""}},bE=(t,e)=>{var n;try{(n=d_(e))==null||n.setItem(a_,t)}catch{}};function R6(t,e){l_.test(t||"")&&!yh(e)&&bE(t,e)}const L6=yh,A6=t=>Rr(_E,{storage:t,fallback:()=>null,parse:e=>Uo(e)?e:void 0}),Ud=(t,e,n)=>wi(_E,{revision:t,hash:kd(e),at:Date.now()},{storage:n});function SE(t){return async(e,n,{headers:s={},body:i}={})=>Wn(n,t,{method:e,headers:{...i?{"content-type":"application/json"}:{},...s},body:i,timeoutMs:8e3})}async function n1(t,e){let n=yh(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,!l_.test(n||""))throw new Error("device non valido");bE(n,e)}return n}async function Wg(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 Ud(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 j6({request:t,token:e,storage:n}={}){var i;const s=t||SE(e);try{let a=await n1(s,n),c=await s("GET","/api/prefs",{headers:{"x-nc-device":a}});if(c.status===404){try{(i=d_(n))==null||i.removeItem(a_)}catch{}a=await n1(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=c_(n),f=il(u.data);if(!f)return Hg(h)?{status:"synced",revision:u.revision}:Wg(s,a,h,u.revision,n);if(Hg(h)){const v=u_(f,{storage:n});return v?wE(v):(Ud(u.revision,f,n),{status:"restored",revision:u.revision})}if(kd(h)===kd(f))return Ud(u.revision,h,n),{status:"synced",revision:u.revision};const g=A6(n);return g&&g.revision===u.revision&&g.hash!==kd(h)?Wg(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 M6(t,e,{request:n,token:s,storage:i}={}){if(!e)return{status:"error",code:"no-conflict"};const a=n||SE(s);try{if(t==="server"){if(!e.server)return{status:"error",code:"no-server-copy"};const c=u_(e.server,{storage:i,note:"restore-from-server"});return c?wE(c):(Ud(e.revision,e.server,i),{status:"restored",revision:e.revision})}return await Wg(a,e.deviceId||yh(i),e.local,e.revision,i)}catch(c){return{status:"offline",note:String((c==null?void 0:c.message)||c).slice(0,120)}}}function T6(t){return JSON.stringify({kind:yE,version:1,exportedAt:new Date().toISOString(),data:c_(t)},null,2)}function P6(t,{storage:e}={}){let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:"not-json"}}if(!Uo(n)||n.kind!==yE||n.version!==1)return{ok:!1,reason:"wrong-kind"};const s=il(n.data);if(!s)return{ok:!1,reason:"bad-schema"};const i=u_(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 Wd={status:"idle"};let kr=Wd;const qg=new Set,qd=t=>{kr=t,qg.forEach(e=>e(t))};let Kg=null,Ic=0;const I6=t=>{const e=t||null;Kg!==e&&(Kg=e,Ic+=1,kr!==Wd&&qd(Wd))},xE=()=>{const[t,e]=w.useState(kr);return w.useEffect(()=>(qg.add(e),e(kr),()=>{qg.delete(e)}),[]),t};async function kE(t,e){var i;if(kr.status!=="conflict")return;const n=Ic;if(Kg!==(t||null)||((i=kr.conflict)==null?void 0:i.deviceId)!==L6()){qd(Wd);try{window.dispatchEvent(new Event("nexuscrew-roster-preferences"))}catch{}return}const s=await M6(e,kr.conflict,{token:t});n===Ic&&qd({...s,at:Date.now()})}const D6=1500,O6=3e3,s1="nexuscrew-roster-preferences";function B6(t){w.useEffect(()=>{if(I6(t),!t)return;let n=null,s=!0;const i=async()=>{if(!s||kr.status==="conflict")return;const u=Ic,h=await j6({token:t});s&&u===Ic&&qd({...h,at:Date.now()})},a=u=>{clearTimeout(n),n=setTimeout(i,u)},c=()=>{kr.status!=="conflict"&&a(O6)};return a(D6),window.addEventListener(s1,c),window.addEventListener("storage",c),()=>{s=!1,clearTimeout(n),window.removeEventListener(s1,c),window.removeEventListener("storage",c)}},[t]);const e=w.useCallback(n=>kE(t,n),[t]);return{state:xE(),resolve:e}}const $6=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 z6({token:t=""}){$n();const e=xE(),n=w.useRef(null),s=h=>kE(t,h),[i,a]=w.useState(null),c=()=>{try{const h=URL.createObjectURL(new Blob([T6()],{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 $6(f)}catch(_){a({ok:!1,text:String((_==null?void 0:_.message)||_)});return}if(!Hg(c_())&&!window.confirm(p("prefs-import-confirm")))return;const v=P6(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 F6({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(Tt,{name:"copy",size:14})," ",p(e?"copied":"copy")]})]})}function H6({value:t}){const[e,n]=w.useState("");return w.useEffect(()=>{let s=!0;return WD.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 U6({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(""),[T,E]=w.useState(""),[H,F]=w.useState(!1),[X,V]=w.useState(null),Y=Date.now(),ne=s&&s.deviceName||"",G=(e||[]).filter(N=>N&&N.direction==="outbound"&&N.name&&N.ssh),I=G.find(N=>N.name===R)||G[0]||null,P=I?Ag(I.tunnel,Y):null,B=I!=null&&I.shared?P!=null&&P.up?"share-local-active":"share-local-pending":P!=null&&P.up?"share-local-private":"share-local-private-down",M=[{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")}],$=X&&(e||[]).find(N=>`${N.kind||"direct"}:${N.nodeId||N.name}`===X)||null,A=async N=>{if(I){g(null),_(`${I.name}:share`);try{const U=await ZN(t,I.name,N);await a(),U&&U.reversePoolPending===!0&&g(`${I.name}: ${p("share-reverse-pool-pending")}`)}catch(U){const D=U!=null&&U.data&&U.data.shared===!1?U.data:null;if(D)try{await a()}catch{}const W=U!=null&&U.data&&typeof U.data.hint=="string"?U.data.hint:"",se=(D==null?void 0:D.revoked)===!0&&(D==null?void 0:D.localReconcilePending)===!0?p("share-off-local-reconcile-pending"):(D==null?void 0:D.revoked)===!1&&(D==null?void 0:D.reconcilePending)===!0?p("share-off-hub-reconcile-pending"):"",me=U!=null&&U.data&&U.data.reversePoolPending===!0?p("share-reverse-pool-pending"):"",pe=U!=null&&U.data&&typeof U.data.code=="string"?U.data.code:"",Ie=U!=null&&U.data&&typeof U.data.detail=="string"?U.data.detail.trim():"",J=Ie&&Ie!==String(U.message||"")?Ie:"";g(`${I.name}: ${String(U.message||U)}${pe?` [${pe}]`:""}${J?` — ${J}`:""}${W?` — ${W}`:""}${se?` — ${se}`:""}${me?` — ${me}`:""}`)}_(null)}},j=async()=>{g(null);const N=ho(L.name||T||ne||"NexusCrew"),U=KP({name:N,ssh:L.ssh,sshPort:L.sshPort});if(!U.ok){g(p(U.error));return}_("invite");try{x(await GN(t,{...T||ne?{label:T||ne}:{},name:N,ssh:U.value.ssh,...U.value.sshPort?{sshPort:U.value.sshPort}:{}}))}catch(D){g(String(D.message||D))}_(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")}),M.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 D=n3(U);if(!D)return null;const W=`${U.kind||"direct"}:${U.nodeId||U.name}`,se=D.routed?{up:D.reach.up,since:null}:Ag(U.tunnel,Y);return l.jsxs("button",{type:"button",className:`nc-set-node nc-node-row${D.routed?" routed":""}`,"aria-label":`${D.title} — ${p("node-detail-open")}`,onClick:()=>V(W),children:[l.jsx("span",{className:`nc-dot ${D.reach.up?"on":""}`}),l.jsxs("span",{className:"nc-node-row-text",children:[l.jsx("b",{children:D.title}),l.jsxs("small",{children:[D.routed?D.routeLabel:`${D.subtitle} · ${p(D.exposure.shortKey)}`,!D.routed&&D.exposure.shortKey==="visibility-selected"?` (${D.exposure.count})`:""]})]}),l.jsxs("span",{className:`nc-set-tunnel${D.reach.up?" up":""}`,children:[p(D.reach.key),se.since?` · ${se.since}`:""]}),l.jsx("span",{className:"nc-node-row-more",children:l.jsx(Tt,{name:"chevronDown",size:14})})]},W)})]},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(", ")]}),$&&l.jsx(C3,{node:$,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 JN(t,N.instanceId,U):await Fw(t,N.instanceId),c()}catch(D){g(String(D.message||D))}_(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 Fw(t,N.instanceId),c()}catch(U){g(String(U.message||U))}_(null)},children:p("reset-alias")})]})]},N.instanceId))]}),I&&l.jsxs("div",{className:"nc-set-form nc-local-share",children:[l.jsx("div",{className:"nc-sheet-label",children:p("share-local-heading")}),G.length>1&&l.jsxs("label",{className:"nc-field",children:[p("share-local-hub"),l.jsx("select",{value:I.name,disabled:i||!!v,onChange:N=>S(N.target.value),children:G.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:I.shared===!0,disabled:i||!!v,onChange:N=>A(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("share-local-through").replace("{device}",ne||p("local")).replace("{hub}",I.label||I.name)}),l.jsx("small",{children:p(I.shared?"share-node-on-desc":"share-node-off-desc")})]})]}),l.jsx("div",{className:`nc-set-test${I.shared&&(P!=null&&P.up)?" ok":P!=null&&P.up?"":" ko"}`,children:p(B)}),!(P!=null&&P.up)&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:i||!!v,onClick:()=>A(I.shared===!0),children:p("share-local-reconnect")})]}),l.jsx(HC,{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")})]}),G.length>0&&l.jsx("small",{className:"nc-set-hint nc-invite-hub-hint",children:p("invite-hub-only")}),H&&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:T,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(T||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:j,children:p("create-pairing-link")}),l.jsxs("button",{type:"button",className:"nc-btn ghost",disabled:!!v,onClick:()=>F(N=>!N),children:[H?"▾":"▸"," ",p("pair-advanced")]})]}),b&&l.jsxs(l.Fragment,{children:[l.jsx(H6,{value:b.pairingUrl}),l.jsx(F6,{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 W6({token:t,readonly:e}){const[n,s]=w.useState("idle"),[i,a]=w.useState(()=>VC()),[c,u]=w.useState(!1),[h,f]=w.useState(null);w.useEffect(()=>{let _=!1;return YC().then(b=>{_||s(b)}),()=>{_=!0}},[]);const g=async()=>{f(null),u(!0);try{n==="subscribed"?(await qS(t),s("idle")):(await GC(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 _=g3({enabled:i.enabled!==!1});if(a(_),f(null),_.enabled===!1&&n==="subscribed"){u(!0);try{await qS(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 q6(){const[t,e]=vE(),[n,s]=w.useState(""),[i,a]=w.useState(""),[c,u]=w.useState(!1),[h,f]=w.useState(fE),g=w.useRef(0),v=w.useRef(!1),_=w.useRef(null),b=Pc();w.useEffect(()=>()=>{var C;g.current+=1,v.current&&((C=_.current)==null||C.abort(),_.current=null,v.current=!1,zg())},[]);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 y6(p("notification-speech-preview"),Nd(),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),zg(),S||gE()}};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 K6({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[A,j]=await Promise.all([t5(t),r5(t)]);a(A),u(Array.isArray(j==null?void 0:j.groups)?j.groups:[]),R("")}catch(A){R(String(A.message||A))}},[t]);w.useEffect(()=>{S()},[S]);const T=async A=>{b(!0),L(null),R("");try{a(await n5(t,A))}catch(j){R(String(j.message||j))}b(!1)},E=async()=>{b(!0),L(null),R("");try{L({kind:"test",...await s5(t)})}catch(A){R(String(A.message||A))}b(!1)},H=async()=>{b(!0),L(null),R("");try{L({kind:"stop",...await i5(t)})}catch(A){R(String(A.message||A))}b(!1)},F=[],X=new Set,V=(A,j)=>{const N=typeof A=="string"?A.toLowerCase():"";!/^[a-f0-9]{32}$/.test(N)||X.has(N)||(X.add(N),F.push({id:N,label:j||N}))};V(s==null?void 0:s.nodeId,p("audio-group-local"));for(const A of n||[])V((A==null?void 0:A.nodeId)||(A==null?void 0:A.instanceId),(A==null?void 0:A.label)||(A==null?void 0:A.name)||(A==null?void 0:A.nodeId));for(const A of h.targets)V(A,`${A} (${p("audio-group-unavailable-target")})`);const Y=(A=null)=>{R(""),A?(v(A.name),f({name:A.name,mode:A.mode,targets:[...A.targets||[]]})):(v(null),f({name:"",mode:"primary-failover",targets:[]}))},ne=(A,j)=>f(N=>({...N,targets:j?[...new Set([...N.targets,A])]:N.targets.filter(U=>U!==A)})),G=async()=>{const A=h.name.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(A)||h.targets.length<1){R(p("audio-group-invalid"));return}b(!0),R("");try{const j=await o5(t,A,{targets:h.targets,mode:h.mode}),N=j==null?void 0:j.group;if(!N||!N.name)throw new Error(p("audio-group-save-failed"));u(U=>[...U.filter(D=>D.name!==N.name),N].sort((D,W)=>D.name.localeCompare(W.name))),Y(null)}catch(j){R(String(j.message||j))}b(!1)},I=async A=>{b(!0),R("");try{await a5(t,A),u(j=>j.filter(N=>N.name!==A)),g===A&&Y(null)}catch(j){R(String(j.message||j))}b(!1)},P=(i==null?void 0:i.installed)===!0,B=(i==null?void 0:i.liveness)==="ready",M=(i==null?void 0:i.consent)===!0&&P&&B,$=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:A=>{T(A.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(B?"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||_||!M,title:e?p("settings-readonly"):"",onClick:()=>{E()},children:p(_?"audio-testing":"audio-test")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>{H()},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(A=>{var j;return l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("span",{children:[l.jsx("b",{children:A.name})," ",l.jsxs("small",{children:["· ",A.mode==="fanout"?p("audio-group-fanout"):p("audio-group-primary")," · ",((j=A.targets)==null?void 0:j.length)||0]})]}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>Y(A),children:p("audio-group-edit")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>{I(A.name)},children:p("audio-group-delete")})]},A.name)}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>Y(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:A=>f(j=>({...j,name:A.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:A=>f(j=>({...j,mode:A.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")}),F.length===0?l.jsx("small",{className:"nc-set-hint",children:p("audio-group-no-targets")}):F.map(A=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:h.targets.includes(A.id),disabled:e||_,onChange:j=>ne(A.id,j.target.checked)}),l.jsxs("span",{children:[A.label,l.jsx("small",{children:A.id})]})]},A.id)),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:e||_,onClick:()=>{G()},children:p("audio-group-save")}),g&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>Y(null),children:p("audio-group-cancel")})]})]})]}):l.jsx("div",{className:"nc-set-info",children:p("audio-loading")}),$&&l.jsx("div",{className:"nc-set-note",role:"status",children:$}),C&&l.jsx("div",{className:"nc-err",children:C})]})}function V6(){const[t,e]=zv(),[n,s]=w.useState(lE),[i,a]=w.useState(uE),[c,u]=w.useState(dE);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:yC.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:wC.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),cE(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),s6(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),i6(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 Y6({token:t,roster:e=[],readonly:n}){const s=[{key:"local",route:[],label:p("diagnostics-local"),status:"up"},...e.filter(M=>Array.isArray(M.route)&&M.route.length).map(M=>({key:M.route.join("/"),route:M.route,label:M.label||M.name,status:M.status}))],[i,a]=w.useState("local"),c=s.find(M=>M.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),[T,E]=w.useState("all"),[H,F]=w.useState(""),X=w.useRef(0),V=w.useRef(null),Y=w.useCallback(async()=>{try{const M=await d5(t,c.route);if(h(M),_(""),!b){const $=await h5(t,{after:X.current,limit:200},c.route);Array.isArray($.records)&&$.records.length&&(X.current=$.cursor,g(A=>[...A,...$.records].slice(-500)))}}catch(M){_(M&&M.status===404?p("diagnostics-unsupported"):String(M.message||M))}},[t,c.key,b]);w.useEffect(()=>{X.current=0,g([]),h(null),_("")},[c.key]),w.useEffect(()=>{let M=null,$=!0;const A=()=>{!$||document.visibilityState==="hidden"||Y()},j=()=>{M&&clearInterval(M),M=document.visibilityState==="hidden"?null:setInterval(A,2e3),document.visibilityState!=="hidden"&&A()};return document.addEventListener("visibilitychange",j),j(),()=>{$=!1,M&&clearInterval(M),document.removeEventListener("visibilitychange",j)}},[Y]),w.useEffect(()=>{L&&V.current&&(V.current.scrollTop=V.current.scrollHeight)},[f,L]);const ne=f.filter(M=>(T==="all"||M.level===T)&&(!H||String(M.component||"").toLowerCase().includes(H.toLowerCase()))),G=ne.map(M=>`${M.ts} ${M.level.toUpperCase()} ${M.component} ${M.code} ${M.message}${Object.keys(M.meta||{}).length?` ${JSON.stringify(M.meta)}`:""}`).join(`
168
168
  `),I=async M=>{_("");try{const $=await M();h($),await Y()}catch($){_(String($.message||$))}},P=async()=>{try{await navigator.clipboard.writeText(G)}catch{_(p("copy-manual"))}},B=()=>{try{const M=new Blob([`${JSON.stringify(ne,null,2)}
169
- `],{type:"application/json"}),$=URL.createObjectURL(M),A=document.createElement("a");A.href=$,A.download="nexuscrew-diagnostics.json",A.click(),URL.revokeObjectURL($)}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:M=>a(M.target.value),children:s.map(M=>l.jsxs("option",{value:M.key,children:[M.label,M.status!=="up"?` · ${M.status}`:""]},M.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:M=>S(Number(M.target.value)),disabled:n,children:[300,900,1800,3600].map(M=>l.jsxs("option",{value:M,children:[M/60," min"]},M))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(u==null?void 0:u.verbose)===!0,onClick:()=>I(()=>Hw(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:()=>I(()=>Hw(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:T,onChange:M=>E(M.target.value),children:[l.jsx("option",{value:"all",children:p("diagnostics-all-levels")}),["debug","info","warn","error"].map(M=>l.jsx("option",{value:M,children:M},M))]}),l.jsx("input",{"aria-label":p("diagnostics-component"),placeholder:p("diagnostics-component"),value:H,onChange:M=>F(M.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:M=>x(M.target.checked)})," ",p("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:L,onChange:M=>C(M.target.checked)})," ",p("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:V,className:"nc-diag-log","aria-label":p("diagnostics-log"),children:G||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:B,children:p("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(p("diagnostics-clear-confirm"))&&I(async()=>{const M=await f5(t,c.route);return X.current=0,g([]),M})},children:p("diagnostics-clear")})]}),v&&l.jsx("div",{className:"nc-err",children:v})]})}function G6(){typeof window<"u"&&window.location&&typeof window.location.reload=="function"&&window.location.reload()}function X6({token:t,settings:e,readonly:n,refresh:s,roster:i,section:a,setSection:c}){const[u,h]=w.useState(Cc),[f,g]=w.useState(null),[v,_]=w.useState(null),[b,x]=w.useState(!1),[L,C]=w.useState(!1),[R,S]=w.useState(null),[T,E]=w.useState(!1),[H,F]=w.useState(!1),[X,V]=w.useState(null);w.useEffect(()=>{S(e&&e.update||null),E(!!(e&&e.autoUpdate===!0)),F(!!(e&&e.alternateScreen))},[e]);const Y=async()=>{g(null),_(null),C(!0);try{const N=await VN(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 l5(t);_(`${N.note||"ok"}${N.target?` (${N.target})`:""}`)}catch(N){g(String(N.message||N))}C(!1)},G=async N=>{g(null),_(null),C(!0);try{await Ed(t,{autoUpdate:N}),E(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},I=async N=>{g(null),_(null),C(!0);try{await Ed(t,{alternateScreen:N}),F(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},P=w.useCallback(async()=>{if(t)try{V(await KN(t))}catch{V(null)}},[t]);w.useEffect(()=>{P()},[P]);const B=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 B1(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)},M=async()=>{g(null),_(null),C(!0);try{S(await c5(t))}catch(N){g(String(N.message||N))}C(!1)},$=async()=>{g(null),_(null),C(!0);try{const N=await u5(t);S(N),_(p("npm-update-restarting"))}catch(N){g(String(N.message||N))}C(!1)},A=()=>{window.confirm(p("composer-clear-confirm"))&&(g(null),xI()?(window.dispatchEvent(new Event(Tg)),_(p("composer-clear-done"))):g(p("composer-clear-failed")))},j=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=wk(N.target.checked?fo:po);h(U),G6()}}),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",{}),j&&j.installed?p("service-installed"):p("service-missing"),j&&j.installed?` · ${j.active?p("service-active"):p("service-inactive")}`:"",j?` · boot ${j.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(W6,{token:t,readonly:n}),l.jsx(q6,{})]}),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:T,disabled:n||L||R&&!R.supported,onChange:N=>G(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:M,children:p("npm-update-check")}),R&&R.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||L||R.phase==="installing",onClick:$,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=>B(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:A,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:H,disabled:n||L,onChange:N=>I(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("alternate-screen")}),l.jsx("small",{children:p("alternate-screen-help")})]})]})]}),l.jsx(z6,{token:t}),l.jsx(k6,{}),l.jsx(Y6,{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:Y,children:p("confirm")})]})]}),v&&l.jsx("div",{className:"nc-set-note",children:v}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function J6({token:t,onClose:e,initialTab:n="nodes",initialLocation:s="",startNewCell:i=!1}){$n();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,T]=w.useState(null),[E,H]=w.useState([]),[F,X]=w.useState(!1),[V,Y]=w.useState(null),[ne,G]=w.useState(0),I=Nv(t,!0,ne),P=w.useCallback(()=>{const D=h.current;if(!D)return;const W=D.scrollWidth>D.clientWidth+1,se={start:W&&D.scrollLeft>1,end:W&&D.scrollLeft+D.clientWidth<D.scrollWidth-1};v(me=>me.start===se.start&&me.end===se.end?me:se)},[]);w.useEffect(()=>{const D=h.current;if(!D)return;const W=typeof ResizeObserver=="function"?new ResizeObserver(P):null;return W==null||W.observe(D),window.addEventListener("resize",P),P(),()=>{W==null||W.disconnect(),window.removeEventListener("resize",P)}},[P]),w.useEffect(()=>{var W,se;(se=(W=f.current)==null?void 0:W.scrollIntoView)==null||se.call(W,{behavior:"smooth",block:"nearest",inline:"nearest"});const D=window.requestAnimationFrame?window.requestAnimationFrame(P):setTimeout(P,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(D):clearTimeout(D)}},[c,P]);const B=w.useRef(th()),M=w.useRef(null),$=w.useRef([]),A=w.useRef(new Map),j=w.useRef({token:null,instanceId:null}),N=w.useCallback((D,W)=>{if(!D.isCurrent(W))return;const se=$.current,me=[],pe=new Set;for(const Ie of A.current.values())for(const J of Ie){const te=Array.isArray(J.route)&&J.route.length?J.route.join("/"):"local",ge=`${J.ownerInstanceId}:${te}:${J.nodeId||J.name||J.label||""}`;pe.has(ge)||(pe.add(ge),me.push(J))}R([...se,...me])},[]),U=w.useCallback(async()=>{const D=B.current,W=D.begin();if(W===null)return;const se=new AbortController;M.current=se;const me={timeoutMs:N1,signal:se.signal};try{const pe=I1(t,me).then(te=>{D.isCurrent(W)&&(L(te),Y(null))}).catch(te=>{D.isCurrent(W)&&Y(String((te==null?void 0:te.message)||te))}),Ie=WN(t,me).then(te=>{if(!D.isCurrent(W))return;const ge=te.peers||[];$.current=ge,T(Number.isInteger(te.accessRevision)?te.accessRevision:null),N(D,W)}).catch(te=>{D.isCurrent(W)&&Y(String((te==null?void 0:te.message)||te))}),J=(async()=>{const[te,ge]=await Promise.all([Oc(t,[],me).then(Q=>Q).catch(()=>null),O1(t,me).then(Q=>Q).catch(()=>null)]);if(!D.isCurrent(W))return;const Se=te&&typeof te.instanceId=="string"?te.instanceId:"";if(!Se)return;j.current.instanceId!==Se&&(A.current.clear(),j.current.instanceId=Se);const Be=[{instanceId:Se||null,route:[],label:null},...Tk(ge,Se)],je=Q=>`${Q.instanceId}:${Q.route.join("/")}`;if(ge){const Q=new Set(Be.map(je));for(const ve of A.current.keys())Q.has(ve)||A.current.delete(ve)}if(!ge)for(const[Q,ve]of A.current)ve.some(Z=>Z.route.length)&&A.current.set(Q,ve.map(Z=>({...Z,stale:!0,online:!1,canManage:!1,capabilities:[]})));const ze=new Map;H([]),N(D,W),await Promise.allSettled(Be.map(async Q=>{const ve=je(Q);try{const Z=await D1(t,Q.route,{signal:se.signal});if(!D.isCurrent(W))return;const we=(Z.nodes||[]).map(K=>Mk(K,Q)).filter(Boolean);A.current.set(ve,we),ze.delete(ve)}catch(Z){if(!D.isCurrent(W))return;if((Z==null?void 0:Z.status)===403||(Z==null?void 0:Z.status)===404)A.current.delete(ve);else{const K=A.current.get(ve);K&&A.current.set(ve,K.map(fe=>({...fe,stale:!0,online:!1,canManage:!1,capabilities:[]})))}Q.route.length>0&&ze.set(ve,{instanceId:Q.instanceId,label:Q.label,route:Q.route,failure:/timeout/i.test(String((Z==null?void 0:Z.message)||Z))?"timeout":"unreachable"})}D.isCurrent(W)&&(H([...ze.values()]),N(D,W))}))})();await Promise.allSettled([pe,Ie,J])}finally{M.current===se&&(M.current=null),D.end(W)}},[t,N]);return w.useEffect(()=>{j.current.token!==t&&(j.current={token:t,instanceId:null},$.current=[],A.current.clear(),R([]),H([]),T(null)),U();const D=setInterval(U,5e3);return()=>{clearInterval(D),B.current.reset(),M.current&&M.current.abort()}},[U]),w.useEffect(()=>{let D=!1;return Wn("/api/config",t).then(W=>W.json()).then(W=>{D||X(!!W.readonlyDefault)}).catch(()=>{}),()=>{D=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:D=>D.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(Tt,{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(Tt,{name:"x",size:18})})]}),F&&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(D=>l.jsx("button",{ref:c===D?f:null,type:"button",className:`nc-set-tabbtn${c===D?" on":""}`,onClick:()=>u(D),children:p(`tab-${D}`)},D))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(U6,{token:t,nodes:C,roster:I,settings:x,readonly:F,vlUnavailable:E,accessRevision:S,refresh:U,refreshAliases:()=>G(D=>D+1)}),c==="fleet"&&l.jsx(n6,{token:t,readonly:F,startNewCell:i,initialLocation:s,targets:I.map(D=>({route:D.route,label:D.label||D.name,status:D.status}))}),c==="audio"&&l.jsx(K6,{token:t,readonly:F,nodes:C,settings:x}),c==="input"&&l.jsx(V6,{}),c==="system"&&l.jsx(X6,{token:t,settings:x,readonly:F,refresh:U,roster:I,section:_,setSection:b})]})]})})}function Q6({token:t,initialPair:e,deviceDefault:n="",localNodeId:s="",localNameDefault:i="",deviceNameNeeded:a=!1,deviceNameSuggestion:c="",onPairDone:u,onDone:h}){$n();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),T=async()=>{_(!0),x(null);try{const E={wizardDone:!0};a&&L.trim()&&(E.deviceName=L.trim()),await Ed(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:T,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(HC,{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(Gv,{line:R.line,note:R.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:T,children:p("finish")})})]}),b&&l.jsx("div",{className:"nc-err",children:b})]})})}function Z6({token:t,suggestion:e="",onSaved:n,onLater:s}){$n();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 Ed(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 e4=50;function t4(t){if(Number.isFinite(t))return t;const e=typeof t=="string"?Date.parse(t):NaN;return Number.isFinite(e)?e:0}function CE(t,e){return`${String(t)}|${String(e)}`}function i1(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:CE(e,t.eventId),ownerId:String(e),eventId:String(t.eventId),title:s,body:i,urgency:n.urgency==="high"?"high":"normal",ts:t4(t.emittedAt??(t.frame&&t.frame.ts)??t.ts),arrivalSeq:0}}function r1(t){return[...t].sort((e,n)=>n.ts-e.ts).slice(0,e4)}function o1(t,e,n,s=null){const i=new Set((e||[]).map(c=>c&&c.key)),a=new Map;for(const c of t||[])s&&s.owners.has(c.ownerId)&&!i.has(c.key)&&!s.arrivedAfter(c)||(!n||n.has(c.ownerId))&&a.set(c.key,c);for(const c of e||[])c&&a.set(c.key,c);return[...a.values()]}function n4(t,e,n,s){if(typeof EventSource>"u"||!t)return()=>{};const i=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return i.onopen=()=>{typeof n=="function"&&n()},i.onerror=()=>{typeof s=="function"&&s()},i.onmessage=a=>{try{const c=JSON.parse(a.data);c&&typeof c=="object"&&typeof c.type=="string"&&e(c)}catch{}},()=>{try{i.close()}catch{}}}const s4=6e3,i4=12e3,Qn=(t,e,n)=>`${e||""}:${n||t}`,r4=(t,e)=>{const n=t&&t[e];return n?n.stale===!0||n.error===!0?"degraded":"live":"missing"},EE=600*1e3,a1=30*1e3,o4=300*1e3,Vg=new Map,a4=900*1e3,za=new Map;function cm(t){za.set(t,Date.now()),za.size>4096&&za.delete(za.keys().next().value)}function um(t){const e=za.get(t);return e===void 0?!1:Date.now()-e>a4?(za.delete(t),!1):!0}const l4={pending:"ask-dismiss-local-pending",blocked:"ask-dismiss-local-blocked"},c4=t=>l4[t]||t,Yo=t=>Object.hasOwn(t,"ownerAskTs")?t.ownerAskTs:t.ownerAskId||t.originNode?null:t.ts;function NE(t,e){Vg.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 RE(t){const e=Qn(t.id,t.ownerId,t.ownerAskId),n=Vg.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>EE?(Vg.delete(e),!1):!0}function Cd(t,e){const n=new Map(t.map(s=>[Qn(s.id,s.ownerId,s.ownerAskId),s]));for(const s of e||[]){if(!s||!s.id||RE(s))continue;const i=Qn(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 u4(t,e){const n=Cd([],t.filter(a=>a.imported)),s=new Set(n.map(a=>Qn(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!s.has(Qn(a.id,a.ownerId,a.ownerAskId))&&!RE(a)),...n]}function d4({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(Tt,{name:"x",size:14})})]})}function h4({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),[T,E]=w.useState(c),[H,F]=w.useState(!1),[X,V]=w.useState(!1),Y=w.useRef(null);w.useEffect(()=>{c&&E(c)},[c]);const ne=R||b||!!T||X||!!t.ownerId&&f==="loading",G=!!t.ownerId&&!h,I=async M=>{const $=String(M||"").trim();if(!(!$||b||R||T||X)){C(null),x(!0);try{if(t.ownerId){const A=t.ownerAskId||t.id,j=await v5(e,{ownerId:t.ownerId,askId:A,text:$,requestId:Y.current||(Y.current=crypto.randomUUID())});if(j&&j.uncertain){const N=j.reason==="delivery-unknown-block"&&!j.originalRequestId;E(N?null:j.originalRequestId||j.requestId||Y.current),V(N);return}if(!j||j.status!=="committed"){Y.current=null,g(),C(p("ask-reconcile"));return}n(t.id,t.ownerId,t.ownerAskId)}else await m5(e,t.id,$),n(t.id)}catch(A){C(String(A.message||A)),t.ownerId&&!A.status?E(Y.current):Y.current=null,g()}finally{x(!1)}}},P=async()=>{if(!ne){C(null),S(!0);try{let M;if(G){if(M=await S5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),(M==null?void 0:M.dismissed)!==!0||M.scope!=="local"||!["pending","blocked"].includes(M.ownerSync))throw new Error(p("ask-dismiss-unconfirmed"))}else t.ownerId?await b5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}):await g5(e,t.id);NE(Qn(t.id,t.ownerId,t.ownerAskId),G?t:null),s(t.id,t.ownerId,t.ownerAskId,M)}catch(M){C(String(M&&M.message||M)),g()}finally{S(!1)}}},B=p(T||X?"ask-uncertain":G?"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:B,"aria-label":B,disabled:ne,onClick:P,children:l.jsx(Tt,{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")}),(T||X)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:p("ask-uncertain")}),X&&!T&&l.jsx("div",{className:"nc-err",children:p("ask-reconcile")}),T&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:H,onClick:async()=>{F(!0);try{const M=await _5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id,requestId:T});(M==null?void 0:M.state)==="committed"?n(t.id,t.ownerId,t.ownerAskId):(M==null?void 0:M.state)==="failed"&&(E(null),Y.current=null,g())}catch(M){C(String(M.message||M)),g()}finally{F(!1)}},children:p("ask-verify")})]}),(!t.ownerId||i===!0)&&!T&&!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(M=>l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:b||R,onClick:()=>I(M),children:M},M))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:p("ask-reply-ph"),value:v,disabled:b||R,onChange:M=>_(M.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:b||R||!v.trim(),onClick:()=>I(v),children:p("send")})]})]}),L&&l.jsx("div",{className:"nc-err",children:L})]})}function f4({token:t}){const[e]=$n(),[n]=vE(),[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),T=w.useRef(new Map),E=w.useRef(0),H=w.useRef(0),F=w.useRef(new Map),X=w.useRef(new Map),V=w.useRef(new Map),Y=J=>(J||[]).filter(te=>{const ge=T.current.get(Qn(te.id,te.ownerId,te.ownerAskId));if(!ge)return!0;if(Date.now()-ge.at>EE)return T.current.delete(Qn(te.id,te.ownerId,te.ownerAskId)),!0;const Se=Yo(te);return Number.isSafeInteger(Se)&&Se>0&&Number.isSafeInteger(ge.ts)&&ge.ts>0?Se!==ge.ts:ge.fingerprint!==null&&ge.fingerprint!==void 0&&ge.fingerprint!==JSON.stringify([te.question,te.options||[],te.session])}),ne=w.useRef(a);ne.current=a;const G=w.useCallback((J=!1)=>{if(!t)return;const te=new Set;for(const ge of ne.current){if(!ge.ownerId)continue;const Se=ge.ownerAskId||ge.id,Be=`${ge.ownerId}|${Se}`;te.add(Be);const je=L.current.get(Be);if(je&&(!J||je.pending))continue;const ze=new AbortController,Q=C.current,ve={controller:ze,pending:!0};L.current.set(Be,ve),x(Z=>({...Z,[Be]:{canReply:!1,status:"loading"}})),y5(t,{ownerId:ge.ownerId,askId:Se},{signal:ze.signal}).then(Z=>{if(Q!==C.current||ze.signal.aborted||L.current.get(Be)!==ve)return;const we=Z&&Z.ownerId===ge.ownerId&&Z.askId===Se&&typeof Z.canReply=="boolean"&&(!Z.canReply||Z.status==="open");x(K=>({...K,[Be]:we?Z:{canReply:!1,status:"unreachable"}}))}).catch(()=>{Q===C.current&&!ze.signal.aborted&&L.current.get(Be)===ve&&x(Z=>({...Z,[Be]:{canReply:!1,status:"unreachable"}}))}).finally(()=>{ve.pending=!1})}for(const[ge,Se]of L.current)te.has(ge)||(Se.controller.abort(),L.current.delete(ge))},[t]);w.useEffect(()=>{C.current++;for(const J of L.current.values())J.controller.abort();return L.current.clear(),x({}),()=>{C.current++;for(const J of L.current.values())J.controller.abort();L.current.clear()}},[t]),w.useEffect(()=>{G()},[a,G]);const I=w.useRef(!1);w.useEffect(()=>{v&&(I.current&&G(!0),I.current=!0)},[v,G]);const P=w.useRef(0),B=w.useRef(null);B.current||(B.current=w6());const M=w.useRef({enabled:n,lang:e});M.current={enabled:n,lang:e};const $=w.useCallback(J=>{i(te=>te.filter(ge=>ge.key!==J))},[]),A=w.useCallback(J=>{if(J.askId&&J.ownerId){const Se=Number.isSafeInteger(J.ownerAskTs)&&J.ownerAskTs>0?J.ownerAskTs:J.ownerAskFingerprint;if(Se){const Be=JSON.stringify([J.ownerId,J.ownerAskId||J.askId,Se]),je=Date.now();for(const[ze,Q]of V.current)je-Q>1440*60*1e3&&V.current.delete(ze);if(V.current.has(Be))return;V.current.set(Be,je),V.current.size>4096&&V.current.delete(V.current.keys().next().value)}}const te=`t${P.current+=1}`;i(Se=>[...Se.slice(-3),{...J,key:te}]),setTimeout(()=>$(te),J.urgency==="high"?i4:s4);const ge=M.current;if(ge.enabled)try{B.current.enqueue(J,m6(J,ge.lang))}catch{}},[$]);w.useEffect(()=>{n||B.current.stop()},[n]),w.useEffect(()=>{const J=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&B.current.stop()},te=()=>B.current.stop();return document.addEventListener("visibilitychange",J),window.addEventListener("blur",J),window.addEventListener($g,te),()=>{document.removeEventListener("visibilitychange",J),window.removeEventListener("blur",J),window.removeEventListener($g,te),typeof B.current.dispose=="function"?B.current.dispose():B.current.stop()}},[]);const j=J=>{if(J.ownerAskId||!J.ownerId)return J;const te=ne.current.filter(Se=>Se.ownerId===J.ownerId&&(Se.id===J.id||Se.ownerAskId===J.id)),ge=new Set(te.map(Se=>Se.ownerAskId||Se.id));return ge.size>1?null:{...J,ownerAskId:ge.size===1?[...ge][0]:J.id}},N=(J,te)=>{const ge=ne.current.find(Be=>Qn(Be.id,Be.ownerId,Be.ownerAskId)===J),Se=ge&&Yo(ge);return Number.isSafeInteger(te==null?void 0:te.ownerAskTs)&&te.ownerAskTs>0&&Number.isSafeInteger(Se)&&Se>0&&te.ownerAskTs!==Se},U=(J,te,ge,Se)=>{const Be=Qn(J,te,ge);(Se==null?void 0:Se.scope)==="local"&&["pending","blocked"].includes(Se.ownerSync)&&h(Se.ownerSync);const je=ne.current.find(ve=>Qn(ve.id,ve.ownerId,ve.ownerAskId)===Be),ze=je&&Yo(je);if(N(Be,Se))return;const Q=je||(Se==null?void 0:Se.askGeneration);T.current.set(Be,{at:Date.now(),ts:je?ze:Se==null?void 0:Se.ownerAskTs,fingerprint:Q&&Q.question!==void 0?JSON.stringify([Q.question,Q.options||[],Q.session]):null}),F.current.delete(Be),T.current.size>4096&&T.current.delete(T.current.keys().next().value),c(ve=>ve.filter(Z=>Qn(Z.id,Z.ownerId,Z.ownerAskId)!==Be))},D=async J=>{h(null);try{const te=await k5(t,{ownerId:J.ownerId,eventId:J.eventId});if(!te||te.dismissed!==!0)throw new Error(p("remote-notices-dismiss-failed"));(te.ownerSync==="pending"||te.ownerSync==="blocked")&&h(te.ownerSync),cm(J.key),g(ge=>ge.filter(Se=>Se.key!==J.key))}catch{h("remote-notices-dismiss-failed")}},W=async()=>{const J=f,te=[...new Set(J.map(ge=>ge.ownerId))];if(te.length!==0){h(null);try{const ge=await C5(t,{owners:te}),Se=ge&&ge.results||{},Be=new Set;let je=null;for(const ze of te){const Q=Se[ze];if(!Q||Q.failed){je!=="blocked"&&(je="failed");continue}Q.blocked?je="blocked":Q.pending&&je!=="blocked"&&je!=="failed"&&(je="pending"),Be.add(ze)}for(const ze of J)Be.has(ze.ownerId)&&cm(ze.key);g(ze=>ze.filter(Q=>!Be.has(Q.ownerId))),je==="blocked"?h("blocked"):je==="failed"?h("remote-notices-clear-failed"):je==="pending"&&h("pending")}catch{h("remote-notices-clear-failed")}}};w.useEffect(()=>{if(!t)return;let J=!0,te=!1,ge=null,Se=a1;const Be=()=>{ge!==null&&clearTimeout(ge),ge=null},je=()=>{!J||te||ge!==null||(ge=setTimeout(()=>{ge=null,!(!J||te)&&(S(Q=>Q+1),Se=Math.min(Se*2,o4),je())},Se))},ze=n4(t,Q=>{if(J){if(Q.type==="feed-state-changed"){S(ve=>ve+1);return}if(Q.type==="notify"&&Q.ownerId&&Q.eventId){const ve=i1(Q,Q.ownerId);ve&&(ve.arrivalSeq=++H.current),ve&&!um(ve.key)&&g(Z=>r1(o1(Z,[ve],null)))}if(Q.type==="notify-dismissed"){const ve=String(Q.ownerId||""),Z=String(Q.eventId||"");if(ve&&Z){const we=CE(ve,Z);cm(we),g(K=>K.filter(fe=>fe.key!==we))}return}if(Q.type==="notify")A(Q);else if(Q.type==="ask"&&Q.ask&&Q.ask.id){const ve=Qn(Q.ask.id,Q.ask.ownerId,Q.ask.ownerAskId);F.current.set(ve,++E.current),F.current.size>4096&&F.current.delete(F.current.keys().next().value),c(Z=>Cd(Z,Y([Q.ask])))}else if(Q.type==="ask-answered"&&Q.id){const ve=j(Q);ve&&U(ve.id,ve.ownerId,ve.ownerAskId,Q)}else if(Q.type==="ask-dismissed"&&(Q.id||Q.ownerAskId)){const ve=j(Q);if(!ve)return;const Z=Qn(ve.id,ve.ownerId,ve.ownerAskId);if(N(Z,Q))return;const we=Q.scope==="local"&&ne.current.find(K=>Qn(K.id,K.ownerId,K.ownerAskId)===Z);NE(Z,Q.scope==="local"?we||{...Q.askGeneration,ownerAskTs:Q.ownerAskTs}:null),U(ve.id,ve.ownerId,ve.ownerAskId,Q)}}},()=>{J&&(te=!0,Se=a1,Be(),G(!0),S(Q=>Q+1))},()=>{J&&(te=!1,je())});return je(),()=>{J=!1,Be(),ze()}},[t,A,G]),w.useEffect(()=>{let J=!0;const te=E.current;return t&&p5(t).then(ge=>{J&&c(Se=>Cd(u4(Se,Y((ge.asks||[]).filter(Be=>!Be.ownerId||(X.current.get(Be.ownerId)||0)<=te))),Y(Se.filter(Be=>(F.current.get(Qn(Be.id,Be.ownerId,Be.ownerAskId))||0)>te))))}).catch(()=>{}),()=>{J=!1}},[t,R]);const[se,me]=w.useState({});w.useEffect(()=>{if(!t)return;let J=!0;return w5(t).then(te=>{if(!J)return;const ge={};for(const Se of te&&te.attempts||[])Se&&Se.state==="uncertain"&&Se.ownerId&&Se.askId&&Se.requestId&&(ge[Se.ownerId+"|"+Se.askId]=Se.requestId);me(ge)}).catch(()=>{}),()=>{J=!1}},[t]);const[pe,Ie]=w.useState({});return w.useEffect(()=>{let J=!0;const te=E.current,ge=H.current;return x5(t).then(Se=>{if(!J)return;const Be={},je=[],ze=new Map,Q=new Set;for(const Z of Se&&Se.views||[]){Be[Z.ownerId]={stale:Z.stale===!0,error:!!Z.lastError},Q.add(Z.ownerId);for(const we of Z.asks||[])we&&we.id&&je.push({...we,ownerId:Z.ownerId,imported:!0});for(const we of Z.notifications||[]){const K=i1(we,Z.ownerId);K&&ze.set(K.key,K)}}Ie(Be);const ve=new Set((Se&&Se.views||[]).filter(Z=>{const we=typeof Z.cursor=="string"&&/^([1-9]\d*):(\d+)$/.exec(Z.cursor);return Z.stale===!1&&Number.isSafeInteger(Z.viewEpoch)&&Z.viewEpoch>0&&we&&Number(we[1])===Z.viewEpoch&&Number.isSafeInteger(Number(we[2]))&&!Z.lastError&&!Z.error&&Z.resyncRequired!==!0&&Array.isArray(Z.asks)&&Z.asks.length<=100}).map(Z=>Z.ownerId));for(const Z of ve)X.current.delete(Z),X.current.set(Z,++E.current),X.current.size>4096&&X.current.delete(X.current.keys().next().value);c(Z=>Cd(Z.filter(we=>!ve.has(we.ownerId)||(F.current.get(Qn(we.id,we.ownerId,we.ownerAskId))||0)>te),Y(je))),g(Z=>r1(o1(Z.filter(we=>!um(we.key)),[...ze.values()].filter(we=>!um(we.key)),Q,{owners:ve,arrivedAfter:we=>(we.arrivalSeq||0)>ge})))}).catch(()=>{}),()=>{J=!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(c4(u))}),l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("close"),onClick:()=>h(null),children:l.jsx(Tt,{name:"x",size:14})})]})}),s.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:s.map(J=>l.jsx(d4,{n:J,onClose:()=>$(J.key)},J.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(Tt,{name:"x",size:16})})]}),l.jsxs("div",{className:"nc-ask-panel-body",children:[a.map(J=>{var te,ge,Se,Be,je,ze;return l.jsx(h4,{ask:J,token:t,askReplyAccess:!J.ownerId||((te=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:te.canReply)===!0,canDismissLocal:((ge=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:ge.canDismissLocal)===!0,canDismissRemote:((Se=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:Se.canDismissRemote)===!0||((Be=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:Be.canDismissRemote)===void 0&&((je=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:je.canReply)===!0,capabilityStatus:((ze=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:ze.status)||"loading",onRefused:()=>G(!0),feedViewState:J.ownerId?r4(pe,J.ownerId):"live",initialUncertainRid:J.ownerId&&se[J.ownerId+"|"+(J.ownerAskId||J.id)]||null,onAnswered:U,onDismiss:U},Qn(J.id,J.ownerId,J.ownerAskId))}),f.length>0&&l.jsxs("div",{className:"nc-remote-notices",children:[l.jsxs("div",{className:"nc-remote-notices-head",children:[l.jsx("b",{children:p("remote-notices-title")}),l.jsx("button",{type:"button",className:"nc-remote-notices-clear",onClick:W,children:p("remote-notices-clear")})]}),f.map(J=>l.jsxs("div",{className:"nc-remote-notice"+(J.urgency==="high"?" nc-remote-notice-high":""),children:[l.jsxs("div",{className:"nc-remote-notice-head",children:[J.title?l.jsx("b",{children:J.title}):null,l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("remote-notices-dismiss"),"aria-label":p("remote-notices-dismiss"),onClick:()=>D(J),children:l.jsx(Tt,{name:"x",size:14})})]}),J.body?l.jsx("div",{children:J.body}):null,l.jsxs("div",{className:"nc-remote-notice-meta",children:[J.ownerId.slice(0,8)," · ",new Date(J.ts||Date.now()).toLocaleString()]})]},J.key))]})]})]})]})}const LE="nc_fontsize",AE=9,jE=24;function Yg(t=globalThis.localStorage){const e=Number(t.getItem(LE));return e>=AE&&e<=jE?e:13}function ME(t,e=globalThis.localStorage){const n=Math.max(AE,Math.min(jE,t));return e.setItem(LE,String(n)),n}async function p4(t){const e=await Wn("/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 m4(t,e=[]){var u;const[n,s]=await Promise.allSettled([e.length?nv(t,e):p4(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 g4(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 v4(t,e,n,s=[]){if(t.type==="session"){const c=t.value||{};return{kind:"session",key:t.key,cellName:t.label,session:t.label,node:e.length?e.join("/"):"",nodeLabel:n,route:e,live:!0,selectable:!0,working:!1,degraded:!1,active:!0,activity:t.activity||0,telemetry:c.telemetry||null,preview:c.preview||"",panelUrl:""}}const i=t.value||{},a=s.find(c=>c&&c.name===i.tmuxSession)||{};return{kind:"cell",key:t.key,cellName:i.cell,session:i.tmuxSession||i.cell,node:e.length?e.join("/"):"",nodeLabel:n,route:e,live:t.live===!0,selectable:t.live===!0,working:t.working===!0,degraded:!!i.degraded,active:i.active===!0,activity:t.activity||0,telemetry:a.telemetry||i.telemetry||null,preview:a.preview||i.preview||"",panelUrl:i.panelUrl||""}}function _4({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:_}){const[b,x]=w.useState(iI),[L,C]=w.useState(!1),[R,S]=w.useState("");w.useEffect(()=>yc(t,[],O=>{let de=null;if(!O.sessionsError&&O.sessionsJson)try{const We=JSON.parse(O.sessionsJson);We&&!We.error&&Array.isArray(We.sessions)&&(de=We.sessions)}catch{}const ye=ch({fs:O.fs,error:O.fleetError});x(We=>({...We,...de?{sessions:de}:{},...ye.kind==="data"?{cells:ye.cells,localFresh:!0}:{}}))}),[t]);const[T,E]=w.useState(null),H="stream",[F,X]=w.useState(Yg),V=O=>X(de=>ME(de+O)),[Y,ne]=w.useState(null),[G,I]=w.useState(!1),[P,B]=w.useState(""),M=w.useRef(null),$=w.useRef(null),{pins:A,orders:j,views:N,togglePin:U,removePin:D,pinError:W,canMoveRoster:se,moveRoster:me,stepRoster:pe}=Lv(),{groupsFor:Ie}=dh(),{groups:J,hasLoaded:te}=$k(t),ge=te?J:b.nodeGroups||[],Se=w.useMemo(()=>Ie(ge||[]).filter(O=>Array.isArray(O.route)&&O.route.length&&O.kind!=="vl"),[Ie,ge]),Be=w.useMemo(()=>{const O=new Map,de=Array.isArray(b.sessions)?b.sessions:[],ye=Array.isArray(b.cells)?b.cells:[],We=new Map(de.map(Pe=>[Pe.name,Pe])),ie=new Set(ye.map(Pe=>Pe.tmuxSession).filter(Boolean));O.set("local",Pv(ye,de.filter(Pe=>!ie.has(Pe.name)),We));for(const Pe of Se)O.set(Pe.route.join("/"),gc(Pe).rawItems);return O},[b,Se]),je=w.useMemo(()=>{const O=We=>L?"all":vg(N,We).filter,de=Array.isArray(b.sessions)?b.sessions:[],ye=[];for(const[We,ie]of Be){const Pe=Se.find(Pt=>Pt.route.join("/")===We),ft=Pe&&(Pe.label||Pe.name)||"",It=Pe?Pe.route:[],bt=Pe?Array.isArray(Pe.sessions)?Pe.sessions:[]:de,St=co(ie,A,O(We),Ii(j,We)),_t=L?St:St.filter(Pt=>{var Kt,Mt;return Pt.live===!0||Pt.type==="cell"&&((Kt=Pt.value)==null?void 0:Kt.degraded)===!0&&((Mt=Pt.value)==null?void 0:Mt.active)===!0});ye.push(..._t.map(Pt=>v4(Pt,It,ft,bt)))}return ye},[Be,Se,N,j,A,L,b.sessions]),ze=je,Q=w.useMemo(()=>T?je.find(O=>O.key===T&&O.selectable):null,[je,T]);w.useEffect(()=>{T&&!je.some(O=>O.key===T&&O.selectable)&&E(null)},[je,T]);const ve=w.useMemo(()=>Y?ze.find(O=>O.key===Y.key):null,[ze,Y]),Z=!!(Y&&ve);w.useEffect(()=>{W&&W.message&&S(W.message)},[W]),w.useEffect(()=>{var ye;const O=document.activeElement;(ye=$.current)==null||ye.focus();const de=We=>{We.key==="Escape"&&!Z&&s()};return document.addEventListener("keydown",de),()=>{var We;document.removeEventListener("keydown",de),(We=O==null?void 0:O.focus)==null||We.call(O)}},[s,Z]);const[we,K]=w.useState(""),fe={getLiveHost:O=>Qd(t,O),designateHostCell:(O,de,ye)=>Zd(t,O,de,ye),clearHostCell:(O,de)=>eh(t,O,de)},Re=O=>(u[Cs(O)]||{}).hostCell||null,Ee=async(O,de)=>{K(O.key);const ye=await nh({action:de?"remove":"use",cellId:O.cellName,route:O.route||[],api:fe});K(""),S(p(ye.messageKey).replace("{cell}",ye.hostCell||O.cellName)),ye.ok&&g&&g({route:O.route||[],hostCell:ye.hostCell,revision:ye.revision})},Ke=O=>O.degraded?p("cell-degraded"):O.selectable?O.working?p("cell-working"):p("cell-idle"):p("cell-off"),Je=async O=>{if(S(""),!O.selectable){S(p("cell-switcher-not-active"));return}if(O.kind==="session"){n({session:O.session,...O.node?{node:O.node}:{}}),s();return}B(O.key);try{const de=await m4(t,O.route),ye=(de.cells||[]).find(We=>(We==null?void 0:We.cell)===O.cellName&&(We==null?void 0:We.tmuxSession)===O.session);if(de.fresh!==!0){n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s();return}if(!g4(ye,de.sessions,de.fresh)){S(p("cell-switcher-not-active"));return}n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s()}catch{n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s()}finally{B("")}},at=O=>{if(!O.selectable){Je(O);return}if(T===O.key){Je(O);return}E(O.key)},Oe=w.useRef(null),_e=8,$e=O=>{const de=Oe.current;if(O.isPrimary===!1){de&&de.state==="open"&&(de.state="invalid");return}if(de&&de.state==="open"&&(de.id!==O.pointerId||de.row!==O.currentTarget)){de.state="invalid";return}Oe.current={id:O.pointerId,row:O.currentTarget,x:O.clientX,y:O.clientY,maxDelta:0,state:"open"}},tt=O=>{const de=Oe.current;!de||de.state!=="open"||de.id!==O.pointerId||(de.maxDelta=Math.max(de.maxDelta,Math.hypot(O.clientX-de.x,O.clientY-de.y)),de.maxDelta>_e&&(de.state="invalid"))},Fe=O=>{const de=Oe.current;!de||de.id!==O.pointerId||de.state!=="open"||(de.state=de.maxDelta<=_e?"tap":"invalid")},it=O=>{const de=Oe.current;de&&de.id===O.pointerId&&(de.state="invalid")},re=O=>{const de=Oe.current;return Oe.current=null,O.detail===0?!0:!de||de.state==="invalid"||de.row!==O.currentTarget?!1:Math.hypot(O.clientX-de.x,O.clientY-de.y)<=_e},le=O=>({onToggleLive:()=>Ee(O,Re(O.route||[])===O.cellName),onTogglePin:()=>Av({view:hh({item:{key:O.key,value:{cell:O.cellName}},pins:A,hostByRoute:u,route:O.route||[]}),itemKey:O.key,togglePin:U,removePin:D})});return l.jsxs("div",{className:"nc-cell-switcher-backdrop",onClick:s,children:[Q&&l.jsxs("div",{className:"nc-cell-switcher-anteprima","data-testid":"cell-switcher-anteprima",onClick:O=>O.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-anteprima-testa",children:[l.jsxs("b",{children:[p("cell-switcher-preview-word")," ",Q.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:()=>V(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:"−"}),l.jsxs("span",{"data-testid":"cell-switcher-fontsize",children:[F," px"]}),l.jsx("button",{type:"button",onClick:()=>V(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:"+"})]})]}),l.jsx(Sv,{row:Q,token:t,source:H,chrome:!1,panelPort:Ec(Q.route||[],a,i),liveHost:qa({liveHost:u[Cs(Q.route||[])],cells:b.cells||[]}),onLiveHostApplied:g,fontSize:F,readOnly:!0})]}),l.jsxs("aside",{ref:M,className:`nc-cell-switcher${Q?" with-anteprima":""}`,role:"dialog","aria-label":p("fleet-cells"),tabIndex:-1,onClick:O=>O.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:L?"":"on","aria-pressed":!L,onClick:()=>{S(""),C(!1)},children:p("cell-switcher-show-active")}),l.jsx("button",{type:"button",className:L?"on":"","aria-pressed":L,onClick:()=>{S(""),C(!0)},children:p("cell-switcher-show-all")})]}),l.jsx("button",{type:"button",className:`nc-cell-switcher-reorder${G?" on":""}`,"aria-pressed":G,title:p("reorder-help"),"aria-label":p("reorder"),onClick:()=>{S(""),I(O=>!O)},children:"↕"}),l.jsx("button",{ref:$,type:"button",className:"nc-cell-switcher-close","aria-label":p("cell-switcher-close"),title:p("cell-switcher-close"),onClick:s,children:"×"})]}),!Q&&l.jsx("div",{className:"nc-cell-switcher-hint",children:p("cell-switcher-tap-hint")}),l.jsxs("div",{className:"nc-cell-switcher-list",children:[(()=>{const O=qa({liveHost:u[Cs([])],cells:b.cells||[]});if(!O||!O.cell)return null;const{modeKey:de}=z5(O);return l.jsx("div",{className:"nc-cell-switcher-live-strip","data-testid":"cell-switcher-live-strip",children:p("cell-switcher-live-strip").replace("{cell}",O.cell).replace("{mode}",p(de||"live-host-mode-unknown"))})})(),je.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-empty-active")}),je.map((O,de)=>{const ye=(e==null?void 0:e.session)===O.session&&((e==null?void 0:e.node)||"")===O.node,We=!!Y&&Y.key===O.key,ie=v!=null&&v===O.key,Pe=Ke(O),ft=pg(p,O.activity),It=mg(p,O.telemetry),bt=[ft,It].filter(Boolean).join(" · "),St=O.node||"local",_t=de>0?je[de-1].node||"local":null,Pt=St!==_t,Kt=Be.get(St)||ze.filter(Mt=>(Mt.node||"local")===St);return l.jsxs(w.Fragment,{children:[Pt&&l.jsx("div",{className:"nc-cell-switcher-position",children:p("cell-switcher-group").replace("{node}",O.nodeLabel||c||p("cell-switcher-group-local"))}),l.jsxs("div",{className:`nc-cell-switcher-row${ye?" current":""}${T===O.key?" selected":""}${ie?" side":""}${O.selectable?"":" off"}`,"data-roster-key":O.key,"data-position":St,children:[G&&l.jsx(Gi,{position:St,itemKey:O.key,label:O.cellName,canMove:se,onMove:(Mt,Ot)=>me(St,Mt,Ot,Kt),onStep:Mt=>pe(St,O.key,Mt,Kt)}),l.jsx("span",{className:"nc-cell-switcher-peek",children:l.jsx("span",{className:`nc-cell-switcher-dot${O.degraded?" warn":O.live?` on${O.working?" working":""}`:""}`})}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":ye?"true":void 0,"aria-disabled":!O.selectable,"data-selected":T===O.key?"true":void 0,disabled:P===O.key,onPointerDown:$e,onPointerMove:tt,onPointerUp:Fe,onPointerCancel:it,onClick:Mt=>{re(Mt)&&at(O)},children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsxs("span",{className:"nc-cell-switcher-nameline",children:[l.jsx("b",{children:O.cellName}),ye&&l.jsx("span",{className:"nc-cell-switcher-here",children:p("cell-switcher-here")}),T===O.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:Pe}),bt&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:bt})]})]})}),_&&l.jsx("button",{type:"button",className:`nc-cell-switcher-side${ie?" on":""}`,title:p(ie?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-label":p(ie?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-pressed":ie?"true":"false",disabled:ye||!O.selectable,onClick:Mt=>{Mt.stopPropagation(),!ye&&O.selectable&&_(O)},children:l.jsx(Tt,{name:"splitView",size:20})}),l.jsx("button",{type:"button",className:`nc-cell-switcher-menu${We?" on":""}`,title:`${p("cell-actions-open")}: ${O.cellName}`,"aria-label":`${p("cell-actions-open")}: ${O.cellName}`,"aria-haspopup":"menu","aria-expanded":We?"true":"false",onClick:Mt=>{Mt.stopPropagation(),ne({key:O.key})},children:"⋯"})]})]},O.key)})]}),R&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:R}),Z&&(()=>{const O=ve,de=jv({...oo({item:{key:O.key,value:{cell:O.cellName}},cellName:O.cellName,route:O.route||[],pins:A,hostByRoute:u}),canBoot:!1,alive:O.selectable,handlers:le(O)});return l.jsx(Mv,{cellName:O.cellName,items:de,busy:we===O.key,onClose:()=>ne(null)})})()]})]})}const y4=2e3;function w4(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 b4({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 qN(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,y4);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:w4(f)},`${f.seq}-${f.kind}`))})]})}function l1({peer:t,token:e,onBack:n}){var s;return $n(),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(Tt,{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(b4,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Kd="nc_dual_side";function Gg(t,e){return!t||!e?!1:t.session===e.session&&(t.node||"")===(e.node||"")}function S4(t,e,n){return!n||!n.session||t&&Gg(t,n)?e:e&&Gg(e,n)?null:{session:n.session,...n.node?{node:n.node}:{},...n.ownerId?{ownerId:n.ownerId}:{}}}function x4(){try{const t=JSON.parse(localStorage.getItem(Kd)||"null");return!t||!t.main||!t.side||!t.main.session||!t.side.session?null:t}catch{return null}}function k4(t,e){try{if(!t||!e||!t.session||!e.session){localStorage.removeItem(Kd);return}const n=s=>({session:s.session,...s.node?{node:s.node}:{}});localStorage.setItem(Kd,JSON.stringify({main:n(t),side:n(e)}))}catch{}}function c1(){try{localStorage.removeItem(Kd)}catch{}}const C4=.2;function cd(t){return Math.max(C4,t)}function E4(){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 N4({onSubmit:t,reason:e=""}){$n();const[n,s]=w.useState(""),[i,a]=w.useState(E4),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 dm=t=>vs(Pi(t)).length===0;function Fa(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 u1(t,e){return t.length?t:Array.isArray(e.floating)&&e.floating.length?[]:void 0}function R4(t,e,n,s,i){const a=c=>Fa(c&&c.floating,u=>Ua(u,s,i));return DP(a(t),a(e),n)}function d1(t,e,n,s,i,a){const c=v=>Ua(v,i,a),u=v=>Fa(v&&v.floating,c),{grid:h,floating:f}=$d(n),g=OP(s(h),R4(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 Rg(g.grid,g.floating)}const hm=t=>Array.isArray(t)?t.join("/"):"",L4="nc-decks-cache-v1",TE=t=>`${L4}:${t}`;function A4(t){if(!t)return[];try{const e=localStorage.getItem(TE(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 j4(t,e){if(t)try{localStorage.setItem(TE(t),JSON.stringify(e))}catch{}}function M4(t){const e=new Set,n=[];for(const s of Array.isArray(t)?t:[])!s||!qs.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:Dg(t.layout,a,n)}}function T4(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([]),T=w.useRef([]),E=w.useRef([]),H=w.useRef(new Map),F=w.useRef(""),X=w.useRef(e),V=w.useRef(n),Y=w.useRef(!1),ne=w.useRef(!0),G=w.useRef(""),I=w.useMemo(()=>M4(i),[i]),P=I.map(Q=>`${Q.instanceId}:${hm(Q.route)}`).join("|"),B=I.map(Q=>`${Q.instanceId}:${Q.status??""}:${Q.checking?"checking":"settled"}`).join("|"),M=w.useRef(new Map(I.map(Q=>[Q.instanceId,Q.checking?"pending":Q.status])));T.current=I,E.current=a,V.current=n,X.current=e,S.current=c;const $=w.useCallback(Q=>Ua(Q.layout,F.current,T.current),[]),A=w.useCallback(()=>Xl(X.current,F.current),[]),j=w.useCallback(Q=>(Array.isArray(Q)?Q:[]).find(ve=>ve.id===A()),[A]),N=w.useCallback((Q,ve=!0,Z)=>{const we=Z===void 0?A():Xl(Z,F.current),K=Pp(Q,Ql(),E.current),fe=S.current.some(Ee=>Ee.id===we);S.current=K,u(K),j4(F.current,K.map(Ee=>{if(!Ee.refreshFailedAt)return Ee;const Ke={...Ee};return delete Ke.refreshFailedAt,Ke}));const Re=K.find(Ee=>Ee.id===we);if(ve&&Re){ne.current=!0;const Ee=Rg($(Re),Fa(Re.floating,Ke=>Ua(Ke,F.current,T.current)));s(Ee),Re.local&&sD(Re.name,Pi(Ee))}else fe&&!Re&&(ne.current=!0,s(uo()),b("deck non più condiviso dal nodo owner"));ZI(K.filter(Ee=>Ee.local).map(Ee=>Ee.name))},[s,$]),U=w.useCallback(async Q=>{let ve=await Uu(t);const Z=ve.decks.find(we=>we.name==="main");if(ve.decks.length===1&&Z&&Z.revision===0&&dm(Z.layout)){const we=QI(),K=Pi(Og("main")||uo());if(!dm(K)){const fe=Dg(K,Q,[]);ve.decks[0]=await Wu(t,"main",fe,0,[])}for(const fe of we.filter(Re=>Re!=="main"))try{let Re=await Uw(t,fe,[]);const Ee=Pi(Og(fe)||uo());dm(Ee)||(Re=await Wu(t,fe,Dg(Ee,Q,[]),Re.revision,[]))}catch{}ve=await Uu(t)}return ve},[t]),D=w.useCallback((Q,ve)=>{const Z=new Map(ve.map(fe=>[fe.id,fe])),we=new Set,K=[];for(const fe of S.current){if(fe.local||fe.ownerId!==Q.instanceId){K.push(fe);continue}const Re=Z.get(fe.id);Re&&(K.push(Re),we.add(fe.id))}for(const fe of ve)we.has(fe.id)||K.push(fe);N(K,!1)},[N]),W=w.useCallback(async Q=>{try{const[ve,Z]=await Promise.all([Uu(t,Q.route),zw(t,Q.route).catch(()=>({nodes:[]}))]);D(Q,ve.decks.map(we=>Do(we,Q,Z.nodes,!1,!0)))}catch(ve){if(ve&&(ve.status===403||ve.status===404)){D(Q,[]);return}const Z=S.current.filter(we=>!we.local&&we.ownerId===Q.instanceId).map(we=>({...we,stale:!0,refreshFailedAt:Date.now(),ownerRoute:[...Q.route],ownerLabel:Q.label}));D(Q,Z)}},[t,D]),se=w.useCallback(async({migrate:Q=!1}={})=>{const ve=await Oc(t,[]),Z=qs.test(String(ve.instanceId||""))?ve.instanceId:"";if(!Z)throw new Error("instanceId locale non disponibile");F.current=Z,R(Z);const[we,K]=await Promise.all([Q?U(Z):Uu(t),zw(t,[]).catch(()=>({nodes:[]}))]),fe={instanceId:Z,route:[],label:"Local"},Re=we.decks.map(_e=>Do(_e,fe,K.nodes,!0,!0)),Ee=new Map(T.current.map(_e=>[_e.instanceId,_e])),Ke=S.current.length?S.current:A4(Z),Je=H.current,at=Date.now(),Oe=Ke.filter(_e=>!_e.local).flatMap(_e=>{const $e=Ee.get(_e.ownerId);if(!$e){const it=Je.get(_e.ownerId);return it===void 0?(Je.set(_e.ownerId,at),[{..._e,available:!1,stale:!0}]):at-it>Ev?[]:[{..._e,available:!1,stale:!0}]}Je.delete(_e.ownerId);const tt=$e.status==="up",Fe=$e.status==="pending"||$e.checking===!0;return[{..._e,available:Fe?_e.available:tt?_e.available!==!1:!1,stale:$e.stale===!0,ownerRoute:[...$e.route],ownerLabel:$e.label}]});return setTimeout(()=>{for(const _e of Ee.values())_e.status==="up"&&!_e.checking&&W(_e)},0),[...Re,...Oe]},[t,U,W,P]);w.useEffect(()=>{if(!t)return;let Q=!1;const ve=G.current!==t;return G.current=t,se({migrate:ve}).then(Z=>{if(Q)return;const we=j(S.current),K=j(Z),fe=K&&(!we||K.revision>we.revision||we.available!==K.available||hm(we.ownerRoute)!==hm(K.ownerRoute));N(Z,ve||!!fe&&!Y.current),f(!0),K&&b("")}).catch(Z=>{Q||(f(!0),b(String(Z.message||Z)))}),()=>{Q=!0}},[N,se,P,t,j]),w.useEffect(()=>{if(!S.current.length)return;const Q=Pp(S.current,Ql(),a);(Q.length!==S.current.length||Q.some((Z,we)=>Z.id!==S.current[we].id))&&(S.current=Q,u(Q))},[a]),w.useEffect(()=>{const Q=M.current,ve=new Map;for(const Z of T.current){if(Z.checking||Z.status==="pending"){ve.set(Z.instanceId,Q.get(Z.instanceId)||"pending");continue}Z.status==="up"&&Q.get(Z.instanceId)!=="up"&&W(Z),ve.set(Z.instanceId,Z.status)}M.current=ve},[B,W]);const me=w.useCallback(async(Q,ve=!0)=>{if(!h||!Y.current)return!0;const Z=Q===void 0?A():Xl(Q,F.current),we=S.current.find(K=>K.id===Z);if(!we)return b(`deck inesistente: ${Z}`),!1;if(we.available===!1)return b(`nodo owner offline: ${we.ownerLabel}`),!1;v("saving");try{const{grid:K,floating:fe}=$d(V.current),Re=Jl(Pi(K),we.ownerId,we.ownerTopology),Ee=Fa(fe,at=>Jl(at,we.ownerId,we.ownerTopology)),Ke=await Wu(t,we.name,Re,we.revision,we.ownerRoute,u1(Ee,we)),Je=Do(Ke,ec(we),we.ownerTopology,we.local,!0);return N(S.current.map(at=>at.id===Z?Je:at),!1),Y.current=!1,v("saved"),b(""),L(!1),setTimeout(()=>v("idle"),1500),!0}catch(K){if(ve&&K.status===409&&K.data&&K.data.current){const fe=S.current.find(Re=>Re.id===Z);if(fe){const Re=Do(K.data.current,ec(fe),fe.ownerTopology,fe.local,!0),Ee=d1(fe,Re,V.current,Ke=>Ke,F.current,T.current);return BP(Ee,V.current)||(V.current=Ee,ne.current=!0,s(Ee)),N(S.current.map(Ke=>Ke.id===Z?Re:Ke),!1),Y.current=!0,me(Z,!1)}}return v("error"),b(String(K.message||K)),K.status===409&&L(!0),!1}},[h,t,N,s]),pe=w.useCallback(async()=>{try{const Q=await se();Y.current=!1,L(!1),N(Q,!0),b("")}catch(Q){b(String(Q.message||Q))}},[se,N]);w.useEffect(()=>{if(!h)return;const Q=ne.current&&!Y.current;if(ne.current=!1,Q)return;Y.current=!0,v("saving");const ve=setTimeout(me,650);return()=>clearTimeout(ve)},[n,h,me]),w.useEffect(()=>{if(!h)return;const Q=()=>{if(!Y.current)return;const ve=S.current.find(Re=>Re.id===A());if(!ve||ve.available===!1)return;const{grid:Z,floating:we}=$d(V.current),K=Jl(Pi(Z),ve.ownerId,ve.ownerTopology),fe=Fa(we,Re=>Jl(Re,ve.ownerId,ve.ownerTopology));E5(t,ve.name,K,ve.revision,ve.ownerRoute,u1(fe,ve))};return window.addEventListener("pagehide",Q),window.addEventListener("beforeunload",Q),()=>{window.removeEventListener("pagehide",Q),window.removeEventListener("beforeunload",Q)}},[h,t,A]),w.useEffect(()=>{if(!h)return;const Q=setInterval(async()=>{try{const ve=await se(),Z=j(S.current),we=j(ve),K=!!(we&&Z&&we.revision>Z.revision),fe=!!(we&&(!Z||K||Z.available!==we.available));if(K&&Y.current&&we){const Re=d1(Z,we,V.current,Ee=>FP($(we),Ee),F.current,T.current);N(ve,!1),s(Re);return}N(ve,fe&&!Y.current)}catch{}},5e3);return()=>clearInterval(Q)},[h,se,N,$,s]);const Ie=w.useCallback(Q=>{s(ve=>{const Z=Q(ve);return Z!==ve&&(ne.current=!0),Z})},[]),J=async(Q,ve=null)=>{const Z=ve===Xi?S.current.find(fe=>fe.local):ve?S.current.find(fe=>fe.ownerId===ve):null;if(!Z||Z.available===!1)throw new Error("nodo owner non disponibile");const we=await Uw(t,Q,Z.ownerRoute),K=Do(we,ec(Z),Z.ownerTopology,Z.local,!0);return N([...S.current,K],!1),K},te=async(Q,ve)=>{const Z=S.current.find(Ee=>Ee.id===Q);if(!Z)throw new Error("deck inesistente");if(Xl(Q,F.current)===A()&&Y.current&&!await me(Q))throw new Error(`salvataggio di "${Z.name}" fallito: rinomina annullata`);const we=S.current.find(Ee=>Ee.id===Q);if(!we)throw new Error("deck inesistente");const K=await N5(t,we.name,ve,we.revision,we.ownerRoute),fe=Do(K,ec(we),we.ownerTopology,we.local,!0),Re=we.local?Xi:we.ownerId;return Tp(tD(Ql(),Re,Q,fe.id)),N(S.current.map(Ee=>Ee.id===Q?fe:Ee),!1),fe},ge=async Q=>{const ve=S.current.find(we=>we.id===Q);if(!ve)throw new Error("deck inesistente");Xl(Q,F.current)===A()&&(Y.current=!1),await R5(t,ve.name,ve.revision,ve.ownerRoute);const Z=ve.local?Xi:ve.ownerId;Tp(nD(Ql(),Z,Q)),N(S.current.filter(we=>we.id!==Q),!1)},Se=(Q,ve)=>{const Z=S.current.find(Ke=>Ke.id===Q),we=S.current.find(Ke=>Ke.id===ve);if(!Z||!we)return!1;const K=Z.local?Xi:Z.ownerId,fe=we.local?Xi:we.ownerId;if(K!==fe)return!1;const Re=S.current.filter(Ke=>(Ke.local?Xi:Ke.ownerId)===K).map(Ke=>Ke.id),Ee=Tp(eD(Ql(),K,Q,ve,Re));return N(Pp(S.current,Ee),!1),!0},Be=async(Q,ve)=>{const Z=S.current.find(Ke=>Ke.id===Q);if(!Z)throw new Error("deck inesistente");if(Z.available===!1)throw new Error(`nodo owner offline: ${Z.ownerLabel}`);const we=kC(ve,F.current,T.current);if(!we)throw new Error("riferimento sessione non valido");const K=$(Z),fe=Jl(Zk(K,we),Z.ownerId,Z.ownerTopology),Re=await Wu(t,Z.name,fe,Z.revision,Z.ownerRoute),Ee=Do(Re,ec(Z),Z.ownerTopology,Z.local,!0);return N(S.current.map(Ke=>Ke.id===Q?Ee:Ke),!1),Ee},je=w.useCallback(Q=>Rg($(Q),Fa(Q.floating,ve=>Ua(ve,F.current,T.current))),[$]);return{decks:c,records:c,localNodeId:C,ready:h,saveState:g,error:_,setError:b,conflict:x,reloadCurrent:pe,saveNow:me,select:async Q=>{if(Y.current&&!await me(A()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const ve=S.current.find(Z=>Z.id===Q);if(!ve)throw new Error(`deck inesistente: ${Q}`);return Y.current=!1,ne.current=!0,je(ve)},add:J,rename:te,remove:ge,reorder:Se,addTileTo:Be,viewUpdate:Ie,vistaMaterializzata:je,localMainId:Vo(null,"main"),parseDeckId:qc}}const P4="/sw.js",Xg="nc-sw-update";let Dc=null,Vd=!1,Yd=null,PE=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),IE=!1;function h_(){typeof window<"u"&&window.dispatchEvent(new Event(Xg))}function f_(){const t=Yd||(Vd?{kind:"reload",version:"",browserVersion:""}:null);PE=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 h1(){return PE}function I4(t){return typeof window>"u"?()=>{}:(window.addEventListener(Xg,t),()=>window.removeEventListener(Xg,t))}function p_(t){Vd!==t&&(Vd=t,f_(),h_())}const ud="nc-auto-reload",Gd="nc-reload";function m_(){try{return typeof location<"u"?location:null}catch{return null}}function DE(){try{return typeof history<"u"?history:null}catch{return null}}function D4(t){const e=t===void 0?m_():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Gd)}catch{return null}}function O4(t,{location:e,history:n}={}){const s=e===void 0?m_():e,i=n===void 0?DE():n;if(!s||!i||typeof i.replaceState!="function")return!1;try{const a=new URLSearchParams(s.search||"");return a.set(Gd,t),i.replaceState(i.state??null,"",`${s.pathname||"/"}?${a.toString()}${s.hash||""}`),!0}catch{return!1}}function B4({location:t,history:e}={}){const n=t===void 0?m_():t,s=e===void 0?DE():e;if(!n||!s||typeof s.replaceState!="function")return!1;try{const i=new URLSearchParams(n.search||"");if(!i.has(Gd))return!1;i.delete(Gd);const a=i.toString();return s.replaceState(s.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const OE="nc-update-dismissed";function BE(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function $4(t,e,n){return[t,e,n].map(s=>s||"").join("|")}let Jg=null;function z4(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 F4(t,e){if(!t)return!1;try{return t.getItem(OE)===e}catch{return!1}}function H4(t={}){const e=t.storage===void 0?BE():t.storage;if(Jg&&e)try{e.setItem(OE,Jg)}catch{}Vd=!1,Yd=null,f_(),h_()}function U4(t,e,n,s={}){const i=s.storage===void 0?BE():s.storage,a=n,c=$4(t,e,a);Jg=c;const u=z4(t,e,a);let h=F4(i,c)?null:u;if(h&&h.kind==="stale"){const g=`${e}|${a}`,v=D4(s.location)===g;let _=!1;if(!v&&i&&i.getItem(ud)!==g){try{i.setItem(ud,g)}catch{}_=i.getItem(ud)===g}_&&(O4(g,{location:s.location,history:s.history}),(s.applyImpl||$E)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Yd);if(Yd=h,f_(),f||h_(),!u){try{i&&i.removeItem(ud)}catch{}B4({location:s.location,history:s.history})}}const W4=1200;async function f1(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,W4))])}catch{}}async function $E(){try{Dc&&await Dc.update()}catch{}typeof location<"u"&&(await f1(location.pathname),await f1("/version.json"),location.reload())}function q4(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&p_(!0)})}function K4(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{IE&&location.reload()}),navigator.serviceWorker.register(P4).then(t=>{Dc=t,t.waiting&&p_(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&q4(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function V4(){IE=!0,p_(!1);const t=Dc&&Dc.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function Y4({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 zE="nc_side_w",p1="nc_side_min",G4=240,m1=new Set(["absent","present","active","unknown"]);function X4(){const t=Number(localStorage.getItem(zE));return t>=180&&t<=480?t:G4}function J4(){const t={token:"",pair:""};try{const{token:e,pair:n,device:s,nextUrl:i}=Y4({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e&&(t.token=e,E1(e,{remember:!0})),s&&R6(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=CN()),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function g1(t){try{return Pi(Og(t))}catch{return uo()}}function v1(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 Q4({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 Z4(t,e){if(!t||!t.tmux)return"";const n=Tv(t,e||{});return n.stato==="lavora"?p("cell-working"):n.stato==="attesa"?p("cell-permission"):n.stato==="ferma"?p("cell-idle"):""}function _1({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 ce;$n();const[x]=zv(),L=kk(),[C,R]=w.useState(!1),[S,T]=w.useState(null),[E,H]=w.useState(()=>x.showComposer),[F,X]=w.useState(Yg),[V,Y]=w.useState(()=>Cc()),ne=()=>{wk(YM(Cc())),typeof window<"u"&&window.location.reload()},[G,I]=w.useState(s||t),[P,B]=w.useState(""),[M,$]=w.useState(""),[A,j]=w.useState(""),[N,U]=w.useState(!1),[D,W]=w.useState(!1),se=!!v&&D,[me,pe]=w.useState(!1),[Ie,J]=w.useState({v:{main:1,side:1},h:{main:1,side:1}}),[te,ge]=w.useState(()=>window.matchMedia("(orientation: landscape)").matches);w.useEffect(()=>{const oe=window.matchMedia("(orientation: landscape)"),Me=Ge=>ge(Ge.matches);return oe.addEventListener("change",Me),()=>oe.removeEventListener("change",Me)},[]);const Se=te?Ie.h:Ie.v,Be=w.useRef(Se);Be.current=Se;const[je,ze]=w.useState(null),[Q,ve]=w.useState(!0),Z=w.useRef(()=>{}),we=w.useRef(()=>!1),K=w.useRef(()=>{}),fe=w.useRef(!1),Re=w.useRef(!1),Ee=w.useRef(null),Ke=w.useRef(null),[Je,at]=w.useState(null),Oe=w.useCallback(oe=>at({source:"main",ev:oe}),[]),_e=w.useCallback(oe=>at({source:"side",ev:oe}),[]),$e=!!v&&(Je==null?void 0:Je.source)==="side",tt=oe=>{W(oe),bt((oe?fe:ft).current),Pt((oe?Re:St).current)},Fe=v?`${v.node||""}:${v.session}`:"";w.useEffect(()=>{W(!1),pe(!1),J({v:{main:1,side:1},h:{main:1,side:1}}),ze(null),at(oe=>oe&&oe.source==="side"?null:oe)},[Fe]);const it=w.useMemo(()=>{const oe=new Map;return Me=>{if(oe.has(Me))return oe.get(Me);let Ge=Me*.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=`${Me}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 oe.set(Me,Ge),Ge}},[]),re=Math.max(.01,Se.main+Se.side),le=((ce=Ke.current)==null?void 0:ce.clientWidth)||window.innerWidth,O=Math.max(0,le-12)*(Math.min(Se.main,Se.side)/re)-26,de=!!v&&te&&O/it(Math.max(1,F))<40,ye=oe=>X(Me=>ME(Me+oe));w.useEffect(()=>{f||X(Yg())},[f]);const We=w.useRef(()=>{}),ie=w.useRef(()=>!1),Pe=w.useRef(()=>{}),ft=w.useRef(!1),[It,bt]=w.useState(!1),St=w.useRef(!1),[_t,Pt]=w.useState(!1),Kt=w.useRef(null),[Mt,Ot]=w.useState(!1),an=()=>{const oe=se?fe:ft;oe.current=!oe.current,bt(oe.current)},Tn=()=>{const oe=se?Re:St;oe.current=!oe.current,Pt(oe.current)};w.useEffect(()=>{I(s||t),U(!1)},[s,t]);const Vt=oe=>{const Me=!oe||oe.sessionsError?null:oe.sessionsJson;let Ge=null;Me&&Array.isArray(Me.sessions)&&(Ge=Me.sessions.find(Le=>Le.name===t));const mt=!oe||oe.fleetError?null:oe.fs;let q=null;mt&&mt.available&&Array.isArray(mt.cells)&&(q=mt.cells.find(Le=>Le.tmuxSession===t)),I(jc({session:t,cell:q||(s?{cell:s}:null)})),$(typeof(q==null?void 0:q.panelUrl)=="string"?q.panelUrl.trim():""),j(typeof(q==null?void 0:q.cell)=="string"?q.cell:"");let ae="";q?ae=[`${q.engine}${q.key?`·${q.key}`:""}`,Z4(q,Ge)].filter(Boolean).join(" · "):Ge&&(ae=Ge.attached?`attached · ${v1(Ge.activity)}`:Ge.activity?v1(Ge.activity):""),B(ae),ve(!!(Ge||q))},yn=w.useRef(Vt);yn.current=Vt,w.useEffect(()=>{const oe=e?e.split("/"):[],Me=Ge=>yn.current(Ge);return Me(nc(oe)),yc(i,oe,Me)},[e,i]),w.useEffect(()=>{yn.current(nc(e?e.split("/"):[]))},[t,s]);const en=w.useRef(b);en.current=b;const wn=oe=>{var Qe;if(!v)return;const Me=!oe||oe.sessionsError?null:oe.sessionsJson;let Ge=null,mt=!1;Me&&Array.isArray(Me.sessions)&&(mt=!0,Ge=Me.sessions.find(Te=>Te.name===v.session));const q=!oe||oe.fleetError?null:oe.fs;let ae=null,Le=!1;q&&q.available&&Array.isArray(q.cells)&&(Le=!0,ae=q.cells.find(Te=>Te.tmuxSession===v.session)),ze({title:jc({session:v.session,cell:ae}),present:!!(Ge||ae)}),(mt||Le)&&!Ge&&!ae&&((Qe=en.current)==null||Qe.call(en))},Ut=w.useRef(wn);Ut.current=wn,w.useEffect(()=>{if(!v){ze(null);return}const oe=v.node?v.node.split("/"):[],Me=Ge=>Ut.current(Ge);return Me(nc(oe)),yc(i,oe,Me)},[v,v==null?void 0:v.node,i]),w.useEffect(()=>{v&&Ut.current(nc(v.node?v.node.split("/"):[]))},[v==null?void 0:v.session]);const Jt=se?"side":"main",Qt=()=>at(oe=>oe&&oe.source===Jt?null:{source:Jt,ev:null}),[Zt,as]=w.useState(lE),[ls]=w.useState(uE),[pn]=w.useState(dE),mn=Q4({showComposer:E,showFiles:(Je==null?void 0:Je.source)===Jt,showPanel:N,hasPanel:!!M,rendererKind:V,filesSetting:L?null:Zt,handlers:{onToggleComposer:()=>H(oe=>!oe),onToggleFiles:L?Qt:()=>as(oe=>(cE(!oe),!oe)),onTogglePanel:()=>U(oe=>!oe),onSwitchRenderer:ne}}),Ks=oe=>{oe.preventDefault();const Me=Ke.current;if(!Me)return;const Ge=(xt,gt)=>J(Ze=>({...Ze,[te?"h":"v"]:{main:xt,side:gt}}));if(te){const xt=oe.clientX,gt=Be.current,Ze=Me.clientWidth||1,Nt=me?-1:1,Pn=ot=>{const Wt=gt.main+gt.side,ke=(ot.clientX-xt)/Ze*Wt*Nt,Ae=cd(gt.main+ke);Ge(Ae,cd(Wt-Ae))},qe=()=>{window.removeEventListener("pointermove",Pn),window.removeEventListener("pointerup",qe),window.removeEventListener("pointercancel",qe),window.removeEventListener("blur",qe)};window.addEventListener("pointermove",Pn),window.addEventListener("pointerup",qe),window.addEventListener("pointercancel",qe),window.addEventListener("blur",qe);return}const mt=oe.clientY,q=Be.current,ae=Me.clientHeight||1,Le=me?-1:1,Qe=xt=>{const gt=q.main+q.side,Ze=(xt.clientY-mt)/ae*gt*Le,Nt=cd(q.main+Ze);Ge(Nt,cd(gt-Nt))},Te=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",Te),window.removeEventListener("pointercancel",Te),window.removeEventListener("blur",Te)};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",Te),window.addEventListener("pointercancel",Te),window.addEventListener("blur",Te)},Kn=v&&l.jsxs("div",{className:`nc-dual-pane${se?"":" foco"}${de&&se?" nascosto":""}`,"data-testid":"pane-main",style:{flexGrow:Se.main,flexBasis:te?0:void 0},onPointerDown:()=>tt(!1),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${Q?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:G}),!se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),de&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",(je==null?void 0:je.title)||v.session),"aria-label":p("dual-go-to").replace("{cell}",(je==null?void 0:je.title)||v.session),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),tt(!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${je!=null&&je.present?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(mc,{session:t,node:e,token:i,readonly:a,takeSize:!0,focused:!se,sendRef:We,composerRef:ie,actionRef:Pe,ctrlRef:ft,setCtrlArmed:bt,altRef:St,setAltArmed:Pt,keyboardRef:Kt,onFiles:Oe,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:Y})})]},"pane-main"),wt=v&&l.jsxs("div",{className:`nc-dual-pane${se?" foco":""}${de&&!se?" nascosto":""}`,"data-testid":"pane-side",style:{flexGrow:Se.side,flexBasis:te?0:void 0},onPointerDown:()=>tt(!0),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${je!=null&&je.present?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:je?je.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:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),pe(Me=>!Me)},children:te?"⇆":"⇅"}),l.jsx("button",{type:"button",title:p("dual-close"),"aria-label":p("dual-close"),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),_==null||_()},children:"✕"})]}),de&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",G),"aria-label":p("dual-go-to").replace("{cell}",G),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),tt(!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${Q?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(mc,{session:v.session,node:v.node,token:i,readonly:a,takeSize:!1,focused:se,sendRef:Z,composerRef:we,actionRef:K,ctrlRef:fe,setCtrlArmed:bt,altRef:Re,setAltArmed:Pt,keyboardRef:Ee,onFiles:_e,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture})})]},"pane-side"),cs=l.jsx("div",{className:"nc-dual-handle","data-testid":"dual-handle",role:"separator","aria-orientation":te?"vertical":"horizontal",onPointerDown:Ks},"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(Tt,{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?`${G} · ${e}`:G,children:G}),g&&g.cell&&g.cell===s?l.jsx("span",{className:`nc-live-host-dot ${ov(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(Tt,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>ye(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Tt,{name:"zoomIn",size:18})}),Zt&&l.jsx("button",{type:"button",onClick:Qt,title:p("bar-menu-files"),"aria-label":p("bar-menu-files"),"aria-pressed":(Je==null?void 0:Je.source)===Jt?"true":"false",children:l.jsx(Tt,{name:"folder",size:18})}),ls&&l.jsx("button",{type:"button",onClick:()=>H(oe=>!oe),title:p("bar-menu-keyboard"),"aria-label":p("bar-menu-keyboard"),"aria-pressed":E?"true":"false",children:l.jsx(Tt,{name:"keyboard",size:18})}),M&&pn&&l.jsx("button",{type:"button",onClick:()=>U(oe=>!oe),title:p("bar-menu-panel"),"aria-label":p("bar-menu-panel"),"aria-pressed":N?"true":"false",children:l.jsx(Tt,{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:oe=>{C||T(oe.currentTarget.getBoundingClientRect()),R(Me=>!Me)},children:"⋯"})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[v?l.jsx("div",{className:`nc-dual${te?" row":""}`,ref:Ke,children:de?me?[wt,Kn]:[Kn,wt]:me?[wt,cs,Kn]:[Kn,cs,wt]}):l.jsx(mc,{session:t,node:e,token:i,readonly:a,takeSize:!0,sendRef:We,composerRef:ie,actionRef:Pe,ctrlRef:ft,setCtrlArmed:bt,altRef:St,setAltArmed:Pt,keyboardRef:Kt,onFiles:Oe,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:Y}),N&&M&&A&&l.jsx(bv,{cellId:A,panelUrl:M,route:e?e.split("/"):[],panelPort:c,token:i,title:G})]}),l.jsx(hI,{onKeyboard:()=>H(oe=>!oe),onCellSwitcher:h,cellSwitcherOpen:f,send:oe=>(se?Z:We).current(oe),action:oe=>(se?K:Pe).current(oe),ctrlArmed:It,onCtrl:an,altArmed:_t,onAlt:Tn,onAltConsume:()=>{const oe=se?Re:St;oe.current=!1,Pt(!1)},onKeyboardKeep:()=>{var oe,Me;return(Me=(oe=se?Ee:Kt).current)==null?void 0:Me.call(oe)},selectionMode:Mt,onSelectionMode:Ot,keepKeyboardClosed:x.keybarKeepsKeyboardClosed,showEnter:x.showKeybarEnter,keybarLayout:x.keybarLayout}),E&&l.jsx(vC,{submitText:oe=>(se?we:ie).current(oe),token:i,session:se?v.session:t,node:se?v.node:e,ownerId:se?v.ownerId:n,readonly:a,keepKeyboardClosedOnVoice:x.voiceKeepsKeyboardClosed}),Je&&($e?l.jsx(Mg,{session:v.session,node:v.node,token:i,filesEvent:Je.ev,onClose:()=>at(null)}):Je.source==="main"?l.jsx(Mg,{session:t,node:e,token:i,filesEvent:Je.ev,onClose:()=>at(null)}):null),C&&(L?l.jsx(Wk,{anchorRect:S,items:mn,onClose:()=>R(!1)}):l.jsx(Mv,{cellName:G,items:mn,onClose:()=>R(!1)}))]})}function eO(){$n();const[t]=w.useState(J4),[e,n]=w.useState(t.token),[s,i]=w.useState(!1);B6(s?"":e);const a=w.useRef(t.token);a.current=e,w.useEffect(()=>{const ke=Ae=>{Ae&&Ae.detail&&Ae.detail.token===a.current&&i(!0)};return window.addEventListener(pm,ke),()=>window.removeEventListener(pm,ke)},[]);const c=w.useCallback((ke,Ae)=>{const Xe=E1(ke,{remember:Ae});if(!Xe.ok||Ae&&Xe.where!=="local")try{window.dispatchEvent(new CustomEvent(mm))}catch{}i(!1),n(ke)},[]),[u,h]=w.useState(t.pair||""),f=w.useCallback(()=>{h("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),g=kk(),[v]=w.useState(()=>JI(typeof location<"u"?location.pathname:"/")),[_,b]=w.useState(v.id),x=_===Vo(null,ni),[L,C]=w.useState(null),R=ke=>{const Ae=Cr(ke);C(Ae?{...Ae,...typeof(ke==null?void 0:ke.cellName)=="string"&&ke.cellName?{cellName:ke.cellName}:{}}:null)},[S,T]=w.useState(null);w.useEffect(()=>{const ke=x4();T(ke&&L&&Gg(ke.main,L)?ke.side:null)},[L]);const E=ke=>{const Ae=L?{session:L.session,node:L.node}:null,Xe=S4(Ae,S,ke);T(Xe),Xe?k4(Ae,Xe):c1()},H=()=>{T(null),c1()},[F,X]=w.useState([]),[V,Y]=w.useState(!0),[ne,G]=w.useState(null),[I,P]=w.useState([]),[B,M]=w.useState([]),[$,A]=w.useState(!1),[j,N]=w.useState(null),[U,D]=w.useState(()=>v.ownerId?uo():g1(v.name)),[W,se]=w.useState(null),[me,pe]=w.useState(null),Ie=ke=>pe(Cr(ke)),[J,te]=w.useState(null),ge=Nv(e,g),Se=w.useMemo(()=>(ge||[]).filter(ke=>ke.instanceId).map(ke=>({instanceId:ke.instanceId,route:ke.route,label:ke.label,status:ke.status,stale:ke.stale===!0,checking:ke.checking===!0})),[ge]),{order:Be}=dh(),je=T4(e,_,U,D,Se,Be),{notice:ze,showActionNotice:Q}=lC(),ve=je.decks;w.useEffect(()=>{const ke=new Map;for(const Ae of ge||[]){const Xe=(Ae.route||[Ae.name]).join("/"),lt=new Set((Ae.sessions||[]).map(Rt=>Rt.name));for(const Rt of Ae.cells||[])!Rt.cell||!Rt.tmuxSession||Rt.cell===Rt.tmuxSession||lt.has(Rt.cell)||ke.set(`${Xe}:${Rt.cell}`,`${Xe}:${Rt.tmuxSession}`)}D(Ae=>AP(Ae,ke))},[ge]),w.useEffect(()=>{je.localNodeId&&v.ownerId&&v.ownerId===je.localNodeId&&D(ke=>ke.columns.some(Ae=>Ae.tiles.length)?ke:g1(v.name))},[je.localNodeId]),w.useEffect(()=>{je.localNodeId&&(KI(Se),je.viewUpdate(ke=>{const Ae=Ua(ke,je.localNodeId,Se);return JSON.stringify(Ae)===JSON.stringify(ke)?ke:Ae}))},[Se,je.localNodeId,je.viewUpdate]);const[Z,we]=w.useState(null),[K,fe]=w.useState(null),Re=w.useRef(0),[Ee,Ke]=w.useState(!1),[Je,at]=w.useState(X4),[Oe,_e]=w.useState(!x),[$e,tt]=w.useState(()=>x?localStorage.getItem(p1)==="1":!0),[Fe,it]=w.useState(!1),[re,le]=w.useState("nodes"),[O,de]=w.useState(!1),[ye,We]=w.useState(""),[ie,Pe]=w.useState(!1),ft=(ke="nodes",Ae=!1,Xe="")=>{le(ke),de(Ae),We(Xe),it(!0)},[It,bt]=w.useState(!1),[St,_t]=w.useState(null),[Pt,Kt]=w.useState({deviceDefault:"",localNodeId:"",localNameDefault:"",deviceNameNeeded:!1,deviceNameSuggestion:""}),[Mt,Ot]=w.useState(""),[an,Tn]=w.useState(!1),[Vt,yn]=w.useState(0),[en,wn]=w.useState({});w.useEffect(()=>{try{localStorage.setItem(zE,String(Je))}catch{}},[Je]),w.useEffect(()=>{try{localStorage.setItem(p1,$e?"1":"")}catch{}},[$e]),w.useEffect(()=>{if(!e)return;let ke=!1;return Promise.all([I1(e),Wn("/api/config",e).then(Ae=>Ae.json())]).then(([Ae,Xe])=>{if(!ke){if(Kt({deviceDefault:Ae.deviceName||"",localNodeId:Ae.nodeId||"",localNameDefault:Ae.localName||"",deviceNameNeeded:Ae.deviceNameNeeded===!0,deviceNameSuggestion:Ae.deviceNameSuggestion||""}),Ot(Ae.deviceName||""),Tn(!!Xe.readonlyDefault),QM(Xe.terminal),yn(Number.isInteger(Xe.panelPort)?Xe.panelPort:0),wn(Xe.nodePanelPorts&&typeof Xe.nodePanelPorts=="object"&&!Array.isArray(Xe.nodePanelPorts)?Xe.nodePanelPorts:{}),Ae.firstRun===!0&&!Xe.readonlyDefault)bt(!0);else if(u)bt(!0);else if(Ae.deviceNameNeeded===!0&&!Xe.readonlyDefault){let lt=!1;try{lt=sessionStorage.getItem("nc_device_ask_later")==="1"}catch{}lt||_t({suggestion:Ae.deviceNameSuggestion||""})}}}).catch(()=>{}),()=>{ke=!0}},[e,u]);const[Ut,Jt]=w.useState({}),Qt=w.useCallback(({route:ke,hostCell:Ae,revision:Xe})=>{const lt=Cs(ke);Jt(Rt=>({...Rt,[lt]:{hostCell:Ae||null,hostLease:null,hostRevision:Number.isInteger(Xe)?Xe:(Rt[lt]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Zt=ke=>{const Ae=Cs(ke),Xe=ke.length?((ge||[]).find(lt=>Cs(Array.isArray(lt.route)?lt.route:[])===Ae)||{}).cells||[]:I;return qa({liveHost:Ut[Ae]||null,cells:Xe,localNodeId:je.localNodeId,ownerId:ke.length?Ae:je.localNodeId})},as=w.useRef(ge);w.useEffect(()=>{as.current=ge},[ge]);const ls=w.useRef(null);ls.current||(ls.current=th());const pn=3500;w.useEffect(()=>{let ke=!1;const Ae=async()=>{const lt=ls.current,Rt=lt.begin();if(Rt!==null)try{const Vs=[[],...(as.current||[]).filter(tn=>tn.kind!=="vl"&&tn.status==="up").map(tn=>Array.isArray(tn.route)&&tn.route.length?tn.route:[tn.name])],Ps=await Promise.all(Vs.map(async tn=>{const _s=Cs(tn);try{const Bt=await Qd(e,tn,{timeoutMs:pn});return[_s,{hostCell:Bt&&typeof Bt.hostCell=="string"?Bt.hostCell:null,hostLease:Bt&&Bt.host&&typeof Bt.host.lease=="string"?Bt.host.lease:null,hostRevision:Number.isInteger(Bt&&Bt.revision)?Bt.revision:0,threadStatus:Bt&&m1.has(Bt.threadStatus)?Bt.threadStatus:"unknown"}]}catch{return[_s,{error:!0}]}}));if(ke||!lt.isCurrent(Rt))return;Jt(tn=>{let _s=!1;const Bt={...tn};for(const Ys of Ps){if(!Ys)continue;const[mo,rr]=Ys;Bt[mo]=rr.error?{...tn[mo]||{},threadStatus:"unknown"}:rr,_s=!0}return _s?Bt:tn})}finally{lt.end(Rt)}};Ae();const Xe=setInterval(Ae,4e3);return()=>{ke=!0,clearInterval(Xe),ls.current.reset()}},[e]),w.useEffect(()=>{if(!g)return;const ke=Ae=>{if(!Ae)return;const Xe=Ae.sessionsError?null:Ae.sessionsJson;Xe&&!Xe.error?(X(Xe.sessions||[]),Y(!0),G(Ae.at)):Y(!1);const lt=ch({fs:Ae.fs,error:Ae.fleetError});lt.kind==="data"?(Va("local",lt.cells),P(lt.cells),M(lt.capabilities),A(!1),N(null)):lt.kind==="stale"?(P(Rt=>Rt.length?Rt:Cv("local")),A(!0),N(null)):(P([]),Va("local",[]),M([]),A(!1),N(lt.reason||""))};return ke(nc([])),yc(e,[],ke)},[g,e]);const mn=w.useCallback(async(ke,Ae=[])=>{const Xe=Cs(Ae),lt=Ut[Xe]&&Ut[Xe].hostRevision||0;try{const Rt=await Zd(e,ke,lt,Ae);return Jt(Vs=>({...Vs,[Xe]:{hostCell:Rt.hostCell||null,hostLease:Rt.host&&typeof Rt.host.lease=="string"?Rt.host.lease:null,hostRevision:Number.isInteger(Rt.revision)?Rt.revision:lt,threadStatus:m1.has(Rt.threadStatus)?Rt.threadStatus:"unknown"}})),{ok:!0}}catch(Rt){return{ok:!1,error:Rt}}},[e,Ut]),Ks=w.useCallback(async(ke,Ae=[])=>{const Xe=await mn(ke,Ae);return Xe.ok||window.alert(p(_m(Xe.error))),Xe.ok},[mn]),Kn=w.useCallback(async(ke=[])=>{const Ae=Cs(ke),Xe=Ut[Ae]&&Ut[Ae].hostRevision||0;try{const lt=await eh(e,Xe,ke);return Jt(Rt=>({...Rt,[Ae]:{hostCell:lt.hostCell||null,hostLease:null,hostRevision:Number.isInteger(lt.revision)?lt.revision:Xe,threadStatus:"unknown"}})),{ok:!0}}catch(lt){return{ok:!1,error:lt}}},[e,Ut]),wt=w.useCallback(async(ke=[])=>{const Ae=await Kn(ke);return Ae.ok||window.alert(p(_m(Ae.error))),Ae.ok},[Kn]);w.useEffect(()=>{let ke=!1;const Ae=()=>{Wn("/api/config",e).then(lt=>lt.json()).then(lt=>{ke||U4(lt.version,lt.uiVersion,"0.9.65")}).catch(()=>{})};Ae();const Xe=setInterval(Ae,6e4);return()=>{ke=!0,clearInterval(Xe)}},[e]);const cs=new Set([...F.map(ke=>ke.name),...ge.flatMap(ke=>ke.sessions.map(Ae=>Ae.key))]),ce=w.useMemo(()=>{const ke=new Map;for(const Ae of F)Ae&&typeof Ae.name=="string"&&Number.isFinite(Ae.created)&&ke.set(Ae.name,Ae.created);return ke},[F]),oe=vs(U),Me=ke=>D(Ae=>{const Xe=kC(ke,je.localNodeId,Se)||ke,lt=Zk(Ae,Xe);return lt===Ae&&vs(Ae).length>=9&&je.setError(p("grid-full")),lt}),Ge=async(ke,Ae=[])=>{try{await ev(e,ke,Ae)}catch{return}const Xe=Ae.length?`${Ae.join("/")}:${ke}`:ke;D(lt=>Ac(lt,Xe)),sc(Ae,e)},mt=async(ke,Ae,Xe=[])=>{try{await P1(e,ke,Ae,Xe)}catch{return}sc(Xe,e)},q=async(ke,Ae,Xe=[])=>{await j1(e,{cell:ke,enabled:!!Ae},Xe),sc(Xe,e)},ae=async ke=>{if(!Z)return;const{cell:Ae}=Z,Xe=Array.isArray(Z.route)?Z.route:[];if(!await Dv({token:e,powerCell:Z,payload:ke,onNotice:Q})){const Rt=ke.action==="up"?!!ke.boot:ke.boot?!1:!!Z.boot;fe({id:++Re.current,cell:Ae,route:Xe,enabled:Rt})}sc(Xe,e)},Le=w.useCallback(ke=>{fe(Ae=>(Ae==null?void 0:Ae.id)===ke?null:Ae)},[]),Qe=async ke=>{if(!(!(ke!=null&&ke.direct)||Ee)){Ke(!0);try{await sv(e,ke.name,ke.tunnelStatus==="up"?"down":"up")}finally{Ke(!1)}}},Te=async(ke,Ae)=>{const Xe=String(Ae||"").trim();return!(ke!=null&&ke.direct)||!Ga(Xe)?!1:(await $1(e,ke.name,Xe),!0)},xt=ke=>{const Ae=ve.find(Xe=>Xe.id===ke);if(!Ae)return!1;try{const Xe=window.open(Mp(Ae,e),"_blank");return Xe&&(Xe.opener=null),!!Xe}catch{return!1}},gt=async ke=>{if(!ke||ke===_)return;const Ae=await je.select(ke),Xe=je.records.find(lt=>lt.id===ke);b(ke),D(Ae),se(null),pe(null);try{history.replaceState(null,"",Mp(Xe||ke,null))}catch{}},Ze=async(ke,Ae)=>{const Xe=await je.add(ke,Ae);await gt(Xe.id)},Nt=async(ke,Ae)=>{const Xe=await je.rename(ke,Ae);if(ke===_){b(Xe.id),D(je.vistaMaterializzata(Xe)),se(null),pe(null);try{history.replaceState(null,"",Mp(Xe,null))}catch{}}},Pn=async ke=>{await je.remove(ke),ke===_&&await gt(je.localMainId)},qe=async(ke,Ae)=>{!Ae||Ae===_||(await je.addTileTo(Ae,ke),D(Xe=>Ac(Xe,ke)))};if(!e||s)return l.jsx(N4,{onSubmit:c,reason:s?"invalid":""});const ot=l.jsxs(l.Fragment,{children:[Fe&&l.jsx(J6,{token:e,initialTab:re,initialLocation:ye,startNewCell:O,onClose:()=>{it(!1),de(!1),We("")}}),It&&l.jsx(Q6,{token:e,initialPair:u,...Pt,onPairDone:f,onDone:()=>bt(!1)}),St&&l.jsx(Z6,{token:e,suggestion:St.suggestion,onSaved:ke=>{Ot(ke),Kt(Ae=>({...Ae,deviceDefault:ke,deviceNameNeeded:!1})),_t(null)},onLater:()=>{try{sessionStorage.setItem("nc_device_ask_later","1")}catch{}_t(null)}}),l.jsx(f4,{token:e})]});if(!g)return J?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(l1,{peer:J,token:e,onBack:()=>te(null)})}),ot]}):L?l.jsxs(l.Fragment,{children:[l.jsx(_1,{session:L.session,node:L.node,ownerId:L.ownerId,cellName:L.cellName,token:e,readonly:an,liveHost:Zt(L.node?L.node.split("/"):[]),panelPort:Ec(L.node?L.node.split("/"):[],en,Vt),side:S,onSideClose:H,onSideGone:H,onBack:()=>C(null),onCellSwitcher:()=>Pe(!0),cellSwitcherOpen:ie}),ie&&l.jsx(_4,{token:e,current:L,localNodeLabel:Mt,panelPort:Vt,nodePanelPorts:en,hostByRoute:Ut,onDesignateCell:mn,onClearHostCell:Kn,onLiveHostApplied:Qt,sideKey:S?Rc(S.node?S.node.split("/"):[],S.session):null,onToggleSide:E,onPick:ke=>{R(ke),Pe(!1)},onClose:()=>Pe(!1)}),ot]}):l.jsxs(l.Fragment,{children:[l.jsx(oI,{onPick:R,token:e,onSettings:ft,onOpenVlSession:te,panelPort:Vt,nodePanelPorts:en,hostByRoute:Ut,onDesignateCell:Ks,onClearHostCell:wt}),ot]});const Wt=x||!Oe;return l.jsxs("div",{className:"nc-workspace",children:[Wt&&l.jsx(jI,{sessions:F,cells:I,localVerified:V,activeSessions:oe,nodeGroups:ge,token:e,onPeekOpen:()=>Pe(!1),overlayOpen:ie,fleetCapabilities:B,fleetStale:$,fleetOff:j,bootSettlement:K,onBootSettlementApplied:Le,localNodeId:je.localNodeId,hostByRoute:Ut,onDesignateCell:Ks,onClearHostCell:wt,onPick:Ie,onAddTile:Me,onPower:we,onBoot:q,onBootError:ke=>je.setError(String((ke==null?void 0:ke.message)||ke)),onNodePower:Qe,onNodeRename:Te,onKill:Ge,onVisibility:mt,onNew:()=>ft("fleet",!0),onSettings:ft,onOpenVlSession:te,width:Je,collapsed:$e,onResize:at,onToggleCollapse:()=>tt(ke=>!ke)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(wD,{decks:ve,currentDeck:_,onCreate:Ze,onRename:Nt,onDelete:Pn,onReorder:je.reorder,onOpenWindow:xt,onNavigate:gt,saveState:je.saveState,error:je.error,conflict:je.conflict,onReloadDeck:je.reloadCurrent,sidebarVisible:Wt,onToggleSidebar:x?null:()=>_e(ke=>!ke)}),ze&&l.jsx("div",{className:"nc-notice nc-deck-notice",role:"status",title:ze,children:ze}),l.jsx(qI,{layout:U,onLayoutChange:D,onResizeEnd:()=>{je.saveNow()},token:e,readonly:an,sessionsAlive:cs,localVerified:V,localIdentities:ce,localVerifiedAt:ne,focusSession:W,onFocus:se,onOpenSingle:Ie,decks:ve,currentDeck:_,onSendToDeck:qe,cells:I,nodeGroups:ge,panelPort:Vt,nodePanelPorts:en})]}),J&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(l1,{peer:J,token:e,onBack:()=>te(null)})}),me&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(_1,{session:me.session,node:me.node,ownerId:me.ownerId,cellName:jc({session:me.session,node:me.node,ownerId:me.ownerId,cells:I,nodeGroups:ge}),token:e,readonly:an,liveHost:Zt(me.node?me.node.split("/"):[]),panelPort:Ec(me.node?me.node.split("/"):[],en,Vt),onBack:()=>pe(null)})}),Z&&l.jsx(Dd,{cell:Z,token:e,route:Array.isArray(Z.route)?Z.route:[],onConfirm:ae,onClose:()=>we(null)}),ot]})}function tO(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 nO(){$n();const t=w.useSyncExternalStore(I4,h1,h1);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:tO(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:$E,children:p("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:V4,children:p("reload")}),l.jsx("button",{className:"nc-update-close",onClick:H4,"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}function sO(){$n();const[t,e]=w.useState(!1);return w.useEffect(()=>{const n=()=>e(!0);return window.addEventListener(mm,n),()=>window.removeEventListener(mm,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}K4();S6();xN.createRoot(document.getElementById("root")).render(l.jsxs(gN.StrictMode,{children:[l.jsx(eO,{}),l.jsx(nO,{}),l.jsx(sO,{})]}));
169
+ `],{type:"application/json"}),$=URL.createObjectURL(M),A=document.createElement("a");A.href=$,A.download="nexuscrew-diagnostics.json",A.click(),URL.revokeObjectURL($)}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:M=>a(M.target.value),children:s.map(M=>l.jsxs("option",{value:M.key,children:[M.label,M.status!=="up"?` · ${M.status}`:""]},M.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:M=>S(Number(M.target.value)),disabled:n,children:[300,900,1800,3600].map(M=>l.jsxs("option",{value:M,children:[M/60," min"]},M))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(u==null?void 0:u.verbose)===!0,onClick:()=>I(()=>Hw(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:()=>I(()=>Hw(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:T,onChange:M=>E(M.target.value),children:[l.jsx("option",{value:"all",children:p("diagnostics-all-levels")}),["debug","info","warn","error"].map(M=>l.jsx("option",{value:M,children:M},M))]}),l.jsx("input",{"aria-label":p("diagnostics-component"),placeholder:p("diagnostics-component"),value:H,onChange:M=>F(M.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:M=>x(M.target.checked)})," ",p("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:L,onChange:M=>C(M.target.checked)})," ",p("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:V,className:"nc-diag-log","aria-label":p("diagnostics-log"),children:G||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:B,children:p("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(p("diagnostics-clear-confirm"))&&I(async()=>{const M=await f5(t,c.route);return X.current=0,g([]),M})},children:p("diagnostics-clear")})]}),v&&l.jsx("div",{className:"nc-err",children:v})]})}function G6(){typeof window<"u"&&window.location&&typeof window.location.reload=="function"&&window.location.reload()}function X6({token:t,settings:e,readonly:n,refresh:s,roster:i,section:a,setSection:c}){const[u,h]=w.useState(Cc),[f,g]=w.useState(null),[v,_]=w.useState(null),[b,x]=w.useState(!1),[L,C]=w.useState(!1),[R,S]=w.useState(null),[T,E]=w.useState(!1),[H,F]=w.useState(!1),[X,V]=w.useState(null);w.useEffect(()=>{S(e&&e.update||null),E(!!(e&&e.autoUpdate===!0)),F(!!(e&&e.alternateScreen))},[e]);const Y=async()=>{g(null),_(null),C(!0);try{const N=await VN(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 l5(t);_(`${N.note||"ok"}${N.target?` (${N.target})`:""}`)}catch(N){g(String(N.message||N))}C(!1)},G=async N=>{g(null),_(null),C(!0);try{await Ed(t,{autoUpdate:N}),E(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},I=async N=>{g(null),_(null),C(!0);try{await Ed(t,{alternateScreen:N}),F(N),s&&await s()}catch(U){g(String(U.message||U))}C(!1)},P=w.useCallback(async()=>{if(t)try{V(await KN(t))}catch{V(null)}},[t]);w.useEffect(()=>{P()},[P]);const B=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 B1(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)},M=async()=>{g(null),_(null),C(!0);try{S(await c5(t))}catch(N){g(String(N.message||N))}C(!1)},$=async()=>{g(null),_(null),C(!0);try{const N=await u5(t);S(N),_(p("npm-update-restarting"))}catch(N){g(String(N.message||N))}C(!1)},A=()=>{window.confirm(p("composer-clear-confirm"))&&(g(null),xI()?(window.dispatchEvent(new Event(Tg)),_(p("composer-clear-done"))):g(p("composer-clear-failed")))},j=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=wk(N.target.checked?fo:po);h(U),G6()}}),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",{}),j&&j.installed?p("service-installed"):p("service-missing"),j&&j.installed?` · ${j.active?p("service-active"):p("service-inactive")}`:"",j?` · boot ${j.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(W6,{token:t,readonly:n}),l.jsx(q6,{})]}),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:T,disabled:n||L||R&&!R.supported,onChange:N=>G(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:M,children:p("npm-update-check")}),R&&R.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||L||R.phase==="installing",onClick:$,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=>B(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:A,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:H,disabled:n||L,onChange:N=>I(N.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:p("alternate-screen")}),l.jsx("small",{children:p("alternate-screen-help")})]})]})]}),l.jsx(z6,{token:t}),l.jsx(k6,{}),l.jsx(Y6,{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:Y,children:p("confirm")})]})]}),v&&l.jsx("div",{className:"nc-set-note",children:v}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function J6({token:t,onClose:e,initialTab:n="nodes",initialLocation:s="",startNewCell:i=!1}){$n();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,T]=w.useState(null),[E,H]=w.useState([]),[F,X]=w.useState(!1),[V,Y]=w.useState(null),[ne,G]=w.useState(0),I=Nv(t,!0,ne),P=w.useCallback(()=>{const D=h.current;if(!D)return;const W=D.scrollWidth>D.clientWidth+1,se={start:W&&D.scrollLeft>1,end:W&&D.scrollLeft+D.clientWidth<D.scrollWidth-1};v(me=>me.start===se.start&&me.end===se.end?me:se)},[]);w.useEffect(()=>{const D=h.current;if(!D)return;const W=typeof ResizeObserver=="function"?new ResizeObserver(P):null;return W==null||W.observe(D),window.addEventListener("resize",P),P(),()=>{W==null||W.disconnect(),window.removeEventListener("resize",P)}},[P]),w.useEffect(()=>{var W,se;(se=(W=f.current)==null?void 0:W.scrollIntoView)==null||se.call(W,{behavior:"smooth",block:"nearest",inline:"nearest"});const D=window.requestAnimationFrame?window.requestAnimationFrame(P):setTimeout(P,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(D):clearTimeout(D)}},[c,P]);const B=w.useRef(th()),M=w.useRef(null),$=w.useRef([]),A=w.useRef(new Map),j=w.useRef({token:null,instanceId:null}),N=w.useCallback((D,W)=>{if(!D.isCurrent(W))return;const se=$.current,me=[],pe=new Set;for(const Ie of A.current.values())for(const J of Ie){const te=Array.isArray(J.route)&&J.route.length?J.route.join("/"):"local",ge=`${J.ownerInstanceId}:${te}:${J.nodeId||J.name||J.label||""}`;pe.has(ge)||(pe.add(ge),me.push(J))}R([...se,...me])},[]),U=w.useCallback(async()=>{const D=B.current,W=D.begin();if(W===null)return;const se=new AbortController;M.current=se;const me={timeoutMs:N1,signal:se.signal};try{const pe=I1(t,me).then(te=>{D.isCurrent(W)&&(L(te),Y(null))}).catch(te=>{D.isCurrent(W)&&Y(String((te==null?void 0:te.message)||te))}),Ie=WN(t,me).then(te=>{if(!D.isCurrent(W))return;const ge=te.peers||[];$.current=ge,T(Number.isInteger(te.accessRevision)?te.accessRevision:null),N(D,W)}).catch(te=>{D.isCurrent(W)&&Y(String((te==null?void 0:te.message)||te))}),J=(async()=>{const[te,ge]=await Promise.all([Oc(t,[],me).then(Q=>Q).catch(()=>null),O1(t,me).then(Q=>Q).catch(()=>null)]);if(!D.isCurrent(W))return;const Se=te&&typeof te.instanceId=="string"?te.instanceId:"";if(!Se)return;j.current.instanceId!==Se&&(A.current.clear(),j.current.instanceId=Se);const Be=[{instanceId:Se||null,route:[],label:null},...Tk(ge,Se)],je=Q=>`${Q.instanceId}:${Q.route.join("/")}`;if(ge){const Q=new Set(Be.map(je));for(const ve of A.current.keys())Q.has(ve)||A.current.delete(ve)}if(!ge)for(const[Q,ve]of A.current)ve.some(Z=>Z.route.length)&&A.current.set(Q,ve.map(Z=>({...Z,stale:!0,online:!1,canManage:!1,capabilities:[]})));const ze=new Map;H([]),N(D,W),await Promise.allSettled(Be.map(async Q=>{const ve=je(Q);try{const Z=await D1(t,Q.route,{signal:se.signal});if(!D.isCurrent(W))return;const we=(Z.nodes||[]).map(K=>Mk(K,Q)).filter(Boolean);A.current.set(ve,we),ze.delete(ve)}catch(Z){if(!D.isCurrent(W))return;if((Z==null?void 0:Z.status)===403||(Z==null?void 0:Z.status)===404)A.current.delete(ve);else{const K=A.current.get(ve);K&&A.current.set(ve,K.map(fe=>({...fe,stale:!0,online:!1,canManage:!1,capabilities:[]})))}Q.route.length>0&&ze.set(ve,{instanceId:Q.instanceId,label:Q.label,route:Q.route,failure:/timeout/i.test(String((Z==null?void 0:Z.message)||Z))?"timeout":"unreachable"})}D.isCurrent(W)&&(H([...ze.values()]),N(D,W))}))})();await Promise.allSettled([pe,Ie,J])}finally{M.current===se&&(M.current=null),D.end(W)}},[t,N]);return w.useEffect(()=>{j.current.token!==t&&(j.current={token:t,instanceId:null},$.current=[],A.current.clear(),R([]),H([]),T(null)),U();const D=setInterval(U,5e3);return()=>{clearInterval(D),B.current.reset(),M.current&&M.current.abort()}},[U]),w.useEffect(()=>{let D=!1;return Wn("/api/config",t).then(W=>W.json()).then(W=>{D||X(!!W.readonlyDefault)}).catch(()=>{}),()=>{D=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:D=>D.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(Tt,{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(Tt,{name:"x",size:18})})]}),F&&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(D=>l.jsx("button",{ref:c===D?f:null,type:"button",className:`nc-set-tabbtn${c===D?" on":""}`,onClick:()=>u(D),children:p(`tab-${D}`)},D))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(U6,{token:t,nodes:C,roster:I,settings:x,readonly:F,vlUnavailable:E,accessRevision:S,refresh:U,refreshAliases:()=>G(D=>D+1)}),c==="fleet"&&l.jsx(n6,{token:t,readonly:F,startNewCell:i,initialLocation:s,targets:I.map(D=>({route:D.route,label:D.label||D.name,status:D.status}))}),c==="audio"&&l.jsx(K6,{token:t,readonly:F,nodes:C,settings:x}),c==="input"&&l.jsx(V6,{}),c==="system"&&l.jsx(X6,{token:t,settings:x,readonly:F,refresh:U,roster:I,section:_,setSection:b})]})]})})}function Q6({token:t,initialPair:e,deviceDefault:n="",localNodeId:s="",localNameDefault:i="",deviceNameNeeded:a=!1,deviceNameSuggestion:c="",onPairDone:u,onDone:h}){$n();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),T=async()=>{_(!0),x(null);try{const E={wizardDone:!0};a&&L.trim()&&(E.deviceName=L.trim()),await Ed(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:T,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(HC,{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(Gv,{line:R.line,note:R.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:v,onClick:T,children:p("finish")})})]}),b&&l.jsx("div",{className:"nc-err",children:b})]})})}function Z6({token:t,suggestion:e="",onSaved:n,onLater:s}){$n();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 Ed(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 e4=50;function t4(t){if(Number.isFinite(t))return t;const e=typeof t=="string"?Date.parse(t):NaN;return Number.isFinite(e)?e:0}function CE(t,e){return`${String(t)}|${String(e)}`}function i1(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:CE(e,t.eventId),ownerId:String(e),eventId:String(t.eventId),title:s,body:i,urgency:n.urgency==="high"?"high":"normal",ts:t4(t.emittedAt??(t.frame&&t.frame.ts)??t.ts),arrivalSeq:0}}function r1(t){return[...t].sort((e,n)=>n.ts-e.ts).slice(0,e4)}function o1(t,e,n,s=null){const i=new Set((e||[]).map(c=>c&&c.key)),a=new Map;for(const c of t||[])s&&s.owners.has(c.ownerId)&&!i.has(c.key)&&!s.arrivedAfter(c)||(!n||n.has(c.ownerId))&&a.set(c.key,c);for(const c of e||[])c&&a.set(c.key,c);return[...a.values()]}function n4(t,e,n,s){if(typeof EventSource>"u"||!t)return()=>{};const i=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return i.onopen=()=>{typeof n=="function"&&n()},i.onerror=()=>{typeof s=="function"&&s()},i.onmessage=a=>{try{const c=JSON.parse(a.data);c&&typeof c=="object"&&typeof c.type=="string"&&e(c)}catch{}},()=>{try{i.close()}catch{}}}const s4=6e3,i4=12e3,Qn=(t,e,n)=>`${e||""}:${n||t}`,r4=(t,e)=>{const n=t&&t[e];return n?n.stale===!0||n.error===!0?"degraded":"live":"missing"},EE=600*1e3,a1=30*1e3,o4=300*1e3,Vg=new Map,a4=900*1e3,za=new Map;function cm(t){za.set(t,Date.now()),za.size>4096&&za.delete(za.keys().next().value)}function um(t){const e=za.get(t);return e===void 0?!1:Date.now()-e>a4?(za.delete(t),!1):!0}const l4={pending:"ask-dismiss-local-pending",blocked:"ask-dismiss-local-blocked"},c4=t=>l4[t]||t,Yo=t=>Object.hasOwn(t,"ownerAskTs")?t.ownerAskTs:t.ownerAskId||t.originNode?null:t.ts;function NE(t,e){Vg.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 RE(t){const e=Qn(t.id,t.ownerId,t.ownerAskId),n=Vg.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>EE?(Vg.delete(e),!1):!0}function Cd(t,e){const n=new Map(t.map(s=>[Qn(s.id,s.ownerId,s.ownerAskId),s]));for(const s of e||[]){if(!s||!s.id||RE(s))continue;const i=Qn(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 u4(t,e){const n=Cd([],t.filter(a=>a.imported)),s=new Set(n.map(a=>Qn(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!s.has(Qn(a.id,a.ownerId,a.ownerAskId))&&!RE(a)),...n]}function d4({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(Tt,{name:"x",size:14})})]})}function h4({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),[T,E]=w.useState(c),[H,F]=w.useState(!1),[X,V]=w.useState(!1),Y=w.useRef(null);w.useEffect(()=>{c&&E(c)},[c]);const ne=R||b||!!T||X||!!t.ownerId&&f==="loading",G=!!t.ownerId&&!h,I=async M=>{const $=String(M||"").trim();if(!(!$||b||R||T||X)){C(null),x(!0);try{if(t.ownerId){const A=t.ownerAskId||t.id,j=await v5(e,{ownerId:t.ownerId,askId:A,text:$,requestId:Y.current||(Y.current=crypto.randomUUID())});if(j&&j.uncertain){const N=j.reason==="delivery-unknown-block"&&!j.originalRequestId;E(N?null:j.originalRequestId||j.requestId||Y.current),V(N);return}if(!j||j.status!=="committed"){Y.current=null,g(),C(p("ask-reconcile"));return}n(t.id,t.ownerId,t.ownerAskId)}else await m5(e,t.id,$),n(t.id)}catch(A){C(String(A.message||A)),t.ownerId&&!A.status?E(Y.current):Y.current=null,g()}finally{x(!1)}}},P=async()=>{if(!ne){C(null),S(!0);try{let M;if(G){if(M=await S5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),(M==null?void 0:M.dismissed)!==!0||M.scope!=="local"||!["pending","blocked"].includes(M.ownerSync))throw new Error(p("ask-dismiss-unconfirmed"))}else t.ownerId?await b5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}):await g5(e,t.id);NE(Qn(t.id,t.ownerId,t.ownerAskId),G?t:null),s(t.id,t.ownerId,t.ownerAskId,M)}catch(M){C(String(M&&M.message||M)),g()}finally{S(!1)}}},B=p(T||X?"ask-uncertain":G?"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:B,"aria-label":B,disabled:ne,onClick:P,children:l.jsx(Tt,{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")}),(T||X)&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:p("ask-uncertain")}),X&&!T&&l.jsx("div",{className:"nc-err",children:p("ask-reconcile")}),T&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:H,onClick:async()=>{F(!0);try{const M=await _5(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id,requestId:T});(M==null?void 0:M.state)==="committed"?n(t.id,t.ownerId,t.ownerAskId):(M==null?void 0:M.state)==="failed"&&(E(null),Y.current=null,g())}catch(M){C(String(M.message||M)),g()}finally{F(!1)}},children:p("ask-verify")})]}),(!t.ownerId||i===!0)&&!T&&!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(M=>l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:b||R,onClick:()=>I(M),children:M},M))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:p("ask-reply-ph"),value:v,disabled:b||R,onChange:M=>_(M.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:b||R||!v.trim(),onClick:()=>I(v),children:p("send")})]})]}),L&&l.jsx("div",{className:"nc-err",children:L})]})}function f4({token:t}){const[e]=$n(),[n]=vE(),[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),T=w.useRef(new Map),E=w.useRef(0),H=w.useRef(0),F=w.useRef(new Map),X=w.useRef(new Map),V=w.useRef(new Map),Y=J=>(J||[]).filter(te=>{const ge=T.current.get(Qn(te.id,te.ownerId,te.ownerAskId));if(!ge)return!0;if(Date.now()-ge.at>EE)return T.current.delete(Qn(te.id,te.ownerId,te.ownerAskId)),!0;const Se=Yo(te);return Number.isSafeInteger(Se)&&Se>0&&Number.isSafeInteger(ge.ts)&&ge.ts>0?Se!==ge.ts:ge.fingerprint!==null&&ge.fingerprint!==void 0&&ge.fingerprint!==JSON.stringify([te.question,te.options||[],te.session])}),ne=w.useRef(a);ne.current=a;const G=w.useCallback((J=!1)=>{if(!t)return;const te=new Set;for(const ge of ne.current){if(!ge.ownerId)continue;const Se=ge.ownerAskId||ge.id,Be=`${ge.ownerId}|${Se}`;te.add(Be);const je=L.current.get(Be);if(je&&(!J||je.pending))continue;const ze=new AbortController,Q=C.current,ve={controller:ze,pending:!0};L.current.set(Be,ve),x(Z=>({...Z,[Be]:{canReply:!1,status:"loading"}})),y5(t,{ownerId:ge.ownerId,askId:Se},{signal:ze.signal}).then(Z=>{if(Q!==C.current||ze.signal.aborted||L.current.get(Be)!==ve)return;const we=Z&&Z.ownerId===ge.ownerId&&Z.askId===Se&&typeof Z.canReply=="boolean"&&(!Z.canReply||Z.status==="open");x(K=>({...K,[Be]:we?Z:{canReply:!1,status:"unreachable"}}))}).catch(()=>{Q===C.current&&!ze.signal.aborted&&L.current.get(Be)===ve&&x(Z=>({...Z,[Be]:{canReply:!1,status:"unreachable"}}))}).finally(()=>{ve.pending=!1})}for(const[ge,Se]of L.current)te.has(ge)||(Se.controller.abort(),L.current.delete(ge))},[t]);w.useEffect(()=>{C.current++;for(const J of L.current.values())J.controller.abort();return L.current.clear(),x({}),()=>{C.current++;for(const J of L.current.values())J.controller.abort();L.current.clear()}},[t]),w.useEffect(()=>{G()},[a,G]);const I=w.useRef(!1);w.useEffect(()=>{v&&(I.current&&G(!0),I.current=!0)},[v,G]);const P=w.useRef(0),B=w.useRef(null);B.current||(B.current=w6());const M=w.useRef({enabled:n,lang:e});M.current={enabled:n,lang:e};const $=w.useCallback(J=>{i(te=>te.filter(ge=>ge.key!==J))},[]),A=w.useCallback(J=>{if(J.askId&&J.ownerId){const Se=Number.isSafeInteger(J.ownerAskTs)&&J.ownerAskTs>0?J.ownerAskTs:J.ownerAskFingerprint;if(Se){const Be=JSON.stringify([J.ownerId,J.ownerAskId||J.askId,Se]),je=Date.now();for(const[ze,Q]of V.current)je-Q>1440*60*1e3&&V.current.delete(ze);if(V.current.has(Be))return;V.current.set(Be,je),V.current.size>4096&&V.current.delete(V.current.keys().next().value)}}const te=`t${P.current+=1}`;i(Se=>[...Se.slice(-3),{...J,key:te}]),setTimeout(()=>$(te),J.urgency==="high"?i4:s4);const ge=M.current;if(ge.enabled)try{B.current.enqueue(J,m6(J,ge.lang))}catch{}},[$]);w.useEffect(()=>{n||B.current.stop()},[n]),w.useEffect(()=>{const J=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&B.current.stop()},te=()=>B.current.stop();return document.addEventListener("visibilitychange",J),window.addEventListener("blur",J),window.addEventListener($g,te),()=>{document.removeEventListener("visibilitychange",J),window.removeEventListener("blur",J),window.removeEventListener($g,te),typeof B.current.dispose=="function"?B.current.dispose():B.current.stop()}},[]);const j=J=>{if(J.ownerAskId||!J.ownerId)return J;const te=ne.current.filter(Se=>Se.ownerId===J.ownerId&&(Se.id===J.id||Se.ownerAskId===J.id)),ge=new Set(te.map(Se=>Se.ownerAskId||Se.id));return ge.size>1?null:{...J,ownerAskId:ge.size===1?[...ge][0]:J.id}},N=(J,te)=>{const ge=ne.current.find(Be=>Qn(Be.id,Be.ownerId,Be.ownerAskId)===J),Se=ge&&Yo(ge);return Number.isSafeInteger(te==null?void 0:te.ownerAskTs)&&te.ownerAskTs>0&&Number.isSafeInteger(Se)&&Se>0&&te.ownerAskTs!==Se},U=(J,te,ge,Se)=>{const Be=Qn(J,te,ge);(Se==null?void 0:Se.scope)==="local"&&["pending","blocked"].includes(Se.ownerSync)&&h(Se.ownerSync);const je=ne.current.find(ve=>Qn(ve.id,ve.ownerId,ve.ownerAskId)===Be),ze=je&&Yo(je);if(N(Be,Se))return;const Q=je||(Se==null?void 0:Se.askGeneration);T.current.set(Be,{at:Date.now(),ts:je?ze:Se==null?void 0:Se.ownerAskTs,fingerprint:Q&&Q.question!==void 0?JSON.stringify([Q.question,Q.options||[],Q.session]):null}),F.current.delete(Be),T.current.size>4096&&T.current.delete(T.current.keys().next().value),c(ve=>ve.filter(Z=>Qn(Z.id,Z.ownerId,Z.ownerAskId)!==Be))},D=async J=>{h(null);try{const te=await k5(t,{ownerId:J.ownerId,eventId:J.eventId});if(!te||te.dismissed!==!0)throw new Error(p("remote-notices-dismiss-failed"));(te.ownerSync==="pending"||te.ownerSync==="blocked")&&h(te.ownerSync),cm(J.key),g(ge=>ge.filter(Se=>Se.key!==J.key))}catch{h("remote-notices-dismiss-failed")}},W=async()=>{const J=f,te=[...new Set(J.map(ge=>ge.ownerId))];if(te.length!==0){h(null);try{const ge=await C5(t,{owners:te}),Se=ge&&ge.results||{},Be=new Set;let je=null;for(const ze of te){const Q=Se[ze];if(!Q||Q.failed){je!=="blocked"&&(je="failed");continue}Q.blocked?je="blocked":Q.pending&&je!=="blocked"&&je!=="failed"&&(je="pending"),Be.add(ze)}for(const ze of J)Be.has(ze.ownerId)&&cm(ze.key);g(ze=>ze.filter(Q=>!Be.has(Q.ownerId))),je==="blocked"?h("blocked"):je==="failed"?h("remote-notices-clear-failed"):je==="pending"&&h("pending")}catch{h("remote-notices-clear-failed")}}};w.useEffect(()=>{if(!t)return;let J=!0,te=!1,ge=null,Se=a1;const Be=()=>{ge!==null&&clearTimeout(ge),ge=null},je=()=>{!J||te||ge!==null||(ge=setTimeout(()=>{ge=null,!(!J||te)&&(S(Q=>Q+1),Se=Math.min(Se*2,o4),je())},Se))},ze=n4(t,Q=>{if(J){if(Q.type==="feed-state-changed"){S(ve=>ve+1);return}if(Q.type==="notify"&&Q.ownerId&&Q.eventId){const ve=i1(Q,Q.ownerId);ve&&(ve.arrivalSeq=++H.current),ve&&!um(ve.key)&&g(Z=>r1(o1(Z,[ve],null)))}if(Q.type==="notify-dismissed"){const ve=String(Q.ownerId||""),Z=String(Q.eventId||"");if(ve&&Z){const we=CE(ve,Z);cm(we),g(K=>K.filter(fe=>fe.key!==we))}return}if(Q.type==="notify")A(Q);else if(Q.type==="ask"&&Q.ask&&Q.ask.id){const ve=Qn(Q.ask.id,Q.ask.ownerId,Q.ask.ownerAskId);F.current.set(ve,++E.current),F.current.size>4096&&F.current.delete(F.current.keys().next().value),c(Z=>Cd(Z,Y([Q.ask])))}else if(Q.type==="ask-answered"&&Q.id){const ve=j(Q);ve&&U(ve.id,ve.ownerId,ve.ownerAskId,Q)}else if(Q.type==="ask-dismissed"&&(Q.id||Q.ownerAskId)){const ve=j(Q);if(!ve)return;const Z=Qn(ve.id,ve.ownerId,ve.ownerAskId);if(N(Z,Q))return;const we=Q.scope==="local"&&ne.current.find(K=>Qn(K.id,K.ownerId,K.ownerAskId)===Z);NE(Z,Q.scope==="local"?we||{...Q.askGeneration,ownerAskTs:Q.ownerAskTs}:null),U(ve.id,ve.ownerId,ve.ownerAskId,Q)}}},()=>{J&&(te=!0,Se=a1,Be(),G(!0),S(Q=>Q+1))},()=>{J&&(te=!1,je())});return je(),()=>{J=!1,Be(),ze()}},[t,A,G]),w.useEffect(()=>{let J=!0;const te=E.current;return t&&p5(t).then(ge=>{J&&c(Se=>Cd(u4(Se,Y((ge.asks||[]).filter(Be=>!Be.ownerId||(X.current.get(Be.ownerId)||0)<=te))),Y(Se.filter(Be=>(F.current.get(Qn(Be.id,Be.ownerId,Be.ownerAskId))||0)>te))))}).catch(()=>{}),()=>{J=!1}},[t,R]);const[se,me]=w.useState({});w.useEffect(()=>{if(!t)return;let J=!0;return w5(t).then(te=>{if(!J)return;const ge={};for(const Se of te&&te.attempts||[])Se&&Se.state==="uncertain"&&Se.ownerId&&Se.askId&&Se.requestId&&(ge[Se.ownerId+"|"+Se.askId]=Se.requestId);me(ge)}).catch(()=>{}),()=>{J=!1}},[t]);const[pe,Ie]=w.useState({});return w.useEffect(()=>{let J=!0;const te=E.current,ge=H.current;return x5(t).then(Se=>{if(!J)return;const Be={},je=[],ze=new Map,Q=new Set;for(const Z of Se&&Se.views||[]){Be[Z.ownerId]={stale:Z.stale===!0,error:!!Z.lastError},Q.add(Z.ownerId);for(const we of Z.asks||[])we&&we.id&&je.push({...we,ownerId:Z.ownerId,imported:!0});for(const we of Z.notifications||[]){const K=i1(we,Z.ownerId);K&&ze.set(K.key,K)}}Ie(Be);const ve=new Set((Se&&Se.views||[]).filter(Z=>{const we=typeof Z.cursor=="string"&&/^([1-9]\d*):(\d+)$/.exec(Z.cursor);return Z.stale===!1&&Number.isSafeInteger(Z.viewEpoch)&&Z.viewEpoch>0&&we&&Number(we[1])===Z.viewEpoch&&Number.isSafeInteger(Number(we[2]))&&!Z.lastError&&!Z.error&&Z.resyncRequired!==!0&&Array.isArray(Z.asks)&&Z.asks.length<=100}).map(Z=>Z.ownerId));for(const Z of ve)X.current.delete(Z),X.current.set(Z,++E.current),X.current.size>4096&&X.current.delete(X.current.keys().next().value);c(Z=>Cd(Z.filter(we=>!ve.has(we.ownerId)||(F.current.get(Qn(we.id,we.ownerId,we.ownerAskId))||0)>te),Y(je))),g(Z=>r1(o1(Z.filter(we=>!um(we.key)),[...ze.values()].filter(we=>!um(we.key)),Q,{owners:ve,arrivedAfter:we=>(we.arrivalSeq||0)>ge})))}).catch(()=>{}),()=>{J=!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(c4(u))}),l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("close"),onClick:()=>h(null),children:l.jsx(Tt,{name:"x",size:14})})]})}),s.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:s.map(J=>l.jsx(d4,{n:J,onClose:()=>$(J.key)},J.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(Tt,{name:"x",size:16})})]}),l.jsxs("div",{className:"nc-ask-panel-body",children:[a.map(J=>{var te,ge,Se,Be,je,ze;return l.jsx(h4,{ask:J,token:t,askReplyAccess:!J.ownerId||((te=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:te.canReply)===!0,canDismissLocal:((ge=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:ge.canDismissLocal)===!0,canDismissRemote:((Se=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:Se.canDismissRemote)===!0||((Be=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:Be.canDismissRemote)===void 0&&((je=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:je.canReply)===!0,capabilityStatus:((ze=b[J.ownerId+"|"+(J.ownerAskId||J.id)])==null?void 0:ze.status)||"loading",onRefused:()=>G(!0),feedViewState:J.ownerId?r4(pe,J.ownerId):"live",initialUncertainRid:J.ownerId&&se[J.ownerId+"|"+(J.ownerAskId||J.id)]||null,onAnswered:U,onDismiss:U},Qn(J.id,J.ownerId,J.ownerAskId))}),f.length>0&&l.jsxs("div",{className:"nc-remote-notices",children:[l.jsxs("div",{className:"nc-remote-notices-head",children:[l.jsx("b",{children:p("remote-notices-title")}),l.jsx("button",{type:"button",className:"nc-remote-notices-clear",onClick:W,children:p("remote-notices-clear")})]}),f.map(J=>l.jsxs("div",{className:"nc-remote-notice"+(J.urgency==="high"?" nc-remote-notice-high":""),children:[l.jsxs("div",{className:"nc-remote-notice-head",children:[J.title?l.jsx("b",{children:J.title}):null,l.jsx("button",{type:"button",className:"nc-ntf-x",title:p("remote-notices-dismiss"),"aria-label":p("remote-notices-dismiss"),onClick:()=>D(J),children:l.jsx(Tt,{name:"x",size:14})})]}),J.body?l.jsx("div",{children:J.body}):null,l.jsxs("div",{className:"nc-remote-notice-meta",children:[J.ownerId.slice(0,8)," · ",new Date(J.ts||Date.now()).toLocaleString()]})]},J.key))]})]})]})]})}const LE="nc_fontsize",AE=9,jE=24;function Yg(t=globalThis.localStorage){const e=Number(t.getItem(LE));return e>=AE&&e<=jE?e:13}function ME(t,e=globalThis.localStorage){const n=Math.max(AE,Math.min(jE,t));return e.setItem(LE,String(n)),n}async function p4(t){const e=await Wn("/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 m4(t,e=[]){var u;const[n,s]=await Promise.allSettled([e.length?nv(t,e):p4(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 g4(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 v4(t,e,n,s=[]){if(t.type==="session"){const c=t.value||{};return{kind:"session",key:t.key,cellName:t.label,session:t.label,node:e.length?e.join("/"):"",nodeLabel:n,route:e,live:!0,selectable:!0,working:!1,degraded:!1,active:!0,activity:t.activity||0,telemetry:c.telemetry||null,preview:c.preview||"",panelUrl:""}}const i=t.value||{},a=s.find(c=>c&&c.name===i.tmuxSession)||{};return{kind:"cell",key:t.key,cellName:i.cell,session:i.tmuxSession||i.cell,node:e.length?e.join("/"):"",nodeLabel:n,route:e,live:t.live===!0,selectable:t.live===!0,working:t.working===!0,degraded:!!i.degraded,active:i.active===!0,activity:t.activity||0,telemetry:a.telemetry||i.telemetry||null,preview:a.preview||i.preview||"",panelUrl:i.panelUrl||""}}function _4({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:_}){const[b,x]=w.useState(iI),[L,C]=w.useState(!1),[R,S]=w.useState("");w.useEffect(()=>yc(t,[],O=>{let de=null;if(!O.sessionsError&&O.sessionsJson)try{const We=JSON.parse(O.sessionsJson);We&&!We.error&&Array.isArray(We.sessions)&&(de=We.sessions)}catch{}const ye=ch({fs:O.fs,error:O.fleetError});x(We=>({...We,...de?{sessions:de}:{},...ye.kind==="data"?{cells:ye.cells,localFresh:!0}:{}}))}),[t]);const[T,E]=w.useState(null),H="stream",[F,X]=w.useState(Yg),V=O=>X(de=>ME(de+O)),[Y,ne]=w.useState(null),[G,I]=w.useState(!1),[P,B]=w.useState(""),M=w.useRef(null),$=w.useRef(null),{pins:A,orders:j,views:N,togglePin:U,removePin:D,pinError:W,canMoveRoster:se,moveRoster:me,stepRoster:pe}=Lv(),{groupsFor:Ie}=dh(),{groups:J,hasLoaded:te}=$k(t),ge=te?J:b.nodeGroups||[],Se=w.useMemo(()=>Ie(ge||[]).filter(O=>Array.isArray(O.route)&&O.route.length&&O.kind!=="vl"),[Ie,ge]),Be=w.useMemo(()=>{const O=new Map,de=Array.isArray(b.sessions)?b.sessions:[],ye=Array.isArray(b.cells)?b.cells:[],We=new Map(de.map(Pe=>[Pe.name,Pe])),ie=new Set(ye.map(Pe=>Pe.tmuxSession).filter(Boolean));O.set("local",Pv(ye,de.filter(Pe=>!ie.has(Pe.name)),We));for(const Pe of Se)O.set(Pe.route.join("/"),gc(Pe).rawItems);return O},[b,Se]),je=w.useMemo(()=>{const O=We=>L?"all":vg(N,We).filter,de=Array.isArray(b.sessions)?b.sessions:[],ye=[];for(const[We,ie]of Be){const Pe=Se.find(Pt=>Pt.route.join("/")===We),ft=Pe&&(Pe.label||Pe.name)||"",It=Pe?Pe.route:[],bt=Pe?Array.isArray(Pe.sessions)?Pe.sessions:[]:de,St=co(ie,A,O(We),Ii(j,We)),_t=L?St:St.filter(Pt=>{var Kt,Mt;return Pt.live===!0||Pt.type==="cell"&&((Kt=Pt.value)==null?void 0:Kt.degraded)===!0&&((Mt=Pt.value)==null?void 0:Mt.active)===!0});ye.push(..._t.map(Pt=>v4(Pt,It,ft,bt)))}return ye},[Be,Se,N,j,A,L,b.sessions]),ze=je,Q=w.useMemo(()=>T?je.find(O=>O.key===T&&O.selectable):null,[je,T]);w.useEffect(()=>{T&&!je.some(O=>O.key===T&&O.selectable)&&E(null)},[je,T]);const ve=w.useMemo(()=>Y?ze.find(O=>O.key===Y.key):null,[ze,Y]),Z=!!(Y&&ve);w.useEffect(()=>{W&&W.message&&S(W.message)},[W]),w.useEffect(()=>{var ye;const O=document.activeElement;(ye=$.current)==null||ye.focus();const de=We=>{We.key==="Escape"&&!Z&&s()};return document.addEventListener("keydown",de),()=>{var We;document.removeEventListener("keydown",de),(We=O==null?void 0:O.focus)==null||We.call(O)}},[s,Z]);const[we,K]=w.useState(""),fe={getLiveHost:O=>Qd(t,O),designateHostCell:(O,de,ye)=>Zd(t,O,de,ye),clearHostCell:(O,de)=>eh(t,O,de)},Re=O=>(u[Cs(O)]||{}).hostCell||null,Ee=async(O,de)=>{K(O.key);const ye=await nh({action:de?"remove":"use",cellId:O.cellName,route:O.route||[],api:fe});K(""),S(p(ye.messageKey).replace("{cell}",ye.hostCell||O.cellName)),ye.ok&&g&&g({route:O.route||[],hostCell:ye.hostCell,revision:ye.revision})},Ke=O=>O.degraded?p("cell-degraded"):O.selectable?O.working?p("cell-working"):p("cell-idle"):p("cell-off"),Je=async O=>{if(S(""),!O.selectable){S(p("cell-switcher-not-active"));return}if(O.kind==="session"){n({session:O.session,...O.node?{node:O.node}:{}}),s();return}B(O.key);try{const de=await m4(t,O.route),ye=(de.cells||[]).find(We=>(We==null?void 0:We.cell)===O.cellName&&(We==null?void 0:We.tmuxSession)===O.session);if(de.fresh!==!0){n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s();return}if(!g4(ye,de.sessions,de.fresh)){S(p("cell-switcher-not-active"));return}n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s()}catch{n({session:O.session,...O.node?{node:O.node}:{},cellName:O.cellName}),s()}finally{B("")}},at=O=>{if(!O.selectable){Je(O);return}if(T===O.key){Je(O);return}E(O.key)},Oe=w.useRef(null),_e=8,$e=O=>{const de=Oe.current;if(O.isPrimary===!1){de&&de.state==="open"&&(de.state="invalid");return}if(de&&de.state==="open"&&(de.id!==O.pointerId||de.row!==O.currentTarget)){de.state="invalid";return}Oe.current={id:O.pointerId,row:O.currentTarget,x:O.clientX,y:O.clientY,maxDelta:0,state:"open"}},tt=O=>{const de=Oe.current;!de||de.state!=="open"||de.id!==O.pointerId||(de.maxDelta=Math.max(de.maxDelta,Math.hypot(O.clientX-de.x,O.clientY-de.y)),de.maxDelta>_e&&(de.state="invalid"))},Fe=O=>{const de=Oe.current;!de||de.id!==O.pointerId||de.state!=="open"||(de.state=de.maxDelta<=_e?"tap":"invalid")},it=O=>{const de=Oe.current;de&&de.id===O.pointerId&&(de.state="invalid")},re=O=>{const de=Oe.current;return Oe.current=null,O.detail===0?!0:!de||de.state==="invalid"||de.row!==O.currentTarget?!1:Math.hypot(O.clientX-de.x,O.clientY-de.y)<=_e},le=O=>({onToggleLive:()=>Ee(O,Re(O.route||[])===O.cellName),onTogglePin:()=>Av({view:hh({item:{key:O.key,value:{cell:O.cellName}},pins:A,hostByRoute:u,route:O.route||[]}),itemKey:O.key,togglePin:U,removePin:D})});return l.jsxs("div",{className:"nc-cell-switcher-backdrop",onClick:s,children:[Q&&l.jsxs("div",{className:"nc-cell-switcher-anteprima","data-testid":"cell-switcher-anteprima",onClick:O=>O.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-anteprima-testa",children:[l.jsxs("b",{children:[p("cell-switcher-preview-word")," ",Q.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:()=>V(-1),title:p("zoom-out"),"aria-label":p("zoom-out"),children:"−"}),l.jsxs("span",{"data-testid":"cell-switcher-fontsize",children:[F," px"]}),l.jsx("button",{type:"button",onClick:()=>V(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:"+"})]})]}),l.jsx(Sv,{row:Q,token:t,source:H,chrome:!1,panelPort:Ec(Q.route||[],a,i),liveHost:qa({liveHost:u[Cs(Q.route||[])],cells:b.cells||[]}),onLiveHostApplied:g,fontSize:F,readOnly:!0})]}),l.jsxs("aside",{ref:M,className:`nc-cell-switcher${Q?" with-anteprima":""}`,role:"dialog","aria-label":p("fleet-cells"),tabIndex:-1,onClick:O=>O.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:L?"":"on","aria-pressed":!L,onClick:()=>{S(""),C(!1)},children:p("cell-switcher-show-active")}),l.jsx("button",{type:"button",className:L?"on":"","aria-pressed":L,onClick:()=>{S(""),C(!0)},children:p("cell-switcher-show-all")})]}),l.jsx("button",{type:"button",className:`nc-cell-switcher-reorder${G?" on":""}`,"aria-pressed":G,title:p("reorder-help"),"aria-label":p("reorder"),onClick:()=>{S(""),I(O=>!O)},children:"↕"}),l.jsx("button",{ref:$,type:"button",className:"nc-cell-switcher-close","aria-label":p("cell-switcher-close"),title:p("cell-switcher-close"),onClick:s,children:"×"})]}),!Q&&l.jsx("div",{className:"nc-cell-switcher-hint",children:p("cell-switcher-tap-hint")}),l.jsxs("div",{className:"nc-cell-switcher-list",children:[(()=>{const O=qa({liveHost:u[Cs([])],cells:b.cells||[]});if(!O||!O.cell)return null;const{modeKey:de}=z5(O);return l.jsx("div",{className:"nc-cell-switcher-live-strip","data-testid":"cell-switcher-live-strip",children:p("cell-switcher-live-strip").replace("{cell}",O.cell).replace("{mode}",p(de||"live-host-mode-unknown"))})})(),je.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:p("cell-switcher-empty-active")}),je.map((O,de)=>{const ye=(e==null?void 0:e.session)===O.session&&((e==null?void 0:e.node)||"")===O.node,We=!!Y&&Y.key===O.key,ie=v!=null&&v===O.key,Pe=Ke(O),ft=pg(p,O.activity),It=mg(p,O.telemetry),bt=[ft,It].filter(Boolean).join(" · "),St=O.node||"local",_t=de>0?je[de-1].node||"local":null,Pt=St!==_t,Kt=Be.get(St)||ze.filter(Mt=>(Mt.node||"local")===St);return l.jsxs(w.Fragment,{children:[Pt&&l.jsx("div",{className:"nc-cell-switcher-position",children:p("cell-switcher-group").replace("{node}",O.nodeLabel||c||p("cell-switcher-group-local"))}),l.jsxs("div",{className:`nc-cell-switcher-row${ye?" current":""}${T===O.key?" selected":""}${ie?" side":""}${O.selectable?"":" off"}`,"data-roster-key":O.key,"data-position":St,children:[G&&l.jsx(Gi,{position:St,itemKey:O.key,label:O.cellName,canMove:se,onMove:(Mt,Ot)=>me(St,Mt,Ot,Kt),onStep:Mt=>pe(St,O.key,Mt,Kt)}),l.jsx("span",{className:"nc-cell-switcher-peek",children:l.jsx("span",{className:`nc-cell-switcher-dot${O.degraded?" warn":O.live?` on${O.working?" working":""}`:""}`})}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":ye?"true":void 0,"aria-disabled":!O.selectable,"data-selected":T===O.key?"true":void 0,disabled:P===O.key,onPointerDown:$e,onPointerMove:tt,onPointerUp:Fe,onPointerCancel:it,onClick:Mt=>{re(Mt)&&at(O)},children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsxs("span",{className:"nc-cell-switcher-nameline",children:[l.jsx("b",{children:O.cellName}),ye&&l.jsx("span",{className:"nc-cell-switcher-here",children:p("cell-switcher-here")}),T===O.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:Pe}),bt&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:bt})]})]})}),_&&l.jsx("button",{type:"button",className:`nc-cell-switcher-side${ie?" on":""}`,title:p(ie?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-label":p(ie?"cell-switcher-side-remove":"cell-switcher-side-add"),"aria-pressed":ie?"true":"false",disabled:ye||!O.selectable,onClick:Mt=>{Mt.stopPropagation(),!ye&&O.selectable&&_(O)},children:l.jsx(Tt,{name:"splitView",size:20})}),l.jsx("button",{type:"button",className:`nc-cell-switcher-menu${We?" on":""}`,title:`${p("cell-actions-open")}: ${O.cellName}`,"aria-label":`${p("cell-actions-open")}: ${O.cellName}`,"aria-haspopup":"menu","aria-expanded":We?"true":"false",onClick:Mt=>{Mt.stopPropagation(),ne({key:O.key})},children:"⋯"})]})]},O.key)})]}),R&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:R}),Z&&(()=>{const O=ve,de=jv({...oo({item:{key:O.key,value:{cell:O.cellName}},cellName:O.cellName,route:O.route||[],pins:A,hostByRoute:u}),canBoot:!1,alive:O.selectable,handlers:le(O)});return l.jsx(Mv,{cellName:O.cellName,items:de,busy:we===O.key,onClose:()=>ne(null)})})()]})]})}const y4=2e3;function w4(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 b4({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 qN(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,y4);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:w4(f)},`${f.seq}-${f.kind}`))})]})}function l1({peer:t,token:e,onBack:n}){var s;return $n(),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(Tt,{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(b4,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Kd="nc_dual_side";function Gg(t,e){return!t||!e?!1:t.session===e.session&&(t.node||"")===(e.node||"")}function S4(t,e,n){return!n||!n.session||t&&Gg(t,n)?e:e&&Gg(e,n)?null:{session:n.session,...n.node?{node:n.node}:{},...n.ownerId?{ownerId:n.ownerId}:{}}}function x4(){try{const t=JSON.parse(localStorage.getItem(Kd)||"null");return!t||!t.main||!t.side||!t.main.session||!t.side.session?null:t}catch{return null}}function k4(t,e){try{if(!t||!e||!t.session||!e.session){localStorage.removeItem(Kd);return}const n=s=>({session:s.session,...s.node?{node:s.node}:{}});localStorage.setItem(Kd,JSON.stringify({main:n(t),side:n(e)}))}catch{}}function c1(){try{localStorage.removeItem(Kd)}catch{}}const C4=.2;function cd(t){return Math.max(C4,t)}function E4(){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 N4({onSubmit:t,reason:e=""}){$n();const[n,s]=w.useState(""),[i,a]=w.useState(E4),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 dm=t=>vs(Pi(t)).length===0;function Fa(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 u1(t,e){return t.length?t:Array.isArray(e.floating)&&e.floating.length?[]:void 0}function R4(t,e,n,s,i){const a=c=>Fa(c&&c.floating,u=>Ua(u,s,i));return DP(a(t),a(e),n)}function d1(t,e,n,s,i,a){const c=v=>Ua(v,i,a),u=v=>Fa(v&&v.floating,c),{grid:h,floating:f}=$d(n),g=OP(s(h),R4(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 Rg(g.grid,g.floating)}const hm=t=>Array.isArray(t)?t.join("/"):"",L4="nc-decks-cache-v1",TE=t=>`${L4}:${t}`;function A4(t){if(!t)return[];try{const e=localStorage.getItem(TE(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 j4(t,e){if(t)try{localStorage.setItem(TE(t),JSON.stringify(e))}catch{}}function M4(t){const e=new Set,n=[];for(const s of Array.isArray(t)?t:[])!s||!qs.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:Dg(t.layout,a,n)}}function T4(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([]),T=w.useRef([]),E=w.useRef([]),H=w.useRef(new Map),F=w.useRef(""),X=w.useRef(e),V=w.useRef(n),Y=w.useRef(!1),ne=w.useRef(!0),G=w.useRef(""),I=w.useMemo(()=>M4(i),[i]),P=I.map(Q=>`${Q.instanceId}:${hm(Q.route)}`).join("|"),B=I.map(Q=>`${Q.instanceId}:${Q.status??""}:${Q.checking?"checking":"settled"}`).join("|"),M=w.useRef(new Map(I.map(Q=>[Q.instanceId,Q.checking?"pending":Q.status])));T.current=I,E.current=a,V.current=n,X.current=e,S.current=c;const $=w.useCallback(Q=>Ua(Q.layout,F.current,T.current),[]),A=w.useCallback(()=>Xl(X.current,F.current),[]),j=w.useCallback(Q=>(Array.isArray(Q)?Q:[]).find(ve=>ve.id===A()),[A]),N=w.useCallback((Q,ve=!0,Z)=>{const we=Z===void 0?A():Xl(Z,F.current),K=Pp(Q,Ql(),E.current),fe=S.current.some(Ee=>Ee.id===we);S.current=K,u(K),j4(F.current,K.map(Ee=>{if(!Ee.refreshFailedAt)return Ee;const Ke={...Ee};return delete Ke.refreshFailedAt,Ke}));const Re=K.find(Ee=>Ee.id===we);if(ve&&Re){ne.current=!0;const Ee=Rg($(Re),Fa(Re.floating,Ke=>Ua(Ke,F.current,T.current)));s(Ee),Re.local&&sD(Re.name,Pi(Ee))}else fe&&!Re&&(ne.current=!0,s(uo()),b("deck non più condiviso dal nodo owner"));ZI(K.filter(Ee=>Ee.local).map(Ee=>Ee.name))},[s,$]),U=w.useCallback(async Q=>{let ve=await Uu(t);const Z=ve.decks.find(we=>we.name==="main");if(ve.decks.length===1&&Z&&Z.revision===0&&dm(Z.layout)){const we=QI(),K=Pi(Og("main")||uo());if(!dm(K)){const fe=Dg(K,Q,[]);ve.decks[0]=await Wu(t,"main",fe,0,[])}for(const fe of we.filter(Re=>Re!=="main"))try{let Re=await Uw(t,fe,[]);const Ee=Pi(Og(fe)||uo());dm(Ee)||(Re=await Wu(t,fe,Dg(Ee,Q,[]),Re.revision,[]))}catch{}ve=await Uu(t)}return ve},[t]),D=w.useCallback((Q,ve)=>{const Z=new Map(ve.map(fe=>[fe.id,fe])),we=new Set,K=[];for(const fe of S.current){if(fe.local||fe.ownerId!==Q.instanceId){K.push(fe);continue}const Re=Z.get(fe.id);Re&&(K.push(Re),we.add(fe.id))}for(const fe of ve)we.has(fe.id)||K.push(fe);N(K,!1)},[N]),W=w.useCallback(async Q=>{try{const[ve,Z]=await Promise.all([Uu(t,Q.route),zw(t,Q.route).catch(()=>({nodes:[]}))]);D(Q,ve.decks.map(we=>Do(we,Q,Z.nodes,!1,!0)))}catch(ve){if(ve&&(ve.status===403||ve.status===404)){D(Q,[]);return}const Z=S.current.filter(we=>!we.local&&we.ownerId===Q.instanceId).map(we=>({...we,stale:!0,refreshFailedAt:Date.now(),ownerRoute:[...Q.route],ownerLabel:Q.label}));D(Q,Z)}},[t,D]),se=w.useCallback(async({migrate:Q=!1}={})=>{const ve=await Oc(t,[]),Z=qs.test(String(ve.instanceId||""))?ve.instanceId:"";if(!Z)throw new Error("instanceId locale non disponibile");F.current=Z,R(Z);const[we,K]=await Promise.all([Q?U(Z):Uu(t),zw(t,[]).catch(()=>({nodes:[]}))]),fe={instanceId:Z,route:[],label:"Local"},Re=we.decks.map(_e=>Do(_e,fe,K.nodes,!0,!0)),Ee=new Map(T.current.map(_e=>[_e.instanceId,_e])),Ke=S.current.length?S.current:A4(Z),Je=H.current,at=Date.now(),Oe=Ke.filter(_e=>!_e.local).flatMap(_e=>{const $e=Ee.get(_e.ownerId);if(!$e){const it=Je.get(_e.ownerId);return it===void 0?(Je.set(_e.ownerId,at),[{..._e,available:!1,stale:!0}]):at-it>Ev?[]:[{..._e,available:!1,stale:!0}]}Je.delete(_e.ownerId);const tt=$e.status==="up",Fe=$e.status==="pending"||$e.checking===!0;return[{..._e,available:Fe?_e.available:tt?_e.available!==!1:!1,stale:$e.stale===!0,ownerRoute:[...$e.route],ownerLabel:$e.label}]});return setTimeout(()=>{for(const _e of Ee.values())_e.status==="up"&&!_e.checking&&W(_e)},0),[...Re,...Oe]},[t,U,W,P]);w.useEffect(()=>{if(!t)return;let Q=!1;const ve=G.current!==t;return G.current=t,se({migrate:ve}).then(Z=>{if(Q)return;const we=j(S.current),K=j(Z),fe=K&&(!we||K.revision>we.revision||we.available!==K.available||hm(we.ownerRoute)!==hm(K.ownerRoute));N(Z,ve||!!fe&&!Y.current),f(!0),K&&b("")}).catch(Z=>{Q||(f(!0),b(String(Z.message||Z)))}),()=>{Q=!0}},[N,se,P,t,j]),w.useEffect(()=>{if(!S.current.length)return;const Q=Pp(S.current,Ql(),a);(Q.length!==S.current.length||Q.some((Z,we)=>Z.id!==S.current[we].id))&&(S.current=Q,u(Q))},[a]),w.useEffect(()=>{const Q=M.current,ve=new Map;for(const Z of T.current){if(Z.checking||Z.status==="pending"){ve.set(Z.instanceId,Q.get(Z.instanceId)||"pending");continue}Z.status==="up"&&Q.get(Z.instanceId)!=="up"&&W(Z),ve.set(Z.instanceId,Z.status)}M.current=ve},[B,W]);const me=w.useCallback(async(Q,ve=!0)=>{if(!h||!Y.current)return!0;const Z=Q===void 0?A():Xl(Q,F.current),we=S.current.find(K=>K.id===Z);if(!we)return b(`deck inesistente: ${Z}`),!1;if(we.available===!1)return b(`nodo owner offline: ${we.ownerLabel}`),!1;v("saving");try{const{grid:K,floating:fe}=$d(V.current),Re=Jl(Pi(K),we.ownerId,we.ownerTopology),Ee=Fa(fe,at=>Jl(at,we.ownerId,we.ownerTopology)),Ke=await Wu(t,we.name,Re,we.revision,we.ownerRoute,u1(Ee,we)),Je=Do(Ke,ec(we),we.ownerTopology,we.local,!0);return N(S.current.map(at=>at.id===Z?Je:at),!1),Y.current=!1,v("saved"),b(""),L(!1),setTimeout(()=>v("idle"),1500),!0}catch(K){if(ve&&K.status===409&&K.data&&K.data.current){const fe=S.current.find(Re=>Re.id===Z);if(fe){const Re=Do(K.data.current,ec(fe),fe.ownerTopology,fe.local,!0),Ee=d1(fe,Re,V.current,Ke=>Ke,F.current,T.current);return BP(Ee,V.current)||(V.current=Ee,ne.current=!0,s(Ee)),N(S.current.map(Ke=>Ke.id===Z?Re:Ke),!1),Y.current=!0,me(Z,!1)}}return v("error"),b(String(K.message||K)),K.status===409&&L(!0),!1}},[h,t,N,s]),pe=w.useCallback(async()=>{try{const Q=await se();Y.current=!1,L(!1),N(Q,!0),b("")}catch(Q){b(String(Q.message||Q))}},[se,N]);w.useEffect(()=>{if(!h)return;const Q=ne.current&&!Y.current;if(ne.current=!1,Q)return;Y.current=!0,v("saving");const ve=setTimeout(me,650);return()=>clearTimeout(ve)},[n,h,me]),w.useEffect(()=>{if(!h)return;const Q=()=>{if(!Y.current)return;const ve=S.current.find(Re=>Re.id===A());if(!ve||ve.available===!1)return;const{grid:Z,floating:we}=$d(V.current),K=Jl(Pi(Z),ve.ownerId,ve.ownerTopology),fe=Fa(we,Re=>Jl(Re,ve.ownerId,ve.ownerTopology));E5(t,ve.name,K,ve.revision,ve.ownerRoute,u1(fe,ve))};return window.addEventListener("pagehide",Q),window.addEventListener("beforeunload",Q),()=>{window.removeEventListener("pagehide",Q),window.removeEventListener("beforeunload",Q)}},[h,t,A]),w.useEffect(()=>{if(!h)return;const Q=setInterval(async()=>{try{const ve=await se(),Z=j(S.current),we=j(ve),K=!!(we&&Z&&we.revision>Z.revision),fe=!!(we&&(!Z||K||Z.available!==we.available));if(K&&Y.current&&we){const Re=d1(Z,we,V.current,Ee=>FP($(we),Ee),F.current,T.current);N(ve,!1),s(Re);return}N(ve,fe&&!Y.current)}catch{}},5e3);return()=>clearInterval(Q)},[h,se,N,$,s]);const Ie=w.useCallback(Q=>{s(ve=>{const Z=Q(ve);return Z!==ve&&(ne.current=!0),Z})},[]),J=async(Q,ve=null)=>{const Z=ve===Xi?S.current.find(fe=>fe.local):ve?S.current.find(fe=>fe.ownerId===ve):null;if(!Z||Z.available===!1)throw new Error("nodo owner non disponibile");const we=await Uw(t,Q,Z.ownerRoute),K=Do(we,ec(Z),Z.ownerTopology,Z.local,!0);return N([...S.current,K],!1),K},te=async(Q,ve)=>{const Z=S.current.find(Ee=>Ee.id===Q);if(!Z)throw new Error("deck inesistente");if(Xl(Q,F.current)===A()&&Y.current&&!await me(Q))throw new Error(`salvataggio di "${Z.name}" fallito: rinomina annullata`);const we=S.current.find(Ee=>Ee.id===Q);if(!we)throw new Error("deck inesistente");const K=await N5(t,we.name,ve,we.revision,we.ownerRoute),fe=Do(K,ec(we),we.ownerTopology,we.local,!0),Re=we.local?Xi:we.ownerId;return Tp(tD(Ql(),Re,Q,fe.id)),N(S.current.map(Ee=>Ee.id===Q?fe:Ee),!1),fe},ge=async Q=>{const ve=S.current.find(we=>we.id===Q);if(!ve)throw new Error("deck inesistente");Xl(Q,F.current)===A()&&(Y.current=!1),await R5(t,ve.name,ve.revision,ve.ownerRoute);const Z=ve.local?Xi:ve.ownerId;Tp(nD(Ql(),Z,Q)),N(S.current.filter(we=>we.id!==Q),!1)},Se=(Q,ve)=>{const Z=S.current.find(Ke=>Ke.id===Q),we=S.current.find(Ke=>Ke.id===ve);if(!Z||!we)return!1;const K=Z.local?Xi:Z.ownerId,fe=we.local?Xi:we.ownerId;if(K!==fe)return!1;const Re=S.current.filter(Ke=>(Ke.local?Xi:Ke.ownerId)===K).map(Ke=>Ke.id),Ee=Tp(eD(Ql(),K,Q,ve,Re));return N(Pp(S.current,Ee),!1),!0},Be=async(Q,ve)=>{const Z=S.current.find(Ke=>Ke.id===Q);if(!Z)throw new Error("deck inesistente");if(Z.available===!1)throw new Error(`nodo owner offline: ${Z.ownerLabel}`);const we=kC(ve,F.current,T.current);if(!we)throw new Error("riferimento sessione non valido");const K=$(Z),fe=Jl(Zk(K,we),Z.ownerId,Z.ownerTopology),Re=await Wu(t,Z.name,fe,Z.revision,Z.ownerRoute),Ee=Do(Re,ec(Z),Z.ownerTopology,Z.local,!0);return N(S.current.map(Ke=>Ke.id===Q?Ee:Ke),!1),Ee},je=w.useCallback(Q=>Rg($(Q),Fa(Q.floating,ve=>Ua(ve,F.current,T.current))),[$]);return{decks:c,records:c,localNodeId:C,ready:h,saveState:g,error:_,setError:b,conflict:x,reloadCurrent:pe,saveNow:me,select:async Q=>{if(Y.current&&!await me(A()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const ve=S.current.find(Z=>Z.id===Q);if(!ve)throw new Error(`deck inesistente: ${Q}`);return Y.current=!1,ne.current=!0,je(ve)},add:J,rename:te,remove:ge,reorder:Se,addTileTo:Be,viewUpdate:Ie,vistaMaterializzata:je,localMainId:Vo(null,"main"),parseDeckId:qc}}const P4="/sw.js",Xg="nc-sw-update";let Dc=null,Vd=!1,Yd=null,PE=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),IE=!1;function h_(){typeof window<"u"&&window.dispatchEvent(new Event(Xg))}function f_(){const t=Yd||(Vd?{kind:"reload",version:"",browserVersion:""}:null);PE=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 h1(){return PE}function I4(t){return typeof window>"u"?()=>{}:(window.addEventListener(Xg,t),()=>window.removeEventListener(Xg,t))}function p_(t){Vd!==t&&(Vd=t,f_(),h_())}const ud="nc-auto-reload",Gd="nc-reload";function m_(){try{return typeof location<"u"?location:null}catch{return null}}function DE(){try{return typeof history<"u"?history:null}catch{return null}}function D4(t){const e=t===void 0?m_():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Gd)}catch{return null}}function O4(t,{location:e,history:n}={}){const s=e===void 0?m_():e,i=n===void 0?DE():n;if(!s||!i||typeof i.replaceState!="function")return!1;try{const a=new URLSearchParams(s.search||"");return a.set(Gd,t),i.replaceState(i.state??null,"",`${s.pathname||"/"}?${a.toString()}${s.hash||""}`),!0}catch{return!1}}function B4({location:t,history:e}={}){const n=t===void 0?m_():t,s=e===void 0?DE():e;if(!n||!s||typeof s.replaceState!="function")return!1;try{const i=new URLSearchParams(n.search||"");if(!i.has(Gd))return!1;i.delete(Gd);const a=i.toString();return s.replaceState(s.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const OE="nc-update-dismissed";function BE(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function $4(t,e,n){return[t,e,n].map(s=>s||"").join("|")}let Jg=null;function z4(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 F4(t,e){if(!t)return!1;try{return t.getItem(OE)===e}catch{return!1}}function H4(t={}){const e=t.storage===void 0?BE():t.storage;if(Jg&&e)try{e.setItem(OE,Jg)}catch{}Vd=!1,Yd=null,f_(),h_()}function U4(t,e,n,s={}){const i=s.storage===void 0?BE():s.storage,a=n,c=$4(t,e,a);Jg=c;const u=z4(t,e,a);let h=F4(i,c)?null:u;if(h&&h.kind==="stale"){const g=`${e}|${a}`,v=D4(s.location)===g;let _=!1;if(!v&&i&&i.getItem(ud)!==g){try{i.setItem(ud,g)}catch{}_=i.getItem(ud)===g}_&&(O4(g,{location:s.location,history:s.history}),(s.applyImpl||$E)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Yd);if(Yd=h,f_(),f||h_(),!u){try{i&&i.removeItem(ud)}catch{}B4({location:s.location,history:s.history})}}const W4=1200;async function f1(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,W4))])}catch{}}async function $E(){try{Dc&&await Dc.update()}catch{}typeof location<"u"&&(await f1(location.pathname),await f1("/version.json"),location.reload())}function q4(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&p_(!0)})}function K4(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{IE&&location.reload()}),navigator.serviceWorker.register(P4).then(t=>{Dc=t,t.waiting&&p_(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&q4(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function V4(){IE=!0,p_(!1);const t=Dc&&Dc.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function Y4({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 zE="nc_side_w",p1="nc_side_min",G4=240,m1=new Set(["absent","present","active","unknown"]);function X4(){const t=Number(localStorage.getItem(zE));return t>=180&&t<=480?t:G4}function J4(){const t={token:"",pair:""};try{const{token:e,pair:n,device:s,nextUrl:i}=Y4({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e&&(t.token=e,E1(e,{remember:!0})),s&&R6(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=CN()),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function g1(t){try{return Pi(Og(t))}catch{return uo()}}function v1(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 Q4({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 Z4(t,e){if(!t||!t.tmux)return"";const n=Tv(t,e||{});return n.stato==="lavora"?p("cell-working"):n.stato==="attesa"?p("cell-permission"):n.stato==="ferma"?p("cell-idle"):""}function _1({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 ce;$n();const[x]=zv(),L=kk(),[C,R]=w.useState(!1),[S,T]=w.useState(null),[E,H]=w.useState(()=>x.showComposer),[F,X]=w.useState(Yg),[V,Y]=w.useState(()=>Cc()),ne=()=>{wk(YM(Cc())),typeof window<"u"&&window.location.reload()},[G,I]=w.useState(s||t),[P,B]=w.useState(""),[M,$]=w.useState(""),[A,j]=w.useState(""),[N,U]=w.useState(!1),[D,W]=w.useState(!1),se=!!v&&D,[me,pe]=w.useState(!1),[Ie,J]=w.useState({v:{main:1,side:1},h:{main:1,side:1}}),[te,ge]=w.useState(()=>window.matchMedia("(orientation: landscape)").matches);w.useEffect(()=>{const oe=window.matchMedia("(orientation: landscape)"),Me=Ge=>ge(Ge.matches);return oe.addEventListener("change",Me),()=>oe.removeEventListener("change",Me)},[]);const Se=te?Ie.h:Ie.v,Be=w.useRef(Se);Be.current=Se;const[je,ze]=w.useState(null),[Q,ve]=w.useState(!0),Z=w.useRef(()=>{}),we=w.useRef(()=>!1),K=w.useRef(()=>{}),fe=w.useRef(!1),Re=w.useRef(!1),Ee=w.useRef(null),Ke=w.useRef(null),[Je,at]=w.useState(null),Oe=w.useCallback(oe=>at({source:"main",ev:oe}),[]),_e=w.useCallback(oe=>at({source:"side",ev:oe}),[]),$e=!!v&&(Je==null?void 0:Je.source)==="side",tt=oe=>{W(oe),bt((oe?fe:ft).current),Pt((oe?Re:St).current)},Fe=v?`${v.node||""}:${v.session}`:"";w.useEffect(()=>{W(!1),pe(!1),J({v:{main:1,side:1},h:{main:1,side:1}}),ze(null),at(oe=>oe&&oe.source==="side"?null:oe)},[Fe]);const it=w.useMemo(()=>{const oe=new Map;return Me=>{if(oe.has(Me))return oe.get(Me);let Ge=Me*.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=`${Me}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 oe.set(Me,Ge),Ge}},[]),re=Math.max(.01,Se.main+Se.side),le=((ce=Ke.current)==null?void 0:ce.clientWidth)||window.innerWidth,O=Math.max(0,le-12)*(Math.min(Se.main,Se.side)/re)-26,de=!!v&&te&&O/it(Math.max(1,F))<40,ye=oe=>X(Me=>ME(Me+oe));w.useEffect(()=>{f||X(Yg())},[f]);const We=w.useRef(()=>{}),ie=w.useRef(()=>!1),Pe=w.useRef(()=>{}),ft=w.useRef(!1),[It,bt]=w.useState(!1),St=w.useRef(!1),[_t,Pt]=w.useState(!1),Kt=w.useRef(null),[Mt,Ot]=w.useState(!1),an=()=>{const oe=se?fe:ft;oe.current=!oe.current,bt(oe.current)},Tn=()=>{const oe=se?Re:St;oe.current=!oe.current,Pt(oe.current)};w.useEffect(()=>{I(s||t),U(!1)},[s,t]);const Vt=oe=>{const Me=!oe||oe.sessionsError?null:oe.sessionsJson;let Ge=null;Me&&Array.isArray(Me.sessions)&&(Ge=Me.sessions.find(Le=>Le.name===t));const mt=!oe||oe.fleetError?null:oe.fs;let q=null;mt&&mt.available&&Array.isArray(mt.cells)&&(q=mt.cells.find(Le=>Le.tmuxSession===t)),I(jc({session:t,cell:q||(s?{cell:s}:null)})),$(typeof(q==null?void 0:q.panelUrl)=="string"?q.panelUrl.trim():""),j(typeof(q==null?void 0:q.cell)=="string"?q.cell:"");let ae="";q?ae=[`${q.engine}${q.key?`·${q.key}`:""}`,Z4(q,Ge)].filter(Boolean).join(" · "):Ge&&(ae=Ge.attached?`attached · ${v1(Ge.activity)}`:Ge.activity?v1(Ge.activity):""),B(ae),ve(!!(Ge||q))},yn=w.useRef(Vt);yn.current=Vt,w.useEffect(()=>{const oe=e?e.split("/"):[],Me=Ge=>yn.current(Ge);return Me(nc(oe)),yc(i,oe,Me)},[e,i]),w.useEffect(()=>{yn.current(nc(e?e.split("/"):[]))},[t,s]);const en=w.useRef(b);en.current=b;const wn=oe=>{var Qe;if(!v)return;const Me=!oe||oe.sessionsError?null:oe.sessionsJson;let Ge=null,mt=!1;Me&&Array.isArray(Me.sessions)&&(mt=!0,Ge=Me.sessions.find(Te=>Te.name===v.session));const q=!oe||oe.fleetError?null:oe.fs;let ae=null,Le=!1;q&&q.available&&Array.isArray(q.cells)&&(Le=!0,ae=q.cells.find(Te=>Te.tmuxSession===v.session)),ze({title:jc({session:v.session,cell:ae}),present:!!(Ge||ae)}),(mt||Le)&&!Ge&&!ae&&((Qe=en.current)==null||Qe.call(en))},Ut=w.useRef(wn);Ut.current=wn,w.useEffect(()=>{if(!v){ze(null);return}const oe=v.node?v.node.split("/"):[],Me=Ge=>Ut.current(Ge);return Me(nc(oe)),yc(i,oe,Me)},[v,v==null?void 0:v.node,i]),w.useEffect(()=>{v&&Ut.current(nc(v.node?v.node.split("/"):[]))},[v==null?void 0:v.session]);const Jt=se?"side":"main",Qt=()=>at(oe=>oe&&oe.source===Jt?null:{source:Jt,ev:null}),[Zt,as]=w.useState(lE),[ls]=w.useState(uE),[pn]=w.useState(dE),mn=Q4({showComposer:E,showFiles:(Je==null?void 0:Je.source)===Jt,showPanel:N,hasPanel:!!M,rendererKind:V,filesSetting:L?null:Zt,handlers:{onToggleComposer:()=>H(oe=>!oe),onToggleFiles:L?Qt:()=>as(oe=>(cE(!oe),!oe)),onTogglePanel:()=>U(oe=>!oe),onSwitchRenderer:ne}}),Ks=oe=>{oe.preventDefault();const Me=Ke.current;if(!Me)return;const Ge=(xt,gt)=>J(Ze=>({...Ze,[te?"h":"v"]:{main:xt,side:gt}}));if(te){const xt=oe.clientX,gt=Be.current,Ze=Me.clientWidth||1,Nt=me?-1:1,Pn=ot=>{const Wt=gt.main+gt.side,ke=(ot.clientX-xt)/Ze*Wt*Nt,Ae=cd(gt.main+ke);Ge(Ae,cd(Wt-Ae))},qe=()=>{window.removeEventListener("pointermove",Pn),window.removeEventListener("pointerup",qe),window.removeEventListener("pointercancel",qe),window.removeEventListener("blur",qe)};window.addEventListener("pointermove",Pn),window.addEventListener("pointerup",qe),window.addEventListener("pointercancel",qe),window.addEventListener("blur",qe);return}const mt=oe.clientY,q=Be.current,ae=Me.clientHeight||1,Le=me?-1:1,Qe=xt=>{const gt=q.main+q.side,Ze=(xt.clientY-mt)/ae*gt*Le,Nt=cd(q.main+Ze);Ge(Nt,cd(gt-Nt))},Te=()=>{window.removeEventListener("pointermove",Qe),window.removeEventListener("pointerup",Te),window.removeEventListener("pointercancel",Te),window.removeEventListener("blur",Te)};window.addEventListener("pointermove",Qe),window.addEventListener("pointerup",Te),window.addEventListener("pointercancel",Te),window.addEventListener("blur",Te)},Kn=v&&l.jsxs("div",{className:`nc-dual-pane${se?"":" foco"}${de&&se?" nascosto":""}`,"data-testid":"pane-main",style:{flexGrow:Se.main,flexBasis:te?0:void 0},onPointerDown:()=>tt(!1),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${Q?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:G}),!se&&l.jsx("span",{className:"nc-dual-matita","aria-hidden":"true",title:p("dual-focus"),children:"✎"}),de&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",(je==null?void 0:je.title)||v.session),"aria-label":p("dual-go-to").replace("{cell}",(je==null?void 0:je.title)||v.session),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),tt(!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${je!=null&&je.present?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(mc,{session:t,node:e,token:i,readonly:a,takeSize:!0,focused:!se,sendRef:We,composerRef:ie,actionRef:Pe,ctrlRef:ft,setCtrlArmed:bt,altRef:St,setAltArmed:Pt,keyboardRef:Kt,onFiles:Oe,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:Y})})]},"pane-main"),wt=v&&l.jsxs("div",{className:`nc-dual-pane${se?" foco":""}${de&&!se?" nascosto":""}`,"data-testid":"pane-side",style:{flexGrow:Se.side,flexBasis:te?0:void 0},onPointerDown:()=>tt(!0),children:[l.jsxs("div",{className:"nc-dual-strip",children:[l.jsx("span",{className:`nc-dual-dot${je!=null&&je.present?" on":""}`,"aria-hidden":"true"}),l.jsx("b",{children:je?je.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:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),pe(Me=>!Me)},children:te?"⇆":"⇅"}),l.jsx("button",{type:"button",title:p("dual-close"),"aria-label":p("dual-close"),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),_==null||_()},children:"✕"})]}),de&&l.jsxs("button",{type:"button",className:"nc-dual-alt",title:p("dual-go-to").replace("{cell}",G),"aria-label":p("dual-go-to").replace("{cell}",G),onPointerDown:oe=>oe.stopPropagation(),onClick:oe=>{oe.stopPropagation(),tt(!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${Q?" on":""}`,"aria-hidden":"true"})]})]}),l.jsx("div",{className:"nc-dual-body",children:l.jsx(mc,{session:v.session,node:v.node,token:i,readonly:a,takeSize:!1,focused:se,sendRef:Z,composerRef:we,actionRef:K,ctrlRef:fe,setCtrlArmed:bt,altRef:Re,setAltArmed:Pt,keyboardRef:Ee,onFiles:_e,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture})})]},"pane-side"),cs=l.jsx("div",{className:"nc-dual-handle","data-testid":"dual-handle",role:"separator","aria-orientation":te?"vertical":"horizontal",onPointerDown:Ks},"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(Tt,{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?`${G} · ${e}`:G,children:G}),g&&g.cell&&g.cell===s?l.jsx("span",{className:`nc-live-host-dot ${ov(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(Tt,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>ye(1),title:p("zoom-in"),"aria-label":p("zoom-in"),children:l.jsx(Tt,{name:"zoomIn",size:18})}),Zt&&l.jsx("button",{type:"button",onClick:Qt,title:p("bar-menu-files"),"aria-label":p("bar-menu-files"),"aria-pressed":(Je==null?void 0:Je.source)===Jt?"true":"false",children:l.jsx(Tt,{name:"folder",size:18})}),ls&&l.jsx("button",{type:"button",onClick:()=>H(oe=>!oe),title:p("bar-menu-keyboard"),"aria-label":p("bar-menu-keyboard"),"aria-pressed":E?"true":"false",children:l.jsx(Tt,{name:"keyboard",size:18})}),M&&pn&&l.jsx("button",{type:"button",onClick:()=>U(oe=>!oe),title:p("bar-menu-panel"),"aria-label":p("bar-menu-panel"),"aria-pressed":N?"true":"false",children:l.jsx(Tt,{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:oe=>{C||T(oe.currentTarget.getBoundingClientRect()),R(Me=>!Me)},children:"⋯"})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[v?l.jsx("div",{className:`nc-dual${te?" row":""}`,ref:Ke,children:de?me?[wt,Kn]:[Kn,wt]:me?[wt,cs,Kn]:[Kn,cs,wt]}):l.jsx(mc,{session:t,node:e,token:i,readonly:a,takeSize:!0,sendRef:We,composerRef:ie,actionRef:Pe,ctrlRef:ft,setCtrlArmed:bt,altRef:St,setAltArmed:Pt,keyboardRef:Kt,onFiles:Oe,fontSize:F,selectionMode:Mt,onSelectionModeChange:Ot,keyboardGesture:x.terminalKeyboardGesture,onRendererChange:Y}),N&&M&&A&&l.jsx(bv,{cellId:A,panelUrl:M,route:e?e.split("/"):[],panelPort:c,token:i,title:G})]}),l.jsx(hI,{onKeyboard:()=>H(oe=>!oe),onCellSwitcher:h,cellSwitcherOpen:f,send:oe=>(se?Z:We).current(oe),action:oe=>(se?K:Pe).current(oe),ctrlArmed:It,onCtrl:an,altArmed:_t,onAlt:Tn,onAltConsume:()=>{const oe=se?Re:St;oe.current=!1,Pt(!1)},onKeyboardKeep:()=>{var oe,Me;return(Me=(oe=se?Ee:Kt).current)==null?void 0:Me.call(oe)},selectionMode:Mt,onSelectionMode:Ot,keepKeyboardClosed:x.keybarKeepsKeyboardClosed,showEnter:x.showKeybarEnter,keybarLayout:x.keybarLayout}),E&&l.jsx(vC,{submitText:oe=>(se?we:ie).current(oe),token:i,session:se?v.session:t,node:se?v.node:e,ownerId:se?v.ownerId:n,readonly:a,keepKeyboardClosedOnVoice:x.voiceKeepsKeyboardClosed}),Je&&($e?l.jsx(Mg,{session:v.session,node:v.node,token:i,filesEvent:Je.ev,onClose:()=>at(null)}):Je.source==="main"?l.jsx(Mg,{session:t,node:e,token:i,filesEvent:Je.ev,onClose:()=>at(null)}):null),C&&(L?l.jsx(Wk,{anchorRect:S,items:mn,onClose:()=>R(!1)}):l.jsx(Mv,{cellName:G,items:mn,onClose:()=>R(!1)}))]})}function eO(){$n();const[t]=w.useState(J4),[e,n]=w.useState(t.token),[s,i]=w.useState(!1);B6(s?"":e);const a=w.useRef(t.token);a.current=e,w.useEffect(()=>{const ke=Ae=>{Ae&&Ae.detail&&Ae.detail.token===a.current&&i(!0)};return window.addEventListener(pm,ke),()=>window.removeEventListener(pm,ke)},[]);const c=w.useCallback((ke,Ae)=>{const Xe=E1(ke,{remember:Ae});if(!Xe.ok||Ae&&Xe.where!=="local")try{window.dispatchEvent(new CustomEvent(mm))}catch{}i(!1),n(ke)},[]),[u,h]=w.useState(t.pair||""),f=w.useCallback(()=>{h("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),g=kk(),[v]=w.useState(()=>JI(typeof location<"u"?location.pathname:"/")),[_,b]=w.useState(v.id),x=_===Vo(null,ni),[L,C]=w.useState(null),R=ke=>{const Ae=Cr(ke);C(Ae?{...Ae,...typeof(ke==null?void 0:ke.cellName)=="string"&&ke.cellName?{cellName:ke.cellName}:{}}:null)},[S,T]=w.useState(null);w.useEffect(()=>{const ke=x4();T(ke&&L&&Gg(ke.main,L)?ke.side:null)},[L]);const E=ke=>{const Ae=L?{session:L.session,node:L.node}:null,Xe=S4(Ae,S,ke);T(Xe),Xe?k4(Ae,Xe):c1()},H=()=>{T(null),c1()},[F,X]=w.useState([]),[V,Y]=w.useState(!0),[ne,G]=w.useState(null),[I,P]=w.useState([]),[B,M]=w.useState([]),[$,A]=w.useState(!1),[j,N]=w.useState(null),[U,D]=w.useState(()=>v.ownerId?uo():g1(v.name)),[W,se]=w.useState(null),[me,pe]=w.useState(null),Ie=ke=>pe(Cr(ke)),[J,te]=w.useState(null),ge=Nv(e,g),Se=w.useMemo(()=>(ge||[]).filter(ke=>ke.instanceId).map(ke=>({instanceId:ke.instanceId,route:ke.route,label:ke.label,status:ke.status,stale:ke.stale===!0,checking:ke.checking===!0})),[ge]),{order:Be}=dh(),je=T4(e,_,U,D,Se,Be),{notice:ze,showActionNotice:Q}=lC(),ve=je.decks;w.useEffect(()=>{const ke=new Map;for(const Ae of ge||[]){const Xe=(Ae.route||[Ae.name]).join("/"),lt=new Set((Ae.sessions||[]).map(Rt=>Rt.name));for(const Rt of Ae.cells||[])!Rt.cell||!Rt.tmuxSession||Rt.cell===Rt.tmuxSession||lt.has(Rt.cell)||ke.set(`${Xe}:${Rt.cell}`,`${Xe}:${Rt.tmuxSession}`)}D(Ae=>AP(Ae,ke))},[ge]),w.useEffect(()=>{je.localNodeId&&v.ownerId&&v.ownerId===je.localNodeId&&D(ke=>ke.columns.some(Ae=>Ae.tiles.length)?ke:g1(v.name))},[je.localNodeId]),w.useEffect(()=>{je.localNodeId&&(KI(Se),je.viewUpdate(ke=>{const Ae=Ua(ke,je.localNodeId,Se);return JSON.stringify(Ae)===JSON.stringify(ke)?ke:Ae}))},[Se,je.localNodeId,je.viewUpdate]);const[Z,we]=w.useState(null),[K,fe]=w.useState(null),Re=w.useRef(0),[Ee,Ke]=w.useState(!1),[Je,at]=w.useState(X4),[Oe,_e]=w.useState(!x),[$e,tt]=w.useState(()=>x?localStorage.getItem(p1)==="1":!0),[Fe,it]=w.useState(!1),[re,le]=w.useState("nodes"),[O,de]=w.useState(!1),[ye,We]=w.useState(""),[ie,Pe]=w.useState(!1),ft=(ke="nodes",Ae=!1,Xe="")=>{le(ke),de(Ae),We(Xe),it(!0)},[It,bt]=w.useState(!1),[St,_t]=w.useState(null),[Pt,Kt]=w.useState({deviceDefault:"",localNodeId:"",localNameDefault:"",deviceNameNeeded:!1,deviceNameSuggestion:""}),[Mt,Ot]=w.useState(""),[an,Tn]=w.useState(!1),[Vt,yn]=w.useState(0),[en,wn]=w.useState({});w.useEffect(()=>{try{localStorage.setItem(zE,String(Je))}catch{}},[Je]),w.useEffect(()=>{try{localStorage.setItem(p1,$e?"1":"")}catch{}},[$e]),w.useEffect(()=>{if(!e)return;let ke=!1;return Promise.all([I1(e),Wn("/api/config",e).then(Ae=>Ae.json())]).then(([Ae,Xe])=>{if(!ke){if(Kt({deviceDefault:Ae.deviceName||"",localNodeId:Ae.nodeId||"",localNameDefault:Ae.localName||"",deviceNameNeeded:Ae.deviceNameNeeded===!0,deviceNameSuggestion:Ae.deviceNameSuggestion||""}),Ot(Ae.deviceName||""),Tn(!!Xe.readonlyDefault),QM(Xe.terminal),yn(Number.isInteger(Xe.panelPort)?Xe.panelPort:0),wn(Xe.nodePanelPorts&&typeof Xe.nodePanelPorts=="object"&&!Array.isArray(Xe.nodePanelPorts)?Xe.nodePanelPorts:{}),Ae.firstRun===!0&&!Xe.readonlyDefault)bt(!0);else if(u)bt(!0);else if(Ae.deviceNameNeeded===!0&&!Xe.readonlyDefault){let lt=!1;try{lt=sessionStorage.getItem("nc_device_ask_later")==="1"}catch{}lt||_t({suggestion:Ae.deviceNameSuggestion||""})}}}).catch(()=>{}),()=>{ke=!0}},[e,u]);const[Ut,Jt]=w.useState({}),Qt=w.useCallback(({route:ke,hostCell:Ae,revision:Xe})=>{const lt=Cs(ke);Jt(Rt=>({...Rt,[lt]:{hostCell:Ae||null,hostLease:null,hostRevision:Number.isInteger(Xe)?Xe:(Rt[lt]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Zt=ke=>{const Ae=Cs(ke),Xe=ke.length?((ge||[]).find(lt=>Cs(Array.isArray(lt.route)?lt.route:[])===Ae)||{}).cells||[]:I;return qa({liveHost:Ut[Ae]||null,cells:Xe,localNodeId:je.localNodeId,ownerId:ke.length?Ae:je.localNodeId})},as=w.useRef(ge);w.useEffect(()=>{as.current=ge},[ge]);const ls=w.useRef(null);ls.current||(ls.current=th());const pn=3500;w.useEffect(()=>{let ke=!1;const Ae=async()=>{const lt=ls.current,Rt=lt.begin();if(Rt!==null)try{const Vs=[[],...(as.current||[]).filter(tn=>tn.kind!=="vl"&&tn.status==="up").map(tn=>Array.isArray(tn.route)&&tn.route.length?tn.route:[tn.name])],Ps=await Promise.all(Vs.map(async tn=>{const _s=Cs(tn);try{const Bt=await Qd(e,tn,{timeoutMs:pn});return[_s,{hostCell:Bt&&typeof Bt.hostCell=="string"?Bt.hostCell:null,hostLease:Bt&&Bt.host&&typeof Bt.host.lease=="string"?Bt.host.lease:null,hostRevision:Number.isInteger(Bt&&Bt.revision)?Bt.revision:0,threadStatus:Bt&&m1.has(Bt.threadStatus)?Bt.threadStatus:"unknown"}]}catch{return[_s,{error:!0}]}}));if(ke||!lt.isCurrent(Rt))return;Jt(tn=>{let _s=!1;const Bt={...tn};for(const Ys of Ps){if(!Ys)continue;const[mo,rr]=Ys;Bt[mo]=rr.error?{...tn[mo]||{},threadStatus:"unknown"}:rr,_s=!0}return _s?Bt:tn})}finally{lt.end(Rt)}};Ae();const Xe=setInterval(Ae,4e3);return()=>{ke=!0,clearInterval(Xe),ls.current.reset()}},[e]),w.useEffect(()=>{if(!g)return;const ke=Ae=>{if(!Ae)return;const Xe=Ae.sessionsError?null:Ae.sessionsJson;Xe&&!Xe.error?(X(Xe.sessions||[]),Y(!0),G(Ae.at)):Y(!1);const lt=ch({fs:Ae.fs,error:Ae.fleetError});lt.kind==="data"?(Va("local",lt.cells),P(lt.cells),M(lt.capabilities),A(!1),N(null)):lt.kind==="stale"?(P(Rt=>Rt.length?Rt:Cv("local")),A(!0),N(null)):(P([]),Va("local",[]),M([]),A(!1),N(lt.reason||""))};return ke(nc([])),yc(e,[],ke)},[g,e]);const mn=w.useCallback(async(ke,Ae=[])=>{const Xe=Cs(Ae),lt=Ut[Xe]&&Ut[Xe].hostRevision||0;try{const Rt=await Zd(e,ke,lt,Ae);return Jt(Vs=>({...Vs,[Xe]:{hostCell:Rt.hostCell||null,hostLease:Rt.host&&typeof Rt.host.lease=="string"?Rt.host.lease:null,hostRevision:Number.isInteger(Rt.revision)?Rt.revision:lt,threadStatus:m1.has(Rt.threadStatus)?Rt.threadStatus:"unknown"}})),{ok:!0}}catch(Rt){return{ok:!1,error:Rt}}},[e,Ut]),Ks=w.useCallback(async(ke,Ae=[])=>{const Xe=await mn(ke,Ae);return Xe.ok||window.alert(p(_m(Xe.error))),Xe.ok},[mn]),Kn=w.useCallback(async(ke=[])=>{const Ae=Cs(ke),Xe=Ut[Ae]&&Ut[Ae].hostRevision||0;try{const lt=await eh(e,Xe,ke);return Jt(Rt=>({...Rt,[Ae]:{hostCell:lt.hostCell||null,hostLease:null,hostRevision:Number.isInteger(lt.revision)?lt.revision:Xe,threadStatus:"unknown"}})),{ok:!0}}catch(lt){return{ok:!1,error:lt}}},[e,Ut]),wt=w.useCallback(async(ke=[])=>{const Ae=await Kn(ke);return Ae.ok||window.alert(p(_m(Ae.error))),Ae.ok},[Kn]);w.useEffect(()=>{let ke=!1;const Ae=()=>{Wn("/api/config",e).then(lt=>lt.json()).then(lt=>{ke||U4(lt.version,lt.uiVersion,"0.9.66")}).catch(()=>{})};Ae();const Xe=setInterval(Ae,6e4);return()=>{ke=!0,clearInterval(Xe)}},[e]);const cs=new Set([...F.map(ke=>ke.name),...ge.flatMap(ke=>ke.sessions.map(Ae=>Ae.key))]),ce=w.useMemo(()=>{const ke=new Map;for(const Ae of F)Ae&&typeof Ae.name=="string"&&Number.isFinite(Ae.created)&&ke.set(Ae.name,Ae.created);return ke},[F]),oe=vs(U),Me=ke=>D(Ae=>{const Xe=kC(ke,je.localNodeId,Se)||ke,lt=Zk(Ae,Xe);return lt===Ae&&vs(Ae).length>=9&&je.setError(p("grid-full")),lt}),Ge=async(ke,Ae=[])=>{try{await ev(e,ke,Ae)}catch{return}const Xe=Ae.length?`${Ae.join("/")}:${ke}`:ke;D(lt=>Ac(lt,Xe)),sc(Ae,e)},mt=async(ke,Ae,Xe=[])=>{try{await P1(e,ke,Ae,Xe)}catch{return}sc(Xe,e)},q=async(ke,Ae,Xe=[])=>{await j1(e,{cell:ke,enabled:!!Ae},Xe),sc(Xe,e)},ae=async ke=>{if(!Z)return;const{cell:Ae}=Z,Xe=Array.isArray(Z.route)?Z.route:[];if(!await Dv({token:e,powerCell:Z,payload:ke,onNotice:Q})){const Rt=ke.action==="up"?!!ke.boot:ke.boot?!1:!!Z.boot;fe({id:++Re.current,cell:Ae,route:Xe,enabled:Rt})}sc(Xe,e)},Le=w.useCallback(ke=>{fe(Ae=>(Ae==null?void 0:Ae.id)===ke?null:Ae)},[]),Qe=async ke=>{if(!(!(ke!=null&&ke.direct)||Ee)){Ke(!0);try{await sv(e,ke.name,ke.tunnelStatus==="up"?"down":"up")}finally{Ke(!1)}}},Te=async(ke,Ae)=>{const Xe=String(Ae||"").trim();return!(ke!=null&&ke.direct)||!Ga(Xe)?!1:(await $1(e,ke.name,Xe),!0)},xt=ke=>{const Ae=ve.find(Xe=>Xe.id===ke);if(!Ae)return!1;try{const Xe=window.open(Mp(Ae,e),"_blank");return Xe&&(Xe.opener=null),!!Xe}catch{return!1}},gt=async ke=>{if(!ke||ke===_)return;const Ae=await je.select(ke),Xe=je.records.find(lt=>lt.id===ke);b(ke),D(Ae),se(null),pe(null);try{history.replaceState(null,"",Mp(Xe||ke,null))}catch{}},Ze=async(ke,Ae)=>{const Xe=await je.add(ke,Ae);await gt(Xe.id)},Nt=async(ke,Ae)=>{const Xe=await je.rename(ke,Ae);if(ke===_){b(Xe.id),D(je.vistaMaterializzata(Xe)),se(null),pe(null);try{history.replaceState(null,"",Mp(Xe,null))}catch{}}},Pn=async ke=>{await je.remove(ke),ke===_&&await gt(je.localMainId)},qe=async(ke,Ae)=>{!Ae||Ae===_||(await je.addTileTo(Ae,ke),D(Xe=>Ac(Xe,ke)))};if(!e||s)return l.jsx(N4,{onSubmit:c,reason:s?"invalid":""});const ot=l.jsxs(l.Fragment,{children:[Fe&&l.jsx(J6,{token:e,initialTab:re,initialLocation:ye,startNewCell:O,onClose:()=>{it(!1),de(!1),We("")}}),It&&l.jsx(Q6,{token:e,initialPair:u,...Pt,onPairDone:f,onDone:()=>bt(!1)}),St&&l.jsx(Z6,{token:e,suggestion:St.suggestion,onSaved:ke=>{Ot(ke),Kt(Ae=>({...Ae,deviceDefault:ke,deviceNameNeeded:!1})),_t(null)},onLater:()=>{try{sessionStorage.setItem("nc_device_ask_later","1")}catch{}_t(null)}}),l.jsx(f4,{token:e})]});if(!g)return J?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(l1,{peer:J,token:e,onBack:()=>te(null)})}),ot]}):L?l.jsxs(l.Fragment,{children:[l.jsx(_1,{session:L.session,node:L.node,ownerId:L.ownerId,cellName:L.cellName,token:e,readonly:an,liveHost:Zt(L.node?L.node.split("/"):[]),panelPort:Ec(L.node?L.node.split("/"):[],en,Vt),side:S,onSideClose:H,onSideGone:H,onBack:()=>C(null),onCellSwitcher:()=>Pe(!0),cellSwitcherOpen:ie}),ie&&l.jsx(_4,{token:e,current:L,localNodeLabel:Mt,panelPort:Vt,nodePanelPorts:en,hostByRoute:Ut,onDesignateCell:mn,onClearHostCell:Kn,onLiveHostApplied:Qt,sideKey:S?Rc(S.node?S.node.split("/"):[],S.session):null,onToggleSide:E,onPick:ke=>{R(ke),Pe(!1)},onClose:()=>Pe(!1)}),ot]}):l.jsxs(l.Fragment,{children:[l.jsx(oI,{onPick:R,token:e,onSettings:ft,onOpenVlSession:te,panelPort:Vt,nodePanelPorts:en,hostByRoute:Ut,onDesignateCell:Ks,onClearHostCell:wt}),ot]});const Wt=x||!Oe;return l.jsxs("div",{className:"nc-workspace",children:[Wt&&l.jsx(jI,{sessions:F,cells:I,localVerified:V,activeSessions:oe,nodeGroups:ge,token:e,onPeekOpen:()=>Pe(!1),overlayOpen:ie,fleetCapabilities:B,fleetStale:$,fleetOff:j,bootSettlement:K,onBootSettlementApplied:Le,localNodeId:je.localNodeId,hostByRoute:Ut,onDesignateCell:Ks,onClearHostCell:wt,onPick:Ie,onAddTile:Me,onPower:we,onBoot:q,onBootError:ke=>je.setError(String((ke==null?void 0:ke.message)||ke)),onNodePower:Qe,onNodeRename:Te,onKill:Ge,onVisibility:mt,onNew:()=>ft("fleet",!0),onSettings:ft,onOpenVlSession:te,width:Je,collapsed:$e,onResize:at,onToggleCollapse:()=>tt(ke=>!ke)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(wD,{decks:ve,currentDeck:_,onCreate:Ze,onRename:Nt,onDelete:Pn,onReorder:je.reorder,onOpenWindow:xt,onNavigate:gt,saveState:je.saveState,error:je.error,conflict:je.conflict,onReloadDeck:je.reloadCurrent,sidebarVisible:Wt,onToggleSidebar:x?null:()=>_e(ke=>!ke)}),ze&&l.jsx("div",{className:"nc-notice nc-deck-notice",role:"status",title:ze,children:ze}),l.jsx(qI,{layout:U,onLayoutChange:D,onResizeEnd:()=>{je.saveNow()},token:e,readonly:an,sessionsAlive:cs,localVerified:V,localIdentities:ce,localVerifiedAt:ne,focusSession:W,onFocus:se,onOpenSingle:Ie,decks:ve,currentDeck:_,onSendToDeck:qe,cells:I,nodeGroups:ge,panelPort:Vt,nodePanelPorts:en})]}),J&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(l1,{peer:J,token:e,onBack:()=>te(null)})}),me&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(_1,{session:me.session,node:me.node,ownerId:me.ownerId,cellName:jc({session:me.session,node:me.node,ownerId:me.ownerId,cells:I,nodeGroups:ge}),token:e,readonly:an,liveHost:Zt(me.node?me.node.split("/"):[]),panelPort:Ec(me.node?me.node.split("/"):[],en,Vt),onBack:()=>pe(null)})}),Z&&l.jsx(Dd,{cell:Z,token:e,route:Array.isArray(Z.route)?Z.route:[],onConfirm:ae,onClose:()=>we(null)}),ot]})}function tO(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 nO(){$n();const t=w.useSyncExternalStore(I4,h1,h1);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:tO(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:$E,children:p("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:V4,children:p("reload")}),l.jsx("button",{className:"nc-update-close",onClick:H4,"aria-label":p("update-dismiss"),title:p("update-dismiss"),children:"×"})]}):null}function sO(){$n();const[t,e]=w.useState(!1);return w.useEffect(()=>{const n=()=>e(!0);return window.addEventListener(mm,n),()=>window.removeEventListener(mm,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}K4();S6();xN.createRoot(document.getElementById("root")).render(l.jsxs(gN.StrictMode,{children:[l.jsx(eO,{}),l.jsx(nO,{}),l.jsx(sO,{})]}));