@mmmbuto/nexuscrew 0.9.32 → 0.9.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,11 @@ All notable changes to NexusCrew are tracked here.
4
4
 
5
5
  ## Unreleased
6
6
 
7
+ ## 0.9.33 — 2026-09-19
8
+
9
+ - **A declared model can be edited without detaching its engine.** `POST /api/fleet/edit-model` patches the non-identity fields of an existing declaration (`contextWindow`, `label`, `maxTokens`, `reasoning`) with the same validation as the declaration itself; an unknown model answers 404, an unknown or invalid field answers 400, and the engine that resolves the model is left untouched — no reload, no restart. The capability is `edit-model`, and the publish guards now also refuse internal node hostnames in the shipped payload and on the public surface.
10
+ - **Node hostnames are no longer publishable.** The payload and public-surface guards now reject the internal node hostnames as whole words (composed forms included) while leaving look-alike words alone, and the guard suite grew to 25 cases covering each name, its extensions, and the fact that test fixtures live outside the shipped package.
11
+
7
12
  ## 0.9.32 — 2026-09-19
8
13
 
9
14
  - **Column widths from another window no longer land on the wrong columns.** When a deck's poll merged a remote layout that had restructured its columns (tiles moved between columns, columns fused or split), a merged column could inherit the width of a local column that no longer existed in that shape — a narrow column could become wide and the widths no longer summed to the layout. A remote column now keeps the locally resized width only when it holds exactly the same set of tiles as a local column; a restructured column keeps the width the other window chose.
@@ -164,4 +164,4 @@ Minimum version required to store current data is: `+H+`.
164
164
  `).filter(s=>s!==""),promptMode:t.promptMode};return t.modelFlag&&(i.model={flag:t.modelFlag,value:t.modelValue||""}),t.promptMode==="flag"&&(i.promptFlag=t.promptFlag),e&&(i.env=Object.fromEntries(t.envRows.filter(s=>!s.remove&&s.key).map(s=>[s.key,s.value]))),Yb(i,t,e)}function kr({children:t,onClose:e,label:n,error:i=""}){const s=k.useRef(null),a=k.useRef(null),c=k.useRef(e);return c.current=e,k.useEffect(()=>{const d=document.activeElement,h=s.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})}),y=_=>{var C;if(_.key==="Escape"){_.preventDefault(),(C=c.current)==null||C.call(c);return}if(_.key!=="Tab")return;const w=f();if(!w.length){_.preventDefault(),h==null||h.focus();return}const S=w[0],N=w[w.length-1];_.shiftKey&&document.activeElement===S?(_.preventDefault(),N.focus()):!_.shiftKey&&document.activeElement===N&&(_.preventDefault(),S.focus())};return document.addEventListener("keydown",y),()=>{cancelAnimationFrame(g),document.removeEventListener("keydown",y),d&&d.isConnected&&typeof d.focus=="function"&&d.focus({preventScroll:!0})}},[]),k.useEffect(()=>{i&&requestAnimationFrame(()=>{var d;return(d=a.current)==null?void 0:d.scrollIntoView({block:"nearest"})})},[i]),l.jsx("div",{className:"nc-fleet-modal",role:"presentation",onMouseDown:d=>{d.target===d.currentTarget&&e()},children:l.jsxs("div",{ref:s,className:"nc-fleet-modal-dialog",role:"dialog","aria-modal":"true","aria-label":n||m("settings"),tabIndex:-1,children:[t,i&&l.jsx("div",{ref:a,className:"nc-err nc-fleet-modal-error",role:"alert","aria-live":"assertive",children:i})]})})}function Xf({token:t,targets:e=[],readonly:n=!1,onPower:i,onImport:s}){const[a,c]=k.useState([]),[d,h]=k.useState(0);k.useEffect(()=>{let C=!0;async function E(){const M=[{route:[],label:m("local")}].concat((e||[]).map(U=>({route:Array.isArray(U.route)?U.route:[],label:U.label||(U.route||[]).join(" › ")}))),T=await Promise.all(M.map(async U=>{const z={...U,available:!1,readonly:!1,capabilities:[],provider:null,cells:[],unmanaged:[],err:""};try{const V=await Dr(t,U.route);z.available=!!V.available,z.capabilities=V.capabilities||[],z.provider=V.provider||null,z.cells=(V.cells||[]).map(J=>({...J,route:U.route}));try{z.readonly=!!(await bm(t,U.route)).readonlyDefault}catch{}try{const J=await wm(t,U.route),q=new Set(z.cells.map(X=>X.tmuxSession).filter(Boolean));z.unmanaged=(J.sessions||[]).filter(X=>X&&!q.has(X.name))}catch{}}catch(V){z.err=String(V&&V.message||V)}return z}));C&&c(T)}E();const x=setInterval(E,6e3);return()=>{C=!1,clearInterval(x)}},[t,e,d]);const f=(C,E)=>Array.isArray(C.capabilities)&&C.capabilities.includes(E)&&!n&&!C.readonly,g=()=>h(C=>C+1),y=(C,E)=>{i&&i({...C,route:E})},_=(C,E)=>{i&&i({...C,route:E})},w=async(C,E)=>{try{await fl(t,C.cell,E)}catch{}g()},S=async(C,E)=>{if(window.confirm(m("fleet-remove-cell").replace("{id}",C.cell))){try{await g0(t,C.cell,!0,E)}catch{}g()}},N=async(C,E)=>{if(window.confirm(m("terminate-confirm").replace("{name}",C.name))){try{await _m(t,C.name,E)}catch{}g()}};return l.jsxs("div",{className:"nc-fleet-inventory",children:[l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:m("fleet-inventory")}),l.jsx("small",{children:m("fleet-inventory-help")})]}),a.map(C=>{const E=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} ${m("fleet-cells")} · ${C.unmanaged.length} ${m("fleet-tmux")}`:C.err||m("fleet-not-available")})]}),C.cells.map(x=>l.jsxs("div",{className:"nc-fleet-item nc-fleet-cell",children:[l.jsxs("span",{children:[l.jsx("b",{children:x.cell}),l.jsx("small",{children:`${x.engine||""}${x.key?`·${x.key}`:""}${x.active?"":` · ${m("cell-off")}`}`})]}),l.jsxs("span",{className:"nc-fleet-cell-actions",children:[x.active&&f(C,"down")&&l.jsx("button",{className:"nc-btn ghost",title:m("power-off"),onClick:()=>_(x,C.route),children:m("stop")}),!x.active&&f(C,"up")&&l.jsx("button",{className:"nc-btn ghost",title:m("power-on"),onClick:()=>y(x,C.route),children:m("start")}),f(C,"restart")&&x.active&&l.jsx("button",{className:"nc-btn ghost",title:m("restart"),onClick:()=>w(x,C.route),children:m("restart")}),f(C,"remove")&&l.jsx("button",{className:"nc-btn danger",title:m("delete"),onClick:()=>S(x,C.route),children:"×"})]})]},`${E}:${x.cell}`)),C.unmanaged.map(x=>l.jsxs("div",{className:"nc-fleet-item nc-fleet-unmanaged",children:[l.jsxs("span",{children:[l.jsx("b",{children:x.name}),l.jsx("small",{children:m("fleet-tmux")})]}),l.jsxs("span",{className:"nc-fleet-cell-actions",children:[f(C,"import")&&s&&l.jsx("button",{className:"nc-btn ghost",title:m("import-as-cell"),onClick:()=>s(x,C.route),children:m("import-as-cell")}),l.jsx("button",{className:"nc-btn danger",title:m("terminate"),onClick:()=>N(x,C.route),children:"×"})]})]},`${E}:u:${x.name}`)),C.available&&C.cells.length===0&&C.unmanaged.length===0&&l.jsx("div",{className:"nc-empty",children:m("fleet-inventory-empty")})]},E)})]})}function qP({cells:t=[],engines:e=[],models:n=[],busy:i,canRestore:s=!1,onRestore:a,onClose:c}){const[d,h]=k.useState("export"),[f,g]=k.useState([]),[y,_]=k.useState(()=>new Set(t.map(O=>O.id))),[w,S]=k.useState(()=>new Set(e.map(O=>O.id))),[N,C]=k.useState([]),[E,x]=k.useState([]),[M,T]=k.useState(""),U=new Set(e.map(O=>O.id)),z=new Set(t.map(O=>O.id)),V=(O,R)=>O(A=>{const j=new Set(A);return j.has(R)?j.delete(R):j.add(R),j}),J=()=>{const O=OP(t,y,e,w,new Date,n);if(O.ok===!1){T(m(`fleet-backup-${O.error}`));return}const R=t.filter(W=>y.has(W.id)).length,A=e.filter(W=>w.has(W.id)).length;if(O.cells.length!==R){T(m("fleet-backup-invalid-cell"));return}if(O.engines.length!==A){T(m("fleet-backup-invalid-engine"));return}if(!O.cells.length&&!O.engines.length){T(m("fleet-backup-select-one"));return}const j=new Blob([`${JSON.stringify(O,null,2)}
165
165
  `],{type:"application/json"}),F=URL.createObjectURL(j),$=document.createElement("a");$.href=F,$.download=`nexuscrew-fleet-${new Date().toISOString().slice(0,10)}.json`,document.body.appendChild($),$.click(),$.remove(),setTimeout(()=>URL.revokeObjectURL(F),0),T("")},q=async O=>{if(T(""),C([]),x([]),!!O){if(O.size>1024*1024){T(m("fleet-backup-too-large"));return}try{const R=$P(await O.text());if(!R.ok){T(m(`fleet-backup-${R.error}`));return}g(Array.isArray(R.models)?R.models:[]);const A=new Set(R.engines.map(j=>j.id));x(R.engines.map(j=>({engine:j,exists:U.has(j.id),selected:!U.has(j.id)}))),C(R.cells.map(j=>{const F=U.has(j.engine)||A.has(j.engine),$=z.has(j.id);return{cell:j,engine:F?j.engine:"",selected:F&&!$,exists:$}}))}catch(R){T(String(R.message||R))}}},X=(O,R)=>C(A=>A.map((j,F)=>F===O?{...j,...R}:j)),H=(O,R)=>x(A=>A.map((j,F)=>F===O?{...j,...R}:j)),P=new Set([...U,...E.filter(O=>O.selected).map(O=>O.engine.id)]),L=N.filter(O=>O.selected&&O.engine&&P.has(O.engine)),D=E.filter(O=>O.selected),I=[...new Map([...e.map(O=>[O.id,O.label||O.id]),...E.filter(O=>O.selected).map(O=>[O.engine.id,O.engine.label||O.engine.id])]).entries()];return l.jsxs("div",{className:"nc-set-form nc-fleet-form nc-backup-dialog",children:[l.jsx("b",{children:m("fleet-backup")}),l.jsx("small",{children:m("fleet-backup-help")}),l.jsxs("div",{className:"nc-set-tabs nc-backup-tabs",children:[l.jsx("button",{type:"button",className:`nc-set-tabbtn${d==="export"?" on":""}`,onClick:()=>{h("export"),T("")},children:m("fleet-backup-export")}),l.jsx("button",{type:"button",className:`nc-set-tabbtn${d==="import"?" on":""}`,disabled:!s,title:s?"":m("fleet-backup-restore-unavailable"),onClick:()=>{h("import"),T("")},children:m("fleet-backup-import")})]}),d==="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(O=>O.id))),S(new Set(e.map(O=>O.id)))},children:m("select-all")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{_(new Set),S(new Set)},children:m("select-none")})]}),l.jsxs("div",{className:"nc-backup-list",children:[l.jsx("b",{children:m("fleet-engines")}),e.map(O=>{var R;return l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:w.has(O.id),onChange:()=>V(S,O.id)}),l.jsxs("span",{children:[l.jsx("b",{children:O.label||O.id}),l.jsxs("small",{children:[O.id,(R=O.envKeys)!=null&&R.length?` · ${O.envKeys.length} ${m("fleet-backup-env-names")}`:""]})]})]},O.id)}),l.jsx("b",{children:m("fleet-cells")}),t.map(O=>l.jsxs("label",{className:"nc-check nc-backup-row",children:[l.jsx("input",{type:"checkbox",checked:y.has(O.id),onChange:()=>V(_,O.id)}),l.jsxs("span",{children:[l.jsx("b",{children:O.id}),l.jsxs("small",{children:[O.engine," · ",m("fleet-system-prompt")," ",(O.prompt||"").length," ",m("characters")]})]})]},O.id)),!t.length&&!e.length&&l.jsx("div",{className:"nc-empty",children:m("fleet-backup-empty")})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:!y.size&&!w.size,onClick:J,children:m("fleet-backup-download")})]})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{type:"file",accept:"application/json,.json",disabled:i,onChange:O=>q(O.target.files&&O.target.files[0])}),l.jsx("small",{children:m("fleet-backup-import-help")}),!!(N.length||E.length)&&l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{x(O=>O.map(R=>({...R,selected:!0}))),C(O=>O.map(R=>({...R,selected:!!R.engine})))},children:m("select-all")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>{x(O=>O.map(R=>({...R,selected:!1}))),C(O=>O.map(R=>({...R,selected:!1})))},children:m("select-none")})]}),l.jsxs("div",{className:"nc-backup-list",children:[!!E.length&&l.jsx("b",{children:m("fleet-engines")}),E.map((O,R)=>{var A;return l.jsx("div",{className:"nc-backup-import-row",children:l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:O.selected,onChange:j=>H(R,{selected:j.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:O.engine.label||O.engine.id}),l.jsxs("small",{children:[O.engine.id," · ",O.exists?m("fleet-backup-overwrite"):m("fleet-backup-new"),(A=O.engine.envKeys)!=null&&A.length?` · ${m("fleet-backup-env-values-required")}`:""]})]})]})},O.engine.id)}),!!N.length&&l.jsx("b",{children:m("fleet-cells")}),N.map((O,R)=>l.jsxs("div",{className:"nc-backup-import-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:O.selected,disabled:!O.engine||!P.has(O.engine),onChange:A=>X(R,{selected:A.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:O.cell.id}),l.jsxs("small",{children:[O.exists?m("fleet-backup-overwrite"):m("fleet-backup-new")," · ",m("fleet-system-prompt")," ",O.cell.systemPrompt.length," ",m("characters")]})]})]}),l.jsxs("select",{value:O.engine,onChange:A=>X(R,{engine:A.target.value,selected:!!A.target.value}),children:[l.jsx("option",{value:"",children:m("fleet-backup-engine-missing")}),I.map(([A,j])=>l.jsx("option",{value:A,children:j},A))]})]},O.cell.id))]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:c,children:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:i||!L.length&&!D.length,onClick:()=>a({engineRows:E,cellRows:N,models:f}),children:m("fleet-backup-restore")})]})]}),M&&l.jsx("div",{className:"nc-err",children:M})]})}function KP({state:t,setState:e,busy:n,onSave:i,catalog:s}){var E;const a=t.form,c=x=>e({...t,form:{...a,...x}}),d=a.envRows||[],h=[...new Map(s.map(x=>[x.client,x.clientLabel||x.client])).entries()],f=s.filter(x=>x.client===a.client),g=Ml(s,a),y=typeof(g==null?void 0:g.credentialEnv)=="string"?g.credentialEnv:"",_=Array.isArray(g==null?void 0:g.credentialUsedBy)?g.credentialUsedBy:[],w=(g==null?void 0:g.credentialSource)||"missing",S=!!(g!=null&&g.credentialEnv)||a.credentialProfile==="a"||a.credentialProfile==="p",N=!!y&&t.mode==="new"&&(g==null?void 0:g.authConfigured)!==!0&&!a.credentialValue&&!a.allowMissingCredential,C=x=>{x&&c({client:x.client,provider:x.provider,credentialProfile:x.credentialProfile||"",managedModel:x.model||"",protocol:x.protocol||"",permissionPolicy:x.permissionPolicyDefault||"standard",credentialSourcePolicy:"auto",rc:!!x.rc,displayName:x.custom?m("fleet-custom-provider-default"):"",baseUrl:x.custom?"":x.endpoint||"",envKey:x.defaultEnvKey||"",providerId:"nexuscrew-custom",credentialValue:"",credentialReveal:!1,allowMissingCredential:!1,...t.mode==="new"?{id:x.id,label:""}:{}})};return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsx("b",{children:t.mode==="new"?m("fleet-new-engine"):`${m("edit")} ${a.id}`}),l.jsx("input",{value:a.id,disabled:t.mode!=="new",placeholder:"id",onChange:x=>c({id:x.target.value})}),l.jsx("input",{value:a.label,placeholder:m("label"),onChange:x=>c({label:x.target.value})}),l.jsxs("select",{value:a.kind,disabled:t.mode!=="new",onChange:x=>c({kind:x.target.value}),children:[l.jsx("option",{value:"managed",children:m("fleet-managed")}),l.jsx("option",{value:"custom",children:m("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:x=>C(s.find(M=>M.client===x.target.value&&M.default)||s.find(M=>M.client===x.target.value)),children:h.map(([x,M])=>l.jsx("option",{value:x,children:M},x))}),l.jsx("select",{value:((E=Ml(s,a))==null?void 0:E.id)||"",disabled:t.mode!=="new",onChange:x=>C(s.find(M=>M.id===x.target.value)),children:f.map(x=>l.jsx("option",{value:x.id,children:x.label},x.id))})]}),a.client!=="shell"&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.managedModel,list:"nc-managed-models",placeholder:m(g!=null&&g.requiresModel?"fleet-model-required":"fleet-model-default"),onChange:x=>c({managedModel:x.target.value})}),l.jsx("datalist",{id:"nc-managed-models",children:[...(g==null?void 0:g.models)||[],...a.modelOptions||[]].filter((x,M,T)=>x&&T.indexOf(x)===M).map(x=>l.jsx("option",{value:x},x))})]}),g!=null&&g.supportsUnsafe?l.jsxs("select",{value:a.permissionPolicy,onChange:x=>c({permissionPolicy:x.target.value}),children:[l.jsx("option",{value:"standard",children:m("fleet-standard-permissions")}),l.jsx("option",{value:"unsafe",children:m("fleet-unsafe-permissions")})]}):l.jsx("small",{children:m("fleet-standard-permissions")}),(g==null?void 0:g.supportsUnsafe)&&a.permissionPolicy==="unsafe"&&l.jsx("small",{className:"nc-err",children:m("fleet-unsafe-warning")}),S&&l.jsxs("select",{"aria-label":m("fleet-credential-source-policy"),value:a.credentialSourcePolicy||"auto",onChange:x=>c({credentialSourcePolicy:x.target.value}),children:[l.jsx("option",{value:"auto",children:m("fleet-credential-source-policy-auto")}),l.jsx("option",{value:"nexuscrew-store",children:m("fleet-credential-source-policy-nexuscrew-store")}),l.jsx("option",{value:"environment",children:m("fleet-credential-source-policy-environment")})]}),(g==null?void 0:g.credentialEnv)===!0&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.envKey,placeholder:m("fleet-api-key-env"),onChange:x=>c({envKey:x.target.value})}),l.jsx("small",{children:m("fleet-custom-secret-help")})]}),y&&l.jsxs("section",{className:"nc-fleet-key","aria-label":m("fleet-key-section"),children:[l.jsxs("div",{className:"nc-fleet-key-head",children:[l.jsx("b",{children:m("fleet-key-section")}),l.jsx("span",{children:m(`fleet-credential-source-${w}`)})]}),l.jsxs("label",{className:"nc-field",children:[m("fleet-key-variable"),l.jsx("input",{value:y,readOnly:!0,"aria-label":m("fleet-key-variable")})]}),l.jsx("small",{children:_.length?m("fleet-key-used-by").replace("{engines}",_.join(", ")):m("fleet-key-used-by-none")}),_.length>0&&l.jsx("small",{children:m("fleet-key-shared-impact").replace("{key}",y).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":m("fleet-key-value").replace("{key}",y),autoComplete:"new-password",spellCheck:!1,autoCapitalize:"none",autoCorrect:"off",placeholder:g!=null&&g.authConfigured||t.mode==="edit"?m("fleet-key-blank-keeps"):m("fleet-key-enter"),onChange:x=>c({credentialValue:x.target.value,allowMissingCredential:x.target.value?!1:a.allowMissingCredential})}),l.jsx("button",{type:"button",className:"nc-btn ghost","aria-label":m(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal"),onClick:()=>c({credentialReveal:!a.credentialReveal}),children:m(a.credentialReveal?"fleet-key-hide":"fleet-key-reveal")})]}),l.jsx("small",{children:m("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:x=>c({allowMissingCredential:x.target.checked})}),m("fleet-key-create-missing")]}),(g==null?void 0:g.notice)&&l.jsx("small",{className:"nc-fleet-provider-notice",children:m(`fleet-provider-notice-${g.notice}`)})]}),(g==null?void 0:g.notice)&&!y&&l.jsx("small",{className:"nc-fleet-provider-notice",children:m(`fleet-provider-notice-${g.notice}`)}),a.provider==="custom"&&l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.displayName,placeholder:m("fleet-provider-display"),onChange:x=>c({displayName:x.target.value})}),l.jsx("input",{value:a.baseUrl,placeholder:"https://api.example.com/v1",onChange:x=>c({baseUrl:x.target.value})}),((g==null?void 0:g.protocols)||[]).length>1&&l.jsx("select",{value:a.protocol,onChange:x=>c({protocol:x.target.value}),children:g.protocols.map(x=>l.jsx("option",{value:x,children:x},x))}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:a.envKey,placeholder:m("fleet-api-key-env"),onChange:x=>c({envKey:x.target.value})}),l.jsx("input",{value:a.providerId,placeholder:m("fleet-provider-id"),onChange:x=>c({providerId:x.target.value})})]}),l.jsxs("small",{children:[a.protocol," · ",m("fleet-custom-secret-help")]})]}),l.jsx("small",{children:m(a.client==="shell"?"fleet-shell-engine-help":"fleet-managed-help")})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{value:a.command,placeholder:m("command-path"),onChange:x=>c({command:x.target.value})}),l.jsx("textarea",{value:a.argsText,placeholder:m("args-lines"),onChange:x=>c({argsText:x.target.value})}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:a.rc,onChange:x=>c({rc:x.target.checked})})," ",m("fleet-remote-control")]}),l.jsxs("select",{value:a.promptMode,onChange:x=>c({promptMode:x.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:x=>c({promptFlag:x.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:a.modelFlag,placeholder:"model flag",onChange:x=>c({modelFlag:x.target.value})}),l.jsx("input",{value:a.modelValue,placeholder:"model default",onChange:x=>c({modelValue:x.target.value})})]}),l.jsx("small",{children:m("env-write-only")}),d.map((x,M)=>l.jsxs("div",{className:"nc-fleet-env",children:[l.jsx("input",{value:x.key,disabled:x.configured,placeholder:"ENV_KEY",onChange:T=>{const U=d.slice();U[M]={...x,key:T.target.value},c({envRows:U})}}),l.jsx("input",{type:"password",value:x.value,placeholder:x.configured?"•••••• (unchanged)":"value",onChange:T=>{const U=d.slice();U[M]={...x,value:T.target.value},c({envRows:U})}}),l.jsx("button",{className:"nc-btn danger",onClick:()=>c({envRows:d.filter((T,U)=>U!==M)}),children:"×"})]},`${x.key}-${M}`)),l.jsx("button",{className:"nc-btn ghost",onClick:()=>c({envRows:[...d,{key:"",value:"",configured:!1}]}),children:"+ env"})]}),l.jsx("input",{value:a.panelUrl||"",maxLength:512,placeholder:m("fleet-panel-url"),onChange:x=>c({panelUrl:x.target.value})}),l.jsx("small",{children:m("fleet-panel-url-help")}),a.panelUrl&&!fg(a.panelUrl)&&l.jsx("small",{className:"nc-err",children:m("fleet-panel-url-invalid")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>e(null),children:m("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:n||!a.id||N||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:i,children:m("save")})]})]})}function VP({state:t,setState:e,busy:n,onSave:i,onTest:s,profiles:a=[],canTest:c=!0}){const[d,h]=k.useState(null),[f,g]=k.useState(!1),y=t.form,_=C=>e({...t,form:{...y,...C}}),w=/^[^\x00-\x1f\x7f]{1,128}$/.test(y.id||""),S=!!(y.id||"").trim()&&!!(y.engine||"").trim()&&w,N=async()=>{h(null),g(!0);try{h(await s(y.engine,y.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:[m("model-editor-engine"),l.jsxs("select",{value:y.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:[m("model-editor-id"),l.jsx("input",{value:y.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:m("model-editor-id-help")}),l.jsxs("label",{className:"nc-field",children:[m("model-editor-context"),l.jsx("input",{inputMode:"numeric",value:y.contextWindow||"",disabled:n,onChange:C=>_({contextWindow:C.target.value.replace(/[^0-9]/g,"").slice(0,9)})})]}),l.jsxs("label",{className:"nc-field",children:[m("model-editor-max-tokens"),l.jsx("input",{inputMode:"numeric",value:y.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:y.reasoning===!0,disabled:n,onChange:C=>_({reasoning:C.target.checked})})," ",m("model-editor-reasoning")]}),l.jsxs("div",{className:"nc-set-row",children:[c&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||f||!S,onClick:N,children:m(f?"model-test-running":"model-test")}),d&&l.jsxs("span",{className:`nc-model-test ${d.outcome}`,children:[m(`model-test-${d.outcome}`),d.outcome==="ok"&&Number.isInteger(d.latencyMs)?` · ${d.latencyMs}ms`:""]})]}),d&&d.detail&&l.jsx("small",{className:"nc-set-hint",children:d.detail}),d&&d.outcome==="unverified"&&l.jsx("small",{className:"nc-set-hint",children:m("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:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||!S,onClick:()=>i(y),children:m("save")})]})]})}function YP({token:t,route:e,targets:n=[],location:i,setLocation:s,state:a,setState:c,engines:d,mcpServers:h=[],managedCatalog:f=[],busy:g,onSave:y}){var D,I,O;const[_,w]=k.useState(null),[S,N]=k.useState(""),C=a.form,E=R=>c({...a,form:{...C,...R}}),x=d.find(R=>R.id===C.engine),M=((D=x==null?void 0:x.managed)==null?void 0:D.client)==="shell",T=((I=x==null?void 0:x.managed)==null?void 0:I.client)||"",U=((O=f.find(R=>R.client===T))==null?void 0:O.mcpManaged)!==!1,z=R=>{var F,$,W,ce;const A=d.find(ge=>ge.id===R),j={...C.commands||{}};((F=x==null?void 0:x.managed)==null?void 0:F.client)==="shell"&&(C.command?j[C.engine]=C.command:delete j[C.engine]),E({engine:R,model:(($=C.models)==null?void 0:$[R])||((W=A==null?void 0:A.managed)==null?void 0:W.model)||((ce=A==null?void 0:A.model)==null?void 0:ce.value)||"",commands:j,command:j[R]||""})},V=R=>{const A={...C.commands||{}};R?A[C.engine]=R:delete A[C.engine],E({command:R,commands:A})},J=M&&/[|&;<>()`$*?{}\[\]~]/.test(C.command||""),q=[...new Set([...h||[],...Array.isArray(C.mcp)?C.mcp:[]])].sort(),X=Array.isArray(C.mcp)?C.mcp.length?"some":"none":"all",H=R=>{var A;return E({mcp:R==="all"?void 0:R==="none"?[]:(A=C.mcp)!=null&&A.length?C.mcp:[...q]})},P=R=>{const A=Array.isArray(C.mcp)?C.mcp:[];E({mcp:A.includes(R)?A.filter(j=>j!==R):[...A,R].sort()})},L=async R=>{try{const A=await ym(t,R,e);w(A),E({cwd:A.path}),N("")}catch(A){N(String(A.message||A))}};return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsx("b",{children:a.mode==="new"?m("fleet-new-cell"):`${m("edit")} ${C.id}`}),a.mode==="new"&&l.jsxs("label",{className:"nc-field",children:[m("location"),l.jsx("span",{className:"nc-req",children:" *"}),l.jsxs("select",{value:i,onChange:R=>{s(R.target.value),E({engine:""})},children:[l.jsx("option",{value:"",children:m("local")}),n.map(R=>l.jsxs("option",{value:R.route.join("/"),disabled:R.status&&R.status!=="up",children:[R.label,R.status&&R.status!=="up"?` · ${m("node-offline")}`:""]},R.route.join("/")))]})]}),l.jsx("input",{value:C.id,disabled:a.mode!=="new",placeholder:"id",onChange:R=>E({id:R.target.value})}),l.jsx("input",{value:C.label||"",maxLength:64,placeholder:m("fleet-cell-label"),onChange:R=>E({label:R.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:C.cwd,placeholder:m("cwd"),onChange:R=>E({cwd:R.target.value})}),l.jsx("button",{className:"nc-btn ghost",onClick:()=>_?w(null):L(C.cwd),children:m("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:()=>L(_.parent),children:["↑ ",m("fs-parent")]}),(_.dirs||[]).map(R=>l.jsxs("button",{className:"nc-fs-item",onClick:()=>L(`${_.path.replace(/\/$/,"")}/${R}`),children:["📁 ",R]},R))]})]}),S&&l.jsx("div",{className:"nc-err",children:S}),l.jsx("select",{value:C.engine,onChange:R=>z(R.target.value),children:d.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:!!C.boot,onChange:R=>E({boot:R.target.checked})})," ",m("fleet-boot")]}),l.jsx("input",{value:C.panelUrl||"",maxLength:512,placeholder:m("fleet-panel-url"),onChange:R=>E({panelUrl:R.target.value})}),l.jsx("small",{children:m("fleet-panel-url-help")}),C.panelUrl&&!fg(C.panelUrl)&&l.jsx("small",{className:"nc-err",children:m("fleet-panel-url-invalid")}),M?l.jsxs(l.Fragment,{children:[l.jsx("input",{value:C.command||"",maxLength:4096,placeholder:m("fleet-shell-command-placeholder"),onChange:R=>V(R.target.value)}),l.jsx("small",{children:C.command?m("fleet-shell-command-help"):m("fleet-shell-interactive")}),J&&l.jsx("small",{className:"nc-note",children:m("fleet-shell-command-metachar")})]}):l.jsxs(l.Fragment,{children:[l.jsx("input",{value:C.model||"",list:"nc-cell-models",placeholder:m("fleet-model-override"),onChange:R=>E({model:R.target.value})}),l.jsx("datalist",{id:"nc-cell-models",children:((x==null?void 0:x.availableModels)||[]).map(R=>l.jsx("option",{value:R},R))}),l.jsx("textarea",{value:C.prompt||"",placeholder:m("cell-prompt"),onChange:R=>E({prompt:R.target.value})}),l.jsx("small",{children:m("cell-prompt-help")}),l.jsxs("label",{className:"nc-field",children:[m("cell-mcp"),l.jsxs("select",{value:X,onChange:R=>H(R.target.value),children:[l.jsx("option",{value:"all",children:m("cell-mcp-all")}),l.jsx("option",{value:"none",children:m("cell-mcp-none")}),l.jsx("option",{value:"some",children:m("cell-mcp-some")})]})]}),!U&&l.jsx("small",{className:"nc-note",children:m("cell-mcp-inert")}),X==="some"&&l.jsx("div",{className:"nc-fleet-mcp-list",children:q.map(R=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:(C.mcp||[]).includes(R),onChange:()=>P(R)})," ",R]},R))}),l.jsx("small",{children:m("cell-mcp-help")})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>c(null),children:m("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:g||!C.id||!C.cwd||!C.engine,onClick:y,children:m("save")})]})]})}function Gb({token:t,route:e=[],state:n,setState:i,busy:s,onSave:a}){const[c,d]=k.useState(null),[h,f]=k.useState([]),[g,y]=k.useState(""),_=Array.isArray(e)?e.join("/"):"";k.useEffect(()=>{let E=!0;return Yu(t,_?_.split("/"):[]).then(x=>{E&&(f(x.engines||[]),y(""))}).catch(x=>{E&&(f([]),y(String(x.message||x)))}),()=>{E=!1}},[t,_]);const w=n.form,S=E=>i({...n,form:{...w,...E}}),N=async E=>{try{const x=await ym(t,E,e);d(x),S({cwd:x.path})}catch{}},C=!w.id&&w.tmuxSession?w.tmuxSession.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,32):w.id;return l.jsxs("div",{className:"nc-set-form nc-fleet-form",children:[l.jsxs("b",{children:[m("import-as-cell")," · ",w.tmuxSession]}),l.jsx("small",{children:m("import-help")}),l.jsx("input",{value:w.tmuxSession,disabled:!0,placeholder:"tmux session",readOnly:!0}),l.jsx("input",{value:w.id,placeholder:m("name"),onChange:E=>S({id:E.target.value})}),l.jsxs("div",{className:"nc-fleet-pair",children:[l.jsx("input",{value:w.cwd,placeholder:m("cwd"),onChange:E=>S({cwd:E.target.value})}),l.jsx("button",{className:"nc-btn ghost",type:"button",onClick:()=>c?d(null):N(w.cwd),children:m("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:()=>N(c.parent),children:["↑ ",m("fs-parent")]}),(c.dirs||[]).map(E=>l.jsxs("button",{className:"nc-fs-item",onClick:()=>N(`${c.path.replace(/\/$/,"")}/${E}`),children:["📁 ",E]},E))]})]}),l.jsxs("select",{value:w.engine,onChange:E=>S({engine:E.target.value}),children:[l.jsx("option",{value:"",children:m("import-engine-required")}),h.map(E=>l.jsx("option",{value:E.id,children:E.label},E.id))]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:!!w.boot,onChange:E=>S({boot:E.target.checked})})," ",m("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:()=>i(null),children:m("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:s||!w.tmuxSession||!w.engine||!h.length,onClick:a,children:m(C?"import-as-cell":"save")})]})]})}function lu(t){const e=ro(t);return e===null?`~/${t}`:e?`~/${e}`:"~"}function GP(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 XP({token:t,route:e,cell:n,busy:i=!1,onSaved:s,onClose:a}){const[c,d]=k.useState(""),[h,f]=k.useState(null),[g,y]=k.useState(!1),[_,w]=k.useState(""),S=typeof(n==null?void 0:n.cwdSuggestion)=="string"&&ro(n.cwdSuggestion)!==null?ro(n.cwdSuggestion):null,[N,C]=k.useState(S),E=n==null?void 0:n.id,x=i||g,M=async q=>{const X=ro(q);if(X===null){f({rel:"",dirs:[],loading:!1,err:m("fleet-cwd-repair-invalid")});return}f({rel:X,dirs:[],loading:!0,err:""});try{const H=await ym(t,X,e),P=GP(H);f({rel:P,dirs:Array.isArray(H.dirs)?H.dirs:[],loading:!1,err:""})}catch(H){f({rel:X,dirs:[],loading:!1,err:String(H&&H.message||H)})}},T=q=>{if(!h)return;const X=h.rel?`${h.rel}/${q}`:q;M(X)},U=()=>{h!=null&&h.rel&&M(h.rel.split("/").slice(0,-1).join("/"))},z=()=>{h&&(d(h.rel||""),f(null),w(""),C(null))},V=()=>{N!==null&&(d(N),C(null),w(""))},J=async()=>{if(x)return;const q=ro(c);if(q===null){w(m("fleet-cwd-repair-invalid"));return}const X=lu(q);let H=!0;try{H=window.confirm(m("fleet-cwd-repair-confirm").replace("{id}",String(E||"")).replace("{path}",X))}catch{H=!1}if(H){y(!0),w(""),C(null);try{const P=await m0(t,E,{cwdRel:q},e);s==null||s(P)}catch(P){const L=P&&P.data||{};if(L.code==="unportable-cwd"){w(m("fleet-cwd-repair-unportable"));const D=Array.isArray(L.cells)?L.cells.find(O=>O&&O.id===E):null,I=D&&typeof D.suggestion=="string"?D.suggestion:null;I!==null&&ro(I)!==null&&C(I)}else w(String(P&&P.message||P))}finally{y(!1)}}};return l.jsxs("div",{className:"nc-set-form nc-fleet-form nc-cwd-repair",children:[l.jsx("b",{children:m("fleet-cwd-repair-title").replace("{id}",String(E||""))}),l.jsx("small",{className:"nc-set-info",children:m("fleet-cwd-repair-help")}),l.jsx("small",{className:"nc-cwd-no-source",children:m("fleet-cwd-repair-no-source-path")}),l.jsxs("label",{className:"nc-field",children:[m("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:m("fleet-cwd-repair-placeholder"),autoComplete:"off",spellCheck:"false",autoCapitalize:"none",onChange:q=>d(q.target.value)}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:x,onClick:()=>h?f(null):M(""),children:m(h?"close":"fleet-cwd-repair-browse")})]})]}),l.jsx("div",{className:"nc-cwd-preview",children:m("fleet-cwd-repair-preview").replace("{path}",lu(c))}),h&&l.jsxs("div",{className:"nc-fs",children:[l.jsx("div",{className:"nc-fs-path",children:lu(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:U,children:["↑ ",m("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:m("fleet-cwd-repair-fs-empty")}),!h.loading&&h.dirs.map(q=>l.jsxs("button",{type:"button",className:"nc-fs-item",onClick:()=>T(q),children:["📁 ",q]},q))]}),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:x||h.loading||!!h.err,onClick:z,children:m("fleet-cwd-repair-use-current")})})]}),_&&l.jsx("div",{className:"nc-err",role:"alert",children:_}),N!==null&&l.jsxs("div",{className:"nc-cwd-suggestion",role:"status",children:[l.jsx("span",{children:m("fleet-cwd-repair-suggestion")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:V,children:m("fleet-cwd-repair-use-suggestion").replace("{path}",lu(N))})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:g,onClick:a,children:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:x,onClick:J,children:g?"…":m("save")})]})]})}function QP({token:t,readonly:e,targets:n=[],startNewCell:i=!1,initialLocation:s=""}){const[a,c]=k.useState({engines:[],cells:[],managedCatalog:[]}),[d,h]=k.useState({available:!1,capabilities:[]}),[f,g]=k.useState(!1),[y,_]=k.useState(null),[w,S]=k.useState(null),[N,C]=k.useState({}),[E,x]=k.useState(null),[M,T]=k.useState(!1),[U,z]=k.useState(""),[V,J]=k.useState(""),[q,X]=k.useState(s),[H,P]=k.useState(!1),[L,D]=k.useState(null),[I,O]=k.useState(null),[R,A]=k.useState(null),[j,F]=k.useState(!1),[$,W]=k.useState([]),[ce,ge]=k.useState(null),[K,oe]=k.useState("manage"),le=k.useRef(!1),te=q?q.split("/"):[],fe=k.useCallback(async()=>{try{const ae=await Dr(t,te);h(ae);try{const se=await bm(t,te);P(!!se.readonlyDefault)}catch{P(!1)}if(ae.provider==="builtin"&&(ae.capabilities||[]).includes("definitions")){const se=await Yu(t,te),Z=new Map((ae.engines||[]).map(_e=>[_e.id,_e]));if(se.engines=(se.engines||[]).map(_e=>{var xe;return{..._e,availableModels:((xe=Z.get(_e.id))==null?void 0:xe.models)||[]}}),c(se),(ae.capabilities||[]).includes("credentials"))try{W((await wk(t,te)).credentials||[])}catch{W([])}else W([])}z("")}catch(ae){z(String(ae.message||ae))}finally{g(!0)}},[t,q]);k.useEffect(()=>{fe();const ae=setInterval(fe,5e3);return()=>clearInterval(ae)},[fe]);const Le=new Set((d.cells||[]).filter(ae=>ae.active).map(ae=>ae.cell)),$e=d.provider==="builtin"&&(d.capabilities||[]).includes("edit"),ue=(d.capabilities||[]).includes("restore");k.useEffect(()=>{!i||le.current||!$e||!a.engines.length||(le.current=!0,x({mode:"new",form:Vb(a.engines[0].id)}))},[i,$e,a.engines]);const ye=async ae=>{T(!0),z(""),J("");try{await ae(),await fe()}catch(se){z(String(se.message||se))}T(!1)},Ne=async(ae,se)=>{const Z=await Nk(t,ae,se,te);return C(_e=>({..._e,[`${ae}::${se}`]:Z})),Z},Ye=ae=>ye(async()=>{const se={id:String(ae.id||"").trim(),engine:String(ae.engine||"").trim()};for(const Z of["contextWindow","maxTokens"]){const _e=String(ae[Z]||"").trim();_e&&(se[Z]=Number(_e))}ae.reasoning===!0&&(se.reasoning=!0),await kk(t,se,te),S(null),await fe()}),kt=()=>ye(async()=>{var Lt;const ae=y.mode==="new",se=y.form,Z=a.managedCatalog||[],_e=se.kind==="managed"?Ml(Z,se):null,xe=typeof(_e==null?void 0:_e.credentialEnv)=="string"?_e.credentialEnv:"",rt=xe&&se.credentialValue||"",ct=WP(se,ae,Z);!ae&&y.form.kind==="custom"&&!y.form.modelFlag&&(ct.model=null),!ae&&y.form.kind==="custom"&&y.form.promptMode!=="flag"&&(ct.promptFlag=null);let pt;if(ae)pt=await Sk(t,ct,te);else{const Q=y.original,Se=new Set(y.form.envRows.filter(Qe=>!Qe.remove).map(Qe=>Qe.key)),ze=(Q.envKeys||[]).filter(Qe=>!Se.has(Qe)),qe=Object.fromEntries(y.form.envRows.filter(Qe=>!Qe.remove&&Qe.key&&(!Qe.configured||Qe.value!=="")).map(Qe=>[Qe.key,Qe.value]));pt=await xk(t,Q.id,ct,y.form.kind==="custom"?{set:qe,remove:ze}:void 0,te)}let At=null;if(xe&&rt)try{At=await q_(t,xe,rt,te),W(At.credentials||[])}catch{throw await fe(),ae&&_({mode:"edit",original:{...ct,id:se.id},form:{...se,credentialReveal:!1}}),new Error(m(ae?"fleet-key-partial-create":"fleet-key-partial-edit"))}await fe(),_(null),J(m("fleet-saved"));const Wt=((Lt=((At==null?void 0:At.credentials)||[]).find(Q=>Q.envKey===xe))==null?void 0:Lt.activeCells)||[],Nt=[...new Set([...(pt==null?void 0:pt.activeCells)||[],...Wt])];if(Nt.length&&window.confirm(m("fleet-restart-confirm").replace("{cells}",Nt.join(", "))))for(const Q of Nt)await fl(t,Q,te)}),bt=()=>ye(async()=>{var Wt,Nt,Lt,Q,Se,ze;const ae=E.mode==="new",se=E.form,Z={...ae?{id:se.id}:{},cwd:se.cwd,engine:se.engine,boot:!!se.boot},_e={...se.commands||{}},xe=a.engines.find(qe=>qe.id===se.engine);((Wt=xe==null?void 0:xe.managed)==null?void 0:Wt.client)==="shell"&&typeof se.command=="string"&&se.command.length?_e[se.engine]=se.command:((Nt=xe==null?void 0:xe.managed)==null?void 0:Nt.client)==="shell"&&delete _e[se.engine],(Object.keys(_e).length||!ae)&&(Z.commands=_e);const rt=(se.label||"").trim();ae?rt&&(Z.label=rt):Z.label=rt||null;const ct=(se.panelUrl||"").trim();ae?ct&&(Z.panelUrl=ct):Z.panelUrl=ct||null,ae?Array.isArray(se.mcp)&&(Z.mcp=se.mcp):Z.mcp=Array.isArray(se.mcp)?se.mcp:null,ae?(((Lt=xe==null?void 0:xe.managed)==null?void 0:Lt.client)!=="shell"&&se.model&&(Z.model=se.model),((Q=xe==null?void 0:xe.managed)==null?void 0:Q.client)!=="shell"&&se.prompt&&(Z.prompt=se.prompt)):(Z.model=((Se=xe==null?void 0:xe.managed)==null?void 0:Se.client)==="shell"?null:se.model||null,((ze=xe==null?void 0:xe.managed)==null?void 0:ze.client)!=="shell"&&(Z.prompt=se.prompt||null));const pt=ae?await Lk(t,Z,te):await m0(t,E.original.id,Z,te),At=ae?se.id:E.original.id;x(null),J(m("fleet-saved")),!ae&&(pt!=null&&pt.active)&&window.confirm(m("fleet-restart-confirm").replace("{cells}",At))&&await fl(t,At,te)}),st=e||H,mt=d.capabilities||[],Et=te.length>0&&st,it=ae=>$.find(se=>{var Z;return(Z=se.engines)==null?void 0:Z.includes(ae.id)})||null,It=()=>ye(async()=>{var Z;const ae=await q_(t,ce.envKey,ce.value,te);W(ae.credentials||[]),ge(null),J(m("fleet-credential-saved"));const se=((Z=(ae.credentials||[]).find(_e=>_e.envKey===ce.envKey))==null?void 0:Z.activeCells)||[];if(se.length&&window.confirm(m("fleet-restart-confirm").replace("{cells}",se.join(", "))))for(const _e of se)await fl(t,_e,te)}),Ut=ae=>ye(async()=>{if(!window.confirm(m("fleet-credential-remove-confirm").replace("{key}",ae.envKey)))return;const se=await bk(t,ae.envKey,te);W(se.credentials||[]),J(m("fleet-credential-removed"))}),Bt=ae=>D({...ae,route:Array.isArray(ae==null?void 0:ae.route)?ae.route:te}),gt=async ae=>{if(!L)return;const se=L.cell||L.id,Z=Array.isArray(L.route)?L.route:te;if(ae.action==="up"){const _e=await vm(t,{cell:se,boot:!!ae.boot,...ae.engine?{engine:ae.engine}:{},...ae.model!==void 0?{model:ae.model}:{},...ae.permissionPolicy?{permissionPolicy:ae.permissionPolicy}:{}},Z),xe=Pm(_e);xe&&J(xe.text)}else await Su(t,{cell:se,boot:!!ae.boot},Z)},vt=(ae,se)=>{z(""),O({mode:"new",route:Array.isArray(se)?se:te,form:{tmuxSession:ae.name,id:"",engine:"",cwd:"",boot:!1},err:""})},un=()=>ye(async()=>{const ae=I.form;if(!ae.engine){O({...I,err:m("import-engine-required")});return}await Rk(t,{tmuxSession:ae.tmuxSession,id:ae.id||void 0,engine:ae.engine,cwd:ae.cwd||void 0,boot:!!ae.boot},ae.route||te),O(null),J(m("fleet-saved"))}),re=({engineRows:ae=[],cellRows:se=[],models:Z=[]})=>ye(async()=>{const _e=ae.filter(Q=>Q.selected),xe=_e.map(Q=>gx(Q.engine));if(xe.some(Q=>!Q))throw new Error(m("fleet-backup-invalid-engine"));const rt=_e.filter(Q=>Q.exists).map(Q=>Q.engine.id);if(rt.length&&!window.confirm(m("fleet-backup-confirm-engine-overwrite").replace("{engines}",rt.join(", "))))return;const ct=[...new Set([...a.engines.map(Q=>Q.id),...xe.map(Q=>Q.id)])],pt=[];for(const Q of se.filter(Se=>Se.selected)){const Se=zP(Q.cell,Q.engine,ct);if(!Se)throw new Error(`${Q.cell.id}: ${m("fleet-backup-engine-missing")}`);pt.push(Se)}const At=se.filter(Q=>Q.selected&&Q.exists).map(Q=>Q.cell.id);if(At.length&&!window.confirm(m("fleet-backup-confirm-overwrite").replace("{cells}",At.join(", "))))return;const Wt=xe.length?await Mk(t,xe,rt.length>0,te,Z):{needsRestart:[]},Nt=pt.length?await Ak(t,pt,te):{needsRestart:[]},Lt=[...new Set([...Wt.needsRestart||[],...Nt.needsRestart||[]])];F(!1),J(`${m("fleet-backup-restored").replace("{n}",String(pt.length))}${xe.length?` · ${xe.length} ${m("fleet-engines").toLowerCase()}`:""}${Lt.length?` · ${m("fleet-backup-needs-restart").replace("{cells}",Lt.join(", "))}`:""}`)}),et=l.jsxs("label",{className:"nc-field",children:[m("location"),l.jsxs("select",{value:q,onChange:ae=>{X(ae.target.value),_(null),x(null),z(""),J(""),P(!1),g(!1),h({available:!1,capabilities:[]}),c({engines:[],cells:[],managedCatalog:[]}),W([]),ge(null)},children:[l.jsx("option",{value:"",children:m("local")}),n.map(ae=>l.jsxs("option",{value:ae.route.join("/"),disabled:ae.status&&ae.status!=="up",children:[ae.label,ae.status&&ae.status!=="up"?` · ${m("node-offline")}`:""]},ae.route.join("/")))]})]}),jt=l.jsxs("div",{className:"nc-fleet-view-tabs",role:"tablist","aria-label":m("tab-fleet"),children:[l.jsx("button",{type:"button",role:"tab","aria-selected":K==="manage",className:`nc-set-tabbtn${K==="manage"?" on":""}`,onClick:()=>oe("manage"),children:m("fleet-manage-location")}),l.jsx("button",{type:"button",role:"tab","aria-selected":K==="overview",className:`nc-set-tabbtn${K==="overview"?" on":""}`,onClick:()=>oe("overview"),children:m("fleet-network-overview")})]});return f?$e?l.jsxs("div",{className:"nc-set-tab nc-fleet-editor",children:[jt,K==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:m("fleet-overview-help")}),l.jsx(Xf,{token:t,targets:n,readonly:e,onPower:Bt,onImport:vt})]}):l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:m("fleet-manage-help")}),et,l.jsxs("div",{className:"nc-set-row nc-fleet-backup-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>{z(""),F(!0)},children:m("fleet-backup")}),l.jsx("small",{children:m("fleet-backup-help")})]}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:m("fleet-cells")}),l.jsx("span",{className:"nc-fleet-head-actions",children:l.jsxs("button",{className:"nc-btn primary",disabled:st||M||!a.engines.length,onClick:()=>{var ae;z(""),x({mode:"new",form:Vb((ae=a.engines[0])==null?void 0:ae.id)})},children:["+ ",m("add")]})})]}),a.cells.map(ae=>{const se=Le.has(ae.id),Z=ae.needsRepair===!0;return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:ae.id}),ae.label?l.jsxs("small",{className:"nc-fleet-label",children:[" ",ae.label]}):null,l.jsxs("small",{children:[ae.engine," · ",Z?l.jsx("span",{className:"nc-fleet-tag nc-fleet-tag-warn",children:m("fleet-cwd-needs-repair")}):ae.cwd,se?` · ${m("service-active")}`:` · ${m("cell-off")}`]})]}),l.jsxs("span",{children:[se&&mt.includes("down")&&l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>ye(()=>Su(t,{cell:ae.id},te)),children:m("stop")}),!se&&mt.includes("up")&&l.jsx("button",{className:"nc-btn primary",disabled:st||M,onClick:()=>Bt({cell:ae.id,id:ae.id,engine:ae.engine,model:ae.model,models:ae.models,permissionPolicies:ae.permissionPolicies,active:!1,boot:ae.boot}),children:m("start")}),se&&mt.includes("restart")&&l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>ye(()=>fl(t,ae.id,te)),children:m("restart")}),Z?l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>{z(""),A(ae)},children:m("fleet-cwd-repair")}):l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>{var _e;z(""),x({mode:"edit",original:ae,form:{...ae,commands:{...ae.commands||{}},command:((_e=ae.commands)==null?void 0:_e[ae.engine])||""}})},children:m("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:st||M,onClick:()=>ye(async()=>{window.confirm(m("fleet-remove-cell").replace("{id}",ae.id))&&await g0(t,ae.id,!0,te)}),children:"×"})]})]},ae.id)}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:m("fleet-engines")}),l.jsxs("button",{className:"nc-btn primary",disabled:st||M,onClick:()=>{z(""),_({mode:"new",form:FP()})},children:["+ ",m("add")]})]}),a.engines.map(ae=>{var Z,_e;const se=it(ae);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:ae.label}),l.jsx("small",{children:ae.managed?`${ae.id} · ${ae.managed.client} / ${ae.managed.provider} · ${(Z=ae.managedInfo)!=null&&Z.configured?m("fleet-ready"):((_e=ae.managedInfo)==null?void 0:_e.reason)||m("fleet-not-ready")}`:`${ae.id} · ${ae.command}`}),se&&l.jsxs("small",{children:[se.envKey," · ",m(`fleet-credential-source-${se.source||"missing"}`)]})]}),l.jsxs("span",{children:[se&&l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>{z(""),ge({envKey:se.envKey,value:""})},children:se.configured?m("fleet-credential-change"):m("fleet-credential-set")}),(se==null?void 0:se.source)==="local"&&l.jsx("button",{className:"nc-btn danger",disabled:st||M,onClick:()=>Ut(se),children:m("fleet-credential-forget")}),l.jsx("button",{className:"nc-btn ghost",disabled:st||M,onClick:()=>{z(""),_({mode:"edit",original:ae,form:UP(ae)})},children:m("edit")}),l.jsx("button",{className:"nc-btn danger",disabled:st||M,onClick:()=>ye(async()=>{window.confirm(m("fleet-remove-engine").replace("{id}",ae.id))&&await Ck(t,ae.id,te)}),children:"×"})]})]},ae.id)}),l.jsxs("div",{className:"nc-fleet-section-head",children:[l.jsx("b",{children:m("fleet-models")}),l.jsxs("button",{className:"nc-btn primary",disabled:st||M,onClick:()=>{z(""),S({mode:"new",form:{id:"",engine:""}})},children:["+ ",m("add")]})]}),!(a.models||[]).length&&l.jsx("small",{className:"nc-set-hint",children:m("fleet-no-models")}),(a.models||[]).map(ae=>{const se=`${ae.engine}::${ae.id}`,Z=N[se],_e=(a.engines||[]).some(xe=>xe.managed&&xe.managed.model===ae.id);return l.jsxs("div",{className:"nc-fleet-item",children:[l.jsxs("span",{children:[l.jsx("b",{children:ae.id}),l.jsxs("small",{children:[ae.engine,ae.contextWindow?` · ${ae.contextWindow}`:"",_e?` · ${m("model-in-use")}`:""]}),Z&&l.jsxs("small",{className:`nc-model-test ${Z.outcome}`,children:[m(`model-test-${Z.outcome}`),Z.outcome==="ok"&&Number.isInteger(Z.latencyMs)?` · ${Z.latencyMs}ms`:""]})]}),l.jsxs("span",{children:[mt.includes("model-test")&&l.jsx("button",{className:"nc-btn ghost",disabled:M||Et,onClick:()=>ye(()=>Ne(ae.engine,ae.id)),children:m("model-test")}),l.jsx("button",{className:"nc-btn danger",disabled:st||M,onClick:()=>ye(()=>Ek(t,ae.id,ae.engine,te)),children:"×"})]})]},se)})]}),w&&l.jsx(kr,{onClose:()=>S(null),label:m("fleet-models"),error:U,children:l.jsx(VP,{state:w,setState:S,busy:M,onSave:Ye,onTest:Ne,profiles:a.managedCatalog||[],canTest:mt.includes("model-test")&&!Et})}),y&&l.jsx(kr,{onClose:()=>_(null),label:m("fleet-new-engine"),error:U,children:l.jsx(KP,{state:y,setState:_,busy:M,onSave:kt,catalog:a.managedCatalog||[]})}),E&&l.jsx(kr,{onClose:()=>x(null),label:m("fleet-new-cell"),error:U,children:l.jsx(YP,{token:t,route:te,targets:n,location:q,setLocation:X,state:E,setState:x,engines:a.engines,mcpServers:a.mcpServers||[],managedCatalog:a.managedCatalog||[],busy:M,onSave:bt})}),R&&l.jsx(kr,{onClose:()=>A(null),label:m("fleet-cwd-repair-title").replace("{id}",R.id),error:"",children:l.jsx(XP,{token:t,route:te,cell:R,busy:M,onSaved:async()=>{A(null),J(m("fleet-cwd-repaired")),await fe()},onClose:()=>A(null)})}),V&&l.jsx("div",{className:"nc-set-note",children:V}),U&&l.jsx("div",{className:"nc-err",children:U}),j&&l.jsx(kr,{onClose:()=>F(!1),label:m("fleet-backup"),error:U,children:l.jsx(qP,{cells:a.cells,engines:a.engines,models:a.models||[],busy:M,canRestore:ue,onRestore:re,onClose:()=>F(!1)})}),ce&&l.jsx(kr,{onClose:()=>ge(null),label:m("fleet-credential-title"),error:U,children:l.jsxs("div",{className:"nc-fleet-form nc-credential-form",children:[l.jsx("b",{children:m("fleet-credential-title")}),l.jsx("small",{children:m("fleet-credential-help")}),l.jsxs("label",{className:"nc-field",children:[ce.envKey,l.jsx("input",{type:"password",autoComplete:"off",spellCheck:"false",autoCapitalize:"none",value:ce.value,onChange:ae=>ge({...ce,value:ae.target.value})})]}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",onClick:()=>ge(null),children:m("cancel")}),l.jsx("button",{className:"nc-btn primary",disabled:M||!ce.value,onClick:It,children:m("save")})]})]})}),I&&l.jsx(kr,{onClose:()=>O(null),label:m("import-as-cell"),error:U,children:l.jsx(Gb,{token:t,route:I.route||te,state:I,setState:O,busy:M,onSave:un})}),L&&l.jsx(Nu,{cell:L,token:t,route:Array.isArray(L.route)?L.route:te,onConfirm:async ae=>{try{await gt(ae)}finally{await fe()}},onClose:()=>D(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[jt,K==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:m("fleet-overview-help")}),l.jsx(Xf,{token:t,targets:n,readonly:e,onPower:Bt,onImport:vt})]}):l.jsxs(l.Fragment,{children:[et,l.jsxs("div",{className:"nc-set-info",children:[m(U?"fleet-editor-load-error":"fleet-editor-unavailable"),!U&&d.reason?` ${d.reason}`:""]})]}),U&&l.jsx("div",{className:"nc-err",children:U}),I&&l.jsx(kr,{onClose:()=>O(null),label:m("import-as-cell"),error:U,children:l.jsx(Gb,{token:t,route:I.route||te,state:I,setState:O,busy:M,onSave:un})}),L&&l.jsx(Nu,{cell:L,token:t,route:Array.isArray(L.route)?L.route:te,onConfirm:async ae=>{try{await gt(ae)}finally{await fe()}},onClose:()=>D(null)})]}):l.jsxs("div",{className:"nc-set-tab",children:[jt,K==="overview"?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-set-info",children:m("fleet-overview-help")}),l.jsx(Xf,{token:t,targets:n,readonly:e,onPower:Bt,onImport:vt})]}):l.jsxs(l.Fragment,{children:[et,l.jsx("div",{className:"nc-set-info",children:m("fleet-editor-loading")})]})]})}const mg="nc_notification_speech_v1",cu="nc-notification-speech",dm="nc-notification-speech-preview",JP=320,ZP=2,eT=3e4,tT=1e4,nT=6e4,iT=64,Xb=Object.freeze({enabled:!1}),sT=Object.freeze({it:"it-IT",en:"en-US",es:"es-ES"}),rT=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"])}),gg=new WeakSet;function vg(t){return{enabled:(t&&typeof t=="object"&&!Array.isArray(t)?t:{}).enabled===!0}}function _x(){try{return typeof localStorage<"u"?localStorage:null}catch{return null}}function Qb(t=_x()){if(!t)return{...Xb};try{return vg(JSON.parse(t.getItem(mg)||"null"))}catch{return{...Xb}}}function oT(t,e=_x()){const n=vg(t);if(e)try{e.setItem(mg,JSON.stringify(n))}catch{}return n}function va(){try{return typeof window<"u"?window:null}catch{return null}}function jl(t=va()){try{return!!(t&&t.speechSynthesis&&typeof t.speechSynthesis.speak=="function"&&typeof t.SpeechSynthesisUtterance=="function")}catch{return!1}}function yx(t=va()){return!!(t&&(typeof t=="object"||typeof t=="function")&&gg.has(t))}function hm(t=va()){t&&(typeof t=="object"||typeof t=="function")&&gg.delete(t)}function sa(t){const e=String(t||"").trim().toLowerCase().split("-")[0];return sT[e]||""}function cd(t){return String(t||"").normalize("NFC").replace(/[\p{Cc}\p{Cf}]+/gu," ").replace(/\s+/g," ").trim()}function aT(t){const e=cd(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 i=Object.entries(rT).map(([s,a])=>({lang:s,score:[...n].reduce((c,d)=>c+(a.has(d)?1:0),0)})).sort((s,a)=>a.score-s.score);return i[0].score>=3&&i[0].score-i[1].score>=2?i[0].lang:""}function lT(t,e){const n=sa(t&&t.lang);return n||sa(aT(t&&t.body))||sa(e)}function wx(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 bx(t,e){const n=sa(e);if(!n)return null;const i=Array.from(t||[]).filter(d=>d&&typeof d.lang=="string"&&d.lang.trim()),s=i.filter(d=>d.lang.trim().toLowerCase()===n.toLowerCase()),a=n.slice(0,2).toLowerCase(),c=i.filter(d=>d.lang.trim().toLowerCase().split("-")[0]===a);return s.find(d=>d.default===!0)||s[0]||c.find(d=>d.default===!0)||c[0]||null}function Jb(t){return cd(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 cT(t,e=JP){const n=Jb(t&&t.title),i=Jb(t&&t.body),s=[n,i&&i!==n?i:""].filter(Boolean).join(". "),a=Array.from(s);return a.length<=e?s:`${a.slice(0,Math.max(0,e-1)).join("").trimEnd()}…`}function uT(t){try{return!!(t&&t.visibilityState==="visible"&&typeof t.hasFocus=="function"&&t.hasFocus())}catch{return!1}}function Sx(t=va()){if(!jl(t))return!1;try{return t.speechSynthesis.cancel(),!0}catch{return!1}}function dT(t){try{t&&typeof t.dispatchEvent=="function"&&typeof t.Event=="function"&&t.dispatchEvent(new t.Event(dm))}catch{}}function hT(t,e,n=va(),i={}){var f;if(hm(n),!jl(n))return Promise.resolve(!1);const s=cd(t);if(!s||(f=i.signal)!=null&&f.aborted)return Promise.resolve(!1);const a=Number.isFinite(i.timeoutMs)&&i.timeoutMs>0?i.timeoutMs:tT,c=i.setTimer||((g,y)=>setTimeout(g,y)),d=i.clearTimer||(g=>clearTimeout(g)),h=i.signal;return dT(n),new Promise(g=>{let y=!1,_=!1,w=null,S=null;const N=C=>{if(!y){if(y=!0,h&&S&&h.removeEventListener("abort",S),w!==null&&d(w),C!==!0)try{n.speechSynthesis.cancel()}catch{}else gg.add(n);g(C)}};S=()=>N("no-activation"),h&&h.addEventListener("abort",S,{once:!0});try{n.speechSynthesis.cancel();const C=new n.SpeechSynthesisUtterance(s);C.lang=sa(e);const E=bx(wx(n),C.lang);E&&(C.voice=E),C.onstart=()=>{_=!0},C.onend=()=>N(_?!0:"no-activation"),C.onerror=()=>N("voice-error"),w=c(()=>N("timeout"),a),n.speechSynthesis.speak(C)}catch{N("no-activation")}})}function fT(t={}){const e=t.scope||va(),n=t.document||e&&e.document,i=Number.isInteger(t.maxPending)&&t.maxPending>=0?t.maxPending:ZP,s=Number.isFinite(t.watchdogMs)&&t.watchdogMs>0?t.watchdogMs:eT,a=Number.isFinite(t.dedupWindowMs)&&t.dedupWindowMs>0?t.dedupWindowMs:nT,c=Number.isInteger(t.maxDedup)&&t.maxDedup>0?t.maxDedup:iT,d=t.now||Date.now,h=t.setTimer||((H,P)=>setTimeout(H,P)),f=t.clearTimer||(H=>clearTimeout(H)),g=t.isPrimed||(()=>yx(e)),y=e&&e.speechSynthesis;let _=null,w=null,S=[],N=[],C=()=>{};const E=new Map,x=()=>{N=wx(e)};if(x(),y&&typeof y.addEventListener=="function")y.addEventListener("voiceschanged",x),C=()=>y.removeEventListener("voiceschanged",x);else if(y&&"onvoiceschanged"in y){const H=y.onvoiceschanged,P=(...L)=>{x(),typeof H=="function"&&H.apply(y,L)};y.onvoiceschanged=P,C=()=>{y.onvoiceschanged===P&&(y.onvoiceschanged=H)}}const M=H=>{if(H&&typeof H.id=="string"&&H.id)return`id:${H.id}`;const P=Number(H&&H.ts),L=cd(H&&H.title);return Number.isFinite(P)&&L?`frame:${P}:${L}`:""},T=H=>{if(!H)return!0;const P=d();for(const[L,D]of E)P-D>=a&&E.delete(L);if(E.has(H))return!1;for(E.set(H,P);E.size>c;)E.delete(E.keys().next().value);return!0},U=()=>{w!==null&&f(w),w=null},z=()=>{U(),_&&(_.onend=null,_.onerror=null,_=null),Sx(e)},V=H=>{if(!jl(e))return S=[],"unsupported";let P;try{P=new e.SpeechSynthesisUtterance(H.text),P.lang=sa(H.lang);const D=bx(N,P.lang);D&&(P.voice=D)}catch{return S=[],"error"}_=P;const L=()=>{if(_!==P)return;U(),_=null,P.onend=null,P.onerror=null;const D=S.shift();D&&V(D)};P.onend=L,P.onerror=L;try{return w=h(()=>{if(_!==P)return;_=null,P.onend=null,P.onerror=null;try{e.speechSynthesis.cancel()}catch{}U();const D=S.shift();D&&V(D)},s),e.speechSynthesis.speak(P),"speaking"}catch{return L(),"error"}},J=(H,P)=>{if(!jl(e))return"unsupported";const L=cT(H);if(!L)return"empty";if(!T(M(H)))return"duplicate";if(!uT(n))return"inactive";if(!g())return"unprimed";const D={text:L,lang:P};return H&&H.urgency==="high"?(S=[],z(),V(D)):_?i===0?"dropped":(S.length>=i&&S.shift(),S.push(D),"queued"):V(D)},q=()=>{S=[],z()};return{enqueue:J,stop:q,dispose:()=>{q(),C(),C=()=>{}}}}function xx(){const[t,e]=k.useState(Qb);k.useEffect(()=>{const i=s=>{if((s==null?void 0:s.type)==="storage"&&s.key!==mg&&s.key!==null)return;const a=(s==null?void 0:s.type)===cu?vg(s.detail):Qb();e(a)};return window.addEventListener(cu,i),window.addEventListener("storage",i),()=>{window.removeEventListener(cu,i),window.removeEventListener("storage",i)}},[]);const n=k.useCallback(i=>{const s=oT({enabled:i===!0});return e(s),window.dispatchEvent(new CustomEvent(cu,{detail:s})),s.enabled},[]);return[t.enabled,n]}function pT({text:t}){const[e,n]=k.useState(!1),i=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:i,children:[l.jsx(ht,{name:"copy",size:14})," ",m(e?"copied":"copy")]})]})}function mT({value:t}){const[e,n]=k.useState("");return k.useEffect(()=>{let i=!0;return Oj.toDataURL(t,{margin:1,width:220}).then(s=>{i&&n(s)}).catch(()=>{}),()=>{i=!1}},[t]),e?l.jsx("img",{src:e,width:"220",height:"220",alt:"NexusCrew pairing QR"}):null}function gT({token:t,nodes:e,roster:n,settings:i,readonly:s,refresh:a,refreshAliases:c,vlUnavailable:d=[],accessRevision:h=null}){const[f,g]=k.useState(null),[y,_]=k.useState(null),[w,S]=k.useState(null),[N,C]=k.useState({ssh:"",sshPort:"",name:""}),[E,x]=k.useState(""),[M,T]=k.useState(""),[U,z]=k.useState(!1),[V,J]=k.useState(null),q=Date.now(),X=i&&i.deviceName||"",H=(e||[]).filter(j=>j&&j.direction==="outbound"&&j.name&&j.ssh),P=H.find(j=>j.name===E)||H[0]||null,L=P?lp(P.tunnel,q):null,D=P!=null&&P.shared?L!=null&&L.up?"share-local-active":"share-local-pending":L!=null&&L.up?"share-local-private":"share-local-private-down",I=[{key:"peer-group-hubs",rows:(e||[]).filter(j=>j.kind!=="transitive"&&j.kind!=="vl"&&j.relation!=="client")},{key:"peer-group-clients",rows:(e||[]).filter(j=>j.kind!=="transitive"&&j.kind!=="vl"&&j.relation==="client")},{key:"peer-group-routed",rows:(e||[]).filter(j=>j.kind==="transitive")},{key:"peer-group-vl",rows:(e||[]).filter(j=>j.kind==="vl")}],O=V&&(e||[]).find(j=>`${j.kind||"direct"}:${j.nodeId||j.name}`===V)||null,R=async j=>{if(P){g(null),_(`${P.name}:share`);try{const F=await Fk(t,P.name,j);await a(),F&&F.reversePoolPending===!0&&g(`${P.name}: ${m("share-reverse-pool-pending")}`)}catch(F){const $=F!=null&&F.data&&F.data.shared===!1?F.data:null;if($)try{await a()}catch{}const W=F!=null&&F.data&&typeof F.data.hint=="string"?F.data.hint:"",ce=($==null?void 0:$.revoked)===!0&&($==null?void 0:$.localReconcilePending)===!0?m("share-off-local-reconcile-pending"):($==null?void 0:$.revoked)===!1&&($==null?void 0:$.reconcilePending)===!0?m("share-off-hub-reconcile-pending"):"",ge=F!=null&&F.data&&F.data.reversePoolPending===!0?m("share-reverse-pool-pending"):"",K=F!=null&&F.data&&typeof F.data.code=="string"?F.data.code:"",oe=F!=null&&F.data&&typeof F.data.detail=="string"?F.data.detail.trim():"",le=oe&&oe!==String(F.message||"")?oe:"";g(`${P.name}: ${String(F.message||F)}${K?` [${K}]`:""}${le?` — ${le}`:""}${W?` — ${W}`:""}${ce?` — ${ce}`:""}${ge?` — ${ge}`:""}`)}_(null)}},A=async()=>{g(null);const j=jr(N.name||M||X||"NexusCrew"),F=s5({name:j,ssh:N.ssh,sshPort:N.sshPort});if(!F.ok){g(m(F.error));return}_("invite");try{S(await Bk(t,{...M||X?{label:M||X}:{},name:j,ssh:F.value.ssh,...F.value.sshPort?{sshPort:F.value.sshPort}:{}}))}catch($){g(String($.message||$))}_(null)};return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-sheet-label",children:m("peer-inventory-title")}),(e||[]).length===0&&l.jsx("div",{className:"nc-empty",children:m("no-nodes")}),I.map(j=>j.rows.length>0&&l.jsxs("div",{className:"nc-peer-group",children:[l.jsxs("div",{className:"nc-peer-group-title",children:[m(j.key)," ",l.jsx("span",{children:j.rows.length})]}),j.rows.map(F=>{const $=Xj(F);if(!$)return null;const W=`${F.kind||"direct"}:${F.nodeId||F.name}`,ce=$.routed?{up:$.reach.up,since:null}:lp(F.tunnel,q);return l.jsxs("button",{type:"button",className:`nc-set-node nc-node-row${$.routed?" routed":""}`,"aria-label":`${$.title} — ${m("node-detail-open")}`,onClick:()=>J(W),children:[l.jsx("span",{className:`nc-dot ${$.reach.up?"on":""}`}),l.jsxs("span",{className:"nc-node-row-text",children:[l.jsx("b",{children:$.title}),l.jsxs("small",{children:[$.routed?$.routeLabel:`${$.subtitle} · ${m($.exposure.shortKey)}`,!$.routed&&$.exposure.shortKey==="visibility-selected"?` (${$.exposure.count})`:""]})]}),l.jsxs("span",{className:`nc-set-tunnel${$.reach.up?" up":""}`,children:[m($.reach.key),ce.since?` · ${ce.since}`:""]}),l.jsx("span",{className:"nc-node-row-more",children:l.jsx(ht,{name:"chevronDown",size:14})})]},W)})]},j.key)),d.length>0&&l.jsxs("div",{className:"nc-err",children:[m("vl-owners-unavailable"),": ",d.map(j=>j.label||j.route.join("/")).join(", ")]}),O&&l.jsx(gP,{node:O,nodes:e||[],token:t,readonly:s,refresh:a,onClose:()=>J(null),peerAccessRevision:h}),(n||[]).some(j=>!j.direct&&j.instanceId)&&l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("routed-node-aliases")}),l.jsx("small",{className:"nc-set-hint",children:m("routed-node-aliases-help")}),(n||[]).filter(j=>!j.direct&&j.instanceId).map(j=>l.jsxs("div",{className:"nc-set-node",children:[l.jsxs("div",{className:"nc-set-node-head",children:[l.jsx("span",{className:`nc-dot ${j.status==="up"?"on":""}`}),l.jsx("b",{children:j.label||j.name}),l.jsx("small",{children:(j.route||[]).join(" › ")})]}),l.jsxs("div",{className:"nc-set-node-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!y,onClick:async()=>{const F=window.prompt(m("node-local-alias"),j.alias||"");if(F!=null){if(F.trim()&&!aa(F.normalize("NFC"))){g(m("err-label"));return}_(`${j.instanceId}:alias`),g(null);try{F.trim()?await $k(t,j.instanceId,F):await Y_(t,j.instanceId),c()}catch($){g(String($.message||$))}_(null)}},children:m("alias-on-device")}),j.alias&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!y,onClick:async()=>{_(`${j.instanceId}:alias-reset`),g(null);try{await Y_(t,j.instanceId),c()}catch(F){g(String(F.message||F))}_(null)},children:m("reset-alias")})]})]},j.instanceId))]}),P&&l.jsxs("div",{className:"nc-set-form nc-local-share",children:[l.jsx("div",{className:"nc-sheet-label",children:m("share-local-heading")}),H.length>1&&l.jsxs("label",{className:"nc-field",children:[m("share-local-hub"),l.jsx("select",{value:P.name,disabled:s||!!y,onChange:j=>x(j.target.value),children:H.map(j=>l.jsx("option",{value:j.name,children:j.label||j.name},j.name))})]}),l.jsxs("label",{className:"nc-check nc-node-share",children:[l.jsx("input",{type:"checkbox",checked:P.shared===!0,disabled:s||!!y,onChange:j=>R(j.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("share-local-through").replace("{device}",X||m("local")).replace("{hub}",P.label||P.name)}),l.jsx("small",{children:m(P.shared?"share-node-on-desc":"share-node-off-desc")})]})]}),l.jsx("div",{className:`nc-set-test${P.shared&&(L!=null&&L.up)?" ok":L!=null&&L.up?"":" ko"}`,children:m(D)}),!(L!=null&&L.up)&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:s||!!y,onClick:()=>R(P.shared===!0),children:m("share-local-reconnect")})]}),l.jsx(ix,{token:t,deviceDefault:X,localNodeId:i&&i.nodeId||"",localNameDefault:i&&i.localName||"",readonly:s,onSuccess:a}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("invite-node")}),l.jsx("small",{className:"nc-set-hint",children:m("invite-v2-hint")}),l.jsxs("div",{className:"nc-set-info nc-invite-endpoint",children:[m("invite-target-local"),": ",l.jsx("b",{children:X||m("invite-target-this")})]}),l.jsxs("label",{className:"nc-field",children:[m("invite-endpoint-label"),l.jsx("input",{placeholder:"user@host",value:N.ssh,disabled:s,onChange:j=>C({...N,ssh:j.target.value})}),l.jsx("small",{className:"nc-set-hint",children:m("invite-endpoint-needed")})]}),H.length>0&&l.jsx("small",{className:"nc-set-hint nc-invite-hub-hint",children:m("invite-hub-only")}),U&&l.jsxs("div",{className:"nc-invite-advanced",children:[l.jsxs("label",{className:"nc-field",children:[m("node-ssh-port-label"),l.jsx("input",{inputMode:"numeric",placeholder:"22",value:N.sshPort,disabled:s,onChange:j=>C({...N,sshPort:j.target.value.replace(/[^0-9]/g,"").slice(0,5)})})]}),l.jsxs("label",{className:"nc-field",children:[m("device-name-label"),l.jsx("input",{placeholder:X||"NexusCrew",value:M,disabled:s,onChange:j=>T(j.target.value)}),l.jsx("small",{className:"nc-set-hint",children:m("device-name-hint")})]}),l.jsxs("label",{className:"nc-field",children:[m("node-name-label"),l.jsx("input",{placeholder:jr(M||X||m("node-name-ph")),value:N.name,disabled:s,onChange:j=>C({...N,name:j.target.value?jr(j.target.value):""})})]})]}),l.jsxs("div",{className:"nc-set-row nc-invite-actions",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:s||!!y||!N.ssh.trim(),onClick:A,children:m("create-pairing-link")}),l.jsxs("button",{type:"button",className:"nc-btn ghost",disabled:!!y,onClick:()=>z(j=>!j),children:[U?"▾":"▸"," ",m("pair-advanced")]})]}),w&&l.jsxs(l.Fragment,{children:[l.jsx(mT,{value:w.pairingUrl}),l.jsx(pT,{text:w.pairingUrl}),l.jsx("div",{className:"nc-set-info",children:m("invite-next-steps")})]})]}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function vT({token:t,readonly:e}){const[n,i]=k.useState("idle"),[s,a]=k.useState(()=>lx()),[c,d]=k.useState(!1),[h,f]=k.useState(null);k.useEffect(()=>{let _=!1;return wP().then(w=>{_||i(w)}),()=>{_=!0}},[]);const g=async()=>{f(null),d(!0);try{n==="subscribed"?(await Kb(t),i("idle")):(await bP(t),i("subscribed"))}catch(_){const w=String(_.message||_);w==="push-denied"?(i("denied"),f(m("push-denied"))):w==="push-unsupported"?(i("unsupported"),f(m("push-unsupported"))):f(w==="push-disabled-local"?m("push-local-disabled"):w)}d(!1)},y=async()=>{const _=vP({enabled:s.enabled!==!1});if(a(_),f(null),_.enabled===!1&&n==="subscribed"){d(!0);try{await Kb(t),i("idle")}catch{}d(!1)}};return n==="unsupported"?l.jsx("div",{className:"nc-set-info",children:m("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:y,disabled:c,children:s.enabled===!1?m("push-local-on"):m("push-local-off")}),l.jsx("span",{className:"nc-set-info",children:s.enabled===!1?m("push-local-off-note"):m("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?m("settings-readonly"):"",onClick:g,children:m(n==="subscribed"?"push-disable":"push-enable")}),l.jsx("span",{className:"nc-set-info",children:m(n==="subscribed"?"push-on":n==="denied"?"push-denied":"push-off")})]}),h&&l.jsx("div",{className:"nc-err",children:h})]})}function _T(){const[t,e]=xx(),[n,i]=k.useState(""),[s,a]=k.useState(""),[c,d]=k.useState(!1),[h,f]=k.useState(yx),g=k.useRef(0),y=k.useRef(!1),_=k.useRef(null),w=jl();k.useEffect(()=>()=>{var C;g.current+=1,y.current&&((C=_.current)==null||C.abort(),_.current=null,y.current=!1,hm())},[]);const S=async()=>{const C=g.current+=1,E=typeof AbortController=="function"?new AbortController:null;i(""),a(""),d(!0),f(!1),y.current=!0,_.current=E;const x=await hT(m("notification-speech-preview"),xu(),void 0,E?{signal:E.signal}:{});return C!==g.current||(_.current=null,y.current=!1,d(!1),f(x===!0),x===!0?a(m("notification-speech-preview-ok")):i(m(x==="voice-error"?"notification-speech-preview-voice-error":x==="timeout"?"notification-speech-preview-timeout":"notification-speech-preview-failed"))),x},N=C=>{var E;if(e(C),i(""),a(""),C)S();else{g.current+=1;const x=y.current;(E=_.current)==null||E.abort(),_.current=null,y.current=!1,d(!1),f(!1),hm(),x||Sx()}};return l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":m("notification-speech-enable"),checked:t,disabled:!w,onChange:C=>N(C.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("notification-speech-enable")}),l.jsx("small",{children:m("notification-speech-help")})]})]}),w?l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:!t||c,onClick:()=>{S()},children:m(c?"notification-speech-testing":"notification-speech-test")})}):l.jsx("div",{className:"nc-set-info",children:m("notification-speech-unsupported")}),t&&!h&&!c&&!n&&l.jsx("div",{className:"nc-set-info",children:m("notification-speech-needs-test")}),s&&l.jsx("div",{className:"nc-set-info",role:"status",children:s}),n&&l.jsx("div",{className:"nc-err",children:n})]})}function yT({token:t,readonly:e,nodes:n=[],settings:i=null}){const[s,a]=k.useState(null),[c,d]=k.useState([]),[h,f]=k.useState({name:"",mode:"primary-failover",targets:[]}),[g,y]=k.useState(null),[_,w]=k.useState(!1),[S,N]=k.useState(null),[C,E]=k.useState(""),x=k.useCallback(async()=>{try{const[R,A]=await Promise.all([Uk(t),Vk(t)]);a(R),d(Array.isArray(A==null?void 0:A.groups)?A.groups:[]),E("")}catch(R){E(String(R.message||R))}},[t]);k.useEffect(()=>{x()},[x]);const M=async R=>{w(!0),N(null),E("");try{a(await Wk(t,R))}catch(A){E(String(A.message||A))}w(!1)},T=async()=>{w(!0),N(null),E("");try{N({kind:"test",...await qk(t)})}catch(R){E(String(R.message||R))}w(!1)},U=async()=>{w(!0),N(null),E("");try{N({kind:"stop",...await Kk(t)})}catch(R){E(String(R.message||R))}w(!1)},z=[],V=new Set,J=(R,A)=>{const j=typeof R=="string"?R.toLowerCase():"";!/^[a-f0-9]{32}$/.test(j)||V.has(j)||(V.add(j),z.push({id:j,label:A||j}))};J(i==null?void 0:i.nodeId,m("audio-group-local"));for(const R of n||[])J((R==null?void 0:R.nodeId)||(R==null?void 0:R.instanceId),(R==null?void 0:R.label)||(R==null?void 0:R.name)||(R==null?void 0:R.nodeId));for(const R of h.targets)J(R,`${R} (${m("audio-group-unavailable-target")})`);const q=(R=null)=>{E(""),R?(y(R.name),f({name:R.name,mode:R.mode,targets:[...R.targets||[]]})):(y(null),f({name:"",mode:"primary-failover",targets:[]}))},X=(R,A)=>f(j=>({...j,targets:A?[...new Set([...j.targets,R])]:j.targets.filter(F=>F!==R)})),H=async()=>{const R=h.name.trim().toLowerCase();if(!/^[a-z0-9][a-z0-9-]{0,31}$/.test(R)||h.targets.length<1){E(m("audio-group-invalid"));return}w(!0),E("");try{const A=await Yk(t,R,{targets:h.targets,mode:h.mode}),j=A==null?void 0:A.group;if(!j||!j.name)throw new Error(m("audio-group-save-failed"));d(F=>[...F.filter($=>$.name!==j.name),j].sort(($,W)=>$.name.localeCompare(W.name))),q(null)}catch(A){E(String(A.message||A))}w(!1)},P=async R=>{w(!0),E("");try{await Gk(t,R),d(A=>A.filter(j=>j.name!==R)),g===R&&q(null)}catch(A){E(String(A.message||A))}w(!1)},L=(s==null?void 0:s.installed)===!0,D=(s==null?void 0:s.liveness)==="ready",I=(s==null?void 0:s.consent)===!0&&L&&D,O=S?S.kind==="stop"?m(S.stopped?"audio-stop-stopped":"audio-stop-idle"):S.status==="accepted"||S.status==="spoken"?m("audio-test-accepted"):S.status==="unknown"?m("audio-test-unknown"):`${m("audio-test-refused")}${S.reason?` (${S.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:m("audio-title")}),l.jsx("br",{}),m("audio-help")]}),s?l.jsxs(l.Fragment,{children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":m("audio-consent"),checked:s.consent===!0,disabled:e||_,onChange:R=>{M(R.target.checked)}}),l.jsxs("span",{children:[l.jsx("b",{children:m("audio-consent")}),l.jsx("small",{children:m("audio-consent-help")})]})]}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("audio-capability")}),l.jsxs("div",{className:"nc-set-info",children:[m("audio-adapter"),": ",s.adapter||m("audio-adapter-none"),l.jsx("br",{}),m("audio-installed"),": ",m(L?"audio-installed-yes":"audio-installed-no"),l.jsx("br",{}),m("audio-liveness"),": ",m(D?"audio-liveness-ready":"audio-liveness-unavailable"),Array.isArray(s.languages)&&s.languages.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("br",{}),m("audio-languages"),": ",s.languages.join(", ")]})]}),s.limits&&l.jsxs("small",{className:"nc-set-hint",children:[m("audio-limits"),": ",s.limits]})]}),!s.consent&&l.jsx("div",{className:"nc-set-info",children:m("audio-test-needs-consent")}),!L&&l.jsx("div",{className:"nc-set-info",children:m("audio-unavailable")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:e||_||!I,title:e?m("settings-readonly"):"",onClick:()=>{T()},children:m(_?"audio-testing":"audio-test")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>{U()},children:m(_?"audio-stopping":"audio-stop")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>{x()},children:m("refresh")})]}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("audio-groups-title")}),l.jsx("small",{className:"nc-set-hint",children:m("audio-groups-help")}),c.length===0&&l.jsx("div",{className:"nc-set-info",children:m("audio-groups-empty")}),c.map(R=>{var A;return l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("span",{children:[l.jsx("b",{children:R.name})," ",l.jsxs("small",{children:["· ",R.mode==="fanout"?m("audio-group-fanout"):m("audio-group-primary")," · ",((A=R.targets)==null?void 0:A.length)||0]})]}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>q(R),children:m("audio-group-edit")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>{P(R.name)},children:m("audio-group-delete")})]},R.name)}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:e||_,onClick:()=>q(null),children:m("audio-group-new")})}),l.jsxs("label",{className:"nc-field",children:[m("audio-group-name"),l.jsx("input",{"aria-label":m("audio-group-name"),value:h.name,maxLength:"32",disabled:e||_,onChange:R=>f(A=>({...A,name:R.target.value}))})]}),l.jsxs("label",{className:"nc-field",children:[m("audio-group-mode"),l.jsxs("select",{"aria-label":m("audio-group-mode"),value:h.mode,disabled:e||_,onChange:R=>f(A=>({...A,mode:R.target.value})),children:[l.jsx("option",{value:"primary-failover",children:m("audio-group-primary")}),l.jsx("option",{value:"fanout",children:m("audio-group-fanout")})]})]}),l.jsx("div",{className:"nc-set-info",children:m("audio-group-targets")}),z.length===0?l.jsx("small",{className:"nc-set-hint",children:m("audio-group-no-targets")}):z.map(R=>l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:h.targets.includes(R.id),disabled:e||_,onChange:A=>X(R.id,A.target.checked)}),l.jsxs("span",{children:[R.label,l.jsx("small",{children:R.id})]})]},R.id)),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn primary",disabled:e||_,onClick:()=>{H()},children:m("audio-group-save")}),g&&l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:_,onClick:()=>q(null),children:m("audio-group-cancel")})]})]})]}):l.jsx("div",{className:"nc-set-info",children:m("audio-loading")}),O&&l.jsx("div",{className:"nc-set-note",role:"status",children:O}),C&&l.jsx("div",{className:"nc-err",children:C})]})}function wT(){const[t,e]=Zm();return l.jsxs("div",{className:"nc-set-tab nc-input-settings",children:[l.jsx("div",{className:"nc-set-info",children:m("input-settings-local")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsxs("label",{className:"nc-field",children:[m("terminal-keyboard-gesture"),l.jsx("select",{"aria-label":m("terminal-keyboard-gesture"),value:t.terminalKeyboardGesture,onChange:n=>e({terminalKeyboardGesture:n.target.value}),children:T1.map(n=>l.jsx("option",{value:n,children:m(`terminal-keyboard-${n}`)},n))}),l.jsx("small",{children:m("terminal-keyboard-gesture-help")})]}),l.jsxs("label",{className:"nc-field",children:[m("keybar-layout"),l.jsx("select",{"aria-label":m("keybar-layout"),value:t.keybarLayout,onChange:n=>e({keybarLayout:n.target.value}),children:D1.map(n=>l.jsx("option",{value:n,children:m(`keybar-layout-${n}`)},n))}),l.jsx("small",{children:m("keybar-layout-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.keybarKeepsKeyboardClosed,onChange:n=>e({keybarKeepsKeyboardClosed:n.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:m("keybar-ime-lock")}),l.jsx("small",{children:m("keybar-ime-lock-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.voiceKeepsKeyboardClosed,onChange:n=>e({voiceKeepsKeyboardClosed:n.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:m("voice-ime-lock")}),l.jsx("small",{children:m("voice-ime-lock-help")})]})]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:t.showKeybarEnter,onChange:n=>e({showKeybarEnter:n.target.checked})}),l.jsxs("span",{children:[l.jsx("b",{children:m("keybar-enter-show")}),l.jsx("small",{children:m("keybar-enter-show-help")})]})]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:()=>e(Rr),children:m("input-settings-reset")})})]})}function bT({token:t,roster:e=[],readonly:n}){const i=[{key:"local",route:[],label:m("diagnostics-local"),status:"up"},...e.filter(I=>Array.isArray(I.route)&&I.route.length).map(I=>({key:I.route.join("/"),route:I.route,label:I.label||I.name,status:I.status}))],[s,a]=k.useState("local"),c=i.find(I=>I.key===s)||i[0],[d,h]=k.useState(null),[f,g]=k.useState([]),[y,_]=k.useState(""),[w,S]=k.useState(!1),[N,C]=k.useState(!0),[E,x]=k.useState(900),[M,T]=k.useState("all"),[U,z]=k.useState(""),V=k.useRef(0),J=k.useRef(null),q=k.useCallback(async()=>{try{const I=await Zk(t,c.route);if(h(I),_(""),!w){const O=await e2(t,{after:V.current,limit:200},c.route);Array.isArray(O.records)&&O.records.length&&(V.current=O.cursor,g(R=>[...R,...O.records].slice(-500)))}}catch(I){_(I&&I.status===404?m("diagnostics-unsupported"):String(I.message||I))}},[t,c.key,w]);k.useEffect(()=>{V.current=0,g([]),h(null),_("")},[c.key]),k.useEffect(()=>{let I=null,O=!0;const R=()=>{!O||document.visibilityState==="hidden"||q()},A=()=>{I&&clearInterval(I),I=document.visibilityState==="hidden"?null:setInterval(R,2e3),document.visibilityState!=="hidden"&&R()};return document.addEventListener("visibilitychange",A),A(),()=>{O=!1,I&&clearInterval(I),document.removeEventListener("visibilitychange",A)}},[q]),k.useEffect(()=>{N&&J.current&&(J.current.scrollTop=J.current.scrollHeight)},[f,N]);const X=f.filter(I=>(M==="all"||I.level===M)&&(!U||String(I.component||"").toLowerCase().includes(U.toLowerCase()))),H=X.map(I=>`${I.ts} ${I.level.toUpperCase()} ${I.component} ${I.code} ${I.message}${Object.keys(I.meta||{}).length?` ${JSON.stringify(I.meta)}`:""}`).join(`
166
166
  `),P=async I=>{_("");try{const O=await I();h(O),await q()}catch(O){_(String(O.message||O))}},L=async()=>{try{await navigator.clipboard.writeText(H)}catch{_(m("copy-manual"))}},D=()=>{try{const I=new Blob([`${JSON.stringify(X,null,2)}
167
- `],{type:"application/json"}),O=URL.createObjectURL(I),R=document.createElement("a");R.href=O,R.download="nexuscrew-diagnostics.json",R.click(),URL.revokeObjectURL(O)}catch{_(m("diagnostics-export-failed"))}};return l.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[l.jsxs("label",{className:"nc-field",children:[m("diagnostics-target"),l.jsx("select",{value:c.key,onChange:I=>a(I.target.value),children:i.map(I=>l.jsxs("option",{value:I.key,children:[I.label,I.status!=="up"?` · ${I.status}`:""]},I.key))})]}),l.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[l.jsx("div",{className:"nc-sheet-label",children:m("diagnostics-verbose")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("select",{"aria-label":m("diagnostics-duration"),value:E,onChange:I=>x(Number(I.target.value)),disabled:n,children:[300,900,1800,3600].map(I=>l.jsxs("option",{value:I,children:[I/60," min"]},I))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(d==null?void 0:d.verbose)===!0,onClick:()=>P(()=>G_(t,!0,E,c.route)),children:m("enable")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(d==null?void 0:d.verbose)!==!0,onClick:()=>P(()=>G_(t,!1,E,c.route)),children:m("stop")})]}),l.jsx("small",{className:"nc-set-hint",children:d!=null&&d.verbose?m("diagnostics-expires").replace("{time}",new Date(d.expiresAt).toLocaleTimeString()):m("diagnostics-off")})]}),l.jsxs("div",{className:"nc-diag-filters",children:[l.jsxs("select",{"aria-label":m("diagnostics-level"),value:M,onChange:I=>T(I.target.value),children:[l.jsx("option",{value:"all",children:m("diagnostics-all-levels")}),["debug","info","warn","error"].map(I=>l.jsx("option",{value:I,children:I},I))]}),l.jsx("input",{"aria-label":m("diagnostics-component"),placeholder:m("diagnostics-component"),value:U,onChange:I=>z(I.target.value)})]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:w,onChange:I=>S(I.target.checked)})," ",m("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:N,onChange:I=>C(I.target.checked)})," ",m("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:J,className:"nc-diag-log","aria-label":m("diagnostics-log"),children:H||m("diagnostics-empty")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:L,children:m("copy")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:D,children:m("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(m("diagnostics-clear-confirm"))&&P(async()=>{const I=await t2(t,c.route);return V.current=0,g([]),I})},children:m("diagnostics-clear")})]}),y&&l.jsx("div",{className:"nc-err",children:y})]})}function ST({token:t,settings:e,readonly:n,refresh:i,roster:s,section:a,setSection:c}){const[d,h]=k.useState(null),[f,g]=k.useState(null),[y,_]=k.useState(!1),[w,S]=k.useState(!1),[N,C]=k.useState(null),[E,x]=k.useState(!0),[M,T]=k.useState(!1);k.useEffect(()=>{C(e&&e.update||null),x(!e||e.autoUpdate!==!1),T(!!(e&&e.alternateScreen))},[e]);const U=async()=>{h(null),g(null),S(!0);try{const L=await Dk(t);g(L.note||"ok"),_(!1)}catch(L){h(String(L.message||L))}S(!1)},z=async()=>{h(null),g(null),S(!0);try{const L=await Xk(t);g(`${L.note||"ok"}${L.target?` (${L.target})`:""}`)}catch(L){h(String(L.message||L))}S(!1)},V=async L=>{h(null),g(null),S(!0);try{await ep(t,{autoUpdate:L}),x(L),i&&await i()}catch(D){h(String(D.message||D))}S(!1)},J=async L=>{h(null),g(null),S(!0);try{await ep(t,{alternateScreen:L}),T(L),i&&await i()}catch(D){h(String(D.message||D))}S(!1)},q=async()=>{h(null),g(null),S(!0);try{C(await Qk(t))}catch(L){h(String(L.message||L))}S(!1)},X=async()=>{h(null),g(null),S(!0);try{const L=await Jk(t);C(L),g(m("npm-update-restarting"))}catch(L){h(String(L.message||L))}S(!1)},H=()=>{window.confirm(m("composer-clear-confirm"))&&(h(null),pM()?(window.dispatchEvent(new Event(im)),g(m("composer-clear-done"))):h(m("composer-clear-failed")))},P=e&&e.service;return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-system-tabs",role:"tablist","aria-label":m("tab-system"),children:["general","diagnostics"].map(L=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===L,className:`nc-set-tabbtn${a===L?" on":""}`,onClick:()=>c(L),children:m(`system-${L}`)},L))}),a==="general"&&l.jsxs(l.Fragment,{children:[l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-this-node")}),e&&l.jsxs("div",{className:"nc-set-info",children:["v",e.version," · ",e.platform," · :",e.port,l.jsx("br",{}),P&&P.installed?m("service-installed"):m("service-missing"),P&&P.installed?` · ${P.active?m("service-active"):m("service-inactive")}`:"",P?` · boot ${P.boot?"on":"off"}`:""]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w,title:n?m("settings-readonly"):"",onClick:z,children:m("service-regenerate")})}),l.jsx(vT,{token:t,readonly:n}),l.jsx(_T,{})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("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:E,disabled:n||w||N&&!N.supported,onChange:L=>V(L.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("npm-auto-update")}),l.jsx("small",{children:m("npm-auto-update-help")})]})]}),N&&l.jsxs("div",{className:"nc-set-info",children:[m("npm-update-current")," v",N.current,N.latest?` · ${m("npm-update-latest")} v${N.latest}`:""," · ",m(N.supported?N.phase==="idle"&&N.checked!==!0?"npm-update-never":`npm-update-${N.phase}`:"unsupported")]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w||!N||!N.supported,onClick:q,children:m("npm-update-check")}),N&&N.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||w||N.phase==="installing",onClick:X,children:m("npm-update-install")})]}),N&&N.lastError&&l.jsx("div",{className:"nc-err",children:N.lastError})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-security")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w,title:n?m("settings-readonly"):"",onClick:()=>{h(null),g(null),_(!0)},children:m("token-rotate")})})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-local-data")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("composer-clear-data")}),l.jsx("small",{className:"nc-set-hint",children:m("composer-clear-data-help")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:H,children:m("composer-clear-data")})})]})]})]}),a==="diagnostics"&&l.jsxs("section",{className:"nc-system-group nc-system-diagnostics",children:[l.jsx("h3",{children:m("system-diagnostics")}),l.jsxs("div",{className:"nc-set-form nc-alternate-screen-settings",children:[l.jsx("div",{className:"nc-sheet-label",children:m("system-terminal")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":m("alternate-screen"),checked:M,disabled:n||w,onChange:L=>J(L.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("alternate-screen")}),l.jsx("small",{children:m("alternate-screen-help")})]})]})]}),l.jsx(bT,{token:t,roster:s,readonly:n})]}),y&&l.jsxs("div",{className:"nc-set-confirm",children:[l.jsx("div",{children:m("token-rotate-explain")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:w,onClick:()=>_(!1),children:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:w,onClick:U,children:m("confirm")})]})]}),f&&l.jsx("div",{className:"nc-set-note",children:f}),d&&l.jsx("div",{className:"nc-err",children:d})]})}function xT({token:t,onClose:e,initialTab:n="nodes",initialLocation:i="",startNewCell:s=!1}){ui();const a=n==="diagnostics"?"diagnostics":"general",[c,d]=k.useState(n==="diagnostics"?"system":n),h=k.useRef(null),f=k.useRef(null),[g,y]=k.useState({start:!1,end:!1}),[_,w]=k.useState(a),[S,N]=k.useState(null),[C,E]=k.useState([]),[x,M]=k.useState(null),[T,U]=k.useState([]),[z,V]=k.useState(!1),[J,q]=k.useState(null),[X,H]=k.useState(0),P=km(t,!0,X),L=k.useCallback(()=>{const I=h.current;if(!I)return;const O=I.scrollWidth>I.clientWidth+1,R={start:O&&I.scrollLeft>1,end:O&&I.scrollLeft+I.clientWidth<I.scrollWidth-1};y(A=>A.start===R.start&&A.end===R.end?A:R)},[]);k.useEffect(()=>{const I=h.current;if(!I)return;const O=typeof ResizeObserver=="function"?new ResizeObserver(L):null;return O==null||O.observe(I),window.addEventListener("resize",L),L(),()=>{O==null||O.disconnect(),window.removeEventListener("resize",L)}},[L]),k.useEffect(()=>{var O,R;(R=(O=f.current)==null?void 0:O.scrollIntoView)==null||R.call(O,{behavior:"smooth",block:"nearest",inline:"nearest"});const I=window.requestAnimationFrame?window.requestAnimationFrame(L):setTimeout(L,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(I):clearTimeout(I)}},[c,L]);const D=k.useCallback(async()=>{var I;try{const O=await _0(t);N(O),q(null)}catch(O){q(String(O.message||O))}try{const O=await Pk(t),R=O.peers||[];M(Number.isInteger(O.accessRevision)?O.accessRevision:null);let A=[],j=[];try{const[F,$]=await Promise.all([cn("/api/config",t).then(K=>K.json()).catch(()=>null),w0(t).catch(()=>null)]),W=F&&typeof F.instanceId=="string"?F.instanceId:"",ce=[{instanceId:W||null,route:[],label:null},...I0($,W)],ge=await Promise.all(ce.map(async K=>{try{return{ok:!0,peers:((await y0(t,K.route)).nodes||[]).map(te=>D0(te,K)).filter(Boolean)}}catch(oe){return{ok:!1,owner:K,error:oe}}}));for(const K of ge){if(K.ok){A.push(...K.peers);continue}K.owner.route.length!==0&&j.push({instanceId:K.owner.instanceId,label:K.owner.label,route:K.owner.route,failure:/timeout/i.test(String(((I=K.error)==null?void 0:I.message)||K.error))?"timeout":"unreachable"})}}catch{}U(j),E([...R,...A])}catch(O){q(String(O.message||O))}},[t]);return k.useEffect(()=>{D();const I=setInterval(D,5e3);return()=>clearInterval(I)},[D]),k.useEffect(()=>{let I=!1;return cn("/api/config",t).then(O=>O.json()).then(O=>{I||V(!!O.readonlyDefault)}).catch(()=>{}),()=>{I=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:I=>I.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(ht,{name:"gear",size:18}),l.jsx("b",{children:m("settings")}),l.jsx("button",{type:"button",className:"nc-set-close",onClick:e,title:m("close"),children:l.jsx(ht,{name:"x",size:18})})]}),z&&l.jsx("div",{className:"nc-set-readonly",children:m("settings-readonly")}),J&&l.jsx("div",{className:"nc-err",children:J}),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:L,children:["nodes","fleet","audio","input","system"].map(I=>l.jsx("button",{ref:c===I?f:null,type:"button",className:`nc-set-tabbtn${c===I?" on":""}`,onClick:()=>d(I),children:m(`tab-${I}`)},I))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(gT,{token:t,nodes:C,roster:P,settings:S,readonly:z,vlUnavailable:T,accessRevision:x,refresh:D,refreshAliases:()=>H(I=>I+1)}),c==="fleet"&&l.jsx(QP,{token:t,readonly:z,startNewCell:s,initialLocation:i,targets:P.map(I=>({route:I.route,label:I.label||I.name,status:I.status}))}),c==="audio"&&l.jsx(yT,{token:t,readonly:z,nodes:C,settings:S}),c==="input"&&l.jsx(wT,{}),c==="system"&&l.jsx(ST,{token:t,settings:S,readonly:z,refresh:D,roster:P,section:_,setSection:w})]})]})})}function CT({token:t,initialPair:e,deviceDefault:n="",localNodeId:i="",localNameDefault:s="",onPairDone:a,onDone:c}){ui();const[d,h]=k.useState(e?"pair":"welcome"),[f,g]=k.useState(!1),[y,_]=k.useState(null),[w,S]=k.useState(null),N=async()=>{g(!0),_(null);try{await ep(t,{wizardDone:!0}),a&&a(),c()}catch(C){_(String(C.message||C)),g(!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:m("wizard-title")}),l.jsx("small",{children:m("hydra-simple")})]}),d==="welcome"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:m("local-ready")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:N,children:m("local-only")}),l.jsx("button",{className:"nc-btn primary",disabled:f,onClick:()=>h("pair"),children:m("add-node")})]})]}),d==="pair"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx(ix,{token:t,initial:e||"",autoStart:!!e,deviceDefault:n,localNodeId:i,localNameDefault:s,onBusyChange:g,onSuccess:async C=>{S(C&&C.authorizedKeys?{line:C.authorizedKeys,note:C.authorizedKeysNote||""}:null),a&&a(),h("done")}}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:()=>{a&&a(),h("welcome")},children:m("back")})})]}),d==="done"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:m("node-connected")}),w&&l.jsx(cg,{line:w.line,note:w.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:f,onClick:N,children:m("finish")})})]}),y&&l.jsx("div",{className:"nc-err",children:y})]})})}function kT(t,e){if(typeof EventSource>"u"||!t)return()=>{};const n=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return n.onmessage=i=>{try{const s=JSON.parse(i.data);s&&typeof s=="object"&&typeof s.type=="string"&&e(s)}catch{}},()=>{try{n.close()}catch{}}}const ET=6e3,NT=12e3,Gs=(t,e,n)=>`${e||""}:${n||t}`;function Cx(t,e){const n=new Set(t.map(s=>Gs(s.id,s.ownerId,s.ownerAskId))),i=(e||[]).filter(s=>s&&s.id&&!n.has(Gs(s.id,s.ownerId,s.ownerAskId)));return i.length?[...t,...i]:t}function LT(t,e){const n=Cx([],t.filter(a=>a.imported)),i=new Set(n.map(a=>Gs(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!i.has(Gs(a.id,a.ownerId,a.ownerAskId))),...n]}function RT({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:m("feed-owner")})]}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:e,title:m("close"),children:l.jsx(ht,{name:"x",size:14})})]})}function AT({ask:t,token:e,onAnswered:n,onDismiss:i,askReplyAccess:s=!1}){const[a,c]=k.useState(""),[d,h]=k.useState(!1),[f,g]=k.useState(null),[y,_]=k.useState(!1),[w,S]=k.useState(null),[N,C]=k.useState(!1),E=async M=>{const T=String(M||"").trim();if(!(!T||d)){g(null),h(!0);try{if(t.ownerId){const U=t.ownerAskId||t.id,z=await r2(e,{ownerId:t.ownerId,askId:U,text:T});if(z&&z.uncertain){S(z.requestId);return}n(t.id,t.ownerId)}else await i2(e,t.id,T),n(t.id)}catch(U){g(String(U.message||U))}h(!1)}},x=async()=>{if(!y){_(!0);try{if(t.ownerId){if(w)return;await a2(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),i(t.id,t.ownerId)}else await s2(e,t.id),i(t.id)}catch{_(!1)}}};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:m("feed-owner")}),l.jsxs("code",{className:"nc-ask-id",children:["#",t.id]}),l.jsx("button",{type:"button",className:"nc-ask-dismiss",title:m("ask-dismiss"),"aria-label":m("ask-dismiss"),disabled:y||!!t.ownerId&&s===!1,onClick:x,children:l.jsx(ht,{name:"x",size:14})})]}),l.jsx("div",{className:"nc-ask-q",children:t.question}),t.ownerId&&s===!1&&l.jsx("small",{className:"nc-set-hint",children:m("ask-remote-readonly")}),w&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:m("ask-uncertain")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:N,onClick:async()=>{C(!0);try{const M=await o2(e,{ownerId:t.ownerId,askId:t.id,requestId:w});M&&(M.state==="committed"||M.state==="failed")&&i(t.id,t.ownerId)}finally{C(!1)}},children:m("ask-verify")})]}),(!t.ownerId||s===!0)&&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:d,onClick:()=>E(M),children:M},M))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:m("ask-reply-ph"),value:a,disabled:d,onChange:M=>c(M.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:d||!a.trim(),onClick:()=>E(a),children:m("send")})]})]}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function MT({token:t}){const[e]=ui(),[n]=xx(),[i,s]=k.useState([]),[a,c]=k.useState([]),[d,h]=k.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),f=k.useRef(0),g=k.useRef(null);g.current||(g.current=fT());const y=k.useRef({enabled:n,lang:e});y.current={enabled:n,lang:e};const _=k.useCallback(E=>{s(x=>x.filter(M=>M.key!==E))},[]),w=k.useCallback(E=>{const x=`t${f.current+=1}`;s(T=>[...T.slice(-3),{...E,key:x}]),setTimeout(()=>_(x),E.urgency==="high"?NT:ET);const M=y.current;if(M.enabled)try{g.current.enqueue(E,lT(E,M.lang))}catch{}},[_]);k.useEffect(()=>{n||g.current.stop()},[n]),k.useEffect(()=>{const E=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&g.current.stop()},x=()=>g.current.stop();return document.addEventListener("visibilitychange",E),window.addEventListener("blur",E),window.addEventListener(dm,x),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("blur",E),window.removeEventListener(dm,x),typeof g.current.dispose=="function"?g.current.dispose():g.current.stop()}},[]);const S=(E,x)=>c(M=>M.filter(T=>Gs(T.id,T.ownerId)!==Gs(E,x)));k.useEffect(()=>{if(!t)return;let E=!1;n2(t).then(M=>{E||c(T=>LT(T,M.asks))}).catch(()=>{});const x=kT(t,M=>{if(M.type==="notify")w(M);else if(M.type==="ask"&&M.ask&&M.ask.id){const T=Gs(M.ask.id,M.ask.ownerId);c(U=>U.some(z=>Gs(z.id,z.ownerId)===T)?U:[...U,M.ask])}else(M.type==="ask-answered"&&M.id||M.type==="ask-dismissed"&&M.id)&&S(M.id,M.ownerId)});return()=>{E=!0,x()}},[t,w]);const[N,C]=k.useState({});return k.useEffect(()=>{let E=!0;return l2(t).then(x=>{if(!E)return;const M={},T=[];for(const U of x&&x.views||[]){M[U.ownerId]=U.askReplyAccess===!0;for(const z of U.asks||[])z&&z.id&&T.push({...z,ownerId:U.ownerId,imported:!0})}C(M),T.length&&c(U=>Cx(U,T))}).catch(()=>{}),()=>{E=!1}},[t]),l.jsxs(l.Fragment,{children:[i.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:i.map(E=>l.jsx(RT,{n:E,onClose:()=>_(E.key)},E.key))}),a.length>0&&!d&&l.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>h(!0),title:m("asks-title"),children:["? ",l.jsx("span",{className:"nc-ask-count",children:a.length})]}),a.length>0&&d&&l.jsxs("div",{className:"nc-ask-panel",children:[l.jsxs("div",{className:"nc-ask-panel-head",children:[l.jsx("b",{children:m("asks-title")}),l.jsx("span",{className:"nc-ask-count",children:a.length}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>h(!1),title:m("close"),children:l.jsx(ht,{name:"x",size:16})})]}),l.jsx("div",{className:"nc-ask-panel-body",children:a.map(E=>l.jsx(AT,{ask:E,token:t,askReplyAccess:!E.ownerId||N[E.ownerId]===!0,onAnswered:S,onDismiss:S},Gs(E.id,E.ownerId)))})]})]})}const jT=4e3;async function PT(t){const e=await cn("/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 Qf(t,e=[]){var d;const[n,i]=await Promise.allSettled([e.length?wm(t,e):PT(t),Dr(t,e)]),s=n.status==="fulfilled"&&Array.isArray((d=n.value)==null?void 0:d.sessions)?n.value.sessions:Array.isArray(n.value)?n.value:null,a=i.status==="fulfilled"?i.value:null,c=(a==null?void 0:a.available)===!0&&Array.isArray(a.cells)?a.cells:null;return{sessions:s,cells:c,fresh:Array.isArray(s)&&Array.isArray(c)}}function kx(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(i=>(i==null?void 0:i.name)===t.tmuxSession)}function TT(t){const e=new Map((t.sessions||[]).map(s=>[s.name,s])),n=[],i=(s,a,c,d=[],h="")=>{const f=new Map((a||[]).map(g=>[g.name,g]));for(const g of s||[]){const y=f.get(g.tmuxSession)||{},_=Lm(g,y),w=kx(g,a,c);n.push({key:El(d,g.tmuxSession||g.cell),session:g.tmuxSession,route:d,cellName:g.cell,label:g.cell,node:d.length?d.join("/"):"",nodeLabel:h,live:w,selectable:w,verified:c===!0,working:_.working,degraded:!!g.degraded,active:g.active===!0,activity:y.activity||g.activity||0,subtitle:_.subtitle,preview:y.preview||g.preview||"",telemetry:y.telemetry||null,panelUrl:g.panelUrl||""})}};i(t.cells,[...e.values()],t.localFresh===!0);for(const s of t.nodeGroups||[]){const a=Array.isArray(s.route)?s.route:[];s.kind==="vl"||!a.length||i(s.cells,s.sessions,s.switcherFresh===!0,a,s.label||s.name||"")}return n}function DT(t){const e=new Map,n=Array.isArray(t.sessions)?t.sessions:[],i=Array.isArray(t.cells)?t.cells:[],s=new Map(n.map(c=>[c.name,c])),a=new Set(i.map(c=>c.tmuxSession).filter(Boolean));e.set("local",Rm(i,n.filter(c=>!a.has(c.name)),s));for(const c of t.nodeGroups||[]){const d=Array.isArray(c.route)?c.route:[];if(c.kind==="vl"||!d.length)continue;const h=Array.isArray(c.cells)?c.cells:[],f=Array.isArray(c.sessions)?c.sessions:[],g=new Set(h.map(y=>y.tmuxSession).filter(Boolean));e.set(d.join("/"),Au({...c,route:d,cells:h,sessions:f,unmanaged:f.filter(y=>!g.has(y.name))}).rawItems)}return e}function IT(t,e,n,i){return[...new Set(t.map(a=>a.node||"local"))].flatMap(a=>{const c=t.filter(g=>(g.node||"local")===a),d=new Map((e.get(a)||[]).map(g=>[g.key,g])),h=new Map(c.map(g=>[g.key,g])),f=c.map(g=>{const y=d.get(g.key);return{...g,label:(y==null?void 0:y.label)||g.label,live:(y==null?void 0:y.live)??g.live,fresh:(y==null?void 0:y.fresh)===!0,activity:(y==null?void 0:y.activity)??g.activity}});return Mr(f,n,"all",Js(i,a)).map(g=>h.get(g.key))})}function BT({token:t,current:e,onPick:n,onClose:i,panelPort:s=0,nodePanelPorts:a={},hostByRoute:c={},onDesignateCell:d,onClearHostCell:h,onLiveHostApplied:f}){const[g,y]=k.useState(dy),[_,w]=k.useState(!1),[S,N]=k.useState(!1),[C,E]=k.useState(""),[x,M]=k.useState(null),[T,U]=k.useState(""),[z,V]=k.useState(""),J=k.useRef(null),q=k.useRef(null),X=k.useMemo(()=>TT(g),[g]),H=k.useMemo(()=>DT(g),[g]),{pins:P,orders:L,togglePin:D,removePin:I,pinError:O,canMoveRoster:R,moveRoster:A,stepRoster:j}=Nm(),F=k.useMemo(()=>IT(X,H,P,L),[X,H,P,L]),$=k.useMemo(()=>_?F:F.filter(ue=>ue.selectable||ue.degraded&&ue.active),[F,_]),W=k.useMemo(()=>X.find(ue=>ue.key===T&&ue.selectable),[X,T]),ce=k.useMemo(()=>x?X.find(ue=>ue.key===x.key):null,[X,x]);k.useEffect(()=>{O&&O.message&&E(O.message)},[O]),k.useEffect(()=>{var Ne;const ue=document.activeElement;(Ne=q.current)==null||Ne.focus();const ye=Ye=>{Ye.key==="Escape"&&i()};return document.addEventListener("keydown",ye),()=>{var Ye;document.removeEventListener("keydown",ye),(Ye=ue==null?void 0:ue.focus)==null||Ye.call(ue)}},[i]),k.useEffect(()=>{let ue=!0,ye=!1;const Ne=async()=>{if(ye)return;ye=!0;const kt=dy(),bt=Array.isArray(kt.nodeGroups)?kt.nodeGroups:[],st=Qf(t),mt=gt=>gt.kind!=="vl"&&Array.isArray(gt.route)&&gt.route.length>0,Et=await Promise.all(bt.filter(mt).map(async gt=>({group:gt,result:await Qf(t,gt.route)}))),it=await st;if(!ue)return;const It=new Map(Et.map(({group:gt,result:vt})=>[JSON.stringify(gt.route||[]),vt])),Ut=bt.map(gt=>{if(!mt(gt))return{...gt,switcherFresh:!1};const vt=It.get(JSON.stringify(gt.route||[]));return vt?{...gt,sessions:vt.sessions||gt.sessions||[],cells:vt.cells||gt.cells||[],switcherFresh:vt.fresh}:{...gt,switcherFresh:!1}}),Bt=Q0({...kt,sessions:it.sessions||kt.sessions||[],cells:it.cells||kt.cells||[],localFresh:it.fresh,nodeGroups:Ut,refreshedAt:Date.now()});y(Bt),N(!0),ye=!1};Ne();const Ye=setInterval(Ne,jT);return()=>{ue=!1,clearInterval(Ye)}},[t]);const[ge,K]=k.useState(""),oe={getLiveHost:ue=>Xu(t,ue),designateHostCell:(ue,ye,Ne)=>Qu(t,ue,ye,Ne),clearHostCell:(ue,ye)=>Ju(t,ue,ye)},le=ue=>(c[Di(ue)]||{}).hostCell||null,te=async(ue,ye)=>{K(ue.key);const Ne=await j1({action:ye?"remove":"use",cellId:ue.cellName,route:ue.route||[],api:oe});K(""),E(m(Ne.messageKey).replace("{cell}",Ne.hostCell||ue.cellName)),Ne.ok&&f&&f({route:ue.route||[],hostCell:Ne.hostCell,revision:Ne.revision})},fe=ue=>ue.degraded?m("cell-degraded"):ue.verified?ue.selectable?ue.working?m("cell-working"):m("cell-idle"):m("cell-off"):m("cell-switcher-not-confirmed"),Le=ue=>{if(E(""),!ue.selectable){E(ue.verified?m("cell-switcher-not-active"):m("cell-switcher-not-confirmed"));return}U(ue.key)},$e=async()=>{const ue=W;if(!ue){E(m("cell-switcher-select"));return}E(""),V(ue.key);try{const ye=await Qf(t,ue.route),Ne=(ye.cells||[]).find(Ye=>(Ye==null?void 0:Ye.cell)===ue.cellName&&(Ye==null?void 0:Ye.tmuxSession)===ue.session);if(ye.fresh!==!0){E(m("cell-switcher-verify-failed"));return}if(!kx(Ne,ye.sessions,ye.fresh)){E(m("cell-switcher-not-active"));return}n({session:ue.session,...ue.node?{node:ue.node}:{},cellName:ue.cellName}),i()}catch{E(m("cell-switcher-verify-failed"))}finally{V("")}};return l.jsx("div",{className:"nc-cell-switcher-backdrop",onClick:i,children:l.jsxs("aside",{ref:J,className:"nc-cell-switcher",role:"dialog","aria-label":m("fleet-cells"),tabIndex:-1,onClick:ue=>ue.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-list",children:[l.jsx(R1,{className:"nc-cell-switcher-live-host",view:Hu({liveHost:c[Di([])],cells:g.cells||[]})}),!S&&l.jsx("div",{className:"nc-empty",role:"status",children:m("cell-switcher-refreshing")}),S&&$.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:m("cell-switcher-empty-active")}),$.map(ue=>{const ye=(e==null?void 0:e.session)===ue.session&&((e==null?void 0:e.node)||"")===ue.node,Ne=T===ue.key,Ye=fe(ue),kt=rm(m,ue.activity),bt=om(m,ue.telemetry),st=[kt,bt].filter(Boolean).join(" · "),mt=ue.node||"local",Et=H.get(mt)||X.filter(it=>(it.node||"local")===mt);return l.jsxs("div",{className:`nc-cell-switcher-row${ye?" current":""}${Ne?" selected":""}${ue.selectable?"":" off"}`,"data-roster-key":ue.key,"data-position":mt,children:[l.jsx(Ss,{position:mt,itemKey:ue.key,label:ue.cellName,canMove:R,onMove:(it,It)=>A(mt,it,It,Et),onStep:it=>j(mt,ue.key,it,Et)}),l.jsx("button",{type:"button",className:"nc-cell-switcher-peek",title:m("cell-peek"),"aria-label":`${m("cell-peek")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"preview"})},children:l.jsx("span",{className:`nc-cell-switcher-dot${ue.degraded?" warn":ue.live?` on${ue.working?" working":""}`:""}`})}),l.jsxs("span",{className:"nc-cell-switcher-acts",children:[l.jsx("button",{type:"button",className:"nc-cell-switcher-act",title:m("cell-peek-stream"),"aria-label":`${m("cell-peek-stream")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"stream"})},children:"▶"}),ue.panelUrl&&l.jsx("button",{type:"button",className:"nc-cell-switcher-act",title:m("cell-peek-panel"),"aria-label":`${m("cell-peek-panel")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"panel"})},children:"▣"})]}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":ye?"true":void 0,"aria-pressed":Ne,"aria-disabled":!ue.selectable,disabled:z===ue.key,onClick:()=>Le(ue),children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsx("b",{children:ue.cellName}),l.jsx("small",{className:"nc-cell-switcher-state",children:Ye}),l.jsx("small",{children:[ue.nodeLabel,ue.subtitle].filter(Boolean).join(" · ")}),st&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:st})]})}),l.jsx(Eu,{item:{key:ue.key,value:{cell:ue.cellName}},pins:P,hostByRoute:c,route:ue.route||[],cellName:ue.cellName,baseClassName:"nc-cell-switcher-star",togglePin:D,removePin:I,onOutcome:it=>{it.ok||E(m(ku(it.error)))}}),l.jsx("button",{type:"button",className:`nc-cell-switcher-act nc-cell-switcher-host${le(ue.route||[])===ue.cellName?" on":""}`,"data-testid":`live-host-command-${ue.key}`,"data-live-host-state":le(ue.route||[])===ue.cellName?"host":"idle",disabled:ge===ue.key,title:le(ue.route||[])===ue.cellName?m("live-host-action-remove"):m("live-host-action-use"),"aria-label":`${le(ue.route||[])===ue.cellName?m("live-host-action-remove"):m("live-host-action-use")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),te(ue,le(ue.route||[])===ue.cellName)},children:l.jsx(ht,{name:"broadcast",size:18})})]},ue.key)})]}),C&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:C}),x&&ce&&l.jsx(P1,{row:ce,token:t,initialSource:x.source,panelPort:Uu(ce.route||[],a,s),liveHost:Hu({liveHost:c[Di(ce.route||[])],cells:g.cells||[]}),onLiveHostApplied:f,onClose:()=>M(null)}),l.jsx("div",{className:"nc-cell-switcher-actions",children:l.jsx("button",{type:"button",className:"nc-cell-switcher-open",disabled:!W||!!z,onClick:$e,children:W?`${m("cell-switcher-open")}: ${W.cellName}`:m("cell-switcher-select")})}),l.jsxs("div",{className:"nc-cell-switcher-controls",children:[l.jsx("b",{children:m("fleet-cells")}),l.jsx("button",{type:"button",className:"nc-cell-switcher-filter","aria-pressed":_,onClick:()=>{E(""),w(ue=>!ue)},children:m(_?"cell-switcher-show-active":"cell-switcher-show-all")}),l.jsx("button",{ref:q,type:"button",className:"nc-cell-switcher-close","aria-label":m("cell-switcher-close"),title:m("cell-switcher-close"),onClick:i,children:"×"})]})]})})}const OT=2e3;function $T(t){if(t.kind==="gap")return`${m("vl-events-gap")} ${t.count||"?"}`;if(t.kind==="truncate")return m("vl-events-truncated");if(t.kind==="turn_end")return m("vl-events-turn-end");if(t.kind==="done")return m("vl-events-done");if(t.kind==="writer_epoch")return m("vl-events-writer-epoch");if(t.kind==="tool_start")return`${m("vl-events-tool")} ${t.name||""}`.trim();if(t.kind==="tool_end"){const e=t.isError?m("vl-events-tool-failed"):m("vl-events-tool-ok");return`${m("vl-events-tool")} ${t.name||""} — ${e}`.trim()}return t.kind==="usage"?t.text||m("vl-events-usage"):t.text||""}function zT({token:t,nodeId:e,route:n=[]}){const[i,s]=k.useState([]),[a,c]=k.useState(!1),d=k.useRef(0),h=k.useRef(!1);return k.useEffect(()=>{let f=!0;d.current=0,h.current=!1,s([]);const g=async()=>{if(!h.current){h.current=!0;try{const w=await Tk(t,e,d.current,n);if(!f)return;c(!1);const N=(Array.isArray(w==null?void 0:w.events)?w.events:[]).filter(C=>Number.isSafeInteger(C==null?void 0:C.seq)&&C.seq>d.current);N.length&&(s(C=>C.concat(N).slice(-500)),d.current=N[N.length-1].seq),Number.isSafeInteger(w==null?void 0:w.cursor)&&w.cursor>d.current&&(d.current=w.cursor)}catch{f&&c(!0)}finally{h.current=!1}}},y=()=>{g().catch(()=>{})};y();const _=setInterval(y,OT);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:m("vl-events-stale")}),i.length===0&&!a&&l.jsx("small",{className:"nc-set-hint","data-testid":"vl-events-empty",children:m("vl-events-empty")}),i.length>0&&l.jsx("ol",{className:"nc-vl-events-list",children:i.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:$T(f)},`${f.seq}-${f.kind}`))})]})}function Zb({peer:t,token:e,onBack:n}){var i;return ui(),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:m("back"),children:[l.jsx(ht,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:m("back")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:t.label,children:t.label}),((i=t.session)==null?void 0:i.profile)&&l.jsxs("small",{className:"nc-bar-sub",children:[t.session.profile," · ",m("vl-events-title")]})]}),l.jsx("span",{className:"nc-bar-right"})]}),l.jsx("div",{className:"nc-vl-session-body",children:l.jsx(zT,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Jf=t=>as(Cs(t)).length===0,Zf=t=>Array.isArray(t)?t.join("/"):"";function FT(t){const e=new Set,n=[];for(const i of Array.isArray(t)?t:[])!i||!Ii.test(String(i.instanceId||""))||!Array.isArray(i.route)||!i.route.length||e.has(i.instanceId)||(e.add(i.instanceId),n.push({instanceId:i.instanceId,route:[...i.route],label:String(i.label||i.name||i.route.join(" › ")),status:i.status||"offline"}));return n.sort((i,s)=>i.label.localeCompare(s.label))}function hl(t){return{instanceId:t.ownerId,route:t.ownerRoute||[],label:t.ownerLabel,status:t.available===!1?"offline":"up"}}function no(t,e,n,i=!1,s=!0){const a=e.instanceId;return{...t,id:fo(i?null:a,t.name),ownerId:a,ownerRoute:i?[]:[...e.route],ownerLabel:i?"Local":e.label,local:i,available:s,ownerTopology:Array.isArray(n)?n:[],layout:am(t.layout,a,n)}}function HT(t,e,n,i,s=[]){const[a,c]=k.useState([]),[d,h]=k.useState(!1),[f,g]=k.useState("idle"),[y,_]=k.useState(""),[w,S]=k.useState(!1),[N,C]=k.useState(""),E=k.useRef([]),x=k.useRef([]),M=k.useRef(""),T=k.useRef(e),U=k.useRef(n),z=k.useRef(!1),V=k.useRef(!0),J=k.useRef(""),q=k.useMemo(()=>FT(s),[s]),X=q.map(K=>`${K.instanceId}:${Zf(K.route)}:${K.status}:${K.label}`).join("|");x.current=q,U.current=n,T.current=e,E.current=a;const H=k.useCallback(K=>lm(K.layout,M.current,x.current),[]),P=k.useCallback(()=>ul(T.current,M.current),[]),L=k.useCallback(K=>(Array.isArray(K)?K:[]).find(oe=>oe.id===P()),[P]),D=k.useCallback((K,oe=!0,le)=>{const te=le===void 0?P():ul(le,M.current),fe=nb(K,su()),Le=E.current.some(ue=>ue.id===te);E.current=fe,c(fe);const $e=fe.find(ue=>ue.id===te);if(oe&&$e){V.current=!0;const ue=H($e);i(ue),$e.local&&QM($e.name,ue)}else Le&&!$e&&(V.current=!0,i(na()),_("deck non più condiviso dal nodo owner"));VM(fe.filter(ue=>ue.local).map(ue=>ue.name))},[i,H]),I=k.useCallback(async K=>{let oe=await qc(t);const le=oe.decks.find(te=>te.name==="main");if(oe.decks.length===1&&le&&le.revision===0&&Jf(le.layout)){const te=KM(),fe=Cs(cm("main")||na());if(!Jf(fe)){const Le=am(fe,K,[]);oe.decks[0]=await Kc(t,"main",Le,0,[])}for(const Le of te.filter($e=>$e!=="main"))try{let $e=await X_(t,Le,[]);const ue=Cs(cm(Le)||na());Jf(ue)||($e=await Kc(t,Le,am(ue,K,[]),$e.revision,[]))}catch{}oe=await qc(t)}return oe},[t]),O=k.useCallback(async({migrate:K=!1}={})=>{const oe=await bm(t,[]),le=Ii.test(String(oe.instanceId||""))?oe.instanceId:"";if(!le)throw new Error("instanceId locale non disponibile");M.current=le,C(le);const[te,fe]=await Promise.all([K?I(le):qc(t),V_(t,[]).catch(()=>({nodes:[]}))]),Le={instanceId:le,route:[],label:"Local"},$e=te.decks.map(ye=>no(ye,Le,fe.nodes,!0,!0)),ue=E.current;return await Promise.all(x.current.map(async ye=>{if(ye.status!=="up"){$e.push(...ue.filter(Ne=>!Ne.local&&Ne.ownerId===ye.instanceId).map(Ne=>({...Ne,ownerRoute:[...ye.route],ownerLabel:ye.label,available:!1})));return}try{const[Ne,Ye]=await Promise.all([qc(t,ye.route),V_(t,ye.route).catch(()=>({nodes:[]}))]);$e.push(...Ne.decks.map(kt=>no(kt,ye,Ye.nodes,!1,!0)))}catch{$e.push(...ue.filter(Ye=>!Ye.local&&Ye.ownerId===ye.instanceId).map(Ye=>({...Ye,ownerRoute:[...ye.route],ownerLabel:ye.label,available:!1})))}})),$e.sort((ye,Ne)=>ye.local===Ne.local?ye.ownerLabel.localeCompare(Ne.ownerLabel)||(ye.name==="main"?-1:Ne.name==="main"?1:ye.name.localeCompare(Ne.name)):ye.local?-1:1),$e},[t,I,X]);k.useEffect(()=>{if(!t)return;let K=!1;const oe=J.current!==t;return J.current=t,O({migrate:oe}).then(le=>{if(K)return;const te=L(E.current),fe=L(le),Le=fe&&(!te||fe.revision>te.revision||te.available!==fe.available||Zf(te.ownerRoute)!==Zf(fe.ownerRoute));D(le,oe||!!Le&&!z.current),h(!0),fe&&_("")}).catch(le=>{K||(h(!0),_(String(le.message||le)))}),()=>{K=!0}},[D,O,X,t,L]);const R=k.useCallback(async(K,oe=!0)=>{if(!d||!z.current)return!0;const le=K===void 0?P():ul(K,M.current),te=E.current.find(fe=>fe.id===le);if(!te)return _(`deck inesistente: ${le}`),!1;if(te.available===!1)return _(`nodo owner offline: ${te.ownerLabel}`),!1;g("saving");try{const fe=xf(Cs(U.current),te.ownerId,te.ownerTopology),Le=await Kc(t,te.name,fe,te.revision,te.ownerRoute),$e=no(Le,hl(te),te.ownerTopology,te.local,!0);return D(E.current.map(ue=>ue.id===le?$e:ue),!1),z.current=!1,g("saved"),_(""),S(!1),setTimeout(()=>g("idle"),1500),!0}catch(fe){if(oe&&fe.status===409&&fe.data&&fe.data.current){const Le=E.current.find($e=>$e.id===le);if(Le){const $e=no(fe.data.current,hl(Le),Le.ownerTopology,Le.local,!0);return D(E.current.map(ue=>ue.id===le?$e:ue),!1),z.current=!0,R(le,!1)}}return g("error"),_(String(fe.message||fe)),fe.status===409&&S(!0),!1}},[d,t,D]),A=k.useCallback(async()=>{try{const K=await O();z.current=!1,S(!1),D(K,!0),_("")}catch(K){_(String(K.message||K))}},[O,D]);return k.useEffect(()=>{if(!d)return;if(V.current){V.current=!1;return}z.current=!0,g("saving");const K=setTimeout(R,650);return()=>clearTimeout(K)},[n,d,R]),k.useEffect(()=>{if(!d)return;const K=()=>{if(!z.current)return;const oe=E.current.find(te=>te.id===P());if(!oe||oe.available===!1)return;const le=xf(Cs(U.current),oe.ownerId,oe.ownerTopology);c2(t,oe.name,le,oe.revision,oe.ownerRoute)};return window.addEventListener("pagehide",K),window.addEventListener("beforeunload",K),()=>{window.removeEventListener("pagehide",K),window.removeEventListener("beforeunload",K)}},[d,t,P]),k.useEffect(()=>{if(!d)return;const K=setInterval(async()=>{try{const oe=await O(),le=L(E.current),te=L(oe),fe=te&&(!le||te.revision>le.revision||le.available!==te.available);if(fe&&z.current&&te){const Le=Z2(H(te),U.current);D(oe,!1),i(Le);return}D(oe,fe&&!z.current)}catch{}},5e3);return()=>clearInterval(K)},[d,O,D,H,i]),{decks:a,records:a,localNodeId:N,ready:d,saveState:f,error:y,setError:_,conflict:w,reloadCurrent:A,saveNow:R,select:async K=>{if(z.current&&!await R(P()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const oe=E.current.find(le=>le.id===K);if(!oe)throw new Error(`deck inesistente: ${K}`);return z.current=!1,V.current=!0,H(oe)},add:async(K,oe=null)=>{const le=oe===xs?E.current.find(Le=>Le.local):oe?E.current.find(Le=>Le.ownerId===oe):null;if(!le||le.available===!1)throw new Error("nodo owner non disponibile");const te=await X_(t,K,le.ownerRoute),fe=no(te,hl(le),le.ownerTopology,le.local,!0);return D([...E.current,fe],!1),fe},rename:async(K,oe)=>{const le=E.current.find(ue=>ue.id===K);if(!le)throw new Error("deck inesistente");if(ul(K,M.current)===P()&&z.current&&!await R(K))throw new Error(`salvataggio di "${le.name}" fallito: rinomina annullata`);const te=E.current.find(ue=>ue.id===K);if(!te)throw new Error("deck inesistente");const fe=await u2(t,te.name,oe,te.revision,te.ownerRoute),Le=no(fe,hl(te),te.ownerTopology,te.local,!0),$e=te.local?xs:te.ownerId;return kf(GM(su(),$e,K,Le.id)),D(E.current.map(ue=>ue.id===K?Le:ue),!1),Le},remove:async K=>{const oe=E.current.find(te=>te.id===K);if(!oe)throw new Error("deck inesistente");ul(K,M.current)===P()&&(z.current=!1),await d2(t,oe.name,oe.revision,oe.ownerRoute);const le=oe.local?xs:oe.ownerId;kf(XM(su(),le,K)),D(E.current.filter(te=>te.id!==K),!1)},reorder:(K,oe)=>{const le=E.current.find(ye=>ye.id===K),te=E.current.find(ye=>ye.id===oe);if(!le||!te)return!1;const fe=le.local?xs:le.ownerId,Le=te.local?xs:te.ownerId;if(fe!==Le)return!1;const $e=E.current.filter(ye=>(ye.local?xs:ye.ownerId)===fe).map(ye=>ye.id),ue=kf(YM(su(),fe,K,oe,$e));return D(nb(E.current,ue),!1),!0},addTileTo:async(K,oe)=>{const le=E.current.find(ye=>ye.id===K);if(!le)throw new Error("deck inesistente");if(le.available===!1)throw new Error(`nodo owner offline: ${le.ownerLabel}`);const te=$1(oe,M.current,x.current);if(!te)throw new Error("riferimento sessione non valido");const fe=H(le),Le=xf(jm(fe,te),le.ownerId,le.ownerTopology),$e=await Kc(t,le.name,Le,le.revision,le.ownerRoute),ue=no($e,hl(le),le.ownerTopology,le.local,!0);return D(E.current.map(ye=>ye.id===K?ue:ye),!1),ue},localMainId:fo(null,"main"),parseDeckId:zl}}const UT="/sw.js",fm="nc-sw-update";let Pl=null,qu=!1,Ku=null,Ex=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),Nx=!1;function _g(){typeof window<"u"&&window.dispatchEvent(new Event(fm))}function yg(){const t=Ku||(qu?{kind:"reload",version:"",browserVersion:""}:null);Ex=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 e0(){return Ex}function WT(t){return typeof window>"u"?()=>{}:(window.addEventListener(fm,t),()=>window.removeEventListener(fm,t))}function wg(t){qu!==t&&(qu=t,yg(),_g())}const uu="nc-auto-reload",Vu="nc-reload";function bg(){try{return typeof location<"u"?location:null}catch{return null}}function Lx(){try{return typeof history<"u"?history:null}catch{return null}}function qT(t){const e=t===void 0?bg():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Vu)}catch{return null}}function KT(t,{location:e,history:n}={}){const i=e===void 0?bg():e,s=n===void 0?Lx():n;if(!i||!s||typeof s.replaceState!="function")return!1;try{const a=new URLSearchParams(i.search||"");return a.set(Vu,t),s.replaceState(s.state??null,"",`${i.pathname||"/"}?${a.toString()}${i.hash||""}`),!0}catch{return!1}}function VT({location:t,history:e}={}){const n=t===void 0?bg():t,i=e===void 0?Lx():e;if(!n||!i||typeof i.replaceState!="function")return!1;try{const s=new URLSearchParams(n.search||"");if(!s.has(Vu))return!1;s.delete(Vu);const a=s.toString();return i.replaceState(i.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const Rx="nc-update-dismissed";function Ax(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function YT(t,e,n){return[t,e,n].map(i=>i||"").join("|")}let pm=null;function GT(t,e,n){const i=n;return t&&e&&t!==e&&t!==i?{kind:"install",version:t,browserVersion:i}:e&&i&&e!==i?{kind:"stale",version:e,browserVersion:i}:null}function XT(t,e){if(!t)return!1;try{return t.getItem(Rx)===e}catch{return!1}}function QT(t={}){const e=t.storage===void 0?Ax():t.storage;if(pm&&e)try{e.setItem(Rx,pm)}catch{}qu=!1,Ku=null,yg(),_g()}function JT(t,e,n,i={}){const s=i.storage===void 0?Ax():i.storage,a=n,c=YT(t,e,a);pm=c;const d=GT(t,e,a);let h=XT(s,c)?null:d;if(h&&h.kind==="stale"){const g=`${e}|${a}`,y=qT(i.location)===g;let _=!1;if(!y&&s&&s.getItem(uu)!==g){try{s.setItem(uu,g)}catch{}_=s.getItem(uu)===g}_&&(KT(g,{location:i.location,history:i.history}),(i.applyImpl||Mx)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Ku);if(Ku=h,yg(),f||_g(),!d){try{s&&s.removeItem(uu)}catch{}VT({location:i.location,history:i.history})}}const ZT=1200;async function t0(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,ZT))])}catch{}}async function Mx(){try{Pl&&await Pl.update()}catch{}typeof location<"u"&&(await t0(location.pathname),await t0("/version.json"),location.reload())}function e3(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&wg(!0)})}function t3(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{Nx&&location.reload()}),navigator.serviceWorker.register(UT).then(t=>{Pl=t,t.waiting&&wg(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&e3(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function n3(){Nx=!0,wg(!1);const t=Pl&&Pl.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function i3({hash:t="",origin:e="",pathname:n="",search:i=""}={}){const s=String(t||"").replace(/^#/,""),a=`${n||""}${i||""}`;if(!s)return{token:"",pair:"",nextUrl:a};const c=new URLSearchParams(s),d=c.get("token")||"",h=c.get("pair")||"",f=h?`${e||""}${n||""}#pair=${h}`:"";return{token:d,pair:f,nextUrl:a}}const jx=9,Px=24,Tx="nc_side_w",n0="nc_side_min",s3=240,i0=new Set(["absent","present","active","unknown"]);function r3(){const t=Number(localStorage.getItem(Tx));return t>=180&&t<=480?t:s3}function o3(){const t=Number(localStorage.getItem("nc_fontsize"));return t>=jx&&t<=Px?t:13}function a3(){const t={token:"",pair:""};try{const{token:e,pair:n,nextUrl:i}=i3({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e){t.token=e;try{localStorage.setItem("nc_token",e)}catch{}}if(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=sessionStorage.getItem("nc_token")||localStorage.getItem("nc_token")||""),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function s0(t){try{return Cs(cm(t))}catch{return na()}}function r0(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 o0({session:t,node:e,ownerId:n,cellName:i,token:s,readonly:a=!1,panelPort:c=0,onBack:d,onCellSwitcher:h,cellSwitcherOpen:f=!1,liveHost:g=null}){ui();const[y]=Zm(),[_,w]=k.useState(!1),[S,N]=k.useState(()=>window.matchMedia("(pointer: coarse)").matches),[C,E]=k.useState(null),[x,M]=k.useState(o3),[T,U]=k.useState(xl),[z,V]=k.useState(()=>xl()),J=()=>{const fe=fA(pA(xl()));U(fe),typeof window<"u"&&window.location.reload()},[q,X]=k.useState(i||t),[H,P]=k.useState(""),[L,D]=k.useState(""),[I,O]=k.useState(""),[R,A]=k.useState(!1),j=fe=>M(Le=>{const $e=Math.max(jx,Math.min(Px,Le+fe));return localStorage.setItem("nc_fontsize",String($e)),$e}),F=k.useRef(()=>{}),$=k.useRef(()=>!1),W=k.useRef(()=>{}),ce=k.useRef(!1),[ge,K]=k.useState(!1),[oe,le]=k.useState(!1),te=()=>{ce.current=!ce.current,K(ce.current)};return k.useEffect(()=>{X(i||t),A(!1)},[i,t]),k.useEffect(()=>{let fe=!0;const Le=e?e.split("/"):[],$e=e?`/api/route/${e.split("/").map(encodeURIComponent).join("/")}/_`:"/api";async function ue(){let Ne=null,Ye=null;try{const st=await(await cn(`${$e}/sessions`,s)).json();Array.isArray(st.sessions)&&(Ne=st.sessions.find(mt=>mt.name===t))}catch{}try{const bt=await Dr(s,Le);bt.available&&Array.isArray(bt.cells)&&(Ye=bt.cells.find(st=>st.tmuxSession===t))}catch{}if(!fe)return;X(eg({session:t,cell:Ye||(i?{cell:i}:null)})),D(typeof(Ye==null?void 0:Ye.panelUrl)=="string"?Ye.panelUrl.trim():""),O(typeof(Ye==null?void 0:Ye.cell)=="string"?Ye.cell:"");let kt="";Ye?kt=`${Ye.engine}${Ye.key?`·${Ye.key}`:""}`:Ne&&(kt=Ne.attached?`attached · ${r0(Ne.activity)}`:Ne.activity?r0(Ne.activity):""),P(kt)}ue();const ye=setInterval(ue,4e3);return()=>{fe=!1,clearInterval(ye)}},[t,e,s]),l.jsxs("div",{className:"nc-app",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:d,title:m("sessions"),children:[l.jsx(ht,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:m("sessions")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:e?`${q} · ${e}`:q,children:q}),g&&g.cell&&g.cell===i?l.jsx("span",{className:`nc-live-host-dot ${L1(g)} nc-live-host-dot-header`,"data-testid":"live-host-header-dot",title:m("live-host-indicator").replace("{cell}",g.cell).replace("{mode}",m(g.mode?`live-host-mode-${g.mode}`:"live-host-mode-unknown")).replace("{state}",m(`live-host-state-${g.state}`))}):null,H&&l.jsx("small",{className:"nc-bar-sub",children:H})]}),l.jsxs("span",{className:"nc-bar-right",children:[l.jsx("button",{onClick:()=>j(-1),title:m("zoom-out"),children:l.jsx(ht,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>j(1),title:m("zoom-in"),children:l.jsx(ht,{name:"zoomIn",size:18})}),l.jsx("button",{type:"button",className:`nc-renderer-toggle${z==="webgl"?" on":""}`,onClick:J,"aria-pressed":z==="webgl",title:m("terminal-renderer-switch").replace("{requested}",m(T==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")).replace("{effective}",m(z==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")),"aria-label":m("terminal-renderer-switch").replace("{requested}",m(T==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")).replace("{effective}",m(z==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")),children:l.jsx(ht,{name:"gpu",size:18})}),l.jsx("button",{onClick:()=>N(fe=>!fe),title:m("composer"),children:l.jsx(ht,{name:"keyboard",size:20})}),l.jsx("button",{onClick:()=>w(fe=>!fe),title:m("files"),children:l.jsx(ht,{name:"folder",size:20})}),L&&l.jsx("button",{onClick:()=>A(fe=>!fe),title:m("panel"),"aria-pressed":R,children:l.jsx(ht,{name:"monitor",size:20})})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[l.jsx(Vm,{session:t,node:e,token:s,readonly:a,takeSize:!0,sendRef:F,composerRef:$,actionRef:W,ctrlRef:ce,setCtrlArmed:K,onFiles:E,fontSize:x,selectionMode:oe,onSelectionModeChange:le,keyboardGesture:y.terminalKeyboardGesture,onRendererChange:V}),R&&L&&I&&l.jsx(Xm,{cellId:I,panelUrl:L,route:e?e.split("/"):[],panelPort:c,token:s,title:q})]}),l.jsx(iM,{onKeyboard:()=>N(fe=>!fe),onCellSwitcher:h,cellSwitcherOpen:f,send:fe=>F.current(fe),action:fe=>W.current(fe),ctrlArmed:ge,onCtrl:te,selectionMode:oe,onSelectionMode:le,keepKeyboardClosed:y.keybarKeepsKeyboardClosed,showEnter:y.showKeybarEnter,keybarLayout:y.keybarLayout}),S&&l.jsx(N1,{submitText:fe=>$.current(fe),token:s,session:t,node:e,ownerId:n,readonly:a,keepKeyboardClosedOnVoice:y.voiceKeepsKeyboardClosed}),_&&l.jsx(_1,{session:t,node:e,token:s,filesEvent:C,onClose:()=>w(!1)})]})}function l3(){ui();const[t]=k.useState(a3),[e,n]=k.useState(t.token),[i,s]=k.useState(t.pair||""),a=k.useCallback(()=>{s("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),[c,d]=k.useState(!1),h=DA(),[f]=k.useState(()=>qM(typeof location<"u"?location.pathname:"/")),[g,y]=k.useState(f.id),_=g===fo(null,Bi),[w,S]=k.useState(null),N=me=>{const Ce=Tr(me);S(Ce?{...Ce,...typeof(me==null?void 0:me.cellName)=="string"&&me.cellName?{cellName:me.cellName}:{}}:null)},[C,E]=k.useState([]),[x,M]=k.useState([]),[T,U]=k.useState([]),[z,V]=k.useState(!1),[J,q]=k.useState(null),[X,H]=k.useState(()=>f.ownerId?na():s0(f.name)),[P,L]=k.useState(null),[D,I]=k.useState(null),O=me=>I(Tr(me)),[R,A]=k.useState(null),j=km(e,h),F=k.useMemo(()=>(j||[]).filter(me=>me.instanceId).map(me=>({instanceId:me.instanceId,route:me.route,label:me.label,status:me.status})),[j]),$=HT(e,g,X,H,F),W=$.decks;k.useEffect(()=>{const me=new Map;for(const Ce of j||[]){const Me=(Ce.route||[Ce.name]).join("/"),Ze=new Set((Ce.sessions||[]).map(at=>at.name));for(const at of Ce.cells||[])!at.cell||!at.tmuxSession||at.cell===at.tmuxSession||Ze.has(at.cell)||me.set(`${Me}:${at.cell}`,`${Me}:${at.tmuxSession}`)}H(Ce=>Y2(Ce,me))},[j]),k.useEffect(()=>{$.localNodeId&&(f.ownerId&&f.ownerId===$.localNodeId&&H(me=>me.columns.some(Ce=>Ce.tiles.length)?me:s0(f.name)),H(me=>{const Ce=lm(me,$.localNodeId,F);return JSON.stringify(Ce)===JSON.stringify(me)?me:Ce}))},[F,$.localNodeId]);const[ce,ge]=k.useState(null),[K,oe]=k.useState(null),le=k.useRef(0),[te,fe]=k.useState(!1),[Le,$e]=k.useState(r3),[ue,ye]=k.useState(!_),[Ne,Ye]=k.useState(()=>_?localStorage.getItem(n0)==="1":!0),[kt,bt]=k.useState(!1),[st,mt]=k.useState("nodes"),[Et,it]=k.useState(!1),[It,Ut]=k.useState(""),[Bt,gt]=k.useState(!1),vt=(me="nodes",Ce=!1,Me="")=>{mt(me),it(Ce),Ut(Me),bt(!0)},[un,re]=k.useState(!1),[et,jt]=k.useState({deviceDefault:"",localNodeId:"",localNameDefault:""}),[ae,se]=k.useState(!1),[Z,_e]=k.useState(0),[xe,rt]=k.useState({});k.useEffect(()=>{try{localStorage.setItem(Tx,String(Le))}catch{}},[Le]),k.useEffect(()=>{try{localStorage.setItem(n0,Ne?"1":"")}catch{}},[Ne]),k.useEffect(()=>{if(!e)return;let me=!1;return Promise.all([_0(e),cn("/api/config",e).then(Ce=>Ce.json())]).then(([Ce,Me])=>{me||(jt({deviceDefault:Ce.deviceName||"",localNodeId:Ce.nodeId||"",localNameDefault:Ce.localName||""}),se(!!Me.readonlyDefault),_e(Number.isInteger(Me.panelPort)?Me.panelPort:0),rt(Me.nodePanelPorts&&typeof Me.nodePanelPorts=="object"&&!Array.isArray(Me.nodePanelPorts)?Me.nodePanelPorts:{}),(Ce.firstRun===!0&&!Me.readonlyDefault||i)&&re(!0))}).catch(()=>{}),()=>{me=!0}},[e,i]);const[ct,pt]=k.useState({}),At=k.useCallback(({route:me,hostCell:Ce,revision:Me})=>{const Ze=Di(me);pt(at=>({...at,[Ze]:{hostCell:Ce||null,hostLease:null,hostRevision:Number.isInteger(Me)?Me:(at[Ze]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Wt=me=>{const Ce=Di(me),Me=me.length?((j||[]).find(Ze=>Di(Array.isArray(Ze.route)?Ze.route:[])===Ce)||{}).cells||[]:x;return Hu({liveHost:ct[Ce]||null,cells:Me,localNodeId:$.localNodeId,ownerId:me.length?Ce:$.localNodeId})},Nt=k.useRef(j);k.useEffect(()=>{Nt.current=j},[j]);const Lt=k.useCallback(async()=>{try{const at=await(await cn("/api/sessions",e)).json();at.error||E(at.sessions||[])}catch{}let me=null,Ce=null;try{me=await Dr(e)}catch(Ze){Ce=Ze}const Me=Cm({fs:me,error:Ce});Me.kind==="data"?(M(Me.cells),U(Me.capabilities),V(!1),q(null)):Me.kind==="stale"?(V(!0),q(null)):(M([]),U([]),V(!1),q(Me.reason||""))},[e]);k.useEffect(()=>{let me=!1;const Ce=async()=>{const Ze=[[],...(Nt.current||[]).filter(Ot=>Ot.kind!=="vl"&&Ot.status==="up").map(Ot=>Array.isArray(Ot.route)&&Ot.route.length?Ot.route:[Ot.name])],at=await Promise.all(Ze.map(async Ot=>{const $t=Di(Ot);try{const sn=await Xu(e,Ot);return[$t,{hostCell:sn&&typeof sn.hostCell=="string"?sn.hostCell:null,hostLease:sn&&sn.host&&typeof sn.host.lease=="string"?sn.host.lease:null,hostRevision:Number.isInteger(sn&&sn.revision)?sn.revision:0,threadStatus:sn&&i0.has(sn.threadStatus)?sn.threadStatus:"unknown"}]}catch{return[$t,{error:!0}]}}));me||pt(Ot=>{let $t=!1;const sn={...Ot};for(const Oi of at){if(!Oi)continue;const[fi,Ms]=Oi;sn[fi]=Ms.error?{...Ot[fi]||{},threadStatus:"unknown"}:Ms,$t=!0}return $t?sn:Ot})};Ce();const Me=setInterval(Ce,4e3);return()=>{me=!0,clearInterval(Me)}},[e]),k.useEffect(()=>{if(!h)return;Lt();const me=setInterval(Lt,4e3);return()=>clearInterval(me)},[h,Lt]);const Q=k.useCallback(async(me,Ce=[])=>{const Me=Di(Ce),Ze=ct[Me]&&ct[Me].hostRevision||0;try{const at=await Qu(e,me,Ze,Ce);return pt(Ot=>({...Ot,[Me]:{hostCell:at.hostCell||null,hostLease:at.host&&typeof at.host.lease=="string"?at.host.lease:null,hostRevision:Number.isInteger(at.revision)?at.revision:Ze,threadStatus:i0.has(at.threadStatus)?at.threadStatus:"unknown"}})),{ok:!0}}catch(at){return{ok:!1,error:at}}},[e,ct]),Se=k.useCallback(async(me,Ce=[])=>{const Me=await Q(me,Ce);return Me.ok||window.alert(m(ku(Me.error))),Me.ok},[Q]),ze=k.useCallback(async(me=[])=>{const Ce=Di(me),Me=ct[Ce]&&ct[Ce].hostRevision||0;try{const Ze=await Ju(e,Me,me);return pt(at=>({...at,[Ce]:{hostCell:Ze.hostCell||null,hostLease:null,hostRevision:Number.isInteger(Ze.revision)?Ze.revision:Me,threadStatus:"unknown"}})),{ok:!0}}catch(Ze){return{ok:!1,error:Ze}}},[e,ct]),qe=k.useCallback(async(me=[])=>{const Ce=await ze(me);return Ce.ok||window.alert(m(ku(Ce.error))),Ce.ok},[ze]);k.useEffect(()=>{let me=!1;const Ce=()=>{cn("/api/config",e).then(Ze=>Ze.json()).then(Ze=>{me||JT(Ze.version,Ze.uiVersion,"0.9.32")}).catch(()=>{})};Ce();const Me=setInterval(Ce,6e4);return()=>{me=!0,clearInterval(Me)}},[e]);const Qe=new Set([...C.map(me=>me.name),...j.flatMap(me=>me.sessions.map(Ce=>Ce.key))]),Pt=as(X),Tt=me=>H(Ce=>{const Me=$1(me,$.localNodeId,F)||me,Ze=jm(Ce,Me);return Ze===Ce&&as(Ce).length>=9&&$.setError(m("grid-full")),Ze}),G=async(me,Ce=[])=>{try{await _m(e,me,Ce)}catch{return}const Me=Ce.length?`${Ce.join("/")}:${me}`:me;H(Ze=>ju(Ze,Me)),Lt()},ne=async(me,Ce,Me=[])=>{try{await v0(e,me,Ce,Me)}catch{return}Lt()},be=async(me,Ce,Me=[])=>{await p0(e,{cell:me,enabled:!!Ce},Me),Lt()},Ve=async me=>{if(!ce)return;const{cell:Ce}=ce,Me=Array.isArray(ce.route)?ce.route:[];if(me.action==="up"){const at=await vm(e,{cell:Ce,boot:!!me.boot,...me.engine?{engine:me.engine}:{},...me.model!==void 0?{model:me.model}:{},...me.permissionPolicy?{permissionPolicy:me.permissionPolicy}:{}},Me),Ot=Pm(at);Ot&&$.setError(Ot.text)}else await Su(e,{cell:Ce,boot:!!me.boot},Me);const Ze=me.action==="up"?!!me.boot:me.boot?!1:!!ce.boot;oe({id:++le.current,cell:Ce,route:Me,enabled:Ze}),Lt()},Be=k.useCallback(me=>{oe(Ce=>(Ce==null?void 0:Ce.id)===me?null:Ce)},[]),Ae=async me=>{if(!(!(me!=null&&me.direct)||te)){fe(!0);try{await Sm(e,me.name,me.tunnelStatus==="up"?"down":"up")}finally{fe(!1)}}},ot=async(me,Ce)=>{const Me=String(Ce||"").trim();return!(me!=null&&me.direct)||!aa(Me)?!1:(await b0(e,me.name,Me),!0)},zt=me=>{const Ce=W.find(Me=>Me.id===me);if(!Ce)return!1;try{const Me=window.open(Cf(Ce,e),"_blank");return Me&&(Me.opener=null),!!Me}catch{return!1}},nn=async me=>{if(!me||me===g)return;const Ce=await $.select(me),Me=$.records.find(Ze=>Ze.id===me);y(me),H(Ce),L(null),I(null);try{history.replaceState(null,"",Cf(Me||me,null))}catch{}},Ue=async(me,Ce)=>{const Me=await $.add(me,Ce);await nn(Me.id)},Oe=async(me,Ce)=>{const Me=await $.rename(me,Ce);if(me===g){y(Me.id),H(lm(Me.layout,$.localNodeId,F)),L(null),I(null);try{history.replaceState(null,"",Cf(Me,null))}catch{}}},xt=async me=>{await $.remove(me),me===g&&await nn($.localMainId)},Hn=async(me,Ce)=>{!Ce||Ce===g||(await $.addTileTo(Ce,me),H(Me=>ju(Me,me)))};if(!e)return l.jsxs("div",{className:"nc-auth",children:[l.jsx("p",{children:m("auth-prompt")}),l.jsx("input",{onChange:me=>n(me.target.value.trim()),placeholder:"token"}),l.jsxs("label",{children:[l.jsx("input",{type:"checkbox",checked:c,onChange:me=>d(me.target.checked)})," ",m("remember-device")]}),l.jsx("button",{onClick:()=>{(c?localStorage:sessionStorage).setItem("nc_token",e)},children:"ok"})]});const Xn=l.jsxs(l.Fragment,{children:[kt&&l.jsx(xT,{token:e,initialTab:st,initialLocation:It,startNewCell:Et,onClose:()=>{bt(!1),it(!1),Ut("")}}),un&&l.jsx(CT,{token:e,initialPair:i,...et,onPairDone:a,onDone:()=>re(!1)}),l.jsx(MT,{token:e})]});if(!h)return R?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(Zb,{peer:R,token:e,onBack:()=>A(null)})}),Xn]}):w?l.jsxs(l.Fragment,{children:[l.jsx(o0,{session:w.session,node:w.node,ownerId:w.ownerId,cellName:w.cellName,token:e,readonly:ae,liveHost:Wt(w.node?w.node.split("/"):[]),panelPort:Uu(w.node?w.node.split("/"):[],xe,Z),onBack:()=>S(null),onCellSwitcher:()=>gt(!0),cellSwitcherOpen:Bt}),Bt&&l.jsx(BT,{token:e,current:w,panelPort:Z,nodePanelPorts:xe,hostByRoute:ct,onDesignateCell:Q,onClearHostCell:ze,onLiveHostApplied:At,onPick:me=>{N(me),gt(!1)},onClose:()=>gt(!1)}),Xn]}):l.jsxs(l.Fragment,{children:[l.jsx(f5,{onPick:N,token:e,onSettings:vt,onOpenVlSession:A,hostByRoute:ct,onDesignateCell:Se,onClearHostCell:qe}),Xn]});const Cn=_||!ue;return l.jsxs("div",{className:"nc-workspace",children:[Cn&&l.jsx(jM,{sessions:C,cells:x,activeSessions:Pt,nodeGroups:j,token:e,onPeekOpen:()=>gt(!1),overlayOpen:Bt,fleetCapabilities:T,fleetStale:z,fleetOff:J,bootSettlement:K,onBootSettlementApplied:Be,localNodeId:$.localNodeId,hostByRoute:ct,onDesignateCell:Se,onClearHostCell:qe,onPick:O,onAddTile:Tt,onPower:ge,onBoot:be,onBootError:me=>$.setError(String((me==null?void 0:me.message)||me)),onNodePower:Ae,onNodeRename:ot,onKill:G,onVisibility:ne,onNew:()=>vt("fleet",!0),onSettings:vt,onOpenVlSession:A,width:Le,collapsed:Ne,onResize:$e,onToggleCollapse:()=>Ye(me=>!me)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(pj,{decks:W,currentDeck:g,onCreate:Ue,onRename:Oe,onDelete:xt,onReorder:$.reorder,onOpenWindow:zt,onNavigate:nn,saveState:$.saveState,error:$.error,conflict:$.conflict,onReloadDeck:$.reloadCurrent,sidebarVisible:Cn,onToggleSidebar:_?null:()=>ye(me=>!me)}),l.jsx(zM,{layout:X,onLayoutChange:H,onResizeEnd:()=>{$.saveNow()},token:e,readonly:ae,sessionsAlive:Qe,focusSession:P,onFocus:L,onOpenSingle:O,decks:W,currentDeck:g,onSendToDeck:Hn,cells:x,nodeGroups:j,panelPort:Z,nodePanelPorts:xe})]}),R&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(Zb,{peer:R,token:e,onBack:()=>A(null)})}),D&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(o0,{session:D.session,node:D.node,ownerId:D.ownerId,cellName:eg({session:D.session,node:D.node,ownerId:D.ownerId,cells:x,nodeGroups:j}),token:e,readonly:ae,liveHost:Wt(D.node?D.node.split("/"):[]),panelPort:Uu(D.node?D.node.split("/"):[],xe,Z),onBack:()=>I(null)})}),ce&&l.jsx(Nu,{cell:ce,token:e,route:Array.isArray(ce.route)?ce.route:[],onConfirm:Ve,onClose:()=>ge(null)}),Xn]})}function c3(t){return t.kind==="install"?m("update-installed-restart").replace("{v}",t.version):t.kind==="stale"?m("update-stale").replace("{ui}",t.version).replace("{browser}",t.browserVersion):m("update-available").replace("{v}",t.version).replace(" "," ").trim()}function u3(){ui();const t=k.useSyncExternalStore(WT,e0,e0);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:c3(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:Mx,children:m("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:n3,children:m("reload")}),l.jsx("button",{className:"nc-update-close",onClick:QT,"aria-label":m("update-dismiss"),title:m("update-dismiss"),children:"×"})]}):null}t3();_k.createRoot(document.getElementById("root")).render(l.jsxs(dk.StrictMode,{children:[l.jsx(l3,{}),l.jsx(u3,{})]}));
167
+ `],{type:"application/json"}),O=URL.createObjectURL(I),R=document.createElement("a");R.href=O,R.download="nexuscrew-diagnostics.json",R.click(),URL.revokeObjectURL(O)}catch{_(m("diagnostics-export-failed"))}};return l.jsxs("div",{className:"nc-set-tab nc-diagnostics",children:[l.jsxs("label",{className:"nc-field",children:[m("diagnostics-target"),l.jsx("select",{value:c.key,onChange:I=>a(I.target.value),children:i.map(I=>l.jsxs("option",{value:I.key,children:[I.label,I.status!=="up"?` · ${I.status}`:""]},I.key))})]}),l.jsxs("div",{className:"nc-set-form nc-diag-controls",children:[l.jsx("div",{className:"nc-sheet-label",children:m("diagnostics-verbose")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("select",{"aria-label":m("diagnostics-duration"),value:E,onChange:I=>x(Number(I.target.value)),disabled:n,children:[300,900,1800,3600].map(I=>l.jsxs("option",{value:I,children:[I/60," min"]},I))}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||(d==null?void 0:d.verbose)===!0,onClick:()=>P(()=>G_(t,!0,E,c.route)),children:m("enable")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||(d==null?void 0:d.verbose)!==!0,onClick:()=>P(()=>G_(t,!1,E,c.route)),children:m("stop")})]}),l.jsx("small",{className:"nc-set-hint",children:d!=null&&d.verbose?m("diagnostics-expires").replace("{time}",new Date(d.expiresAt).toLocaleTimeString()):m("diagnostics-off")})]}),l.jsxs("div",{className:"nc-diag-filters",children:[l.jsxs("select",{"aria-label":m("diagnostics-level"),value:M,onChange:I=>T(I.target.value),children:[l.jsx("option",{value:"all",children:m("diagnostics-all-levels")}),["debug","info","warn","error"].map(I=>l.jsx("option",{value:I,children:I},I))]}),l.jsx("input",{"aria-label":m("diagnostics-component"),placeholder:m("diagnostics-component"),value:U,onChange:I=>z(I.target.value)})]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:w,onChange:I=>S(I.target.checked)})," ",m("diagnostics-pause")]}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox",checked:N,onChange:I=>C(I.target.checked)})," ",m("diagnostics-autoscroll")]})]}),l.jsx("pre",{ref:J,className:"nc-diag-log","aria-label":m("diagnostics-log"),children:H||m("diagnostics-empty")}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:L,children:m("copy")}),l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:D,children:m("diagnostics-export")}),l.jsx("button",{type:"button",className:"nc-btn danger",disabled:n,onClick:()=>{window.confirm(m("diagnostics-clear-confirm"))&&P(async()=>{const I=await t2(t,c.route);return V.current=0,g([]),I})},children:m("diagnostics-clear")})]}),y&&l.jsx("div",{className:"nc-err",children:y})]})}function ST({token:t,settings:e,readonly:n,refresh:i,roster:s,section:a,setSection:c}){const[d,h]=k.useState(null),[f,g]=k.useState(null),[y,_]=k.useState(!1),[w,S]=k.useState(!1),[N,C]=k.useState(null),[E,x]=k.useState(!0),[M,T]=k.useState(!1);k.useEffect(()=>{C(e&&e.update||null),x(!e||e.autoUpdate!==!1),T(!!(e&&e.alternateScreen))},[e]);const U=async()=>{h(null),g(null),S(!0);try{const L=await Dk(t);g(L.note||"ok"),_(!1)}catch(L){h(String(L.message||L))}S(!1)},z=async()=>{h(null),g(null),S(!0);try{const L=await Xk(t);g(`${L.note||"ok"}${L.target?` (${L.target})`:""}`)}catch(L){h(String(L.message||L))}S(!1)},V=async L=>{h(null),g(null),S(!0);try{await ep(t,{autoUpdate:L}),x(L),i&&await i()}catch(D){h(String(D.message||D))}S(!1)},J=async L=>{h(null),g(null),S(!0);try{await ep(t,{alternateScreen:L}),T(L),i&&await i()}catch(D){h(String(D.message||D))}S(!1)},q=async()=>{h(null),g(null),S(!0);try{C(await Qk(t))}catch(L){h(String(L.message||L))}S(!1)},X=async()=>{h(null),g(null),S(!0);try{const L=await Jk(t);C(L),g(m("npm-update-restarting"))}catch(L){h(String(L.message||L))}S(!1)},H=()=>{window.confirm(m("composer-clear-confirm"))&&(h(null),pM()?(window.dispatchEvent(new Event(im)),g(m("composer-clear-done"))):h(m("composer-clear-failed")))},P=e&&e.service;return l.jsxs("div",{className:"nc-set-tab",children:[l.jsx("div",{className:"nc-system-tabs",role:"tablist","aria-label":m("tab-system"),children:["general","diagnostics"].map(L=>l.jsx("button",{type:"button",role:"tab","aria-selected":a===L,className:`nc-set-tabbtn${a===L?" on":""}`,onClick:()=>c(L),children:m(`system-${L}`)},L))}),a==="general"&&l.jsxs(l.Fragment,{children:[l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-this-node")}),e&&l.jsxs("div",{className:"nc-set-info",children:["v",e.version," · ",e.platform," · :",e.port,l.jsx("br",{}),P&&P.installed?m("service-installed"):m("service-missing"),P&&P.installed?` · ${P.active?m("service-active"):m("service-inactive")}`:"",P?` · boot ${P.boot?"on":"off"}`:""]}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w,title:n?m("settings-readonly"):"",onClick:z,children:m("service-regenerate")})}),l.jsx(vT,{token:t,readonly:n}),l.jsx(_T,{})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("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:E,disabled:n||w||N&&!N.supported,onChange:L=>V(L.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("npm-auto-update")}),l.jsx("small",{children:m("npm-auto-update-help")})]})]}),N&&l.jsxs("div",{className:"nc-set-info",children:[m("npm-update-current")," v",N.current,N.latest?` · ${m("npm-update-latest")} v${N.latest}`:""," · ",m(N.supported?N.phase==="idle"&&N.checked!==!0?"npm-update-never":`npm-update-${N.phase}`:"unsupported")]}),l.jsxs("div",{className:"nc-set-row",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w||!N||!N.supported,onClick:q,children:m("npm-update-check")}),N&&N.available&&l.jsx("button",{type:"button",className:"nc-btn primary",disabled:n||w||N.phase==="installing",onClick:X,children:m("npm-update-install")})]}),N&&N.lastError&&l.jsx("div",{className:"nc-err",children:N.lastError})]})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-security")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:n||w,title:n?m("settings-readonly"):"",onClick:()=>{h(null),g(null),_(!0)},children:m("token-rotate")})})]}),l.jsxs("section",{className:"nc-system-group",children:[l.jsx("h3",{children:m("system-local-data")}),l.jsxs("div",{className:"nc-set-form",children:[l.jsx("div",{className:"nc-sheet-label",children:m("composer-clear-data")}),l.jsx("small",{className:"nc-set-hint",children:m("composer-clear-data-help")}),l.jsx("div",{className:"nc-set-row",children:l.jsx("button",{type:"button",className:"nc-btn ghost",onClick:H,children:m("composer-clear-data")})})]})]})]}),a==="diagnostics"&&l.jsxs("section",{className:"nc-system-group nc-system-diagnostics",children:[l.jsx("h3",{children:m("system-diagnostics")}),l.jsxs("div",{className:"nc-set-form nc-alternate-screen-settings",children:[l.jsx("div",{className:"nc-sheet-label",children:m("system-terminal")}),l.jsxs("label",{className:"nc-check",children:[l.jsx("input",{type:"checkbox","aria-label":m("alternate-screen"),checked:M,disabled:n||w,onChange:L=>J(L.target.checked)}),l.jsxs("span",{children:[l.jsx("b",{children:m("alternate-screen")}),l.jsx("small",{children:m("alternate-screen-help")})]})]})]}),l.jsx(bT,{token:t,roster:s,readonly:n})]}),y&&l.jsxs("div",{className:"nc-set-confirm",children:[l.jsx("div",{children:m("token-rotate-explain")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:w,onClick:()=>_(!1),children:m("cancel")}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:w,onClick:U,children:m("confirm")})]})]}),f&&l.jsx("div",{className:"nc-set-note",children:f}),d&&l.jsx("div",{className:"nc-err",children:d})]})}function xT({token:t,onClose:e,initialTab:n="nodes",initialLocation:i="",startNewCell:s=!1}){ui();const a=n==="diagnostics"?"diagnostics":"general",[c,d]=k.useState(n==="diagnostics"?"system":n),h=k.useRef(null),f=k.useRef(null),[g,y]=k.useState({start:!1,end:!1}),[_,w]=k.useState(a),[S,N]=k.useState(null),[C,E]=k.useState([]),[x,M]=k.useState(null),[T,U]=k.useState([]),[z,V]=k.useState(!1),[J,q]=k.useState(null),[X,H]=k.useState(0),P=km(t,!0,X),L=k.useCallback(()=>{const I=h.current;if(!I)return;const O=I.scrollWidth>I.clientWidth+1,R={start:O&&I.scrollLeft>1,end:O&&I.scrollLeft+I.clientWidth<I.scrollWidth-1};y(A=>A.start===R.start&&A.end===R.end?A:R)},[]);k.useEffect(()=>{const I=h.current;if(!I)return;const O=typeof ResizeObserver=="function"?new ResizeObserver(L):null;return O==null||O.observe(I),window.addEventListener("resize",L),L(),()=>{O==null||O.disconnect(),window.removeEventListener("resize",L)}},[L]),k.useEffect(()=>{var O,R;(R=(O=f.current)==null?void 0:O.scrollIntoView)==null||R.call(O,{behavior:"smooth",block:"nearest",inline:"nearest"});const I=window.requestAnimationFrame?window.requestAnimationFrame(L):setTimeout(L,0);return()=>{window.cancelAnimationFrame?window.cancelAnimationFrame(I):clearTimeout(I)}},[c,L]);const D=k.useCallback(async()=>{var I;try{const O=await _0(t);N(O),q(null)}catch(O){q(String(O.message||O))}try{const O=await Pk(t),R=O.peers||[];M(Number.isInteger(O.accessRevision)?O.accessRevision:null);let A=[],j=[];try{const[F,$]=await Promise.all([cn("/api/config",t).then(K=>K.json()).catch(()=>null),w0(t).catch(()=>null)]),W=F&&typeof F.instanceId=="string"?F.instanceId:"",ce=[{instanceId:W||null,route:[],label:null},...I0($,W)],ge=await Promise.all(ce.map(async K=>{try{return{ok:!0,peers:((await y0(t,K.route)).nodes||[]).map(te=>D0(te,K)).filter(Boolean)}}catch(oe){return{ok:!1,owner:K,error:oe}}}));for(const K of ge){if(K.ok){A.push(...K.peers);continue}K.owner.route.length!==0&&j.push({instanceId:K.owner.instanceId,label:K.owner.label,route:K.owner.route,failure:/timeout/i.test(String(((I=K.error)==null?void 0:I.message)||K.error))?"timeout":"unreachable"})}}catch{}U(j),E([...R,...A])}catch(O){q(String(O.message||O))}},[t]);return k.useEffect(()=>{D();const I=setInterval(D,5e3);return()=>clearInterval(I)},[D]),k.useEffect(()=>{let I=!1;return cn("/api/config",t).then(O=>O.json()).then(O=>{I||V(!!O.readonlyDefault)}).catch(()=>{}),()=>{I=!0}},[t]),l.jsx("div",{className:"nc-set-overlay",onClick:e,children:l.jsxs("div",{className:"nc-set-panel",onClick:I=>I.stopPropagation(),children:[l.jsxs("div",{className:"nc-set-head",children:[l.jsx(ht,{name:"gear",size:18}),l.jsx("b",{children:m("settings")}),l.jsx("button",{type:"button",className:"nc-set-close",onClick:e,title:m("close"),children:l.jsx(ht,{name:"x",size:18})})]}),z&&l.jsx("div",{className:"nc-set-readonly",children:m("settings-readonly")}),J&&l.jsx("div",{className:"nc-err",children:J}),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:L,children:["nodes","fleet","audio","input","system"].map(I=>l.jsx("button",{ref:c===I?f:null,type:"button",className:`nc-set-tabbtn${c===I?" on":""}`,onClick:()=>d(I),children:m(`tab-${I}`)},I))})}),l.jsxs("div",{className:"nc-set-body",children:[c==="nodes"&&l.jsx(gT,{token:t,nodes:C,roster:P,settings:S,readonly:z,vlUnavailable:T,accessRevision:x,refresh:D,refreshAliases:()=>H(I=>I+1)}),c==="fleet"&&l.jsx(QP,{token:t,readonly:z,startNewCell:s,initialLocation:i,targets:P.map(I=>({route:I.route,label:I.label||I.name,status:I.status}))}),c==="audio"&&l.jsx(yT,{token:t,readonly:z,nodes:C,settings:S}),c==="input"&&l.jsx(wT,{}),c==="system"&&l.jsx(ST,{token:t,settings:S,readonly:z,refresh:D,roster:P,section:_,setSection:w})]})]})})}function CT({token:t,initialPair:e,deviceDefault:n="",localNodeId:i="",localNameDefault:s="",onPairDone:a,onDone:c}){ui();const[d,h]=k.useState(e?"pair":"welcome"),[f,g]=k.useState(!1),[y,_]=k.useState(null),[w,S]=k.useState(null),N=async()=>{g(!0),_(null);try{await ep(t,{wizardDone:!0}),a&&a(),c()}catch(C){_(String(C.message||C)),g(!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:m("wizard-title")}),l.jsx("small",{children:m("hydra-simple")})]}),d==="welcome"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:m("local-ready")}),l.jsxs("div",{className:"nc-sheet-actions",children:[l.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:N,children:m("local-only")}),l.jsx("button",{className:"nc-btn primary",disabled:f,onClick:()=>h("pair"),children:m("add-node")})]})]}),d==="pair"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx(ix,{token:t,initial:e||"",autoStart:!!e,deviceDefault:n,localNodeId:i,localNameDefault:s,onBusyChange:g,onSuccess:async C=>{S(C&&C.authorizedKeys?{line:C.authorizedKeys,note:C.authorizedKeysNote||""}:null),a&&a(),h("done")}}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn ghost",disabled:f,onClick:()=>{a&&a(),h("welcome")},children:m("back")})})]}),d==="done"&&l.jsxs("div",{className:"nc-wiz-body",children:[l.jsx("div",{className:"nc-wiz-done",children:m("node-connected")}),w&&l.jsx(cg,{line:w.line,note:w.note}),l.jsx("div",{className:"nc-sheet-actions",children:l.jsx("button",{className:"nc-btn primary",disabled:f,onClick:N,children:m("finish")})})]}),y&&l.jsx("div",{className:"nc-err",children:y})]})})}function kT(t,e){if(typeof EventSource>"u"||!t)return()=>{};const n=new EventSource(`/api/events?token=${encodeURIComponent(t)}`);return n.onmessage=i=>{try{const s=JSON.parse(i.data);s&&typeof s=="object"&&typeof s.type=="string"&&e(s)}catch{}},()=>{try{n.close()}catch{}}}const ET=6e3,NT=12e3,Gs=(t,e,n)=>`${e||""}:${n||t}`;function Cx(t,e){const n=new Set(t.map(s=>Gs(s.id,s.ownerId,s.ownerAskId))),i=(e||[]).filter(s=>s&&s.id&&!n.has(Gs(s.id,s.ownerId,s.ownerAskId)));return i.length?[...t,...i]:t}function LT(t,e){const n=Cx([],t.filter(a=>a.imported)),i=new Set(n.map(a=>Gs(a.id,a.ownerId,a.ownerAskId)));return[...(e||[]).filter(a=>a&&a.id&&!i.has(Gs(a.id,a.ownerId,a.ownerAskId))),...n]}function RT({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:m("feed-owner")})]}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:e,title:m("close"),children:l.jsx(ht,{name:"x",size:14})})]})}function AT({ask:t,token:e,onAnswered:n,onDismiss:i,askReplyAccess:s=!1}){const[a,c]=k.useState(""),[d,h]=k.useState(!1),[f,g]=k.useState(null),[y,_]=k.useState(!1),[w,S]=k.useState(null),[N,C]=k.useState(!1),E=async M=>{const T=String(M||"").trim();if(!(!T||d)){g(null),h(!0);try{if(t.ownerId){const U=t.ownerAskId||t.id,z=await r2(e,{ownerId:t.ownerId,askId:U,text:T});if(z&&z.uncertain){S(z.requestId);return}n(t.id,t.ownerId)}else await i2(e,t.id,T),n(t.id)}catch(U){g(String(U.message||U))}h(!1)}},x=async()=>{if(!y){_(!0);try{if(t.ownerId){if(w)return;await a2(e,{ownerId:t.ownerId,askId:t.ownerAskId||t.id}),i(t.id,t.ownerId)}else await s2(e,t.id),i(t.id)}catch{_(!1)}}};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:m("feed-owner")}),l.jsxs("code",{className:"nc-ask-id",children:["#",t.id]}),l.jsx("button",{type:"button",className:"nc-ask-dismiss",title:m("ask-dismiss"),"aria-label":m("ask-dismiss"),disabled:y||!!t.ownerId&&s===!1,onClick:x,children:l.jsx(ht,{name:"x",size:14})})]}),l.jsx("div",{className:"nc-ask-q",children:t.question}),t.ownerId&&s===!1&&l.jsx("small",{className:"nc-set-hint",children:m("ask-remote-readonly")}),w&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-err",children:m("ask-uncertain")}),l.jsx("button",{type:"button",className:"nc-btn ghost",disabled:N,onClick:async()=>{C(!0);try{const M=await o2(e,{ownerId:t.ownerId,askId:t.id,requestId:w});M&&(M.state==="committed"||M.state==="failed")&&i(t.id,t.ownerId)}finally{C(!1)}},children:m("ask-verify")})]}),(!t.ownerId||s===!0)&&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:d,onClick:()=>E(M),children:M},M))}),l.jsxs("div",{className:"nc-ask-reply",children:[l.jsx("textarea",{rows:2,placeholder:m("ask-reply-ph"),value:a,disabled:d,onChange:M=>c(M.target.value)}),l.jsx("button",{type:"button",className:"nc-btn primary",disabled:d||!a.trim(),onClick:()=>E(a),children:m("send")})]})]}),f&&l.jsx("div",{className:"nc-err",children:f})]})}function MT({token:t}){const[e]=ui(),[n]=xx(),[i,s]=k.useState([]),[a,c]=k.useState([]),[d,h]=k.useState(()=>{try{return/(?:^|[#&])ask=/.test(location.hash)}catch{return!1}}),f=k.useRef(0),g=k.useRef(null);g.current||(g.current=fT());const y=k.useRef({enabled:n,lang:e});y.current={enabled:n,lang:e};const _=k.useCallback(E=>{s(x=>x.filter(M=>M.key!==E))},[]),w=k.useCallback(E=>{const x=`t${f.current+=1}`;s(T=>[...T.slice(-3),{...E,key:x}]),setTimeout(()=>_(x),E.urgency==="high"?NT:ET);const M=y.current;if(M.enabled)try{g.current.enqueue(E,lT(E,M.lang))}catch{}},[_]);k.useEffect(()=>{n||g.current.stop()},[n]),k.useEffect(()=>{const E=()=>{(document.visibilityState!=="visible"||!document.hasFocus())&&g.current.stop()},x=()=>g.current.stop();return document.addEventListener("visibilitychange",E),window.addEventListener("blur",E),window.addEventListener(dm,x),()=>{document.removeEventListener("visibilitychange",E),window.removeEventListener("blur",E),window.removeEventListener(dm,x),typeof g.current.dispose=="function"?g.current.dispose():g.current.stop()}},[]);const S=(E,x)=>c(M=>M.filter(T=>Gs(T.id,T.ownerId)!==Gs(E,x)));k.useEffect(()=>{if(!t)return;let E=!1;n2(t).then(M=>{E||c(T=>LT(T,M.asks))}).catch(()=>{});const x=kT(t,M=>{if(M.type==="notify")w(M);else if(M.type==="ask"&&M.ask&&M.ask.id){const T=Gs(M.ask.id,M.ask.ownerId);c(U=>U.some(z=>Gs(z.id,z.ownerId)===T)?U:[...U,M.ask])}else(M.type==="ask-answered"&&M.id||M.type==="ask-dismissed"&&M.id)&&S(M.id,M.ownerId)});return()=>{E=!0,x()}},[t,w]);const[N,C]=k.useState({});return k.useEffect(()=>{let E=!0;return l2(t).then(x=>{if(!E)return;const M={},T=[];for(const U of x&&x.views||[]){M[U.ownerId]=U.askReplyAccess===!0;for(const z of U.asks||[])z&&z.id&&T.push({...z,ownerId:U.ownerId,imported:!0})}C(M),T.length&&c(U=>Cx(U,T))}).catch(()=>{}),()=>{E=!1}},[t]),l.jsxs(l.Fragment,{children:[i.length>0&&l.jsx("div",{className:"nc-ntf-toasts",children:i.map(E=>l.jsx(RT,{n:E,onClose:()=>_(E.key)},E.key))}),a.length>0&&!d&&l.jsxs("button",{type:"button",className:"nc-ask-badge",onClick:()=>h(!0),title:m("asks-title"),children:["? ",l.jsx("span",{className:"nc-ask-count",children:a.length})]}),a.length>0&&d&&l.jsxs("div",{className:"nc-ask-panel",children:[l.jsxs("div",{className:"nc-ask-panel-head",children:[l.jsx("b",{children:m("asks-title")}),l.jsx("span",{className:"nc-ask-count",children:a.length}),l.jsx("button",{type:"button",className:"nc-ntf-x",onClick:()=>h(!1),title:m("close"),children:l.jsx(ht,{name:"x",size:16})})]}),l.jsx("div",{className:"nc-ask-panel-body",children:a.map(E=>l.jsx(AT,{ask:E,token:t,askReplyAccess:!E.ownerId||N[E.ownerId]===!0,onAnswered:S,onDismiss:S},Gs(E.id,E.ownerId)))})]})]})}const jT=4e3;async function PT(t){const e=await cn("/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 Qf(t,e=[]){var d;const[n,i]=await Promise.allSettled([e.length?wm(t,e):PT(t),Dr(t,e)]),s=n.status==="fulfilled"&&Array.isArray((d=n.value)==null?void 0:d.sessions)?n.value.sessions:Array.isArray(n.value)?n.value:null,a=i.status==="fulfilled"?i.value:null,c=(a==null?void 0:a.available)===!0&&Array.isArray(a.cells)?a.cells:null;return{sessions:s,cells:c,fresh:Array.isArray(s)&&Array.isArray(c)}}function kx(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(i=>(i==null?void 0:i.name)===t.tmuxSession)}function TT(t){const e=new Map((t.sessions||[]).map(s=>[s.name,s])),n=[],i=(s,a,c,d=[],h="")=>{const f=new Map((a||[]).map(g=>[g.name,g]));for(const g of s||[]){const y=f.get(g.tmuxSession)||{},_=Lm(g,y),w=kx(g,a,c);n.push({key:El(d,g.tmuxSession||g.cell),session:g.tmuxSession,route:d,cellName:g.cell,label:g.cell,node:d.length?d.join("/"):"",nodeLabel:h,live:w,selectable:w,verified:c===!0,working:_.working,degraded:!!g.degraded,active:g.active===!0,activity:y.activity||g.activity||0,subtitle:_.subtitle,preview:y.preview||g.preview||"",telemetry:y.telemetry||null,panelUrl:g.panelUrl||""})}};i(t.cells,[...e.values()],t.localFresh===!0);for(const s of t.nodeGroups||[]){const a=Array.isArray(s.route)?s.route:[];s.kind==="vl"||!a.length||i(s.cells,s.sessions,s.switcherFresh===!0,a,s.label||s.name||"")}return n}function DT(t){const e=new Map,n=Array.isArray(t.sessions)?t.sessions:[],i=Array.isArray(t.cells)?t.cells:[],s=new Map(n.map(c=>[c.name,c])),a=new Set(i.map(c=>c.tmuxSession).filter(Boolean));e.set("local",Rm(i,n.filter(c=>!a.has(c.name)),s));for(const c of t.nodeGroups||[]){const d=Array.isArray(c.route)?c.route:[];if(c.kind==="vl"||!d.length)continue;const h=Array.isArray(c.cells)?c.cells:[],f=Array.isArray(c.sessions)?c.sessions:[],g=new Set(h.map(y=>y.tmuxSession).filter(Boolean));e.set(d.join("/"),Au({...c,route:d,cells:h,sessions:f,unmanaged:f.filter(y=>!g.has(y.name))}).rawItems)}return e}function IT(t,e,n,i){return[...new Set(t.map(a=>a.node||"local"))].flatMap(a=>{const c=t.filter(g=>(g.node||"local")===a),d=new Map((e.get(a)||[]).map(g=>[g.key,g])),h=new Map(c.map(g=>[g.key,g])),f=c.map(g=>{const y=d.get(g.key);return{...g,label:(y==null?void 0:y.label)||g.label,live:(y==null?void 0:y.live)??g.live,fresh:(y==null?void 0:y.fresh)===!0,activity:(y==null?void 0:y.activity)??g.activity}});return Mr(f,n,"all",Js(i,a)).map(g=>h.get(g.key))})}function BT({token:t,current:e,onPick:n,onClose:i,panelPort:s=0,nodePanelPorts:a={},hostByRoute:c={},onDesignateCell:d,onClearHostCell:h,onLiveHostApplied:f}){const[g,y]=k.useState(dy),[_,w]=k.useState(!1),[S,N]=k.useState(!1),[C,E]=k.useState(""),[x,M]=k.useState(null),[T,U]=k.useState(""),[z,V]=k.useState(""),J=k.useRef(null),q=k.useRef(null),X=k.useMemo(()=>TT(g),[g]),H=k.useMemo(()=>DT(g),[g]),{pins:P,orders:L,togglePin:D,removePin:I,pinError:O,canMoveRoster:R,moveRoster:A,stepRoster:j}=Nm(),F=k.useMemo(()=>IT(X,H,P,L),[X,H,P,L]),$=k.useMemo(()=>_?F:F.filter(ue=>ue.selectable||ue.degraded&&ue.active),[F,_]),W=k.useMemo(()=>X.find(ue=>ue.key===T&&ue.selectable),[X,T]),ce=k.useMemo(()=>x?X.find(ue=>ue.key===x.key):null,[X,x]);k.useEffect(()=>{O&&O.message&&E(O.message)},[O]),k.useEffect(()=>{var Ne;const ue=document.activeElement;(Ne=q.current)==null||Ne.focus();const ye=Ye=>{Ye.key==="Escape"&&i()};return document.addEventListener("keydown",ye),()=>{var Ye;document.removeEventListener("keydown",ye),(Ye=ue==null?void 0:ue.focus)==null||Ye.call(ue)}},[i]),k.useEffect(()=>{let ue=!0,ye=!1;const Ne=async()=>{if(ye)return;ye=!0;const kt=dy(),bt=Array.isArray(kt.nodeGroups)?kt.nodeGroups:[],st=Qf(t),mt=gt=>gt.kind!=="vl"&&Array.isArray(gt.route)&&gt.route.length>0,Et=await Promise.all(bt.filter(mt).map(async gt=>({group:gt,result:await Qf(t,gt.route)}))),it=await st;if(!ue)return;const It=new Map(Et.map(({group:gt,result:vt})=>[JSON.stringify(gt.route||[]),vt])),Ut=bt.map(gt=>{if(!mt(gt))return{...gt,switcherFresh:!1};const vt=It.get(JSON.stringify(gt.route||[]));return vt?{...gt,sessions:vt.sessions||gt.sessions||[],cells:vt.cells||gt.cells||[],switcherFresh:vt.fresh}:{...gt,switcherFresh:!1}}),Bt=Q0({...kt,sessions:it.sessions||kt.sessions||[],cells:it.cells||kt.cells||[],localFresh:it.fresh,nodeGroups:Ut,refreshedAt:Date.now()});y(Bt),N(!0),ye=!1};Ne();const Ye=setInterval(Ne,jT);return()=>{ue=!1,clearInterval(Ye)}},[t]);const[ge,K]=k.useState(""),oe={getLiveHost:ue=>Xu(t,ue),designateHostCell:(ue,ye,Ne)=>Qu(t,ue,ye,Ne),clearHostCell:(ue,ye)=>Ju(t,ue,ye)},le=ue=>(c[Di(ue)]||{}).hostCell||null,te=async(ue,ye)=>{K(ue.key);const Ne=await j1({action:ye?"remove":"use",cellId:ue.cellName,route:ue.route||[],api:oe});K(""),E(m(Ne.messageKey).replace("{cell}",Ne.hostCell||ue.cellName)),Ne.ok&&f&&f({route:ue.route||[],hostCell:Ne.hostCell,revision:Ne.revision})},fe=ue=>ue.degraded?m("cell-degraded"):ue.verified?ue.selectable?ue.working?m("cell-working"):m("cell-idle"):m("cell-off"):m("cell-switcher-not-confirmed"),Le=ue=>{if(E(""),!ue.selectable){E(ue.verified?m("cell-switcher-not-active"):m("cell-switcher-not-confirmed"));return}U(ue.key)},$e=async()=>{const ue=W;if(!ue){E(m("cell-switcher-select"));return}E(""),V(ue.key);try{const ye=await Qf(t,ue.route),Ne=(ye.cells||[]).find(Ye=>(Ye==null?void 0:Ye.cell)===ue.cellName&&(Ye==null?void 0:Ye.tmuxSession)===ue.session);if(ye.fresh!==!0){E(m("cell-switcher-verify-failed"));return}if(!kx(Ne,ye.sessions,ye.fresh)){E(m("cell-switcher-not-active"));return}n({session:ue.session,...ue.node?{node:ue.node}:{},cellName:ue.cellName}),i()}catch{E(m("cell-switcher-verify-failed"))}finally{V("")}};return l.jsx("div",{className:"nc-cell-switcher-backdrop",onClick:i,children:l.jsxs("aside",{ref:J,className:"nc-cell-switcher",role:"dialog","aria-label":m("fleet-cells"),tabIndex:-1,onClick:ue=>ue.stopPropagation(),children:[l.jsxs("div",{className:"nc-cell-switcher-list",children:[l.jsx(R1,{className:"nc-cell-switcher-live-host",view:Hu({liveHost:c[Di([])],cells:g.cells||[]})}),!S&&l.jsx("div",{className:"nc-empty",role:"status",children:m("cell-switcher-refreshing")}),S&&$.length===0&&l.jsx("div",{className:"nc-empty",role:"status",children:m("cell-switcher-empty-active")}),$.map(ue=>{const ye=(e==null?void 0:e.session)===ue.session&&((e==null?void 0:e.node)||"")===ue.node,Ne=T===ue.key,Ye=fe(ue),kt=rm(m,ue.activity),bt=om(m,ue.telemetry),st=[kt,bt].filter(Boolean).join(" · "),mt=ue.node||"local",Et=H.get(mt)||X.filter(it=>(it.node||"local")===mt);return l.jsxs("div",{className:`nc-cell-switcher-row${ye?" current":""}${Ne?" selected":""}${ue.selectable?"":" off"}`,"data-roster-key":ue.key,"data-position":mt,children:[l.jsx(Ss,{position:mt,itemKey:ue.key,label:ue.cellName,canMove:R,onMove:(it,It)=>A(mt,it,It,Et),onStep:it=>j(mt,ue.key,it,Et)}),l.jsx("button",{type:"button",className:"nc-cell-switcher-peek",title:m("cell-peek"),"aria-label":`${m("cell-peek")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"preview"})},children:l.jsx("span",{className:`nc-cell-switcher-dot${ue.degraded?" warn":ue.live?` on${ue.working?" working":""}`:""}`})}),l.jsxs("span",{className:"nc-cell-switcher-acts",children:[l.jsx("button",{type:"button",className:"nc-cell-switcher-act",title:m("cell-peek-stream"),"aria-label":`${m("cell-peek-stream")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"stream"})},children:"▶"}),ue.panelUrl&&l.jsx("button",{type:"button",className:"nc-cell-switcher-act",title:m("cell-peek-panel"),"aria-label":`${m("cell-peek-panel")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),M({key:ue.key,source:"panel"})},children:"▣"})]}),l.jsx("button",{type:"button",className:"nc-cell-switcher-row-select","aria-current":ye?"true":void 0,"aria-pressed":Ne,"aria-disabled":!ue.selectable,disabled:z===ue.key,onClick:()=>Le(ue),children:l.jsxs("span",{className:"nc-cell-switcher-copy",children:[l.jsx("b",{children:ue.cellName}),l.jsx("small",{className:"nc-cell-switcher-state",children:Ye}),l.jsx("small",{children:[ue.nodeLabel,ue.subtitle].filter(Boolean).join(" · ")}),st&&l.jsx("small",{className:"nc-cell-switcher-telemetry",children:st})]})}),l.jsx(Eu,{item:{key:ue.key,value:{cell:ue.cellName}},pins:P,hostByRoute:c,route:ue.route||[],cellName:ue.cellName,baseClassName:"nc-cell-switcher-star",togglePin:D,removePin:I,onOutcome:it=>{it.ok||E(m(ku(it.error)))}}),l.jsx("button",{type:"button",className:`nc-cell-switcher-act nc-cell-switcher-host${le(ue.route||[])===ue.cellName?" on":""}`,"data-testid":`live-host-command-${ue.key}`,"data-live-host-state":le(ue.route||[])===ue.cellName?"host":"idle",disabled:ge===ue.key,title:le(ue.route||[])===ue.cellName?m("live-host-action-remove"):m("live-host-action-use"),"aria-label":`${le(ue.route||[])===ue.cellName?m("live-host-action-remove"):m("live-host-action-use")}: ${ue.cellName}`,onClick:it=>{it.stopPropagation(),te(ue,le(ue.route||[])===ue.cellName)},children:l.jsx(ht,{name:"broadcast",size:18})})]},ue.key)})]}),C&&l.jsx("div",{className:"nc-cell-switcher-notice",role:"status",children:C}),x&&ce&&l.jsx(P1,{row:ce,token:t,initialSource:x.source,panelPort:Uu(ce.route||[],a,s),liveHost:Hu({liveHost:c[Di(ce.route||[])],cells:g.cells||[]}),onLiveHostApplied:f,onClose:()=>M(null)}),l.jsx("div",{className:"nc-cell-switcher-actions",children:l.jsx("button",{type:"button",className:"nc-cell-switcher-open",disabled:!W||!!z,onClick:$e,children:W?`${m("cell-switcher-open")}: ${W.cellName}`:m("cell-switcher-select")})}),l.jsxs("div",{className:"nc-cell-switcher-controls",children:[l.jsx("b",{children:m("fleet-cells")}),l.jsx("button",{type:"button",className:"nc-cell-switcher-filter","aria-pressed":_,onClick:()=>{E(""),w(ue=>!ue)},children:m(_?"cell-switcher-show-active":"cell-switcher-show-all")}),l.jsx("button",{ref:q,type:"button",className:"nc-cell-switcher-close","aria-label":m("cell-switcher-close"),title:m("cell-switcher-close"),onClick:i,children:"×"})]})]})})}const OT=2e3;function $T(t){if(t.kind==="gap")return`${m("vl-events-gap")} ${t.count||"?"}`;if(t.kind==="truncate")return m("vl-events-truncated");if(t.kind==="turn_end")return m("vl-events-turn-end");if(t.kind==="done")return m("vl-events-done");if(t.kind==="writer_epoch")return m("vl-events-writer-epoch");if(t.kind==="tool_start")return`${m("vl-events-tool")} ${t.name||""}`.trim();if(t.kind==="tool_end"){const e=t.isError?m("vl-events-tool-failed"):m("vl-events-tool-ok");return`${m("vl-events-tool")} ${t.name||""} — ${e}`.trim()}return t.kind==="usage"?t.text||m("vl-events-usage"):t.text||""}function zT({token:t,nodeId:e,route:n=[]}){const[i,s]=k.useState([]),[a,c]=k.useState(!1),d=k.useRef(0),h=k.useRef(!1);return k.useEffect(()=>{let f=!0;d.current=0,h.current=!1,s([]);const g=async()=>{if(!h.current){h.current=!0;try{const w=await Tk(t,e,d.current,n);if(!f)return;c(!1);const N=(Array.isArray(w==null?void 0:w.events)?w.events:[]).filter(C=>Number.isSafeInteger(C==null?void 0:C.seq)&&C.seq>d.current);N.length&&(s(C=>C.concat(N).slice(-500)),d.current=N[N.length-1].seq),Number.isSafeInteger(w==null?void 0:w.cursor)&&w.cursor>d.current&&(d.current=w.cursor)}catch{f&&c(!0)}finally{h.current=!1}}},y=()=>{g().catch(()=>{})};y();const _=setInterval(y,OT);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:m("vl-events-stale")}),i.length===0&&!a&&l.jsx("small",{className:"nc-set-hint","data-testid":"vl-events-empty",children:m("vl-events-empty")}),i.length>0&&l.jsx("ol",{className:"nc-vl-events-list",children:i.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:$T(f)},`${f.seq}-${f.kind}`))})]})}function Zb({peer:t,token:e,onBack:n}){var i;return ui(),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:m("back"),children:[l.jsx(ht,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:m("back")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:t.label,children:t.label}),((i=t.session)==null?void 0:i.profile)&&l.jsxs("small",{className:"nc-bar-sub",children:[t.session.profile," · ",m("vl-events-title")]})]}),l.jsx("span",{className:"nc-bar-right"})]}),l.jsx("div",{className:"nc-vl-session-body",children:l.jsx(zT,{token:e,nodeId:t.nodeId,route:t.route||[]})})]}):null}const Jf=t=>as(Cs(t)).length===0,Zf=t=>Array.isArray(t)?t.join("/"):"";function FT(t){const e=new Set,n=[];for(const i of Array.isArray(t)?t:[])!i||!Ii.test(String(i.instanceId||""))||!Array.isArray(i.route)||!i.route.length||e.has(i.instanceId)||(e.add(i.instanceId),n.push({instanceId:i.instanceId,route:[...i.route],label:String(i.label||i.name||i.route.join(" › ")),status:i.status||"offline"}));return n.sort((i,s)=>i.label.localeCompare(s.label))}function hl(t){return{instanceId:t.ownerId,route:t.ownerRoute||[],label:t.ownerLabel,status:t.available===!1?"offline":"up"}}function no(t,e,n,i=!1,s=!0){const a=e.instanceId;return{...t,id:fo(i?null:a,t.name),ownerId:a,ownerRoute:i?[]:[...e.route],ownerLabel:i?"Local":e.label,local:i,available:s,ownerTopology:Array.isArray(n)?n:[],layout:am(t.layout,a,n)}}function HT(t,e,n,i,s=[]){const[a,c]=k.useState([]),[d,h]=k.useState(!1),[f,g]=k.useState("idle"),[y,_]=k.useState(""),[w,S]=k.useState(!1),[N,C]=k.useState(""),E=k.useRef([]),x=k.useRef([]),M=k.useRef(""),T=k.useRef(e),U=k.useRef(n),z=k.useRef(!1),V=k.useRef(!0),J=k.useRef(""),q=k.useMemo(()=>FT(s),[s]),X=q.map(K=>`${K.instanceId}:${Zf(K.route)}:${K.status}:${K.label}`).join("|");x.current=q,U.current=n,T.current=e,E.current=a;const H=k.useCallback(K=>lm(K.layout,M.current,x.current),[]),P=k.useCallback(()=>ul(T.current,M.current),[]),L=k.useCallback(K=>(Array.isArray(K)?K:[]).find(oe=>oe.id===P()),[P]),D=k.useCallback((K,oe=!0,le)=>{const te=le===void 0?P():ul(le,M.current),fe=nb(K,su()),Le=E.current.some(ue=>ue.id===te);E.current=fe,c(fe);const $e=fe.find(ue=>ue.id===te);if(oe&&$e){V.current=!0;const ue=H($e);i(ue),$e.local&&QM($e.name,ue)}else Le&&!$e&&(V.current=!0,i(na()),_("deck non più condiviso dal nodo owner"));VM(fe.filter(ue=>ue.local).map(ue=>ue.name))},[i,H]),I=k.useCallback(async K=>{let oe=await qc(t);const le=oe.decks.find(te=>te.name==="main");if(oe.decks.length===1&&le&&le.revision===0&&Jf(le.layout)){const te=KM(),fe=Cs(cm("main")||na());if(!Jf(fe)){const Le=am(fe,K,[]);oe.decks[0]=await Kc(t,"main",Le,0,[])}for(const Le of te.filter($e=>$e!=="main"))try{let $e=await X_(t,Le,[]);const ue=Cs(cm(Le)||na());Jf(ue)||($e=await Kc(t,Le,am(ue,K,[]),$e.revision,[]))}catch{}oe=await qc(t)}return oe},[t]),O=k.useCallback(async({migrate:K=!1}={})=>{const oe=await bm(t,[]),le=Ii.test(String(oe.instanceId||""))?oe.instanceId:"";if(!le)throw new Error("instanceId locale non disponibile");M.current=le,C(le);const[te,fe]=await Promise.all([K?I(le):qc(t),V_(t,[]).catch(()=>({nodes:[]}))]),Le={instanceId:le,route:[],label:"Local"},$e=te.decks.map(ye=>no(ye,Le,fe.nodes,!0,!0)),ue=E.current;return await Promise.all(x.current.map(async ye=>{if(ye.status!=="up"){$e.push(...ue.filter(Ne=>!Ne.local&&Ne.ownerId===ye.instanceId).map(Ne=>({...Ne,ownerRoute:[...ye.route],ownerLabel:ye.label,available:!1})));return}try{const[Ne,Ye]=await Promise.all([qc(t,ye.route),V_(t,ye.route).catch(()=>({nodes:[]}))]);$e.push(...Ne.decks.map(kt=>no(kt,ye,Ye.nodes,!1,!0)))}catch{$e.push(...ue.filter(Ye=>!Ye.local&&Ye.ownerId===ye.instanceId).map(Ye=>({...Ye,ownerRoute:[...ye.route],ownerLabel:ye.label,available:!1})))}})),$e.sort((ye,Ne)=>ye.local===Ne.local?ye.ownerLabel.localeCompare(Ne.ownerLabel)||(ye.name==="main"?-1:Ne.name==="main"?1:ye.name.localeCompare(Ne.name)):ye.local?-1:1),$e},[t,I,X]);k.useEffect(()=>{if(!t)return;let K=!1;const oe=J.current!==t;return J.current=t,O({migrate:oe}).then(le=>{if(K)return;const te=L(E.current),fe=L(le),Le=fe&&(!te||fe.revision>te.revision||te.available!==fe.available||Zf(te.ownerRoute)!==Zf(fe.ownerRoute));D(le,oe||!!Le&&!z.current),h(!0),fe&&_("")}).catch(le=>{K||(h(!0),_(String(le.message||le)))}),()=>{K=!0}},[D,O,X,t,L]);const R=k.useCallback(async(K,oe=!0)=>{if(!d||!z.current)return!0;const le=K===void 0?P():ul(K,M.current),te=E.current.find(fe=>fe.id===le);if(!te)return _(`deck inesistente: ${le}`),!1;if(te.available===!1)return _(`nodo owner offline: ${te.ownerLabel}`),!1;g("saving");try{const fe=xf(Cs(U.current),te.ownerId,te.ownerTopology),Le=await Kc(t,te.name,fe,te.revision,te.ownerRoute),$e=no(Le,hl(te),te.ownerTopology,te.local,!0);return D(E.current.map(ue=>ue.id===le?$e:ue),!1),z.current=!1,g("saved"),_(""),S(!1),setTimeout(()=>g("idle"),1500),!0}catch(fe){if(oe&&fe.status===409&&fe.data&&fe.data.current){const Le=E.current.find($e=>$e.id===le);if(Le){const $e=no(fe.data.current,hl(Le),Le.ownerTopology,Le.local,!0);return D(E.current.map(ue=>ue.id===le?$e:ue),!1),z.current=!0,R(le,!1)}}return g("error"),_(String(fe.message||fe)),fe.status===409&&S(!0),!1}},[d,t,D]),A=k.useCallback(async()=>{try{const K=await O();z.current=!1,S(!1),D(K,!0),_("")}catch(K){_(String(K.message||K))}},[O,D]);return k.useEffect(()=>{if(!d)return;if(V.current){V.current=!1;return}z.current=!0,g("saving");const K=setTimeout(R,650);return()=>clearTimeout(K)},[n,d,R]),k.useEffect(()=>{if(!d)return;const K=()=>{if(!z.current)return;const oe=E.current.find(te=>te.id===P());if(!oe||oe.available===!1)return;const le=xf(Cs(U.current),oe.ownerId,oe.ownerTopology);c2(t,oe.name,le,oe.revision,oe.ownerRoute)};return window.addEventListener("pagehide",K),window.addEventListener("beforeunload",K),()=>{window.removeEventListener("pagehide",K),window.removeEventListener("beforeunload",K)}},[d,t,P]),k.useEffect(()=>{if(!d)return;const K=setInterval(async()=>{try{const oe=await O(),le=L(E.current),te=L(oe),fe=te&&(!le||te.revision>le.revision||le.available!==te.available);if(fe&&z.current&&te){const Le=Z2(H(te),U.current);D(oe,!1),i(Le);return}D(oe,fe&&!z.current)}catch{}},5e3);return()=>clearInterval(K)},[d,O,D,H,i]),{decks:a,records:a,localNodeId:N,ready:d,saveState:f,error:y,setError:_,conflict:w,reloadCurrent:A,saveNow:R,select:async K=>{if(z.current&&!await R(P()))throw new Error("salvataggio del deck corrente fallito: cambio annullato");const oe=E.current.find(le=>le.id===K);if(!oe)throw new Error(`deck inesistente: ${K}`);return z.current=!1,V.current=!0,H(oe)},add:async(K,oe=null)=>{const le=oe===xs?E.current.find(Le=>Le.local):oe?E.current.find(Le=>Le.ownerId===oe):null;if(!le||le.available===!1)throw new Error("nodo owner non disponibile");const te=await X_(t,K,le.ownerRoute),fe=no(te,hl(le),le.ownerTopology,le.local,!0);return D([...E.current,fe],!1),fe},rename:async(K,oe)=>{const le=E.current.find(ue=>ue.id===K);if(!le)throw new Error("deck inesistente");if(ul(K,M.current)===P()&&z.current&&!await R(K))throw new Error(`salvataggio di "${le.name}" fallito: rinomina annullata`);const te=E.current.find(ue=>ue.id===K);if(!te)throw new Error("deck inesistente");const fe=await u2(t,te.name,oe,te.revision,te.ownerRoute),Le=no(fe,hl(te),te.ownerTopology,te.local,!0),$e=te.local?xs:te.ownerId;return kf(GM(su(),$e,K,Le.id)),D(E.current.map(ue=>ue.id===K?Le:ue),!1),Le},remove:async K=>{const oe=E.current.find(te=>te.id===K);if(!oe)throw new Error("deck inesistente");ul(K,M.current)===P()&&(z.current=!1),await d2(t,oe.name,oe.revision,oe.ownerRoute);const le=oe.local?xs:oe.ownerId;kf(XM(su(),le,K)),D(E.current.filter(te=>te.id!==K),!1)},reorder:(K,oe)=>{const le=E.current.find(ye=>ye.id===K),te=E.current.find(ye=>ye.id===oe);if(!le||!te)return!1;const fe=le.local?xs:le.ownerId,Le=te.local?xs:te.ownerId;if(fe!==Le)return!1;const $e=E.current.filter(ye=>(ye.local?xs:ye.ownerId)===fe).map(ye=>ye.id),ue=kf(YM(su(),fe,K,oe,$e));return D(nb(E.current,ue),!1),!0},addTileTo:async(K,oe)=>{const le=E.current.find(ye=>ye.id===K);if(!le)throw new Error("deck inesistente");if(le.available===!1)throw new Error(`nodo owner offline: ${le.ownerLabel}`);const te=$1(oe,M.current,x.current);if(!te)throw new Error("riferimento sessione non valido");const fe=H(le),Le=xf(jm(fe,te),le.ownerId,le.ownerTopology),$e=await Kc(t,le.name,Le,le.revision,le.ownerRoute),ue=no($e,hl(le),le.ownerTopology,le.local,!0);return D(E.current.map(ye=>ye.id===K?ue:ye),!1),ue},localMainId:fo(null,"main"),parseDeckId:zl}}const UT="/sw.js",fm="nc-sw-update";let Pl=null,qu=!1,Ku=null,Ex=Object.freeze({needed:!1,kind:null,version:"",browserVersion:""}),Nx=!1;function _g(){typeof window<"u"&&window.dispatchEvent(new Event(fm))}function yg(){const t=Ku||(qu?{kind:"reload",version:"",browserVersion:""}:null);Ex=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 e0(){return Ex}function WT(t){return typeof window>"u"?()=>{}:(window.addEventListener(fm,t),()=>window.removeEventListener(fm,t))}function wg(t){qu!==t&&(qu=t,yg(),_g())}const uu="nc-auto-reload",Vu="nc-reload";function bg(){try{return typeof location<"u"?location:null}catch{return null}}function Lx(){try{return typeof history<"u"?history:null}catch{return null}}function qT(t){const e=t===void 0?bg():t;if(!e||typeof e.search!="string")return null;try{return new URLSearchParams(e.search).get(Vu)}catch{return null}}function KT(t,{location:e,history:n}={}){const i=e===void 0?bg():e,s=n===void 0?Lx():n;if(!i||!s||typeof s.replaceState!="function")return!1;try{const a=new URLSearchParams(i.search||"");return a.set(Vu,t),s.replaceState(s.state??null,"",`${i.pathname||"/"}?${a.toString()}${i.hash||""}`),!0}catch{return!1}}function VT({location:t,history:e}={}){const n=t===void 0?bg():t,i=e===void 0?Lx():e;if(!n||!i||typeof i.replaceState!="function")return!1;try{const s=new URLSearchParams(n.search||"");if(!s.has(Vu))return!1;s.delete(Vu);const a=s.toString();return i.replaceState(i.state??null,"",`${n.pathname||"/"}${a?`?${a}`:""}${n.hash||""}`),!0}catch{return!1}}const Rx="nc-update-dismissed";function Ax(){try{return typeof sessionStorage<"u"?sessionStorage:null}catch{return null}}function YT(t,e,n){return[t,e,n].map(i=>i||"").join("|")}let pm=null;function GT(t,e,n){const i=n;return t&&e&&t!==e&&t!==i?{kind:"install",version:t,browserVersion:i}:e&&i&&e!==i?{kind:"stale",version:e,browserVersion:i}:null}function XT(t,e){if(!t)return!1;try{return t.getItem(Rx)===e}catch{return!1}}function QT(t={}){const e=t.storage===void 0?Ax():t.storage;if(pm&&e)try{e.setItem(Rx,pm)}catch{}qu=!1,Ku=null,yg(),_g()}function JT(t,e,n,i={}){const s=i.storage===void 0?Ax():i.storage,a=n,c=YT(t,e,a);pm=c;const d=GT(t,e,a);let h=XT(s,c)?null:d;if(h&&h.kind==="stale"){const g=`${e}|${a}`,y=qT(i.location)===g;let _=!1;if(!y&&s&&s.getItem(uu)!==g){try{s.setItem(uu,g)}catch{}_=s.getItem(uu)===g}_&&(KT(g,{location:i.location,history:i.history}),(i.applyImpl||Mx)(),h=null)}const f=JSON.stringify(h)===JSON.stringify(Ku);if(Ku=h,yg(),f||_g(),!d){try{s&&s.removeItem(uu)}catch{}VT({location:i.location,history:i.history})}}const ZT=1200;async function t0(t){if(typeof fetch=="function")try{await Promise.race([fetch(t,{cache:"reload"}),new Promise(e=>setTimeout(e,ZT))])}catch{}}async function Mx(){try{Pl&&await Pl.update()}catch{}typeof location<"u"&&(await t0(location.pathname),await t0("/version.json"),location.reload())}function e3(t){t.addEventListener("statechange",()=>{t.state==="installed"&&navigator.serviceWorker.controller&&wg(!0)})}function t3(){typeof navigator>"u"||!("serviceWorker"in navigator)||(navigator.serviceWorker.addEventListener("controllerchange",()=>{Nx&&location.reload()}),navigator.serviceWorker.register(UT).then(t=>{Pl=t,t.waiting&&wg(!0),t.addEventListener("updatefound",()=>{const e=t.installing;e&&e3(e)}),setInterval(()=>{t.update().catch(()=>{})},3600*1e3)}).catch(()=>{}))}function n3(){Nx=!0,wg(!1);const t=Pl&&Pl.waiting;t?(t.postMessage({type:"SKIP_WAITING"}),setTimeout(()=>location.reload(),4e3)):location.reload()}function i3({hash:t="",origin:e="",pathname:n="",search:i=""}={}){const s=String(t||"").replace(/^#/,""),a=`${n||""}${i||""}`;if(!s)return{token:"",pair:"",nextUrl:a};const c=new URLSearchParams(s),d=c.get("token")||"",h=c.get("pair")||"",f=h?`${e||""}${n||""}#pair=${h}`:"";return{token:d,pair:f,nextUrl:a}}const jx=9,Px=24,Tx="nc_side_w",n0="nc_side_min",s3=240,i0=new Set(["absent","present","active","unknown"]);function r3(){const t=Number(localStorage.getItem(Tx));return t>=180&&t<=480?t:s3}function o3(){const t=Number(localStorage.getItem("nc_fontsize"));return t>=jx&&t<=Px?t:13}function a3(){const t={token:"",pair:""};try{const{token:e,pair:n,nextUrl:i}=i3({hash:location.hash,origin:location.origin,pathname:location.pathname,search:location.search});if(e){t.token=e;try{localStorage.setItem("nc_token",e)}catch{}}if(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=sessionStorage.getItem("nc_token")||localStorage.getItem("nc_token")||""),!t.pair){const e=sessionStorage.getItem("nc_pair");e&&(t.pair=e)}return t}function s0(t){try{return Cs(cm(t))}catch{return na()}}function r0(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 o0({session:t,node:e,ownerId:n,cellName:i,token:s,readonly:a=!1,panelPort:c=0,onBack:d,onCellSwitcher:h,cellSwitcherOpen:f=!1,liveHost:g=null}){ui();const[y]=Zm(),[_,w]=k.useState(!1),[S,N]=k.useState(()=>window.matchMedia("(pointer: coarse)").matches),[C,E]=k.useState(null),[x,M]=k.useState(o3),[T,U]=k.useState(xl),[z,V]=k.useState(()=>xl()),J=()=>{const fe=fA(pA(xl()));U(fe),typeof window<"u"&&window.location.reload()},[q,X]=k.useState(i||t),[H,P]=k.useState(""),[L,D]=k.useState(""),[I,O]=k.useState(""),[R,A]=k.useState(!1),j=fe=>M(Le=>{const $e=Math.max(jx,Math.min(Px,Le+fe));return localStorage.setItem("nc_fontsize",String($e)),$e}),F=k.useRef(()=>{}),$=k.useRef(()=>!1),W=k.useRef(()=>{}),ce=k.useRef(!1),[ge,K]=k.useState(!1),[oe,le]=k.useState(!1),te=()=>{ce.current=!ce.current,K(ce.current)};return k.useEffect(()=>{X(i||t),A(!1)},[i,t]),k.useEffect(()=>{let fe=!0;const Le=e?e.split("/"):[],$e=e?`/api/route/${e.split("/").map(encodeURIComponent).join("/")}/_`:"/api";async function ue(){let Ne=null,Ye=null;try{const st=await(await cn(`${$e}/sessions`,s)).json();Array.isArray(st.sessions)&&(Ne=st.sessions.find(mt=>mt.name===t))}catch{}try{const bt=await Dr(s,Le);bt.available&&Array.isArray(bt.cells)&&(Ye=bt.cells.find(st=>st.tmuxSession===t))}catch{}if(!fe)return;X(eg({session:t,cell:Ye||(i?{cell:i}:null)})),D(typeof(Ye==null?void 0:Ye.panelUrl)=="string"?Ye.panelUrl.trim():""),O(typeof(Ye==null?void 0:Ye.cell)=="string"?Ye.cell:"");let kt="";Ye?kt=`${Ye.engine}${Ye.key?`·${Ye.key}`:""}`:Ne&&(kt=Ne.attached?`attached · ${r0(Ne.activity)}`:Ne.activity?r0(Ne.activity):""),P(kt)}ue();const ye=setInterval(ue,4e3);return()=>{fe=!1,clearInterval(ye)}},[t,e,s]),l.jsxs("div",{className:"nc-app",children:[l.jsxs("header",{className:"nc-bar nc-bar-single",children:[l.jsxs("button",{onClick:d,title:m("sessions"),children:[l.jsx(ht,{name:"chevronLeft",size:18}),l.jsx("span",{className:"nc-bar-label",children:m("sessions")})]}),l.jsxs("span",{className:"nc-bar-center",children:[l.jsx("b",{title:e?`${q} · ${e}`:q,children:q}),g&&g.cell&&g.cell===i?l.jsx("span",{className:`nc-live-host-dot ${L1(g)} nc-live-host-dot-header`,"data-testid":"live-host-header-dot",title:m("live-host-indicator").replace("{cell}",g.cell).replace("{mode}",m(g.mode?`live-host-mode-${g.mode}`:"live-host-mode-unknown")).replace("{state}",m(`live-host-state-${g.state}`))}):null,H&&l.jsx("small",{className:"nc-bar-sub",children:H})]}),l.jsxs("span",{className:"nc-bar-right",children:[l.jsx("button",{onClick:()=>j(-1),title:m("zoom-out"),children:l.jsx(ht,{name:"zoomOut",size:18})}),l.jsx("button",{onClick:()=>j(1),title:m("zoom-in"),children:l.jsx(ht,{name:"zoomIn",size:18})}),l.jsx("button",{type:"button",className:`nc-renderer-toggle${z==="webgl"?" on":""}`,onClick:J,"aria-pressed":z==="webgl",title:m("terminal-renderer-switch").replace("{requested}",m(T==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")).replace("{effective}",m(z==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")),"aria-label":m("terminal-renderer-switch").replace("{requested}",m(T==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")).replace("{effective}",m(z==="dom"?"terminal-renderer-dom":"terminal-renderer-webgl")),children:l.jsx(ht,{name:"gpu",size:18})}),l.jsx("button",{onClick:()=>N(fe=>!fe),title:m("composer"),children:l.jsx(ht,{name:"keyboard",size:20})}),l.jsx("button",{onClick:()=>w(fe=>!fe),title:m("files"),children:l.jsx(ht,{name:"folder",size:20})}),L&&l.jsx("button",{onClick:()=>A(fe=>!fe),title:m("panel"),"aria-pressed":R,children:l.jsx(ht,{name:"monitor",size:20})})]})]}),l.jsxs("div",{className:"nc-termwrap",children:[l.jsx(Vm,{session:t,node:e,token:s,readonly:a,takeSize:!0,sendRef:F,composerRef:$,actionRef:W,ctrlRef:ce,setCtrlArmed:K,onFiles:E,fontSize:x,selectionMode:oe,onSelectionModeChange:le,keyboardGesture:y.terminalKeyboardGesture,onRendererChange:V}),R&&L&&I&&l.jsx(Xm,{cellId:I,panelUrl:L,route:e?e.split("/"):[],panelPort:c,token:s,title:q})]}),l.jsx(iM,{onKeyboard:()=>N(fe=>!fe),onCellSwitcher:h,cellSwitcherOpen:f,send:fe=>F.current(fe),action:fe=>W.current(fe),ctrlArmed:ge,onCtrl:te,selectionMode:oe,onSelectionMode:le,keepKeyboardClosed:y.keybarKeepsKeyboardClosed,showEnter:y.showKeybarEnter,keybarLayout:y.keybarLayout}),S&&l.jsx(N1,{submitText:fe=>$.current(fe),token:s,session:t,node:e,ownerId:n,readonly:a,keepKeyboardClosedOnVoice:y.voiceKeepsKeyboardClosed}),_&&l.jsx(_1,{session:t,node:e,token:s,filesEvent:C,onClose:()=>w(!1)})]})}function l3(){ui();const[t]=k.useState(a3),[e,n]=k.useState(t.token),[i,s]=k.useState(t.pair||""),a=k.useCallback(()=>{s("");try{sessionStorage.removeItem("nc_pair")}catch{}},[]),[c,d]=k.useState(!1),h=DA(),[f]=k.useState(()=>qM(typeof location<"u"?location.pathname:"/")),[g,y]=k.useState(f.id),_=g===fo(null,Bi),[w,S]=k.useState(null),N=me=>{const Ce=Tr(me);S(Ce?{...Ce,...typeof(me==null?void 0:me.cellName)=="string"&&me.cellName?{cellName:me.cellName}:{}}:null)},[C,E]=k.useState([]),[x,M]=k.useState([]),[T,U]=k.useState([]),[z,V]=k.useState(!1),[J,q]=k.useState(null),[X,H]=k.useState(()=>f.ownerId?na():s0(f.name)),[P,L]=k.useState(null),[D,I]=k.useState(null),O=me=>I(Tr(me)),[R,A]=k.useState(null),j=km(e,h),F=k.useMemo(()=>(j||[]).filter(me=>me.instanceId).map(me=>({instanceId:me.instanceId,route:me.route,label:me.label,status:me.status})),[j]),$=HT(e,g,X,H,F),W=$.decks;k.useEffect(()=>{const me=new Map;for(const Ce of j||[]){const Me=(Ce.route||[Ce.name]).join("/"),Ze=new Set((Ce.sessions||[]).map(at=>at.name));for(const at of Ce.cells||[])!at.cell||!at.tmuxSession||at.cell===at.tmuxSession||Ze.has(at.cell)||me.set(`${Me}:${at.cell}`,`${Me}:${at.tmuxSession}`)}H(Ce=>Y2(Ce,me))},[j]),k.useEffect(()=>{$.localNodeId&&(f.ownerId&&f.ownerId===$.localNodeId&&H(me=>me.columns.some(Ce=>Ce.tiles.length)?me:s0(f.name)),H(me=>{const Ce=lm(me,$.localNodeId,F);return JSON.stringify(Ce)===JSON.stringify(me)?me:Ce}))},[F,$.localNodeId]);const[ce,ge]=k.useState(null),[K,oe]=k.useState(null),le=k.useRef(0),[te,fe]=k.useState(!1),[Le,$e]=k.useState(r3),[ue,ye]=k.useState(!_),[Ne,Ye]=k.useState(()=>_?localStorage.getItem(n0)==="1":!0),[kt,bt]=k.useState(!1),[st,mt]=k.useState("nodes"),[Et,it]=k.useState(!1),[It,Ut]=k.useState(""),[Bt,gt]=k.useState(!1),vt=(me="nodes",Ce=!1,Me="")=>{mt(me),it(Ce),Ut(Me),bt(!0)},[un,re]=k.useState(!1),[et,jt]=k.useState({deviceDefault:"",localNodeId:"",localNameDefault:""}),[ae,se]=k.useState(!1),[Z,_e]=k.useState(0),[xe,rt]=k.useState({});k.useEffect(()=>{try{localStorage.setItem(Tx,String(Le))}catch{}},[Le]),k.useEffect(()=>{try{localStorage.setItem(n0,Ne?"1":"")}catch{}},[Ne]),k.useEffect(()=>{if(!e)return;let me=!1;return Promise.all([_0(e),cn("/api/config",e).then(Ce=>Ce.json())]).then(([Ce,Me])=>{me||(jt({deviceDefault:Ce.deviceName||"",localNodeId:Ce.nodeId||"",localNameDefault:Ce.localName||""}),se(!!Me.readonlyDefault),_e(Number.isInteger(Me.panelPort)?Me.panelPort:0),rt(Me.nodePanelPorts&&typeof Me.nodePanelPorts=="object"&&!Array.isArray(Me.nodePanelPorts)?Me.nodePanelPorts:{}),(Ce.firstRun===!0&&!Me.readonlyDefault||i)&&re(!0))}).catch(()=>{}),()=>{me=!0}},[e,i]);const[ct,pt]=k.useState({}),At=k.useCallback(({route:me,hostCell:Ce,revision:Me})=>{const Ze=Di(me);pt(at=>({...at,[Ze]:{hostCell:Ce||null,hostLease:null,hostRevision:Number.isInteger(Me)?Me:(at[Ze]||{}).hostRevision||0,threadStatus:"absent"}}))},[]),Wt=me=>{const Ce=Di(me),Me=me.length?((j||[]).find(Ze=>Di(Array.isArray(Ze.route)?Ze.route:[])===Ce)||{}).cells||[]:x;return Hu({liveHost:ct[Ce]||null,cells:Me,localNodeId:$.localNodeId,ownerId:me.length?Ce:$.localNodeId})},Nt=k.useRef(j);k.useEffect(()=>{Nt.current=j},[j]);const Lt=k.useCallback(async()=>{try{const at=await(await cn("/api/sessions",e)).json();at.error||E(at.sessions||[])}catch{}let me=null,Ce=null;try{me=await Dr(e)}catch(Ze){Ce=Ze}const Me=Cm({fs:me,error:Ce});Me.kind==="data"?(M(Me.cells),U(Me.capabilities),V(!1),q(null)):Me.kind==="stale"?(V(!0),q(null)):(M([]),U([]),V(!1),q(Me.reason||""))},[e]);k.useEffect(()=>{let me=!1;const Ce=async()=>{const Ze=[[],...(Nt.current||[]).filter(Ot=>Ot.kind!=="vl"&&Ot.status==="up").map(Ot=>Array.isArray(Ot.route)&&Ot.route.length?Ot.route:[Ot.name])],at=await Promise.all(Ze.map(async Ot=>{const $t=Di(Ot);try{const sn=await Xu(e,Ot);return[$t,{hostCell:sn&&typeof sn.hostCell=="string"?sn.hostCell:null,hostLease:sn&&sn.host&&typeof sn.host.lease=="string"?sn.host.lease:null,hostRevision:Number.isInteger(sn&&sn.revision)?sn.revision:0,threadStatus:sn&&i0.has(sn.threadStatus)?sn.threadStatus:"unknown"}]}catch{return[$t,{error:!0}]}}));me||pt(Ot=>{let $t=!1;const sn={...Ot};for(const Oi of at){if(!Oi)continue;const[fi,Ms]=Oi;sn[fi]=Ms.error?{...Ot[fi]||{},threadStatus:"unknown"}:Ms,$t=!0}return $t?sn:Ot})};Ce();const Me=setInterval(Ce,4e3);return()=>{me=!0,clearInterval(Me)}},[e]),k.useEffect(()=>{if(!h)return;Lt();const me=setInterval(Lt,4e3);return()=>clearInterval(me)},[h,Lt]);const Q=k.useCallback(async(me,Ce=[])=>{const Me=Di(Ce),Ze=ct[Me]&&ct[Me].hostRevision||0;try{const at=await Qu(e,me,Ze,Ce);return pt(Ot=>({...Ot,[Me]:{hostCell:at.hostCell||null,hostLease:at.host&&typeof at.host.lease=="string"?at.host.lease:null,hostRevision:Number.isInteger(at.revision)?at.revision:Ze,threadStatus:i0.has(at.threadStatus)?at.threadStatus:"unknown"}})),{ok:!0}}catch(at){return{ok:!1,error:at}}},[e,ct]),Se=k.useCallback(async(me,Ce=[])=>{const Me=await Q(me,Ce);return Me.ok||window.alert(m(ku(Me.error))),Me.ok},[Q]),ze=k.useCallback(async(me=[])=>{const Ce=Di(me),Me=ct[Ce]&&ct[Ce].hostRevision||0;try{const Ze=await Ju(e,Me,me);return pt(at=>({...at,[Ce]:{hostCell:Ze.hostCell||null,hostLease:null,hostRevision:Number.isInteger(Ze.revision)?Ze.revision:Me,threadStatus:"unknown"}})),{ok:!0}}catch(Ze){return{ok:!1,error:Ze}}},[e,ct]),qe=k.useCallback(async(me=[])=>{const Ce=await ze(me);return Ce.ok||window.alert(m(ku(Ce.error))),Ce.ok},[ze]);k.useEffect(()=>{let me=!1;const Ce=()=>{cn("/api/config",e).then(Ze=>Ze.json()).then(Ze=>{me||JT(Ze.version,Ze.uiVersion,"0.9.33")}).catch(()=>{})};Ce();const Me=setInterval(Ce,6e4);return()=>{me=!0,clearInterval(Me)}},[e]);const Qe=new Set([...C.map(me=>me.name),...j.flatMap(me=>me.sessions.map(Ce=>Ce.key))]),Pt=as(X),Tt=me=>H(Ce=>{const Me=$1(me,$.localNodeId,F)||me,Ze=jm(Ce,Me);return Ze===Ce&&as(Ce).length>=9&&$.setError(m("grid-full")),Ze}),G=async(me,Ce=[])=>{try{await _m(e,me,Ce)}catch{return}const Me=Ce.length?`${Ce.join("/")}:${me}`:me;H(Ze=>ju(Ze,Me)),Lt()},ne=async(me,Ce,Me=[])=>{try{await v0(e,me,Ce,Me)}catch{return}Lt()},be=async(me,Ce,Me=[])=>{await p0(e,{cell:me,enabled:!!Ce},Me),Lt()},Ve=async me=>{if(!ce)return;const{cell:Ce}=ce,Me=Array.isArray(ce.route)?ce.route:[];if(me.action==="up"){const at=await vm(e,{cell:Ce,boot:!!me.boot,...me.engine?{engine:me.engine}:{},...me.model!==void 0?{model:me.model}:{},...me.permissionPolicy?{permissionPolicy:me.permissionPolicy}:{}},Me),Ot=Pm(at);Ot&&$.setError(Ot.text)}else await Su(e,{cell:Ce,boot:!!me.boot},Me);const Ze=me.action==="up"?!!me.boot:me.boot?!1:!!ce.boot;oe({id:++le.current,cell:Ce,route:Me,enabled:Ze}),Lt()},Be=k.useCallback(me=>{oe(Ce=>(Ce==null?void 0:Ce.id)===me?null:Ce)},[]),Ae=async me=>{if(!(!(me!=null&&me.direct)||te)){fe(!0);try{await Sm(e,me.name,me.tunnelStatus==="up"?"down":"up")}finally{fe(!1)}}},ot=async(me,Ce)=>{const Me=String(Ce||"").trim();return!(me!=null&&me.direct)||!aa(Me)?!1:(await b0(e,me.name,Me),!0)},zt=me=>{const Ce=W.find(Me=>Me.id===me);if(!Ce)return!1;try{const Me=window.open(Cf(Ce,e),"_blank");return Me&&(Me.opener=null),!!Me}catch{return!1}},nn=async me=>{if(!me||me===g)return;const Ce=await $.select(me),Me=$.records.find(Ze=>Ze.id===me);y(me),H(Ce),L(null),I(null);try{history.replaceState(null,"",Cf(Me||me,null))}catch{}},Ue=async(me,Ce)=>{const Me=await $.add(me,Ce);await nn(Me.id)},Oe=async(me,Ce)=>{const Me=await $.rename(me,Ce);if(me===g){y(Me.id),H(lm(Me.layout,$.localNodeId,F)),L(null),I(null);try{history.replaceState(null,"",Cf(Me,null))}catch{}}},xt=async me=>{await $.remove(me),me===g&&await nn($.localMainId)},Hn=async(me,Ce)=>{!Ce||Ce===g||(await $.addTileTo(Ce,me),H(Me=>ju(Me,me)))};if(!e)return l.jsxs("div",{className:"nc-auth",children:[l.jsx("p",{children:m("auth-prompt")}),l.jsx("input",{onChange:me=>n(me.target.value.trim()),placeholder:"token"}),l.jsxs("label",{children:[l.jsx("input",{type:"checkbox",checked:c,onChange:me=>d(me.target.checked)})," ",m("remember-device")]}),l.jsx("button",{onClick:()=>{(c?localStorage:sessionStorage).setItem("nc_token",e)},children:"ok"})]});const Xn=l.jsxs(l.Fragment,{children:[kt&&l.jsx(xT,{token:e,initialTab:st,initialLocation:It,startNewCell:Et,onClose:()=>{bt(!1),it(!1),Ut("")}}),un&&l.jsx(CT,{token:e,initialPair:i,...et,onPairDone:a,onDone:()=>re(!1)}),l.jsx(MT,{token:e})]});if(!h)return R?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"nc-single-overlay",children:l.jsx(Zb,{peer:R,token:e,onBack:()=>A(null)})}),Xn]}):w?l.jsxs(l.Fragment,{children:[l.jsx(o0,{session:w.session,node:w.node,ownerId:w.ownerId,cellName:w.cellName,token:e,readonly:ae,liveHost:Wt(w.node?w.node.split("/"):[]),panelPort:Uu(w.node?w.node.split("/"):[],xe,Z),onBack:()=>S(null),onCellSwitcher:()=>gt(!0),cellSwitcherOpen:Bt}),Bt&&l.jsx(BT,{token:e,current:w,panelPort:Z,nodePanelPorts:xe,hostByRoute:ct,onDesignateCell:Q,onClearHostCell:ze,onLiveHostApplied:At,onPick:me=>{N(me),gt(!1)},onClose:()=>gt(!1)}),Xn]}):l.jsxs(l.Fragment,{children:[l.jsx(f5,{onPick:N,token:e,onSettings:vt,onOpenVlSession:A,hostByRoute:ct,onDesignateCell:Se,onClearHostCell:qe}),Xn]});const Cn=_||!ue;return l.jsxs("div",{className:"nc-workspace",children:[Cn&&l.jsx(jM,{sessions:C,cells:x,activeSessions:Pt,nodeGroups:j,token:e,onPeekOpen:()=>gt(!1),overlayOpen:Bt,fleetCapabilities:T,fleetStale:z,fleetOff:J,bootSettlement:K,onBootSettlementApplied:Be,localNodeId:$.localNodeId,hostByRoute:ct,onDesignateCell:Se,onClearHostCell:qe,onPick:O,onAddTile:Tt,onPower:ge,onBoot:be,onBootError:me=>$.setError(String((me==null?void 0:me.message)||me)),onNodePower:Ae,onNodeRename:ot,onKill:G,onVisibility:ne,onNew:()=>vt("fleet",!0),onSettings:vt,onOpenVlSession:A,width:Le,collapsed:Ne,onResize:$e,onToggleCollapse:()=>Ye(me=>!me)}),l.jsxs("div",{className:"nc-workspace-main",children:[l.jsx(pj,{decks:W,currentDeck:g,onCreate:Ue,onRename:Oe,onDelete:xt,onReorder:$.reorder,onOpenWindow:zt,onNavigate:nn,saveState:$.saveState,error:$.error,conflict:$.conflict,onReloadDeck:$.reloadCurrent,sidebarVisible:Cn,onToggleSidebar:_?null:()=>ye(me=>!me)}),l.jsx(zM,{layout:X,onLayoutChange:H,onResizeEnd:()=>{$.saveNow()},token:e,readonly:ae,sessionsAlive:Qe,focusSession:P,onFocus:L,onOpenSingle:O,decks:W,currentDeck:g,onSendToDeck:Hn,cells:x,nodeGroups:j,panelPort:Z,nodePanelPorts:xe})]}),R&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(Zb,{peer:R,token:e,onBack:()=>A(null)})}),D&&l.jsx("div",{className:"nc-single-overlay",children:l.jsx(o0,{session:D.session,node:D.node,ownerId:D.ownerId,cellName:eg({session:D.session,node:D.node,ownerId:D.ownerId,cells:x,nodeGroups:j}),token:e,readonly:ae,liveHost:Wt(D.node?D.node.split("/"):[]),panelPort:Uu(D.node?D.node.split("/"):[],xe,Z),onBack:()=>I(null)})}),ce&&l.jsx(Nu,{cell:ce,token:e,route:Array.isArray(ce.route)?ce.route:[],onConfirm:Ve,onClose:()=>ge(null)}),Xn]})}function c3(t){return t.kind==="install"?m("update-installed-restart").replace("{v}",t.version):t.kind==="stale"?m("update-stale").replace("{ui}",t.version).replace("{browser}",t.browserVersion):m("update-available").replace("{v}",t.version).replace(" "," ").trim()}function u3(){ui();const t=k.useSyncExternalStore(WT,e0,e0);return t.needed?l.jsxs("div",{className:"nc-update",role:"status","aria-live":"polite",children:[l.jsx("span",{className:"nc-update-msg",children:c3(t)}),t.kind==="stale"&&l.jsx("button",{className:"nc-update-btn",onClick:Mx,children:m("reload-no-cache")}),t.kind==="reload"&&l.jsx("button",{className:"nc-update-btn",onClick:n3,children:m("reload")}),l.jsx("button",{className:"nc-update-close",onClick:QT,"aria-label":m("update-dismiss"),title:m("update-dismiss"),children:"×"})]}):null}t3();_k.createRoot(document.getElementById("root")).render(l.jsxs(dk.StrictMode,{children:[l.jsx(l3,{}),l.jsx(u3,{})]}));
@@ -11,7 +11,7 @@
11
11
  <meta name="apple-mobile-web-app-title" content="NexusCrew" />
12
12
  <link rel="manifest" href="/manifest.json" />
13
13
  <title>NexusCrew</title>
14
- <script type="module" crossorigin src="/assets/index-CH2iAu6y.js"></script>
14
+ <script type="module" crossorigin src="/assets/index-Uco-EbNb.js"></script>
15
15
  <link rel="stylesheet" crossorigin href="/assets/index-DqCfZFGi.css">
16
16
  </head>
17
17
  <body>
@@ -1 +1 @@
1
- {"version":"0.9.32"}
1
+ {"version":"0.9.33"}
@@ -935,6 +935,51 @@ async function createBuiltinFleet(cfg = {}) {
935
935
  return { ok: true, id: wantedId, engine: wantedEngine };
936
936
  }
937
937
 
938
+ // I campi non-identita' che `parseModel` ammette per una dichiarazione:
939
+ // id ed engine SONO l'identita' (il chiaro per cui esiste edit-model e' non
940
+ // doverla ritoccare), tutto il resto e' patchabile con la stessa validazione.
941
+ const EDIT_MODEL_FIELDS = new Set(['label', 'contextWindow', 'maxTokens', 'reasoning']);
942
+
943
+ async function editModel(id, engine, patch) {
944
+ if (readonly()) throw httpError(403, 'READONLY: edit-model bloccato');
945
+ const wantedId = String(id || '').trim();
946
+ const wantedEngine = String(engine || '').trim();
947
+ if (!wantedId || !wantedEngine) throw httpError(400, 'id e engine sono obbligatori');
948
+ if (!patch || typeof patch !== 'object' || Array.isArray(patch)) throw httpError(400, 'patch mancante');
949
+ const keys = Object.keys(patch);
950
+ if (!keys.length) throw httpError(400, 'patch vuota: niente da modificare');
951
+ for (const key of keys) {
952
+ if (!EDIT_MODEL_FIELDS.has(key)) throw httpError(400, `campo non ammesso per edit-model: ${key}`);
953
+ }
954
+ if (patch.label !== undefined) {
955
+ if (typeof patch.label !== 'string' || !patch.label.trim() || patch.label.trim().length > 64) {
956
+ throw httpError(400, 'label non valida: stringa non vuota, massimo 64 caratteri');
957
+ }
958
+ }
959
+ for (const key of ['contextWindow', 'maxTokens']) {
960
+ if (patch[key] !== undefined && (!Number.isSafeInteger(patch[key]) || patch[key] < 1)) {
961
+ throw httpError(400, `${key} non valido: intero >= 1`);
962
+ }
963
+ }
964
+ if (patch.reasoning !== undefined && typeof patch.reasoning !== 'boolean') {
965
+ throw httpError(400, 'reasoning non valido: booleano');
966
+ }
967
+ const defs = reloadDefs();
968
+ if (!(defs.models || []).some((m) => m.id === wantedId && m.engine === wantedEngine)) {
969
+ throw httpError(404, `modello non dichiarato: ${wantedId} su ${wantedEngine}`);
970
+ }
971
+ // La scrittura passa da `mutate`, che rilegge e RIVALIDA l'intero file: la
972
+ // validazione completa resta quella del parser (contextWindow >= 1024 fino
973
+ // al cap, label entro il limite) e un valore fuori schema non entra. Gli
974
+ // engine che risolvono questo modello NON vengono toccati: la dichiarazione
975
+ // e' la stessa riga del file, l'engine non ha nulla da ricaricare.
976
+ await mutate(defs, (d) => {
977
+ const target = d.models.find((m) => m.id === wantedId && m.engine === wantedEngine);
978
+ Object.assign(target, patch);
979
+ });
980
+ return { ok: true, id: wantedId, engine: wantedEngine, edited: keys };
981
+ }
982
+
938
983
  async function editEngine(id, patch, envChanges) {
939
984
  if (readonly()) throw httpError(403, 'READONLY: edit-engine bloccato');
940
985
  if (!id) throw httpError(400, 'id engine mancante');
@@ -1490,7 +1535,7 @@ async function createBuiltinFleet(cfg = {}) {
1490
1535
  }
1491
1536
 
1492
1537
  function capabilities() {
1493
- return ['status', 'up', 'down', 'restart', 'engine', 'boot', 'define', 'edit', 'remove', 'import', 'restore', 'schema', 'definitions', 'credentials', 'model-test'];
1538
+ return ['status', 'up', 'down', 'restart', 'engine', 'boot', 'define', 'edit', 'remove', 'import', 'restore', 'schema', 'definitions', 'credentials', 'model-test', 'edit-model'];
1494
1539
  }
1495
1540
 
1496
1541
  // Un engine del documento con un `baseUrl` dichiarato a mano: indirizzo e
@@ -1566,7 +1611,7 @@ async function createBuiltinFleet(cfg = {}) {
1566
1611
  defineCell, editCell, removeCell, importCell, restoreCells, restoreEngines,
1567
1612
  schema, definitions, capabilities,
1568
1613
  credentialStatus, setLocalCredential, removeLocalCredential, testModel,
1569
- defineModel, removeModel, close,
1614
+ defineModel, editModel, removeModel, close,
1570
1615
  // Fetta 2b: il lease Live esposto alle route /api/lease, che il bridge
1571
1616
  // MCP delle celle consuma per register/refresh/recovery. Assente se il
1572
1617
  // lease e' disattivato: le route rispondono 501, non 500.
@@ -188,6 +188,11 @@ function fleetRoutes(fleetP, cfg = {}) {
188
188
  if (typeof f.removeModel !== 'function') { const e = new Error('not supported by this fleet provider'); e.status = 501; throw e; }
189
189
  return f.removeModel(String(b.id || ''), String(b.engine || ''));
190
190
  }, { mutate: true }));
191
+ r.post('/edit-model', guard((f, b) => {
192
+ requireCap(f, 'edit-model');
193
+ if (typeof f.editModel !== 'function') { const e = new Error('not supported by this fleet provider'); e.status = 501; throw e; }
194
+ return f.editModel(String(b.id || ''), String(b.engine || ''), b.patch);
195
+ }, { mutate: true }));
191
196
  r.post('/define-engine', guard((f, b) => { requireCap(f, 'define'); return f.defineEngine(b.def); }, { mutate: true }));
192
197
  r.post('/edit-engine', guard((f, b) => { requireCap(f, 'edit'); return f.editEngine(b.id, b.patch, b.envChanges); }, { mutate: true }));
193
198
  r.post('/remove-engine', guard((f, b) => { requireCap(f, 'remove'); return f.removeEngine(b.id); }, { mutate: true }));
@@ -207,7 +207,7 @@ function knownResource(resource) {
207
207
  || /^\/event-feed\/[A-Za-z0-9._-]{1,32}$/.test(resource)
208
208
  || /^\/event-feed\/node\/[a-f0-9]{32}$/.test(resource)
209
209
  || isPanelResource(resource)
210
- || /^\/fleet\/(status|schema|definitions|credentials\/status|credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource);
210
+ || /^\/fleet\/(status|schema|definitions|credentials\/status|credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|edit-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource);
211
211
  }
212
212
 
213
213
  // Il pannello di una cella e' l'unica risorsa federata con un gate PER-PEER a
@@ -293,7 +293,7 @@ function allowedResource(resource, method = 'GET') {
293
293
  // enum. Non genera testo, quindi non consuma token. Resta comunque una
294
294
  // mutazione ai fini di READONLY (sotto): un nodo dichiarato di sola lettura
295
295
  // non emette richieste autenticate su comando di un peer.
296
- if (/^\/fleet\/(credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) return method === 'POST';
296
+ if (/^\/fleet\/(credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|edit-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) return method === 'POST';
297
297
  // Notify: solo POST. `/events` e `/push/*` restano NON federati — SSE non
298
298
  // puo' autenticarsi col Bearer.
299
299
  //
@@ -90,7 +90,7 @@ function classifyResource(resource, method = 'GET') {
90
90
  if (/^\/fleet\/(status|schema|definitions|credentials\/status)$/.test(resource)) {
91
91
  return m === 'GET' ? 'operator' : null;
92
92
  }
93
- if (/^\/fleet\/(credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) {
93
+ if (/^\/fleet\/(credentials\/(?:set|remove)|up|down|restart|engine|boot|define-engine|edit-engine|remove-engine|define-model|edit-model|remove-model|model-test|define-cell|edit-cell|remove-cell|restore-cells|restore-engines)$/.test(resource)) {
94
94
  return m === 'POST' ? 'operator' : null;
95
95
  }
96
96
  if (resource === '/decks') return m === 'GET' || m === 'POST' ? 'operator' : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmmbuto/nexuscrew",
3
- "version": "0.9.32",
3
+ "version": "0.9.33",
4
4
  "description": "Faithful browser tmux client — attach to live sessions over a real PTY, localhost-only, mobile-easy",
5
5
  "main": "lib/server.js",
6
6
  "bin": {