livedesk 0.1.392 → 0.1.393

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.
@@ -14,4 +14,4 @@ ${rf(a,r)}`}const ub={eyebrow:"Change computer role",title:"Switch this computer
14
14
  ${je.displayPath||""}`)}]:[]},Ie=async()=>{try{await c()}catch(ae){b(ae instanceof Error?ae.message:"Unable to refresh Hub drives.")}},Oe=[{id:"local",label:"Local drives",icon:Ll,roots:a.filter(ae=>Jd(ae)==="local")},{id:"removable",label:"Removable drives",icon:ZS,roots:a.filter(ae=>Jd(ae)==="removable")},{id:"network",label:"Network drives",icon:ep,roots:a.filter(ae=>Jd(ae)==="network")}];return s.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[s.jsxs("div",{className:"hub-file-explorer-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub file explorer"}),s.jsxs("strong",{children:[s.jsx(Ll,{size:16})," Browse files on this Hub"]})]}),s.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[s.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:s.jsx(Jy,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(JS,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{Ie()},title:"Refresh drives",type:"button",children:s.jsx(Ho,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(Ll,{size:24}),s.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?s.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[s.jsx(Is,{size:24}),s.jsx("strong",{children:l})]}):s.jsxs("div",{className:"hub-file-explorer-content",children:[s.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[s.jsxs("div",{className:"hub-drive-sidebar-title",children:[s.jsx(Ll,{size:15}),s.jsx("strong",{children:"This PC"})]}),Oe.map(ae=>ae.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(ae.icon,{size:13}),ae.label]}),s.jsx("div",{className:"hub-drive-list",children:ae.roots.map(ke=>{const je=ae.icon,De=ce.has(ke.id)||ke.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${M===ke.id?"active":""} ${De?"unavailable":""}`,onClick:()=>{pe(ke)},"aria-pressed":M===ke.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(je,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:ke.name}),s.jsx("small",{children:ke.displayPath||ke.name}),s.jsxs("em",{children:[my(ke.freeBytes||0)," free / ",my(ke.totalBytes||0)]})]}),L===ke.id?s.jsx(qr,{className:"hub-drive-item-status spin",size:15}):De?s.jsx(rx,{className:"hub-drive-item-status",size:15}):null]},ke.id)})})]},ae.id)),a.length===0&&s.jsxs("div",{className:"hub-drive-sidebar-empty",children:[s.jsx(Is,{size:17}),s.jsx("span",{children:"No drives available."})]})]}),s.jsxs("div",{className:"hub-file-explorer-browser",children:[s.jsxs("div",{className:"hub-file-explorer-navigation",children:[s.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:E.map((ae,ke)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ke>0&&s.jsx(tp,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${ke===E.length-1?"current":""}`,onClick:()=>ge(ke),"aria-current":ke===E.length-1?"location":void 0,type:"button",children:ae.name})]},ae.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[q&&s.jsx(qr,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:Ae,disabled:E.length<=1||q,title:"Back to parent folder",type:"button",children:s.jsx(Vy,{size:16})})]})]}),K&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(rx,{size:15}),s.jsx("span",{children:K})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:s.jsx(WA,{fonts:!1,children:s.jsx(VA,{data:oe,panels:X?[{path:X,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:ie,icons:"simple",menuOptions:Q},`${O?.id||"no-root"}:${W}`)})})]})]})]})}class oN extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,r){console.error("[LiveDesk] Share Files runtime error",a,r.componentStack)}render(){return this.state.error?s.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[s.jsx(gf,{size:24}),s.jsx("strong",{children:"Share Files could not be opened."}),s.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),s.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[s.jsx(Ho,{size:15})," Retry"]})]}):this.props.children}}function cN(n){return n.deviceName||n.hostname||n.deviceId}function uN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c}){const d=new Set(r);return s.jsxs("section",{className:"distribution-targets",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:a==="all"?`${n.length} connected`:`${r.length} selected`})]}),s.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(eb,{size:14})," All connected"]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(en,{size:14})," Selected"]})]})]}),s.jsx("div",{className:"file-share-device-list","aria-label":"Connected workstation targets",children:n.length===0?s.jsx("div",{className:"file-share-empty-inline",children:"No connected workstations."}):n.map(m=>{const p=a==="all"||d.has(m.deviceId);return s.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),s.jsx(en,{size:20,"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:cN(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(Hn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function dN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function fN({folders:n,loading:a,busy:r,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,onAdd:g}){return s.jsxs("section",{className:"file-share-sync-panel",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub folders"}),s.jsx("strong",{children:"Continuous sync"})]}),s.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!l||n.length===0,type:"button",children:[s.jsx(Kd,{size:15})," ",r?"Syncing":"Sync all"]})]}),a?s.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?s.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[s.jsx(Kd,{size:28}),s.jsx("strong",{children:"Add a selected Hub folder"}),s.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):s.jsx("div",{className:"file-share-sync-list",children:n.map(v=>s.jsxs("article",{className:`file-share-sync-row state-${v.status}`,children:[s.jsx("div",{className:"file-share-sync-icon",children:s.jsx(Kd,{size:19})}),s.jsxs("div",{className:"file-share-sync-info",children:[s.jsx("strong",{children:v.name}),s.jsx("span",{children:v.displayPath}),s.jsxs("small",{children:[v.fileCount," files / ",dN(v.totalBytes)," · ",v.lastSyncedAt?`Last sync ${Nh(v.lastSyncedAt)} ago`:v.message||"Not synced yet"]})]}),s.jsxs("label",{className:"file-share-auto-sync",children:[s.jsx("input",{type:"checkbox",checked:v.autoSync,onChange:()=>m(v)}),s.jsx("span",{children:"Auto"})]}),s.jsxs("button",{className:"text-button compact",onClick:()=>d(v),disabled:r||!l||v.status==="syncing",type:"button",children:[s.jsx(Ho,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(v),title:"Remove sync folder",type:"button",children:s.jsx(Zh,{size:15})})]},v.id))})]})}function mN(n){const r=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return s.jsxs("aside",{className:"file-share-distribution-panel",children:[s.jsxs("div",{className:"file-share-distribution-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Distribution"}),s.jsx("strong",{children:"Hub → workstations"})]}),s.jsx(Bo,{size:18})]}),s.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[s.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),s.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?s.jsxs(s.Fragment,{children:[s.jsx(uN,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),s.jsxs("label",{className:"file-share-destination",children:[s.jsx("span",{children:"Destination folder"}),s.jsxs("div",{children:[s.jsx(Lo,{size:15}),s.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),s.jsxs("div",{className:"file-share-selection-summary",children:[s.jsx("span",{children:"Selected"}),s.jsx("strong",{children:n.selectedSummary})]}),s.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[s.jsx(Bo,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(Lo,{size:16})," Add selected folder to Sync"]})]}):s.jsx(fN,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:r,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function hN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function hy(n){return n.totalBytes>0?Math.max(0,Math.min(100,Math.round(n.sentBytes/n.totalBytes*100))):n.totalFiles>0?Math.max(0,Math.min(100,Math.round(n.completedFiles/n.totalFiles*100))):n.state==="completed"?100:0}function py(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} workstation${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} workstation${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function gy(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function pN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,filePickerRef:b,folderPickerRef:y,onBrowserFileImport:w,onBrowserFolderImport:S,onNotice:j,onTransferChange:N}){const M=Array.isArray(a)?a:[],[k,E]=u.useState([]),[R,U]=u.useState(!0),[H,W]=u.useState(""),[_,L]=u.useState([]),[le,q]=u.useState([]),[te,K]=u.useState(null),[ne,ce]=u.useState(!1),[V,O]=u.useState([]),[Y,X]=u.useState(!0),[P,oe]=u.useState(!1),[we,J]=u.useState("send"),[B,pe]=u.useState([]),ge=u.useRef(new Set),xe=u.useMemo(()=>m==="all"?M.map(de=>de.deviceId):p.filter(de=>M.some(be=>be.deviceId===de)),[M,p,m]),Ae=B.find(de=>!gy(de.state)),_e=le.length===1&&le[0].type==="folder"?le[0]:null,ie=le.length===0?"Select files or folders from the Hub explorer.":ne?"Calculating selection size...":te?`${te.files} files, ${te.folders} folders · ${hN(te.totalBytes)}`:`${le.length} item${le.length===1?"":"s"} selected`,Q=de=>{N({id:de.jobId,state:de.state,progress:hy(de),message:py(de)})},Ie=u.useCallback(async()=>{const de=await KA(n,!0);return E(de),W(""),de},[n]),Oe=async()=>{try{const be=(await ZA(n,!0)).jobs||[],We=await Promise.all([...ge.current].map(async Xe=>{try{return await JA(Xe,n)}catch{return null}})),at=[...be,...We.filter(Boolean)],wn=[...new Map(at.map(Xe=>[Xe.jobId,Xe])).values()];pe(wn),wn.forEach(Q),wn.filter(Xe=>gy(Xe.state)).forEach(Xe=>ge.current.delete(Xe.jobId))}catch{}};u.useEffect(()=>{let de=!0;U(!0),W(""),Promise.all([Ie(),fy(n).then(We=>{de&&O(We)})]).catch(We=>{de&&(W(We instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(We instanceof Error?We.message:"Hub file system is unavailable."))}).finally(()=>{de&&(U(!1),X(!1))}),Oe();const be=window.setInterval(()=>{Oe()},800);return()=>{de=!1,window.clearInterval(be)}},[n,Ie]),u.useEffect(()=>{if(_.length===0){K(null);return}let de=!1;return ce(!0),QA(_,n).then(be=>{de||K(be)}).catch(be=>{de||j(be instanceof Error?be.message:"Unable to calculate selected size.")}).finally(()=>{de||ce(!1)}),()=>{de=!0}},[n,_.join("|")]);const ae=(de,be)=>{L(de),q(be)},ke=de=>{de.forEach(be=>ge.current.add(be.jobId)),pe(be=>[...new Map([...be,...de].map(We=>[We.jobId,We])).values()]),de.forEach(Q)},je=async()=>{if(!r){j(l);return}if(_.length===0){j("Select files or folders from the Hub explorer.");return}if(xe.length===0){j("Choose at least one connected workstation.");return}if(Ae){j("A Hub transfer is already running.");return}try{const de=await XA(_,xe,c.trim(),n);ge.current.add(de.jobId),j("Hub transfer queued."),await Oe()}catch(de){j(de instanceof Error?de.message:"Unable to start Hub transfer.")}},De=async de=>{const be=de||_e;if(!be||be.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const We=await tN(be.id,n);O(at=>[...at.filter(wn=>wn.id!==We.folder.id),We.folder]),J("sync"),j(`${be.name} is ready for Hub sync.`)}catch(We){j(We instanceof Error?We.message:"Unable to add the Hub folder to Sync.")}},Le=async de=>{if(xe.length===0){j("Choose at least one connected workstation.");return}oe(!0),O(be=>be.map(We=>We.id===de.id?{...We,status:"syncing"}:We));try{const be=await sN(de.id,xe,c.trim(),n);ke(be.jobs||[]),j(be.jobs?.length?"Hub sync queued.":"No changed files to sync.");const We=await fy(n);O(We)}catch(be){j(be instanceof Error?be.message:"Unable to sync the Hub folder."),O(We=>We.map(at=>at.id===de.id?{...at,status:"error",message:"Sync failed"}:at))}finally{oe(!1)}},$e=async()=>{oe(!0);try{for(const de of V)await Le(de)}finally{oe(!1)}},he=async de=>{try{const be=await nN(de.id,{autoSync:!de.autoSync},n);O(We=>We.map(at=>at.id===de.id?be.folder:at))}catch(be){j(be instanceof Error?be.message:"Unable to update auto sync.")}},Me=async de=>{try{await aN(de.id,n),O(be=>be.filter(We=>We.id!==de.id))}catch(be){j(be instanceof Error?be.message:"Unable to remove the sync folder.")}};return s.jsxs("section",{className:"livedesk-file-explorer",children:[s.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,onChange:de=>{de.currentTarget.files&&w(de.currentTarget.files),de.currentTarget.value=""}}),s.jsx("input",{ref:y,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:de=>{de.currentTarget.files&&S(de.currentTarget.files),de.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(oN,{onRetry:()=>window.location.reload(),children:[s.jsx(lN,{hubUrl:n,roots:k,loading:R,error:H,onRefreshRoots:Ie,onImportFiles:()=>b.current?.click(),onImportFolder:()=>y.current?.click(),onSelectionChange:ae,onShareItem:de=>{L([de.id]),q([de]),J("send")},onAddSyncFolder:de=>{L([de.id]),q([de]),De(de)},onNotice:j}),s.jsx(mN,{devices:M,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:le,selectedSummary:ie,canShare:r&&!Ae&&_.length>0&&xe.length>0&&!ne,onShare:()=>{je()},canAddSync:!!_e,onAddSync:()=>{De()},tab:we,onTabChange:J,folders:V,foldersLoading:Y,syncBusy:P,onSyncAll:()=>{$e()},onSync:de=>{Le(de)},onToggleAuto:de=>{he(de)},onRemove:de=>{Me(de)},onAddFolder:()=>{De()}})]})}),Ae&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[py(Ae)," · ",hy(Ae),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{eN(Ae.jobId,n).then(de=>{pe(be=>be.map(We=>We.jobId===de.jobId?de:We)),Q(de)})},title:"Cancel transfer",type:"button",children:s.jsx(Ja,{size:14})})]})})]})}const gN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1},g){return s.jsxs("form",{className:"agents-composer",onSubmit:v=>{v.preventDefault(),l()},children:[s.jsxs("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:p,children:[s.jsx(e0,{size:17}),m!==void 0&&s.jsx("span",{className:"agents-suggested-count","aria-hidden":"true",children:m})]}),s.jsx("textarea",{ref:g,value:a,onChange:v=>r(v.target.value.slice(0,4e3)),placeholder:"Ask LiveDesk to work across your machines...","aria-label":"Ask LiveDesk",rows:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(qr,{className:"spin",size:16}):s.jsx(Bo,{size:16}),p?"Running":"Run"]})]})}),vN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function iw(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function $h(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function xN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function yN(n){switch(n){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function bN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Za(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Pd(n){const a=Za(n);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function wN(n){const a=Za(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function SN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function hf(n,a){if(a.error)return a.error;const r=bN(a.data),l=SN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=Pd(r.freeMemoryBytes),m=Pd(r.totalMemoryBytes),p=Za(r.totalMemoryBytes)&&Za(r.freeMemoryBytes)!==null?`${Math.round(Za(r.freeMemoryBytes)/Za(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof r.root=="string"?r.root:"",d=Pd(r.freeBytes),m=Za(r.totalBytes)&&Za(r.freeBytes)!==null?`${Math.round(Za(r.freeBytes)/Za(r.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU provider",d=wN(r.usageRatio),m=Za(r.temperatureC)!==null?`${Math.round(Za(r.temperatureC))}°C`:"",p=Pd(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Za(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function vy(n,a){const r=hf(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${r}`)}function CN({state:n,operation:a}){const r=n.status==="completed"?$r:n.status==="failed"||n.status==="cancelled"?Ja:n.status==="running"?qr:tb,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?hf(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return s.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[s.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:s.jsx(r,{size:15})}),s.jsx("strong",{children:n.deviceName}),s.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),s.jsx("small",{children:l})]})}function jN({operation:n,states:a,status:r,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(r),[p,g]=u.useState(!1),[v,b]=u.useState("all"),y=u.useMemo(()=>({total:a.length,completed:a.filter(R=>R.status==="completed").length,failed:a.filter(R=>R.status==="failed").length,running:a.filter(R=>R.status==="running").length,queued:a.filter(R=>R.status==="queued").length,cancelled:a.filter(R=>R.status==="cancelled").length}),[a]),w=a.filter(R=>vy(n,R)),S=w.filter(R=>R.status==="completed").length,j=y.failed>0,N=w.length>0,M=a.filter(R=>v==="issues"?vy(n,R):v==="running"?R.status==="running"||R.status==="queued":v==="completed"?R.status==="completed":v==="failed"?R.status==="failed":!0),k=N&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),E=a.filter(R=>R.status==="completed").map(R=>hf(n,R)).filter(Boolean).filter((R,U,H)=>H.indexOf(R)===U).slice(0,2);return s.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[s.jsxs("div",{className:"agent-task-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"LiveDesk Agent"}),s.jsx("strong",{children:yN(n)})]}),s.jsx("span",{className:`agent-task-status status-${N?"completed-with-failures":r}`,children:k})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[y.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[y.completed," completed"]}),y.running>0&&s.jsxs("span",{className:"summary-running",children:[y.running," running"]}),y.queued>0&&s.jsxs("span",{children:[y.queued," queued"]}),j&&s.jsxs("span",{className:"summary-failed",children:[y.failed," failed"]}),S>0&&s.jsxs("span",{className:"summary-cancelled",children:[S," warning"]}),y.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[y.cancelled," cancelled"]})]}),E.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:E.join(" · "),children:[s.jsx("span",{children:"Result"}),E.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,U)=>{const H=R.status==="completed"?"✓":R.status==="failed"?"×":R.status==="cancelled"?"!":R.status==="running"?"…":"·";return s.jsxs("span",{className:`agent-target-chip status-${R.status}`,title:`${R.deviceName}: ${hf(n,R)}`,"aria-label":`${U+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String(U+1).padStart(2,"0")}),s.jsx("span",{children:H})]},R.deviceId)})}),a.length>0&&s.jsx("div",{className:"agent-task-details-toggle",children:s.jsxs("button",{type:"button",onClick:()=>g(R=>!R),"aria-expanded":p,children:[p?s.jsx(t0,{size:14}):s.jsx(nb,{size:14}),p?"Hide details":"Show details"]})}),p&&s.jsxs("div",{className:"agent-task-details",children:[s.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(R=>s.jsx("button",{className:v===R?"active":"",onClick:()=>b(R),role:"tab","aria-selected":v===R,type:"button",children:R==="all"?"All":R==="issues"?"Issues only":R[0].toUpperCase()+R.slice(1)},R))}),s.jsx("div",{className:"agent-task-rows",children:M.length>0?M.map(R=>s.jsx(CN,{operation:n,state:R},R.deviceId)):s.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&s.jsxs("div",{className:"agent-task-actions",children:[m&&l&&s.jsxs("button",{onClick:l,disabled:d,type:"button",children:[s.jsx(n0,{size:14})," Cancel"]}),!m&&j&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx(Qc,{size:14})," Retry failed"]})]})]})}function kN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function AN({approval:n,busy:a=!1,onApprove:r,onReject:l}){return s.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[s.jsxs("div",{className:"agent-approval-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Approval required"}),s.jsx("strong",{children:n.toolName})]}),s.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),s.jsx("p",{children:n.description}),s.jsx("pre",{children:kN(n.arguments)}),s.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),s.jsxs("div",{className:"agent-approval-actions",children:[s.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[s.jsx(Ja,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx($r,{size:14})," Once"]}),s.jsx("button",{disabled:a,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),s.jsx("button",{disabled:a,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),s.jsxs("div",{className:"agent-approval-scope",children:[s.jsx(gf,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function NN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function MN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:g}){const v=u.useRef(null),b=u.useRef(!0),y=u.useRef(""),w=n[n.length-1];return u.useLayoutEffect(()=>{const S=v.current;S&&(w?.type==="user"&&w.id!==y.current&&(b.current=!0),y.current=w?.id||"",b.current&&(S.scrollTop=S.scrollHeight))},[c,n,w?.id,w?.type,g?.message,g?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:v,onScroll:S=>{const j=S.currentTarget;b.current=j.scrollHeight-j.scrollTop-j.clientHeight<72},children:[c.filter(S=>S.status==="pending").map(S=>s.jsx(AN,{approval:S,busy:p===S.approvalId,onApprove:j=>d(S,j),onReject:()=>m(S)},S.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:"Ask LiveDesk to work across your machines."}),s.jsx("span",{children:"Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."})]}),n.map(S=>{if(S.type==="task"){const j=S;return s.jsx(jN,{operation:j.operation,states:j.states,status:j.status,onCancel:()=>a(j.batchId,j.agentRunId),onRetry:()=>r(j.batchId),busy:l===j.batchId},j.id)}return s.jsxs("article",{className:`agents-message ${S.type}`,children:[s.jsx("span",{children:S.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:S.text})]},S.id)}),g&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(qr,{"aria-hidden":"true",size:15}),NN(g.stage)]}),s.jsx("p",{children:g.message})]})]})}const xy=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],yn=["windows","macos","linux"],Fr={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:yn},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:yn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:yn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:yn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:yn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:yn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:yn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:yn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:yn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:yn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:yn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:yn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:yn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:yn}};new Set(Object.keys(Fr));const TN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"AI workloads":["ai","gpu","comfyui","ollama","인공지능","모델"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},yy=["low","medium","high","critical"];function EN(n){return n.reduce((a,r)=>{const l=Fr[r].risk;return yy.indexOf(l)>yy.indexOf(a)?l:a},"low")}function RN(n){return yn.filter(a=>n.every(r=>Fr[r].supportedPlatforms.includes(a)))}function Pe(n,a,r,l,c,d,m={}){const p=m.description||l,g=c.flatMap(b=>b.split(".")),v=[...new Set([...TN[a],...d,...g])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||EN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||RN(c),keywords:v,recommended:m.recommended??!1,enabled:!0}}const rw=[Pe("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target workstations.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Pe("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),Pe("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),Pe("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),Pe("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),Pe("recommended-ai-workers","Recommended","Verify ComfyUI and Ollama workers","Check whether ComfyUI and Ollama workers and their services are available on the current targets.",["process.list","service.status"],["comfyui","ollama","worker"],{recommended:!0}),Pe("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target workstation.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Pe("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),Pe("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),Pe("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Pe("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Pe("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),Pe("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),Pe("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Pe("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),Pe("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),Pe("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),Pe("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),Pe("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target workstation after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Pe("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),Pe("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target workstation with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Pe("process-close-app","Processes & services","Close an application","Close application [application] on the target workstation and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Pe("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),Pe("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),Pe("ai-comfyui-status","AI workloads","Check ComfyUI availability","Check the ComfyUI process, service state, and GPU readiness on the current targets.",["process.list","service.status","gpu.status"],["comfyui","stable diffusion","image generation"]),Pe("ai-start-comfyui","AI workloads","Start ComfyUI","If ComfyUI is stopped, launch its registered application or service and verify it is running.",["process.list","application.launch","service.status"],["comfyui","start","launch"],{targetSupport:"single"}),Pe("ai-restart-ollama","AI workloads","Restart Ollama","Check Ollama, restart its registered application or service, and verify the worker is ready.",["process.list","application.close","application.launch","service.status"],["ollama","restart","llm"],{targetSupport:"single"}),Pe("ai-stable-diffusion","AI workloads","Check Stable Diffusion workers","Check Stable Diffusion or Automatic1111 processes and their GPU usage on the current targets.",["process.list","gpu.status"],["stable diffusion","automatic1111","sd"]),Pe("ai-gpu-readiness","AI workloads","Check GPU readiness for AI","Check GPU temperature, VRAM, utilization, and system health before an AI workload starts.",["gpu.status","system.health"],["readiness","inference","training"]),Pe("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target workstation.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Pe("ai-llama-cpp","AI workloads","Check llama.cpp workers","Find llama.cpp or local model worker processes and inspect their recent logs.",["process.list","logs.collect"],["llama.cpp","local model","inference"]),Pe("ai-recover-orphan-python","AI workloads","Recover an orphaned Python worker","Find an orphaned Python AI worker, stop the stale process, then launch its registered worker again.",["process.list","process.control","application.launch"],["python","orphaned","recovery"],{targetSupport:"single"}),Pe("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target workstation.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Pe("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target workstation.",["file.read"],["config","settings","read","구성"]),Pe("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),Pe("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),Pe("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),Pe("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target workstation and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Pe("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target workstation and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Pe("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target workstation.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Pe("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target workstation, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Pe("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target workstation, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Pe("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target workstation, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Pe("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target workstation and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Pe("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target workstation and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Pe("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target workstation and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Pe("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),Pe("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target workstation.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Pe("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Pe("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Pe("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Pe("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),Pe("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),Pe("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),Pe("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Pe("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),Pe("power-lock","Power & maintenance","Lock the workstation","Lock the target workstation and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Pe("power-logoff","Power & maintenance","Log off the workstation","Log off the target workstation after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Pe("power-sleep","Power & maintenance","Put the workstation to sleep","Put the target workstation to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Pe("power-restart","Power & maintenance","Restart the workstation","Restart the target workstation after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Pe("power-shutdown","Power & maintenance","Shut down the workstation","Shut down the target workstation after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Pe("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target workstation, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Pe("power-timezone","Power & maintenance","Set the workstation timezone","Set the target workstation timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Pe("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target workstation and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Pe("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),Pe("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),Pe("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),Pe("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),Pe("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),Pe("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),Pe("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target workstation.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Pe("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],uh={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function DN(n,a){return n==="safe-auto"?uh:n==="full-access"?{...uh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...uh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function LN(n,a,r){const l=DN(a,r),c=n.requiredOperations.map(d=>l[Fr[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[Fr[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Fr[d].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a workstation."}:n.requiredOperations.every(d=>Fr[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function _N(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function zN(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||l.has(c.deviceId)))}function IN(n,a){const r=_N(n.platform);if(!r||!a.supportedPlatforms.includes(r))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>Fr[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function lw(n,a,r,l,c,d){const m=LN(n,c,d),p=zN(a,r,l),g=p.map(S=>S.deviceId),v={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...v,reason:"Select at least one connected workstation."};if(n.targetSupport==="single"&&p.length!==1)return{...v,reason:"This task supports one workstation at a time."};if(m.state==="blocked")return v;const b=p.filter(S=>IN(S,n)),y=b.map(S=>S.deviceId),w=g.filter(S=>!y.includes(S));return b.length===0?{...v,unsupportedDeviceIds:w,reason:"No current target supports the required platform and client capabilities."}:{...v,available:!0,availableDeviceIds:y,unsupportedDeviceIds:w}}function ON(n,a,r,l,c,d){return n.filter(m=>m.enabled&&lw(m,a,r,l,c,d).available).length}const dh="livedesk.agentPromptRecent",fh="livedesk.agentPromptFavorites",HN={Recommended:Ol,"Health & capacity":cn,"Processes & services":l0,"AI workloads":Qy,"Files & configuration":r0,"Software & automation":sf,"Network & connectivity":ep,"Power & maintenance":Lt,"Troubleshooting & recovery":i0};function by(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(r=>typeof r=="string"):[]}catch{return[]}}function $d(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function mh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function BN(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","AI workloads":"AI","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[n]}function FN(n,a,r){if(!r.trim())return!0;const l=r.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function PN(n){return`permission-${n}`}function $N(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function UN(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function qN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,g]=u.useState(""),[v,b]=u.useState("all"),[y,w]=u.useState(()=>by(dh)),[S,j]=u.useState(()=>by(fh)),[N,M]=u.useState(0),[k,E]=u.useState(""),R=u.useRef(null),U=u.useRef(null),H=u.useMemo(()=>rw.filter(V=>V.enabled),[]),W=u.useMemo(()=>new Map(H.map(V=>[V.id,lw(V,n,a,r,l,c)])),[c,n,l,r,a,H]),_=u.useMemo(()=>[...W.values()].filter(V=>V.available).length,[W]),L=u.useMemo(()=>n.filter(V=>V.connected&&(a==="all"||r.includes(V.deviceId))).length,[n,r,a]),le=u.useMemo(()=>{const V=H.filter(O=>FN(O,W.get(O.id),p));return v==="recent"?y.map(O=>V.find(Y=>Y.id===O)).filter(O=>!!O):v==="favorites"?S.map(O=>V.find(Y=>Y.id===O)).filter(O=>!!O):v==="all"?V:V.filter(O=>{const Y=W.get(O.id);return v==="read-only"?Y.state==="read-only":v==="auto"?Y.state==="auto":v==="approval"?Y.state==="approval":v==="full-access"?Y.state==="full-access":v==="available"?Y.available:v==="unavailable"?!Y.available:O.category===v})},[W,S,v,y,p,H]),q=u.useMemo(()=>v!=="all"?[{category:mh(v),templates:le}]:xy.map(V=>({category:V,templates:le.filter(O=>O.category===V)})).filter(V=>V.templates.length>0),[v,le]);u.useEffect(()=>{M(V=>Math.min(V,Math.max(0,le.length-1)))},[le.length]),u.useEffect(()=>{$d(dh,y)},[y]),u.useEffect(()=>{$d(fh,S)},[S]),u.useEffect(()=>{U.current?.focus();const V=Y=>{Y.target instanceof Node&&!R.current?.contains(Y.target)&&m()},O=Y=>{Y.key==="Escape"&&(Y.preventDefault(),m())};return document.addEventListener("pointerdown",V),document.addEventListener("keydown",O),()=>{document.removeEventListener("pointerdown",V),document.removeEventListener("keydown",O)}},[m]);const te=V=>{const O=W.get(V.id);if(!O.available){E(O.reason||"This task is not available for the current targets and permission policy.");return}const Y=[V.id,...y.filter(X=>X!==V.id)].slice(0,10);w(Y),$d(dh,Y),d(V.prompt),m()},K=V=>{j(O=>{const Y=O.includes(V)?O.filter(X=>X!==V):[V,...O];return $d(fh,Y),Y})},ne=V=>{V.key==="ArrowDown"?(V.preventDefault(),M(O=>Math.min(O+1,Math.max(0,le.length-1)))):V.key==="ArrowUp"?(V.preventDefault(),M(O=>Math.max(O-1,0))):V.key==="Enter"&&le[N]&&(V.preventDefault(),te(le[N]))};let ce=-1;return s.jsxs("section",{className:"agents-suggested-tasks",ref:R,"aria-label":"Suggested tasks",children:[s.jsxs("header",{className:"agents-suggested-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"agents-suggested-title",children:[s.jsx(Ol,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[_," available · ",H.length," total. Choose a task, edit it, then run it."]})]}),s.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:s.jsx(Ja,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(a0,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:U,value:p,onChange:V=>g(V.target.value),onKeyDown:ne,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),s.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...xy].map(V=>{const O=V==="recent"?Ky:V==="favorites"?kh:V==="all"?Ol:V==="available"?Hn:V==="unavailable"?s0:V==="read-only"||V==="auto"||V==="approval"||V==="full-access"?Lt:HN[V];return s.jsxs("button",{className:v===V?"active":"",type:"button",title:mh(V),"aria-label":mh(V),"aria-pressed":v===V,onClick:()=>{b(V),M(0),E("")},children:[s.jsx(O,{size:12})," ",BN(V)]},V)})}),k&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:k}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[q.map(V=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:V.category}),V.templates.map(O=>{ce+=1;const Y=ce===N,X=S.includes(O.id),P=W.get(O.id),oe=P.availableDeviceIds.length+P.unsupportedDeviceIds.length||L,we=P.available?`Available on ${P.availableDeviceIds.length} of ${oe} target${oe===1?"":"s"}`:`Unavailable: ${P.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${Y?"active":""} ${P.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":Y,"aria-disabled":!P.available,onClick:()=>te(O),children:[s.jsx("span",{children:O.title}),s.jsx("small",{className:"agents-suggested-description",children:O.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:O.category}),s.jsx("em",{className:PN(P.state),children:P.label}),s.jsx("em",{className:`risk-${O.risk}`,children:$N(O.risk)}),s.jsx("em",{children:O.supportedPlatforms.map(UN).join(" · ")}),s.jsx("em",{className:P.available?"availability-ok":"availability-unavailable",children:we}),P.available&&P.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",P.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${X?"favorite":""}`,type:"button","aria-label":X?`Remove ${O.title} from favorites`:`Add ${O.title} to favorites`,"aria-pressed":X,onClick:()=>K(O.id),children:s.jsx(kh,{size:14,fill:X?"currentColor":"none"})})]},O.id)})]},V.category)),le.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function GN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter($h),g=r.filter(v=>p.some(b=>b.deviceId===v)).length;return s.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[s.jsxs("div",{className:"agents-target-toolbar",children:[s.jsx("span",{className:"agents-section-label",children:"Targets"}),s.jsxs("div",{className:"agents-target-modes",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx(eb,{size:14})," All connected ",s.jsx("small",{children:p.length})]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx($r,{size:14})," Selected ",g]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(gf,{size:14}),s.jsx("span",{children:"Permission"}),s.jsxs("select",{value:d,onChange:v=>m(v.target.value),"aria-label":"Agent permission mode",children:[s.jsx("option",{value:"ask",children:"Ask"}),s.jsx("option",{value:"safe-auto",children:"Safe Auto"}),s.jsx("option",{value:"full-access",children:"Full Access"}),s.jsx("option",{value:"custom",children:"Custom"})]}),s.jsx(nb,{size:13,"aria-hidden":"true"})]})]}),s.jsx("div",{className:"agents-target-list",children:n.length===0?s.jsx("span",{className:"agents-target-empty",children:"No workstations discovered."}):n.map(v=>{const b=$h(v),y=a==="all"?b:r.includes(v.deviceId);return s.jsxs("label",{className:`agents-target-option ${y?"selected":""} ${b?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:y,disabled:!b||a==="all",onChange:()=>c(v.deviceId)}),s.jsx("span",{className:"agents-target-icon",children:s.jsx(en,{size:15})}),s.jsxs("span",{children:[s.jsx("strong",{children:iw(v)}),s.jsx("small",{children:b?"Ready":v.connected?"Agent reconnecting":"Offline"})]}),y&&s.jsx($r,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},v.deviceId)})})]})}async function VN(n,a){return Ge("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function WN(n,a){return Ge("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function YN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function KN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function QN(n){return Ge("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function XN(n,a,r,l){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function ZN(n,a,r,l="User rejected this action."){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function JN(n,a,r){return Ge(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function eM(n,a){return Ge("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function tM(n,a){return Ge("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function nM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function aM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function sM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function Nl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function Ud(n,a){const r=new Map(a.map(l=>[l.deviceId,iw(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:xN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function iM(n,a){const r=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=r.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function rM(n,a){const r=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${r.filter(p=>{const g=p.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
15
15
  ${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
16
16
  `)}`:m}return l.length>0?`${r.length}대 완료, ${l.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const lM={read:"allow",processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileRead:"ask",fileWrite:"ask",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"ask",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function oM(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function cM(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function uM(n){const a=n instanceof Error?n.message:String(n);return/agent-ai-disabled/i.test(a)?"Enable AI Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(a)?"The selected workstation is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function dM({hubUrl:n,devices:a,launchRequest:r}){const[l,c]=u.useState("all"),[d,m]=u.useState([]),[p,g]=u.useState(""),[v,b]=u.useState([]),[y,w]=u.useState(""),[S,j]=u.useState(""),[N,M]=u.useState(""),[k,E]=u.useState("safe-auto"),[R]=u.useState("custom-default"),[U,H]=u.useState(lM),[W,_]=u.useState([]),[L,le]=u.useState(""),[q,te]=u.useState(!1),[K,ne]=u.useState(null),[ce,V]=u.useState(!1),[O,Y]=u.useState(""),[X,P]=u.useState(!1),[oe,we]=u.useState(null),J=u.useRef(null),B=u.useRef(new Set),pe=u.useRef(new Set),ge=u.useRef(new Set),xe=u.useMemo(()=>a.filter($h).map(he=>he.deviceId),[a]),Ae=u.useMemo(()=>ON(rw,a,l,d,k,U),[U,a,k,d,l]);u.useEffect(()=>{r?.deviceId&&(c("selected"),m([r.deviceId]),g(r.instruction),P(!1),window.requestAnimationFrame(()=>{J.current?.focus(),J.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const _e=u.useCallback(he=>{const Me=Ud(he,a);if(b(de=>de.map(be=>be.type==="task"&&be.batchId===he.batchId?{...be,states:iM(be.states,Me),status:he.status}:be)),!["running","queued"].includes(he.status)&&!B.current.has(he.batchId)){B.current.add(he.batchId);const de=Nl("agent-summary");b(be=>[...be,{type:"agent",id:de,text:rM(he,Me)}]),he.operation&&eM(n,{instruction:he.instructionPreview,operation:he.operation,total:Me.length,completed:Me.filter(be=>be.status==="completed").length,failed:Me.filter(be=>be.status==="failed").length,results:Me.map(be=>({deviceName:be.deviceName,status:be.status,result:be.result,error:be.error}))}).then(be=>{!be.ok||!be.summary||b(We=>We.map(at=>at.type==="agent"&&at.id===de?{...at,text:be.summary}:at))}).catch(()=>{}),w(be=>be===he.batchId?"":be)}},[a,n]),ie=u.useCallback(async he=>{const Me=await nM(n,he);return _e(Me),Me},[n,_e]),Q=u.useCallback((he,Me)=>{ge.current.has(he.batchId)||(ge.current.add(he.batchId),b(de=>[...de,{type:"task",id:Nl("task"),batchId:he.batchId,agentRunId:Me,operation:he.operation||"diagnostics.collect",instruction:he.instructionPreview,states:Ud(he,a),status:he.status}])),_e(he)},[a,_e]),Ie=u.useCallback(async he=>{const Me=await YN(n,he);for(const be of Me.taskBatches||[])Q(be,he);_(Me.approvals||[]);const de=["running","queued","waiting-approval"].includes(Me.status);if(we(de?{runId:he,stage:Me.stage||Me.status,message:Me.progressMessage||(Me.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:be=>be?.runId===he?null:be),!de&&!pe.current.has(he)){pe.current.add(he);const be=[Me.error,Me.errorMessage].filter(Boolean).join(" — "),We=Me.finalResponse?.trim()||(Me.status==="cancelled"?"Codex 작업을 취소했습니다.":be?`Codex 작업이 완료되지 않았습니다: ${be}`:"Codex 작업이 완료되었습니다.");b(at=>[...at,{type:Me.status==="failed"?"error":"agent",id:Nl("agent-run-result"),text:We}])}return Me},[Q,n]);u.useEffect(()=>{if(!y)return;let he=!0;const Me=async()=>{try{const be=await ie(y);he&&!["running","queued"].includes(be.status)&&w("")}catch(be){he&&Y(be instanceof Error?be.message:String(be))}};Me();const de=window.setInterval(()=>{Me()},800);return()=>{he=!1,window.clearInterval(de)}},[y,ie]),u.useEffect(()=>{if(!S)return;let he=!0;const Me=async()=>{try{const be=await Ie(S);he&&!["running","queued","waiting-approval"].includes(be.status)&&(j(""),V(!1))}catch(be){he&&Y(be instanceof Error?be.message:String(be))}};Me();const de=window.setInterval(()=>{Me()},800);return()=>{he=!1,window.clearInterval(de)}},[S,Ie]);const Oe=async(he="",Me,de=!1)=>{const be=(he||p).trim();if(!be||y||S)return;let We=null;const at=Me||(l==="all"?xe:d.filter(Xe=>xe.includes(Xe)));if(at.length===0){Y("Select at least one connected workstation.");return}if(k==="full-access"&&!ce&&!de){ne({instruction:be,targetIds:at});return}if(b(Xe=>[...Xe,{type:"user",id:Nl("user"),text:be}]),g(""),P(!1),Y(""),at.length===0){b(Xe=>[...Xe,{type:"error",id:Nl("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}if(!We){try{if(k==="custom"){const ht=await JN(n,R,U);if(!ht.ok)throw new Error(ht.error||"Custom Agent policy could not be saved.")}const Xe=await WN(n,{instruction:be,deviceIds:at,permissionMode:k,customPolicyId:R});if(!Xe.ok||!Xe.runId)throw new Error(Xe.error||"Codex Agent run could not be started.");_(Xe.approvals||[]),we({runId:Xe.runId,stage:Xe.stage||Xe.status||"queued",message:Xe.progressMessage||"Codex request queued on the Hub."}),j(Xe.runId);return}catch(Xe){try{const ht=await VN(n,be);ht.ok&&ht.plan&&(We={operation:ht.plan.operation,query:ht.plan.targetQuery})}catch{b(ht=>[...ht,{type:"error",id:Nl("unsupported"),text:uM(Xe)}])}}if(!We)return}try{const Xe=await tM(n,{instruction:be,deviceIds:at,operation:We.operation,targetQuery:We.query});if(!Xe.ok||!Xe.batch||!Xe.batchId)throw new Error(Xe.error||"작업을 만들지 못했습니다.");const ht={type:"task",id:Nl("task"),batchId:Xe.batchId,operation:We.operation,instruction:be,states:Ud(Xe.batch,a),status:Xe.batch.status};ge.current.add(Xe.batchId),b(St=>[...St,ht]),w(Xe.batchId)}catch(Xe){Y(Xe instanceof Error?Xe.message:String(Xe))}},ae=async(he,Me)=>{le(he.approvalId);try{const de=await XN(n,he.runId,he.approvalId,Me);if(!de.ok)throw new Error(de.error||"Agent approval could not be applied.");await Ie(he.runId)}catch(de){Y(de instanceof Error?de.message:String(de))}finally{le("")}},ke=async he=>{le(he.approvalId);try{const Me=await ZN(n,he.runId,he.approvalId);if(!Me.ok)throw new Error(Me.error||"Agent approval could not be rejected.");await Ie(he.runId)}catch(Me){Y(Me instanceof Error?Me.message:String(Me))}finally{le("")}},je=async(he,Me)=>{M(he);try{if(Me){const be=await KN(n,Me);for(const We of be.taskBatches||[])_e(We);j(We=>We===Me?"":We),we(We=>We?.runId===Me?null:We);return}const de=await aM(n,he);_e(de),w(be=>be===he?"":be)}catch(de){Y(de instanceof Error?de.message:String(de))}finally{M("")}},De=async()=>{if(!(q||!y&&!S)){te(!0);try{const he=await QN(n);if(!he.ok)throw new Error(he.error||"모든 Agent 작업을 취소하지 못했습니다.");w(""),j(""),we(null),_([]),b(Me=>Me.map(de=>de.type==="task"&&["queued","running"].includes(de.status)?{...de,status:"cancelled",states:de.states.map(be=>["queued","running"].includes(be.status)?{...be,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:be)}:de))}catch(he){Y(he instanceof Error?he.message:String(he))}finally{te(!1)}}},Le=async he=>{M(he);try{const Me=await sM(n,he);if(!Me.ok||!Me.batch||!Me.batchId)throw new Error(Me.error||"재시도하지 못했습니다.");B.current.delete(Me.batchId),b(de=>de.map(be=>be.type==="task"&&be.batchId===he?{...be,batchId:Me.batchId,states:Ud(Me.batch,a),status:Me.batch.status}:be)),w(Me.batchId)}catch(Me){Y(Me instanceof Error?Me.message:String(Me))}finally{M("")}},$e=he=>{g(he),P(!1),window.requestAnimationFrame(()=>J.current?.focus())};return s.jsxs("section",{className:"agents-page",children:[s.jsxs("div",{className:"agents-workspace",children:[(y||S)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[xe.length," workstations · ",oM(k)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{De()},disabled:q,children:q?"Stopping…":"Stop all"})]}),K&&s.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:s.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[s.jsx("span",{className:"agents-permission-modal-icon",children:s.jsx(gf,{size:20})}),s.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),s.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected workstations. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),s.jsxs("div",{className:"agents-permission-modal-actions",children:[s.jsx("button",{type:"button",onClick:()=>ne(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const he=K;ne(null),V(!0),Oe(he.instruction,he.targetIds,!0)},children:"Run with Full Access"})]})]})}),O&&s.jsx("div",{className:"agents-error",role:"alert",children:O}),s.jsx(MN,{items:v,onCancel:je,onRetry:Le,busyBatchId:N,approvals:W,onApprove:ae,onReject:ke,busyApprovalId:L,progress:oe}),s.jsxs("div",{className:"agents-composer-shell",children:[X&&s.jsx(qN,{devices:a,targetMode:l,selectedIds:d,permissionMode:k,customCategories:U,onSelectPrompt:$e,onClose:()=>P(!1)}),s.jsx(gN,{ref:J,value:p,onChange:g,onSubmit:()=>{Oe()},onOpenSuggestedTasks:()=>P(he=>!he),suggestedOpen:X,suggestedTaskCount:Ae,disabled:!!y||!!S})]})]}),s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(GN,{devices:a,mode:l,selectedIds:d,onModeChange:c,onToggle:he=>m(Me=>Me.includes(he)?Me.filter(de=>de!==he):[...Me,he]),permissionMode:k,onPermissionModeChange:he=>{E(he),he!=="full-access"&&V(!1)}}),k==="custom"&&s.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[s.jsxs("div",{className:"agents-custom-policy-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"agents-section-label",children:"Custom policy"}),s.jsx("strong",{children:"Choose what Codex may do automatically."})]}),s.jsx("span",{children:"Denied actions never reach a device."})]}),s.jsx("div",{className:"agents-custom-policy-grid",children:vN.map(he=>s.jsxs("label",{children:[s.jsx("span",{children:cM(he)}),s.jsxs("select",{value:U[he],onChange:Me=>H(de=>({...de,[he]:Me.target.value})),children:[s.jsx("option",{value:"allow",children:"Allow automatically"}),s.jsx("option",{value:"ask",children:"Ask every time"}),s.jsx("option",{value:"deny",children:"Deny"})]})]},he))})]})]})]})}function ow(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function cw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function uw(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:ow(a.target)})),c=await fetch(`${Wr(r)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":n.type||"application/octet-stream"},body:n,cache:"no-store"});if(!c.ok)throw new Error(await cw(c));return await c.json()}async function fM(n,a){return await Ge("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:ow(n.target)})},a)}async function mM(n,a,r,l){const c=await fetch(`${Wr(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await cw(c));return await c.json()}async function hM(n,a,r){return await Ge(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function wy(n,a){await Ge(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function pM(n){return await Ge("/api/captures",void 0,n)}function Sy(n,a){return`${Wr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function gM(n,a){return await Ge(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function vM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await pM(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async g=>{const v=Sy(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:v});return}catch{}window.open(v,"_blank","noopener,noreferrer")};return s.jsxs("section",{className:"capture-gallery",children:[s.jsxs("header",{children:[s.jsxs("div",{children:[s.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),s.jsx("h2",{children:"Saved captures"})]}),s.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[s.jsx(Ho,{size:15})," Refresh"]})]}),c?s.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?s.jsx("p",{className:"settings-help",children:"No captures saved yet."}):s.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const v=Sy(g.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?s.jsx("img",{src:v,alt:g.target.label}):s.jsx("video",{src:v,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:g.fileName}),s.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(v,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(o0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${v}?download=1`,download:g.fileName,children:s.jsx(Xh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(g)},type:"button",children:s.jsx(c0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&gM(g.id,n).then(()=>m()).catch(b=>a(b instanceof Error?b.message:String(b)))},type:"button",children:s.jsx(Zh,{size:15})})]})]})]},g.id)})})]})}function qd(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),r=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return r>0?`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function Cy({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async y=>{try{await y()}catch(w){l?.(w instanceof Error?w.message:String(w))}},g=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
17
- Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},v=c.recording?`Stop recording · ${qd(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,b=c.timelapse?`Stop timelapse · ${qd(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return s.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[s.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{p(n.takeScreenshot)},type:"button",children:s.jsx(u0,{size:17})}),s.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":v,title:v,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?s.jsxs(s.Fragment,{children:[s.jsx(lx,{size:14,fill:"currentColor"}),s.jsx("span",{children:qd(c.recordingStartedAt)})]}):s.jsx(tb,{size:18})}),s.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void p(n.saveLast30Seconds):void g(),type:"button",children:[s.jsx(d0,{size:17}),s.jsx("small",{children:"30s"})]}),s.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":b,title:b,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?s.jsxs(s.Fragment,{children:[s.jsx(lx,{size:14,fill:"currentColor"}),s.jsx("span",{children:qd(c.timelapseStartedAt)})]}):s.jsx(f0,{size:17})})]})}async function xM(n,a={}){const r=n.filter(y=>y.canvas&&y.canvas.width>0&&y.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,r.length)/d)),p=Math.floor(l/d),g=Math.floor(c/m),v=document.createElement("canvas");v.width=Math.max(320,p*d),v.height=Math.max(180,g*m);const b=v.getContext("2d",{alpha:!1});if(!b)return v;b.fillStyle="#0b1220",b.fillRect(0,0,v.width,v.height),b.font="600 14px system-ui, sans-serif",b.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const w=r[y],S=y%d,j=Math.floor(y/d),N=S*p,M=j*g,k=w.canvas,E=Math.min(p/k.width,g/k.height),R=Math.max(1,Math.floor(k.width*E)),U=Math.max(1,Math.floor(k.height*E)),H=N+Math.floor((p-R)/2),W=M+Math.floor((g-U)/2);b.drawImage(k,H,W,R,U),a.includeLabels!==!1&&(b.fillStyle="rgba(4, 10, 20, .74)",b.fillRect(N,M+g-28,p,28),b.fillStyle="#f8fafc",b.fillText(w.label,N+9,M+g-9))}return v}function yM(n){return n?.signature||"none"}function bM(n){return n?.label||"No capture target"}function jy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function wM(){const n=new Date,a=r=>String(r).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function SM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function CM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${SM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${wM()}.png`}async function jM(n,a,r){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await uw(l,{kind:"screenshot",fileName:CM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function dw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function kM(n,a){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${r}.webm`:`LiveDesk_Recording_${l}_${r}.webm`}async function fw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=dw();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await fM({kind:r,fileName:kM(r,n.target),mimeType:a,target:n.target},n.hubUrl),c=n.canvas.captureStream(n.frameRequests?0:n.fps),d=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),m=performance.now();let p=0,g=!1,v=null,b=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const w=p++;b=b.then(()=>mM(l.sessionId,w,y.data,n.hubUrl).then(()=>{})).catch(S=>{v=v||(S instanceof Error?S:new Error(String(S))),n.onError?.(v)})},d.onerror=()=>{v=new Error("Video recording stopped unexpectedly."),n.onError?.(v)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await b,v)throw await wy(l.sessionId,n.hubUrl).catch(()=>{}),v;await hM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await wy(l.sessionId,n.hubUrl).catch(()=>{}))}}}class AM{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=dw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const d=performance.now();for(this.segments.push({blob:c.data,at:d}),this.totalBytes+=c.data.size;this.segments.length>1&&(d-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const m=this.segments.shift();this.totalBytes-=m.blob.size}},this.recorder.start(1e3)}stop(){const a=this.recorder;this.recorder=null,a&&a.state!=="inactive"&&(a.ondataavailable=null,a.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),d=`LiveDesk_Last30s_${a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await uw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function NM(n,a,r,l,c){const d=await fw({canvas:n,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});d.requestFrame?.();const m=window.setInterval(()=>d.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const mw="livedesk.captureSettings";function MM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(mw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function TM(n){const[a,r]=u.useState(MM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,g]=u.useState(0),[v,b]=u.useState(!1),y=u.useRef(void 0),w=u.useRef(!1),S=u.useRef(""),j=u.useRef(null),N=u.useRef(null),M=u.useRef(null),k=u.useRef(null),E=u.useRef(new AM),R=n.sourceRegistry.resolveCurrentTarget(),U=yM(R),H=bM(R),W=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(mw,JSON.stringify(a)),!w.current)return;const X=JSON.stringify(a);X!==S.current&&(S.current=X,Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:y.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(P=>{y.current=Number(P.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let X=!0;return Ge("/api/settings",void 0,n.hubUrl).then(P=>{if(!X)return;const oe=P.settings?.filesAudio||{},we=typeof oe.rollingBufferEnabled=="boolean"?oe.rollingBufferEnabled:a.rollingEnabled,J=oe.recordingQuality==="high"?"high":"standard",B=[5,10,30,60].includes(Number(oe.timelapseIntervalSeconds))?Number(oe.timelapseIntervalSeconds):a.timelapseIntervalSeconds,pe=typeof oe.includeRemoteCursor=="boolean"?oe.includeRemoteCursor:a.includeRemoteCursor,ge={rollingEnabled:we,recordingQuality:J,timelapseIntervalSeconds:B,includeRemoteCursor:pe};y.current=Number(P.revision||0),S.current=JSON.stringify(ge),w.current=!0,r(ge)}).catch(()=>{w.current=!0}),()=>{X=!1}},[n.hubUrl]);const _=u.useCallback(async X=>{if(X.sourceCanvas&&X.sourceCanvas.width>0&&X.sourceCanvas.height>0)return{target:jy(X),canvas:X.sourceCanvas,cleanup:()=>{}};const P=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let oe=!1;const we=window.setInterval(async()=>{if(oe)return;const J=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!J||oe||((P.width!==J.width||P.height!==J.height)&&(P.width=J.width,P.height=J.height),P.getContext("2d")?.drawImage(J,0,0))},100);return{target:jy(X),canvas:P,cleanup:()=>{oe=!0,window.clearInterval(we)}}},[n.sourceRegistry]);u.useEffect(()=>{const X=E.current;if(!a.rollingEnabled||!R||!W){X.stop(),g(0);return}let P=!1,oe=null;return(async()=>{try{if(oe=await _(R),P)return;await X.start(oe.canvas,oe.target);const J=window.setInterval(()=>g(Math.round(X.seconds)),500),B=()=>{window.clearInterval(J),oe?.cleanup()};X.__cleanup=B}catch(J){P||n.onToast(J instanceof Error?J.message:String(J))}})(),()=>{P=!0,X.stop(),X.__cleanup?.(),X.__cleanup=void 0,g(0)}},[_,n.onToast,a.rollingEnabled,U,W]);const L=u.useCallback(X=>r(P=>({...P,rollingEnabled:X})),[]),le=u.useCallback(X=>r(P=>({...P,recordingQuality:X})),[]),q=u.useCallback(X=>r(P=>({...P,timelapseIntervalSeconds:X})),[]),te=u.useCallback(async()=>{const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");b(!0);let P=null;try{P=await _(X),await jM(P.canvas,P.target,n.hubUrl),n.onToast("Screenshot saved")}finally{P?.cleanup(),b(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(M.current)throw new Error("Stop the timelapse before recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(X),oe=await fw({canvas:P.canvas,target:P.target,fps:X.type==="control"?30:15,hubUrl:n.hubUrl,onError:we=>n.onToast(we.message)});N.current=P.cleanup,j.current=oe,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ne=u.useCallback(async()=>{const X=j.current;if(X){b(!0);try{await X.stop(),n.onToast("Recording saved")}finally{j.current=null,N.current?.(),N.current=null,c(0),b(!1)}}},[n.onToast]),ce=u.useCallback(async()=>{if(j.current||M.current)throw new Error("Last 30s is unavailable during a recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");b(!0);try{await E.current.save(X,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{b(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),V=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(X),oe=await NM(P.canvas,P.target,a.timelapseIntervalSeconds,n.hubUrl,we=>n.onToast(we.message));k.current=P.cleanup,M.current=oe,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),O=u.useCallback(async()=>{const X=M.current;if(X){b(!0);try{await X.stop(),n.onToast("Timelapse saved")}finally{M.current=null,k.current?.(),k.current=null,m(0),b(!1)}}},[n.onToast]);return u.useEffect(()=>{const X=P=>{!j.current&&!M.current||(P.preventDefault(),P.returnValue="")};return window.addEventListener("beforeunload",X),()=>window.removeEventListener("beforeunload",X)},[]),u.useEffect(()=>()=>{E.current.stop(),j.current?.cancel(),M.current?.cancel(),N.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!M.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:v,targetLabel:H}),[p,v,l,a.rollingEnabled,H,d]),settings:a,videoSupported:W,targetKey:U,setRollingEnabled:L,setRecordingQuality:le,setTimelapseInterval:q,takeScreenshot:te,startRecording:K,stopRecording:ne,saveLast30Seconds:ce,startTimelapse:V,stopTimelapse:O}}const EM=120,RM=999,Vc=5,Wc=30,DM=Number.POSITIVE_INFINITY,hw="livedesk.remoteDirectory",Uh="livedesk.localHubAccessEnabled",pw="livedesk.streamSettings",qh=16,gw="livedesk.controlStreamSettings",Gh=6,vw="livedesk.wallMonitorSelections",xw=1,hh=512*1024,Vh="".trim(),yw="".trim(),ky="livedesk-adsense-script",ph=!!Vh&&!!yw,LM=1e3/60,gh=1500,_M=650,zM=1800,IM=650,OM=2500,Ay=1500,Ny=15e3,HM=6e4,My=240,BM=1024,FM=480,PM=270,Ty="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Gd="LiveDesk is replacing the Hub and verifying the requested version.",Vd=5*6e4,$M=5e3;function UM(n,a){if(a.deviceId!==n.deviceId)return!1;const r=Number(a.browserReceivedEpochMs);if(!Number.isFinite(r)||r<n.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==n.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===n.frameMode}const Ml={free:{name:"Free",price:"$0",limit:Vc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Wc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:DM,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},bw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ey(n,a){const r=m=>{const g=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const v=g[4]?g[4].split(".").map(b=>/^\d+$/.test(b)?b.length>1&&b.startsWith("0")?Number.NaN:Number(b):b):[];return v.some(b=>typeof b=="number"&&!Number.isFinite(b))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:v}},l=r(n),c=r(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const p=l.prerelease[m],g=c.prerelease[m];if(p===void 0||g===void 0)return g===void 0;if(p!==g){if(typeof p=="number"&&typeof g=="number")return p>g;if(typeof p=="number")return!1;if(typeof g=="number"||p>g)return!0;if(p<g)return!1}}return!0}function zs(n,a){return`${n}:${a}`}const pa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:bw["mode3-h264-hw"],maxWidth:1920,maxHeight:1080,atlasTileWidth:320,atlasTileHeight:180,atlasTileSizeMode:"auto",quality:75,autoStartLive:!0,showScreenStatus:!0,visibleOnlyLive:!0,adaptiveLoadShedding:!0,adaptiveSizeByWall:!0},La={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function ef(n,a){if(n.length===0)return 0;const r=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*a)-1));return r[l]}function Sp(n,a){n.push(a),n.length>My&&n.splice(0,n.length-My)}function Ry(n,a){n.sampleFrames=0,n.sampleStartedAt=a,n.intervalCount=0,n.intervalSumMs=0,n.minIntervalMs=Number.POSITIVE_INFINITY,n.maxIntervalMs=0,n.intervalSamplesMs.length=0,n.seqGapCount=0,n.maxSeqGap=0}function Dy(n,a,r){if(n.lastAt!==void 0){const l=Math.max(0,a-n.lastAt);n.intervalCount+=1,n.intervalSumMs+=l,n.minIntervalMs=Math.min(n.minIntervalMs,l),n.maxIntervalMs=Math.max(n.maxIntervalMs,l),Sp(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=r-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=r}function Ly(n){return!n||n.intervalCount<=0?"waiting":`${Math.round(n.averageIntervalMs)}ms avg / p95 ${Math.round(n.p95IntervalMs)}ms / max ${Math.round(n.maxIntervalMs)}ms`}function qM(){const[n,a]=u.useState({framesPerSecond:0,averageIntervalMs:0,p95IntervalMs:0,maxIntervalMs:0,longTaskCount:0,longTaskMs:0});return u.useEffect(()=>{let r=0,l=performance.now(),c=0,d=0,m=[],p=0,g=0,v=null;const b=w=>{document.visibilityState==="visible"?(c+=1,d>0&&Sp(m,Math.max(0,w-d)),d=w):d=0,r=window.requestAnimationFrame(b)};try{v=new PerformanceObserver(w=>{for(const S of w.getEntries())p+=1,g+=S.duration}),v.observe({entryTypes:["longtask"]})}catch{v=null}r=window.requestAnimationFrame(b);const y=window.setInterval(()=>{const w=performance.now(),S=Math.max(1,w-l),j=m.reduce((N,M)=>N+M,0);a({framesPerSecond:c*1e3/S,averageIntervalMs:m.length>0?j/m.length:0,p95IntervalMs:ef(m,.95),maxIntervalMs:m.length>0?Math.max(...m):0,longTaskCount:p,longTaskMs:g}),l=w,c=0,m=[],p=0,g=0},1e3);return()=>{window.cancelAnimationFrame(r),window.clearInterval(y),v?.disconnect()}},[]),n}function _y(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function GM(n){return Number.isFinite(n)?String(n):"30+"}const tf=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Wh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],VM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],nf=[{id:"640x360",label:"Compact",width:640,height:360},{id:"960x540",label:"Standard",width:960,height:540},{id:"1280x720",label:"HD",width:1280,height:720},{id:"1920x1080",label:"Full HD",width:1920,height:1080},{id:"2560x1440",label:"QHD",width:2560,height:1440},{id:"3840x2160",label:"4K",width:3840,height:2160}],vh=nf.filter(n=>n.width>=1280),xh=[{id:"auto",label:"Auto by wall size"},{id:"320x180",label:"Standard 320x180",width:320,height:180},{id:"480x270",label:"Sharp 480x270",width:480,height:270}],Cp=[1,2,5,8,12,20,30],WM=[20,30,60],zy=[45,60,75,90],Iy={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},small:{maxWidth:640,maxHeight:360}},ia={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,small:32},maxWallFramesPerSecond:di.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Oy=2200,YM=8e3,KM=3500,QM=7e3,XM=2,ZM=2600,JM=4200,eT=750,tT=2,Hy=4200;function By(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function tu(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function ha(n){return n.deviceName||n.hostname||n.deviceId}function nT(){return"npx -y --prefer-online livedesk@latest client"}function aT(){return"npx -y --prefer-online livedesk@latest"}function sT(){try{return localStorage.getItem(hw)||""}catch{return""}}function iT(){try{return localStorage.getItem(Uh)==="1"}catch{return!1}}function To(n){try{n?localStorage.setItem(Uh,"1"):localStorage.removeItem(Uh)}catch{}}function xs(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Yh(n){const a=String(n||"").trim();return tf.some(r=>r.id===a)?a:pa.frameMode}function pf(n){const a=String(n||"").trim();return Wh.some(r=>r.id===a)?a:pa.h264DecodeAcceleration}function Kh(n){return n==="mode3-h264-hw"?n:La.frameMode}function ww(n){return bw[n]||12}function Sw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Qh(n,a){return xs(n,1,Sw(a),ww(a))}function Fl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ma(n){const a=Fl(n.status),r=Fl(a.screens),l=Fl(n.capabilities),c=[a.monitorCount,a.screenCount,r.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function Pr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function rT(n){const a=Fl(n.status),l=[Fl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Fl(d));return[]}function Cw(n,a){const r=rT(n),l=r.find(g=>Number(g.index)===a)||r[a]||r[0]||{},c=Pr(l.width),d=Pr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function lT(n){const a=ma(n);return Array.from({length:a},(r,l)=>Cw(n,l))}function oT(n){const a=[n.name||`Display ${n.index+1}`];return n.width>0&&n.height>0&&a.push(`${n.width}x${n.height}`),n.primary&&a.push("Primary"),a.join(" - ")}function jw(n,a){const r=Cw(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Fl(n.status),c=Pr(l.screenWidth||l.width),d=Pr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function kw(n){if(!n)return null;const a=Pr(n.sourceWidth)||Pr(n.width),r=Pr(n.sourceHeight)||Pr(n.height);return a>0&&r>0?{width:a,height:r}:null}function cT(n,a,r){const d=((typeof a?.monitorIndex=="number"?Da(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?kw(a):null)||jw(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Wd=16/9;function Da(n,a){const r=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(n));return Number.isFinite(l)?Math.max(0,Math.min(r-1,l)):0}function uT(){try{const n=localStorage.getItem(vw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==xw||!r||typeof r!="object"||Array.isArray(r))return{};const l={};for(const[c,d]of Object.entries(r)){const m=c.trim(),p=Math.floor(Number(d));!m||!Number.isFinite(p)||(l[m]=Math.max(0,Math.min(63,p)))}return l}catch{return{}}}function dT(n){try{localStorage.setItem(vw,JSON.stringify({version:xw,selections:n}))}catch{}}function fT(){try{const n=JSON.parse(localStorage.getItem(pw)||"{}"),a=Number(n.version);if(![qh,15,14,13,12,11].includes(a))return pa;const r=Yh(n.frameMode),l=xs(n.maxWidth,320,3840,pa.maxWidth),c=xs(n.maxHeight,180,2160,pa.maxHeight);return{frameMode:r,h264DecodeAcceleration:pf(n.h264DecodeAcceleration),fps:a<qh&&r==="mode3-h264-hw"?pa.fps:Qh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:Number(n.atlasTileWidth)>=480?480:320,atlasTileHeight:Number(n.atlasTileHeight)>=270?270:180,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:xs(n.quality,20,95,pa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:pa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:pa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:pa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:pa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:pa.adaptiveSizeByWall}}catch{return pa}}function mT(n){try{localStorage.setItem(pw,JSON.stringify({...n,version:qh}))}catch{}}function hT(){try{const n=JSON.parse(localStorage.getItem(gw)||"{}"),a=Number(n.version);if(![Gh,5,4,3,2,1].includes(a))return La;const r=xs(n.fps,20,60,La.fps),l=a<Gh;return{frameMode:l?La.frameMode:Kh(n.frameMode),h264DecodeAcceleration:l?La.h264DecodeAcceleration:pf(n.h264DecodeAcceleration),fps:l?La.fps:r,maxWidth:xs(n.maxWidth,1280,3840,La.maxWidth),maxHeight:xs(n.maxHeight,720,2160,La.maxHeight),quality:xs(n.quality,20,95,La.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:La.showScreenStatus}}catch{return La}}function pT(n){try{localStorage.setItem(gw,JSON.stringify({...n,version:Gh}))}catch{}}function yh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function bh(n){return[...new Set(n.filter(Boolean))].sort()}function gT(n){return ia.fallbackVisibleCounts[n]||ia.fallbackVisibleCounts.large}function vT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:480,maxHeight:270}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Iy[a]||Iy.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function xT(n,a=ia.minFps){const r=[...Cp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function yT(n,a){return[...Cp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Yc(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;const c=l===0||r>=100?0:1;return`${r.toFixed(c)} ${a[l]}`}function Fy(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,r=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/r))}GB`}function wh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const r=Math.max(0,n-Math.max(0,Number(a||0)));return`${Fy(r)} / ${Fy(n)}`}function bT(n){const a=new Uint8Array(n),r=32768;let l="";for(let c=0;c<a.length;c+=r){const d=a.subarray(c,c+r);l+=String.fromCharCode(...d)}return btoa(l)}function Py(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const r=a.webkitRelativePath||a.name;return{file:a,relativePath:r,fingerprint:`${a.size}:${a.lastModified}`}})}function wT(n){return n===1?"middle":n===2?"right":"left"}function $y(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Uy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=RM?a:0}const ST={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function CT(n,a,r){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(r==="failed")return"Task failed";const l=n==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return n==="critical"?"Issue":"Check";const d=ST[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function jf(n,a){const r=a.split(".");let l=n;for(const c of r){if(l==null)return;if(Array.isArray(l)){const d=Number(c);l=Number.isInteger(d)?l[d]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function ln(n,...a){for(const r of a){const l=jf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function _a(n,...a){for(const r of a){const l=jf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function jT(n,...a){for(const r of a){const l=jf(n,r);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Ki(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Sh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ki((n-Math.max(0,a))/n)}function Eo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function Ch(n){return n===void 0||!Number.isFinite(n)?"":n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}Gb/s`:`${Math.round(n)}Mb/s`}function Tl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function Aw(n){return!Number.isFinite(n)||!n||n<=0?"-":n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`}function Yd(n,a,r){const l=jf(n,`tools.${a}`),c=_a(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=jT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=_a(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=_a(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||d===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(g="offline"),{id:a,label:r,status:g,detail:g==="offline"?"offline":m||(p?`:${p}`:g==="unknown"?"not reported":g)}}function Nw(n){const a=n.status||{},r=ln(a,"cpu.cores","cpuCores","processorCount"),l=ln(a,"loadavg.0","cpu.load1"),c=Ki(ln(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&l!==void 0?l/Math.max(1,r):void 0)),d=ln(a,"memory.totalBytes","totalMem"),m=ln(a,"memory.freeBytes","freeMem"),p=Ki(ln(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Sh(d,m),g=ln(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),v=ln(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),b=Ki(ln(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Sh(g,v),y=ln(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Ki(ln(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),S=_a(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=ln(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),N=ln(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),M=Ki(ln(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Sh(j,N),k=ln(a,"gpu.temperatureC","thermal.gpuC"),E=Ki(ln(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=_a(a,"npu.name","npu.model","accelerators.npu.name"),U=ln(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),H=ln(a,"network.rxMbps","network.receiveMbps","network.downMbps"),W=ln(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=ln(a,"network.latencyMs","network.rttMs"),L=Ki(ln(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),le=_a(a,"network.link","network.interface","network.name"),q=y===void 0?void 0:Ki((y-35)/60),te=_a(a,"workload.role","role","lane")||(tu(n,"aiAssist")?"Agent worker":tu(n,"taskDispatch")?"Task worker":"Local machine"),K=_a(n.latestTask,"status")||_a(a,"workload.status")||"idle",ne=_a(n.latestTask,"title","instructionPreview")||_a(a,"workload.title"),ce=_a(n.latestTask,"resultSummary","error","instructionPreview")||_a(a,"workload.summary"),V=[Yd(a,"ollama","Ollama"),Yd(a,"lmStudio","LM Studio"),Yd(a,"comfyui","ComfyUI"),Yd(a,"stableDiffusion","Stable Diffusion")],O=V.some(J=>J.status!=="unknown"),Y=Date.parse(n.lastSeenAt||n.connectedAt||""),X=Number.isFinite(Y)?Date.now()-Y:0;let P="online";n.connected?X>5*6e4?P="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(w??0)>=.96||(M??0)>=.96||(E??0)>=.96||(p??0)>=.94||(b??0)>=.94||(_??0)>=200||K==="failed"?P="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(w??0)>=.86||(M??0)>=.88||(E??0)>=.86||(p??0)>=.82||(b??0)>=.86||(_??0)>=80?P="warn":(["queued","running","targeted"].includes(K)||V.some(J=>J.status==="busy"))&&(P="busy"):P="offline";const oe=V.filter(J=>J.status==="online"||J.status==="busy").length,we=[{id:"cpu",label:"CPU",value:Eo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Tl(c,.92,.78)},{id:"memory",label:"RAM",value:Eo(p),detail:wh(d,m),ratio:p,state:Tl(p,.92,.78)},{id:"disk",label:"DISK",value:Eo(b),detail:wh(g,v),ratio:b,state:Tl(b,.92,.82)},{id:"gpu",label:"GPU",value:Eo(w),detail:S||(j&&N!==void 0?`${Yc(N)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:w,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":Tl(w,.96,.86)},{id:"vram",label:"VRAM",value:Eo(M),detail:wh(j,N),ratio:M,state:Tl(M,.96,.88)},{id:"npu",label:"NPU",value:E!==void 0?Eo(E):U!==void 0?`${Math.round(U)} TOPS`:"-",detail:R||(U!==void 0?"neural engine":"not reported"),ratio:E,state:Tl(E,.96,.86)},{id:"temp",label:"TEMP",value:y===void 0?"-":`${Math.round(y)}C`,detail:oe>0?`${oe} local tools`:`uptime ${Aw(ln(a,"uptimeSec"))}`,ratio:q,state:y===void 0?"unknown":y>=86?"critical":y>=78?"warn":"good"},{id:"network",label:"NET",value:Ch(H)||(_!==void 0?`${Math.round(_)}ms`:le||"-"),detail:Ch(W)?`${Ch(W)} up`:le||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Tl(L,.9,.75)}];return{state:P,label:CT(P,we,K),role:te,taskLabel:ne||(K==="idle"?"idle":K),taskStatus:K,taskSummary:ce,tools:O?V:V.map(J=>({...J,detail:"not reported"})),metrics:we}}const kT=[{id:"small",label:"Small"},{id:"medium",label:"Medium"},{id:"large",label:"Large"}],AT=[{id:"sync-server",label:"Hub",icon:Ur,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:nu,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Qd,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Kd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Gc,accent:"violet",tooltip:"agents"}],NT=[{id:"doc",label:"Doc",icon:af,accent:"amber"},{id:"support",label:"Support",icon:Kc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function MT(n){return n.replaceAll("npx -y @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk","npx -y --prefer-online livedesk@latest").replaceAll("npx livedesk","npx -y --prefer-online livedesk@latest")}function on(n){return MT(n).replaceAll("Sync Server","Hub").replace(/\bRemoteHub\b/g,"Hub client endpoint").replace(/\bManagers\b/g,"Hubs").replace(/\bManager\b/g,"Hub").replace(/\bmanager\b/g,"Hub").replace(/\bMANAGER\b/g,"HUB").replace(/매니저/g,"Hub")}function El(n){return n.map(a=>on(a))}function aa(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:on(n.title),intro:on(n.intro),sections:[{title:on(n.managerTitle),body:on(n.managerBody),points:El(n.managerPoints)},{title:on(n.clientTitle),body:on(n.clientBody),points:El(n.clientPoints)},{title:on(n.syncTitle),body:on(n.syncBody),points:El(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:on(n.agentTitle),body:on(n.agentBody),points:El(n.agentPoints)}]:[],{title:on(n.platformTitle),body:on(n.platformBody),points:El(n.platformPoints)}],sync:{title:on(n.syncTitle),body:on(n.syncBody),points:El(n.syncPoints)},firewall:{title:on(n.firewallTitle),body:on(n.firewallBody),points:El(n.firewallPoints)},commands:{title:on(n.commandsTitle),body:on(n.commandsBody),manager:on(n.managerCommandLabel),primary:on(n.clientCommandLabel),slot:on(n.slotCommandLabel),manual:on(n.manualCommandLabel)}}}const Oo={ko:aa({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["Wall은 Mode 3 H.264와 Mode 4 H.264 Atlas를 사용합니다. Mode 2는 Mode 4의 내부 Atlas 입력에만 한정되며 Wall/Control fallback으로 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot 캡처, xdotool 입력 백엔드가 추가되었습니다. 오디오는 아직 비활성입니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 LAN 안에서는 보통 공유기 포트포워딩이 필요 없습니다. 다른 장소의 PC를 붙이려면 클라이언트가 매니저의 클라이언트 접속 포트에 도달할 수 있어야 합니다.",firewallPoints:["클라이언트 접속 포트는 TCP 5197입니다.","클라이언트 쪽은 나가는 연결이므로 보통 인바운드 포트 개방이 필요 없습니다.","다른 네트워크에서 붙일 때는 매니저 PC 방화벽에서 TCP 5197 인바운드를 허용하고, 공유기에서는 TCP 5197을 매니저 PC로 전달합니다.","Screen Wall/API 포트 5179는 매니저 UI용입니다. 외부 브라우저에서 Wall을 직접 열 필요가 있을 때만 별도로 노출을 검토합니다.","공개 인터넷에 바로 열기보다 VPN, Tailscale, ZeroTier, 고정 IP allowlist를 우선합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:aa({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many workstations, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a workstation",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-workstation tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected workstations and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Wall uses Mode 3 H.264 and Mode 4 H.264 Atlas. Mode 2 is restricted to internal Mode 4 Atlas input and is never used as a Wall or Control fallback.","Remote audio is available when the selected workstation advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, grim/gnome-screenshot/import/scrot capture, and xdotool input backend. Audio is still disabled."],firewallTitle:"Firewall and remote locations",firewallBody:"On the same LAN, router forwarding is usually unnecessary. For another office, building, or country, clients must be able to reach the manager client port.",firewallPoints:["Client connection port: TCP 5197.","Client machines normally only need outbound access.","For remote networks, allow inbound TCP 5197 on the manager firewall and forward TCP 5197 from the router to the manager PC.","Screen Wall/API port 5179 is for the manager UI. Expose it only if a remote browser must open the Wall directly.","Prefer VPN, Tailscale, ZeroTier, or fixed-IP allowlists over public internet exposure."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:aa({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. workstation を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ LAN なら通常 router forwarding は不要です。外部拠点では client が manager の接続ポートへ到達できる必要があります。",firewallPoints:["client 接続ポートは TCP 5197 です。","client 側は通常 outbound だけで足ります。","外部 network では manager PC の firewall で TCP 5197 inbound を許可し、router から manager PC へ forward します。","5179 は manager UI 用なので、外部ブラウザで Wall を開く必要がある時だけ公開を検討します。","公開 internet より VPN、Tailscale、ZeroTier、IP allowlist を優先してください。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"workstation 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":aa({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 workstation",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、xdotool 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 LAN 通常不需要路由端口转发。不同地点连接时,client 必须能访问 manager 的 client 连接端口。",firewallPoints:["client 连接端口是 TCP 5197。","client 机器通常只需要出站访问。","跨网络时,在 manager 防火墙放行 TCP 5197 入站,并在路由器转发到 manager PC。","5179 是 manager UI 端口,仅在需要远程浏览器直接打开 Wall 时考虑暴露。","优先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":aa({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 workstation",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 LAN 通常不需要路由器轉發。不同地點連線時,client 必須能到達 manager 的 client 連線埠。",firewallPoints:["client 連線埠是 TCP 5197。","client 電腦通常只需要對外連線。","跨網路時,請在 manager 防火牆允許 TCP 5197 inbound,並從路由器轉發到 manager PC。","5179 是 manager UI 連接埠,只在需要遠端瀏覽器直接打開 Wall 時才考慮公開。","優先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:aa({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una workstation",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: agregado linux-x64 runtime, captura grim/gnome-screenshot/import/scrot y entrada xdotool. Audio aún desactivado."],firewallTitle:"Firewall y sedes remotas",firewallBody:"En la misma LAN normalmente no hace falta port forwarding. Para otra red, los clients deben llegar al puerto client del manager.",firewallPoints:["Puerto de conexión client: TCP 5197.","Los equipos client normalmente solo necesitan salida.","Para redes remotas, permite TCP 5197 inbound en el manager y reenvía TCP 5197 al PC manager.","El puerto 5179 es para la UI del manager; expónlo solo si un navegador remoto debe abrir el Wall.","Prefiere VPN, Tailscale, ZeroTier o allowlist de IP fijas."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:aa({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une workstation",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot et entrée xdotool ajoutés. Audio désactivé."],firewallTitle:"Firewall et sites distants",firewallBody:"Sur le même LAN, le port forwarding est rarement nécessaire. Depuis un autre réseau, les clients doivent atteindre le port client du manager.",firewallPoints:["Port de connexion client: TCP 5197.","Les machines client ont normalement seulement besoin de sortie réseau.","Pour un réseau distant, autorisez TCP 5197 entrant sur le manager et redirigez TCP 5197 vers le PC manager.","Le port 5179 sert à l’UI manager; exposez-le seulement si un navigateur distant doit ouvrir le Wall.","Préférez VPN, Tailscale, ZeroTier ou allowlist IP fixes."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter workstation",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:aa({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Workstations, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Workstation verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, grim/gnome-screenshot/import/scrot Capture und xdotool Input Backend sind ergänzt. Audio ist deaktiviert."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"Im gleichen LAN ist Router-Forwarding meist unnötig. Aus anderen Netzwerken müssen Clients den Client-Port des Managers erreichen.",firewallPoints:["Client-Verbindungsport: TCP 5197.","Client-Rechner brauchen normalerweise nur ausgehenden Zugriff.","Für entfernte Netzwerke TCP 5197 inbound am Manager erlauben und vom Router zum Manager-PC forwarden.","Port 5179 ist für die Manager-UI; nur öffnen, wenn ein Remote-Browser die Wall direkt öffnen muss.","VPN, Tailscale, ZeroTier oder feste IP-Allowlists bevorzugen."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Workstation verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":aa({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma workstation",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada xdotool adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"Na mesma LAN normalmente não é preciso port forwarding. Em outra rede, clients precisam alcançar a porta client do manager.",firewallPoints:["Porta client: TCP 5197.","Máquinas client normalmente só precisam de saída.","Para redes remotas, permita TCP 5197 inbound no manager e encaminhe TCP 5197 para o PC manager.","A porta 5179 é para a UI do manager; exponha apenas se um navegador remoto precisar abrir o Wall.","Prefira VPN, Tailscale, ZeroTier ou allowlist de IP fixo."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:aa({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare workstation, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una workstation",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input xdotool. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"Nella stessa LAN di solito non serve port forwarding. Da altre reti, i client devono raggiungere la porta client del manager.",firewallPoints:["Porta client: TCP 5197.","I client normalmente richiedono solo uscita.","Per reti remote, abilita TCP 5197 inbound sul manager e inoltra TCP 5197 al PC manager.","La porta 5179 è per la UI manager; esponila solo se un browser remoto deve aprire il Wall.","Preferisci VPN, Tailscale, ZeroTier o IP allowlist."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti workstation",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:aa({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak workstation, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan workstation",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input xdotool sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"Di LAN yang sama biasanya tidak perlu port forwarding. Dari jaringan lain, client harus mencapai port client manager.",firewallPoints:["Port client: TCP 5197.","Mesin client biasanya hanya perlu akses keluar.","Untuk jaringan luar, izinkan TCP 5197 inbound di manager dan forward TCP 5197 ke PC manager.","Port 5179 untuk UI manager; buka hanya jika browser luar harus membuka Wall.","Utamakan VPN, Tailscale, ZeroTier, atau IP allowlist."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan workstation",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:aa({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều workstation, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối workstation",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input xdotool. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"Trong cùng LAN thường không cần port forwarding. Từ mạng khác, client phải truy cập được port client của manager.",firewallPoints:["Port client: TCP 5197.","Máy client thường chỉ cần kết nối outbound.","Với mạng ngoài, cho phép TCP 5197 inbound trên manager và forward TCP 5197 tới PC manager.","Port 5179 dành cho UI manager; chỉ mở nếu trình duyệt từ xa cần mở Wall trực tiếp.","Ưu tiên VPN, Tailscale, ZeroTier hoặc allowlist IP cố định."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối workstation",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:aa({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู workstation, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม workstation",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ xdotool input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน LAN เดียวกันปกติไม่ต้อง port forwarding ถ้าอยู่คนละ network client ต้องเข้าถึง client port ของ manager ได้",firewallPoints:["Client port คือ TCP 5197","เครื่อง client ปกติต้องการ outbound เท่านั้น","ถ้าอยู่นอก network ให้เปิด TCP 5197 inbound ที่ manager และ forward TCP 5197 ไปยัง manager PC","Port 5179 เป็น UI ของ manager เปิดเฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง","ควรใช้ VPN, Tailscale, ZeroTier หรือ IP allowlist ก่อนเปิดสู่ public internet"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม workstation",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:aa({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई workstation, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. workstation जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture और xdotool input backend जोड़े गए हैं। Audio अभी disabled है।"],firewallTitle:"Firewall और remote locations",firewallBody:"Same LAN में आम तौर पर router forwarding जरूरी नहीं। दूसरे network से clients को manager client port तक पहुंचना होगा।",firewallPoints:["Client connection port: TCP 5197.","Client machines को आम तौर पर सिर्फ outbound access चाहिए।","Remote network के लिए manager firewall में TCP 5197 inbound allow करें और router से TCP 5197 manager PC पर forward करें।","5179 manager UI port है; इसे तभी expose करें जब remote browser को Wall खोलना हो।","Public internet से पहले VPN, Tailscale, ZeroTier या fixed IP allowlist बेहतर है।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:aa({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة workstations وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل workstation",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وxdotool input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس LAN غالبا لا تحتاج port forwarding. من شبكة أخرى يجب أن يصل client إلى منفذ manager client.",firewallPoints:["منفذ client: TCP 5197.","أجهزة client تحتاج عادة اتصال outbound فقط.","للشبكات البعيدة، اسمح TCP 5197 inbound على manager ووجه TCP 5197 من router إلى manager PC.","المنفذ 5179 مخصص لواجهة manager؛ اكشفه فقط إذا كان متصفح بعيد يحتاج فتح Wall مباشرة.","يفضل VPN أو Tailscale أو ZeroTier أو fixed IP allowlist بدل التعريض العام."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:aa({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok workstation, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Workstation bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve xdotool input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"Aynı LAN içinde genelde router forwarding gerekmez. Başka ağdan clients manager client portuna ulaşabilmelidir.",firewallPoints:["Client port: TCP 5197.","Client makineler normalde sadece outbound erişim ister.","Uzak ağ için manager firewall üzerinde TCP 5197 inbound aç ve routerdan TCP 5197yi manager PCye forward et.","5179 manager UI portudur; sadece uzak browser Wall açacaksa expose et.","Public internet yerine VPN, Tailscale, ZeroTier veya sabit IP allowlist tercih et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Workstation bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},TT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function ET(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const r=a.toLowerCase();if(Oo[a])return a;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const l=r.split("-")[0];if(Oo[l])return l}return"en"}function qy({index:n}){const a=n+1;return s.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:s.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[s.jsx("span",{className:"slot-grid","aria-hidden":"true"}),s.jsxs("span",{className:"empty-screen",children:[s.jsx(en,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}function RT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Qi(a)&&n.capabilities?.screenRecordingPermission===!1}function Qi(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function Gy(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:Qi(n.platform)}function jh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:g,onOpenControl:v,onCycleMonitor:b,onCanvasReady:y,sendInput:w,updateIndicator:S,presentationReady:j,showPresentationSpinner:N=!1}){const M=u.useRef(null),k=u.useRef(null),E=u.useRef(0),R=u.useRef(null),U=Nw(n),H=["cpu","gpu","memory","vram"].map(B=>U.metrics.find(pe=>pe.id===B)).filter(B=>!!B),W=Da(d,m),_=m>1,L=j??!!a,le=RT(n)&&!L,q=N&&n.connected&&!L&&!le,te=cT(n,a,W),K=te>=Wd?100:te/Wd*100,ne=te>=Wd?Wd/te*100:100,ce={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,K)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,ne)).toFixed(3)}%`},V=u.useCallback(B=>{M.current=B,y(n.deviceId,B)},[n.deviceId,y]),O=B=>{const pe=B.currentTarget.getBoundingClientRect();return Nj(B.clientX,B.clientY,pe)},Y=B=>({shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}),X=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),P=u.useCallback(()=>{const B=k.current;if(!B)return;k.current=null;const pe=Number(B.input.normalizedX),ge=Number(B.input.normalizedY);if(!Number.isFinite(pe)||!Number.isFinite(ge))return;w(n.deviceId,{...B.input,normalizedX:pe,normalizedY:ge})&&(E.current=performance.now())},[n.deviceId,w]),oe=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,P()}))},[P]);u.useEffect(()=>()=>{X(),k.current=null},[X]);const we=(B,pe)=>{if(!l)return;const ge={type:pe,monitorIndex:W,...O(B),button:wT(B.button),...Y(B)};if(pe==="pointermove"){const xe=performance.now();k.current={input:ge},xe-E.current>=LM&&(X(),P()),oe();return}k.current&&(X(),P()),w(n.deviceId,ge)},J=u.useCallback(B=>{const pe=document.activeElement;pe instanceof HTMLElement&&B.contains(pe)&&pe.classList.contains("monitor-cycle-button")&&pe.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:ce,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||l||p()},onKeyDown:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||l||(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),p())},onDoubleClick:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||(B.preventDefault(),v())},onPointerLeave:B=>J(B.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:V,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:B=>{l&&(B.preventDefault(),B.stopPropagation(),g(),B.currentTarget.focus(),B.currentTarget.setPointerCapture(B.pointerId),we(B,"pointerdown"))},onPointerMove:B=>{l&&B.preventDefault(),we(B,"pointermove")},onPointerLeave:B=>{l&&(we(B,"pointermove"),X(),P())},onPointerUp:B=>{l&&(B.preventDefault(),B.stopPropagation(),we(B,"pointerup"),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId))},onPointerCancel:B=>{B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId)},onWheel:B=>{l&&(B.preventDefault(),w(n.deviceId,{type:"wheel",monitorIndex:W,...O(B),deltaX:B.deltaX,deltaY:B.deltaY,...Y(B)}))},onKeyDown:B=>{l&&(B.preventDefault(),B.stopPropagation(),w(n.deviceId,{type:"keydown",monitorIndex:W,key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:B.repeat,...Y(B)}))},onKeyUp:B=>{l&&(B.preventDefault(),B.stopPropagation(),w(n.deviceId,{type:"keyup",monitorIndex:W,key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:!1,...Y(B)}))},onContextMenu:B=>l&&B.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(en,{size:26})}),q&&s.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),s.jsx("strong",{children:"Preparing video"})]}),le&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(Lt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"Screen Recording permission required"}),s.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),S&&s.jsxs("span",{className:`wall-update-status state-${S.state}`,role:"status","aria-live":"polite",title:S.error||S.label,children:[S.state==="updated"?s.jsx(Hn,{size:20,"aria-hidden":"true"}):S.state==="failed"?s.jsx(Ja,{size:22,"aria-hidden":"true"}):S.state==="offline"?s.jsx(Il,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:S.label}),S.error?s.jsx("small",{children:S.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${U.state}`,children:U.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${ha(n)} status`,children:H.map(B=>s.jsxs("span",{className:`tile-metric state-${B.state}`,children:[s.jsx("b",{children:B.label}),s.jsx("em",{children:B.value}),B.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(B.ratio*100)}%`}})]},B.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${ha(n)} display ${W+1} of ${m}`,onPointerDown:B=>B.stopPropagation(),onClick:B=>B.stopPropagation(),onDoubleClick:B=>B.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(-1),B.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(ab,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",W+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(1),B.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(tp,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx($r,{size:23,strokeWidth:3.5})})]})})}function DT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(ky)){const r=document.createElement("script");r.id=ky,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Vh)}`,document.head.appendChild(r)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?s.jsxs("aside",{className:`free-ad-banner ${ph?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),ph?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Vh,"data-ad-slot":yw,"data-ad-format":"auto","data-full-width-responsive":"true"}):s.jsxs("div",{className:"house-ad-copy",children:[s.jsx("strong",{children:"Sponsored placement"}),s.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function LT(){const n=qM(),{session:a,loading:r}=ij(),{target:l,error:c,refresh:d}=lj(a),m=u.useMemo(()=>{if(!l?.active)return null;const x=l.expires_at?Date.parse(l.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:l},[l]),p=u.useMemo(()=>Sx(m),[m]),g=u.useMemo(()=>p.length>0?[...new Set([...p,bn])]:[bn],[p]),[v,b]=u.useState(iT),y=u.useMemo(()=>g.some(x=>!!Zc(x)),[g]),w=!y||v,{status:S,devices:j,error:N,refresh:M,hubBaseUrl:k}=rj(g,w),{entitlement:E,licensed:R,loading:U,error:H,refresh:W}=oj(a),[_,L]=u.useState([]),[le,q]=u.useState(""),[te,K]=u.useState(""),[ne,ce]=u.useState(""),[V,O]=u.useState(""),[Y,X]=u.useState(""),[P,oe]=u.useState("idle"),[we,J]=u.useState(!1),[B,pe]=u.useState(null),[ge,xe]=u.useState(""),Ae=u.useRef("");Ae.current=V;const[_e,ie]=u.useState(!1),[Q,Ie]=u.useState(!1),Oe=u.useRef(""),ae=u.useRef(new Map),ke=u.useRef(0),[je,De]=u.useState(""),[Le,$e]=u.useState(""),[he,Me]=u.useState(!1),[de,be]=u.useState(null);u.useEffect(()=>{je==="auth"&&a?.access_token&&De("")},[je,a?.access_token]);const[We,at]=u.useState(""),[wn,Xe]=u.useState(null),ht=u.useRef(null),St=u.useRef(0),Rn=u.useCallback((x,A,D)=>{const $=String(x||"").trim();if(at($),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!$){Xe(null);return}const z=++St.current;if(Xe({id:z,message:$,tone:A}),!D)return;const me=window.setTimeout(()=>{Xe(ve=>ve?.id===z?null:ve),ht.current===me&&(ht.current=null)},5e3);ht.current=me},[]),He=u.useCallback((x,A="info")=>{Rn(x,A,!0)},[Rn]),Ct=u.useCallback(x=>{Rn(x,"progress",!1)},[Rn]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[Gt,pt]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{pt(window.location.pathname.startsWith("/support")?"support":A=>A==="support"?"wall":A)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[rt,tn]=u.useState("large"),[kt,ze]=u.useState(ET),[Dn,Zi]=u.useState(!1),[hn,$n]=u.useState(!1),[ga,ts]=u.useState(!1),[Ln,ns]=u.useState(sT),[Be,hi]=u.useState(fT),[ft,as]=u.useState(hT),[Vt,Bs]=u.useState(uT),[I,Fe]=u.useState(null),[mt,nn]=u.useState([]),[pn,Fs]=u.useState(Be.fps),[ra,ee]=u.useState(""),[Te,qe]=u.useState(0),[it,Kt]=u.useState(0),[Tt,Ze]=u.useState(()=>new Set),lt=u.useRef(new Map),Qt=u.useRef(new Map),$t=u.useRef(new Map),_t=u.useRef(new Map),Ft=u.useRef(new Map),Ut=u.useRef(new Set),zt=u.useRef(new Map),gn=u.useRef(""),ss=u.useRef(""),un=u.useRef(null),Xt=u.useRef(null),bs=u.useRef(new Map),ws=u.useRef(null),pi=u.useRef(0),$o=u.useRef(new Map),[Ji,Pl]=u.useState({}),Oa=u.useRef(new Map),[Qn,cu]=u.useState({}),[uu,Xn]=u.useState(!1),$l=u.useRef(null),la=u.useRef(null),va=u.useRef(0),Sn=u.useRef(""),gi=u.useRef(new Map),er=u.useRef(new Map),tr=u.useRef(performance.now()),is=u.useRef(new Map),vi=u.useRef(new Map),xi=u.useRef(new Map),Ps=u.useRef(new Map),Yr=u.useRef(0),Kr=u.useRef(0),Qr=u.useRef(0),nr=u.useRef(0),Uo=u.useRef(0),du=u.useRef(new Map),Ha=u.useRef(new Map),[Un,rs]=u.useState(null),[qo,$s]=u.useState(!1),[Xr,fu]=u.useState([]),[Us,mu]=u.useState("all"),[ls,Ba]=u.useState([]),[hu,Ul]=u.useState(!1),[yi,Go]=u.useState(!0),Zr=u.useRef(null),Vo=u.useRef(null),ql=u.useRef(null),Gl=u.useRef(null),pu=u.useRef(!1),_n=u.useRef(!1),Ss=u.useRef(!1),qs=u.useRef(0),xa=u.useRef(0),Vl=Gt==="settings",Wl=Gt==="pricing",Yl=Gt==="doc",ar=Gt==="support",Gs=Gt==="share-files",Kl=Gt==="agents",gu=!Vl&&!Wl&&!Yl&&!ar&&!Gs&&!Kl,nt=Gt==="control",ut=Be.frameMode==="mode4-h264-atlas",Zn=Y||ft.frameMode,sr=Zn!=="mode3-h264-hw"?Math.min(30,ft.fps):ft.fps,Vs=Zn!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ft.maxWidth),maxHeight:Math.min(1080,ft.maxHeight)}:{maxWidth:ft.maxWidth,maxHeight:ft.maxHeight};u.useEffect(()=>{if(S?.started){if(!a?.access_token){Ge("/api/remote/license",{method:"DELETE"},k).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`}},k).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[E?.updated_at,k,a?.access_token,S?.started]),u.useEffect(()=>{!a?.access_token||!S?.started||S.runtimeRole!=="hub"||!S.deviceId||(async()=>{try{const{data:x,error:A}=await ct.rpc("register_livedesk_device",{p_device_id:S.deviceId,p_device_name:S.deviceName||S.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:S.managerVersion||S.managerPackage||""}),D=Array.isArray(x)?x[0]:x;(A||D?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",A||D?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[a?.access_token,S?.deviceId,S?.deviceName,S?.managerPackage,S?.managerVersion,S?.runtimeRole,S?.started]),u.useEffect(()=>{!a?.access_token||!a.refresh_token||!S?.started||S.runtimeRole!=="hub"||Ss.current||(Ss.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},k||bn).then(x=>{x.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",x.hostTarget.error||"unknown-error"),M()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{Ss.current=!1}))},[k,M,a?.access_token,a?.expires_at,a?.refresh_token,a?.user?.email,a?.user?.id,S?.runtimeRole,S?.started]);const et=u.useMemo(()=>j.filter(x=>x.connected),[j]),vu=Us==="all"?et.length:ls.filter(x=>et.some(A=>A.deviceId===x)).length,kf=u.useMemo(()=>et.reduce((x,A)=>Math.max(x,Uy(A.slotNumber)),0),[et]),Jr=Math.max(EM,et.length,kf),el=u.useMemo(()=>{const x=Array(Jr).fill(null),A=[];for(const D of et){const $=Uy(D.slotNumber);$>0&&$<=Jr&&!x[$-1]?x[$-1]=D:A.push(D)}for(const D of A){const $=x.findIndex(z=>!z);$<0?x.push(D):x[$]=D}return x},[et]),Wo=u.useMemo(()=>et.map(x=>x.deviceId),[et]),ir=u.useMemo(()=>new Set(_),[_]),Fa=u.useMemo(()=>et.filter(x=>ir.has(x.deviceId)),[et,ir]),Ws=u.useMemo(()=>j.find(x=>x.deviceId===le)||Fa[0]||null,[j,le,Fa]),qn=u.useMemo(()=>j.find(x=>x.deviceId===te)||null,[te,j]),Ys=qn?Da(Vt[qn.deviceId],ma(qn)):0,Ee=nt?qn:Ws,Yo=u.useMemo(()=>new Set(ls),[ls]),Af=u.useMemo(()=>Us==="all"?et.map(x=>x.deviceId):et.filter(x=>Yo.has(x.deviceId)).map(x=>x.deviceId),[et,Yo,Us]),os=u.useMemo(()=>Ee?Nw(Ee):null,[Ee]),Nf=Ee?tu(Ee,"control"):!1,Ko=Qi(Ee?.platform)&&(Ee?.capabilities?.controlPermission===!1||Ee?.capabilities?.accessibilityPermission===!1),tl=Ee?tu(Ee,"audio")||tu(Ee,"remoteAudio"):!1,xu=Array.isArray(Ee?.capabilities?.agentTools)?Ee.capabilities.agentTools.map(String):[],Ql=xu.includes("system.power"),yu=xu.includes("command.run"),qt=R?E?.plan==="pro"?"pro":"ltd":"free",Xl=Ml[qt],Ks=Xl.limit,bi=u.useMemo(()=>{if(!Number.isFinite(Ks))return new Set(et.map(A=>A.deviceId));const x=Ee?[Ee,...et.filter(A=>A.deviceId!==Ee.deviceId)]:et;return new Set(x.slice(0,Ks).map(A=>A.deviceId))},[Ks,et,Ee]),bu=!Ee||bi.has(Ee.deviceId),wu=qt==="free",Wt=bu,wi=qt==="ltd"?`Plus includes up to ${Wc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Vc} workstations. Upgrade to Plus for ${Wc} devices and no ads.`,Su=qt==="free",Si=Wt&&!!Ee,Cs=Wt&&!!Ee&&Nf,Cu=Wt&&!!Ee&&tl;u.useEffect(()=>{Me(!1)},[Gt,Ee?.deviceId]);const Zl=u.useMemo(()=>el.filter(x=>!!x?.connected).slice(0,gT(rt)).map(x=>x.deviceId),[el,rt]),nl=u.useMemo(()=>ut?Wo:Be.visibleOnlyLive?mt.length>0?mt:Zl:Wo,[Zl,ut,mt,Be.visibleOnlyLive,Wo]),ya=u.useMemo(()=>bh(nl.filter(x=>bi.has(x))),[bi,nl]),ba=u.useMemo(()=>ya.filter(x=>x!==ra),[ya,ra]),Qs=u.useMemo(()=>new Map(et.map(x=>[x.deviceId,x.platform])),[et]),cs=Mj(ut,ya.length),Gn=u.useMemo(()=>ut?ba.filter(x=>$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(Qs.get(x))})==="atlas"):[],[cs,ut,Qs,ba]),Jn=u.useMemo(()=>ba.filter(x=>$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(Qs.get(x))})==="direct"),[cs,ut,Qs,ba]);u.useEffect(()=>{const x=new Set(ya);Ze(A=>{let D=!1;const $=new Set;for(const z of A)x.has(z)?$.add(z):D=!0;return D?$:A})},[ya]);const ju=u.useMemo(()=>{const x=z=>et.find(me=>me.deviceId===z)||null,A=z=>Da(Vt[z],x(z)?ma(x(z)):0),D=(z,me=A(z))=>z===ne&&(P==="connecting"||P==="active"||P==="warm")?_t.current.get(z)||Qt.current.get(z)||null:ut?bs.current.get(z)||lt.current.get(z)||null:lt.current.get(z)||null,$=(z,me=A(z))=>{const ve=x(z);return`${ve?ha(ve):z} · Monitor ${me+1}`};return{resolveCurrentTarget(){if(nt&&qn){const Ue=Ys;return{type:"control",deviceIds:[qn.deviceId],monitorIndex:Ue,label:`${ha(qn)} · Monitor ${Ue+1}`,sourceCanvas:D(qn.deviceId,Ue),signature:`control:${qn.deviceId}:${Ue}:${ft.frameMode}`}}const z=Fa.map(Ue=>Ue.deviceId).filter(Ue=>ba.includes(Ue)),me=Ws&&ba.includes(Ws.deviceId)?Ws.deviceId:"",ve=z.length>0?z:me?[me]:ba,Ne=z.length===0&&!me;if(ve.length===0)return null;if(ve.length===1){const Ue=ve[0],Ke=A(Ue);return{type:Ne?"wall":z.length>1?"selection":"device",deviceIds:ve,monitorIndex:Ke,label:Ne?"Wall":$(Ue,Ke),sourceCanvas:Ne?null:D(Ue,Ke),signature:`${Ne?"wall":"device"}:${Ue}:${Ke}:${ut?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:ve,label:z.length>1?`${ve.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${ve.join(",")}:${rt}`}},getDeviceCanvas:D,composeWall(z,me={}){return xM(z.map(ve=>{const Ne=A(ve);return{deviceId:ve,label:$(ve,Ne),canvas:D(ve,Ne)}}),me)}}},[et,qn,ne,P,ft.frameMode,lt,ut,Vt,Ys,Fa,nt,ba,Ws,rt]),Jl=TM({hubUrl:k,sourceRegistry:ju,onToast:He}),Xs=u.useMemo(()=>Wt&&ne&&bi.has(ne)&&(P==="connecting"||P==="active"||P==="warm")?[ne]:[],[ne,P,Wt,bi]),ku=u.useMemo(()=>bh([...ya,...Xs]),[Xs,ya]),zn=u.useMemo(()=>vT(Be,rt),[Be,rt]),Ci=Tj({mode4Enabled:ut,directMode4WallEnabled:cs,adaptiveFps:pn,directDeviceCount:Jn.length}),js=u.useCallback((x,A,D)=>{if(x.width<=0||x.height<=0)return!1;const $=D?Math.min(1,D.maxWidth/x.width,D.maxHeight/x.height):1,z=Math.max(1,Math.round(x.width*$)),me=Math.max(1,Math.round(x.height*$));(A.width!==z||A.height!==me)&&(A.width=z,A.height=me);const ve=A.getContext("2d",{alpha:!1});return ve?(ve.imageSmoothingEnabled=!0,ve.imageSmoothingQuality="high",ve.drawImage(x,0,0,x.width,x.height,0,0,A.width,A.height),!0):!1},[]),rr=u.useCallback(x=>{x&&Ze(A=>{if(A.has(x))return A;const D=new Set(A);return D.add(x),D})},[]),eo=u.useCallback(x=>{x&&Ze(A=>{if(!A.has(x))return A;const D=new Set(A);return D.delete(x),D})},[]),to=u.useCallback((x,A)=>{if(!A||A.width<=0||A.height<=0)return!1;const D=document.createElement("canvas");return D.width=A.width,D.height=A.height,js(A,D)?($t.current.set(x,D),rr(x),!0):!1},[rr,js]),ks=u.useCallback((x,A=!1)=>{if(!Ut.current.has(x))return!1;const D=performance.now(),$=zt.current.get(x)||0,z=Math.max(1,Math.min(di.controlWallReuseMaxFps,sr)),me=sr>z?Math.max(0,1e3/z-2):0;if(!A&&D-$<me)return!1;const ve=_t.current.get(x)||Qt.current.get(x),Ne=lt.current.get(x)||bs.current.get(x);return!ve||!Ne||!js(ve,Ne,zn)?!1:(zt.current.set(x,D),rr(x),!0)},[sr,zn,rr,js]);u.useEffect(()=>{gn.current=ra},[ra]);const ea=u.useCallback((x,A)=>{const D=lt.current.get(x);if(D&&D!==A&&(to(x,D),Pc(D)),A){lt.current.set(x,A),$t.current.delete(x),ks(x,!0);return}lt.current.delete(x),$t.current.has(x)||eo(x)},[eo,ks,to]),al=u.useCallback((x,A)=>{const D=Qt.current.get(x);if(D&&D!==A&&Pc(D),A){Qt.current.set(x,A);const $=_t.current.get(x)||$t.current.get(x)||lt.current.get(x)||bs.current.get(x);$&&js($,A)&&x===te&&Xn(!0);return}Qt.current.delete(x)},[te,js]),sl=u.useCallback((x,A,D)=>{const $=performance.now(),z=zs(x,D.deviceId);let me=D;if(x==="control"&&D.visualChanged){const Ne=hj(D.deviceId),Ue=du.current.get(D.deviceId)||0,Ke=Ne?$-Ne.sentAt:Number.POSITIVE_INFINITY;Ne&&Ne.inputSeq>Ue&&Ke<=Ay&&(me={...D,inputFeedbackSeq:Ne.inputSeq,inputFeedbackMs:Math.max(0,Ke),inputFeedbackAt:$},du.current.set(D.deviceId,Ne.inputSeq))}er.current.set(z,$);const ve=$o.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:$,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&me.inputFeedbackMs===void 0&&ve.lastInfo?.inputFeedbackMs!==void 0&&ve.lastInfo.inputFeedbackAt!==void 0&&$-ve.lastInfo.inputFeedbackAt<=Ay&&(me={...me,inputFeedbackSeq:ve.lastInfo.inputFeedbackSeq,inputFeedbackMs:ve.lastInfo.inputFeedbackMs,inputFeedbackAt:ve.lastInfo.inputFeedbackAt}),ve.totalFrames+=1,ve.sampleFrames+=1,Dy(ve,$,me.frameSeq),me.visualChanged&&(ve.totalChangedFrames+=1,ve.sampleChangedFrames+=1),ve.lastInfo=me,$o.current.set(z,ve)},[]),il=u.useCallback((x,A)=>{sl("wall",x,A),x.kind==="live"&&rr(x.deviceId);const D=we&&ne===x.deviceId;gn.current!==x.deviceId&&!D&&(Ut.current.delete(x.deviceId),zt.current.delete(x.deviceId))},[ne,we,rr,sl]),Qo=u.useCallback((x,A)=>{sl("control",x,A),xe(me=>me&&"");const D=_t.current.get(x.deviceId),$=Qt.current.get(x.deviceId);D&&D.width>0&&D.height>0&&($&&js(D,$),Ft.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),$t.current.delete(x.deviceId),Ut.current.add(x.deviceId),x.deviceId===ne&&(J(!0),oe(me=>me==="connecting"?"active":me)),ks(x.deviceId));const z=$l.current;!z||!UM(z,x)||Xn(!0)},[ne,js,ks,sl]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),D={};for(const[$,z]of $o.current.entries()){const me=Math.max(1,A-z.sampleStartedAt);D[$]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/me,changedFramesPerSecond:z.sampleChangedFrames*1e3/me,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:ef(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/me),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/me),sampleMs:me,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,Ry(z,A)}Pl(D)},1e3);return()=>window.clearInterval(x)},[]);const ji=u.useCallback((x,A)=>{const D=performance.now(),$=zs(x,A.deviceId);gi.current.set($,D),Ha.current.delete($),x==="control"&&vi.current.delete($);const z=Oa.current.get($)||{totalFrames:0,sampleFrames:0,sampleStartedAt:D,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(z.totalFrames+=1,z.sampleFrames+=1,z.sampleBytes+=Math.max(0,Number(A.byteLength||0)),String(A.frameMode||A.mode||A.codec||A.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(A.byteLength||0)<=BM&&(z.sampleTinyFrames+=1);const Ue=String(A.contentHash||"");Ue&&z.lastContentHash===Ue&&(z.sampleRepeatedFrames+=1),z.lastContentHash=Ue}const Ne=Number(A.agentSendGapMs||0);Ne>0&&Ne<1e3&&Sp(z.sourceSendIntervalsMs,Ne),z.lastFrame=A,Dy(z,D,A.frameSeq),Oa.current.set($,z)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),D={};for(const[$,z]of Oa.current.entries()){const me=Math.max(1,A-z.sampleStartedAt);D[$]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/me,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:ef(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,averageFrameBytes:z.sampleFrames>0?z.sampleBytes/z.sampleFrames:0,tinyFrameRatio:z.sampleH264Frames>0?z.sampleTinyFrames/z.sampleH264Frames:0,repeatedFrameRatio:z.sampleH264Frames>0?z.sampleRepeatedFrames/z.sampleH264Frames:0,sourceSendAverageMs:z.sourceSendIntervalsMs.length>0?z.sourceSendIntervalsMs.reduce((ve,Ne)=>ve+Ne,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:ef(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:me,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,Ry(z,A)}cu(D)},1e3);return()=>window.clearInterval(x)},[]);const no=u.useCallback(x=>{ji("wall",x);const A=lt.current.get(x.deviceId);if(!A)return;const D=Ej(ut,Be.h264DecodeAcceleration);nh(A,x,()=>lt.current.get(x.deviceId)!==A,il,D.acceleration,D.latencyMode).catch(()=>{})},[il,ut,ji,Be.h264DecodeAcceleration]),Au=u.useCallback(x=>{ji("control",x);let A=_t.current.get(x.deviceId);A||(A=document.createElement("canvas"),A.setAttribute("aria-hidden","true"),_t.current.set(x.deviceId,A));const D=A,$=Ae.current;nh(D,x,()=>_t.current.get(x.deviceId)!==D,Qo,ft.h264DecodeAcceleration,"interactive").catch(z=>{Ae.current!==$||_t.current.get(x.deviceId)!==D||ne!==x.deviceId||xe(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[ne,ft.h264DecodeAcceleration,Qo,ji]),lr=u.useCallback(x=>{const A=Xt.current;A&&A!==x&&Pc(A),Xt.current=x,Yr.current=0,Kr.current=0,Qr.current=0,nr.current=0,Uo.current=0,pi.current=0},[]),Zs=u.useCallback(()=>{const x=Xt.current,A=ws.current;if(!(!x||!A||x.width<=0||x.height<=0||pi.current!==A.layoutVersion))for(const D of A.tiles){const $=bs.current.get(D.deviceId);if(!$||D.width<=0||D.height<=0)continue;const z=Math.max(1,Math.round(D.width)),me=Math.max(1,Math.round(D.height)),ve=FM,Ne=PM;($.width!==ve||$.height!==Ne)&&($.width=ve,$.height=Ne);const Ue=$.getContext("2d",{alpha:!1});if(Ue){Ue.imageSmoothingEnabled=!0,Ue.imageSmoothingQuality="high";try{Ue.drawImage(x,Math.round(D.x),Math.round(D.y),z,me,0,0,ve,Ne)}catch{}}}},[]),rl=u.useCallback((x,A)=>{if(A){bs.current.set(x,A),$t.current.delete(x),window.requestAnimationFrame(Zs),window.requestAnimationFrame(()=>ks(x,!0));return}const D=bs.current.get(x);to(x,D),bs.current.delete(x),$t.current.has(x)||eo(x)},[eo,Zs,ks,to]),ao=u.useCallback((x,A)=>{Qr.current=performance.now(),pi.current=Number(x.layoutVersion||0),Zs();const D=ws.current?.tiles||[],$=D.length>0?Math.round(x.byteLength/D.length):x.byteLength;for(const z of D){const me={...x,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:$};il(me,{...A,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:$}),gn.current===z.deviceId&&ks(z.deviceId,!0)}},[il,Zs,ks]),Nu=u.useCallback(x=>{const A=performance.now();Yr.current<=0&&(Yr.current=A),Kr.current=A;const D=Xt.current;if(!D)return;const $=ws.current?.tiles||[],z=$.length>0?Math.round(x.byteLength/$.length):x.byteLength;for(const me of $)ji("wall",{...x,deviceId:me.deviceId,width:me.width,height:me.height,sourceWidth:me.width,sourceHeight:me.height,byteLength:z});nh(D,x,()=>Xt.current!==D,ao).catch(()=>{})},[ao,ji]),ki=u.useMemo(()=>({fps:Ci,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:Be.quality,mode:ut?"mode3-h264-hw":Be.frameMode,frameMode:ut?"mode3-h264-hw":Be.frameMode,streamPurpose:"wall",monitorSelections:Vt,onFrame:no}),[Ci,no,zn,ut,Vt,Be]),Ai=u.useCallback(x=>{if(x.deviceId!==ne||x.streamPurpose!=="control"||x.monitorIndex!==Ys)return;const A=et.find(D=>D.deviceId===x.deviceId);!A?.sessionId||A.sessionId!==x.sessionId||(pe(x),oe(D=>D==="connecting"?"active":D))},[et,ne,Ys]);u.useEffect(()=>{pe(null)},[ne,V,Zn,Ys]);const Xo=u.useMemo(()=>({fps:sr,maxWidth:Vs.maxWidth,maxHeight:Vs.maxHeight,quality:ft.quality,mode:Zn,frameMode:Zn,streamPurpose:"control",forceRestart:V!=="",forceRestartToken:V,restartReason:V?"control-session-start":"",monitorSelections:Vt,onFrame:Au,onStreamReady:Ai}),[V,ft.quality,Au,sr,Zn,Vs.maxHeight,Vs.maxWidth,Ai,Vt]),{frames:Zo,state:Pa,error:Jo,stats:As,restartLive:ll}=zx(Jn,Be.autoStartLive&&Jn.length>0,k,ki),{frame:or,layout:Ni,state:ec,stats:Mu,refreshInputs:tc}=pj(Gn,ut&&Be.autoStartLive&&Gn.length>0,k,{fps:di.atlasOutputFps,width:1920,height:1080,tileWidth:zn.maxWidth,tileHeight:zn.maxHeight,captureDeviceIds:Gn,monitorSelections:Vt,onFrame:Nu});u.useEffect(()=>{ws.current=Ni,Ni&&window.requestAnimationFrame(Zs)},[Ni,Zs]),u.useEffect(()=>{if(!ut||ec!=="open"){Yr.current=0,Kr.current=0,Qr.current=0;return}const x=window.setInterval(()=>{const A=Xt.current,D=performance.now();if(!A||document.visibilityState!=="visible"||D-tr.current<gh)return;const $=Kr.current,z=Yr.current;if($<=0||z<=0||D-$>500)return;const me=Qr.current||z,ve=D-me;if(ve>=zM&&D-Uo.current>=OM){eh(A)&&(Uo.current=D,nr.current=D);return}ve>=_M&&D-nr.current>=IM&&ZC(A)&&(nr.current=D)},250);return()=>window.clearInterval(x)},[ec,ut]);const{frames:ol,state:oa,error:Js,stats:wa,restartLive:Ns,reconnectLive:so}=zx(Xs,Xs.length>0,k,Xo),Mi=u.useMemo(()=>{const x=new Map(Zo);if(ut&&or&&Gn.length>0){const A=new Map((Ni?.tiles||[]).map($=>[$.deviceId,$])),D=Math.max(1,A.size);for(const $ of Gn){const z=A.get($);z&&x.set($,{...or,deviceId:$,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(or.byteLength/D)})}}for(const[A,D]of ol.entries())x.set(A,D);for(const A of nl){if(!Ut.current.has(A)||x.has(A))continue;const D=Ft.current.get(A);D&&x.set(A,D)}return x},[or,Ni,ol,Gn,ut,Zo,nl,it]),cr=nt&&Xs.length>0?oa:Gn.length>0?ec:Pa,cl=nt&&Xs.length>0?wa:Gn.length>0?Mu:As;u.useCallback((x,A="browser-stale")=>{const D=ll(x,A),$=Ns(x,A);return D||$},[Ns,ll]),u.useEffect(()=>{ut&&Gn.length>0&&!nt&&tc()},[Gn.length,ut,tc,nt]);const us=u.useCallback((x,A,D)=>{const $=A==="control"?_t.current.get(x)||null:lt.current.get(x)||null;if(!$||!eh($))return!1;const z=performance.now();return Ps.current.set(zs(A,x),z),!0},[]),ul=u.useCallback(x=>{if(Zn!=="mode3-h264-hw"||!ne||Y)return!1;const A=et.find(Ne=>Ne.deviceId===ne)||qn,D=String(A?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(D))return!1;const $="mode5-lzo-delta",z=zs("control",ne),me=performance.now();xi.current.set(z,me),gi.current.delete(z),er.current.delete(z),is.current.delete(z),vi.current.delete(z),Ha.current.delete(z),eh(_t.current.get(ne)||null),so([ne],"control-decode-fallback"),X($),O(`control-${$}-fallback-${ne}-${Date.now()}`),J(!1),Xn(!1);const ve=x==="no first frame"||x==="control-first-frame-timeout";return xe(Ne=>Ne||(ve?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),oe("connecting"),!0},[et,qn,ne,Y,Zn,so]);u.useEffect(()=>{const x=nt?qn:null;if(x){$l.current={deviceId:x.deviceId,monitorIndex:Ys,frameMode:Zn,startedAtEpochMs:Date.now()},Xn(ne===x.deviceId&&we||Tt.has(x.deviceId));return}$l.current=null,Xn(!1)},[qn?.sessionId,te,ne,we,Zn,Ys,nt,Tt]);const ei=u.useCallback(async x=>{const A=j.find(ve=>ve.deviceId===x),D=$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(A?.platform)})==="atlas",$=Da(Vt[x],A?ma(A):1),z=D?{fps:di.scalableAtlasInputFps,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:$}:{fps:ut&&!D?Ci:pn,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:Be.quality,mode:ut?"mode3-h264-hw":Be.frameMode,frameMode:ut?"mode3-h264-hw":Be.frameMode,streamPurpose:"wall",monitorIndex:$},me=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(z)},k);if(me?.ok===!1)throw new Error(me.error||"wall-stream-start-failed");return me},[pn,j,cs,Ci,zn.maxHeight,zn.maxWidth,k,ut,Vt,Be.frameMode,Be.quality]),Ms=u.useCallback(async x=>{const A=j.find(z=>z.deviceId===x),D=$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(A?.platform)})==="atlas",$=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:D?"atlas":"wall",reason:"control-active"})},k);if($?.ok===!1)throw new Error($.error||"wall-stream-stop-failed");return $},[j,cs,k,ut]),ur=u.useCallback(async(x,A="control-session-stop")=>{const D=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:A})},k);if(D?.ok===!1)throw new Error(D.error||"control-stream-stop-failed");return D},[k]),Cn=u.useCallback(x=>{const A=_t.current.get(x);A&&(Pc(A),_t.current.delete(x));const D=Qt.current.get(x);D&&Pc(D),Ft.current.delete(x),Ut.current.delete(x),zt.current.delete(x)},[]);u.useEffect(()=>{const x=te&&et.find(z=>z.deviceId===te)||null;if(!nt||!Wt||!x){Sn.current&&(++va.current,Sn.current="");return}if(ne===x.deviceId&&(P==="active"||P==="warm"||P==="connecting")){oe(z=>z==="warm"?"active":z);return}if(Sn.current===x.deviceId)return;const A=++va.current,D=ne;Sn.current=x.deviceId,(async()=>{if(D){if(oe("stopping"),await ur(D,"control-session-switch").catch(()=>{}),A!==va.current)return;const ve=gn.current;if(ve&&ve!==x.deviceId)try{await ei(ve)}catch(Ne){He(Ne instanceof Error?Ne.message:String(Ne))}finally{gn.current===ve&&(gn.current="",ee(""))}if(A!==va.current)return;Cn(D)}if(A!==va.current)return;if(Gy(x)){try{await Ms(x.deviceId)}catch(ve){A===va.current&&(Sn.current="",oe("error"),He(ve instanceof Error?ve.message:String(ve)));return}if(A!==va.current){await ei(x.deviceId).catch(()=>{});return}gn.current=x.deviceId,ee(x.deviceId),Ut.current.add(x.deviceId)}const z=zs("control",x.deviceId),me=`control-session-${A}-${x.deviceId}`;xi.current.set(z,performance.now()),gi.current.delete(z),er.current.delete(z),Ha.current.delete(z),vi.current.delete(z),X(""),xe(""),O(me),ce(x.deviceId),J(!1),oe("connecting"),va.current===A&&Sn.current===x.deviceId&&(Sn.current="")})()},[et,te,ne,P,Wt,Cn,He,nt,ei,ur,Ms]),u.useEffect(()=>{if(!ne||et.some(D=>D.deviceId===ne))return;const x=ne,A=++va.current;oe("stopping"),ur(x,"control-device-disconnected").catch(()=>{}).finally(()=>{A===va.current&&(Cn(x),J(!1),O(""),X(""),xe(""),ce(D=>D===x?"":D),oe("idle"))})},[et,ne,Cn,ur]);const io=Gy(et.find(x=>x.deviceId===ne));u.useEffect(()=>{if(la.current!==null&&(window.clearTimeout(la.current),la.current=null),!ne||P==="idle"||P==="stopping"||P==="error"||nt||Gt==="wall"){ne&&!nt&&Gt==="wall"&&oe(D=>D==="warm"||D==="active"?"active":D);return}oe(D=>D==="idle"||D==="stopping"?D:"warm");const x=ne,A=++va.current;return la.current=window.setTimeout(()=>{la.current=null,oe("stopping"),ur(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{A===va.current&&(Cn(x),J(!1),O(""),X(""),xe(""),ce(D=>D===x?"":D),oe("idle"))})},HM),()=>{la.current!==null&&(window.clearTimeout(la.current),la.current=null)}},[Gt,ne,P,Cn,nt,ur]),u.useEffect(()=>()=>{la.current!==null&&window.clearTimeout(la.current)},[]),u.useEffect(()=>{const A=ne&&(io&&(P==="connecting"||P==="active"||P==="warm"||P==="stopping")||we&&(P==="active"||P==="warm"))?ne:"";if(ss.current=A,un.current)return;const D=async()=>{for(;;){const z=ss.current,me=gn.current;if(me===z)return;if(me){try{await ei(me)}catch(ve){He(ve instanceof Error?ve.message:String(ve))}finally{gn.current===me&&(gn.current="",ee(""))}continue}if(!z)return;try{await Ms(z)}catch(ve){ss.current=gn.current,He(ve instanceof Error?ve.message:String(ve));return}gn.current=z,ee(z),Ut.current.add(z)}};let $;$=D().finally(()=>{un.current===$&&(un.current=null),gn.current!==ss.current&&qe(z=>z+1)}),un.current=$},[ne,we,P,io,ut,He,ei,Ms,Te]);const Vn=ne&&et.find(x=>x.deviceId===ne)||null,dl=!!(nt&&_e&&P==="active"&&Vn?.sessionId&&B?.deviceId===Vn.deviceId&&B.sessionId===Vn.sessionId&&B.streamPurpose==="control"&&B.commandId&&B.captureGeneration>0&&B.monitorIndex===Ys),{state:Ti,sendInput:ti,stats:Sa,error:nc}=gj(Cs&&dl,k),Ei=u.useCallback((x,A)=>!dl||!Vn||!B||x!==Vn.deviceId?!1:ti(x,{...A,controlSessionId:Vn.sessionId,controlCommandId:B.commandId,captureGeneration:B.captureGeneration}),[dl,Vn,B,ti]),dr=dl&&Ti==="open",{state:Ca,lastFrame:Ri,stats:dn,error:fl}=kj(Ee?.deviceId||"",Cu&&Q,k),ni=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",N],["registry",c],["license",H],["wall-stream",Jo],["control-stream",Js],["control-decode",ge],["remote-input",nc],["remote-audio",fl]];for(const[A,D]of x){const $=String(D||"").trim();if(A==="hub"&&I?.requiresHubRestart&&I.stage==="updating"){ni.current.delete(A);continue}if(!$){ni.current.delete(A);continue}ni.current.get(A)!==$&&(ni.current.set(A,$),He($))}},[fl,ge,Js,N,nc,H,c,He,Jo,I]),u.useEffect(()=>{if(!nt||!_e||!Cs||!dr||!Ee)return;const x=($,z)=>{const me=$.target,ve=me?.tagName?.toLowerCase();me?.isContentEditable||ve==="input"||ve==="textarea"||ve==="select"||($.preventDefault(),$.stopPropagation(),Ei(Ee.deviceId,{type:z,monitorIndex:Da(Vt[Ee.deviceId],ma(Ee)),key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:z==="keydown"?$.repeat:!1,shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}))},A=$=>x($,"keydown"),D=$=>x($,"keyup");return window.addEventListener("keydown",A),window.addEventListener("keyup",D),()=>{window.removeEventListener("keydown",A),window.removeEventListener("keyup",D)}},[Cs,dr,_e,Vt,Ee,Ei,nt]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(tr.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!ne||P!=="connecting"&&P!=="active"&&P!=="warm"||oa!=="open")return;const x=ne,A=zs("control",x),D=window.setInterval(()=>{const $=performance.now();if(document.visibilityState!=="visible"||$-tr.current<gh)return;const z=gi.current.get(A)||0,me=er.current.get(A)||0,ve=is.current.get(A)||0,Ne=xi.current.get(A)||$;xi.current.has(A)||xi.current.set(A,Ne);const Ue=z<=0,Ke=Ue?$-Ne>YM:$-z>Oy,sn=z>0&&(me<=0||$-me>Oy);if(!Ke&&sn){const jr=Ps.current.get(A)||0;$-jr>=Hy&&us(x,"control","decoder-paint-stale");return}if(!Ke)return;const Tn=vi.current.get(A)||0;if(Tn>0){if($-Tn<QM)return;vi.current.delete(A)}const Ya=Ha.current.get(A)||0;if(Ya>=XM){if(ul(Ue?"no first frame":"stale stream"))return;J(!1),Xn(!1),oe("error");return}if($-ve<By(KM,Ya))return;Ns([x],Ue?"control-first-frame-timeout":"control-receive-stale")&&(is.current.set(A,$),vi.current.set(A,$),xi.current.set(A,$),Ha.current.set(A,Ya+1))},650);return()=>window.clearInterval(D)},[oa,ne,P,ul,us,Ns]),u.useEffect(()=>{!ge||Zn!=="mode3-h264-hw"||ul(ge)||(J(!1),Xn(!1),oe("error"))},[ge,Zn,ul]),u.useEffect(()=>{!nt||!ne||!Js||oe(x=>x==="error"?x:"error")},[Js,ne,nt]),u.useEffect(()=>{if(Pa!=="open"||!Be.autoStartLive||Jn.length===0)return;const x=window.setInterval(()=>{const A=performance.now();if(document.visibilityState!=="visible"||A-tr.current<gh)return;const D=1e3/Math.max(1,Ci||Be.fps||1),$=Math.max(ZM,Math.ceil(D*4)),z=[];for(const me of Jn){if(z.length>=tT)break;const ve=zs("wall",me),Ne=gi.current.get(ve)||0;if(Ne<=0)continue;const Ue=is.current.get(ve)||0,Ke=er.current.get(ve)||0,sn=A-Ne>$,Tn=Ke<=0||A-Ke>$;if(!sn&&Tn){const Cr=Ps.current.get(ve)||0;A-Cr>=Hy&&us(me,"wall","decoder-paint-stale");continue}if(!sn)continue;const Ya=Ha.current.get(ve)||0;A-Ue>=By(JM,Ya)&&z.push(me)}if(z.length>0&&ll(z,"wall-frame-stale"))for(const me of z){const ve=zs("wall",me);is.current.set(ve,A),Ha.current.set(ve,(Ha.current.get(ve)||0)+1)}},eT);return()=>window.clearInterval(x)},[Ci,Jn,us,ll,Be.autoStartLive,Be.fps,Pa]),u.useEffect(()=>{Fs(Be.fps),qs.current=Date.now(),xa.current=0},[Be.fps,Be.frameMode,Be.adaptiveLoadShedding]),u.useEffect(()=>{qC({h264DecodeAcceleration:Be.h264DecodeAcceleration})},[Be.h264DecodeAcceleration]),u.useEffect(()=>{if(!Wt||nt||!Be.visibleOnlyLive){nn([]);return}const x=Zr.current;if(!x||typeof IntersectionObserver>"u"){nn(Zl);return}const A=Array.from(x.querySelectorAll("[data-live-device-id]"));if(A.length===0){nn([]);return}const D=new Map,$=()=>{const me=bh(A.map(ve=>String(ve.dataset.liveDeviceId||"")).filter(ve=>(D.get(ve)||0)>0));nn(ve=>yh(ve,me)?ve:me)},z=new IntersectionObserver(me=>{for(const ve of me){const Ne=String(ve.target.dataset.liveDeviceId||"");Ne&&D.set(Ne,ve.isIntersecting?ve.intersectionRatio||.01:0)}$()},{root:null,rootMargin:ia.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return A.forEach(me=>z.observe(me)),$(),()=>z.disconnect()},[Zl,Wt,nt,el,Be.visibleOnlyLive,rt]),u.useEffect(()=>{if(!Be.adaptiveLoadShedding||!Be.autoStartLive||Jn.length===0)return;const x=Be.fps;if(Jn.length<=ia.preserveConfiguredFpsDeviceCount){pn!==x&&(Fs(x),qs.current=Date.now(),xa.current=0);return}if(Pa!=="open"||As.sampleMs<500)return;const A=Date.now(),D=Jn.length*pn,$=As.framesPerSecond,z=As.bytesPerSecond,me=Math.max(0,...Jn.map(sn=>Qn[zs("wall",sn)]?.maxIntervalMs||0)),ve=Math.max(0,...Jn.map(sn=>Ji[zs("wall",sn)]?.maxIntervalMs||0)),Ne=D>8&&$>0&&$<D*.72;if($>ia.maxWallFramesPerSecond||z>ia.maxWallBytesPerSecond||me>ia.maxFrameGapMs||ve>ia.maxFrameGapMs||Ne){xa.current=0;const sn=ia.minFps;if(A-qs.current>=ia.downshiftCooldownMs&&pn>sn){const Tn=Math.max(sn,xT(pn,sn));Tn<pn&&(Fs(Tn),qs.current=A)}return}const Ke=$<ia.maxWallFramesPerSecond*ia.lowLoadFrameRatio&&z<ia.maxWallBytesPerSecond*ia.lowLoadByteRatio;if(!Ke||pn>=x){Ke||(xa.current=0);return}if(!xa.current){xa.current=A;return}if(A-xa.current>=ia.recoveryCooldownMs){const sn=Math.min(x,yT(pn,x));sn>pn&&(Fs(sn),qs.current=A,xa.current=0)}},[pn,Jn.length,Jn,Ji,Qn,Pa,As.bytesPerSecond,As.framesPerSecond,As.lastUpdatedAt,As.sampleMs,Be.adaptiveLoadShedding,Be.autoStartLive,Be.frameMode,Be.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){He("Checkout returned. Waiting for Dodo confirmation."),W();const A=window.setInterval(()=>{W()},4e3),D=window.setTimeout(()=>{window.clearInterval(A)},45e3);return()=>{window.clearInterval(A),window.clearTimeout(D)}}x==="cancelled"&&He("Checkout cancelled.")},[W]),u.useEffect(()=>{!Wt&&_e&&ie(!1),!Wt&&Q&&Ie(!1)},[Q,_e,Wt]),u.useEffect(()=>{const x=Ee?.deviceId||"",A=Oe.current;if(Oe.current=x,!A||A===x)return;const D=++ke.current,$=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&Q&&ae.current.set(x,$);let z=!0;return(async()=>{try{const ve=ae.current.get(A);if(ae.current.delete(A),await Ge(`/api/remote/devices/${encodeURIComponent(A)}/audio/stop`,{method:"POST",body:JSON.stringify(ve?{streamId:ve}:{})},k),!z||D!==ke.current||!Q||!x||!Wt||!tl)return;const Ne=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:$,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k);if(Ne.ok===!1)throw new Error(Ne.error||"Remote audio start failed.")}catch(ve){z&&(ae.current.delete(x),Ie(!1),He(ve instanceof Error?ve.message:String(ve)))}})(),()=>{z=!1}},[Q,Wt,k,tl,Ee?.deviceId]),u.useEffect(()=>{const x=et.map($=>$.deviceId),A=new Set(x),D=new Map(et.map($=>[$.deviceId,$]));L($=>{const z=$.filter(me=>A.has(me));return yh($,z)?$:z}),q($=>$&&A.has($)?$:""),K($=>$&&A.has($)?$:""),Bs($=>{let z=!1;const me={};for(const[ve,Ne]of Object.entries($)){const Ue=D.get(ve);if(!Ue){me[ve]=Ne;continue}const Ke=Da(Ne,Ue?ma(Ue):1);me[ve]=Ke,Ke!==Ne&&(z=!0)}return z?me:$}),Ba($=>{const z=$.filter(me=>A.has(me));return yh($,z)?$:z})},[et,Jr]),u.useEffect(()=>{fu([]),Go(!1)},[ks]),u.useEffect(()=>{!Gs||Us!=="selected"||ls.length>0||Fa.length===0||Ba(Fa.map(x=>x.deviceId))},[Fa,ls.length,Us,Gs]),u.useEffect(()=>{try{localStorage.setItem(hw,Ln)}catch{}},[Ln]),u.useEffect(()=>{mT(Be)},[Be]),u.useEffect(()=>{pT(ft)},[ft]),u.useEffect(()=>{dT(Vt)},[Vt]);const ta=u.useCallback(async()=>{const x=new Set(g);x.add(bn);try{const me=await Ge("/api/remote/status",void 0,bn);Sx({endpoint:me.agentEndpoint,endpoint_candidates:[...me.agentEndpointCandidates||[],...me.hostTargetEndpointCandidates||[]]}).forEach(ve=>x.add(ve))}catch{}const A=[...x].sort((me,ve)=>{const Ne=Ue=>{const Ke=Zc(Ue);return Ke==="local"?0:Ke==="loopback"?1:2};return Ne(me)-Ne(ve)||me.localeCompare(ve)});let D=!1,$="",z=!1;try{for(const me of A){const ve=Zc(me);try{if(await Ge("/api/health",void 0,me),ve==="local")return b(!0),To(!0),me;ve==="loopback"&&(D=!0,$=me)}catch{ve==="local"&&(z=!0)}}return D?(z&&He("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),b(!0),To(!0),$||bn):(b(!1),To(!1),"")}catch{return b(!1),To(!1),""}},[g]),In=async()=>{if(De("auth"),$n(!1),await ta(),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();D?.ok===!1&&(He(D.error||"LiveDesk could not open the system browser for Google sign-in."),De(""));return}const{data:x,error:A}=await ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});A&&(He(A.message),De(""))},ai=async()=>{De("auth"),$n(!1),await ct.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?He("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ge("/api/auth/session",{method:"DELETE"},bn).catch(()=>{}),De("")};u.useEffect(()=>{if(!hn)return;const x=D=>{D.target instanceof Element&&(D.target.closest(".account-popover, .rail-account")||$n(!1))},A=D=>{D.key==="Escape"&&$n(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",A),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",A)}},[hn]);const $a=u.useCallback(async(x={})=>{const A=x.silent===!0,D=x.takeover===!0,$=x.requestLocalAccess===!0;if(!a?.user){A||He("Sign in before publishing this host.","error");return}if(!_n.current){_n.current=!0,A||(De("host"),Ct("Hub · 1/4 · Checking the local runtime…"));try{const me=($?await ta():"")||k||bn;if(!(S||await Ge("/api/remote/status",void 0,me)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");A||Ct("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ne=await Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},me);if(!Ne.ok||!Ne.authenticated)throw new Error(Ne.error||"hub-session-sync-failed");A||Ct("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Ue=await Ge("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:D})},me);if(!Ue.ok)throw new Error(Ue.error||"host-target-failed");if(!A){Ct("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ke=await Ge("/api/hub/status",void 0,me);if(!Ke.hostTargetActive)throw new Error(Ke.hostTargetLease?.lastError||"host-target-not-active-after-sync");const sn=Ke.hostTargetEndpoint||Ke.agentEndpoint||"endpoint ready",Tn=Number(Ke.connectedDeviceCount||0),Ya=Tn>0?`${Tn} client${Tn===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";He(`Hub ready · ${sn} · lease auto-renewal active. ${Ya}`,"success"),($||y)&&(b(!0),To(!0)),M()}d()}catch(z){if(!A){const me=z instanceof Error?z.message:String(z);me.includes("local network access")&&(b(!1),To(!1)),He(`Hub setup failed · ${me}`,"error")}}finally{_n.current=!1,A||De("")}}},[k,y,M,d,ta,a,He,Ct,S]),ds=u.useCallback(async()=>{if(!(!S?.update?.canApply||je==="update")){De("update");try{const x=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},k||bn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const A=[...new Set((x.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],D=!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),$=x.state==="hub-restart-requested"?Date.now():void 0;(A.length>0||D)&&Fe({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:A,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:D,initialHostInstanceId:String(S.hostInstanceId||""),targetManagerVersion:String(x.latestVersion||S.update?.latestVersion||""),targetClientVersion:String(x.latestClientVersion||S.update?.latestClientVersion||""),restartRequestedAt:$,restartDeadlineAt:$?$+Vd:void 0}),Ct(x.state==="hub-restart-requested"?Gd:Ty),M()}catch(x){He(x instanceof Error?x.message:String(x),"error")}finally{De("")}}},[je,k,M,He,Ct,S]);u.useEffect(()=>{const x=I,A=S?.update;if(!x||x.stage!=="updating"||!A)return;const D=A.restartResult?.operationId===x.operationId?A.restartResult:null;if(D?.outcome==="restored"){const Ue=D.error||`The requested Hub ${D.targetVersion||x.targetManagerVersion||"version"} failed verification.`;Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"restored",error:Ue}:Ke),He(`LiveDesk update did not complete. Hub ${D.fallbackVersion||D.appVersion||"the previous version"} was restored. ${Ue}`,"error");return}if(D?.outcome==="failed"){const Ue=D.error||"No verified LiveDesk Hub replacement could be started.";Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),He(`LiveDesk Hub update failed. ${Ue}`,"error");return}if(A.operationId===x.operationId&&A.state==="failed"){const Ue=A.error||"LiveDesk update failed before the Hub replacement completed.";Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),He(Ue,"error");return}if(A.operationId===x.operationId){if(A.state==="hub-restart-requested"&&!x.restartDeadlineAt){const Ue=Date.now();Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,restartRequestedAt:Ue,restartDeadlineAt:Ue+Vd}:Ke),Ct(Gd)}!x.requiresHubRestart&&A.state==="clients-updated"&&(Fe(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),He("LiveDesk clients updated and reconnected successfully.","success"));return}if(!x.requiresHubRestart)return;const $=S.started===!0&&(!x.initialHostInstanceId||S.hostInstanceId&&S.hostInstanceId!==x.initialHostInstanceId),z=!!A.checkedAt,me=Ey(A.currentVersion,x.targetManagerVersion),ve=!x.targetClientVersion||Ey(A.currentClientVersion,x.targetClientVersion),Ne=z&&A.state==="idle"&&A.updateAvailable===!1&&me&&ve;$&&Ne&&(Fe(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),He(`LiveDesk Hub ${A.currentVersion||D?.appVersion||x.targetManagerVersion} restarted and passed version verification.`,"success"))},[He,Ct,S,I]),u.useEffect(()=>{const x=I;if(!x||x.stage!=="updating"||!x.requiresHubRestart||x.restartDeadlineAt)return;const A=()=>{const $=Date.now();Fe(z=>z?.operationId===x.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:$,restartDeadlineAt:$+Vd}:z),Ct(Gd)};if(S?.update?.state==="hub-restart-requested"){A();return}if(!N)return;const D=window.setTimeout(A,$M);return()=>window.clearTimeout(D)},[N,Ct,S?.update?.state,I]),u.useEffect(()=>{const x=I;if(!x||x.stage!=="updating"||!x.requiresHubRestart||!x.restartDeadlineAt)return;const A=Math.max(0,x.restartDeadlineAt-Date.now()),D=x.operationId,$=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${x.targetManagerVersion||"the requested version"} within ${Math.round(Vd/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Fe(me=>me?.operationId===D&&me.stage==="updating"?{...me,stage:"failed",error:z}:me),He(z,"error")},A);return()=>window.clearTimeout($)},[He,I]),u.useEffect(()=>{if(!I||I.stage!=="updated")return;const x=I.operationId,A=window.setTimeout(()=>{Fe(D=>D?.operationId===x?null:D)},8e3);return()=>window.clearTimeout(A)},[I]),u.useEffect(()=>{if(We!==Ty&&We!==Gd)return;const x=S?.update;if(String(x?.state||"")==="failed"){He(x?.error||"LiveDesk update failed.","error");return}I?.stage==="updated"&&He("")},[We,He,S?.update?.error,S?.update?.state,I?.stage]);const Ts=u.useCallback(async()=>{if(!je){De("pin");try{const A=await Ge("/api/remote/pairing-pin",{method:"POST"},k||bn);if(!A.ok)throw new Error(A.error||"pin-rotation-failed");await M(),He("New PIN published.")}catch(x){He(x instanceof Error?x.message:String(x))}finally{De("")}}},[je,k,M]),ro=u.useCallback(x=>{x&&(q(x),L(A=>A.includes(x)?A:[...A,x]))},[]),lo=u.useCallback(x=>{if(!x)return;const A=ir.has(x);q(D=>A&&D===x?"":x),L(D=>A?D.filter($=>$!==x):D.includes(x)?D:[...D,x])},[ir]),Di=u.useCallback(()=>{L([]),q("")},[js]),ac=u.useCallback(()=>{L(et.map(x=>x.deviceId)),q("")},[et]),vn=u.useCallback((x,A)=>{const D=et.find(z=>z.deviceId===x);if(!D)return;const $=ma(D);$<=1||(Bs(z=>{const ve=(Da(z[x],$)+A+$)%$;return{...z,[x]:ve}}),nt&&(Xn(!1),K(x)))},[et,nt]);u.useEffect(()=>{const x=A=>{if(nt&&_e&&Cs)return;const D=A.target,$=D?.tagName?.toLowerCase();D?.isContentEditable||$==="input"||$==="textarea"||$==="select"||((A.ctrlKey||A.metaKey)&&A.key.toLowerCase()==="a"&&(A.preventDefault(),ac()),A.key==="Escape"&&Di())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Cs,Di,_e,ac,nt]);const It=async()=>{if(!Ee||Le)return;const x=Ee;if(!bi.has(x.deviceId)){He(wi);return}$e("view-screen"),Me(!1),ie(!1),Xn(!1),K(x.deviceId),pt("control");try{He(`Opening ${ha(x)} screen.`,"success")}finally{$e("")}},gt=(x,A)=>{const D=et.find(z=>z.deviceId===x),$=Da(A,D?ma(D):1);Bs(z=>({...z,[x]:$})),nt?(Xn(!1),K(x)):ro(x)},Ua=async x=>{if(Xn(!1),K(x),pt("control"),!bi.has(x)){ie(!1),He(wi);return}const A=et.find($=>$.deviceId===x);if(Qi(A?.platform)&&(A?.capabilities?.controlPermission===!1||A?.capabilities?.accessibilityPermission===!1)){ie(!1),He("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}ie(!0),He(`Opening remote control${A?` for ${ha(A)}`:""}.`,"success")},ja=async()=>{if(!Ee){He("Select a workstation before playing audio.");return}if(!Wt){He(wi);return}if(!tl){He("Selected workstation does not report remote audio support yet.");return}if(Le)return;const x=!Q,A=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:ae.current.get(Ee.deviceId);x&&A?ae.current.set(Ee.deviceId,A):x||ae.current.delete(Ee.deviceId),$e("audio"),Ie(x);try{await Ge(`/api/remote/devices/${encodeURIComponent(Ee.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...A?{streamId:A}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k),He(`${x?"Audio started":"Audio stopped"} for ${ha(Ee)}.`,"success")}catch(D){x&&ae.current.delete(Ee.deviceId),Ie(!1),He(D instanceof Error?D.message:String(D),"error")}finally{$e("")}},sc=x=>{const A=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(A)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(A)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(A)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(A)?"The workstation disconnected before the action could be sent.":A},qa=async x=>{if(!Ee||Le)return;const A=Ee,$={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${$} ${ha(A)}? Unsaved work on that computer may be lost.`))){Me(!1),$e(x),He(`Sending ${$.toLowerCase()} request to ${ha(A)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(A.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},k);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");He(`${$} request sent to ${ha(A)}.`,"success"),M()}catch(z){He(sc(z),"error")}finally{$e("")}}},Tu=()=>{Ee&&(Me(!1),be({id:Date.now(),deviceId:Ee.deviceId,instruction:"Run command "}),ie(!1),pt("agents"),He(`Command runner opened for ${ha(Ee)}.`))},ic=async(x,A,D="files")=>{const $=x.filter(Ne=>Ne.file.size>=0);if($.length===0)return{files:0,bytes:0};if(!Wt)throw new Error(wi);if(A.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),me=$.reduce((Ne,Ue)=>Ne+Ue.file.size,0);let ve=0;rs({id:z,status:"reading",progress:1,message:`Preparing ${$.length} ${D}`});try{for(let Ne=0;Ne<$.length;Ne+=1){const Ue=$[Ne],Ke=Ue.file,sn=Math.max(1,Math.ceil(Ke.size/hh));for(let Tn=0;Tn<sn;Tn+=1){const Ya=Tn*hh,Cr=Math.min(Ke.size,Ya+hh),jr=Ke.size===0?new ArrayBuffer(0):await Ke.slice(Ya,Cr).arrayBuffer(),pc=Tn===sn-1;rs({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(ve/Math.max(1,me)*96))),message:`${Ne+1}/${$.length} ${Ue.relativePath}`});const jn=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:A,remoteDirectory:Ln.trim(),name:Ke.name,relativePath:Ue.relativePath,size:Ke.size,type:Ke.type,lastModified:Ke.lastModified,offset:Ya,totalBytes:Ke.size,final:pc,dataBase64:bT(jr)})},k);if(!jn.ok||jn.queued!==A.length)throw new Error(jn.error||`file-chunk-not-queued-${jn.queued}/${A.length}`);ve+=jr.byteLength,await new Promise(rn=>window.setTimeout(rn,0))}}return rs({id:z,status:"queued",progress:100,message:`Sent ${$.length} file${$.length===1?"":"s"} to ${A.length} workstation${A.length===1?"":"s"}`}),window.setTimeout(()=>{rs(Ne=>Ne?.id===z&&Ne.status==="queued"?null:Ne)},4500),{files:$.length,bytes:me}}catch(Ne){throw rs({id:z,status:"failed",progress:100,message:Ne instanceof Error?Ne.message:String(Ne)}),Ne}},Li=async x=>{const A=Fa.length>0?Fa.map(D=>D.deviceId):Ee?[Ee.deviceId]:[];try{await ic(Py(x),A)}catch(D){He(D instanceof Error?D.message:String(D))}},si=async x=>{try{await ic(Py(x),Af)}catch(A){He(A instanceof Error?A.message:String(A))}};u.useEffect(()=>{pu.current=!1},[]);const rc=x=>{x.preventDefault(),x.stopPropagation(),$s(!1),Li(x.dataTransfer.files)},ii=async(x="ltd")=>{if(!a){He("Sign in with Google before checkout.");return}if(R&&x===qt){He("LiveDesk license is already active.");return}if(R&&qt==="pro"){He("LiveDesk Pro is already active.");return}De("checkout");try{const{data:A,error:D}=await ct.functions.invoke("dodo-checkout",{body:{plan:x}});if(D)throw D;if(!A?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(A.checkout_url)}catch(A){He(A instanceof Error?A.message:String(A)),De("")}},fs=nT(),ms=aT(),Es=et.length,hs=ku.filter(x=>Mi.has(x)).length,Ga=cr==="open"&&cl.sampleMs>0?`${cl.framesPerSecond.toFixed(1)} fps`:cr,Re=Ee?nt?ol.get(Ee.deviceId):Mi.get(Ee.deviceId):void 0,fr=Ee?Da(Vt[Ee.deviceId],ma(Ee)):0,_i=Ee?lT(Ee):[],oo=typeof Re?.monitorIndex=="number"?Da(Re.monitorIndex,Math.max(1,Re.monitorCount||1)):fr,xn=(Re&&oo===fr?kw(Re):null)||(Ee?jw(Ee,fr):null),co=xn?`${xn.width}x${xn.height}`:"-",ml=Ee?zs(nt?"control":"wall",Ee.deviceId):"",Mn=ml?Qn[ml]:void 0,ca=ml?Ji[ml]:void 0,vt=ca?.lastInfo,fn=Mn&&Mn.sampleMs>0?`${Mn.framesPerSecond.toFixed(1)} fps`:"waiting",lc=Mn?`#${Mn.totalFrames} / ${fn}`:"waiting",hl=ca&&ca.sampleMs>0?`${ca.framesPerSecond.toFixed(1)} fps`:"waiting",pl=ca&&ca.sampleMs>0?`${ca.changedFramesPerSecond.toFixed(1)} fps`:"waiting",oc=vt?`#${vt.frameSeq} ${vt.decoderLabel} q${vt.queueSize} r${vt.renderQueueSize} d${vt.droppedForLatency} f${vt.decoderFlushCount} t${vt.decoderTimestampFallbacks} io${vt.decoderInputCount}/${vt.decoderOutputCount} ${vt.visualChanged?"changed":"same"}`:"waiting",hr=vt?`${Math.round(vt.queuedForMs)}ms total / ${Math.round(vt.decodedForMs)}ms decode / ${Math.round(vt.scheduledForMs)}ms pace / ${vt.drawMs.toFixed(1)}ms draw`:"-",pr=vt?.targetPaintIntervalMs?`${vt.targetPaintIntervalMs.toFixed(1)}ms / ${(1e3/vt.targetPaintIntervalMs).toFixed(1)} fps`:"-",Mf=ca?`${ca.decoderInputFps.toFixed(1)} in / ${ca.decoderOutputFps.toFixed(1)} out fps`:"waiting",Eu=vt?.canvasPresentation||"-",Tf=vt?`${vt.interactiveBufferWaitCount} waits / ${Math.round(vt.interactiveBufferWaitMs)}ms / ${vt.interactiveQueueDrainCount} drains`:"waiting",Ru=n.framesPerSecond>0?`${n.framesPerSecond.toFixed(1)} fps / p95 ${n.p95IntervalMs.toFixed(1)}ms / max ${n.maxIntervalMs.toFixed(1)}ms / long ${n.longTaskCount} (${Math.round(n.longTaskMs)}ms)`:"waiting",zi=Mn?Re?.frameMode==="mode5-lzo-delta"?`${Yc(Mn.averageFrameBytes)} avg / visual ${Re.deltaVisualTileCount||0} + refresh ${Re.deltaRefreshTileCount||0} / ${Re.deltaTotalTiles||0}`:`${Yc(Mn.averageFrameBytes)} avg / tiny ${Math.round(Mn.tinyFrameRatio*100)}% / repeat ${Math.round(Mn.repeatedFrameRatio*100)}%`:"waiting",cc=Mn&&Mn.sourceSendSampleCount>0?`${Mn.sourceSendAverageMs.toFixed(1)}ms avg / p95 ${Mn.sourceSendP95Ms.toFixed(1)}ms`:"waiting",uo=Ly(Mn),Du=Ly(ca),gr=Mn&&ca?`rx ${_y(Mn)} / paint ${_y(ca)}`:"waiting",gl=Re?Re.frameMode||Re.mode||Re.codec||Re.mimeType:nt?ft.frameMode:Be.frameMode,vr=nt?ft.frameMode:Be.frameMode,fo=gl!==vr?`${vr} -> ${gl}`:vr,Lu=Re?`${Re.width}x${Re.height} ${Yc(Re.byteLength)}`:nt?`${Vs.maxWidth}x${Vs.maxHeight}`:`${Be.maxWidth}x${Be.maxHeight}`,_u=Re?`${Re.isKeyFrame?"key":String(Re.chunkType||"delta")}`:"-",Ii=Re&&Re.monitorCount?`${(Re.monitorIndex??0)+1}/${Re.monitorCount}`:"-",Oi=Re?[`src ${Math.round(Re.sourceGapMs||0)}ms`,`gap ${Math.round(Re.agentSendGapMs||0)}ms`,`tx ${Math.round(Re.agentSendDurationMs||0)}ms`,`pace ${Math.round(Re.agentPaceMs||0)}ms`,`queue ${Math.round(Re.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Re.agentFrameAgeMs||0)}ms`,Re.browserReceivedEpochMs&&Re.receivedAt?`hub ${Math.max(0,Math.round(Re.browserReceivedEpochMs-Date.parse(Re.receivedAt)))}ms`:"",Re.browserReceivedEpochMs&&Re.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Re.browserReceivedEpochMs-Re.hubPacketEpochMs))}ms`:"",Re.droppedByAgent?`drop ${Re.droppedByAgent}`:"",Re.hubIngressDropped?`ingress-drop ${Re.hubIngressDropped}`:"",Re.hubClientDropped?`ws-drop ${Re.hubClientDropped}`:"",Re.captureStageMs?`capture ${Math.round(Re.captureStageMs)}ms`:"",Re.requestedFps?`req ${Math.round(Re.requestedFps)}fps`:"",Re.effectiveFps?`eff ${Math.round(Re.effectiveFps)}fps`:"",Re.captureAverageMs?`avg ${Math.round(Re.captureAverageMs)}ms`:"",Re.captureP95Ms?`p95 ${Math.round(Re.captureP95Ms)}ms`:"",Re.slowFrameCount?`slow ${Math.round(Re.slowFrameCount)}`:"",Re.captureHelperRestarts?`helper ${Math.round(Re.captureHelperRestarts)}`:"",Re.convertMs?`rgb565 ${Math.round(Re.convertMs)}ms`:"",Re.compressMs?`lzo ${Math.round(Re.compressMs)}ms`:"",Re.captureSourceSerial?`cap #${Re.captureSourceSerial}`:"",Re.captureSourceSkipped?`cap skip ${Re.captureSourceSkipped}`:"",Re.frameMode==="mode5-lzo-delta"?`tiles ${Re.deltaVisualTileCount||0}+${Re.deltaRefreshTileCount||0}/${Re.deltaTotalTiles||0}@${Re.deltaTileSize||0}`:"",Re.platformProfile||Re.hardwareEncoder||"-",Re.atlasComposeMs?`atlas ${Re.atlasComposeMs.toFixed(1)}ms`:"",Re.atlasPoolStarved?`pool ${Re.atlasPoolStarved}`:"",Re.atlasTileCount?`tiles ${Re.atlasReadyTiles||0}/${Re.atlasTileCount}`:"",Re.atlasInputRevision?`input #${Re.atlasInputRevision}`:"",Re.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Re.atlasSourceMaxAgeMs)}ms`:"",vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=Ny?`feedback ${Math.round(vt.inputFeedbackMs)}ms`:"",Re.contentHash?`enc ${Re.contentHash.slice(0,6)}`:"",vt?.visualHash?`pix ${vt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "):"-",zu=Ti==="open"?[`${Sa.sentPerSecond.toFixed(1)} hz`,Sa.lastInputSeq>0?`rtt ${Math.round(Sa.lastRoundTripMs)}ms`:"",Sa.lastInputSeq>0?`apply ${Sa.lastAgentApplyMs.toFixed(1)}ms`:"",Sa.droppedPerSecond>0?`drop ${Sa.droppedPerSecond.toFixed(1)}/s`:"",Sa.bufferedAmount>0?`buf ${Yc(Sa.bufferedAmount)}`:"",Sa.lastInputType||"ready"].filter(Boolean).join(" / "):Ti,Iu=vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=Ny?`${Math.round(vt.inputFeedbackMs)}ms / input #${vt.inputFeedbackSeq||0}`:"waiting for changed frame",xr=Q?[Ca,`context ${dn.audioContextState}`,`queue ${Math.round(dn.queuedMs)}ms`,`last ${Math.round(dn.lastPacketAgeMs)}ms`,`accepted ${Math.round(dn.lastAcceptedAgeMs)}ms`,`process ${Math.round(dn.localProcessingAgeMs)}ms`,`remote ${Math.round(dn.browserAgeMs)}/${Math.round(dn.captureAgeMs)}ms`,`heartbeat ${Math.round(dn.captureStatusAgeMs)}ms`,`capture ${dn.captureAlive&&dn.helperAlive?"alive":"down"}`,`drop ${dn.drops}`,`resync ${dn.resyncs}`,`restart ${dn.automaticRestarts}`,dn.pendingDecodes>0?`decode ${dn.pendingDecodes}`:"",Ri?`#${Ri.frameSeq}`:"waiting"].filter(Boolean).join(" / "):"off",vl=Re?`#${Re.frameSeq} ${Nh(Re.receivedAt||Re.capturedAt)}`:"waiting",Rs=Math.max(0,cl.bytesPerSecond*8/1e6),yr=or?.atlasReadyTiles??hs,br=or?.atlasTileCount??hs,Ou=yr===br?`${br} tiles`:`${yr}/${br} tiles`,ri=Gn.length>0,Hu=nt?`1 stream / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`:ri?`1 stream / ${Ou} / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`:`${hs} screens / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`,Ds=N?"offline":S?.started?"online":"starting",wr=Fa.length,mo=nt?Ee?ha(Ee):"No workstation":wr===0?"No workstation":wr>1?`${wr} selected`:Ee?ha(Ee):"No workstation",Zt=Oo[kt]||Oo.en,Va=Zt.sync||Oo.en.sync,Sr=r||U?"checking":R?qt==="pro"?"Pro LTD active":`Plus LTD ${et.length}/${Wc}`:wu?`Free ${et.length}/${Vc}`:`Upgrade ${et.length}/${Vc}`,uc=qt==="pro"?"Pro active":je==="checkout"?"Opening":qt==="ltd"?"Pro $199":"Plus $79",xl=R?qt==="pro"?"Pro active":"Upgrade to Pro LTD":a?je==="checkout"?"Opening checkout":qt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":je==="auth"?"Opening Google":"Sign in to buy",yl=qt==="pro"||je==="checkout"||je==="auth"||r||U,dc=a?.user?.user_metadata,bl=$y(dc,"avatar_url","picture"),ps=$y(dc,"full_name","name")||a?.user?.email||"Google",wl=ps.slice(0,1).toUpperCase(),Fu=S?.started?"Local app ready":"Start LiveDesk",fc=l?.active?"Published":a?"Not published":"Sign in required",mc=/^\d{6}$/.test(S?.pairingPin||"")?S?.pairingPin:"------",ua=nf.find(x=>x.width===Be.maxWidth&&x.height===Be.maxHeight)?.id||`${Be.maxWidth}x${Be.maxHeight}`,ka=Be.atlasTileSizeMode==="auto"?"auto":xh.find(x=>x.width===Be.atlasTileWidth&&x.height===Be.atlasTileHeight)?.id||"320x180",li=vh.find(x=>x.width===ft.maxWidth&&x.height===ft.maxHeight)?.id||`${ft.maxWidth}x${ft.maxHeight}`,hc=tf.find(x=>x.id===Be.frameMode)||tf[0],da=x=>{hi(A=>{const D=x.frameMode?Yh(x.frameMode):A.frameMode,$=x.frameMode!==void 0&&D!==A.frameMode;return{...A,...x,frameMode:D,fps:Qh(x.fps??($?ww(D):A.fps),D)}})},oi=x=>{const A=nf.find(D=>D.id===x);A&&da({maxWidth:A.width,maxHeight:A.height})},fa=x=>{if(x==="auto"){da({atlasTileSizeMode:"auto"});return}const A=xh.find(D=>D.id===x);!A?.width||!A?.height||da({atlasTileSizeMode:"fixed",atlasTileWidth:A.width,atlasTileHeight:A.height})},Ot=x=>{x.frameMode!==void 0&&(X(""),xe("")),as(A=>{const D=x.frameMode?Kh(x.frameMode):A.frameMode,$=x.frameMode!==void 0&&D!==A.frameMode,z=x.fps??($?30:A.fps),me=x.maxWidth??A.maxWidth,ve=x.maxHeight??A.maxHeight;return{...A,...x,frameMode:D,fps:xs(z,20,D==="mode3-h264-hw"?60:30,D==="mode3-h264-hw"?60:30),maxWidth:D==="mode3-h264-hw"?me:Math.min(1920,me),maxHeight:D==="mode3-h264-hw"?ve:Math.min(1080,ve)}})},ho=x=>{const A=vh.find(D=>D.id===x);A&&Ot({maxWidth:A.width,maxHeight:A.height})},Wa=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):Gt==="support"&&window.history.pushState({},"","/")),x==="control"){const A=qn||Ws;if(A&&(Xn(!1),K(A.deviceId)),pt(x),!Wt){ie(!1),He(wi);return}ie(!0);return}x==="agents"&&be(null),x==="wall"&&Kt(A=>A+1),pt(x),ie(!1)},tt=je==="update"||I?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(S?.update?.state||""),Et=!!(S?.update?.updateAvailable&&S.update.canApply||tt||!S&&I),an=u.useCallback(x=>{if(!I?.targetIds.includes(x))return;if(I.stage==="updated")return{state:"updated",label:"Updated"};if(I.stage==="restored"||I.stage==="failed")return{state:"failed",label:I.stage==="restored"?"Update restored":"Update failed",error:I.error};const A=S?.update?.operationId===I.operationId?S.update.targets?.find(D=>D.deviceId===x):void 0;switch(A?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:A.error||S?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return A.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[S?.update,I]);return s.jsxs("main",{className:"app-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ob,{size:25})}),s.jsx("nav",{className:"rail-tools",children:AT.map(x=>{const A=x.icon,D=rf(x.tooltip,kt);return s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server":""} ${Gt===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?void $a({takeover:!0,requestLocalAccess:!0}):Wa(x.id),"data-tooltip":Th(x.label,x.tooltip,kt),"aria-label":`${x.label}. ${D}`,type:"button",disabled:x.id==="sync-server"&&je==="host","aria-busy":x.id==="sync-server"&&je==="host",children:[x.id==="sync-server"&&je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(A,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&je==="host"?"Syncing…":x.label})]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[Et?s.jsxs("button",{className:"rail-update-button",onClick:()=>{ds()},title:I?.error||`Update LiveDesk to ${S?.update?.latestVersion||I?.targetManagerVersion||"latest"}`,type:"button",disabled:tt||!S?.update?.canApply,"aria-busy":tt,children:[tt?s.jsx("span",{className:"rail-update-spinner","aria-hidden":"true"}):s.jsx(Xh,{size:16}),s.jsx("span",{children:tt?S?.update?.targetCount?`${S.update.completedCount||0}/${S.update.targetCount}`:"Updating...":I?.stage==="restored"?"Update restored":I?.stage==="failed"?"Update failed":"Update"})]}):null,NT.map(x=>{const A=x.icon;return s.jsxs("button",{className:`rail-tool compact ${Gt===x.id?"active":""} accent-${x.accent}`,onClick:()=>Wa(x.id),title:x.label,type:"button",children:[s.jsx(A,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${Vl?"active":""}`,onClick:()=>{pt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),$n(!1),ie(!1),Zi(!1)},title:"Settings",type:"button",children:[s.jsx(Wy,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${a?"signed-in":""}`,onClick:()=>{$n(x=>!x)},disabled:r||je==="auth","aria-expanded":hn,title:a?`Account: ${a.user?.email||ps}`:"Sign in with Google",type:"button",children:[a?bl?s.jsx("img",{src:bl,alt:ps,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:wl}):s.jsx(zl,{size:18}),s.jsx("span",{children:a?"Account":"Google"})]}),hn&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:a&&bl?s.jsx("img",{src:bl,alt:ps,referrerPolicy:"no-referrer"}):a?s.jsx("span",{children:wl}):s.jsx(zl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:a?ps:"Account"}),s.jsx("p",{children:a?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:a?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:Fu}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:fc}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:Sr}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:qt==="free"?"Standard banner":"Removed"})]}),a?s.jsxs("button",{className:"account-popover-action",onClick:ai,disabled:je==="auth",type:"button",children:[s.jsx(Yy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:In,disabled:je==="auth",type:"button",children:[s.jsx(zl,{size:16}),"Sign in with Google"]})]})]})]}),s.jsxs("section",{className:`desk-stage ${gu&&!Dn?"dock-open":""} ${nt?"control-stage":""} ${Kl?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(cn,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]})]}),Gs&&!nt&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(Ll,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(ep,{size:15}),s.jsx(m0,{size:16}),s.jsxs("div",{children:[s.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),s.jsxs("span",{children:[s.jsx("small",{children:"Destination"}),s.jsxs("strong",{children:[vu," workstation",vu===1?"":"s"]}),s.jsx("em",{children:Ln.trim()||"Desktop/LiveDeskFiles"})]})]})]}),gu&&!nt&&s.jsxs("div",{className:"top-actions",children:[s.jsx(Cy,{controller:Jl,onError:He}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Screen size",children:kT.map(x=>s.jsx("button",{className:rt===x.id?"active":"",onClick:()=>tn(x.id),type:"button",children:x.label},x.id))})]}),nt&&s.jsx("div",{className:"top-actions",children:s.jsx(Cy,{controller:Jl,onError:He})})]}),Yl?s.jsxs("section",{className:"doc-page",lang:kt,dir:kt==="ar"?"rtl":"ltr",children:[s.jsxs("section",{className:"doc-hero",children:[s.jsxs("div",{className:"doc-hero-copy",children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(af,{size:16}),Zt.eyebrow]}),s.jsx("h2",{children:Zt.title}),s.jsx("p",{children:Zt.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(h0,{size:17}),Zt.languageLabel]}),s.jsx("select",{value:kt,onChange:x=>ze(x.target.value),children:TT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:Zt.sections.map((x,A)=>{const $=[Ur,Gc,Um,Lt,Il][A]||af;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx($,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:x.title}),s.jsx("p",{children:x.body}),s.jsx("ul",{children:x.points.map(z=>s.jsx("li",{children:z},z))})]})]},x.title)})}),Va&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Um,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Va.title}),s.jsx("p",{children:Va.body})]})]}),s.jsx("ul",{children:Va.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(Lt,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Zt.firewall.title}),s.jsx("p",{children:Zt.firewall.body})]})]}),s.jsx("ul",{children:Zt.firewall.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Gc,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Zt.commands.title}),s.jsx("p",{children:Zt.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[Zt.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.manager}),s.jsx("code",{children:ms}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(ms),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.primary}),s.jsx("code",{children:fs}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(fs),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.slot}),s.jsx("code",{children:`${fs} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(`${fs} 3`),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]})]})]})]}):Kl?s.jsx(dM,{hubUrl:k,devices:j,launchRequest:de}):Gs?s.jsx(pN,{hubUrl:k,devices:et,localFeatureAccess:Wt,upgradeNotice:wi,remoteDirectory:Ln,onRemoteDirectoryChange:ns,targetMode:Us,selectedTargetIds:ls,onTargetModeChange:mu,onTargetToggle:x=>Ba(A=>A.includes(x)?A.filter(D=>D!==x):[...A,x]),filePickerRef:ql,folderPickerRef:Gl,onBrowserFileImport:x=>{si(x)},onBrowserFolderImport:x=>{si(x)},onNotice:He,onTransferChange:x=>{if(!x){rs(null);return}const A=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";rs({id:x.id,status:A,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>rs(D=>D?.id===x.id?null:D),4500)}}):ar?s.jsx(ib,{session:a,currentProductKey:"livedesk",appVersion:"",onSignIn:In}):Vl?s.jsx(Dj,{hubUrl:k,runtimeRole:S?.runtimeRole||"hub",runtimeDeviceId:S?.deviceId||"",sessionAccessToken:a?.access_token||"",pin:s.jsxs(Lj,{children:[s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Pair a workstation"}),s.jsx("h3",{children:"Connect another local PC"})]}),s.jsx(en,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:mc}),s.jsxs("button",{className:"text-button ghost compact",onClick:Ts,disabled:!S?.started||je==="pin",type:"button",children:[s.jsx(Is,{size:15}),je==="pin"?"Creating":"New PIN"]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub status"}),s.jsx("h3",{children:Ds})]}),s.jsx("span",{className:`settings-status-dot state-${Ds}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:k||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Es,"/",Jr]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:S?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:Sr})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>$a({takeover:!0,requestLocalAccess:!0}),disabled:!a||je==="host",type:"button",children:[je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),je==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>ii(qt==="ltd"?"pro":"ltd"),disabled:je==="checkout"||qt==="pro",type:"button",children:[s.jsx(Do,{size:16}),uc]})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File transfer"}),s.jsx("h3",{children:"Client destination folder"})]}),s.jsx(Lo,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:Ln,onChange:x=>ns(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(_j,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall stream"}),s.jsx("h3",{children:"Frame delivery"})]}),s.jsx(nu,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Be.frameMode,onChange:x=>da({frameMode:Yh(x.target.value)}),children:tf.map(x=>s.jsxs("option",{value:x.id,children:[x.label," - ",x.detail]},x.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:Be.h264DecodeAcceleration,onChange:x=>da({h264DecodeAcceleration:pf(x.target.value)}),children:Wh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:Be.fps,onChange:x=>da({fps:Qh(x.target.value,Be.frameMode)}),children:Cp.filter(x=>x<=Sw(Be.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ut?"Atlas tile":"Resolution"}),s.jsx("select",{value:ut?ka:ua,onChange:x=>ut?fa(x.target.value):oi(x.target.value),children:(ut?xh:nf).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:Be.quality,onChange:x=>da({quality:xs(x.target.value,20,95,pa.quality)}),children:zy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"Visibility and load"})]}),s.jsx(cn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.autoStartLive,onChange:x=>da({autoStartLive:x.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.visibleOnlyLive,onChange:x=>da({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ut&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.adaptiveSizeByWall,onChange:x=>da({adaptiveSizeByWall:x.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.adaptiveLoadShedding,onChange:x=>da({adaptiveLoadShedding:x.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.showScreenStatus,onChange:x=>da({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:hc.label}),s.jsxs("strong",{children:[zn.maxWidth,"x",zn.maxHeight," / ",pn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>hi(pa),type:"button",children:[s.jsx(Qc,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(zj,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control stream"}),s.jsx("h3",{children:"Low-latency delivery"})]}),s.jsx(Qd,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ft.frameMode,onChange:x=>Ot({frameMode:Kh(x.target.value)}),children:VM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ft.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ft.h264DecodeAcceleration,onChange:x=>Ot({h264DecodeAcceleration:pf(x.target.value)}),children:Wh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:ft.fps,onChange:x=>Ot({fps:xs(x.target.value,20,60,La.fps)}),children:WM.filter(x=>ft.frameMode==="mode3-h264-hw"||x<=30).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:li,onChange:x=>ho(x.target.value),children:vh.filter(x=>ft.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ft.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ft.quality,onChange:x=>Ot({quality:xs(x.target.value,20,95,La.quality)}),children:zy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control behavior"}),s.jsx("h3",{children:"Session display"})]}),s.jsx(en,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ft.showScreenStatus,onChange:x=>Ot({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ft.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Vs.maxWidth,"x",Vs.maxHeight," / ",sr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>as(La),type:"button",children:[s.jsx(Qc,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Ij,{hubUrl:k}),captureGallery:s.jsx(vM,{hubUrl:k,onToast:He}),advancedExtras:s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection commands"}),s.jsx("h3",{children:"Developer setup"})]}),s.jsx(kl,{size:20})]}),s.jsxs("div",{className:"settings-command-list",children:[s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Client"}),s.jsx("code",{children:fs}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(fs),title:"Copy client command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${fs} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(`${fs} 3`),title:"Copy slot command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:ms}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(ms),title:"Copy Hub command",type:"button",children:s.jsx(kl,{size:16})})]})]})]})}):Wl?s.jsxs("section",{className:"pricing-page",children:[s.jsxs("header",{className:"pricing-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(kh,{size:15})," LiveDesk plans"]}),s.jsx("h2",{children:"Choose the plan that fits your wall"}),s.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more workstations, or commercial controls."})]}),s.jsx("button",{className:"pricing-close",onClick:()=>Wa("wall"),title:"Close pricing",type:"button",children:s.jsx(Ja,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:Xl.name}),s.jsxs("small",{children:[et.length,"/",GM(Ks)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${qt==="free"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),s.jsx("strong",{children:"$0"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:Ml.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Vc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:qt==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${qt==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(p0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.ltd.audience}),s.jsx("h3",{children:"Ad-free monitoring"}),s.jsx("p",{children:"More room for personal AI workstations without the standard banner."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Wc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",Ml.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>ii("ltd"):In,disabled:qt!=="free"||je==="checkout"||je==="auth"||r||U,type:"button",children:[s.jsx(Do,{size:16}),qt==="free"?a?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${qt==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(Lt,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.pro.audience}),s.jsx("h3",{children:"For serious operations"}),s.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",Ml.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>ii("pro"):In,disabled:qt==="pro"||je==="checkout"||je==="auth"||r||U,type:"button",children:[s.jsx(Do,{size:16}),qt==="pro"?"Pro active":a?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(en,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx(Qd,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(ox,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(Lo,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(Hn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:a?()=>ii(qt==="ltd"?"pro":"ltd"):In,disabled:yl,type:"button",children:[s.jsx(Do,{size:18}),xl]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Dn?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Zr,className:`screen-wall-panel ${qo?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Di()},onDragEnter:x=>{x.preventDefault(),$s(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&$s(!1)},onDrop:rc,children:[Gn.length>0&&s.jsx("canvas",{ref:lr,className:"atlas-source-canvas",width:Ni?.width||1920,height:Ni?.height||1080,"aria-hidden":"true"}),nt?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Ee&&_i.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:_i.map(x=>s.jsxs("button",{className:x.index===fr?"active":"",onClick:()=>gt(Ee.deviceId,x.index),title:oT(x),type:"button",children:[s.jsx("span",{children:x.name||`Display ${x.index+1}`}),x.width>0&&x.height>0&&s.jsxs("small",{children:[x.width,"x",x.height]})]},x.index))}),Ee?s.jsx(jh,{device:Ee,frame:Re,selected:!1,controlEnabled:Cs&&_e&&dr,showStatus:ft.showScreenStatus,monitorIndex:Da(Vt[Ee.deviceId],ma(Ee)),monitorCount:ma(Ee),onSelect:()=>{},onFocusDevice:()=>K(Ee.deviceId),onOpenControl:()=>Ua(Ee.deviceId),onCycleMonitor:x=>vn(Ee.deviceId,x),onCanvasReady:al,sendInput:Ei,presentationReady:uu},Ee.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(en,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Ee&&Ko&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(Lt,{size:22,"aria-hidden":"true"}),s.jsx("strong",{children:"Accessibility permission required"}),s.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ee&&!Ko&&!uu&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[P!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:P==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:P==="error"?"See the notification for details. Reopen Control to retry.":Js||ge?"Control stream is recovering. See the notification for details.":cr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):ut?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${rt}`,onClick:x=>{x.currentTarget===x.target&&Di()},children:el.map((x,A)=>x?s.jsx(jh,{device:x,frame:Mi.get(x.deviceId),selected:ir.has(x.deviceId),controlEnabled:!1,showStatus:Be.showScreenStatus,monitorIndex:Da(Vt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>lo(x.deviceId),onFocusDevice:()=>ro(x.deviceId),onOpenControl:()=>Ua(x.deviceId),onCycleMonitor:D=>vn(x.deviceId,D),onCanvasReady:$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(x.platform)})==="direct"?ea:rl,sendInput:Ei,updateIndicator:an(x.deviceId),presentationReady:Be.autoStartLive&&ya.includes(x.deviceId)?Tt.has(x.deviceId):void 0,showPresentationSpinner:Be.autoStartLive&&ya.includes(x.deviceId)},x.deviceId):s.jsx(qy,{index:A},`slot-${A}`))}):s.jsx("div",{className:`screen-wall size-${rt}`,onClick:x=>{x.currentTarget===x.target&&Di()},children:el.map((x,A)=>x?s.jsx(jh,{device:x,frame:Mi.get(x.deviceId),selected:ir.has(x.deviceId),controlEnabled:Cs&&_e&&dr&&Ee?.deviceId===x.deviceId,showStatus:Be.showScreenStatus,monitorIndex:Da(Vt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>lo(x.deviceId),onFocusDevice:()=>ro(x.deviceId),onOpenControl:()=>Ua(x.deviceId),onCycleMonitor:D=>vn(x.deviceId,D),onCanvasReady:ea,sendInput:Ei,updateIndicator:an(x.deviceId),presentationReady:Be.autoStartLive&&ya.includes(x.deviceId)?Tt.has(x.deviceId):void 0,showPresentationSpinner:Be.autoStartLive&&ya.includes(x.deviceId)},x.deviceId):s.jsx(qy,{index:A},`slot-${A}`))}),s.jsx(DT,{visible:Su&&!nt})]}),!Vl&&s.jsxs("aside",{className:`right-dock actions-mode ${Dn?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>Zi(x=>!x),"aria-label":Dn?"Show control panel":"Hide control panel",title:Dn?"Show control panel":"Hide control panel",type:"button",children:Dn?s.jsx(ab,{size:18}):s.jsx(tp,{size:18})}),!Dn&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsxs("div",{className:"action-context",children:[s.jsx("span",{children:nt?"Control target":wr>0?"Selection":"No selection"}),s.jsx("strong",{children:mo})]}),s.jsx("input",{ref:Vo,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&Li(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"action-grid",children:[s.jsxs("button",{className:"action-tile primary",onClick:()=>{It()},disabled:!Si||!!Le,type:"button",title:"Open this workstation's screen",children:[Le==="view-screen"?s.jsx(qr,{className:"spin",size:21}):s.jsx(cx,{size:21}),s.jsx("span",{children:Le==="view-screen"?"Opening...":"View Screen"})]}),s.jsxs("button",{className:`action-tile ${_e?"active":""}`,onClick:()=>{if(Ee){if(nt&&_e){ie(!1),He("Remote control paused. Screen viewing stays on.");return}Ua(Ee.deviceId)}},disabled:!Cs||!!Le,title:Ko?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Cs?dr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation",type:"button",children:[s.jsx(Qd,{size:21}),s.jsx("span",{children:_e&&Ti==="connecting"?"Connecting...":"Remote Control"})]}),s.jsxs("button",{className:`action-tile ${Q?"active":""}`,onClick:()=>{ja()},disabled:!Cu||!!Le,type:"button",title:tl?Q?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation",children:[Le==="audio"?s.jsx(qr,{className:"spin",size:21}):s.jsx(ox,{size:21}),s.jsx("span",{children:Le==="audio"?"Updating...":Q?"Mute Audio":"Hear Audio"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{He(`Choose files to send to ${mo}.`),Vo.current?.click()},disabled:!!Le||!Wt||(nt?!Ee:Fa.length===0),type:"button",title:"Choose files and send them to the selected workstation",children:[s.jsx(Lo,{size:21}),s.jsx("span",{children:"Send Files"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{qa("restart")},disabled:!Ee||!Wt||!Ql||!!Le,type:"button",title:Ql?"Restart the selected workstation":"Restart requires a current LiveDesk Client",children:[Le==="restart"?s.jsx(qr,{className:"spin",size:21}):s.jsx(Qc,{size:21}),s.jsx("span",{children:Le==="restart"?"Sending...":"Restart"})]}),s.jsxs("button",{className:`action-tile ${he?"active":""}`,onClick:()=>Me(x=>!x),disabled:!Ee||!Wt||!Ql||!!Le,type:"button",title:Ql?"Lock, sleep, or shut down this workstation":"Power options require a current LiveDesk Client","aria-expanded":he,children:[s.jsx(ux,{size:21}),s.jsx("span",{children:"Power Options"})]}),s.jsxs("button",{className:"action-tile",onClick:Tu,disabled:!Ee||!Wt||!yu||!!Le,type:"button",title:yu?"Open the command runner for this workstation":"Command runner requires a current LiveDesk Client",children:[s.jsx(Gc,{size:21}),s.jsx("span",{children:"Run Command"})]})]}),he&&Ee&&s.jsxs("div",{className:"power-action-menu",role:"group","aria-label":`Power options for ${ha(Ee)}`,children:[s.jsxs("button",{type:"button",onClick:()=>{qa("lock")},children:[s.jsx(Is,{size:16}),"Lock"]}),s.jsxs("button",{type:"button",onClick:()=>{qa("sleep")},children:[s.jsx(g0,{size:16}),"Sleep"]}),s.jsxs("button",{type:"button",className:"danger",onClick:()=>{qa("shutdown")},children:[s.jsx(ux,{size:16}),"Shut Down"]})]})]}),Ee&&os&&s.jsxs("section",{className:"side-panel selected-panel",children:[s.jsxs("div",{className:"machine-detail-head",children:[s.jsxs("div",{className:"panel-title",children:[s.jsx(en,{size:17}),s.jsx("h2",{children:"Machine detail"})]}),s.jsx("span",{className:`machine-health state-${os.state}`,children:os.label})]}),s.jsxs("div",{className:"machine-title",children:[s.jsx("strong",{children:ha(Ee)}),s.jsx("span",{children:os.role})]}),s.jsx("div",{className:"machine-metric-grid",children:os.metrics.map(x=>s.jsxs("article",{className:`machine-metric state-${x.state}`,children:[s.jsx("span",{children:x.label}),s.jsx("strong",{children:x.value}),s.jsx("small",{children:x.detail}),x.ratio!==void 0&&s.jsx("i",{children:s.jsx("b",{style:{width:`${Math.round(x.ratio*100)}%`}})})]},x.id))}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(cn,{size:15}),s.jsx("span",{children:"Stream"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Frames"}),s.jsx("dd",{children:lc}),s.jsx("dt",{children:nt?"Control RX":ri?"Atlas RX":"Wall RX"}),s.jsx("dd",{children:Hu}),s.jsx("dt",{children:"Painted"}),s.jsx("dd",{children:hl}),s.jsx("dt",{children:nt?"Encoded changes":"Visual samples"}),s.jsx("dd",{children:pl}),s.jsx("dt",{children:"Decoder"}),s.jsx("dd",{children:oc}),s.jsx("dt",{children:"Decoder IO"}),s.jsx("dd",{children:Mf}),s.jsx("dt",{children:"Canvas"}),s.jsx("dd",{children:Eu}),s.jsx("dt",{children:"Control buffer"}),s.jsx("dd",{children:Tf}),s.jsx("dt",{children:"Browser RAF"}),s.jsx("dd",{children:Ru}),s.jsx("dt",{children:"Latency"}),s.jsx("dd",{children:hr}),s.jsx("dt",{children:"Cadence"}),s.jsx("dd",{children:pr}),s.jsx("dt",{children:"Source send"}),s.jsx("dd",{children:cc}),s.jsx("dt",{children:"Packet mix"}),s.jsx("dd",{children:zi}),s.jsx("dt",{children:"Receive gap"}),s.jsx("dd",{children:uo}),s.jsx("dt",{children:"Paint gap"}),s.jsx("dd",{children:Du}),s.jsx("dt",{children:"Seq gap"}),s.jsx("dd",{children:gr}),s.jsx("dt",{children:"Selected"}),s.jsx("dd",{children:vl}),s.jsx("dt",{children:"Requested"}),s.jsx("dd",{children:fo}),s.jsx("dt",{children:"Mode"}),s.jsx("dd",{children:gl}),s.jsx("dt",{children:"Chunk"}),s.jsx("dd",{children:_u}),s.jsx("dt",{children:"Size"}),s.jsx("dd",{children:Lu}),s.jsx("dt",{children:"Native"}),s.jsx("dd",{children:co}),s.jsx("dt",{children:"Monitor"}),s.jsx("dd",{children:Ii}),s.jsx("dt",{children:"Source"}),s.jsx("dd",{children:Oi}),s.jsx("dt",{children:"Input"}),s.jsx("dd",{children:zu}),s.jsx("dt",{children:"Audio"}),s.jsx("dd",{children:xr}),nt&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Visual feedback"}),s.jsx("dd",{children:Iu})]})]})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Gc,{size:15}),s.jsx("span",{children:"Local services"})]}),s.jsx("div",{className:"tool-probe-list",children:os.tools.map(x=>s.jsxs("span",{className:`tool-probe state-${x.status}`,children:[s.jsx("b",{children:x.label}),s.jsx("em",{children:x.detail})]},x.id))})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Bo,{size:15}),s.jsx("span",{children:"Workload"})]}),s.jsxs("div",{className:"workload-card",children:[s.jsx("strong",{children:os.taskLabel}),s.jsx("span",{children:os.taskStatus}),os.taskSummary&&s.jsx("p",{children:os.taskSummary})]})]}),s.jsxs("div",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Ur,{size:15}),s.jsx("span",{children:"System"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Platform"}),s.jsxs("dd",{children:[Ee.platform||"-"," ",Ee.arch||""]}),s.jsx("dt",{children:"Release"}),s.jsx("dd",{children:_a(Ee.status,"release")||"-"}),s.jsx("dt",{children:"Uptime"}),s.jsx("dd",{children:Aw(ln(Ee.status,"uptimeSec"))}),s.jsx("dt",{children:"Last seen"}),s.jsx("dd",{children:Nh(Ee.lastSeenAt||Ee.connectedAt)}),s.jsx("dt",{children:"Agent"}),s.jsx("dd",{children:Ee.agentVersion||"-"}),s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:Ee.remoteAddress||"-"})]})]}),s.jsxs("button",{className:"text-button full",onClick:()=>{It()},disabled:!Si||!!Le,type:"button",children:[s.jsx(cx,{size:16}),"View screen"]})]})]})]})]})})]}),Un&&s.jsxs("aside",{className:`transfer-bar state-${Un.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Un.status==="queued"?s.jsx(Hn,{size:18}):Un.status==="failed"?s.jsx(Ja,{size:18}):s.jsx(Jy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:Un.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Un.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,Un.progress)),"%"]})]}),wn&&s.jsxs("aside",{className:`livedesk-toast tone-${wn.tone}`,role:wn.tone==="error"?"alert":"status","aria-live":wn.tone==="error"?"assertive":"polite","aria-busy":wn.tone==="progress",children:[wn.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:wn.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>He(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ja,{size:15})})]})]})}function _T(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function zT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of _T())try{const v=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!v.ok)continue;const y=(await v.json()).role==="hub"?"hub":"client";c=!0,l||r(y);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&r("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?s.jsx(wC,{}):s.jsx(LT,{}):s.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[s.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),s.jsx("strong",{children:"Starting LiveDesk"}),s.jsx("p",{children:"Loading this computer's assigned role..."})]})}j0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(zT,{})}));
17
+ Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},v=c.recording?`Stop recording · ${qd(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,b=c.timelapse?`Stop timelapse · ${qd(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return s.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[s.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{p(n.takeScreenshot)},type:"button",children:s.jsx(u0,{size:17})}),s.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":v,title:v,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?s.jsxs(s.Fragment,{children:[s.jsx(lx,{size:14,fill:"currentColor"}),s.jsx("span",{children:qd(c.recordingStartedAt)})]}):s.jsx(tb,{size:18})}),s.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void p(n.saveLast30Seconds):void g(),type:"button",children:[s.jsx(d0,{size:17}),s.jsx("small",{children:"30s"})]}),s.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":b,title:b,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?s.jsxs(s.Fragment,{children:[s.jsx(lx,{size:14,fill:"currentColor"}),s.jsx("span",{children:qd(c.timelapseStartedAt)})]}):s.jsx(f0,{size:17})})]})}async function xM(n,a={}){const r=n.filter(y=>y.canvas&&y.canvas.width>0&&y.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,r.length)/d)),p=Math.floor(l/d),g=Math.floor(c/m),v=document.createElement("canvas");v.width=Math.max(320,p*d),v.height=Math.max(180,g*m);const b=v.getContext("2d",{alpha:!1});if(!b)return v;b.fillStyle="#0b1220",b.fillRect(0,0,v.width,v.height),b.font="600 14px system-ui, sans-serif",b.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const w=r[y],S=y%d,j=Math.floor(y/d),N=S*p,M=j*g,k=w.canvas,E=Math.min(p/k.width,g/k.height),R=Math.max(1,Math.floor(k.width*E)),U=Math.max(1,Math.floor(k.height*E)),H=N+Math.floor((p-R)/2),W=M+Math.floor((g-U)/2);b.drawImage(k,H,W,R,U),a.includeLabels!==!1&&(b.fillStyle="rgba(4, 10, 20, .74)",b.fillRect(N,M+g-28,p,28),b.fillStyle="#f8fafc",b.fillText(w.label,N+9,M+g-9))}return v}function yM(n){return n?.signature||"none"}function bM(n){return n?.label||"No capture target"}function jy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function wM(){const n=new Date,a=r=>String(r).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function SM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function CM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${SM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${wM()}.png`}async function jM(n,a,r){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await uw(l,{kind:"screenshot",fileName:CM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function dw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function kM(n,a){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${r}.webm`:`LiveDesk_Recording_${l}_${r}.webm`}async function fw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=dw();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await fM({kind:r,fileName:kM(r,n.target),mimeType:a,target:n.target},n.hubUrl),c=n.canvas.captureStream(n.frameRequests?0:n.fps),d=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),m=performance.now();let p=0,g=!1,v=null,b=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const w=p++;b=b.then(()=>mM(l.sessionId,w,y.data,n.hubUrl).then(()=>{})).catch(S=>{v=v||(S instanceof Error?S:new Error(String(S))),n.onError?.(v)})},d.onerror=()=>{v=new Error("Video recording stopped unexpectedly."),n.onError?.(v)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await b,v)throw await wy(l.sessionId,n.hubUrl).catch(()=>{}),v;await hM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await wy(l.sessionId,n.hubUrl).catch(()=>{}))}}}class AM{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=dw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const d=performance.now();for(this.segments.push({blob:c.data,at:d}),this.totalBytes+=c.data.size;this.segments.length>1&&(d-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const m=this.segments.shift();this.totalBytes-=m.blob.size}},this.recorder.start(1e3)}stop(){const a=this.recorder;this.recorder=null,a&&a.state!=="inactive"&&(a.ondataavailable=null,a.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),d=`LiveDesk_Last30s_${a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await uw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function NM(n,a,r,l,c){const d=await fw({canvas:n,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});d.requestFrame?.();const m=window.setInterval(()=>d.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const mw="livedesk.captureSettings";function MM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(mw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function TM(n){const[a,r]=u.useState(MM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,g]=u.useState(0),[v,b]=u.useState(!1),y=u.useRef(void 0),w=u.useRef(!1),S=u.useRef(""),j=u.useRef(null),N=u.useRef(null),M=u.useRef(null),k=u.useRef(null),E=u.useRef(new AM),R=n.sourceRegistry.resolveCurrentTarget(),U=yM(R),H=bM(R),W=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(mw,JSON.stringify(a)),!w.current)return;const X=JSON.stringify(a);X!==S.current&&(S.current=X,Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:y.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(P=>{y.current=Number(P.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let X=!0;return Ge("/api/settings",void 0,n.hubUrl).then(P=>{if(!X)return;const oe=P.settings?.filesAudio||{},we=typeof oe.rollingBufferEnabled=="boolean"?oe.rollingBufferEnabled:a.rollingEnabled,J=oe.recordingQuality==="high"?"high":"standard",B=[5,10,30,60].includes(Number(oe.timelapseIntervalSeconds))?Number(oe.timelapseIntervalSeconds):a.timelapseIntervalSeconds,pe=typeof oe.includeRemoteCursor=="boolean"?oe.includeRemoteCursor:a.includeRemoteCursor,ge={rollingEnabled:we,recordingQuality:J,timelapseIntervalSeconds:B,includeRemoteCursor:pe};y.current=Number(P.revision||0),S.current=JSON.stringify(ge),w.current=!0,r(ge)}).catch(()=>{w.current=!0}),()=>{X=!1}},[n.hubUrl]);const _=u.useCallback(async X=>{if(X.sourceCanvas&&X.sourceCanvas.width>0&&X.sourceCanvas.height>0)return{target:jy(X),canvas:X.sourceCanvas,cleanup:()=>{}};const P=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let oe=!1;const we=window.setInterval(async()=>{if(oe)return;const J=await n.sourceRegistry.composeWall(X.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!J||oe||((P.width!==J.width||P.height!==J.height)&&(P.width=J.width,P.height=J.height),P.getContext("2d")?.drawImage(J,0,0))},100);return{target:jy(X),canvas:P,cleanup:()=>{oe=!0,window.clearInterval(we)}}},[n.sourceRegistry]);u.useEffect(()=>{const X=E.current;if(!a.rollingEnabled||!R||!W){X.stop(),g(0);return}let P=!1,oe=null;return(async()=>{try{if(oe=await _(R),P)return;await X.start(oe.canvas,oe.target);const J=window.setInterval(()=>g(Math.round(X.seconds)),500),B=()=>{window.clearInterval(J),oe?.cleanup()};X.__cleanup=B}catch(J){P||n.onToast(J instanceof Error?J.message:String(J))}})(),()=>{P=!0,X.stop(),X.__cleanup?.(),X.__cleanup=void 0,g(0)}},[_,n.onToast,a.rollingEnabled,U,W]);const L=u.useCallback(X=>r(P=>({...P,rollingEnabled:X})),[]),le=u.useCallback(X=>r(P=>({...P,recordingQuality:X})),[]),q=u.useCallback(X=>r(P=>({...P,timelapseIntervalSeconds:X})),[]),te=u.useCallback(async()=>{const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");b(!0);let P=null;try{P=await _(X),await jM(P.canvas,P.target,n.hubUrl),n.onToast("Screenshot saved")}finally{P?.cleanup(),b(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(M.current)throw new Error("Stop the timelapse before recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(X),oe=await fw({canvas:P.canvas,target:P.target,fps:X.type==="control"?30:15,hubUrl:n.hubUrl,onError:we=>n.onToast(we.message)});N.current=P.cleanup,j.current=oe,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ne=u.useCallback(async()=>{const X=j.current;if(X){b(!0);try{await X.stop(),n.onToast("Recording saved")}finally{j.current=null,N.current?.(),N.current=null,c(0),b(!1)}}},[n.onToast]),ce=u.useCallback(async()=>{if(j.current||M.current)throw new Error("Last 30s is unavailable during a recording.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");b(!0);try{await E.current.save(X,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{b(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),V=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const X=n.sourceRegistry.resolveCurrentTarget();if(!X)throw new Error("화면이 준비된 후 다시 시도하세요.");const P=await _(X),oe=await NM(P.canvas,P.target,a.timelapseIntervalSeconds,n.hubUrl,we=>n.onToast(we.message));k.current=P.cleanup,M.current=oe,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),O=u.useCallback(async()=>{const X=M.current;if(X){b(!0);try{await X.stop(),n.onToast("Timelapse saved")}finally{M.current=null,k.current?.(),k.current=null,m(0),b(!1)}}},[n.onToast]);return u.useEffect(()=>{const X=P=>{!j.current&&!M.current||(P.preventDefault(),P.returnValue="")};return window.addEventListener("beforeunload",X),()=>window.removeEventListener("beforeunload",X)},[]),u.useEffect(()=>()=>{E.current.stop(),j.current?.cancel(),M.current?.cancel(),N.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!M.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:v,targetLabel:H}),[p,v,l,a.rollingEnabled,H,d]),settings:a,videoSupported:W,targetKey:U,setRollingEnabled:L,setRecordingQuality:le,setTimelapseInterval:q,takeScreenshot:te,startRecording:K,stopRecording:ne,saveLast30Seconds:ce,startTimelapse:V,stopTimelapse:O}}const EM=120,RM=999,Vc=5,Wc=30,DM=Number.POSITIVE_INFINITY,hw="livedesk.remoteDirectory",Uh="livedesk.localHubAccessEnabled",pw="livedesk.streamSettings",qh=16,gw="livedesk.controlStreamSettings",Gh=6,vw="livedesk.wallMonitorSelections",xw=1,hh=512*1024,Vh="".trim(),yw="".trim(),ky="livedesk-adsense-script",ph=!!Vh&&!!yw,LM=1e3/60,gh=1500,_M=650,zM=1800,IM=650,OM=2500,Ay=1500,Ny=15e3,HM=6e4,My=240,BM=1024,FM=480,PM=270,Ty="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Gd="LiveDesk is replacing the Hub and verifying the requested version.",Vd=5*6e4,$M=5e3;function UM(n,a){if(a.deviceId!==n.deviceId)return!1;const r=Number(a.browserReceivedEpochMs);if(!Number.isFinite(r)||r<n.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==n.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===n.frameMode}const Ml={free:{name:"Free",price:"$0",limit:Vc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Wc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:DM,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},bw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ey(n,a){const r=m=>{const g=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const v=g[4]?g[4].split(".").map(b=>/^\d+$/.test(b)?b.length>1&&b.startsWith("0")?Number.NaN:Number(b):b):[];return v.some(b=>typeof b=="number"&&!Number.isFinite(b))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:v}},l=r(n),c=r(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const p=l.prerelease[m],g=c.prerelease[m];if(p===void 0||g===void 0)return g===void 0;if(p!==g){if(typeof p=="number"&&typeof g=="number")return p>g;if(typeof p=="number")return!1;if(typeof g=="number"||p>g)return!0;if(p<g)return!1}}return!0}function zs(n,a){return`${n}:${a}`}const pa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:bw["mode3-h264-hw"],maxWidth:1920,maxHeight:1080,atlasTileWidth:320,atlasTileHeight:180,atlasTileSizeMode:"auto",quality:75,autoStartLive:!0,showScreenStatus:!0,visibleOnlyLive:!0,adaptiveLoadShedding:!0,adaptiveSizeByWall:!0},La={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function ef(n,a){if(n.length===0)return 0;const r=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*a)-1));return r[l]}function Sp(n,a){n.push(a),n.length>My&&n.splice(0,n.length-My)}function Ry(n,a){n.sampleFrames=0,n.sampleStartedAt=a,n.intervalCount=0,n.intervalSumMs=0,n.minIntervalMs=Number.POSITIVE_INFINITY,n.maxIntervalMs=0,n.intervalSamplesMs.length=0,n.seqGapCount=0,n.maxSeqGap=0}function Dy(n,a,r){if(n.lastAt!==void 0){const l=Math.max(0,a-n.lastAt);n.intervalCount+=1,n.intervalSumMs+=l,n.minIntervalMs=Math.min(n.minIntervalMs,l),n.maxIntervalMs=Math.max(n.maxIntervalMs,l),Sp(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=r-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=r}function Ly(n){return!n||n.intervalCount<=0?"waiting":`${Math.round(n.averageIntervalMs)}ms avg / p95 ${Math.round(n.p95IntervalMs)}ms / max ${Math.round(n.maxIntervalMs)}ms`}function qM(){const[n,a]=u.useState({framesPerSecond:0,averageIntervalMs:0,p95IntervalMs:0,maxIntervalMs:0,longTaskCount:0,longTaskMs:0});return u.useEffect(()=>{let r=0,l=performance.now(),c=0,d=0,m=[],p=0,g=0,v=null;const b=w=>{document.visibilityState==="visible"?(c+=1,d>0&&Sp(m,Math.max(0,w-d)),d=w):d=0,r=window.requestAnimationFrame(b)};try{v=new PerformanceObserver(w=>{for(const S of w.getEntries())p+=1,g+=S.duration}),v.observe({entryTypes:["longtask"]})}catch{v=null}r=window.requestAnimationFrame(b);const y=window.setInterval(()=>{const w=performance.now(),S=Math.max(1,w-l),j=m.reduce((N,M)=>N+M,0);a({framesPerSecond:c*1e3/S,averageIntervalMs:m.length>0?j/m.length:0,p95IntervalMs:ef(m,.95),maxIntervalMs:m.length>0?Math.max(...m):0,longTaskCount:p,longTaskMs:g}),l=w,c=0,m=[],p=0,g=0},1e3);return()=>{window.cancelAnimationFrame(r),window.clearInterval(y),v?.disconnect()}},[]),n}function _y(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function GM(n){return Number.isFinite(n)?String(n):"30+"}const tf=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Wh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],VM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],nf=[{id:"640x360",label:"Compact",width:640,height:360},{id:"960x540",label:"Standard",width:960,height:540},{id:"1280x720",label:"HD",width:1280,height:720},{id:"1920x1080",label:"Full HD",width:1920,height:1080},{id:"2560x1440",label:"QHD",width:2560,height:1440},{id:"3840x2160",label:"4K",width:3840,height:2160}],vh=nf.filter(n=>n.width>=1280),xh=[{id:"auto",label:"Auto by wall size"},{id:"320x180",label:"Standard 320x180",width:320,height:180},{id:"480x270",label:"Sharp 480x270",width:480,height:270}],Cp=[1,2,5,8,12,20,30],WM=[20,30,60],zy=[45,60,75,90],Iy={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},small:{maxWidth:640,maxHeight:360}},ia={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,small:32},maxWallFramesPerSecond:di.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},Oy=2200,YM=8e3,KM=3500,QM=7e3,XM=2,ZM=2600,JM=4200,eT=750,tT=2,Hy=4200;function By(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function tu(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function ha(n){return n.deviceName||n.hostname||n.deviceId}function nT(){return"npx -y --prefer-online livedesk@latest client"}function aT(){return"npx -y --prefer-online livedesk@latest"}function sT(){try{return localStorage.getItem(hw)||""}catch{return""}}function iT(){try{return localStorage.getItem(Uh)==="1"}catch{return!1}}function To(n){try{n?localStorage.setItem(Uh,"1"):localStorage.removeItem(Uh)}catch{}}function xs(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Yh(n){const a=String(n||"").trim();return tf.some(r=>r.id===a)?a:pa.frameMode}function pf(n){const a=String(n||"").trim();return Wh.some(r=>r.id===a)?a:pa.h264DecodeAcceleration}function Kh(n){return n==="mode3-h264-hw"?n:La.frameMode}function ww(n){return bw[n]||12}function Sw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Qh(n,a){return xs(n,1,Sw(a),ww(a))}function Fl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ma(n){const a=Fl(n.status),r=Fl(a.screens),l=Fl(n.capabilities),c=[a.monitorCount,a.screenCount,r.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function Pr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function rT(n){const a=Fl(n.status),l=[Fl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Fl(d));return[]}function Cw(n,a){const r=rT(n),l=r.find(g=>Number(g.index)===a)||r[a]||r[0]||{},c=Pr(l.width),d=Pr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function lT(n){const a=ma(n);return Array.from({length:a},(r,l)=>Cw(n,l))}function oT(n){const a=[n.name||`Display ${n.index+1}`];return n.width>0&&n.height>0&&a.push(`${n.width}x${n.height}`),n.primary&&a.push("Primary"),a.join(" - ")}function jw(n,a){const r=Cw(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Fl(n.status),c=Pr(l.screenWidth||l.width),d=Pr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function kw(n){if(!n)return null;const a=Pr(n.sourceWidth)||Pr(n.width),r=Pr(n.sourceHeight)||Pr(n.height);return a>0&&r>0?{width:a,height:r}:null}function cT(n,a,r){const d=((typeof a?.monitorIndex=="number"?Da(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?kw(a):null)||jw(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Wd=16/9;function Da(n,a){const r=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(n));return Number.isFinite(l)?Math.max(0,Math.min(r-1,l)):0}function uT(){try{const n=localStorage.getItem(vw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==xw||!r||typeof r!="object"||Array.isArray(r))return{};const l={};for(const[c,d]of Object.entries(r)){const m=c.trim(),p=Math.floor(Number(d));!m||!Number.isFinite(p)||(l[m]=Math.max(0,Math.min(63,p)))}return l}catch{return{}}}function dT(n){try{localStorage.setItem(vw,JSON.stringify({version:xw,selections:n}))}catch{}}function fT(){try{const n=JSON.parse(localStorage.getItem(pw)||"{}"),a=Number(n.version);if(![qh,15,14,13,12,11].includes(a))return pa;const r=Yh(n.frameMode),l=xs(n.maxWidth,320,3840,pa.maxWidth),c=xs(n.maxHeight,180,2160,pa.maxHeight);return{frameMode:r,h264DecodeAcceleration:pf(n.h264DecodeAcceleration),fps:a<qh&&r==="mode3-h264-hw"?pa.fps:Qh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:Number(n.atlasTileWidth)>=480?480:320,atlasTileHeight:Number(n.atlasTileHeight)>=270?270:180,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:xs(n.quality,20,95,pa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:pa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:pa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:pa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:pa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:pa.adaptiveSizeByWall}}catch{return pa}}function mT(n){try{localStorage.setItem(pw,JSON.stringify({...n,version:qh}))}catch{}}function hT(){try{const n=JSON.parse(localStorage.getItem(gw)||"{}"),a=Number(n.version);if(![Gh,5,4,3,2,1].includes(a))return La;const r=xs(n.fps,20,60,La.fps),l=a<Gh;return{frameMode:l?La.frameMode:Kh(n.frameMode),h264DecodeAcceleration:l?La.h264DecodeAcceleration:pf(n.h264DecodeAcceleration),fps:l?La.fps:r,maxWidth:xs(n.maxWidth,1280,3840,La.maxWidth),maxHeight:xs(n.maxHeight,720,2160,La.maxHeight),quality:xs(n.quality,20,95,La.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:La.showScreenStatus}}catch{return La}}function pT(n){try{localStorage.setItem(gw,JSON.stringify({...n,version:Gh}))}catch{}}function yh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function bh(n){return[...new Set(n.filter(Boolean))].sort()}function gT(n){return ia.fallbackVisibleCounts[n]||ia.fallbackVisibleCounts.large}function vT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:480,maxHeight:270}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Iy[a]||Iy.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function xT(n,a=ia.minFps){const r=[...Cp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function yT(n,a){return[...Cp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Yc(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;const c=l===0||r>=100?0:1;return`${r.toFixed(c)} ${a[l]}`}function Fy(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,r=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/r))}GB`}function wh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const r=Math.max(0,n-Math.max(0,Number(a||0)));return`${Fy(r)} / ${Fy(n)}`}function bT(n){const a=new Uint8Array(n),r=32768;let l="";for(let c=0;c<a.length;c+=r){const d=a.subarray(c,c+r);l+=String.fromCharCode(...d)}return btoa(l)}function Py(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const r=a.webkitRelativePath||a.name;return{file:a,relativePath:r,fingerprint:`${a.size}:${a.lastModified}`}})}function wT(n){return n===1?"middle":n===2?"right":"left"}function $y(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Uy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=RM?a:0}const ST={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function CT(n,a,r){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(r==="failed")return"Task failed";const l=n==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return n==="critical"?"Issue":"Check";const d=ST[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function jf(n,a){const r=a.split(".");let l=n;for(const c of r){if(l==null)return;if(Array.isArray(l)){const d=Number(c);l=Number.isInteger(d)?l[d]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function ln(n,...a){for(const r of a){const l=jf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function _a(n,...a){for(const r of a){const l=jf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function jT(n,...a){for(const r of a){const l=jf(n,r);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function Ki(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Sh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ki((n-Math.max(0,a))/n)}function Eo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function Ch(n){return n===void 0||!Number.isFinite(n)?"":n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}Gb/s`:`${Math.round(n)}Mb/s`}function Tl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function Aw(n){return!Number.isFinite(n)||!n||n<=0?"-":n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`}function Yd(n,a,r){const l=jf(n,`tools.${a}`),c=_a(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=jT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=_a(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=_a(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||d===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(g="offline"),{id:a,label:r,status:g,detail:g==="offline"?"offline":m||(p?`:${p}`:g==="unknown"?"not reported":g)}}function Nw(n){const a=n.status||{},r=ln(a,"cpu.cores","cpuCores","processorCount"),l=ln(a,"loadavg.0","cpu.load1"),c=Ki(ln(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&l!==void 0?l/Math.max(1,r):void 0)),d=ln(a,"memory.totalBytes","totalMem"),m=ln(a,"memory.freeBytes","freeMem"),p=Ki(ln(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Sh(d,m),g=ln(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),v=ln(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),b=Ki(ln(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Sh(g,v),y=ln(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),w=Ki(ln(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),S=_a(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=ln(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),N=ln(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),M=Ki(ln(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Sh(j,N),k=ln(a,"gpu.temperatureC","thermal.gpuC"),E=Ki(ln(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=_a(a,"npu.name","npu.model","accelerators.npu.name"),U=ln(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),H=ln(a,"network.rxMbps","network.receiveMbps","network.downMbps"),W=ln(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=ln(a,"network.latencyMs","network.rttMs"),L=Ki(ln(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),le=_a(a,"network.link","network.interface","network.name"),q=y===void 0?void 0:Ki((y-35)/60),te=_a(a,"workload.role","role","lane")||(tu(n,"aiAssist")?"Agent worker":tu(n,"taskDispatch")?"Task worker":"Local machine"),K=_a(n.latestTask,"status")||_a(a,"workload.status")||"idle",ne=_a(n.latestTask,"title","instructionPreview")||_a(a,"workload.title"),ce=_a(n.latestTask,"resultSummary","error","instructionPreview")||_a(a,"workload.summary"),V=[Yd(a,"ollama","Ollama"),Yd(a,"lmStudio","LM Studio"),Yd(a,"comfyui","ComfyUI"),Yd(a,"stableDiffusion","Stable Diffusion")],O=V.some(J=>J.status!=="unknown"),Y=Date.parse(n.lastSeenAt||n.connectedAt||""),X=Number.isFinite(Y)?Date.now()-Y:0;let P="online";n.connected?X>5*6e4?P="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(w??0)>=.96||(M??0)>=.96||(E??0)>=.96||(p??0)>=.94||(b??0)>=.94||(_??0)>=200||K==="failed"?P="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(w??0)>=.86||(M??0)>=.88||(E??0)>=.86||(p??0)>=.82||(b??0)>=.86||(_??0)>=80?P="warn":(["queued","running","targeted"].includes(K)||V.some(J=>J.status==="busy"))&&(P="busy"):P="offline";const oe=V.filter(J=>J.status==="online"||J.status==="busy").length,we=[{id:"cpu",label:"CPU",value:Eo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Tl(c,.92,.78)},{id:"memory",label:"RAM",value:Eo(p),detail:wh(d,m),ratio:p,state:Tl(p,.92,.78)},{id:"disk",label:"DISK",value:Eo(b),detail:wh(g,v),ratio:b,state:Tl(b,.92,.82)},{id:"gpu",label:"GPU",value:Eo(w),detail:S||(j&&N!==void 0?`${Yc(N)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:w,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":Tl(w,.96,.86)},{id:"vram",label:"VRAM",value:Eo(M),detail:wh(j,N),ratio:M,state:Tl(M,.96,.88)},{id:"npu",label:"NPU",value:E!==void 0?Eo(E):U!==void 0?`${Math.round(U)} TOPS`:"-",detail:R||(U!==void 0?"neural engine":"not reported"),ratio:E,state:Tl(E,.96,.86)},{id:"temp",label:"TEMP",value:y===void 0?"-":`${Math.round(y)}C`,detail:oe>0?`${oe} local tools`:`uptime ${Aw(ln(a,"uptimeSec"))}`,ratio:q,state:y===void 0?"unknown":y>=86?"critical":y>=78?"warn":"good"},{id:"network",label:"NET",value:Ch(H)||(_!==void 0?`${Math.round(_)}ms`:le||"-"),detail:Ch(W)?`${Ch(W)} up`:le||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Tl(L,.9,.75)}];return{state:P,label:CT(P,we,K),role:te,taskLabel:ne||(K==="idle"?"idle":K),taskStatus:K,taskSummary:ce,tools:O?V:V.map(J=>({...J,detail:"not reported"})),metrics:we}}const kT=[{id:"small",label:"Small"},{id:"medium",label:"Medium"},{id:"large",label:"Large"}],AT=[{id:"sync-server",label:"Hub",icon:Ur,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:nu,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Qd,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Kd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Gc,accent:"violet",tooltip:"agents"}],NT=[{id:"doc",label:"Doc",icon:af,accent:"amber"},{id:"support",label:"Support",icon:Kc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function MT(n){return n.replaceAll("npx -y @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk","npx -y --prefer-online livedesk@latest").replaceAll("npx livedesk","npx -y --prefer-online livedesk@latest")}function on(n){return MT(n).replaceAll("Sync Server","Hub").replace(/\bRemoteHub\b/g,"Hub client endpoint").replace(/\bManagers\b/g,"Hubs").replace(/\bManager\b/g,"Hub").replace(/\bmanager\b/g,"Hub").replace(/\bMANAGER\b/g,"HUB").replace(/매니저/g,"Hub")}function El(n){return n.map(a=>on(a))}function aa(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:on(n.title),intro:on(n.intro),sections:[{title:on(n.managerTitle),body:on(n.managerBody),points:El(n.managerPoints)},{title:on(n.clientTitle),body:on(n.clientBody),points:El(n.clientPoints)},{title:on(n.syncTitle),body:on(n.syncBody),points:El(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:on(n.agentTitle),body:on(n.agentBody),points:El(n.agentPoints)}]:[],{title:on(n.platformTitle),body:on(n.platformBody),points:El(n.platformPoints)}],sync:{title:on(n.syncTitle),body:on(n.syncBody),points:El(n.syncPoints)},firewall:{title:on(n.firewallTitle),body:on(n.firewallBody),points:El(n.firewallPoints)},commands:{title:on(n.commandsTitle),body:on(n.commandsBody),manager:on(n.managerCommandLabel),primary:on(n.clientCommandLabel),slot:on(n.slotCommandLabel),manual:on(n.manualCommandLabel)}}}const Oo={ko:aa({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["Wall은 Mode 3 H.264와 Mode 4 H.264 Atlas를 사용합니다. Mode 2는 Mode 4의 내부 Atlas 입력에만 한정되며 Wall/Control fallback으로 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot 캡처, xdotool 입력 백엔드가 추가되었습니다. 오디오는 아직 비활성입니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 LAN 안에서는 보통 공유기 포트포워딩이 필요 없습니다. 다른 장소의 PC를 붙이려면 클라이언트가 매니저의 클라이언트 접속 포트에 도달할 수 있어야 합니다.",firewallPoints:["클라이언트 접속 포트는 TCP 5197입니다.","클라이언트 쪽은 나가는 연결이므로 보통 인바운드 포트 개방이 필요 없습니다.","다른 네트워크에서 붙일 때는 매니저 PC 방화벽에서 TCP 5197 인바운드를 허용하고, 공유기에서는 TCP 5197을 매니저 PC로 전달합니다.","Screen Wall/API 포트 5179는 매니저 UI용입니다. 외부 브라우저에서 Wall을 직접 열 필요가 있을 때만 별도로 노출을 검토합니다.","공개 인터넷에 바로 열기보다 VPN, Tailscale, ZeroTier, 고정 IP allowlist를 우선합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:aa({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many workstations, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a workstation",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-workstation tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected workstations and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Wall uses Mode 3 H.264 and Mode 4 H.264 Atlas. Mode 2 is restricted to internal Mode 4 Atlas input and is never used as a Wall or Control fallback.","Remote audio is available when the selected workstation advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, grim/gnome-screenshot/import/scrot capture, and xdotool input backend. Audio is still disabled."],firewallTitle:"Firewall and remote locations",firewallBody:"On the same LAN, router forwarding is usually unnecessary. For another office, building, or country, clients must be able to reach the manager client port.",firewallPoints:["Client connection port: TCP 5197.","Client machines normally only need outbound access.","For remote networks, allow inbound TCP 5197 on the manager firewall and forward TCP 5197 from the router to the manager PC.","Screen Wall/API port 5179 is for the manager UI. Expose it only if a remote browser must open the Wall directly.","Prefer VPN, Tailscale, ZeroTier, or fixed-IP allowlists over public internet exposure."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:aa({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. workstation を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ LAN なら通常 router forwarding は不要です。外部拠点では client が manager の接続ポートへ到達できる必要があります。",firewallPoints:["client 接続ポートは TCP 5197 です。","client 側は通常 outbound だけで足ります。","外部 network では manager PC の firewall で TCP 5197 inbound を許可し、router から manager PC へ forward します。","5179 は manager UI 用なので、外部ブラウザで Wall を開く必要がある時だけ公開を検討します。","公開 internet より VPN、Tailscale、ZeroTier、IP allowlist を優先してください。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"workstation 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":aa({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 workstation",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、xdotool 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 LAN 通常不需要路由端口转发。不同地点连接时,client 必须能访问 manager 的 client 连接端口。",firewallPoints:["client 连接端口是 TCP 5197。","client 机器通常只需要出站访问。","跨网络时,在 manager 防火墙放行 TCP 5197 入站,并在路由器转发到 manager PC。","5179 是 manager UI 端口,仅在需要远程浏览器直接打开 Wall 时考虑暴露。","优先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":aa({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 workstation",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 LAN 通常不需要路由器轉發。不同地點連線時,client 必須能到達 manager 的 client 連線埠。",firewallPoints:["client 連線埠是 TCP 5197。","client 電腦通常只需要對外連線。","跨網路時,請在 manager 防火牆允許 TCP 5197 inbound,並從路由器轉發到 manager PC。","5179 是 manager UI 連接埠,只在需要遠端瀏覽器直接打開 Wall 時才考慮公開。","優先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:aa({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una workstation",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: agregado linux-x64 runtime, captura grim/gnome-screenshot/import/scrot y entrada xdotool. Audio aún desactivado."],firewallTitle:"Firewall y sedes remotas",firewallBody:"En la misma LAN normalmente no hace falta port forwarding. Para otra red, los clients deben llegar al puerto client del manager.",firewallPoints:["Puerto de conexión client: TCP 5197.","Los equipos client normalmente solo necesitan salida.","Para redes remotas, permite TCP 5197 inbound en el manager y reenvía TCP 5197 al PC manager.","El puerto 5179 es para la UI del manager; expónlo solo si un navegador remoto debe abrir el Wall.","Prefiere VPN, Tailscale, ZeroTier o allowlist de IP fijas."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:aa({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une workstation",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot et entrée xdotool ajoutés. Audio désactivé."],firewallTitle:"Firewall et sites distants",firewallBody:"Sur le même LAN, le port forwarding est rarement nécessaire. Depuis un autre réseau, les clients doivent atteindre le port client du manager.",firewallPoints:["Port de connexion client: TCP 5197.","Les machines client ont normalement seulement besoin de sortie réseau.","Pour un réseau distant, autorisez TCP 5197 entrant sur le manager et redirigez TCP 5197 vers le PC manager.","Le port 5179 sert à l’UI manager; exposez-le seulement si un navigateur distant doit ouvrir le Wall.","Préférez VPN, Tailscale, ZeroTier ou allowlist IP fixes."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter workstation",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:aa({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Workstations, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Workstation verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, grim/gnome-screenshot/import/scrot Capture und xdotool Input Backend sind ergänzt. Audio ist deaktiviert."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"Im gleichen LAN ist Router-Forwarding meist unnötig. Aus anderen Netzwerken müssen Clients den Client-Port des Managers erreichen.",firewallPoints:["Client-Verbindungsport: TCP 5197.","Client-Rechner brauchen normalerweise nur ausgehenden Zugriff.","Für entfernte Netzwerke TCP 5197 inbound am Manager erlauben und vom Router zum Manager-PC forwarden.","Port 5179 ist für die Manager-UI; nur öffnen, wenn ein Remote-Browser die Wall direkt öffnen muss.","VPN, Tailscale, ZeroTier oder feste IP-Allowlists bevorzugen."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Workstation verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":aa({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma workstation",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada xdotool adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"Na mesma LAN normalmente não é preciso port forwarding. Em outra rede, clients precisam alcançar a porta client do manager.",firewallPoints:["Porta client: TCP 5197.","Máquinas client normalmente só precisam de saída.","Para redes remotas, permita TCP 5197 inbound no manager e encaminhe TCP 5197 para o PC manager.","A porta 5179 é para a UI do manager; exponha apenas se um navegador remoto precisar abrir o Wall.","Prefira VPN, Tailscale, ZeroTier ou allowlist de IP fixo."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:aa({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare workstation, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una workstation",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input xdotool. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"Nella stessa LAN di solito non serve port forwarding. Da altre reti, i client devono raggiungere la porta client del manager.",firewallPoints:["Porta client: TCP 5197.","I client normalmente richiedono solo uscita.","Per reti remote, abilita TCP 5197 inbound sul manager e inoltra TCP 5197 al PC manager.","La porta 5179 è per la UI manager; esponila solo se un browser remoto deve aprire il Wall.","Preferisci VPN, Tailscale, ZeroTier o IP allowlist."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti workstation",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:aa({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak workstation, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan workstation",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input xdotool sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"Di LAN yang sama biasanya tidak perlu port forwarding. Dari jaringan lain, client harus mencapai port client manager.",firewallPoints:["Port client: TCP 5197.","Mesin client biasanya hanya perlu akses keluar.","Untuk jaringan luar, izinkan TCP 5197 inbound di manager dan forward TCP 5197 ke PC manager.","Port 5179 untuk UI manager; buka hanya jika browser luar harus membuka Wall.","Utamakan VPN, Tailscale, ZeroTier, atau IP allowlist."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan workstation",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:aa({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều workstation, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối workstation",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input xdotool. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"Trong cùng LAN thường không cần port forwarding. Từ mạng khác, client phải truy cập được port client của manager.",firewallPoints:["Port client: TCP 5197.","Máy client thường chỉ cần kết nối outbound.","Với mạng ngoài, cho phép TCP 5197 inbound trên manager và forward TCP 5197 tới PC manager.","Port 5179 dành cho UI manager; chỉ mở nếu trình duyệt từ xa cần mở Wall trực tiếp.","Ưu tiên VPN, Tailscale, ZeroTier hoặc allowlist IP cố định."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối workstation",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:aa({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู workstation, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม workstation",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ xdotool input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน LAN เดียวกันปกติไม่ต้อง port forwarding ถ้าอยู่คนละ network client ต้องเข้าถึง client port ของ manager ได้",firewallPoints:["Client port คือ TCP 5197","เครื่อง client ปกติต้องการ outbound เท่านั้น","ถ้าอยู่นอก network ให้เปิด TCP 5197 inbound ที่ manager และ forward TCP 5197 ไปยัง manager PC","Port 5179 เป็น UI ของ manager เปิดเฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง","ควรใช้ VPN, Tailscale, ZeroTier หรือ IP allowlist ก่อนเปิดสู่ public internet"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม workstation",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:aa({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई workstation, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. workstation जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture और xdotool input backend जोड़े गए हैं। Audio अभी disabled है।"],firewallTitle:"Firewall और remote locations",firewallBody:"Same LAN में आम तौर पर router forwarding जरूरी नहीं। दूसरे network से clients को manager client port तक पहुंचना होगा।",firewallPoints:["Client connection port: TCP 5197.","Client machines को आम तौर पर सिर्फ outbound access चाहिए।","Remote network के लिए manager firewall में TCP 5197 inbound allow करें और router से TCP 5197 manager PC पर forward करें।","5179 manager UI port है; इसे तभी expose करें जब remote browser को Wall खोलना हो।","Public internet से पहले VPN, Tailscale, ZeroTier या fixed IP allowlist बेहतर है।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:aa({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة workstations وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل workstation",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وxdotool input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس LAN غالبا لا تحتاج port forwarding. من شبكة أخرى يجب أن يصل client إلى منفذ manager client.",firewallPoints:["منفذ client: TCP 5197.","أجهزة client تحتاج عادة اتصال outbound فقط.","للشبكات البعيدة، اسمح TCP 5197 inbound على manager ووجه TCP 5197 من router إلى manager PC.","المنفذ 5179 مخصص لواجهة manager؛ اكشفه فقط إذا كان متصفح بعيد يحتاج فتح Wall مباشرة.","يفضل VPN أو Tailscale أو ZeroTier أو fixed IP allowlist بدل التعريض العام."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:aa({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok workstation, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Workstation bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve xdotool input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"Aynı LAN içinde genelde router forwarding gerekmez. Başka ağdan clients manager client portuna ulaşabilmelidir.",firewallPoints:["Client port: TCP 5197.","Client makineler normalde sadece outbound erişim ister.","Uzak ağ için manager firewall üzerinde TCP 5197 inbound aç ve routerdan TCP 5197yi manager PCye forward et.","5179 manager UI portudur; sadece uzak browser Wall açacaksa expose et.","Public internet yerine VPN, Tailscale, ZeroTier veya sabit IP allowlist tercih et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Workstation bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},TT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function ET(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const r=a.toLowerCase();if(Oo[a])return a;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const l=r.split("-")[0];if(Oo[l])return l}return"en"}function qy({index:n}){const a=n+1;return s.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:s.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[s.jsx("span",{className:"slot-grid","aria-hidden":"true"}),s.jsxs("span",{className:"empty-screen",children:[s.jsx(en,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}function RT(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return Qi(a)&&n.capabilities?.screenRecordingPermission===!1}function Qi(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function Gy(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:Qi(n.platform)}function jh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:g,onOpenControl:v,onCycleMonitor:b,onCanvasReady:y,sendInput:w,updateIndicator:S,presentationReady:j,showPresentationSpinner:N=!1}){const M=u.useRef(null),k=u.useRef(null),E=u.useRef(0),R=u.useRef(null),U=Nw(n),H=["cpu","gpu","memory","vram"].map(B=>U.metrics.find(pe=>pe.id===B)).filter(B=>!!B),W=Da(d,m),_=m>1,L=j??!!a,le=RT(n)&&!L,q=N&&n.connected&&!L&&!le,te=cT(n,a,W),K=te>=Wd?100:te/Wd*100,ne=te>=Wd?Wd/te*100:100,ce={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,K)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,ne)).toFixed(3)}%`},V=u.useCallback(B=>{M.current=B,y(n.deviceId,B)},[n.deviceId,y]),O=B=>{const pe=B.currentTarget.getBoundingClientRect();return Nj(B.clientX,B.clientY,pe)},Y=B=>({shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}),X=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),P=u.useCallback(()=>{const B=k.current;if(!B)return;k.current=null;const pe=Number(B.input.normalizedX),ge=Number(B.input.normalizedY);if(!Number.isFinite(pe)||!Number.isFinite(ge))return;w(n.deviceId,{...B.input,normalizedX:pe,normalizedY:ge})&&(E.current=performance.now())},[n.deviceId,w]),oe=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,P()}))},[P]);u.useEffect(()=>()=>{X(),k.current=null},[X]);const we=(B,pe)=>{if(!l)return;const ge={type:pe,monitorIndex:W,...O(B),button:wT(B.button),...Y(B)};if(pe==="pointermove"){const xe=performance.now();k.current={input:ge},xe-E.current>=LM&&(X(),P()),oe();return}k.current&&(X(),P()),w(n.deviceId,ge)},J=u.useCallback(B=>{const pe=document.activeElement;pe instanceof HTMLElement&&B.contains(pe)&&pe.classList.contains("monitor-cycle-button")&&pe.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:ce,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||l||p()},onKeyDown:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||l||(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),p())},onDoubleClick:B=>{B.target instanceof Element&&B.target.closest(".monitor-cycle")||(B.preventDefault(),v())},onPointerLeave:B=>J(B.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:V,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:B=>{l&&(B.preventDefault(),B.stopPropagation(),g(),B.currentTarget.focus(),B.currentTarget.setPointerCapture(B.pointerId),we(B,"pointerdown"))},onPointerMove:B=>{l&&B.preventDefault(),we(B,"pointermove")},onPointerLeave:B=>{l&&(we(B,"pointermove"),X(),P())},onPointerUp:B=>{l&&(B.preventDefault(),B.stopPropagation(),we(B,"pointerup"),B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId))},onPointerCancel:B=>{B.currentTarget.hasPointerCapture(B.pointerId)&&B.currentTarget.releasePointerCapture(B.pointerId)},onWheel:B=>{l&&(B.preventDefault(),w(n.deviceId,{type:"wheel",monitorIndex:W,...O(B),deltaX:B.deltaX,deltaY:B.deltaY,...Y(B)}))},onKeyDown:B=>{l&&(B.preventDefault(),B.stopPropagation(),w(n.deviceId,{type:"keydown",monitorIndex:W,key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:B.repeat,...Y(B)}))},onKeyUp:B=>{l&&(B.preventDefault(),B.stopPropagation(),w(n.deviceId,{type:"keyup",monitorIndex:W,key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:!1,...Y(B)}))},onContextMenu:B=>l&&B.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(en,{size:26})}),q&&s.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),s.jsx("strong",{children:"Preparing video"})]}),le&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(Lt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"Screen Recording permission required"}),s.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),S&&s.jsxs("span",{className:`wall-update-status state-${S.state}`,role:"status","aria-live":"polite",title:S.error||S.label,children:[S.state==="updated"?s.jsx(Hn,{size:20,"aria-hidden":"true"}):S.state==="failed"?s.jsx(Ja,{size:22,"aria-hidden":"true"}):S.state==="offline"?s.jsx(Il,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:S.label}),S.error?s.jsx("small",{children:S.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${U.state}`,children:U.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${ha(n)} status`,children:H.map(B=>s.jsxs("span",{className:`tile-metric state-${B.state}`,children:[s.jsx("b",{children:B.label}),s.jsx("em",{children:B.value}),B.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(B.ratio*100)}%`}})]},B.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${ha(n)} display ${W+1} of ${m}`,onPointerDown:B=>B.stopPropagation(),onClick:B=>B.stopPropagation(),onDoubleClick:B=>B.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(-1),B.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(ab,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",W+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:B=>{B.preventDefault(),B.stopPropagation(),b(1),B.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(tp,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx($r,{size:23,strokeWidth:3.5})})]})})}function DT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(ky)){const r=document.createElement("script");r.id=ky,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Vh)}`,document.head.appendChild(r)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?s.jsxs("aside",{className:`free-ad-banner ${ph?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),ph?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":Vh,"data-ad-slot":yw,"data-ad-format":"auto","data-full-width-responsive":"true"}):s.jsxs("div",{className:"house-ad-copy",children:[s.jsx("strong",{children:"Sponsored placement"}),s.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function LT(){const n=qM(),{session:a,loading:r}=ij(),{target:l,error:c,refresh:d}=lj(a),m=u.useMemo(()=>{if(!l?.active)return null;const x=l.expires_at?Date.parse(l.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:l},[l]),p=u.useMemo(()=>Sx(m),[m]),g=u.useMemo(()=>p.length>0?[...new Set([...p,bn])]:[bn],[p]),[v,b]=u.useState(iT),y=u.useMemo(()=>g.some(x=>!!Zc(x)),[g]),w=!y||v,{status:S,devices:j,error:N,refresh:M,hubBaseUrl:k}=rj(g,w),{entitlement:E,licensed:R,loading:U,error:H,refresh:W}=oj(a),[_,L]=u.useState([]),[le,q]=u.useState(""),[te,K]=u.useState(""),[ne,ce]=u.useState(""),[V,O]=u.useState(""),[Y,X]=u.useState(""),[P,oe]=u.useState("idle"),[we,J]=u.useState(!1),[B,pe]=u.useState(null),[ge,xe]=u.useState(""),Ae=u.useRef("");Ae.current=V;const[_e,ie]=u.useState(!1),[Q,Ie]=u.useState(!1),Oe=u.useRef(""),ae=u.useRef(new Map),ke=u.useRef(0),[je,De]=u.useState(""),[Le,$e]=u.useState(""),[he,Me]=u.useState(!1),[de,be]=u.useState(null);u.useEffect(()=>{je==="auth"&&a?.access_token&&De("")},[je,a?.access_token]);const[We,at]=u.useState(""),[wn,Xe]=u.useState(null),ht=u.useRef(null),St=u.useRef(0),Rn=u.useCallback((x,A,D)=>{const $=String(x||"").trim();if(at($),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!$){Xe(null);return}const z=++St.current;if(Xe({id:z,message:$,tone:A}),!D)return;const me=window.setTimeout(()=>{Xe(ve=>ve?.id===z?null:ve),ht.current===me&&(ht.current=null)},5e3);ht.current=me},[]),He=u.useCallback((x,A="info")=>{Rn(x,A,!0)},[Rn]),Ct=u.useCallback(x=>{Rn(x,"progress",!1)},[Rn]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[Gt,pt]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{pt(window.location.pathname.startsWith("/support")?"support":A=>A==="support"?"wall":A)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[rt,tn]=u.useState("large"),[kt,ze]=u.useState(ET),[Dn,Zi]=u.useState(!1),[hn,$n]=u.useState(!1),[ga,ts]=u.useState(!1),[Ln,ns]=u.useState(sT),[Be,hi]=u.useState(fT),[ft,as]=u.useState(hT),[Vt,Bs]=u.useState(uT),[I,Fe]=u.useState(null),[mt,nn]=u.useState([]),[pn,Fs]=u.useState(Be.fps),[ra,ee]=u.useState(""),[Te,qe]=u.useState(0),[it,Kt]=u.useState(0),[Tt,Ze]=u.useState(()=>new Set),lt=u.useRef(new Map),Qt=u.useRef(new Map),$t=u.useRef(new Map),_t=u.useRef(new Map),Ft=u.useRef(new Map),Ut=u.useRef(new Set),zt=u.useRef(new Map),gn=u.useRef(""),ss=u.useRef(""),un=u.useRef(null),Xt=u.useRef(null),bs=u.useRef(new Map),ws=u.useRef(null),pi=u.useRef(0),$o=u.useRef(new Map),[Ji,Pl]=u.useState({}),Oa=u.useRef(new Map),[Qn,cu]=u.useState({}),[uu,Xn]=u.useState(!1),$l=u.useRef(null),la=u.useRef(null),va=u.useRef(0),Sn=u.useRef(""),gi=u.useRef(new Map),er=u.useRef(new Map),tr=u.useRef(performance.now()),is=u.useRef(new Map),vi=u.useRef(new Map),xi=u.useRef(new Map),Ps=u.useRef(new Map),Yr=u.useRef(0),Kr=u.useRef(0),Qr=u.useRef(0),nr=u.useRef(0),Uo=u.useRef(0),du=u.useRef(new Map),Ha=u.useRef(new Map),[Un,rs]=u.useState(null),[qo,$s]=u.useState(!1),[Xr,fu]=u.useState([]),[Us,mu]=u.useState("all"),[ls,Ba]=u.useState([]),[hu,Ul]=u.useState(!1),[yi,Go]=u.useState(!0),Zr=u.useRef(null),Vo=u.useRef(null),ql=u.useRef(null),Gl=u.useRef(null),pu=u.useRef(!1),_n=u.useRef(!1),Ss=u.useRef(!1),qs=u.useRef(0),xa=u.useRef(0),Vl=Gt==="settings",Wl=Gt==="pricing",Yl=Gt==="doc",ar=Gt==="support",Gs=Gt==="share-files",Kl=Gt==="agents",gu=!Vl&&!Wl&&!Yl&&!ar&&!Gs&&!Kl,nt=Gt==="control",ut=Be.frameMode==="mode4-h264-atlas",Zn=Y||ft.frameMode,sr=Zn!=="mode3-h264-hw"?Math.min(30,ft.fps):ft.fps,Vs=Zn!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ft.maxWidth),maxHeight:Math.min(1080,ft.maxHeight)}:{maxWidth:ft.maxWidth,maxHeight:ft.maxHeight};u.useEffect(()=>{if(S?.started){if(!a?.access_token){Ge("/api/remote/license",{method:"DELETE"},k).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${a.access_token}`}},k).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[E?.updated_at,k,a?.access_token,S?.started]),u.useEffect(()=>{!a?.access_token||!S?.started||S.runtimeRole!=="hub"||!S.deviceId||(async()=>{try{const{data:x,error:A}=await ct.rpc("register_livedesk_device",{p_device_id:S.deviceId,p_device_name:S.deviceName||S.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:S.managerVersion||S.managerPackage||""}),D=Array.isArray(x)?x[0]:x;(A||D?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",A||D?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[a?.access_token,S?.deviceId,S?.deviceName,S?.managerPackage,S?.managerVersion,S?.runtimeRole,S?.started]),u.useEffect(()=>{!a?.access_token||!a.refresh_token||!S?.started||S.runtimeRole!=="hub"||Ss.current||(Ss.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},k||bn).then(x=>{x.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",x.hostTarget.error||"unknown-error"),M()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{Ss.current=!1}))},[k,M,a?.access_token,a?.expires_at,a?.refresh_token,a?.user?.email,a?.user?.id,S?.runtimeRole,S?.started]);const et=u.useMemo(()=>j.filter(x=>x.connected),[j]),vu=Us==="all"?et.length:ls.filter(x=>et.some(A=>A.deviceId===x)).length,kf=u.useMemo(()=>et.reduce((x,A)=>Math.max(x,Uy(A.slotNumber)),0),[et]),Jr=Math.max(EM,et.length,kf),el=u.useMemo(()=>{const x=Array(Jr).fill(null),A=[];for(const D of et){const $=Uy(D.slotNumber);$>0&&$<=Jr&&!x[$-1]?x[$-1]=D:A.push(D)}for(const D of A){const $=x.findIndex(z=>!z);$<0?x.push(D):x[$]=D}return x},[et]),Wo=u.useMemo(()=>et.map(x=>x.deviceId),[et]),ir=u.useMemo(()=>new Set(_),[_]),Fa=u.useMemo(()=>et.filter(x=>ir.has(x.deviceId)),[et,ir]),Ws=u.useMemo(()=>j.find(x=>x.deviceId===le)||Fa[0]||null,[j,le,Fa]),qn=u.useMemo(()=>j.find(x=>x.deviceId===te)||null,[te,j]),Ys=qn?Da(Vt[qn.deviceId],ma(qn)):0,Ee=nt?qn:Ws,Yo=u.useMemo(()=>new Set(ls),[ls]),Af=u.useMemo(()=>Us==="all"?et.map(x=>x.deviceId):et.filter(x=>Yo.has(x.deviceId)).map(x=>x.deviceId),[et,Yo,Us]),os=u.useMemo(()=>Ee?Nw(Ee):null,[Ee]),Nf=Ee?tu(Ee,"control"):!1,Ko=Qi(Ee?.platform)&&(Ee?.capabilities?.controlPermission===!1||Ee?.capabilities?.accessibilityPermission===!1),tl=Ee?tu(Ee,"audio")||tu(Ee,"remoteAudio"):!1,xu=Array.isArray(Ee?.capabilities?.agentTools)?Ee.capabilities.agentTools.map(String):[],Ql=xu.includes("system.power"),yu=xu.includes("command.run"),qt=R?E?.plan==="pro"?"pro":"ltd":"free",Xl=Ml[qt],Ks=Xl.limit,bi=u.useMemo(()=>{if(!Number.isFinite(Ks))return new Set(et.map(A=>A.deviceId));const x=Ee?[Ee,...et.filter(A=>A.deviceId!==Ee.deviceId)]:et;return new Set(x.slice(0,Ks).map(A=>A.deviceId))},[Ks,et,Ee]),bu=!Ee||bi.has(Ee.deviceId),wu=qt==="free",Wt=bu,wi=qt==="ltd"?`Plus includes up to ${Wc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Vc} workstations. Upgrade to Plus for ${Wc} devices and no ads.`,Su=qt==="free",Si=Wt&&!!Ee,Cs=Wt&&!!Ee&&Nf,Cu=Wt&&!!Ee&&tl;u.useEffect(()=>{Me(!1)},[Gt,Ee?.deviceId]);const Zl=u.useMemo(()=>el.filter(x=>!!x?.connected).slice(0,gT(rt)).map(x=>x.deviceId),[el,rt]),nl=u.useMemo(()=>ut?Wo:Be.visibleOnlyLive?mt.length>0?mt:Zl:Wo,[Zl,ut,mt,Be.visibleOnlyLive,Wo]),ya=u.useMemo(()=>bh(nl.filter(x=>bi.has(x))),[bi,nl]),ba=u.useMemo(()=>ya.filter(x=>x!==ra),[ya,ra]),Qs=u.useMemo(()=>new Map(et.map(x=>[x.deviceId,x.platform])),[et]),cs=Mj(ut,ya.length),Gn=u.useMemo(()=>ut?ba.filter(x=>$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(Qs.get(x))})==="atlas"):[],[cs,ut,Qs,ba]),Jn=u.useMemo(()=>ba.filter(x=>$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(Qs.get(x))})==="direct"),[cs,ut,Qs,ba]);u.useEffect(()=>{const x=new Set(ya);Ze(A=>{let D=!1;const $=new Set;for(const z of A)x.has(z)?$.add(z):D=!0;return D?$:A})},[ya]);const ju=u.useMemo(()=>{const x=z=>et.find(me=>me.deviceId===z)||null,A=z=>Da(Vt[z],x(z)?ma(x(z)):0),D=(z,me=A(z))=>z===ne&&(P==="connecting"||P==="active"||P==="warm")?_t.current.get(z)||Qt.current.get(z)||null:ut?bs.current.get(z)||lt.current.get(z)||null:lt.current.get(z)||null,$=(z,me=A(z))=>{const ve=x(z);return`${ve?ha(ve):z} · Monitor ${me+1}`};return{resolveCurrentTarget(){if(nt&&qn){const Ue=Ys;return{type:"control",deviceIds:[qn.deviceId],monitorIndex:Ue,label:`${ha(qn)} · Monitor ${Ue+1}`,sourceCanvas:D(qn.deviceId,Ue),signature:`control:${qn.deviceId}:${Ue}:${ft.frameMode}`}}const z=Fa.map(Ue=>Ue.deviceId).filter(Ue=>ba.includes(Ue)),me=Ws&&ba.includes(Ws.deviceId)?Ws.deviceId:"",ve=z.length>0?z:me?[me]:ba,Ne=z.length===0&&!me;if(ve.length===0)return null;if(ve.length===1){const Ue=ve[0],Ke=A(Ue);return{type:Ne?"wall":z.length>1?"selection":"device",deviceIds:ve,monitorIndex:Ke,label:Ne?"Wall":$(Ue,Ke),sourceCanvas:Ne?null:D(Ue,Ke),signature:`${Ne?"wall":"device"}:${Ue}:${Ke}:${ut?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:ve,label:z.length>1?`${ve.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${ve.join(",")}:${rt}`}},getDeviceCanvas:D,composeWall(z,me={}){return xM(z.map(ve=>{const Ne=A(ve);return{deviceId:ve,label:$(ve,Ne),canvas:D(ve,Ne)}}),me)}}},[et,qn,ne,P,ft.frameMode,lt,ut,Vt,Ys,Fa,nt,ba,Ws,rt]),Jl=TM({hubUrl:k,sourceRegistry:ju,onToast:He}),Xs=u.useMemo(()=>Wt&&ne&&bi.has(ne)&&(P==="connecting"||P==="active"||P==="warm")?[ne]:[],[ne,P,Wt,bi]),ku=u.useMemo(()=>bh([...ya,...Xs]),[Xs,ya]),zn=u.useMemo(()=>vT(Be,rt),[Be,rt]),Ci=Tj({mode4Enabled:ut,directMode4WallEnabled:cs,adaptiveFps:pn,directDeviceCount:Jn.length}),js=u.useCallback((x,A,D)=>{if(x.width<=0||x.height<=0)return!1;const $=D?Math.min(1,D.maxWidth/x.width,D.maxHeight/x.height):1,z=Math.max(1,Math.round(x.width*$)),me=Math.max(1,Math.round(x.height*$));(A.width!==z||A.height!==me)&&(A.width=z,A.height=me);const ve=A.getContext("2d",{alpha:!1});return ve?(ve.imageSmoothingEnabled=!0,ve.imageSmoothingQuality="high",ve.drawImage(x,0,0,x.width,x.height,0,0,A.width,A.height),!0):!1},[]),rr=u.useCallback(x=>{x&&Ze(A=>{if(A.has(x))return A;const D=new Set(A);return D.add(x),D})},[]),eo=u.useCallback(x=>{x&&Ze(A=>{if(!A.has(x))return A;const D=new Set(A);return D.delete(x),D})},[]),to=u.useCallback((x,A)=>{if(!A||A.width<=0||A.height<=0)return!1;const D=document.createElement("canvas");return D.width=A.width,D.height=A.height,js(A,D)?($t.current.set(x,D),rr(x),!0):!1},[rr,js]),ks=u.useCallback((x,A=!1)=>{if(!Ut.current.has(x))return!1;const D=performance.now(),$=zt.current.get(x)||0,z=Math.max(1,Math.min(di.controlWallReuseMaxFps,sr)),me=sr>z?Math.max(0,1e3/z-2):0;if(!A&&D-$<me)return!1;const ve=_t.current.get(x)||Qt.current.get(x),Ne=lt.current.get(x)||bs.current.get(x);return!ve||!Ne||!js(ve,Ne,zn)?!1:(zt.current.set(x,D),rr(x),!0)},[sr,zn,rr,js]);u.useEffect(()=>{gn.current=ra},[ra]);const ea=u.useCallback((x,A)=>{const D=lt.current.get(x);if(D&&D!==A&&(to(x,D),Pc(D)),A){lt.current.set(x,A),$t.current.delete(x),ks(x,!0);return}lt.current.delete(x),$t.current.has(x)||eo(x)},[eo,ks,to]),al=u.useCallback((x,A)=>{const D=Qt.current.get(x);if(D&&D!==A&&Pc(D),A){Qt.current.set(x,A);const $=_t.current.get(x)||$t.current.get(x)||lt.current.get(x)||bs.current.get(x);$&&js($,A)&&x===te&&Xn(!0);return}Qt.current.delete(x)},[te,js]),sl=u.useCallback((x,A,D)=>{const $=performance.now(),z=zs(x,D.deviceId);let me=D;if(x==="control"&&D.visualChanged){const Ne=hj(D.deviceId),Ue=du.current.get(D.deviceId)||0,Ke=Ne?$-Ne.sentAt:Number.POSITIVE_INFINITY;Ne&&Ne.inputSeq>Ue&&Ke<=Ay&&(me={...D,inputFeedbackSeq:Ne.inputSeq,inputFeedbackMs:Math.max(0,Ke),inputFeedbackAt:$},du.current.set(D.deviceId,Ne.inputSeq))}er.current.set(z,$);const ve=$o.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:$,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&me.inputFeedbackMs===void 0&&ve.lastInfo?.inputFeedbackMs!==void 0&&ve.lastInfo.inputFeedbackAt!==void 0&&$-ve.lastInfo.inputFeedbackAt<=Ay&&(me={...me,inputFeedbackSeq:ve.lastInfo.inputFeedbackSeq,inputFeedbackMs:ve.lastInfo.inputFeedbackMs,inputFeedbackAt:ve.lastInfo.inputFeedbackAt}),ve.totalFrames+=1,ve.sampleFrames+=1,Dy(ve,$,me.frameSeq),me.visualChanged&&(ve.totalChangedFrames+=1,ve.sampleChangedFrames+=1),ve.lastInfo=me,$o.current.set(z,ve)},[]),il=u.useCallback((x,A)=>{sl("wall",x,A),x.kind==="live"&&rr(x.deviceId);const D=we&&ne===x.deviceId;gn.current!==x.deviceId&&!D&&(Ut.current.delete(x.deviceId),zt.current.delete(x.deviceId))},[ne,we,rr,sl]),Qo=u.useCallback((x,A)=>{sl("control",x,A),xe(me=>me&&"");const D=_t.current.get(x.deviceId),$=Qt.current.get(x.deviceId);D&&D.width>0&&D.height>0&&($&&js(D,$),Ft.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),$t.current.delete(x.deviceId),Ut.current.add(x.deviceId),x.deviceId===ne&&(J(!0),oe(me=>me==="connecting"?"active":me)),ks(x.deviceId));const z=$l.current;!z||!UM(z,x)||Xn(!0)},[ne,js,ks,sl]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),D={};for(const[$,z]of $o.current.entries()){const me=Math.max(1,A-z.sampleStartedAt);D[$]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/me,changedFramesPerSecond:z.sampleChangedFrames*1e3/me,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:ef(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/me),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/me),sampleMs:me,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,Ry(z,A)}Pl(D)},1e3);return()=>window.clearInterval(x)},[]);const ji=u.useCallback((x,A)=>{const D=performance.now(),$=zs(x,A.deviceId);gi.current.set($,D),Ha.current.delete($),x==="control"&&vi.current.delete($);const z=Oa.current.get($)||{totalFrames:0,sampleFrames:0,sampleStartedAt:D,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]};if(z.totalFrames+=1,z.sampleFrames+=1,z.sampleBytes+=Math.max(0,Number(A.byteLength||0)),String(A.frameMode||A.mode||A.codec||A.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(A.byteLength||0)<=BM&&(z.sampleTinyFrames+=1);const Ue=String(A.contentHash||"");Ue&&z.lastContentHash===Ue&&(z.sampleRepeatedFrames+=1),z.lastContentHash=Ue}const Ne=Number(A.agentSendGapMs||0);Ne>0&&Ne<1e3&&Sp(z.sourceSendIntervalsMs,Ne),z.lastFrame=A,Dy(z,D,A.frameSeq),Oa.current.set($,z)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const A=performance.now(),D={};for(const[$,z]of Oa.current.entries()){const me=Math.max(1,A-z.sampleStartedAt);D[$]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/me,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:ef(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,averageFrameBytes:z.sampleFrames>0?z.sampleBytes/z.sampleFrames:0,tinyFrameRatio:z.sampleH264Frames>0?z.sampleTinyFrames/z.sampleH264Frames:0,repeatedFrameRatio:z.sampleH264Frames>0?z.sampleRepeatedFrames/z.sampleH264Frames:0,sourceSendAverageMs:z.sourceSendIntervalsMs.length>0?z.sourceSendIntervalsMs.reduce((ve,Ne)=>ve+Ne,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:ef(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:me,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,Ry(z,A)}cu(D)},1e3);return()=>window.clearInterval(x)},[]);const no=u.useCallback(x=>{ji("wall",x);const A=lt.current.get(x.deviceId);if(!A)return;const D=Ej(ut,Be.h264DecodeAcceleration);nh(A,x,()=>lt.current.get(x.deviceId)!==A,il,D.acceleration,D.latencyMode).catch(()=>{})},[il,ut,ji,Be.h264DecodeAcceleration]),Au=u.useCallback(x=>{ji("control",x);let A=_t.current.get(x.deviceId);A||(A=document.createElement("canvas"),A.setAttribute("aria-hidden","true"),_t.current.set(x.deviceId,A));const D=A,$=Ae.current;nh(D,x,()=>_t.current.get(x.deviceId)!==D,Qo,ft.h264DecodeAcceleration,"interactive").catch(z=>{Ae.current!==$||_t.current.get(x.deviceId)!==D||ne!==x.deviceId||xe(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[ne,ft.h264DecodeAcceleration,Qo,ji]),lr=u.useCallback(x=>{const A=Xt.current;A&&A!==x&&Pc(A),Xt.current=x,Yr.current=0,Kr.current=0,Qr.current=0,nr.current=0,Uo.current=0,pi.current=0},[]),Zs=u.useCallback(()=>{const x=Xt.current,A=ws.current;if(!(!x||!A||x.width<=0||x.height<=0||pi.current!==A.layoutVersion))for(const D of A.tiles){const $=bs.current.get(D.deviceId);if(!$||D.width<=0||D.height<=0)continue;const z=Math.max(1,Math.round(D.width)),me=Math.max(1,Math.round(D.height)),ve=FM,Ne=PM;($.width!==ve||$.height!==Ne)&&($.width=ve,$.height=Ne);const Ue=$.getContext("2d",{alpha:!1});if(Ue){Ue.imageSmoothingEnabled=!0,Ue.imageSmoothingQuality="high";try{Ue.drawImage(x,Math.round(D.x),Math.round(D.y),z,me,0,0,ve,Ne)}catch{}}}},[]),rl=u.useCallback((x,A)=>{if(A){bs.current.set(x,A),$t.current.delete(x),window.requestAnimationFrame(Zs),window.requestAnimationFrame(()=>ks(x,!0));return}const D=bs.current.get(x);to(x,D),bs.current.delete(x),$t.current.has(x)||eo(x)},[eo,Zs,ks,to]),ao=u.useCallback((x,A)=>{Qr.current=performance.now(),pi.current=Number(x.layoutVersion||0),Zs();const D=ws.current?.tiles||[],$=D.length>0?Math.round(x.byteLength/D.length):x.byteLength;for(const z of D){const me={...x,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:$};il(me,{...A,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:$}),gn.current===z.deviceId&&ks(z.deviceId,!0)}},[il,Zs,ks]),Nu=u.useCallback(x=>{const A=performance.now();Yr.current<=0&&(Yr.current=A),Kr.current=A;const D=Xt.current;if(!D)return;const $=ws.current?.tiles||[],z=$.length>0?Math.round(x.byteLength/$.length):x.byteLength;for(const me of $)ji("wall",{...x,deviceId:me.deviceId,width:me.width,height:me.height,sourceWidth:me.width,sourceHeight:me.height,byteLength:z});nh(D,x,()=>Xt.current!==D,ao).catch(()=>{})},[ao,ji]),ki=u.useMemo(()=>({fps:Ci,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:Be.quality,mode:ut?"mode3-h264-hw":Be.frameMode,frameMode:ut?"mode3-h264-hw":Be.frameMode,streamPurpose:"wall",monitorSelections:Vt,onFrame:no}),[Ci,no,zn,ut,Vt,Be]),Ai=u.useCallback(x=>{if(x.deviceId!==ne||x.streamPurpose!=="control"||x.monitorIndex!==Ys)return;const A=et.find(D=>D.deviceId===x.deviceId);!A?.sessionId||A.sessionId!==x.sessionId||(pe(x),oe(D=>D==="connecting"?"active":D))},[et,ne,Ys]);u.useEffect(()=>{pe(null)},[ne,V,Zn,Ys]);const Xo=u.useMemo(()=>({fps:sr,maxWidth:Vs.maxWidth,maxHeight:Vs.maxHeight,quality:ft.quality,mode:Zn,frameMode:Zn,streamPurpose:"control",forceRestart:V!=="",forceRestartToken:V,restartReason:V?"control-session-start":"",monitorSelections:Vt,onFrame:Au,onStreamReady:Ai}),[V,ft.quality,Au,sr,Zn,Vs.maxHeight,Vs.maxWidth,Ai,Vt]),{frames:Zo,state:Pa,error:Jo,stats:As,restartLive:ll}=zx(Jn,Be.autoStartLive&&Jn.length>0,k,ki),{frame:or,layout:Ni,state:ec,stats:Mu,refreshInputs:tc}=pj(Gn,ut&&Be.autoStartLive&&Gn.length>0,k,{fps:di.atlasOutputFps,width:1920,height:1080,tileWidth:zn.maxWidth,tileHeight:zn.maxHeight,captureDeviceIds:Gn,monitorSelections:Vt,onFrame:Nu});u.useEffect(()=>{ws.current=Ni,Ni&&window.requestAnimationFrame(Zs)},[Ni,Zs]),u.useEffect(()=>{if(!ut||ec!=="open"){Yr.current=0,Kr.current=0,Qr.current=0;return}const x=window.setInterval(()=>{const A=Xt.current,D=performance.now();if(!A||document.visibilityState!=="visible"||D-tr.current<gh)return;const $=Kr.current,z=Yr.current;if($<=0||z<=0||D-$>500)return;const me=Qr.current||z,ve=D-me;if(ve>=zM&&D-Uo.current>=OM){eh(A)&&(Uo.current=D,nr.current=D);return}ve>=_M&&D-nr.current>=IM&&ZC(A)&&(nr.current=D)},250);return()=>window.clearInterval(x)},[ec,ut]);const{frames:ol,state:oa,error:Js,stats:wa,restartLive:Ns,reconnectLive:so}=zx(Xs,Xs.length>0,k,Xo),Mi=u.useMemo(()=>{const x=new Map(Zo);if(ut&&or&&Gn.length>0){const A=new Map((Ni?.tiles||[]).map($=>[$.deviceId,$])),D=Math.max(1,A.size);for(const $ of Gn){const z=A.get($);z&&x.set($,{...or,deviceId:$,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(or.byteLength/D)})}}for(const[A,D]of ol.entries())x.set(A,D);for(const A of nl){if(!Ut.current.has(A)||x.has(A))continue;const D=Ft.current.get(A);D&&x.set(A,D)}return x},[or,Ni,ol,Gn,ut,Zo,nl,it]),cr=nt&&Xs.length>0?oa:Gn.length>0?ec:Pa,cl=nt&&Xs.length>0?wa:Gn.length>0?Mu:As;u.useCallback((x,A="browser-stale")=>{const D=ll(x,A),$=Ns(x,A);return D||$},[Ns,ll]),u.useEffect(()=>{ut&&Gn.length>0&&!nt&&tc()},[Gn.length,ut,tc,nt]);const us=u.useCallback((x,A,D)=>{const $=A==="control"?_t.current.get(x)||null:lt.current.get(x)||null;if(!$||!eh($))return!1;const z=performance.now();return Ps.current.set(zs(A,x),z),!0},[]),ul=u.useCallback(x=>{if(Zn!=="mode3-h264-hw"||!ne||Y)return!1;const A=et.find(Ne=>Ne.deviceId===ne)||qn,D=String(A?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(D))return!1;const $="mode5-lzo-delta",z=zs("control",ne),me=performance.now();xi.current.set(z,me),gi.current.delete(z),er.current.delete(z),is.current.delete(z),vi.current.delete(z),Ha.current.delete(z),eh(_t.current.get(ne)||null),so([ne],"control-decode-fallback"),X($),O(`control-${$}-fallback-${ne}-${Date.now()}`),J(!1),Xn(!1);const ve=x==="no first frame"||x==="control-first-frame-timeout";return xe(Ne=>Ne||(ve?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),oe("connecting"),!0},[et,qn,ne,Y,Zn,so]);u.useEffect(()=>{const x=nt?qn:null;if(x){$l.current={deviceId:x.deviceId,monitorIndex:Ys,frameMode:Zn,startedAtEpochMs:Date.now()},Xn(ne===x.deviceId&&we||Tt.has(x.deviceId));return}$l.current=null,Xn(!1)},[qn?.sessionId,te,ne,we,Zn,Ys,nt,Tt]);const ei=u.useCallback(async x=>{const A=j.find(ve=>ve.deviceId===x),D=$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(A?.platform)})==="atlas",$=Da(Vt[x],A?ma(A):1),z=D?{fps:di.scalableAtlasInputFps,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:$}:{fps:ut&&!D?Ci:pn,maxWidth:zn.maxWidth,maxHeight:zn.maxHeight,quality:Be.quality,mode:ut?"mode3-h264-hw":Be.frameMode,frameMode:ut?"mode3-h264-hw":Be.frameMode,streamPurpose:"wall",monitorIndex:$},me=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(z)},k);if(me?.ok===!1)throw new Error(me.error||"wall-stream-start-failed");return me},[pn,j,cs,Ci,zn.maxHeight,zn.maxWidth,k,ut,Vt,Be.frameMode,Be.quality]),Ms=u.useCallback(async x=>{const A=j.find(z=>z.deviceId===x),D=$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(A?.platform)})==="atlas",$=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:D?"atlas":"wall",reason:"control-active"})},k);if($?.ok===!1)throw new Error($.error||"wall-stream-stop-failed");return $},[j,cs,k,ut]),ur=u.useCallback(async(x,A="control-session-stop")=>{const D=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:A})},k);if(D?.ok===!1)throw new Error(D.error||"control-stream-stop-failed");return D},[k]),Cn=u.useCallback(x=>{const A=_t.current.get(x);A&&(Pc(A),_t.current.delete(x));const D=Qt.current.get(x);D&&Pc(D),Ft.current.delete(x),Ut.current.delete(x),zt.current.delete(x)},[]);u.useEffect(()=>{const x=te&&et.find(z=>z.deviceId===te)||null;if(!nt||!Wt||!x){Sn.current&&(++va.current,Sn.current="");return}if(ne===x.deviceId&&(P==="active"||P==="warm"||P==="connecting")){oe(z=>z==="warm"?"active":z);return}if(Sn.current===x.deviceId)return;const A=++va.current,D=ne;Sn.current=x.deviceId,(async()=>{if(D){if(oe("stopping"),await ur(D,"control-session-switch").catch(()=>{}),A!==va.current)return;const ve=gn.current;if(ve&&ve!==x.deviceId)try{await ei(ve)}catch(Ne){He(Ne instanceof Error?Ne.message:String(Ne))}finally{gn.current===ve&&(gn.current="",ee(""))}if(A!==va.current)return;Cn(D)}if(A!==va.current)return;if(Gy(x)){try{await Ms(x.deviceId)}catch(ve){A===va.current&&(Sn.current="",oe("error"),He(ve instanceof Error?ve.message:String(ve)));return}if(A!==va.current){await ei(x.deviceId).catch(()=>{});return}gn.current=x.deviceId,ee(x.deviceId),Ut.current.add(x.deviceId)}const z=zs("control",x.deviceId),me=`control-session-${A}-${x.deviceId}`;xi.current.set(z,performance.now()),gi.current.delete(z),er.current.delete(z),Ha.current.delete(z),vi.current.delete(z),X(""),xe(""),O(me),ce(x.deviceId),J(!1),oe("connecting"),va.current===A&&Sn.current===x.deviceId&&(Sn.current="")})()},[et,te,ne,P,Wt,Cn,He,nt,ei,ur,Ms]),u.useEffect(()=>{if(!ne||et.some(D=>D.deviceId===ne))return;const x=ne,A=++va.current;oe("stopping"),ur(x,"control-device-disconnected").catch(()=>{}).finally(()=>{A===va.current&&(Cn(x),J(!1),O(""),X(""),xe(""),ce(D=>D===x?"":D),oe("idle"))})},[et,ne,Cn,ur]);const io=Gy(et.find(x=>x.deviceId===ne));u.useEffect(()=>{if(la.current!==null&&(window.clearTimeout(la.current),la.current=null),!ne||P==="idle"||P==="stopping"||P==="error"||nt||Gt==="wall"){ne&&!nt&&Gt==="wall"&&oe(D=>D==="warm"||D==="active"?"active":D);return}oe(D=>D==="idle"||D==="stopping"?D:"warm");const x=ne,A=++va.current;return la.current=window.setTimeout(()=>{la.current=null,oe("stopping"),ur(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{A===va.current&&(Cn(x),J(!1),O(""),X(""),xe(""),ce(D=>D===x?"":D),oe("idle"))})},HM),()=>{la.current!==null&&(window.clearTimeout(la.current),la.current=null)}},[Gt,ne,P,Cn,nt,ur]),u.useEffect(()=>()=>{la.current!==null&&window.clearTimeout(la.current)},[]),u.useEffect(()=>{const A=ne&&(io&&(P==="connecting"||P==="active"||P==="warm"||P==="stopping")||we&&(P==="active"||P==="warm"))?ne:"";if(ss.current=A,un.current)return;const D=async()=>{for(;;){const z=ss.current,me=gn.current;if(me===z)return;if(me){try{await ei(me)}catch(ve){He(ve instanceof Error?ve.message:String(ve))}finally{gn.current===me&&(gn.current="",ee(""))}continue}if(!z)return;try{await Ms(z)}catch(ve){ss.current=gn.current,He(ve instanceof Error?ve.message:String(ve));return}gn.current=z,ee(z),Ut.current.add(z)}};let $;$=D().finally(()=>{un.current===$&&(un.current=null),gn.current!==ss.current&&qe(z=>z+1)}),un.current=$},[ne,we,P,io,ut,He,ei,Ms,Te]);const Vn=ne&&et.find(x=>x.deviceId===ne)||null,dl=!!(nt&&_e&&P==="active"&&Vn?.sessionId&&B?.deviceId===Vn.deviceId&&B.sessionId===Vn.sessionId&&B.streamPurpose==="control"&&B.commandId&&B.captureGeneration>0&&B.monitorIndex===Ys),{state:Ti,sendInput:ti,stats:Sa,error:nc}=gj(Cs&&dl,k),Ei=u.useCallback((x,A)=>!dl||!Vn||!B||x!==Vn.deviceId?!1:ti(x,{...A,controlSessionId:Vn.sessionId,controlCommandId:B.commandId,captureGeneration:B.captureGeneration}),[dl,Vn,B,ti]),dr=dl&&Ti==="open",{state:Ca,lastFrame:Ri,stats:dn,error:fl}=kj(Ee?.deviceId||"",Cu&&Q,k),ni=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",N],["registry",c],["license",H],["wall-stream",Jo],["control-stream",Js],["control-decode",ge],["remote-input",nc],["remote-audio",fl]];for(const[A,D]of x){const $=String(D||"").trim();if(A==="hub"&&I?.requiresHubRestart&&I.stage==="updating"){ni.current.delete(A);continue}if(!$){ni.current.delete(A);continue}ni.current.get(A)!==$&&(ni.current.set(A,$),He($))}},[fl,ge,Js,N,nc,H,c,He,Jo,I]),u.useEffect(()=>{if(!nt||!_e||!Cs||!dr||!Ee)return;const x=($,z)=>{const me=$.target,ve=me?.tagName?.toLowerCase();me?.isContentEditable||ve==="input"||ve==="textarea"||ve==="select"||($.preventDefault(),$.stopPropagation(),Ei(Ee.deviceId,{type:z,monitorIndex:Da(Vt[Ee.deviceId],ma(Ee)),key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:z==="keydown"?$.repeat:!1,shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}))},A=$=>x($,"keydown"),D=$=>x($,"keyup");return window.addEventListener("keydown",A),window.addEventListener("keyup",D),()=>{window.removeEventListener("keydown",A),window.removeEventListener("keyup",D)}},[Cs,dr,_e,Vt,Ee,Ei,nt]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(tr.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!ne||P!=="connecting"&&P!=="active"&&P!=="warm"||oa!=="open")return;const x=ne,A=zs("control",x),D=window.setInterval(()=>{const $=performance.now();if(document.visibilityState!=="visible"||$-tr.current<gh)return;const z=gi.current.get(A)||0,me=er.current.get(A)||0,ve=is.current.get(A)||0,Ne=xi.current.get(A)||$;xi.current.has(A)||xi.current.set(A,Ne);const Ue=z<=0,Ke=Ue?$-Ne>YM:$-z>Oy,sn=z>0&&(me<=0||$-me>Oy);if(!Ke&&sn){const jr=Ps.current.get(A)||0;$-jr>=Hy&&us(x,"control","decoder-paint-stale");return}if(!Ke)return;const Tn=vi.current.get(A)||0;if(Tn>0){if($-Tn<QM)return;vi.current.delete(A)}const Ya=Ha.current.get(A)||0;if(Ya>=XM){if(ul(Ue?"no first frame":"stale stream"))return;J(!1),Xn(!1),oe("error");return}if($-ve<By(KM,Ya))return;Ns([x],Ue?"control-first-frame-timeout":"control-receive-stale")&&(is.current.set(A,$),vi.current.set(A,$),xi.current.set(A,$),Ha.current.set(A,Ya+1))},650);return()=>window.clearInterval(D)},[oa,ne,P,ul,us,Ns]),u.useEffect(()=>{!ge||Zn!=="mode3-h264-hw"||ul(ge)||(J(!1),Xn(!1),oe("error"))},[ge,Zn,ul]),u.useEffect(()=>{!nt||!ne||!Js||oe(x=>x==="error"?x:"error")},[Js,ne,nt]),u.useEffect(()=>{if(Pa!=="open"||!Be.autoStartLive||Jn.length===0)return;const x=window.setInterval(()=>{const A=performance.now();if(document.visibilityState!=="visible"||A-tr.current<gh)return;const D=1e3/Math.max(1,Ci||Be.fps||1),$=Math.max(ZM,Math.ceil(D*4)),z=[];for(const me of Jn){if(z.length>=tT)break;const ve=zs("wall",me),Ne=gi.current.get(ve)||0;if(Ne<=0)continue;const Ue=is.current.get(ve)||0,Ke=er.current.get(ve)||0,sn=A-Ne>$,Tn=Ke<=0||A-Ke>$;if(!sn&&Tn){const Cr=Ps.current.get(ve)||0;A-Cr>=Hy&&us(me,"wall","decoder-paint-stale");continue}if(!sn)continue;const Ya=Ha.current.get(ve)||0;A-Ue>=By(JM,Ya)&&z.push(me)}if(z.length>0&&ll(z,"wall-frame-stale"))for(const me of z){const ve=zs("wall",me);is.current.set(ve,A),Ha.current.set(ve,(Ha.current.get(ve)||0)+1)}},eT);return()=>window.clearInterval(x)},[Ci,Jn,us,ll,Be.autoStartLive,Be.fps,Pa]),u.useEffect(()=>{Fs(Be.fps),qs.current=Date.now(),xa.current=0},[Be.fps,Be.frameMode,Be.adaptiveLoadShedding]),u.useEffect(()=>{qC({h264DecodeAcceleration:Be.h264DecodeAcceleration})},[Be.h264DecodeAcceleration]),u.useEffect(()=>{if(!Wt||nt||!Be.visibleOnlyLive){nn([]);return}const x=Zr.current;if(!x||typeof IntersectionObserver>"u"){nn(Zl);return}const A=Array.from(x.querySelectorAll("[data-live-device-id]"));if(A.length===0){nn([]);return}const D=new Map,$=()=>{const me=bh(A.map(ve=>String(ve.dataset.liveDeviceId||"")).filter(ve=>(D.get(ve)||0)>0));nn(ve=>yh(ve,me)?ve:me)},z=new IntersectionObserver(me=>{for(const ve of me){const Ne=String(ve.target.dataset.liveDeviceId||"");Ne&&D.set(Ne,ve.isIntersecting?ve.intersectionRatio||.01:0)}$()},{root:null,rootMargin:ia.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return A.forEach(me=>z.observe(me)),$(),()=>z.disconnect()},[Zl,Wt,nt,el,Be.visibleOnlyLive,rt]),u.useEffect(()=>{if(!Be.adaptiveLoadShedding||!Be.autoStartLive||Jn.length===0)return;const x=Be.fps;if(Jn.length<=ia.preserveConfiguredFpsDeviceCount){pn!==x&&(Fs(x),qs.current=Date.now(),xa.current=0);return}if(Pa!=="open"||As.sampleMs<500)return;const A=Date.now(),D=Jn.length*pn,$=As.framesPerSecond,z=As.bytesPerSecond,me=Math.max(0,...Jn.map(sn=>Qn[zs("wall",sn)]?.maxIntervalMs||0)),ve=Math.max(0,...Jn.map(sn=>Ji[zs("wall",sn)]?.maxIntervalMs||0)),Ne=D>8&&$>0&&$<D*.72;if($>ia.maxWallFramesPerSecond||z>ia.maxWallBytesPerSecond||me>ia.maxFrameGapMs||ve>ia.maxFrameGapMs||Ne){xa.current=0;const sn=ia.minFps;if(A-qs.current>=ia.downshiftCooldownMs&&pn>sn){const Tn=Math.max(sn,xT(pn,sn));Tn<pn&&(Fs(Tn),qs.current=A)}return}const Ke=$<ia.maxWallFramesPerSecond*ia.lowLoadFrameRatio&&z<ia.maxWallBytesPerSecond*ia.lowLoadByteRatio;if(!Ke||pn>=x){Ke||(xa.current=0);return}if(!xa.current){xa.current=A;return}if(A-xa.current>=ia.recoveryCooldownMs){const sn=Math.min(x,yT(pn,x));sn>pn&&(Fs(sn),qs.current=A,xa.current=0)}},[pn,Jn.length,Jn,Ji,Qn,Pa,As.bytesPerSecond,As.framesPerSecond,As.lastUpdatedAt,As.sampleMs,Be.adaptiveLoadShedding,Be.autoStartLive,Be.frameMode,Be.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){He("Checkout returned. Waiting for Dodo confirmation."),W();const A=window.setInterval(()=>{W()},4e3),D=window.setTimeout(()=>{window.clearInterval(A)},45e3);return()=>{window.clearInterval(A),window.clearTimeout(D)}}x==="cancelled"&&He("Checkout cancelled.")},[W]),u.useEffect(()=>{!Wt&&_e&&ie(!1),!Wt&&Q&&Ie(!1)},[Q,_e,Wt]),u.useEffect(()=>{const x=Ee?.deviceId||"",A=Oe.current;if(Oe.current=x,!A||A===x)return;const D=++ke.current,$=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&Q&&ae.current.set(x,$);let z=!0;return(async()=>{try{const ve=ae.current.get(A);if(ae.current.delete(A),await Ge(`/api/remote/devices/${encodeURIComponent(A)}/audio/stop`,{method:"POST",body:JSON.stringify(ve?{streamId:ve}:{})},k),!z||D!==ke.current||!Q||!x||!Wt||!tl)return;const Ne=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:$,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k);if(Ne.ok===!1)throw new Error(Ne.error||"Remote audio start failed.")}catch(ve){z&&(ae.current.delete(x),Ie(!1),He(ve instanceof Error?ve.message:String(ve)))}})(),()=>{z=!1}},[Q,Wt,k,tl,Ee?.deviceId]),u.useEffect(()=>{const x=et.map($=>$.deviceId),A=new Set(x),D=new Map(et.map($=>[$.deviceId,$]));L($=>{const z=$.filter(me=>A.has(me));return yh($,z)?$:z}),q($=>$&&A.has($)?$:""),K($=>$&&A.has($)?$:""),Bs($=>{let z=!1;const me={};for(const[ve,Ne]of Object.entries($)){const Ue=D.get(ve);if(!Ue){me[ve]=Ne;continue}const Ke=Da(Ne,Ue?ma(Ue):1);me[ve]=Ke,Ke!==Ne&&(z=!0)}return z?me:$}),Ba($=>{const z=$.filter(me=>A.has(me));return yh($,z)?$:z})},[et,Jr]),u.useEffect(()=>{fu([]),Go(!1)},[ks]),u.useEffect(()=>{!Gs||Us!=="selected"||ls.length>0||Fa.length===0||Ba(Fa.map(x=>x.deviceId))},[Fa,ls.length,Us,Gs]),u.useEffect(()=>{try{localStorage.setItem(hw,Ln)}catch{}},[Ln]),u.useEffect(()=>{mT(Be)},[Be]),u.useEffect(()=>{pT(ft)},[ft]),u.useEffect(()=>{dT(Vt)},[Vt]);const ta=u.useCallback(async()=>{const x=new Set(g);x.add(bn);try{const me=await Ge("/api/remote/status",void 0,bn);Sx({endpoint:me.agentEndpoint,endpoint_candidates:[...me.agentEndpointCandidates||[],...me.hostTargetEndpointCandidates||[]]}).forEach(ve=>x.add(ve))}catch{}const A=[...x].sort((me,ve)=>{const Ne=Ue=>{const Ke=Zc(Ue);return Ke==="local"?0:Ke==="loopback"?1:2};return Ne(me)-Ne(ve)||me.localeCompare(ve)});let D=!1,$="",z=!1;try{for(const me of A){const ve=Zc(me);try{if(await Ge("/api/health",void 0,me),ve==="local")return b(!0),To(!0),me;ve==="loopback"&&(D=!0,$=me)}catch{ve==="local"&&(z=!0)}}return D?(z&&He("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),b(!0),To(!0),$||bn):(b(!1),To(!1),"")}catch{return b(!1),To(!1),""}},[g]),In=async()=>{if(De("auth"),$n(!1),await ta(),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();D?.ok===!1&&(He(D.error||"LiveDesk could not open the system browser for Google sign-in."),De(""));return}const{data:x,error:A}=await ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});A&&(He(A.message),De(""))},ai=async()=>{De("auth"),$n(!1),await ct.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?He("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ge("/api/auth/session",{method:"DELETE"},bn).catch(()=>{}),De("")};u.useEffect(()=>{if(!hn)return;const x=D=>{D.target instanceof Element&&(D.target.closest(".account-popover, .rail-account")||$n(!1))},A=D=>{D.key==="Escape"&&$n(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",A),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",A)}},[hn]);const $a=u.useCallback(async(x={})=>{const A=x.silent===!0,D=x.takeover===!0,$=x.requestLocalAccess===!0;if(!a?.user){A||He("Sign in before publishing this host.","error");return}if(!_n.current){_n.current=!0,A||(De("host"),Ct("Hub · 1/4 · Checking the local runtime…"));try{const me=($?await ta():"")||k||bn;if(!(S||await Ge("/api/remote/status",void 0,me)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");A||Ct("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ne=await Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:a.access_token,refreshToken:a.refresh_token,expiresAt:a.expires_at,user:{id:a.user.id,email:a.user.email}})},me);if(!Ne.ok||!Ne.authenticated)throw new Error(Ne.error||"hub-session-sync-failed");A||Ct("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const Ue=await Ge("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:D})},me);if(!Ue.ok)throw new Error(Ue.error||"host-target-failed");if(!A){Ct("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ke=await Ge("/api/hub/status",void 0,me);if(!Ke.hostTargetActive)throw new Error(Ke.hostTargetLease?.lastError||"host-target-not-active-after-sync");const sn=Ke.hostTargetEndpoint||Ke.agentEndpoint||"endpoint ready",Tn=Number(Ke.connectedDeviceCount||0),Ya=Tn>0?`${Tn} client${Tn===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";He(`Hub ready · ${sn} · lease auto-renewal active. ${Ya}`,"success"),($||y)&&(b(!0),To(!0)),M()}d()}catch(z){if(!A){const me=z instanceof Error?z.message:String(z);me.includes("local network access")&&(b(!1),To(!1)),He(`Hub setup failed · ${me}`,"error")}}finally{_n.current=!1,A||De("")}}},[k,y,M,d,ta,a,He,Ct,S]),ds=u.useCallback(async()=>{if(!(!S?.update?.canApply||je==="update")){De("update");try{const x=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},k||bn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const A=[...new Set((x.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],D=!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),$=x.state==="hub-restart-requested"?Date.now():void 0;(A.length>0||D)&&Fe({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:A,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:D,initialHostInstanceId:String(S.hostInstanceId||""),targetManagerVersion:String(x.latestVersion||S.update?.latestVersion||""),targetClientVersion:String(x.latestClientVersion||S.update?.latestClientVersion||""),restartRequestedAt:$,restartDeadlineAt:$?$+Vd:void 0}),Ct(x.state==="hub-restart-requested"?Gd:Ty),M()}catch(x){He(x instanceof Error?x.message:String(x),"error")}finally{De("")}}},[je,k,M,He,Ct,S]);u.useEffect(()=>{const x=I,A=S?.update;if(!x||x.stage!=="updating"||!A)return;const D=A.restartResult?.operationId===x.operationId?A.restartResult:null;if(D?.outcome==="restored"){const Ue=D.error||`The requested Hub ${D.targetVersion||x.targetManagerVersion||"version"} failed verification.`;Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"restored",error:Ue}:Ke),He(`LiveDesk update did not complete. Hub ${D.fallbackVersion||D.appVersion||"the previous version"} was restored. ${Ue}`,"error");return}if(D?.outcome==="failed"){const Ue=D.error||"No verified LiveDesk Hub replacement could be started.";Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),He(`LiveDesk Hub update failed. ${Ue}`,"error");return}if(A.operationId===x.operationId&&A.state==="failed"){const Ue=A.error||"LiveDesk update failed before the Hub replacement completed.";Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),He(Ue,"error");return}if(A.operationId===x.operationId){if(A.state==="hub-restart-requested"&&!x.restartDeadlineAt){const Ue=Date.now();Fe(Ke=>Ke?.operationId===x.operationId?{...Ke,restartRequestedAt:Ue,restartDeadlineAt:Ue+Vd}:Ke),Ct(Gd)}!x.requiresHubRestart&&A.state==="clients-updated"&&(Fe(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),He("LiveDesk clients updated and reconnected successfully.","success"));return}if(!x.requiresHubRestart)return;const $=S.started===!0&&(!x.initialHostInstanceId||S.hostInstanceId&&S.hostInstanceId!==x.initialHostInstanceId),z=!!A.checkedAt,me=Ey(A.currentVersion,x.targetManagerVersion),ve=!x.targetClientVersion||Ey(A.currentClientVersion,x.targetClientVersion),Ne=z&&A.state==="idle"&&A.updateAvailable===!1&&me&&ve;$&&Ne&&(Fe(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),He(`LiveDesk Hub ${A.currentVersion||D?.appVersion||x.targetManagerVersion} restarted and passed version verification.`,"success"))},[He,Ct,S,I]),u.useEffect(()=>{const x=I;if(!x||x.stage!=="updating"||!x.requiresHubRestart||x.restartDeadlineAt)return;const A=()=>{const $=Date.now();Fe(z=>z?.operationId===x.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:$,restartDeadlineAt:$+Vd}:z),Ct(Gd)};if(S?.update?.state==="hub-restart-requested"){A();return}if(!N)return;const D=window.setTimeout(A,$M);return()=>window.clearTimeout(D)},[N,Ct,S?.update?.state,I]),u.useEffect(()=>{const x=I;if(!x||x.stage!=="updating"||!x.requiresHubRestart||!x.restartDeadlineAt)return;const A=Math.max(0,x.restartDeadlineAt-Date.now()),D=x.operationId,$=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${x.targetManagerVersion||"the requested version"} within ${Math.round(Vd/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;Fe(me=>me?.operationId===D&&me.stage==="updating"?{...me,stage:"failed",error:z}:me),He(z,"error")},A);return()=>window.clearTimeout($)},[He,I]),u.useEffect(()=>{if(!I||I.stage!=="updated")return;const x=I.operationId,A=window.setTimeout(()=>{Fe(D=>D?.operationId===x?null:D)},8e3);return()=>window.clearTimeout(A)},[I]),u.useEffect(()=>{if(We!==Ty&&We!==Gd)return;const x=S?.update;if(String(x?.state||"")==="failed"){He(x?.error||"LiveDesk update failed.","error");return}I?.stage==="updated"&&He("")},[We,He,S?.update?.error,S?.update?.state,I?.stage]);const Ts=u.useCallback(async()=>{if(!je){De("pin");try{const A=await Ge("/api/remote/pairing-pin",{method:"POST"},k||bn);if(!A.ok)throw new Error(A.error||"pin-rotation-failed");await M(),He("New PIN published.")}catch(x){He(x instanceof Error?x.message:String(x))}finally{De("")}}},[je,k,M]),ro=u.useCallback(x=>{x&&(q(x),L(A=>A.includes(x)?A:[...A,x]))},[]),lo=u.useCallback(x=>{if(!x)return;const A=ir.has(x);q(D=>A&&D===x?"":x),L(D=>A?D.filter($=>$!==x):D.includes(x)?D:[...D,x])},[ir]),Di=u.useCallback(()=>{L([]),q("")},[js]),ac=u.useCallback(()=>{L(et.map(x=>x.deviceId)),q("")},[et]),vn=u.useCallback((x,A)=>{const D=et.find(z=>z.deviceId===x);if(!D)return;const $=ma(D);$<=1||(Bs(z=>{const ve=(Da(z[x],$)+A+$)%$;return{...z,[x]:ve}}),nt&&(Xn(!1),K(x)))},[et,nt]);u.useEffect(()=>{const x=A=>{if(nt&&_e&&Cs)return;const D=A.target,$=D?.tagName?.toLowerCase();D?.isContentEditable||$==="input"||$==="textarea"||$==="select"||((A.ctrlKey||A.metaKey)&&A.key.toLowerCase()==="a"&&(A.preventDefault(),ac()),A.key==="Escape"&&Di())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[Cs,Di,_e,ac,nt]);const It=async()=>{if(!Ee||Le)return;const x=Ee;if(!bi.has(x.deviceId)){He(wi);return}$e("view-screen"),Me(!1),ie(!1),Xn(!1),K(x.deviceId),pt("control");try{He(`Opening ${ha(x)} screen.`,"success")}finally{$e("")}},gt=(x,A)=>{const D=et.find(z=>z.deviceId===x),$=Da(A,D?ma(D):1);Bs(z=>({...z,[x]:$})),nt?(Xn(!1),K(x)):ro(x)},Ua=async x=>{if(Xn(!1),K(x),pt("control"),!bi.has(x)){ie(!1),He(wi);return}const A=et.find($=>$.deviceId===x);if(Qi(A?.platform)&&(A?.capabilities?.controlPermission===!1||A?.capabilities?.accessibilityPermission===!1)){ie(!1),He("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}ie(!0),He(`Opening remote control${A?` for ${ha(A)}`:""}.`,"success")},ja=async()=>{if(!Ee){He("Select a workstation before playing audio.");return}if(!Wt){He(wi);return}if(!tl){He("Selected workstation does not report remote audio support yet.");return}if(Le)return;const x=!Q,A=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:ae.current.get(Ee.deviceId);x&&A?ae.current.set(Ee.deviceId,A):x||ae.current.delete(Ee.deviceId),$e("audio"),Ie(x);try{await Ge(`/api/remote/devices/${encodeURIComponent(Ee.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...A?{streamId:A}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},k),He(`${x?"Audio started":"Audio stopped"} for ${ha(Ee)}.`,"success")}catch(D){x&&ae.current.delete(Ee.deviceId),Ie(!1),He(D instanceof Error?D.message:String(D),"error")}finally{$e("")}},sc=x=>{const A=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(A)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(A)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(A)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(A)?"The workstation disconnected before the action could be sent.":A},qa=async x=>{if(!Ee||Le)return;const A=Ee,$={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${$} ${ha(A)}? Unsaved work on that computer may be lost.`))){Me(!1),$e(x),He(`Sending ${$.toLowerCase()} request to ${ha(A)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(A.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},k);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");He(`${$} request sent to ${ha(A)}.`,"success"),M()}catch(z){He(sc(z),"error")}finally{$e("")}}},Tu=()=>{Ee&&(Me(!1),be({id:Date.now(),deviceId:Ee.deviceId,instruction:"Run command "}),ie(!1),pt("agents"),He(`Command runner opened for ${ha(Ee)}.`))},ic=async(x,A,D="files")=>{const $=x.filter(Ne=>Ne.file.size>=0);if($.length===0)return{files:0,bytes:0};if(!Wt)throw new Error(wi);if(A.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),me=$.reduce((Ne,Ue)=>Ne+Ue.file.size,0);let ve=0;rs({id:z,status:"reading",progress:1,message:`Preparing ${$.length} ${D}`});try{for(let Ne=0;Ne<$.length;Ne+=1){const Ue=$[Ne],Ke=Ue.file,sn=Math.max(1,Math.ceil(Ke.size/hh));for(let Tn=0;Tn<sn;Tn+=1){const Ya=Tn*hh,Cr=Math.min(Ke.size,Ya+hh),jr=Ke.size===0?new ArrayBuffer(0):await Ke.slice(Ya,Cr).arrayBuffer(),pc=Tn===sn-1;rs({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(ve/Math.max(1,me)*96))),message:`${Ne+1}/${$.length} ${Ue.relativePath}`});const jn=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:A,remoteDirectory:Ln.trim(),name:Ke.name,relativePath:Ue.relativePath,size:Ke.size,type:Ke.type,lastModified:Ke.lastModified,offset:Ya,totalBytes:Ke.size,final:pc,dataBase64:bT(jr)})},k);if(!jn.ok||jn.queued!==A.length)throw new Error(jn.error||`file-chunk-not-queued-${jn.queued}/${A.length}`);ve+=jr.byteLength,await new Promise(rn=>window.setTimeout(rn,0))}}return rs({id:z,status:"queued",progress:100,message:`Sent ${$.length} file${$.length===1?"":"s"} to ${A.length} workstation${A.length===1?"":"s"}`}),window.setTimeout(()=>{rs(Ne=>Ne?.id===z&&Ne.status==="queued"?null:Ne)},4500),{files:$.length,bytes:me}}catch(Ne){throw rs({id:z,status:"failed",progress:100,message:Ne instanceof Error?Ne.message:String(Ne)}),Ne}},Li=async x=>{const A=Fa.length>0?Fa.map(D=>D.deviceId):Ee?[Ee.deviceId]:[];try{await ic(Py(x),A)}catch(D){He(D instanceof Error?D.message:String(D))}},si=async x=>{try{await ic(Py(x),Af)}catch(A){He(A instanceof Error?A.message:String(A))}};u.useEffect(()=>{pu.current=!1},[]);const rc=x=>{x.preventDefault(),x.stopPropagation(),$s(!1),Li(x.dataTransfer.files)},ii=async(x="ltd")=>{if(!a){He("Sign in with Google before checkout.");return}if(R&&x===qt){He("LiveDesk license is already active.");return}if(R&&qt==="pro"){He("LiveDesk Pro is already active.");return}De("checkout");try{const{data:A,error:D}=await ct.functions.invoke("dodo-checkout",{body:{plan:x}});if(D)throw D;if(!A?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(A.checkout_url)}catch(A){He(A instanceof Error?A.message:String(A)),De("")}},fs=nT(),ms=aT(),Es=et.length,hs=ku.filter(x=>Mi.has(x)).length,Ga=cr==="open"&&cl.sampleMs>0?`${cl.framesPerSecond.toFixed(1)} fps`:cr,Re=Ee?nt?ol.get(Ee.deviceId):Mi.get(Ee.deviceId):void 0,fr=Ee?Da(Vt[Ee.deviceId],ma(Ee)):0,_i=Ee?lT(Ee):[],oo=typeof Re?.monitorIndex=="number"?Da(Re.monitorIndex,Math.max(1,Re.monitorCount||1)):fr,xn=(Re&&oo===fr?kw(Re):null)||(Ee?jw(Ee,fr):null),co=xn?`${xn.width}x${xn.height}`:"-",ml=Ee?zs(nt?"control":"wall",Ee.deviceId):"",Mn=ml?Qn[ml]:void 0,ca=ml?Ji[ml]:void 0,vt=ca?.lastInfo,fn=Mn&&Mn.sampleMs>0?`${Mn.framesPerSecond.toFixed(1)} fps`:"waiting",lc=Mn?`#${Mn.totalFrames} / ${fn}`:"waiting",hl=ca&&ca.sampleMs>0?`${ca.framesPerSecond.toFixed(1)} fps`:"waiting",pl=ca&&ca.sampleMs>0?`${ca.changedFramesPerSecond.toFixed(1)} fps`:"waiting",oc=vt?`#${vt.frameSeq} ${vt.decoderLabel} q${vt.queueSize} r${vt.renderQueueSize} d${vt.droppedForLatency} f${vt.decoderFlushCount} t${vt.decoderTimestampFallbacks} io${vt.decoderInputCount}/${vt.decoderOutputCount} ${vt.visualChanged?"changed":"same"}`:"waiting",hr=vt?`${Math.round(vt.queuedForMs)}ms total / ${Math.round(vt.decodedForMs)}ms decode / ${Math.round(vt.scheduledForMs)}ms pace / ${vt.drawMs.toFixed(1)}ms draw`:"-",pr=vt?.targetPaintIntervalMs?`${vt.targetPaintIntervalMs.toFixed(1)}ms / ${(1e3/vt.targetPaintIntervalMs).toFixed(1)} fps`:"-",Mf=ca?`${ca.decoderInputFps.toFixed(1)} in / ${ca.decoderOutputFps.toFixed(1)} out fps`:"waiting",Eu=vt?.canvasPresentation||"-",Tf=vt?`${vt.interactiveBufferWaitCount} waits / ${Math.round(vt.interactiveBufferWaitMs)}ms / ${vt.interactiveQueueDrainCount} drains`:"waiting",Ru=n.framesPerSecond>0?`${n.framesPerSecond.toFixed(1)} fps / p95 ${n.p95IntervalMs.toFixed(1)}ms / max ${n.maxIntervalMs.toFixed(1)}ms / long ${n.longTaskCount} (${Math.round(n.longTaskMs)}ms)`:"waiting",zi=Mn?Re?.frameMode==="mode5-lzo-delta"?`${Yc(Mn.averageFrameBytes)} avg / visual ${Re.deltaVisualTileCount||0} + refresh ${Re.deltaRefreshTileCount||0} / ${Re.deltaTotalTiles||0}`:`${Yc(Mn.averageFrameBytes)} avg / tiny ${Math.round(Mn.tinyFrameRatio*100)}% / repeat ${Math.round(Mn.repeatedFrameRatio*100)}%`:"waiting",cc=Mn&&Mn.sourceSendSampleCount>0?`${Mn.sourceSendAverageMs.toFixed(1)}ms avg / p95 ${Mn.sourceSendP95Ms.toFixed(1)}ms`:"waiting",uo=Ly(Mn),Du=Ly(ca),gr=Mn&&ca?`rx ${_y(Mn)} / paint ${_y(ca)}`:"waiting",gl=Re?Re.frameMode||Re.mode||Re.codec||Re.mimeType:nt?ft.frameMode:Be.frameMode,vr=nt?ft.frameMode:Be.frameMode,fo=gl!==vr?`${vr} -> ${gl}`:vr,Lu=Re?`${Re.width}x${Re.height} ${Yc(Re.byteLength)}`:nt?`${Vs.maxWidth}x${Vs.maxHeight}`:`${Be.maxWidth}x${Be.maxHeight}`,_u=Re?`${Re.isKeyFrame?"key":String(Re.chunkType||"delta")}`:"-",Ii=Re&&Re.monitorCount?`${(Re.monitorIndex??0)+1}/${Re.monitorCount}`:"-",Oi=Re?[`src ${Math.round(Re.sourceGapMs||0)}ms`,`gap ${Math.round(Re.agentSendGapMs||0)}ms`,`tx ${Math.round(Re.agentSendDurationMs||0)}ms`,`pace ${Math.round(Re.agentPaceMs||0)}ms`,`queue ${Math.round(Re.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Re.agentFrameAgeMs||0)}ms`,Re.browserReceivedEpochMs&&Re.receivedAt?`hub ${Math.max(0,Math.round(Re.browserReceivedEpochMs-Date.parse(Re.receivedAt)))}ms`:"",Re.browserReceivedEpochMs&&Re.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Re.browserReceivedEpochMs-Re.hubPacketEpochMs))}ms`:"",Re.droppedByAgent?`drop ${Re.droppedByAgent}`:"",Re.hubIngressDropped?`ingress-drop ${Re.hubIngressDropped}`:"",Re.hubClientDropped?`ws-drop ${Re.hubClientDropped}`:"",Re.captureStageMs?`capture ${Math.round(Re.captureStageMs)}ms`:"",Re.requestedFps?`req ${Math.round(Re.requestedFps)}fps`:"",Re.effectiveFps?`eff ${Math.round(Re.effectiveFps)}fps`:"",Re.captureAverageMs?`avg ${Math.round(Re.captureAverageMs)}ms`:"",Re.captureP95Ms?`p95 ${Math.round(Re.captureP95Ms)}ms`:"",Re.slowFrameCount?`slow ${Math.round(Re.slowFrameCount)}`:"",Re.captureHelperRestarts?`helper ${Math.round(Re.captureHelperRestarts)}`:"",Re.convertMs?`rgb565 ${Math.round(Re.convertMs)}ms`:"",Re.compressMs?`lzo ${Math.round(Re.compressMs)}ms`:"",Re.captureSourceSerial?`cap #${Re.captureSourceSerial}`:"",Re.captureSourceSkipped?`cap skip ${Re.captureSourceSkipped}`:"",Re.frameMode==="mode5-lzo-delta"?`tiles ${Re.deltaVisualTileCount||0}+${Re.deltaRefreshTileCount||0}/${Re.deltaTotalTiles||0}@${Re.deltaTileSize||0}`:"",Re.platformProfile||Re.hardwareEncoder||"-",Re.atlasComposeMs?`atlas ${Re.atlasComposeMs.toFixed(1)}ms`:"",Re.atlasPoolStarved?`pool ${Re.atlasPoolStarved}`:"",Re.atlasTileCount?`tiles ${Re.atlasReadyTiles||0}/${Re.atlasTileCount}`:"",Re.atlasInputRevision?`input #${Re.atlasInputRevision}`:"",Re.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Re.atlasSourceMaxAgeMs)}ms`:"",vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=Ny?`feedback ${Math.round(vt.inputFeedbackMs)}ms`:"",Re.contentHash?`enc ${Re.contentHash.slice(0,6)}`:"",vt?.visualHash?`pix ${vt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "):"-",zu=Ti==="open"?[`${Sa.sentPerSecond.toFixed(1)} hz`,Sa.lastInputSeq>0?`rtt ${Math.round(Sa.lastRoundTripMs)}ms`:"",Sa.lastInputSeq>0?`apply ${Sa.lastAgentApplyMs.toFixed(1)}ms`:"",Sa.droppedPerSecond>0?`drop ${Sa.droppedPerSecond.toFixed(1)}/s`:"",Sa.bufferedAmount>0?`buf ${Yc(Sa.bufferedAmount)}`:"",Sa.lastInputType||"ready"].filter(Boolean).join(" / "):Ti,Iu=vt?.inputFeedbackMs!==void 0&&vt.inputFeedbackAt!==void 0&&performance.now()-vt.inputFeedbackAt<=Ny?`${Math.round(vt.inputFeedbackMs)}ms / input #${vt.inputFeedbackSeq||0}`:"waiting for changed frame",xr=Q?[Ca,`context ${dn.audioContextState}`,`queue ${Math.round(dn.queuedMs)}ms`,`last ${Math.round(dn.lastPacketAgeMs)}ms`,`accepted ${Math.round(dn.lastAcceptedAgeMs)}ms`,`process ${Math.round(dn.localProcessingAgeMs)}ms`,`remote ${Math.round(dn.browserAgeMs)}/${Math.round(dn.captureAgeMs)}ms`,`heartbeat ${Math.round(dn.captureStatusAgeMs)}ms`,`capture ${dn.captureAlive&&dn.helperAlive?"alive":"down"}`,`drop ${dn.drops}`,`resync ${dn.resyncs}`,`restart ${dn.automaticRestarts}`,dn.pendingDecodes>0?`decode ${dn.pendingDecodes}`:"",Ri?`#${Ri.frameSeq}`:"waiting"].filter(Boolean).join(" / "):"off",vl=Re?`#${Re.frameSeq} ${Nh(Re.receivedAt||Re.capturedAt)}`:"waiting",Rs=Math.max(0,cl.bytesPerSecond*8/1e6),yr=or?.atlasReadyTiles??hs,br=or?.atlasTileCount??hs,Ou=yr===br?`${br} tiles`:`${yr}/${br} tiles`,ri=Gn.length>0,Hu=nt?`1 stream / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`:ri?`1 stream / ${Ou} / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`:`${hs} screens / ${Ga} / ${Rs.toFixed(Rs>=10?0:1)}Mbps`,Ds=N?"offline":S?.started?"online":"starting",wr=Fa.length,mo=nt?Ee?ha(Ee):"No workstation":wr===0?"No workstation":wr>1?`${wr} selected`:Ee?ha(Ee):"No workstation",Zt=Oo[kt]||Oo.en,Va=Zt.sync||Oo.en.sync,Sr=r||U?"checking":R?qt==="pro"?"Pro LTD active":`Plus LTD ${et.length}/${Wc}`:wu?`Free ${et.length}/${Vc}`:`Upgrade ${et.length}/${Vc}`,uc=qt==="pro"?"Pro active":je==="checkout"?"Opening":qt==="ltd"?"Pro $199":"Plus $79",xl=R?qt==="pro"?"Pro active":"Upgrade to Pro LTD":a?je==="checkout"?"Opening checkout":qt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":je==="auth"?"Opening Google":"Sign in to buy",yl=qt==="pro"||je==="checkout"||je==="auth"||r||U,dc=a?.user?.user_metadata,bl=$y(dc,"avatar_url","picture"),ps=$y(dc,"full_name","name")||a?.user?.email||"Google",wl=ps.slice(0,1).toUpperCase(),Fu=S?.started?"Local app ready":"Start LiveDesk",fc=l?.active?"Published":a?"Not published":"Sign in required",mc=/^\d{6}$/.test(S?.pairingPin||"")?S?.pairingPin:"------",ua=nf.find(x=>x.width===Be.maxWidth&&x.height===Be.maxHeight)?.id||`${Be.maxWidth}x${Be.maxHeight}`,ka=Be.atlasTileSizeMode==="auto"?"auto":xh.find(x=>x.width===Be.atlasTileWidth&&x.height===Be.atlasTileHeight)?.id||"320x180",li=vh.find(x=>x.width===ft.maxWidth&&x.height===ft.maxHeight)?.id||`${ft.maxWidth}x${ft.maxHeight}`,hc=tf.find(x=>x.id===Be.frameMode)||tf[0],da=x=>{hi(A=>{const D=x.frameMode?Yh(x.frameMode):A.frameMode,$=x.frameMode!==void 0&&D!==A.frameMode;return{...A,...x,frameMode:D,fps:Qh(x.fps??($?ww(D):A.fps),D)}})},oi=x=>{const A=nf.find(D=>D.id===x);A&&da({maxWidth:A.width,maxHeight:A.height})},fa=x=>{if(x==="auto"){da({atlasTileSizeMode:"auto"});return}const A=xh.find(D=>D.id===x);!A?.width||!A?.height||da({atlasTileSizeMode:"fixed",atlasTileWidth:A.width,atlasTileHeight:A.height})},Ot=x=>{x.frameMode!==void 0&&(X(""),xe("")),as(A=>{const D=x.frameMode?Kh(x.frameMode):A.frameMode,$=x.frameMode!==void 0&&D!==A.frameMode,z=x.fps??($?30:A.fps),me=x.maxWidth??A.maxWidth,ve=x.maxHeight??A.maxHeight;return{...A,...x,frameMode:D,fps:xs(z,20,D==="mode3-h264-hw"?60:30,D==="mode3-h264-hw"?60:30),maxWidth:D==="mode3-h264-hw"?me:Math.min(1920,me),maxHeight:D==="mode3-h264-hw"?ve:Math.min(1080,ve)}})},ho=x=>{const A=vh.find(D=>D.id===x);A&&Ot({maxWidth:A.width,maxHeight:A.height})},Wa=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):Gt==="support"&&window.history.pushState({},"","/")),x==="control"){const A=qn||Ws;if(A&&(Xn(!1),K(A.deviceId)),pt(x),!Wt){ie(!1),He(wi);return}ie(!0);return}x==="agents"&&be(null),x==="wall"&&Kt(A=>A+1),pt(x),ie(!1)},tt=je==="update"||I?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(S?.update?.state||""),Et=!!(S?.update?.updateAvailable&&S.update.canApply||tt||!S&&I),an=u.useCallback(x=>{if(!I?.targetIds.includes(x))return;if(I.stage==="updated")return{state:"updated",label:"Updated"};if(I.stage==="restored"||I.stage==="failed")return{state:"failed",label:I.stage==="restored"?"Update restored":"Update failed",error:I.error};const A=S?.update?.operationId===I.operationId?S.update.targets?.find(D=>D.deviceId===x):void 0;switch(A?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:A.error||S?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return A.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[S?.update,I]);return s.jsxs("main",{className:"app-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ob,{size:25})}),s.jsx("nav",{className:"rail-tools",children:AT.map(x=>{const A=x.icon,D=rf(x.tooltip,kt);return s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server":""} ${Gt===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?void $a({takeover:!0,requestLocalAccess:!0}):Wa(x.id),"data-tooltip":Th(x.label,x.tooltip,kt),"aria-label":`${x.label}. ${D}`,type:"button",disabled:x.id==="sync-server"&&je==="host","aria-busy":x.id==="sync-server"&&je==="host",children:[x.id==="sync-server"&&je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(A,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&je==="host"?"Syncing…":x.label})]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[NT.map(x=>{const A=x.icon;return s.jsxs("button",{className:`rail-tool compact ${Gt===x.id?"active":""} accent-${x.accent}`,onClick:()=>Wa(x.id),title:x.label,type:"button",children:[s.jsx(A,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${Vl?"active":""}`,onClick:()=>{pt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),$n(!1),ie(!1),Zi(!1)},title:"Settings",type:"button",children:[s.jsx(Wy,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${a?"signed-in":""}`,onClick:()=>{$n(x=>!x)},disabled:r||je==="auth","aria-expanded":hn,title:a?`Account: ${a.user?.email||ps}`:"Sign in with Google",type:"button",children:[a?bl?s.jsx("img",{src:bl,alt:ps,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:wl}):s.jsx(zl,{size:18}),s.jsx("span",{children:a?"Account":"Google"})]}),hn&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:a&&bl?s.jsx("img",{src:bl,alt:ps,referrerPolicy:"no-referrer"}):a?s.jsx("span",{children:wl}):s.jsx(zl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:a?ps:"Account"}),s.jsx("p",{children:a?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:a?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:Fu}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:fc}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:Sr}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:qt==="free"?"Standard banner":"Removed"})]}),a?s.jsxs("button",{className:"account-popover-action",onClick:ai,disabled:je==="auth",type:"button",children:[s.jsx(Yy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:In,disabled:je==="auth",type:"button",children:[s.jsx(zl,{size:16}),"Sign in with Google"]})]})]})]}),s.jsxs("section",{className:`desk-stage ${gu&&!Dn?"dock-open":""} ${nt?"control-stage":""} ${Kl?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(cn,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]})]}),s.jsxs("div",{className:"topbar-tray",children:[Gs&&!nt&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(Ll,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(ep,{size:15}),s.jsx(m0,{size:16}),s.jsxs("div",{children:[s.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),s.jsxs("span",{children:[s.jsx("small",{children:"Destination"}),s.jsxs("strong",{children:[vu," workstation",vu===1?"":"s"]}),s.jsx("em",{children:Ln.trim()||"Desktop/LiveDeskFiles"})]})]})]}),gu&&!nt&&s.jsxs("div",{className:"top-actions",children:[s.jsx(Cy,{controller:Jl,onError:He}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Screen size",children:kT.map(x=>s.jsx("button",{className:rt===x.id?"active":"",onClick:()=>tn(x.id),type:"button",children:x.label},x.id))})]}),nt&&s.jsx("div",{className:"top-actions",children:s.jsx(Cy,{controller:Jl,onError:He})}),Et?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{ds()},title:I?.error||`Update LiveDesk to ${S?.update?.latestVersion||I?.targetManagerVersion||"latest"}`,"aria-label":tt?"LiveDesk update in progress":`Update LiveDesk to ${S?.update?.latestVersion||I?.targetManagerVersion||"latest"}`,type:"button",disabled:tt||!S?.update?.canApply,"aria-busy":tt,children:[tt?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Xh,{size:19,"aria-hidden":"true"}),tt&&S?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[S.update.completedCount||0,"/",S.update.targetCount]}):null]}):null]})]}),Yl?s.jsxs("section",{className:"doc-page",lang:kt,dir:kt==="ar"?"rtl":"ltr",children:[s.jsxs("section",{className:"doc-hero",children:[s.jsxs("div",{className:"doc-hero-copy",children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(af,{size:16}),Zt.eyebrow]}),s.jsx("h2",{children:Zt.title}),s.jsx("p",{children:Zt.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(h0,{size:17}),Zt.languageLabel]}),s.jsx("select",{value:kt,onChange:x=>ze(x.target.value),children:TT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:Zt.sections.map((x,A)=>{const $=[Ur,Gc,Um,Lt,Il][A]||af;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx($,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:x.title}),s.jsx("p",{children:x.body}),s.jsx("ul",{children:x.points.map(z=>s.jsx("li",{children:z},z))})]})]},x.title)})}),Va&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Um,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Va.title}),s.jsx("p",{children:Va.body})]})]}),s.jsx("ul",{children:Va.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(Lt,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Zt.firewall.title}),s.jsx("p",{children:Zt.firewall.body})]})]}),s.jsx("ul",{children:Zt.firewall.points.map(x=>s.jsx("li",{children:x},x))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Gc,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:Zt.commands.title}),s.jsx("p",{children:Zt.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[Zt.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.manager}),s.jsx("code",{children:ms}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(ms),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.primary}),s.jsx("code",{children:fs}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(fs),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:Zt.commands.slot}),s.jsx("code",{children:`${fs} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(`${fs} 3`),title:"Copy command",type:"button",children:s.jsx(kl,{size:16})})]})]})]})]}):Kl?s.jsx(dM,{hubUrl:k,devices:j,launchRequest:de}):Gs?s.jsx(pN,{hubUrl:k,devices:et,localFeatureAccess:Wt,upgradeNotice:wi,remoteDirectory:Ln,onRemoteDirectoryChange:ns,targetMode:Us,selectedTargetIds:ls,onTargetModeChange:mu,onTargetToggle:x=>Ba(A=>A.includes(x)?A.filter(D=>D!==x):[...A,x]),filePickerRef:ql,folderPickerRef:Gl,onBrowserFileImport:x=>{si(x)},onBrowserFolderImport:x=>{si(x)},onNotice:He,onTransferChange:x=>{if(!x){rs(null);return}const A=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";rs({id:x.id,status:A,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>rs(D=>D?.id===x.id?null:D),4500)}}):ar?s.jsx(ib,{session:a,currentProductKey:"livedesk",appVersion:"",onSignIn:In}):Vl?s.jsx(Dj,{hubUrl:k,runtimeRole:S?.runtimeRole||"hub",runtimeDeviceId:S?.deviceId||"",sessionAccessToken:a?.access_token||"",pin:s.jsxs(Lj,{children:[s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Pair a workstation"}),s.jsx("h3",{children:"Connect another local PC"})]}),s.jsx(en,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:mc}),s.jsxs("button",{className:"text-button ghost compact",onClick:Ts,disabled:!S?.started||je==="pin",type:"button",children:[s.jsx(Is,{size:15}),je==="pin"?"Creating":"New PIN"]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub status"}),s.jsx("h3",{children:Ds})]}),s.jsx("span",{className:`settings-status-dot state-${Ds}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:k||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Es,"/",Jr]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:S?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:Sr})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>$a({takeover:!0,requestLocalAccess:!0}),disabled:!a||je==="host",type:"button",children:[je==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),je==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>ii(qt==="ltd"?"pro":"ltd"),disabled:je==="checkout"||qt==="pro",type:"button",children:[s.jsx(Do,{size:16}),uc]})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File transfer"}),s.jsx("h3",{children:"Client destination folder"})]}),s.jsx(Lo,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:Ln,onChange:x=>ns(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(_j,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall stream"}),s.jsx("h3",{children:"Frame delivery"})]}),s.jsx(nu,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Be.frameMode,onChange:x=>da({frameMode:Yh(x.target.value)}),children:tf.map(x=>s.jsxs("option",{value:x.id,children:[x.label," - ",x.detail]},x.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:Be.h264DecodeAcceleration,onChange:x=>da({h264DecodeAcceleration:pf(x.target.value)}),children:Wh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:Be.fps,onChange:x=>da({fps:Qh(x.target.value,Be.frameMode)}),children:Cp.filter(x=>x<=Sw(Be.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ut?"Atlas tile":"Resolution"}),s.jsx("select",{value:ut?ka:ua,onChange:x=>ut?fa(x.target.value):oi(x.target.value),children:(ut?xh:nf).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:Be.quality,onChange:x=>da({quality:xs(x.target.value,20,95,pa.quality)}),children:zy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"Visibility and load"})]}),s.jsx(cn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.autoStartLive,onChange:x=>da({autoStartLive:x.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.visibleOnlyLive,onChange:x=>da({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ut&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.adaptiveSizeByWall,onChange:x=>da({adaptiveSizeByWall:x.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.adaptiveLoadShedding,onChange:x=>da({adaptiveLoadShedding:x.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Be.showScreenStatus,onChange:x=>da({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:hc.label}),s.jsxs("strong",{children:[zn.maxWidth,"x",zn.maxHeight," / ",pn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>hi(pa),type:"button",children:[s.jsx(Qc,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(zj,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control stream"}),s.jsx("h3",{children:"Low-latency delivery"})]}),s.jsx(Qd,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ft.frameMode,onChange:x=>Ot({frameMode:Kh(x.target.value)}),children:VM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ft.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ft.h264DecodeAcceleration,onChange:x=>Ot({h264DecodeAcceleration:pf(x.target.value)}),children:Wh.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:ft.fps,onChange:x=>Ot({fps:xs(x.target.value,20,60,La.fps)}),children:WM.filter(x=>ft.frameMode==="mode3-h264-hw"||x<=30).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:li,onChange:x=>ho(x.target.value),children:vh.filter(x=>ft.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ft.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ft.quality,onChange:x=>Ot({quality:xs(x.target.value,20,95,La.quality)}),children:zy.map(x=>s.jsx("option",{value:x,children:x},x))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control behavior"}),s.jsx("h3",{children:"Session display"})]}),s.jsx(en,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ft.showScreenStatus,onChange:x=>Ot({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ft.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Vs.maxWidth,"x",Vs.maxHeight," / ",sr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>as(La),type:"button",children:[s.jsx(Qc,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Ij,{hubUrl:k}),captureGallery:s.jsx(vM,{hubUrl:k,onToast:He}),advancedExtras:s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection commands"}),s.jsx("h3",{children:"Developer setup"})]}),s.jsx(kl,{size:20})]}),s.jsxs("div",{className:"settings-command-list",children:[s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Client"}),s.jsx("code",{children:fs}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(fs),title:"Copy client command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${fs} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(`${fs} 3`),title:"Copy slot command",type:"button",children:s.jsx(kl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:ms}),s.jsx("button",{className:"icon-button",onClick:()=>Rl(ms),title:"Copy Hub command",type:"button",children:s.jsx(kl,{size:16})})]})]})]})}):Wl?s.jsxs("section",{className:"pricing-page",children:[s.jsxs("header",{className:"pricing-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(kh,{size:15})," LiveDesk plans"]}),s.jsx("h2",{children:"Choose the plan that fits your wall"}),s.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more workstations, or commercial controls."})]}),s.jsx("button",{className:"pricing-close",onClick:()=>Wa("wall"),title:"Close pricing",type:"button",children:s.jsx(Ja,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:Xl.name}),s.jsxs("small",{children:[et.length,"/",GM(Ks)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${qt==="free"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),s.jsx("strong",{children:"$0"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:Ml.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Vc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:qt==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${qt==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(p0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.ltd.audience}),s.jsx("h3",{children:"Ad-free monitoring"}),s.jsx("p",{children:"More room for personal AI workstations without the standard banner."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Wc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",Ml.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>ii("ltd"):In,disabled:qt!=="free"||je==="checkout"||je==="auth"||r||U,type:"button",children:[s.jsx(Do,{size:16}),qt==="free"?a?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${qt==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(Lt,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Ml.pro.audience}),s.jsx("h3",{children:"For serious operations"}),s.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",Ml.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:a?()=>ii("pro"):In,disabled:qt==="pro"||je==="checkout"||je==="auth"||r||U,type:"button",children:[s.jsx(Do,{size:16}),qt==="pro"?"Pro active":a?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(en,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx(Qd,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(ox,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(Lo,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(Hn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:a?()=>ii(qt==="ltd"?"pro":"ltd"):In,disabled:yl,type:"button",children:[s.jsx(Do,{size:18}),xl]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Dn?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Zr,className:`screen-wall-panel ${qo?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Di()},onDragEnter:x=>{x.preventDefault(),$s(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&$s(!1)},onDrop:rc,children:[Gn.length>0&&s.jsx("canvas",{ref:lr,className:"atlas-source-canvas",width:Ni?.width||1920,height:Ni?.height||1080,"aria-hidden":"true"}),nt?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Ee&&_i.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:_i.map(x=>s.jsxs("button",{className:x.index===fr?"active":"",onClick:()=>gt(Ee.deviceId,x.index),title:oT(x),type:"button",children:[s.jsx("span",{children:x.name||`Display ${x.index+1}`}),x.width>0&&x.height>0&&s.jsxs("small",{children:[x.width,"x",x.height]})]},x.index))}),Ee?s.jsx(jh,{device:Ee,frame:Re,selected:!1,controlEnabled:Cs&&_e&&dr,showStatus:ft.showScreenStatus,monitorIndex:Da(Vt[Ee.deviceId],ma(Ee)),monitorCount:ma(Ee),onSelect:()=>{},onFocusDevice:()=>K(Ee.deviceId),onOpenControl:()=>Ua(Ee.deviceId),onCycleMonitor:x=>vn(Ee.deviceId,x),onCanvasReady:al,sendInput:Ei,presentationReady:uu},Ee.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(en,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Ee&&Ko&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(Lt,{size:22,"aria-hidden":"true"}),s.jsx("strong",{children:"Accessibility permission required"}),s.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ee&&!Ko&&!uu&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[P!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:P==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:P==="error"?"See the notification for details. Reopen Control to retry.":Js||ge?"Control stream is recovering. See the notification for details.":cr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):ut?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${rt}`,onClick:x=>{x.currentTarget===x.target&&Di()},children:el.map((x,A)=>x?s.jsx(jh,{device:x,frame:Mi.get(x.deviceId),selected:ir.has(x.deviceId),controlEnabled:!1,showStatus:Be.showScreenStatus,monitorIndex:Da(Vt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>lo(x.deviceId),onFocusDevice:()=>ro(x.deviceId),onOpenControl:()=>Ua(x.deviceId),onCycleMonitor:D=>vn(x.deviceId,D),onCanvasReady:$c({mode4Enabled:ut,directMode4WallEnabled:cs,isMac:Qi(x.platform)})==="direct"?ea:rl,sendInput:Ei,updateIndicator:an(x.deviceId),presentationReady:Be.autoStartLive&&ya.includes(x.deviceId)?Tt.has(x.deviceId):void 0,showPresentationSpinner:Be.autoStartLive&&ya.includes(x.deviceId)},x.deviceId):s.jsx(qy,{index:A},`slot-${A}`))}):s.jsx("div",{className:`screen-wall size-${rt}`,onClick:x=>{x.currentTarget===x.target&&Di()},children:el.map((x,A)=>x?s.jsx(jh,{device:x,frame:Mi.get(x.deviceId),selected:ir.has(x.deviceId),controlEnabled:Cs&&_e&&dr&&Ee?.deviceId===x.deviceId,showStatus:Be.showScreenStatus,monitorIndex:Da(Vt[x.deviceId],ma(x)),monitorCount:ma(x),onSelect:()=>lo(x.deviceId),onFocusDevice:()=>ro(x.deviceId),onOpenControl:()=>Ua(x.deviceId),onCycleMonitor:D=>vn(x.deviceId,D),onCanvasReady:ea,sendInput:Ei,updateIndicator:an(x.deviceId),presentationReady:Be.autoStartLive&&ya.includes(x.deviceId)?Tt.has(x.deviceId):void 0,showPresentationSpinner:Be.autoStartLive&&ya.includes(x.deviceId)},x.deviceId):s.jsx(qy,{index:A},`slot-${A}`))}),s.jsx(DT,{visible:Su&&!nt})]}),!Vl&&s.jsxs("aside",{className:`right-dock actions-mode ${Dn?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>Zi(x=>!x),"aria-label":Dn?"Show control panel":"Hide control panel",title:Dn?"Show control panel":"Hide control panel",type:"button",children:Dn?s.jsx(ab,{size:18}):s.jsx(tp,{size:18})}),!Dn&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsxs("div",{className:"action-context",children:[s.jsx("span",{children:nt?"Control target":wr>0?"Selection":"No selection"}),s.jsx("strong",{children:mo})]}),s.jsx("input",{ref:Vo,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&Li(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"action-grid",children:[s.jsxs("button",{className:"action-tile primary",onClick:()=>{It()},disabled:!Si||!!Le,type:"button",title:"Open this workstation's screen",children:[Le==="view-screen"?s.jsx(qr,{className:"spin",size:21}):s.jsx(cx,{size:21}),s.jsx("span",{children:Le==="view-screen"?"Opening...":"View Screen"})]}),s.jsxs("button",{className:`action-tile ${_e?"active":""}`,onClick:()=>{if(Ee){if(nt&&_e){ie(!1),He("Remote control paused. Screen viewing stays on.");return}Ua(Ee.deviceId)}},disabled:!Cs||!!Le,title:Ko?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":Cs?dr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation",type:"button",children:[s.jsx(Qd,{size:21}),s.jsx("span",{children:_e&&Ti==="connecting"?"Connecting...":"Remote Control"})]}),s.jsxs("button",{className:`action-tile ${Q?"active":""}`,onClick:()=>{ja()},disabled:!Cu||!!Le,type:"button",title:tl?Q?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation",children:[Le==="audio"?s.jsx(qr,{className:"spin",size:21}):s.jsx(ox,{size:21}),s.jsx("span",{children:Le==="audio"?"Updating...":Q?"Mute Audio":"Hear Audio"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{He(`Choose files to send to ${mo}.`),Vo.current?.click()},disabled:!!Le||!Wt||(nt?!Ee:Fa.length===0),type:"button",title:"Choose files and send them to the selected workstation",children:[s.jsx(Lo,{size:21}),s.jsx("span",{children:"Send Files"})]}),s.jsxs("button",{className:"action-tile",onClick:()=>{qa("restart")},disabled:!Ee||!Wt||!Ql||!!Le,type:"button",title:Ql?"Restart the selected workstation":"Restart requires a current LiveDesk Client",children:[Le==="restart"?s.jsx(qr,{className:"spin",size:21}):s.jsx(Qc,{size:21}),s.jsx("span",{children:Le==="restart"?"Sending...":"Restart"})]}),s.jsxs("button",{className:`action-tile ${he?"active":""}`,onClick:()=>Me(x=>!x),disabled:!Ee||!Wt||!Ql||!!Le,type:"button",title:Ql?"Lock, sleep, or shut down this workstation":"Power options require a current LiveDesk Client","aria-expanded":he,children:[s.jsx(ux,{size:21}),s.jsx("span",{children:"Power Options"})]}),s.jsxs("button",{className:"action-tile",onClick:Tu,disabled:!Ee||!Wt||!yu||!!Le,type:"button",title:yu?"Open the command runner for this workstation":"Command runner requires a current LiveDesk Client",children:[s.jsx(Gc,{size:21}),s.jsx("span",{children:"Run Command"})]})]}),he&&Ee&&s.jsxs("div",{className:"power-action-menu",role:"group","aria-label":`Power options for ${ha(Ee)}`,children:[s.jsxs("button",{type:"button",onClick:()=>{qa("lock")},children:[s.jsx(Is,{size:16}),"Lock"]}),s.jsxs("button",{type:"button",onClick:()=>{qa("sleep")},children:[s.jsx(g0,{size:16}),"Sleep"]}),s.jsxs("button",{type:"button",className:"danger",onClick:()=>{qa("shutdown")},children:[s.jsx(ux,{size:16}),"Shut Down"]})]})]}),Ee&&os&&s.jsxs("section",{className:"side-panel selected-panel",children:[s.jsxs("div",{className:"machine-detail-head",children:[s.jsxs("div",{className:"panel-title",children:[s.jsx(en,{size:17}),s.jsx("h2",{children:"Machine detail"})]}),s.jsx("span",{className:`machine-health state-${os.state}`,children:os.label})]}),s.jsxs("div",{className:"machine-title",children:[s.jsx("strong",{children:ha(Ee)}),s.jsx("span",{children:os.role})]}),s.jsx("div",{className:"machine-metric-grid",children:os.metrics.map(x=>s.jsxs("article",{className:`machine-metric state-${x.state}`,children:[s.jsx("span",{children:x.label}),s.jsx("strong",{children:x.value}),s.jsx("small",{children:x.detail}),x.ratio!==void 0&&s.jsx("i",{children:s.jsx("b",{style:{width:`${Math.round(x.ratio*100)}%`}})})]},x.id))}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(cn,{size:15}),s.jsx("span",{children:"Stream"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Frames"}),s.jsx("dd",{children:lc}),s.jsx("dt",{children:nt?"Control RX":ri?"Atlas RX":"Wall RX"}),s.jsx("dd",{children:Hu}),s.jsx("dt",{children:"Painted"}),s.jsx("dd",{children:hl}),s.jsx("dt",{children:nt?"Encoded changes":"Visual samples"}),s.jsx("dd",{children:pl}),s.jsx("dt",{children:"Decoder"}),s.jsx("dd",{children:oc}),s.jsx("dt",{children:"Decoder IO"}),s.jsx("dd",{children:Mf}),s.jsx("dt",{children:"Canvas"}),s.jsx("dd",{children:Eu}),s.jsx("dt",{children:"Control buffer"}),s.jsx("dd",{children:Tf}),s.jsx("dt",{children:"Browser RAF"}),s.jsx("dd",{children:Ru}),s.jsx("dt",{children:"Latency"}),s.jsx("dd",{children:hr}),s.jsx("dt",{children:"Cadence"}),s.jsx("dd",{children:pr}),s.jsx("dt",{children:"Source send"}),s.jsx("dd",{children:cc}),s.jsx("dt",{children:"Packet mix"}),s.jsx("dd",{children:zi}),s.jsx("dt",{children:"Receive gap"}),s.jsx("dd",{children:uo}),s.jsx("dt",{children:"Paint gap"}),s.jsx("dd",{children:Du}),s.jsx("dt",{children:"Seq gap"}),s.jsx("dd",{children:gr}),s.jsx("dt",{children:"Selected"}),s.jsx("dd",{children:vl}),s.jsx("dt",{children:"Requested"}),s.jsx("dd",{children:fo}),s.jsx("dt",{children:"Mode"}),s.jsx("dd",{children:gl}),s.jsx("dt",{children:"Chunk"}),s.jsx("dd",{children:_u}),s.jsx("dt",{children:"Size"}),s.jsx("dd",{children:Lu}),s.jsx("dt",{children:"Native"}),s.jsx("dd",{children:co}),s.jsx("dt",{children:"Monitor"}),s.jsx("dd",{children:Ii}),s.jsx("dt",{children:"Source"}),s.jsx("dd",{children:Oi}),s.jsx("dt",{children:"Input"}),s.jsx("dd",{children:zu}),s.jsx("dt",{children:"Audio"}),s.jsx("dd",{children:xr}),nt&&s.jsxs(s.Fragment,{children:[s.jsx("dt",{children:"Visual feedback"}),s.jsx("dd",{children:Iu})]})]})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Gc,{size:15}),s.jsx("span",{children:"Local services"})]}),s.jsx("div",{className:"tool-probe-list",children:os.tools.map(x=>s.jsxs("span",{className:`tool-probe state-${x.status}`,children:[s.jsx("b",{children:x.label}),s.jsx("em",{children:x.detail})]},x.id))})]}),s.jsxs("section",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Bo,{size:15}),s.jsx("span",{children:"Workload"})]}),s.jsxs("div",{className:"workload-card",children:[s.jsx("strong",{children:os.taskLabel}),s.jsx("span",{children:os.taskStatus}),os.taskSummary&&s.jsx("p",{children:os.taskSummary})]})]}),s.jsxs("div",{className:"machine-section",children:[s.jsxs("div",{className:"machine-section-title",children:[s.jsx(Ur,{size:15}),s.jsx("span",{children:"System"})]}),s.jsxs("dl",{className:"facts compact",children:[s.jsx("dt",{children:"Platform"}),s.jsxs("dd",{children:[Ee.platform||"-"," ",Ee.arch||""]}),s.jsx("dt",{children:"Release"}),s.jsx("dd",{children:_a(Ee.status,"release")||"-"}),s.jsx("dt",{children:"Uptime"}),s.jsx("dd",{children:Aw(ln(Ee.status,"uptimeSec"))}),s.jsx("dt",{children:"Last seen"}),s.jsx("dd",{children:Nh(Ee.lastSeenAt||Ee.connectedAt)}),s.jsx("dt",{children:"Agent"}),s.jsx("dd",{children:Ee.agentVersion||"-"}),s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:Ee.remoteAddress||"-"})]})]}),s.jsxs("button",{className:"text-button full",onClick:()=>{It()},disabled:!Si||!!Le,type:"button",children:[s.jsx(cx,{size:16}),"View screen"]})]})]})]})]})})]}),Un&&s.jsxs("aside",{className:`transfer-bar state-${Un.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Un.status==="queued"?s.jsx(Hn,{size:18}):Un.status==="failed"?s.jsx(Ja,{size:18}):s.jsx(Jy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:Un.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Un.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,Un.progress)),"%"]})]}),wn&&s.jsxs("aside",{className:`livedesk-toast tone-${wn.tone}`,role:wn.tone==="error"?"alert":"status","aria-live":wn.tone==="error"?"assertive":"polite","aria-busy":wn.tone==="progress",children:[wn.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:wn.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>He(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ja,{size:15})})]})]})}function _T(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function zT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of _T())try{const v=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!v.ok)continue;const y=(await v.json()).role==="hub"?"hub":"client";c=!0,l||r(y);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&r("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?s.jsx(wC,{}):s.jsx(LT,{}):s.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[s.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),s.jsx("strong",{children:"Starting LiveDesk"}),s.jsx("p",{children:"Loading this computer's assigned role..."})]})}j0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(zT,{})}));