livedesk 0.1.408 → 0.1.409

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.
@@ -22,4 +22,4 @@ ${je}`:w==="execute"?`Execute this request within the configured LiveDesk approv
22
22
  ${je}`:je,Un=m==="auto"?`Auto target selection is enabled. Inspect the allowed workstations and use only the most suitable target or targets for this request.
23
23
 
24
24
  ${ua}`:ua;if(!Xe){try{if(Y==="custom"){const $t=await nM(n,L,ae);if(!$t.ok)throw new Error($t.error||"Custom Agent policy could not be saved.")}const tt=await QN(n,{instruction:Un,deviceIds:gt,permissionMode:Y,customPolicyId:L});if(!tt.ok||!tt.runId)throw new Error(tt.error||"Codex Agent run could not be started.");P(tt.approvals||[]),ve({runId:tt.runId,stage:tt.stage||tt.status||"queued",message:tt.progressMessage||"Codex request queued on the Hub."}),R(tt.runId);return}catch(tt){try{const $t=await KN(n,Un);$t.ok&&$t.plan&&(Xe={operation:$t.plan.operation,query:$t.plan.targetQuery})}catch{A($t=>[...$t,{type:"error",id:Tl("unsupported"),text:mM(tt)}])}}if(!Xe)return}try{const tt=await sM(n,{instruction:Un,deviceIds:gt,operation:Xe.operation,targetQuery:Xe.query});if(!tt.ok||!tt.batch||!tt.batchId)throw new Error(tt.error||"작업을 만들지 못했습니다.");const $t={type:"task",id:Tl("task"),batchId:tt.batchId,operation:Xe.operation,instruction:je,states:zd(tt.batch,a),status:tt.batch.status};Z.current.add(tt.batchId),A(an=>[...an,$t]),k(tt.batchId)}catch(tt){X(tt instanceof Error?tt.message:String(tt))}},$e=async(J,Re)=>{ie(J.approvalId);try{const ze=await eM(n,J.runId,J.approvalId,Re);if(!ze.ok)throw new Error(ze.error||"Agent approval could not be applied.");await Te(J.runId)}catch(ze){X(ze instanceof Error?ze.message:String(ze))}finally{ie("")}},et=async J=>{ie(J.approvalId);try{const Re=await tM(n,J.runId,J.approvalId);if(!Re.ok)throw new Error(Re.error||"Agent approval could not be rejected.");await Te(J.runId)}catch(Re){X(Re instanceof Error?Re.message:String(Re))}finally{ie("")}},Mt=async(J,Re)=>{O(J);try{if(Re){const je=await ZN(n,Re);for(const Xe of je.taskBatches||[])se(Xe);R(Xe=>Xe===Re?"":Xe),ve(Xe=>Xe?.runId===Re?null:Xe);return}const ze=await rM(n,J);se(ze),k(je=>je===J?"":je)}catch(ze){X(ze instanceof Error?ze.message:String(ze))}finally{O("")}},ke=async()=>{if(!(K||!N&&!T)){I(!0);try{const J=await JN(n);if(!J.ok)throw new Error(J.error||"모든 Agent 작업을 취소하지 못했습니다.");k(""),R(""),ve(null),P([]),A(Re=>Re.map(ze=>ze.type==="task"&&["queued","running"].includes(ze.status)?{...ze,status:"cancelled",states:ze.states.map(je=>["queued","running"].includes(je.status)?{...je,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:je)}:ze))}catch(J){X(J instanceof Error?J.message:String(J))}finally{I(!1)}}},Ye=async J=>{O(J);try{const Re=await lM(n,J);if(!Re.ok||!Re.batch||!Re.batchId)throw new Error(Re.error||"재시도하지 못했습니다.");Oe.current.delete(Re.batchId),A(ze=>ze.map(je=>je.type==="task"&&je.batchId===J?{...je,batchId:Re.batchId,states:zd(Re.batch,a),status:Re.batch.status}:je)),k(Re.batchId)}catch(Re){X(Re instanceof Error?Re.message:String(Re))}finally{O("")}},rt=J=>{C(J),de(!1),window.requestAnimationFrame(()=>Se.current?.focus())},vt=u.useMemo(()=>a.filter(lf),[a]),vn=u.useMemo(()=>vt.filter(J=>v.includes(J.deviceId)),[vt,v]),It=m==="auto"?`Auto · ${vt.length} available`:m==="all"?`All ${vt.length} computers`:vn.length===1?rf(vn[0]):`${vn.length} selected`,Zt=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":vn.length>0?vn.map(rf).join(" · "):"Select one or more computers on the Wall.",ht=m==="selected"&&vn.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],$n=m==="selected"?vn.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Gt=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return s.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&s.jsxs("header",{className:"agent-console-header",children:[s.jsxs("div",{className:"agent-console-title",children:[s.jsx("span",{className:"agent-console-mark",children:s.jsx(Ls,{size:16})}),s.jsxs("div",{children:[s.jsx("small",{children:"Live agent"}),s.jsx("strong",{children:"Agent Console"})]}),s.jsx("i",{children:"Ready"})]}),s.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:It}),s.jsx("small",{children:Zt})]}),s.jsxs("div",{className:"agent-console-target-modes",children:[s.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[s.jsx(ri,{size:12})," Selected"]}),s.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[s.jsx(Qc,{size:12})," All"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx(Qc,{size:12})," Group"]}),s.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[s.jsx(Ls,{size:12})," Auto"]})]})]}),s.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(J=>s.jsxs("button",{className:w===J?"active":"",onClick:()=>y(J),type:"button",children:[J==="auto"?s.jsx(Ls,{size:12}):J==="execute"?s.jsx(Yt,{size:12}):null,J[0].toUpperCase()+J.slice(1)]},J))})]}),s.jsxs("div",{className:"agents-workspace",children:[(N||T)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[He.length," workstations · ",dM(Y)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{ke()},disabled:K,children:K?"Stopping…":"Stop all"})]}),Q&&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(uf,{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:()=>U(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const J=Q;U(null),ue(!0),Be(J.instruction,J.targetIds,!0)},children:"Run with Full Access"})]})]})}),be&&s.jsx("div",{className:"agents-error",role:"alert",children:be}),s.jsx(RN,{items:j,onCancel:Mt,onRetry:Ye,busyBatchId:q,approvals:te,onApprove:$e,onReject:et,busyApprovalId:ye,progress:me,emptyTitle:d?$n:void 0,emptyBody:d?Gt:void 0}),d&&j.length===0&&!me&&s.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ht.map(J=>s.jsx("button",{type:"button",onClick:()=>rt(J),children:J},J))}),s.jsxs("div",{className:"agents-composer-shell",children:[$&&s.jsx(WN,{devices:a,targetMode:m,selectedIds:v,permissionMode:Y,customCategories:ae,onSelectPrompt:rt,onClose:()=>de(!1)}),s.jsx(yN,{ref:Se,value:b,onChange:C,onSubmit:()=>{Be()},onOpenSuggestedTasks:()=>de(J=>!J),suggestedOpen:$,suggestedTaskCount:_e,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(YN,{devices:a,mode:m,selectedIds:v,onModeChange:p,onToggle:J=>g(Re=>Re.includes(J)?Re.filter(ze=>ze!==J):[...Re,J]),permissionMode:Y,onPermissionModeChange:J=>{_(J),J!=="full-access"&&ue(!1)}}),Y==="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:bN.map(J=>s.jsxs("label",{children:[s.jsx("span",{children:fM(J)}),s.jsxs("select",{value:ae[J],onChange:Re=>G(ze=>({...ze,[J]:Re.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"})]})]},J))})]})]})]})}function iw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function rw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function lw(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:iw(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 rw(c));return await c.json()}async function hM(n,a){return await Ge("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:iw(n.target)})},a)}async function pM(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 rw(c));return await c.json()}async function gM(n,a,r){return await Ge(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function xy(n,a){await Ge(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function vM(n){return await Ge("/api/captures",void 0,n)}function yy(n,a){return`${Wr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function xM(n,a){return await Ge(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function yM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await vM(n)).captures||[])}catch(v){a(v instanceof Error?v.message:String(v))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async v=>{const g=yy(v.id,n);if(navigator.share)try{await navigator.share({title:v.fileName,url:g});return}catch{}window.open(g,"_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(v=>{const g=yy(v.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[v.mimeType.startsWith("image/")?s.jsx("img",{src:g,alt:v.target.label}):s.jsx("video",{src:g,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:v.fileName}),s.jsxs("small",{children:[v.target.label," · ",new Date(v.createdAt).toLocaleString()," · ",Math.ceil(v.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(g,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(o0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${g}?download=1`,download:v.fileName,children:s.jsx(Qh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(v)},type:"button",children:s.jsx(c0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${v.fileName}?`)&&xM(v.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(Xh,{size:15})})]})]})]},v.id)})})]})}function Id(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 by({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async y=>{try{await y()}catch(b){l?.(b instanceof Error?b.message:String(b))}},v=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
25
- Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},g=c.recording?`Stop recording · ${Id(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Id(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":g,title:g,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(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.recordingStartedAt)})]}):s.jsx(Xy,{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 v(),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":w,title:w,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(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.timelapseStartedAt)})]}):s.jsx(f0,{size:17})})]})}async function bM(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),v=Math.floor(c/m),g=document.createElement("canvas");g.width=Math.max(320,p*d),g.height=Math.max(180,v*m);const w=g.getContext("2d",{alpha:!1});if(!w)return g;w.fillStyle="#0b1220",w.fillRect(0,0,g.width,g.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const b=r[y],C=y%d,j=Math.floor(y/d),A=C*p,N=j*v,k=b.canvas,T=Math.min(p/k.width,v/k.height),R=Math.max(1,Math.floor(k.width*T)),q=Math.max(1,Math.floor(k.height*T)),O=A+Math.floor((p-R)/2),Y=N+Math.floor((v-q)/2);w.drawImage(k,O,Y,R,q),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,N+v-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,A+9,N+v-9))}return g}function wM(n){return n?.signature||"none"}function SM(n){return n?.label||"No capture target"}function wy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function CM(){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 jM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function kM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${jM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${CM()}.png`}async function AM(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 lw(l,{kind:"screenshot",fileName:kM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function ow(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function NM(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 cw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=ow();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await hM({kind:r,fileName:NM(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,v=!1,g=null,w=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const b=p++;w=w.then(()=>pM(l.sessionId,b,y.data,n.hubUrl).then(()=>{})).catch(C=>{g=g||(C instanceof Error?C:new Error(String(C))),n.onError?.(g)})},d.onerror=()=>{g=new Error("Video recording stopped unexpectedly."),n.onError?.(g)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!v){if(v=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await w,g)throw await xy(l.sessionId,n.hubUrl).catch(()=>{}),g;await gM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{v||(v=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await xy(l.sessionId,n.hubUrl).catch(()=>{}))}}}class MM{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=ow();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 lw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function TM(n,a,r,l,c){const d=await cw({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 uw="livedesk.captureSettings";function EM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(uw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function RM(n){const[a,r]=u.useState(EM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,v]=u.useState(0),[g,w]=u.useState(!1),y=u.useRef(void 0),b=u.useRef(!1),C=u.useRef(""),j=u.useRef(null),A=u.useRef(null),N=u.useRef(null),k=u.useRef(null),T=u.useRef(new MM),R=n.sourceRegistry.resolveCurrentTarget(),q=wM(R),O=SM(R),Y=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(uw,JSON.stringify(a)),!b.current)return;const U=JSON.stringify(a);U!==C.current&&(C.current=U,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(W=>{y.current=Number(W.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let U=!0;return Ge("/api/settings",void 0,n.hubUrl).then(W=>{if(!U)return;const ue=W.settings?.filesAudio||{},be=typeof ue.rollingBufferEnabled=="boolean"?ue.rollingBufferEnabled:a.rollingEnabled,X=ue.recordingQuality==="high"?"high":"standard",$=[5,10,30,60].includes(Number(ue.timelapseIntervalSeconds))?Number(ue.timelapseIntervalSeconds):a.timelapseIntervalSeconds,de=typeof ue.includeRemoteCursor=="boolean"?ue.includeRemoteCursor:a.includeRemoteCursor,me={rollingEnabled:be,recordingQuality:X,timelapseIntervalSeconds:$,includeRemoteCursor:de};y.current=Number(W.revision||0),C.current=JSON.stringify(me),b.current=!0,r(me)}).catch(()=>{b.current=!0}),()=>{U=!1}},[n.hubUrl]);const _=u.useCallback(async U=>{if(U.sourceCanvas&&U.sourceCanvas.width>0&&U.sourceCanvas.height>0)return{target:wy(U),canvas:U.sourceCanvas,cleanup:()=>{}};const W=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let ue=!1;const be=window.setInterval(async()=>{if(ue)return;const X=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!X||ue||((W.width!==X.width||W.height!==X.height)&&(W.width=X.width,W.height=X.height),W.getContext("2d")?.drawImage(X,0,0))},100);return{target:wy(U),canvas:W,cleanup:()=>{ue=!0,window.clearInterval(be)}}},[n.sourceRegistry]);u.useEffect(()=>{const U=T.current;if(!a.rollingEnabled||!R||!Y){U.stop(),v(0);return}let W=!1,ue=null;return(async()=>{try{if(ue=await _(R),W)return;await U.start(ue.canvas,ue.target);const X=window.setInterval(()=>v(Math.round(U.seconds)),500),$=()=>{window.clearInterval(X),ue?.cleanup()};U.__cleanup=$}catch(X){W||n.onToast(X instanceof Error?X.message:String(X))}})(),()=>{W=!0,U.stop(),U.__cleanup?.(),U.__cleanup=void 0,v(0)}},[_,n.onToast,a.rollingEnabled,q,Y]);const L=u.useCallback(U=>r(W=>({...W,rollingEnabled:U})),[]),ae=u.useCallback(U=>r(W=>({...W,recordingQuality:U})),[]),G=u.useCallback(U=>r(W=>({...W,timelapseIntervalSeconds:U})),[]),te=u.useCallback(async()=>{const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let W=null;try{W=await _(U),await AM(W.canvas,W.target,n.hubUrl),n.onToast("Screenshot saved")}finally{W?.cleanup(),w(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),P=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await cw({canvas:W.canvas,target:W.target,fps:U.type==="control"?30:15,hubUrl:n.hubUrl,onError:be=>n.onToast(be.message)});A.current=W.cleanup,j.current=ue,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const U=j.current;if(U){w(!0);try{await U.stop(),n.onToast("Recording saved")}finally{j.current=null,A.current?.(),A.current=null,c(0),w(!1)}}},[n.onToast]),ie=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(U,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await TM(W.canvas,W.target,a.timelapseIntervalSeconds,n.hubUrl,be=>n.onToast(be.message));k.current=W.cleanup,N.current=ue,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const U=N.current;if(U){w(!0);try{await U.stop(),n.onToast("Timelapse saved")}finally{N.current=null,k.current?.(),k.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const U=W=>{!j.current&&!N.current||(W.preventDefault(),W.returnValue="")};return window.addEventListener("beforeunload",U),()=>window.removeEventListener("beforeunload",U)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),A.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:g,targetLabel:O}),[p,g,l,a.rollingEnabled,O,d]),settings:a,videoSupported:Y,targetKey:q,setRollingEnabled:L,setRecordingQuality:ae,setTimelapseInterval:G,takeScreenshot:te,startRecording:P,stopRecording:ye,saveLast30Seconds:ie,startTimelapse:K,stopTimelapse:I}}const DM=120,LM=999,Hc=5,Bc=30,_M=Number.POSITIVE_INFINITY,dw="livedesk.remoteDirectory",$h="livedesk.localHubAccessEnabled",fw="livedesk.streamSettings",Uh=16,mw="livedesk.controlStreamSettings",qh=6,hw="livedesk.wallMonitorSelections",pw=1,hh=512*1024,Gh="".trim(),gw="".trim(),Sy="livedesk-adsense-script",ph=!!Gh&&!!gw,zM=1e3/60,gh=1500,IM=650,OM=1800,HM=650,BM=2500,Cy=1500,jy=15e3,FM=6e4,ky=240,PM=1024,$M=480,UM=270,Ay="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Od="LiveDesk is replacing the Hub and verifying the requested version.",Hd=5*6e4,qM=5e3;function Pr({label:n,tooltip:a,disabled:r=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){return s.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":a,children:s.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:r,"aria-label":n,"aria-pressed":d,type:"button",children:p})})}function GM(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 El={free:{name:"Free",price:"$0",limit:Hc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Bc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:_M,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},vw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ny(n,a){const r=m=>{const v=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(!v)return null;const g=v[4]?v[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return g.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(v[1]),Number(v[2]),Number(v[3])],prerelease:g}},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],v=c.prerelease[m];if(p===void 0||v===void 0)return v===void 0;if(p!==v){if(typeof p=="number"&&typeof v=="number")return p>v;if(typeof p=="number")return!1;if(typeof v=="number"||p>v)return!0;if(p<v)return!1}}return!0}function Rs(n,a){return`${n}:${a}`}const xa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:vw["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},Ia={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function vh(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 xw(n,a){n.push(a),n.length>ky&&n.splice(0,n.length-ky)}function My(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 Ty(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),xw(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 Ey(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 Ry(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function VM(n){return Number.isFinite(n)?String(n):"30+"}const Wd=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Vh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],WM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],Yd=[{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}],xh=Yd.filter(n=>n.width>=1280),yh=[{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}],bp=[1,2,5,8,12,20,30],YM=[20,30,60],Dy=[45,60,75,90],Ly={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},ca={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:li.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},_y=2200,KM=8e3,QM=3500,XM=7e3,ZM=2,JM=2600,eT=4200,tT=750,nT=2,zy=4200;function Iy(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Wc(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Ka(n){return n.deviceName||n.hostname||n.deviceId}function aT(){return"npx -y --prefer-online livedesk@latest client"}function sT(){return"npx -y --prefer-online livedesk@latest"}function iT(){try{return localStorage.getItem(dw)||""}catch{return""}}function rT(){try{return localStorage.getItem($h)==="1"}catch{return!1}}function To(n){try{n?localStorage.setItem($h,"1"):localStorage.removeItem($h)}catch{}}function ds(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Wh(n){const a=String(n||"").trim();return Wd.some(r=>r.id===a)?a:xa.frameMode}function cf(n){const a=String(n||"").trim();return Vh.some(r=>r.id===a)?a:xa.h264DecodeAcceleration}function Yh(n){return n==="mode3-h264-hw"?n:Ia.frameMode}function yw(n){return vw[n]||12}function bw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Kh(n,a){return ds(n,1,bw(a),yw(a))}function Pl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function va(n){const a=Pl(n.status),r=Pl(a.screens),l=Pl(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 qr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function lT(n){const a=Pl(n.status),l=[Pl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Pl(d));return[]}function ww(n,a){const r=lT(n),l=r.find(v=>Number(v.index)===a)||r[a]||r[0]||{},c=qr(l.width),d=qr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(v=>typeof v=="string"&&v.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 oT(n){const a=va(n);return Array.from({length:a},(r,l)=>ww(n,l))}function cT(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 Sw(n,a){const r=ww(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Pl(n.status),c=qr(l.screenWidth||l.width),d=qr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Cw(n){if(!n)return null;const a=qr(n.sourceWidth)||qr(n.width),r=qr(n.sourceHeight)||qr(n.height);return a>0&&r>0?{width:a,height:r}:null}function uT(n,a,r){const d=((typeof a?.monitorIndex=="number"?za(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?Cw(a):null)||Sw(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Bd=16/9;function za(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 dT(){try{const n=localStorage.getItem(hw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==pw||!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 fT(n){try{localStorage.setItem(hw,JSON.stringify({version:pw,selections:n}))}catch{}}function mT(){try{const n=JSON.parse(localStorage.getItem(fw)||"{}"),a=Number(n.version);if(![Uh,15,14,13,12,11].includes(a))return xa;const r=Wh(n.frameMode),l=ds(n.maxWidth,320,3840,xa.maxWidth),c=ds(n.maxHeight,180,2160,xa.maxHeight);return{frameMode:r,h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:a<Uh&&r==="mode3-h264-hw"?xa.fps:Kh(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:ds(n.quality,20,95,xa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:xa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:xa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:xa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:xa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:xa.adaptiveSizeByWall}}catch{return xa}}function hT(n){try{localStorage.setItem(fw,JSON.stringify({...n,version:Uh}))}catch{}}function pT(){try{const n=JSON.parse(localStorage.getItem(mw)||"{}"),a=Number(n.version);if(![qh,5,4,3,2,1].includes(a))return Ia;const r=ds(n.fps,20,60,Ia.fps),l=a<qh;return{frameMode:l?Ia.frameMode:Yh(n.frameMode),h264DecodeAcceleration:l?Ia.h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:l?Ia.fps:r,maxWidth:ds(n.maxWidth,1280,3840,Ia.maxWidth),maxHeight:ds(n.maxHeight,720,2160,Ia.maxHeight),quality:ds(n.quality,20,95,Ia.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ia.showScreenStatus}}catch{return Ia}}function gT(n){try{localStorage.setItem(mw,JSON.stringify({...n,version:qh}))}catch{}}function bh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function wh(n){return[...new Set(n.filter(Boolean))].sort()}function vT(n){return ca.fallbackVisibleCounts[n]||ca.fallbackVisibleCounts.large}function xT(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=Ly[a]||Ly.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function yT(n,a=ca.minFps){const r=[...bp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function bT(n,a){return[...bp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Fc(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 Oy(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 Sh(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`${Oy(r)} / ${Oy(n)}`}function wT(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 Hy(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 ST(n){return n===1?"middle":n===2?"right":"left"}function By(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Fy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=LM?a:0}const CT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function jT(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=CT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function yf(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 pn(n,...a){for(const r of a){const l=yf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function Qa(n,...a){for(const r of a){const l=yf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function kT(n,...a){for(const r of a){const l=yf(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 Ui(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Ch(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ui((n-Math.max(0,a))/n)}function Eo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function jh(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 Rl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function AT(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 Fd(n,a,r){const l=yf(n,`tools.${a}`),c=Qa(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=kT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=Qa(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=Qa(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let v="unknown";return c==="busy"?v="busy":["online","running","ready","active"].includes(c)||d===!0?v="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(v="offline"),{id:a,label:r,status:v,detail:v==="offline"?"offline":m||(p?`:${p}`:v==="unknown"?"not reported":v)}}function jw(n){const a=n.status||{},r=pn(a,"cpu.cores","cpuCores","processorCount"),l=pn(a,"loadavg.0","cpu.load1"),c=Ui(pn(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=pn(a,"memory.totalBytes","totalMem"),m=pn(a,"memory.freeBytes","freeMem"),p=Ui(pn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ch(d,m),v=pn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),g=pn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Ui(pn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ch(v,g),y=pn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=Ui(pn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),C=Qa(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=pn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=pn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=Ui(pn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ch(j,A),k=pn(a,"gpu.temperatureC","thermal.gpuC"),T=Ui(pn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=Qa(a,"npu.name","npu.model","accelerators.npu.name"),q=pn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=pn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),Y=pn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=pn(a,"network.latencyMs","network.rttMs"),L=Ui(pn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ae=Qa(a,"network.link","network.interface","network.name"),G=Math.max(y??Number.NEGATIVE_INFINITY,k??Number.NEGATIVE_INFINITY),te=Number.isFinite(G)?G:void 0,P=te===void 0?void 0:Ui((te-35)/60),ye=y!==void 0&&k!==void 0?`CPU ${Math.round(y)}° · GPU ${Math.round(k)}°`:y!==void 0?`CPU ${Math.round(y)}°`:k!==void 0?`GPU ${Math.round(k)}°`:"-",ie=Qa(a,"workload.role","role","lane")||(Wc(n,"aiAssist")?"Agent worker":Wc(n,"taskDispatch")?"Task worker":"Local machine"),K=Qa(n.latestTask,"status")||Qa(a,"workload.status")||"idle",I=Qa(n.latestTask,"title","instructionPreview")||Qa(a,"workload.title"),Q=Qa(n.latestTask,"resultSummary","error","instructionPreview")||Qa(a,"workload.summary"),U=[Fd(a,"ollama","Ollama"),Fd(a,"lmStudio","LM Studio"),Fd(a,"comfyui","ComfyUI"),Fd(a,"stableDiffusion","Stable Diffusion")],W=U.some(me=>me.status!=="unknown"),ue=Date.parse(n.lastSeenAt||n.connectedAt||""),be=Number.isFinite(ue)?Date.now()-ue:0;let X="online";n.connected?be>5*6e4?X="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(b??0)>=.96||(N??0)>=.96||(T??0)>=.96||(p??0)>=.94||(w??0)>=.94||(_??0)>=200||K==="failed"?X="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(b??0)>=.86||(N??0)>=.88||(T??0)>=.86||(p??0)>=.82||(w??0)>=.86||(_??0)>=80?X="warn":(["queued","running","targeted"].includes(K)||U.some(me=>me.status==="busy"))&&(X="busy"):X="offline";const $=U.filter(me=>me.status==="online"||me.status==="busy").length,de=[{id:"cpu",label:"CPU",value:Eo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Rl(c,.92,.78)},{id:"memory",label:"RAM",value:Eo(p),detail:Sh(d,m),ratio:p,state:Rl(p,.92,.78)},{id:"disk",label:"DISK",value:Eo(w),detail:Sh(v,g),ratio:w,state:Rl(w,.92,.82)},{id:"gpu",label:"GPU",value:Eo(b),detail:C||(j&&A!==void 0?`${Fc(A)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:b,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":Rl(b,.96,.86)},{id:"vram",label:"VRAM",value:Eo(N),detail:Sh(j,A),ratio:N,state:Rl(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?Eo(T):q!==void 0?`${Math.round(q)} TOPS`:"-",detail:R||(q!==void 0?"neural engine":"not reported"),ratio:T,state:Rl(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:$>0?`${$} local tools`:`uptime ${AT(pn(a,"uptimeSec"))}`,ratio:P,state:te===void 0?"unknown":te>=86?"critical":te>=78?"warn":"good"},{id:"network",label:"NET",value:jh(O)||(_!==void 0?`${Math.round(_)}ms`:ae||"-"),detail:jh(Y)?`${jh(Y)} up`:ae||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Rl(L,.9,.75)}];return{state:X,label:jT(X,de,K),role:ie,taskLabel:I||(K==="idle"?"idle":K),taskStatus:K,taskSummary:Q,tools:W?U:U.map(me=>({...me,detail:"not reported"})),metrics:de}}const NT=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],MT=[{id:"sync-server",label:"Hub",icon:Gi,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Kc,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:$d,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Pd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Ud,accent:"violet",tooltip:"agents"}],TT=[{id:"doc",label:"Doc",icon:Kd,accent:"amber"},{id:"support",label:"Support",icon:Pc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function ET(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 ln(n){return ET(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 Dl(n){return n.map(a=>ln(a))}function la(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:ln(n.title),intro:ln(n.intro),sections:[{title:ln(n.managerTitle),body:ln(n.managerBody),points:Dl(n.managerPoints)},{title:ln(n.clientTitle),body:ln(n.clientBody),points:Dl(n.clientPoints)},{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:ln(n.agentTitle),body:ln(n.agentBody),points:Dl(n.agentPoints)}]:[],{title:ln(n.platformTitle),body:ln(n.platformBody),points:Dl(n.platformPoints)}],sync:{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},firewall:{title:ln(n.firewallTitle),body:ln(n.firewallBody),points:Dl(n.firewallPoints)},commands:{title:ln(n.commandsTitle),body:ln(n.commandsBody),manager:ln(n.managerCommandLabel),primary:ln(n.clientCommandLabel),slot:ln(n.slotCommandLabel),manual:ln(n.manualCommandLabel)}}}const Oo={ko:la({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:la({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:la({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":la({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":la({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:la({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:la({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:la({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":la({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:la({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:la({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:la({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:la({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:la({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:la({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:la({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ı"})},RT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function DT(){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 Py({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(Yt,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const LT=["cpu","gpu","memory","vram","network","disk","temp"];function _T({device:n,slotNumber:a,selected:r,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=jw(n),p=new Map(m.metrics.map(g=>[g.id,g])),v=l?.label||m.label;return s.jsxs("div",{className:`wall-device-list-row state-${m.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:c,onDoubleClick:g=>{g.preventDefault(),d()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c())},children:[s.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[s.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:s.jsx(Yt,{size:17})}),s.jsxs("span",{children:[s.jsx("strong",{children:Ka(n)}),s.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),r&&s.jsx(ri,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),s.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||v,children:[s.jsx("i",{"aria-hidden":"true"}),s.jsx("strong",{children:v})]}),LT.map(g=>{const w=p.get(g);return s.jsxs("span",{className:`wall-device-list-metric state-${w?.state||"unknown"}`,role:"gridcell",title:w?`${w.label}: ${w.value} · ${w.detail}`:"Not reported",children:[s.jsx("strong",{children:w?.value||"-"}),s.jsx("small",{children:w?.detail||"not reported"}),w?.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(w.ratio*100)}%`},"aria-hidden":"true"})]},g)})]})}function zT(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 $y(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:qi(n.platform)}function kh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:v,onOpenControl:g,onCycleMonitor:w,onCanvasReady:y,sendInput:b,updateIndicator:C,presentationReady:j,showPresentationSpinner:A=!1}){const N=u.useRef(null),k=u.useRef(null),T=u.useRef(0),R=u.useRef(null),q=jw(n),O=["cpu","gpu","memory","vram"].map($=>q.metrics.find(de=>de.id===$)).filter($=>!!$),Y=za(d,m),_=m>1,L=j??!!a,ae=zT(n)&&!L,G=A&&n.connected&&!L&&!ae,te=uT(n,a,Y),P=te>=Bd?100:te/Bd*100,ye=te>=Bd?Bd/te*100:100,ie={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,P)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,ye)).toFixed(3)}%`},K=u.useCallback($=>{N.current=$,y(n.deviceId,$)},[n.deviceId,y]),I=$=>{const de=$.currentTarget.getBoundingClientRect();return Ej($.clientX,$.clientY,de)},Q=$=>({shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}),U=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),W=u.useCallback(()=>{const $=k.current;if(!$)return;k.current=null;const de=Number($.input.normalizedX),me=Number($.input.normalizedY);if(!Number.isFinite(de)||!Number.isFinite(me))return;b(n.deviceId,{...$.input,normalizedX:de,normalizedY:me})&&(T.current=performance.now())},[n.deviceId,b]),ue=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,W()}))},[W]);u.useEffect(()=>()=>{U(),k.current=null},[U]);const be=($,de)=>{if(!l)return;const me={type:de,monitorIndex:Y,...I($),button:ST($.button),...Q($)};if(de==="pointermove"){const ve=performance.now();k.current={input:me},ve-T.current>=zM&&(U(),W()),ue();return}k.current&&(U(),W()),b(n.deviceId,me)},X=u.useCallback($=>{const de=document.activeElement;de instanceof HTMLElement&&$.contains(de)&&de.classList.contains("monitor-cycle-button")&&de.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:ie,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||p()},onKeyDown:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),p())},onDoubleClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||($.preventDefault(),g())},onPointerLeave:$=>X($.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:K,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:$=>{l&&($.preventDefault(),$.stopPropagation(),v(),$.currentTarget.focus(),$.currentTarget.setPointerCapture($.pointerId),be($,"pointerdown"))},onPointerMove:$=>{l&&$.preventDefault(),be($,"pointermove")},onPointerLeave:$=>{l&&(be($,"pointermove"),U(),W())},onPointerUp:$=>{l&&($.preventDefault(),$.stopPropagation(),be($,"pointerup"),$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId))},onPointerCancel:$=>{$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId)},onWheel:$=>{l&&($.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:Y,...I($),deltaX:$.deltaX,deltaY:$.deltaY,...Q($)}))},onKeyDown:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:$.repeat,...Q($)}))},onKeyUp:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:!1,...Q($)}))},onContextMenu:$=>l&&$.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(Yt,{size:26})}),G&&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"})]}),ae&&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."})]}),C&&s.jsxs("span",{className:`wall-update-status state-${C.state}`,role:"status","aria-live":"polite",title:C.error||C.label,children:[C.state==="updated"?s.jsx(Hn,{size:20,"aria-hidden":"true"}):C.state==="failed"?s.jsx(Ha,{size:22,"aria-hidden":"true"}):C.state==="offline"?s.jsx(Hl,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:C.label}),C.error?s.jsx("small",{children:C.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${q.state}`,children:q.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${Ka(n)} status`,children:O.map($=>s.jsxs("span",{className:`tile-metric state-${$.state}`,children:[s.jsx("b",{children:$.label}),s.jsx("em",{children:$.value}),$.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round($.ratio*100)}%`}})]},$.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${Ka(n)} display ${Y+1} of ${m}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>$.stopPropagation(),onDoubleClick:$=>$.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(-1),$.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Jy,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",Y+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(1),$.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(ep,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(ri,{size:23,strokeWidth:3.5})})]})})}function IT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(Sy)){const r=document.createElement("script");r.id=Sy,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Gh)}`,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":Gh,"data-ad-slot":gw,"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 OT(){const{session:n,loading:a}=oj(),{target:r,error:l,refresh:c}=uj(n),d=u.useMemo(()=>{if(!r?.active)return null;const x=r.expires_at?Date.parse(r.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:r},[r]),m=u.useMemo(()=>xx(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,Cn])]:[Cn],[m]),[v,g]=u.useState(rT),w=u.useMemo(()=>p.some(x=>!!qc(x)),[p]),y=!w||v,{status:b,devices:C,error:j,refresh:A,hubBaseUrl:N}=cj(p,y),{entitlement:k,licensed:T,loading:R,error:q,refresh:O}=dj(n),[Y,_]=u.useState([]),[L,ae]=u.useState(""),[G,te]=u.useState(""),[P,ye]=u.useState(""),[ie,K]=u.useState(""),[I,Q]=u.useState(""),[U,W]=u.useState("idle"),[ue,be]=u.useState(!1),[X,$]=u.useState(null),[de,me]=u.useState(""),ve=u.useRef("");ve.current=ie;const[Se,Oe]=u.useState(!1),[le,Z]=u.useState(!1),He=u.useRef(""),_e=u.useRef(new Map),se=u.useRef(0),[fe,Ne]=u.useState(""),[Te,Be]=u.useState(""),[$e,et]=u.useState(!1),Mt=u.useRef(null),ke=u.useRef(null),[Ye,rt]=u.useState(null);u.useEffect(()=>{fe==="auth"&&n?.access_token&&Ne("")},[fe,n?.access_token]);const[vt,vn]=u.useState(""),[It,Zt]=u.useState(null),ht=u.useRef(null),$n=u.useRef(0),Gt=u.useCallback((x,M,D)=>{const B=String(x||"").trim();if(vn(B),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!B){Zt(null);return}const z=++$n.current;if(Zt({id:z,message:B,tone:M}),!D)return;const ge=window.setTimeout(()=>{Zt(pe=>pe?.id===z?null:pe),ht.current===ge&&(ht.current=null)},5e3);ht.current=ge},[]),J=u.useCallback((x,M="info")=>{Gt(x,M,!0)},[Gt]),Re=u.useCallback(x=>{Gt(x,"progress",!1)},[Gt]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[ze,je]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{je(window.location.pathname.startsWith("/support")?"support":M=>M==="support"?"wall":M)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[Xe,gt]=u.useState("large"),[Ee,ua]=u.useState(DT),[Un,tt]=u.useState(!1),[$t,an]=u.useState(!1),[Za,Ja]=u.useState(!1),[Xn,Wi]=u.useState(iT),[Fe,Is]=u.useState(mT),[ut,ui]=u.useState(pT),[Kt,H]=u.useState(dT),[De,st]=u.useState(null),[on,es]=u.useState([]),[Tn,da]=u.useState(Fe.fps),[ne,Ae]=u.useState(""),[qe,ot]=u.useState(0),[Jt,Ut]=u.useState(0),[Ze,jt]=u.useState(()=>new Set),Ot=u.useRef(new Map),Vt=u.useRef(new Map),sn=u.useRef(new Map),wt=u.useRef(new Map),cn=u.useRef(new Map),Tt=u.useRef(new Set),ts=u.useRef(new Map),xn=u.useRef(""),un=u.useRef(""),dn=u.useRef(null),Os=u.useRef(null),ya=u.useRef(new Map),Hs=u.useRef(null),Po=u.useRef(0),Yi=u.useRef(new Map),[Ki,ms]=u.useState({}),Zn=u.useRef(new Map),[$l,bf]=u.useState({}),[Ul,ba]=u.useState(!1),Qi=u.useRef(null),ns=u.useRef(null),Qt=u.useRef(0),hs=u.useRef(""),Xi=u.useRef(new Map),di=u.useRef(new Map),ps=u.useRef(performance.now()),Zi=u.useRef(new Map),fi=u.useRef(new Map),Fa=u.useRef(new Map),$o=u.useRef(new Map),Ji=u.useRef(0),Yr=u.useRef(0),er=u.useRef(0),ql=u.useRef(0),Uo=u.useRef(0),Kr=u.useRef(new Map),Ln=u.useRef(new Map),[gs,as]=u.useState(null),[tr,Bs]=u.useState(!1),[wf,qo]=u.useState([]),[mi,Qr]=u.useState("all"),[Jn,Xr]=u.useState([]),[Gl,hi]=u.useState(!1),[au,Vl]=u.useState(!0),Go=u.useRef(null),Zr=u.useRef(null),Wl=u.useRef(null),su=u.useRef(null),ea=u.useRef(!1),vs=u.useRef(!1),nr=u.useRef(!1),xs=u.useRef(0),Fs=u.useRef(0),ar=ze==="settings",Yl=ze==="pricing",sr=ze==="doc",Jr=ze==="support",ir=ze==="share-files",Vo=ze==="agents",iu=!ar&&!Yl&&!sr&&!Jr&&!ir&&!Vo,it=ze==="control",ct=Fe.frameMode==="mode4-h264-atlas",wa=I||ut.frameMode,rr=wa!=="mode3-h264-hw"?Math.min(30,ut.fps):ut.fps,Ps=wa!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ut.maxWidth),maxHeight:Math.min(1080,ut.maxHeight)}:{maxWidth:ut.maxWidth,maxHeight:ut.maxHeight};u.useEffect(()=>{if(b?.started){if(!n?.access_token){Ge("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[k?.updated_at,N,n?.access_token,b?.started]),u.useEffect(()=>{!n?.access_token||!b?.started||b.runtimeRole!=="hub"||!b.deviceId||(async()=>{try{const{data:x,error:M}=await mt.rpc("register_livedesk_device",{p_device_id:b.deviceId,p_device_name:b.deviceName||b.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:b.managerVersion||b.managerPackage||""}),D=Array.isArray(x)?x[0]:x;(M||D?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",M||D?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[n?.access_token,b?.deviceId,b?.deviceName,b?.managerPackage,b?.managerVersion,b?.runtimeRole,b?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!b?.started||b.runtimeRole!=="hub"||nr.current||(nr.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},N||Cn).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"),A()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{nr.current=!1}))},[N,A,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,b?.runtimeRole,b?.started]);const at=u.useMemo(()=>C.filter(x=>x.connected),[C]),ru=mi==="all"?at.length:Jn.filter(x=>at.some(M=>M.deviceId===x)).length,lu=u.useMemo(()=>at.reduce((x,M)=>Math.max(x,Fy(M.slotNumber)),0),[at]),Kl=Math.max(DM,at.length,lu),pi=u.useMemo(()=>{const x=Array(Kl).fill(null),M=[];for(const D of at){const B=Fy(D.slotNumber);B>0&&B<=Kl&&!x[B-1]?x[B-1]=D:M.push(D)}for(const D of M){const B=x.findIndex(z=>!z);B<0?x.push(D):x[B]=D}return x},[at]),ou=u.useMemo(()=>pi.flatMap((x,M)=>x?[{device:x,slotNumber:M+1}]:[]),[pi]),Wo=u.useMemo(()=>at.map(x=>x.deviceId),[at]),ys=u.useMemo(()=>new Set(Y),[Y]),fa=u.useMemo(()=>at.filter(x=>ys.has(x.deviceId)),[at,ys]),lr=u.useMemo(()=>C.find(x=>x.deviceId===L)||fa[0]||null,[C,L,fa]),qn=u.useMemo(()=>C.find(x=>x.deviceId===G)||null,[G,C]),bs=qn?za(Kt[qn.deviceId],va(qn)):0,Le=it?qn:lr,cu=u.useMemo(()=>new Set(Jn),[Jn]),Sf=u.useMemo(()=>mi==="all"?at.map(x=>x.deviceId):at.filter(x=>cu.has(x.deviceId)).map(x=>x.deviceId),[at,cu,mi]),Cf=Le?Wc(Le,"control"):!1,Yo=qi(Le?.platform)&&(Le?.capabilities?.controlPermission===!1||Le?.capabilities?.accessibilityPermission===!1),el=Le?Wc(Le,"audio")||Wc(Le,"remoteAudio"):!1,uu=Array.isArray(Le?.capabilities?.agentTools)?Le.capabilities.agentTools.map(String):[],du=uu.includes("system.power"),fu=uu.includes("command.run"),Ht=T?k?.plan==="pro"?"pro":"ltd":"free",or=El[Ht],Ql=or.limit,gi=u.useMemo(()=>{if(!Number.isFinite(Ql))return new Set(at.map(M=>M.deviceId));const x=Le?[Le,...at.filter(M=>M.deviceId!==Le.deviceId)]:at;return new Set(x.slice(0,Ql).map(M=>M.deviceId))},[Ql,at,Le]),mu=!Le||gi.has(Le.deviceId),hu=Ht==="free",Wt=mu,cr=Ht==="ltd"?`Plus includes up to ${Bc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Hc} workstations. Upgrade to Plus for ${Bc} devices and no ads.`,ur=Ht==="free",ws=Wt&&!!Le&&Cf,pu=Wt&&!!Le&&el,Xl=u.useMemo(()=>pi.filter(x=>!!x?.connected).slice(0,vT(Xe)).map(x=>x.deviceId),[pi,Xe]),tl=u.useMemo(()=>Xe==="list"?[]:ct?Wo:Fe.visibleOnlyLive?on.length>0?on:Xl:Wo,[Xl,ct,on,Fe.visibleOnlyLive,Wo,Xe]),Sa=u.useMemo(()=>wh(tl.filter(x=>gi.has(x))),[gi,tl]),Ca=u.useMemo(()=>Sa.filter(x=>x!==ne),[Sa,ne]),$s=u.useMemo(()=>new Map(at.map(x=>[x.deviceId,x.platform])),[at]),ss=Rj(ct,Sa.length),Gn=u.useMemo(()=>ct?Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="atlas"):[],[ss,ct,$s,Ca]),ta=u.useMemo(()=>Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="direct"),[ss,ct,$s,Ca]);u.useEffect(()=>{const x=new Set(Sa);jt(M=>{let D=!1;const B=new Set;for(const z of M)x.has(z)?B.add(z):D=!0;return D?B:M})},[Sa]);const gu=u.useMemo(()=>{const x=z=>at.find(ge=>ge.deviceId===z)||null,M=z=>za(Kt[z],x(z)?va(x(z)):0),D=(z,ge=M(z))=>z===P&&(U==="connecting"||U==="active"||U==="warm")?wt.current.get(z)||Vt.current.get(z)||null:ct?ya.current.get(z)||Ot.current.get(z)||null:Ot.current.get(z)||null,B=(z,ge=M(z))=>{const pe=x(z);return`${pe?Ka(pe):z} · Monitor ${ge+1}`};return{resolveCurrentTarget(){if(it&&qn){const Ue=bs;return{type:"control",deviceIds:[qn.deviceId],monitorIndex:Ue,label:`${Ka(qn)} · Monitor ${Ue+1}`,sourceCanvas:D(qn.deviceId,Ue),signature:`control:${qn.deviceId}:${Ue}:${ut.frameMode}`}}const z=fa.map(Ue=>Ue.deviceId).filter(Ue=>Ca.includes(Ue)),ge=lr&&Ca.includes(lr.deviceId)?lr.deviceId:"",pe=z.length>0?z:ge?[ge]:Ca,Ie=z.length===0&&!ge;if(pe.length===0)return null;if(pe.length===1){const Ue=pe[0],Ke=M(Ue);return{type:Ie?"wall":z.length>1?"selection":"device",deviceIds:pe,monitorIndex:Ke,label:Ie?"Wall":B(Ue,Ke),sourceCanvas:Ie?null:D(Ue,Ke),signature:`${Ie?"wall":"device"}:${Ue}:${Ke}:${ct?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:pe,label:z.length>1?`${pe.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${pe.join(",")}:${Xe}`}},getDeviceCanvas:D,composeWall(z,ge={}){return bM(z.map(pe=>{const Ie=M(pe);return{deviceId:pe,label:B(pe,Ie),canvas:D(pe,Ie)}}),ge)}}},[at,qn,P,U,ut.frameMode,Ot,ct,Kt,bs,fa,it,Ca,lr,Xe]),Zl=RM({hubUrl:N,sourceRegistry:gu,onToast:J}),Us=u.useMemo(()=>Wt&&P&&gi.has(P)&&(U==="connecting"||U==="active"||U==="warm")?[P]:[],[P,U,Wt,gi]),vu=u.useMemo(()=>wh([...Sa,...Us]),[Us,Sa]),_n=u.useMemo(()=>xT(Fe,Xe),[Fe,Xe]),vi=Dj({mode4Enabled:ct,directMode4WallEnabled:ss,adaptiveFps:Tn,directDeviceCount:ta.length}),Ss=u.useCallback((x,M,D)=>{if(x.width<=0||x.height<=0)return!1;const B=D?Math.min(1,D.maxWidth/x.width,D.maxHeight/x.height):1,z=Math.max(1,Math.round(x.width*B)),ge=Math.max(1,Math.round(x.height*B));(M.width!==z||M.height!==ge)&&(M.width=z,M.height=ge);const pe=M.getContext("2d",{alpha:!1});return pe?(pe.imageSmoothingEnabled=!0,pe.imageSmoothingQuality="high",pe.drawImage(x,0,0,x.width,x.height,0,0,M.width,M.height),!0):!1},[]),dr=u.useCallback(x=>{x&&jt(M=>{if(M.has(x))return M;const D=new Set(M);return D.add(x),D})},[]),Jl=u.useCallback(x=>{x&&jt(M=>{if(!M.has(x))return M;const D=new Set(M);return D.delete(x),D})},[]),eo=u.useCallback((x,M)=>{if(!M||M.width<=0||M.height<=0)return!1;const D=document.createElement("canvas");return D.width=M.width,D.height=M.height,Ss(M,D)?(sn.current.set(x,D),dr(x),!0):!1},[dr,Ss]),Cs=u.useCallback((x,M=!1)=>{if(!Tt.current.has(x))return!1;const D=performance.now(),B=ts.current.get(x)||0,z=Math.max(1,Math.min(li.controlWallReuseMaxFps,rr)),ge=rr>z?Math.max(0,1e3/z-2):0;if(!M&&D-B<ge)return!1;const pe=wt.current.get(x)||Vt.current.get(x),Ie=Ot.current.get(x)||ya.current.get(x);return!pe||!Ie||!Ss(pe,Ie,_n)?!1:(ts.current.set(x,D),dr(x),!0)},[rr,_n,dr,Ss]);u.useEffect(()=>{xn.current=ne},[ne]);const na=u.useCallback((x,M)=>{const D=Ot.current.get(x);if(D&&D!==M&&(eo(x,D),_c(D)),M){Ot.current.set(x,M),sn.current.delete(x),Cs(x,!0);return}Ot.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,Cs,eo]),nl=u.useCallback((x,M)=>{const D=Vt.current.get(x);if(D&&D!==M&&_c(D),M){Vt.current.set(x,M);const B=wt.current.get(x)||sn.current.get(x)||Ot.current.get(x)||ya.current.get(x);B&&Ss(B,M)&&x===G&&ba(!0);return}Vt.current.delete(x)},[G,Ss]),al=u.useCallback((x,M,D)=>{const B=performance.now(),z=Rs(x,D.deviceId);let ge=D;if(x==="control"&&D.visualChanged){const Ie=vj(D.deviceId),Ue=Kr.current.get(D.deviceId)||0,Ke=Ie?B-Ie.sentAt:Number.POSITIVE_INFINITY;Ie&&Ie.inputSeq>Ue&&Ke<=Cy&&(ge={...D,inputFeedbackSeq:Ie.inputSeq,inputFeedbackMs:Math.max(0,Ke),inputFeedbackAt:B},Kr.current.set(D.deviceId,Ie.inputSeq))}di.current.set(z,B);const pe=Yi.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:B,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&ge.inputFeedbackMs===void 0&&pe.lastInfo?.inputFeedbackMs!==void 0&&pe.lastInfo.inputFeedbackAt!==void 0&&B-pe.lastInfo.inputFeedbackAt<=Cy&&(ge={...ge,inputFeedbackSeq:pe.lastInfo.inputFeedbackSeq,inputFeedbackMs:pe.lastInfo.inputFeedbackMs,inputFeedbackAt:pe.lastInfo.inputFeedbackAt}),pe.totalFrames+=1,pe.sampleFrames+=1,Ty(pe,B,ge.frameSeq),ge.visualChanged&&(pe.totalChangedFrames+=1,pe.sampleChangedFrames+=1),pe.lastInfo=ge,Yi.current.set(z,pe)},[]),sl=u.useCallback((x,M)=>{al("wall",x,M),x.kind==="live"&&dr(x.deviceId);const D=ue&&P===x.deviceId;xn.current!==x.deviceId&&!D&&(Tt.current.delete(x.deviceId),ts.current.delete(x.deviceId))},[P,ue,dr,al]),Ko=u.useCallback((x,M)=>{al("control",x,M),me(ge=>ge&&"");const D=wt.current.get(x.deviceId),B=Vt.current.get(x.deviceId);D&&D.width>0&&D.height>0&&(B&&Ss(D,B),cn.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),sn.current.delete(x.deviceId),Tt.current.add(x.deviceId),x.deviceId===P&&(be(!0),W(ge=>ge==="connecting"?"active":ge)),Cs(x.deviceId));const z=Qi.current;!z||!GM(z,x)||ba(!0)},[P,Ss,Cs,al]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Yi.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/ge,changedFramesPerSecond:z.sampleChangedFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/ge),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/ge),sampleMs:ge,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,My(z,M)}ms(D)},1e3);return()=>window.clearInterval(x)},[]);const xi=u.useCallback((x,M)=>{const D=performance.now(),B=Rs(x,M.deviceId);Xi.current.set(B,D),Ln.current.delete(B),x==="control"&&fi.current.delete(B);const z=Zn.current.get(B)||{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(M.byteLength||0)),String(M.frameMode||M.mode||M.codec||M.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(M.byteLength||0)<=PM&&(z.sampleTinyFrames+=1);const Ue=String(M.contentHash||"");Ue&&z.lastContentHash===Ue&&(z.sampleRepeatedFrames+=1),z.lastContentHash=Ue}const Ie=Number(M.agentSendGapMs||0);Ie>0&&Ie<1e3&&xw(z.sourceSendIntervalsMs,Ie),z.lastFrame=M,Ty(z,D,M.frameSeq),Zn.current.set(B,z)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Zn.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(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((pe,Ie)=>pe+Ie,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:vh(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:ge,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,My(z,M)}bf(D)},1e3);return()=>window.clearInterval(x)},[]);const to=u.useCallback(x=>{xi("wall",x);const M=Ot.current.get(x.deviceId);if(!M)return;const D=Lj(ct,Fe.h264DecodeAcceleration);nh(M,x,()=>Ot.current.get(x.deviceId)!==M,sl,D.acceleration,D.latencyMode).catch(()=>{})},[sl,ct,xi,Fe.h264DecodeAcceleration]),xu=u.useCallback(x=>{xi("control",x);let M=wt.current.get(x.deviceId);M||(M=document.createElement("canvas"),M.setAttribute("aria-hidden","true"),wt.current.set(x.deviceId,M));const D=M,B=ve.current;nh(D,x,()=>wt.current.get(x.deviceId)!==D,Ko,ut.h264DecodeAcceleration,"interactive").catch(z=>{ve.current!==B||wt.current.get(x.deviceId)!==D||P!==x.deviceId||me(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[P,ut.h264DecodeAcceleration,Ko,xi]),fr=u.useCallback(x=>{const M=Os.current;M&&M!==x&&_c(M),Os.current=x,Ji.current=0,Yr.current=0,er.current=0,ql.current=0,Uo.current=0,Po.current=0},[]),qs=u.useCallback(()=>{const x=Os.current,M=Hs.current;if(!(!x||!M||x.width<=0||x.height<=0||Po.current!==M.layoutVersion))for(const D of M.tiles){const B=ya.current.get(D.deviceId);if(!B||D.width<=0||D.height<=0)continue;const z=Math.max(1,Math.round(D.width)),ge=Math.max(1,Math.round(D.height)),pe=$M,Ie=UM;(B.width!==pe||B.height!==Ie)&&(B.width=pe,B.height=Ie);const Ue=B.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,ge,0,0,pe,Ie)}catch{}}}},[]),il=u.useCallback((x,M)=>{if(M){ya.current.set(x,M),sn.current.delete(x),window.requestAnimationFrame(qs),window.requestAnimationFrame(()=>Cs(x,!0));return}const D=ya.current.get(x);eo(x,D),ya.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,qs,Cs,eo]),no=u.useCallback((x,M)=>{er.current=performance.now(),Po.current=Number(x.layoutVersion||0),qs();const D=Hs.current?.tiles||[],B=D.length>0?Math.round(x.byteLength/D.length):x.byteLength;for(const z of D){const ge={...x,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:B};sl(ge,{...M,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:B}),xn.current===z.deviceId&&Cs(z.deviceId,!0)}},[sl,qs,Cs]),yu=u.useCallback(x=>{const M=performance.now();Ji.current<=0&&(Ji.current=M),Yr.current=M;const D=Os.current;if(!D)return;const B=Hs.current?.tiles||[],z=B.length>0?Math.round(x.byteLength/B.length):x.byteLength;for(const ge of B)xi("wall",{...x,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:z});nh(D,x,()=>Os.current!==D,no).catch(()=>{})},[no,xi]),yi=u.useMemo(()=>({fps:vi,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorSelections:Kt,onFrame:to}),[vi,to,_n,ct,Kt,Fe]),bi=u.useCallback(x=>{if(x.deviceId!==P||x.streamPurpose!=="control"||x.monitorIndex!==bs)return;const M=at.find(D=>D.deviceId===x.deviceId);!M?.sessionId||M.sessionId!==x.sessionId||($(x),W(D=>D==="connecting"?"active":D))},[at,P,bs]);u.useEffect(()=>{$(null)},[P,ie,wa,bs]);const Qo=u.useMemo(()=>({fps:rr,maxWidth:Ps.maxWidth,maxHeight:Ps.maxHeight,quality:ut.quality,mode:wa,frameMode:wa,streamPurpose:"control",forceRestart:ie!=="",forceRestartToken:ie,restartReason:ie?"control-session-start":"",monitorSelections:Kt,onFrame:xu,onStreamReady:bi}),[ie,ut.quality,xu,rr,wa,Ps.maxHeight,Ps.maxWidth,bi,Kt]),{frames:Xo,state:Pa,error:Zo,stats:js,restartLive:rl}=Rx(ta,Fe.autoStartLive&&ta.length>0,N,yi),{frame:mr,layout:wi,state:Jo,stats:bu,refreshInputs:ec}=xj(Gn,ct&&Fe.autoStartLive&&Gn.length>0,N,{fps:li.atlasOutputFps,width:1920,height:1080,tileWidth:_n.maxWidth,tileHeight:_n.maxHeight,captureDeviceIds:Gn,monitorSelections:Kt,onFrame:yu});u.useEffect(()=>{Hs.current=wi,wi&&window.requestAnimationFrame(qs)},[wi,qs]),u.useEffect(()=>{if(!ct||Jo!=="open"){Ji.current=0,Yr.current=0,er.current=0;return}const x=window.setInterval(()=>{const M=Os.current,D=performance.now();if(!M||document.visibilityState!=="visible"||D-ps.current<gh)return;const B=Yr.current,z=Ji.current;if(B<=0||z<=0||D-B>500)return;const ge=er.current||z,pe=D-ge;if(pe>=OM&&D-Uo.current>=BM){eh(M)&&(Uo.current=D,ql.current=D);return}pe>=IM&&D-ql.current>=HM&&tj(M)&&(ql.current=D)},250);return()=>window.clearInterval(x)},[Jo,ct]);const{frames:ll,state:ma,error:Gs,stats:ja,restartLive:ks,reconnectLive:ao}=Rx(Us,Us.length>0,N,Qo),Si=u.useMemo(()=>{const x=new Map(Xo);if(ct&&mr&&Gn.length>0){const M=new Map((wi?.tiles||[]).map(B=>[B.deviceId,B])),D=Math.max(1,M.size);for(const B of Gn){const z=M.get(B);z&&x.set(B,{...mr,deviceId:B,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(mr.byteLength/D)})}}for(const[M,D]of ll.entries())x.set(M,D);for(const M of tl){if(!Tt.current.has(M)||x.has(M))continue;const D=cn.current.get(M);D&&x.set(M,D)}return x},[mr,wi,ll,Gn,ct,Xo,tl,Jt]),hr=it&&Us.length>0?ma:Gn.length>0?Jo:Pa,ol=it&&Us.length>0?ja:Gn.length>0?bu:js;u.useCallback((x,M="browser-stale")=>{const D=rl(x,M),B=ks(x,M);return D||B},[ks,rl]),u.useEffect(()=>{ct&&Gn.length>0&&!it&&ec()},[Gn.length,ct,ec,it]);const is=u.useCallback((x,M,D)=>{const B=M==="control"?wt.current.get(x)||null:Ot.current.get(x)||null;if(!B||!eh(B))return!1;const z=performance.now();return $o.current.set(Rs(M,x),z),!0},[]),cl=u.useCallback(x=>{if(wa!=="mode3-h264-hw"||!P||I)return!1;const M=at.find(Ie=>Ie.deviceId===P)||qn,D=String(M?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(D))return!1;const B="mode5-lzo-delta",z=Rs("control",P),ge=performance.now();Fa.current.set(z,ge),Xi.current.delete(z),di.current.delete(z),Zi.current.delete(z),fi.current.delete(z),Ln.current.delete(z),eh(wt.current.get(P)||null),ao([P],"control-decode-fallback"),Q(B),K(`control-${B}-fallback-${P}-${Date.now()}`),be(!1),ba(!1);const pe=x==="no first frame"||x==="control-first-frame-timeout";return me(Ie=>Ie||(pe?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),W("connecting"),!0},[at,qn,P,I,wa,ao]);u.useEffect(()=>{const x=it?qn:null;if(x){Qi.current={deviceId:x.deviceId,monitorIndex:bs,frameMode:wa,startedAtEpochMs:Date.now()},ba(P===x.deviceId&&ue||Ze.has(x.deviceId));return}Qi.current=null,ba(!1)},[qn?.sessionId,G,P,ue,wa,bs,it,Ze]);const Vs=u.useCallback(async x=>{const M=C.find(pe=>pe.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=za(Kt[x],M?va(M):1),z=D?{fps:li.scalableAtlasInputFps,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:B}:{fps:ct&&!D?vi:Tn,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorIndex:B},ge=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(z)},N);if(ge?.ok===!1)throw new Error(ge.error||"wall-stream-start-failed");return ge},[Tn,C,ss,vi,_n.maxHeight,_n.maxWidth,N,ct,Kt,Fe.frameMode,Fe.quality]),As=u.useCallback(async x=>{const M=C.find(z=>z.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:D?"atlas":"wall",reason:"control-active"})},N);if(B?.ok===!1)throw new Error(B.error||"wall-stream-stop-failed");return B},[C,ss,N,ct]),pr=u.useCallback(async(x,M="control-session-stop")=>{const D=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:M})},N);if(D?.ok===!1)throw new Error(D.error||"control-stream-stop-failed");return D},[N]),jn=u.useCallback(x=>{const M=wt.current.get(x);M&&(_c(M),wt.current.delete(x));const D=Vt.current.get(x);D&&_c(D),cn.current.delete(x),Tt.current.delete(x),ts.current.delete(x)},[]);u.useEffect(()=>{const x=G&&at.find(z=>z.deviceId===G)||null;if(!it||!Wt||!x){hs.current&&(++Qt.current,hs.current="");return}if(P===x.deviceId&&(U==="active"||U==="warm"||U==="connecting")){W(z=>z==="warm"?"active":z);return}if(hs.current===x.deviceId)return;const M=++Qt.current,D=P;hs.current=x.deviceId,(async()=>{if(D){if(W("stopping"),await pr(D,"control-session-switch").catch(()=>{}),M!==Qt.current)return;const pe=xn.current;if(pe&&pe!==x.deviceId)try{await Vs(pe)}catch(Ie){J(Ie instanceof Error?Ie.message:String(Ie))}finally{xn.current===pe&&(xn.current="",Ae(""))}if(M!==Qt.current)return;jn(D)}if(M!==Qt.current)return;if($y(x)){try{await As(x.deviceId)}catch(pe){M===Qt.current&&(hs.current="",W("error"),J(pe instanceof Error?pe.message:String(pe)));return}if(M!==Qt.current){await Vs(x.deviceId).catch(()=>{});return}xn.current=x.deviceId,Ae(x.deviceId),Tt.current.add(x.deviceId)}const z=Rs("control",x.deviceId),ge=`control-session-${M}-${x.deviceId}`;Fa.current.set(z,performance.now()),Xi.current.delete(z),di.current.delete(z),Ln.current.delete(z),fi.current.delete(z),Q(""),me(""),K(ge),ye(x.deviceId),be(!1),W("connecting"),Qt.current===M&&hs.current===x.deviceId&&(hs.current="")})()},[at,G,P,U,Wt,jn,J,it,Vs,pr,As]),u.useEffect(()=>{if(!P||at.some(D=>D.deviceId===P))return;const x=P,M=++Qt.current;W("stopping"),pr(x,"control-device-disconnected").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},[at,P,jn,pr]);const so=$y(at.find(x=>x.deviceId===P));u.useEffect(()=>{if(ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null),!P||U==="idle"||U==="stopping"||U==="error"||it||ze==="wall"){P&&!it&&ze==="wall"&&W(D=>D==="warm"||D==="active"?"active":D);return}W(D=>D==="idle"||D==="stopping"?D:"warm");const x=P,M=++Qt.current;return ns.current=window.setTimeout(()=>{ns.current=null,W("stopping"),pr(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},FM),()=>{ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null)}},[ze,P,U,jn,it,pr]),u.useEffect(()=>()=>{ns.current!==null&&window.clearTimeout(ns.current)},[]),u.useEffect(()=>{const M=P&&(so&&(U==="connecting"||U==="active"||U==="warm"||U==="stopping")||ue&&(U==="active"||U==="warm"))?P:"";if(un.current=M,dn.current)return;const D=async()=>{for(;;){const z=un.current,ge=xn.current;if(ge===z)return;if(ge){try{await Vs(ge)}catch(pe){J(pe instanceof Error?pe.message:String(pe))}finally{xn.current===ge&&(xn.current="",Ae(""))}continue}if(!z)return;try{await As(z)}catch(pe){un.current=xn.current,J(pe instanceof Error?pe.message:String(pe));return}xn.current=z,Ae(z),Tt.current.add(z)}};let B;B=D().finally(()=>{dn.current===B&&(dn.current=null),xn.current!==un.current&&ot(z=>z+1)}),dn.current=B},[P,ue,U,so,ct,J,Vs,As,qe]);const Vn=P&&at.find(x=>x.deviceId===P)||null,ul=!!(it&&Se&&U==="active"&&Vn?.sessionId&&X?.deviceId===Vn.deviceId&&X.sessionId===Vn.sessionId&&X.streamPurpose==="control"&&X.commandId&&X.captureGeneration>0&&X.monitorIndex===bs),{state:gr,sendInput:Ws,stats:ka,error:tc}=yj(ws&&ul,N),Ci=u.useCallback((x,M)=>!ul||!Vn||!X||x!==Vn.deviceId?!1:Ws(x,{...M,controlSessionId:Vn.sessionId,controlCommandId:X.commandId,captureGeneration:X.captureGeneration}),[ul,Vn,X,Ws]),vr=ul&&gr==="open",{state:Aa,lastFrame:ji,stats:fn,error:dl}=Mj(Le?.deviceId||"",pu&&le,N),Ys=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",j],["registry",l],["license",q],["wall-stream",Zo],["control-stream",Gs],["control-decode",de],["remote-input",tc],["remote-audio",dl]];for(const[M,D]of x){const B=String(D||"").trim();if(M==="hub"&&De?.requiresHubRestart&&De.stage==="updating"){Ys.current.delete(M);continue}if(!B){Ys.current.delete(M);continue}Ys.current.get(M)!==B&&(Ys.current.set(M,B),J(B))}},[dl,de,Gs,j,tc,q,l,J,Zo,De]),u.useEffect(()=>{if(!it||!Se||!ws||!vr||!Le)return;const x=(B,z)=>{const ge=B.target,pe=ge?.tagName?.toLowerCase();ge?.isContentEditable||pe==="input"||pe==="textarea"||pe==="select"||(B.preventDefault(),B.stopPropagation(),Ci(Le.deviceId,{type:z,monitorIndex:za(Kt[Le.deviceId],va(Le)),key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:z==="keydown"?B.repeat:!1,shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}))},M=B=>x(B,"keydown"),D=B=>x(B,"keyup");return window.addEventListener("keydown",M),window.addEventListener("keyup",D),()=>{window.removeEventListener("keydown",M),window.removeEventListener("keyup",D)}},[ws,vr,Se,Kt,Le,Ci,it]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(ps.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!P||U!=="connecting"&&U!=="active"&&U!=="warm"||ma!=="open")return;const x=P,M=Rs("control",x),D=window.setInterval(()=>{const B=performance.now();if(document.visibilityState!=="visible"||B-ps.current<gh)return;const z=Xi.current.get(M)||0,ge=di.current.get(M)||0,pe=Zi.current.get(M)||0,Ie=Fa.current.get(M)||B;Fa.current.has(M)||Fa.current.set(M,Ie);const Ue=z<=0,Ke=Ue?B-Ie>KM:B-z>_y,en=z>0&&(ge<=0||B-ge>_y);if(!Ke&&en){const Ar=$o.current.get(M)||0;B-Ar>=zy&&is(x,"control","decoder-paint-stale");return}if(!Ke)return;const Dt=fi.current.get(M)||0;if(Dt>0){if(B-Dt<XM)return;fi.current.delete(M)}const tn=Ln.current.get(M)||0;if(tn>=ZM){if(cl(Ue?"no first frame":"stale stream"))return;be(!1),ba(!1),W("error");return}if(B-pe<Iy(QM,tn))return;ks([x],Ue?"control-first-frame-timeout":"control-receive-stale")&&(Zi.current.set(M,B),fi.current.set(M,B),Fa.current.set(M,B),Ln.current.set(M,tn+1))},650);return()=>window.clearInterval(D)},[ma,P,U,cl,is,ks]),u.useEffect(()=>{!de||wa!=="mode3-h264-hw"||cl(de)||(be(!1),ba(!1),W("error"))},[de,wa,cl]),u.useEffect(()=>{!it||!P||!Gs||W(x=>x==="error"?x:"error")},[Gs,P,it]),u.useEffect(()=>{if(Pa!=="open"||!Fe.autoStartLive||ta.length===0)return;const x=window.setInterval(()=>{const M=performance.now();if(document.visibilityState!=="visible"||M-ps.current<gh)return;const D=1e3/Math.max(1,vi||Fe.fps||1),B=Math.max(JM,Math.ceil(D*4)),z=[];for(const ge of ta){if(z.length>=nT)break;const pe=Rs("wall",ge),Ie=Xi.current.get(pe)||0;if(Ie<=0)continue;const Ue=Zi.current.get(pe)||0,Ke=di.current.get(pe)||0,en=M-Ie>B,Dt=Ke<=0||M-Ke>B;if(!en&&Dt){const Ua=$o.current.get(pe)||0;M-Ua>=zy&&is(ge,"wall","decoder-paint-stale");continue}if(!en)continue;const tn=Ln.current.get(pe)||0;M-Ue>=Iy(eT,tn)&&z.push(ge)}if(z.length>0&&rl(z,"wall-frame-stale"))for(const ge of z){const pe=Rs("wall",ge);Zi.current.set(pe,M),Ln.current.set(pe,(Ln.current.get(pe)||0)+1)}},tT);return()=>window.clearInterval(x)},[vi,ta,is,rl,Fe.autoStartLive,Fe.fps,Pa]),u.useEffect(()=>{da(Fe.fps),xs.current=Date.now(),Fs.current=0},[Fe.fps,Fe.frameMode,Fe.adaptiveLoadShedding]),u.useEffect(()=>{WC({h264DecodeAcceleration:Fe.h264DecodeAcceleration})},[Fe.h264DecodeAcceleration]),u.useEffect(()=>{if(!Wt||it||Xe==="list"||!Fe.visibleOnlyLive){es([]);return}const x=Go.current;if(!x||typeof IntersectionObserver>"u"){es(Xl);return}const M=Array.from(x.querySelectorAll("[data-live-device-id]"));if(M.length===0){es([]);return}const D=new Map,B=()=>{const ge=wh(M.map(pe=>String(pe.dataset.liveDeviceId||"")).filter(pe=>(D.get(pe)||0)>0));es(pe=>bh(pe,ge)?pe:ge)},z=new IntersectionObserver(ge=>{for(const pe of ge){const Ie=String(pe.target.dataset.liveDeviceId||"");Ie&&D.set(Ie,pe.isIntersecting?pe.intersectionRatio||.01:0)}B()},{root:null,rootMargin:ca.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return M.forEach(ge=>z.observe(ge)),B(),()=>z.disconnect()},[Xl,Wt,it,pi,Fe.visibleOnlyLive,Xe]),u.useEffect(()=>{if(!Fe.adaptiveLoadShedding||!Fe.autoStartLive||ta.length===0)return;const x=Fe.fps;if(ta.length<=ca.preserveConfiguredFpsDeviceCount){Tn!==x&&(da(x),xs.current=Date.now(),Fs.current=0);return}if(Pa!=="open"||js.sampleMs<500)return;const M=Date.now(),D=ta.length*Tn,B=js.framesPerSecond,z=js.bytesPerSecond,ge=Math.max(0,...ta.map(en=>$l[Rs("wall",en)]?.maxIntervalMs||0)),pe=Math.max(0,...ta.map(en=>Ki[Rs("wall",en)]?.maxIntervalMs||0)),Ie=D>8&&B>0&&B<D*.72;if(B>ca.maxWallFramesPerSecond||z>ca.maxWallBytesPerSecond||ge>ca.maxFrameGapMs||pe>ca.maxFrameGapMs||Ie){Fs.current=0;const en=ca.minFps;if(M-xs.current>=ca.downshiftCooldownMs&&Tn>en){const Dt=Math.max(en,yT(Tn,en));Dt<Tn&&(da(Dt),xs.current=M)}return}const Ke=B<ca.maxWallFramesPerSecond*ca.lowLoadFrameRatio&&z<ca.maxWallBytesPerSecond*ca.lowLoadByteRatio;if(!Ke||Tn>=x){Ke||(Fs.current=0);return}if(!Fs.current){Fs.current=M;return}if(M-Fs.current>=ca.recoveryCooldownMs){const en=Math.min(x,bT(Tn,x));en>Tn&&(da(en),xs.current=M,Fs.current=0)}},[Tn,ta.length,ta,Ki,$l,Pa,js.bytesPerSecond,js.framesPerSecond,js.lastUpdatedAt,js.sampleMs,Fe.adaptiveLoadShedding,Fe.autoStartLive,Fe.frameMode,Fe.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){J("Checkout returned. Waiting for Dodo confirmation."),O();const M=window.setInterval(()=>{O()},4e3),D=window.setTimeout(()=>{window.clearInterval(M)},45e3);return()=>{window.clearInterval(M),window.clearTimeout(D)}}x==="cancelled"&&J("Checkout cancelled.")},[O]),u.useEffect(()=>{!Wt&&Se&&Oe(!1),!Wt&&le&&Z(!1)},[le,Se,Wt]),u.useEffect(()=>{const x=Le?.deviceId||"",M=He.current;if(He.current=x,!M||M===x)return;const D=++se.current,B=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&le&&_e.current.set(x,B);let z=!0;return(async()=>{try{const pe=_e.current.get(M);if(_e.current.delete(M),await Ge(`/api/remote/devices/${encodeURIComponent(M)}/audio/stop`,{method:"POST",body:JSON.stringify(pe?{streamId:pe}:{})},N),!z||D!==se.current||!le||!x||!Wt||!el)return;const Ie=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:B,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(Ie.ok===!1)throw new Error(Ie.error||"Remote audio start failed.")}catch(pe){z&&(_e.current.delete(x),Z(!1),J(pe instanceof Error?pe.message:String(pe)))}})(),()=>{z=!1}},[le,Wt,N,el,Le?.deviceId]),u.useEffect(()=>{const x=at.map(B=>B.deviceId),M=new Set(x),D=new Map(at.map(B=>[B.deviceId,B]));_(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z}),ae(B=>B&&M.has(B)?B:""),te(B=>B&&M.has(B)?B:""),H(B=>{let z=!1;const ge={};for(const[pe,Ie]of Object.entries(B)){const Ue=D.get(pe);if(!Ue){ge[pe]=Ie;continue}const Ke=za(Ie,Ue?va(Ue):1);ge[pe]=Ke,Ke!==Ie&&(z=!0)}return z?ge:B}),Xr(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z})},[at,Kl]),u.useEffect(()=>{qo([]),Vl(!1)},[Cs]),u.useEffect(()=>{!ir||mi!=="selected"||Jn.length>0||fa.length===0||Xr(fa.map(x=>x.deviceId))},[fa,Jn.length,mi,ir]),u.useEffect(()=>{try{localStorage.setItem(dw,Xn)}catch{}},[Xn]),u.useEffect(()=>{hT(Fe)},[Fe]),u.useEffect(()=>{gT(ut)},[ut]),u.useEffect(()=>{fT(Kt)},[Kt]);const aa=u.useCallback(async()=>{const x=new Set(p);x.add(Cn);try{const ge=await Ge("/api/remote/status",void 0,Cn);xx({endpoint:ge.agentEndpoint,endpoint_candidates:[...ge.agentEndpointCandidates||[],...ge.hostTargetEndpointCandidates||[]]}).forEach(pe=>x.add(pe))}catch{}const M=[...x].sort((ge,pe)=>{const Ie=Ue=>{const Ke=qc(Ue);return Ke==="local"?0:Ke==="loopback"?1:2};return Ie(ge)-Ie(pe)||ge.localeCompare(pe)});let D=!1,B="",z=!1;try{for(const ge of M){const pe=qc(ge);try{if(await Ge("/api/health",void 0,ge),pe==="local")return g(!0),To(!0),ge;pe==="loopback"&&(D=!0,B=ge)}catch{pe==="local"&&(z=!0)}}return D?(z&&J("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),g(!0),To(!0),B||Cn):(g(!1),To(!1),"")}catch{return g(!1),To(!1),""}},[p]),zn=async()=>{if(Ne("auth"),an(!1),await aa(),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();D?.ok===!1&&(J(D.error||"LiveDesk could not open the system browser for Google sign-in."),Ne(""));return}const{data:x,error:M}=await mt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});M&&(J(M.message),Ne(""))},Ks=async()=>{Ne("auth"),an(!1),await mt.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?J("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"},Cn).catch(()=>{}),Ne("")};u.useEffect(()=>{if(!$t)return;const x=D=>{D.target instanceof Element&&(D.target.closest(".account-popover, .rail-account")||an(!1))},M=D=>{D.key==="Escape"&&an(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",M),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",M)}},[$t]);const Na=u.useCallback(async(x={})=>{const M=x.silent===!0,D=x.takeover===!0,B=x.requestLocalAccess===!0;if(!n?.user){M||J("Sign in before publishing this host.","error");return}if(!vs.current){vs.current=!0,M||(Ne("host"),Re("Hub · 1/4 · Checking the local runtime…"));try{const ge=(B?await aa():"")||N||Cn;if(!(b||await Ge("/api/remote/status",void 0,ge)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");M||Re("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ie=await Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},ge);if(!Ie.ok||!Ie.authenticated)throw new Error(Ie.error||"hub-session-sync-failed");M||Re("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})},ge);if(!Ue.ok)throw new Error(Ue.error||"host-target-failed");if(!M){Re("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ke=await Ge("/api/hub/status",void 0,ge);if(!Ke.hostTargetActive)throw new Error(Ke.hostTargetLease?.lastError||"host-target-not-active-after-sync");const en=Ke.hostTargetEndpoint||Ke.agentEndpoint||"endpoint ready",Dt=Number(Ke.connectedDeviceCount||0),tn=Dt>0?`${Dt} client${Dt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";J(`Hub ready · ${en} · lease auto-renewal active. ${tn}`,"success"),(B||w)&&(g(!0),To(!0)),A()}c()}catch(z){if(!M){const ge=z instanceof Error?z.message:String(z);ge.includes("local network access")&&(g(!1),To(!1)),J(`Hub setup failed · ${ge}`,"error")}}finally{vs.current=!1,M||Ne("")}}},[N,w,A,c,aa,n,J,Re,b]),sa=u.useCallback((x=!0)=>{fe!=="host"&&(et(!1),x&&window.requestAnimationFrame(()=>ke.current?.focus()))},[fe]),Ns=u.useCallback(()=>{fe!=="host"&&(ke.current=document.activeElement instanceof HTMLElement?document.activeElement:null,an(!1),et(!0))},[fe]),wu=u.useCallback(()=>{et(!1),Na({takeover:!0,requestLocalAccess:!0})},[Na]);u.useEffect(()=>{if(!$e)return;const x=window.requestAnimationFrame(()=>Mt.current?.focus()),M=B=>{B.target instanceof Element&&B.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||sa(!1)},D=B=>{B.key==="Escape"&&sa()};return window.addEventListener("pointerdown",M),window.addEventListener("keydown",D),()=>{window.cancelAnimationFrame(x),window.removeEventListener("pointerdown",M),window.removeEventListener("keydown",D)}},[sa,$e]);const nc=u.useCallback(async()=>{if(!(!b?.update?.canApply||fe==="update")){Ne("update");try{const x=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||Cn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const M=[...new Set((x.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],D=!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),B=x.state==="hub-restart-requested"?Date.now():void 0;(M.length>0||D)&&st({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:M,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:D,initialHostInstanceId:String(b.hostInstanceId||""),targetManagerVersion:String(x.latestVersion||b.update?.latestVersion||""),targetClientVersion:String(x.latestClientVersion||b.update?.latestClientVersion||""),restartRequestedAt:B,restartDeadlineAt:B?B+Hd:void 0}),Re(x.state==="hub-restart-requested"?Od:Ay),A()}catch(x){J(x instanceof Error?x.message:String(x),"error")}finally{Ne("")}}},[fe,N,A,J,Re,b]);u.useEffect(()=>{const x=De,M=b?.update;if(!x||x.stage!=="updating"||!M)return;const D=M.restartResult?.operationId===x.operationId?M.restartResult:null;if(D?.outcome==="restored"){const Ue=D.error||`The requested Hub ${D.targetVersion||x.targetManagerVersion||"version"} failed verification.`;st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"restored",error:Ue}:Ke),J(`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.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(`LiveDesk Hub update failed. ${Ue}`,"error");return}if(M.operationId===x.operationId&&M.state==="failed"){const Ue=M.error||"LiveDesk update failed before the Hub replacement completed.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(Ue,"error");return}if(M.operationId===x.operationId){if(M.state==="hub-restart-requested"&&!x.restartDeadlineAt){const Ue=Date.now();st(Ke=>Ke?.operationId===x.operationId?{...Ke,restartRequestedAt:Ue,restartDeadlineAt:Ue+Hd}:Ke),Re(Od)}!x.requiresHubRestart&&M.state==="clients-updated"&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J("LiveDesk clients updated and reconnected successfully.","success"));return}if(!x.requiresHubRestart)return;const B=b.started===!0&&(!x.initialHostInstanceId||b.hostInstanceId&&b.hostInstanceId!==x.initialHostInstanceId),z=!!M.checkedAt,ge=Ny(M.currentVersion,x.targetManagerVersion),pe=!x.targetClientVersion||Ny(M.currentClientVersion,x.targetClientVersion),Ie=z&&M.state==="idle"&&M.updateAvailable===!1&&ge&&pe;B&&Ie&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J(`LiveDesk Hub ${M.currentVersion||D?.appVersion||x.targetManagerVersion} restarted and passed version verification.`,"success"))},[J,Re,b,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||x.restartDeadlineAt)return;const M=()=>{const B=Date.now();st(z=>z?.operationId===x.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:B,restartDeadlineAt:B+Hd}:z),Re(Od)};if(b?.update?.state==="hub-restart-requested"){M();return}if(!j)return;const D=window.setTimeout(M,qM);return()=>window.clearTimeout(D)},[j,Re,b?.update?.state,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||!x.restartDeadlineAt)return;const M=Math.max(0,x.restartDeadlineAt-Date.now()),D=x.operationId,B=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${x.targetManagerVersion||"the requested version"} within ${Math.round(Hd/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;st(ge=>ge?.operationId===D&&ge.stage==="updating"?{...ge,stage:"failed",error:z}:ge),J(z,"error")},M);return()=>window.clearTimeout(B)},[J,De]),u.useEffect(()=>{if(!De||De.stage!=="updated")return;const x=De.operationId,M=window.setTimeout(()=>{st(D=>D?.operationId===x?null:D)},8e3);return()=>window.clearTimeout(M)},[De]),u.useEffect(()=>{if(vt!==Ay&&vt!==Od)return;const x=b?.update;if(String(x?.state||"")==="failed"){J(x?.error||"LiveDesk update failed.","error");return}De?.stage==="updated"&&J("")},[vt,J,b?.update?.error,b?.update?.state,De?.stage]);const ac=u.useCallback(async()=>{if(!fe){Ne("pin");try{const M=await Ge("/api/remote/pairing-pin",{method:"POST"},N||Cn);if(!M.ok)throw new Error(M.error||"pin-rotation-failed");await A(),J("New PIN published.")}catch(x){J(x instanceof Error?x.message:String(x))}finally{Ne("")}}},[fe,N,A]),io=u.useCallback(x=>{x&&(ae(x),_(M=>M.includes(x)?M:[...M,x]))},[]),yn=u.useCallback(x=>{if(!x)return;const M=ys.has(x);ae(D=>M?D===x?"":D:x),_(D=>M?D.filter(B=>B!==x):D.includes(x)?D:[...D,x])},[ys]),Et=u.useCallback(()=>{_([]),ae("")},[Ss]),xt=u.useCallback(()=>{_(at.map(x=>x.deviceId)),ae("")},[at]),rs=u.useCallback((x,M)=>{const D=at.find(z=>z.deviceId===x);if(!D)return;const B=va(D);B<=1||(H(z=>{const pe=(za(z[x],B)+M+B)%B;return{...z,[x]:pe}}),it&&(ba(!1),te(x)))},[at,it]);u.useEffect(()=>{const x=M=>{if(it&&Se&&ws)return;const D=M.target,B=D?.tagName?.toLowerCase();D?.isContentEditable||B==="input"||B==="textarea"||B==="select"||((M.ctrlKey||M.metaKey)&&M.key.toLowerCase()==="a"&&(M.preventDefault(),xt()),M.key==="Escape"&&Et())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[ws,Et,Se,xt,it]);const Ma=(x,M)=>{const D=at.find(z=>z.deviceId===x),B=za(M,D?va(D):1);H(z=>({...z,[x]:B})),it?(ba(!1),te(x)):io(x)},ki=async x=>{if(ba(!1),te(x),je("control"),!gi.has(x)){Oe(!1),J(cr);return}const M=at.find(B=>B.deviceId===x);if(qi(M?.platform)&&(M?.capabilities?.controlPermission===!1||M?.capabilities?.accessibilityPermission===!1)){Oe(!1),J("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Oe(!0),J(`Opening remote control${M?` for ${Ka(M)}`:""}.`,"success")},Qs=async()=>{if(!Le){J("Select a workstation before playing audio.");return}if(!Wt){J(cr);return}if(!el){J("Selected workstation does not report remote audio support yet.");return}if(Te)return;const x=!le,M=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:_e.current.get(Le.deviceId);x&&M?_e.current.set(Le.deviceId,M):x||_e.current.delete(Le.deviceId),Be("audio"),Z(x);try{await Ge(`/api/remote/devices/${encodeURIComponent(Le.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...M?{streamId:M}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),J(`${x?"Audio started":"Audio stopped"} for ${Ka(Le)}.`,"success")}catch(D){x&&_e.current.delete(Le.deviceId),Z(!1),J(D instanceof Error?D.message:String(D),"error")}finally{Be("")}},Su=x=>{const M=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(M)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(M)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(M)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(M)?"The workstation disconnected before the action could be sent.":M},fl=async x=>{if(!Le||Te)return;const M=Le,B={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${B} ${Ka(M)}? Unsaved work on that computer may be lost.`))){Be(x),J(`Sending ${B.toLowerCase()} request to ${Ka(M)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(M.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},N);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");J(`${B} request sent to ${Ka(M)}.`,"success"),A()}catch(z){J(Su(z),"error")}finally{Be("")}}},xr=()=>{Le&&(rt({id:Date.now(),deviceId:Le.deviceId,instruction:"Run command "}),Oe(!1),je("agents"),J(`Command runner opened for ${Ka(Le)}.`))},Xs=async(x,M,D="files")=>{const B=x.filter(Ie=>Ie.file.size>=0);if(B.length===0)return{files:0,bytes:0};if(!Wt)throw new Error(cr);if(M.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),ge=B.reduce((Ie,Ue)=>Ie+Ue.file.size,0);let pe=0;as({id:z,status:"reading",progress:1,message:`Preparing ${B.length} ${D}`});try{for(let Ie=0;Ie<B.length;Ie+=1){const Ue=B[Ie],Ke=Ue.file,en=Math.max(1,Math.ceil(Ke.size/hh));for(let Dt=0;Dt<en;Dt+=1){const tn=Dt*hh,Ua=Math.min(Ke.size,tn+hh),Ar=Ke.size===0?new ArrayBuffer(0):await Ke.slice(tn,Ua).arrayBuffer(),Tu=Dt===en-1;as({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(pe/Math.max(1,ge)*96))),message:`${Ie+1}/${B.length} ${Ue.relativePath}`});const qa=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:M,remoteDirectory:Xn.trim(),name:Ke.name,relativePath:Ue.relativePath,size:Ke.size,type:Ke.type,lastModified:Ke.lastModified,offset:tn,totalBytes:Ke.size,final:Tu,dataBase64:wT(Ar)})},N);if(!qa.ok||qa.queued!==M.length)throw new Error(qa.error||`file-chunk-not-queued-${qa.queued}/${M.length}`);pe+=Ar.byteLength,await new Promise(pa=>window.setTimeout(pa,0))}}return as({id:z,status:"queued",progress:100,message:`Sent ${B.length} file${B.length===1?"":"s"} to ${M.length} workstation${M.length===1?"":"s"}`}),window.setTimeout(()=>{as(Ie=>Ie?.id===z&&Ie.status==="queued"?null:Ie)},4500),{files:B.length,bytes:ge}}catch(Ie){throw as({id:z,status:"failed",progress:100,message:Ie instanceof Error?Ie.message:String(Ie)}),Ie}},ro=async x=>{const M=fa.length>0?fa.map(D=>D.deviceId):Le?[Le.deviceId]:[];try{await Xs(Hy(x),M)}catch(D){J(D instanceof Error?D.message:String(D))}},yr=async x=>{try{await Xs(Hy(x),Sf)}catch(M){J(M instanceof Error?M.message:String(M))}};u.useEffect(()=>{ea.current=!1},[]);const sc=x=>{x.preventDefault(),x.stopPropagation(),Bs(!1),ro(x.dataTransfer.files)},ls=async(x="ltd")=>{if(!n){J("Sign in with Google before checkout.");return}if(T&&x===Ht){J("LiveDesk license is already active.");return}if(T&&Ht==="pro"){J("LiveDesk Pro is already active.");return}Ne("checkout");try{const{data:M,error:D}=await mt.functions.invoke("dodo-checkout",{body:{plan:x}});if(D)throw D;if(!M?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(M.checkout_url)}catch(M){J(M instanceof Error?M.message:String(M)),Ne("")}},In=aT(),$a=sT(),Ms=at.length,ml=vu.filter(x=>Si.has(x)).length,hl=hr==="open"&&ol.sampleMs>0?`${ol.framesPerSecond.toFixed(1)} fps`:hr,Me=Le?it?ll.get(Le.deviceId):Si.get(Le.deviceId):void 0,Ai=Le?za(Kt[Le.deviceId],va(Le)):0,Zs=Le?oT(Le):[],En=typeof Me?.monitorIndex=="number"?za(Me.monitorIndex,Math.max(1,Me.monitorCount||1)):Ai,lo=(Me&&En===Ai?Cw(Me):null)||(Le?Sw(Le,Ai):null);lo&&`${lo.width}${lo.height}`;const oo=Le?Rs(it?"control":"wall",Le.deviceId):"",Rn=oo?$l[oo]:void 0,ha=oo?Ki[oo]:void 0,Qe=ha?.lastInfo,rc=Rn&&Rn.sampleMs>0?`${Rn.framesPerSecond.toFixed(1)} fps`:"waiting";Rn&&`${Rn.totalFrames}${rc}`,ha&&ha.sampleMs>0&&`${ha.framesPerSecond.toFixed(1)}`,ha&&ha.sampleMs>0&&`${ha.changedFramesPerSecond.toFixed(1)}`,Qe&&(`${Qe.frameSeq}${Qe.decoderLabel}${Qe.queueSize}${Qe.renderQueueSize}${Qe.droppedForLatency}${Qe.decoderFlushCount}${Qe.decoderTimestampFallbacks}${Qe.decoderInputCount}${Qe.decoderOutputCount}`,Qe.visualChanged),Qe&&`${Math.round(Qe.queuedForMs)}${Math.round(Qe.decodedForMs)}${Math.round(Qe.scheduledForMs)}${Qe.drawMs.toFixed(1)}`,Qe?.targetPaintIntervalMs&&`${Qe.targetPaintIntervalMs.toFixed(1)}${(1e3/Qe.targetPaintIntervalMs).toFixed(1)}`,ha&&`${ha.decoderInputFps.toFixed(1)}${ha.decoderOutputFps.toFixed(1)}`,Qe?.canvasPresentation,Qe&&`${Qe.interactiveBufferWaitCount}${Math.round(Qe.interactiveBufferWaitMs)}${Qe.interactiveQueueDrainCount}`,Rn&&(Me?.frameMode==="mode5-lzo-delta"?`${Fc(Rn.averageFrameBytes)}${Me.deltaVisualTileCount||0}${Me.deltaRefreshTileCount||0}${Me.deltaTotalTiles||0}`:`${Fc(Rn.averageFrameBytes)}${Math.round(Rn.tinyFrameRatio*100)}${Math.round(Rn.repeatedFrameRatio*100)}`),Rn&&Rn.sourceSendSampleCount>0&&`${Rn.sourceSendAverageMs.toFixed(1)}${Rn.sourceSendP95Ms.toFixed(1)}`,Ey(Rn),Ey(ha),Rn&&ha&&`${Ry(Rn)}${Ry(ha)}`,Me?Me.frameMode||Me.mode||Me.codec||Me.mimeType:it?ut.frameMode:Fe.frameMode,it?ut.frameMode:Fe.frameMode,Me?`${Me.width}${Me.height}${Fc(Me.byteLength)}`:it?`${Ps.maxWidth}${Ps.maxHeight}`:`${Fe.maxWidth}${Fe.maxHeight}`,Me&&`${Me.isKeyFrame?"key":String(Me.chunkType||"delta")}`,Me&&Me.monitorCount&&((Me.monitorIndex??0)+1,`${Me.monitorCount}`),Me&&[`src ${Math.round(Me.sourceGapMs||0)}ms`,`gap ${Math.round(Me.agentSendGapMs||0)}ms`,`tx ${Math.round(Me.agentSendDurationMs||0)}ms`,`pace ${Math.round(Me.agentPaceMs||0)}ms`,`queue ${Math.round(Me.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Me.agentFrameAgeMs||0)}ms`,Me.browserReceivedEpochMs&&Me.receivedAt?`hub ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Date.parse(Me.receivedAt)))}ms`:"",Me.browserReceivedEpochMs&&Me.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Me.hubPacketEpochMs))}ms`:"",Me.droppedByAgent?`drop ${Me.droppedByAgent}`:"",Me.hubIngressDropped?`ingress-drop ${Me.hubIngressDropped}`:"",Me.hubClientDropped?`ws-drop ${Me.hubClientDropped}`:"",Me.captureStageMs?`capture ${Math.round(Me.captureStageMs)}ms`:"",Me.requestedFps?`req ${Math.round(Me.requestedFps)}fps`:"",Me.effectiveFps?`eff ${Math.round(Me.effectiveFps)}fps`:"",Me.captureAverageMs?`avg ${Math.round(Me.captureAverageMs)}ms`:"",Me.captureP95Ms?`p95 ${Math.round(Me.captureP95Ms)}ms`:"",Me.slowFrameCount?`slow ${Math.round(Me.slowFrameCount)}`:"",Me.captureHelperRestarts?`helper ${Math.round(Me.captureHelperRestarts)}`:"",Me.convertMs?`rgb565 ${Math.round(Me.convertMs)}ms`:"",Me.compressMs?`lzo ${Math.round(Me.compressMs)}ms`:"",Me.captureSourceSerial?`cap #${Me.captureSourceSerial}`:"",Me.captureSourceSkipped?`cap skip ${Me.captureSourceSkipped}`:"",Me.frameMode==="mode5-lzo-delta"?`tiles ${Me.deltaVisualTileCount||0}+${Me.deltaRefreshTileCount||0}/${Me.deltaTotalTiles||0}@${Me.deltaTileSize||0}`:"",Me.platformProfile||Me.hardwareEncoder||"-",Me.atlasComposeMs?`atlas ${Me.atlasComposeMs.toFixed(1)}ms`:"",Me.atlasPoolStarved?`pool ${Me.atlasPoolStarved}`:"",Me.atlasTileCount?`tiles ${Me.atlasReadyTiles||0}/${Me.atlasTileCount}`:"",Me.atlasInputRevision?`input #${Me.atlasInputRevision}`:"",Me.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Me.atlasSourceMaxAgeMs)}ms`:"",Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy?`feedback ${Math.round(Qe.inputFeedbackMs)}ms`:"",Me.contentHash?`enc ${Me.contentHash.slice(0,6)}`:"",Qe?.visualHash?`pix ${Qe.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),gr==="open"&&[`${ka.sentPerSecond.toFixed(1)} hz`,ka.lastInputSeq>0?`rtt ${Math.round(ka.lastRoundTripMs)}ms`:"",ka.lastInputSeq>0?`apply ${ka.lastAgentApplyMs.toFixed(1)}ms`:"",ka.droppedPerSecond>0?`drop ${ka.droppedPerSecond.toFixed(1)}/s`:"",ka.bufferedAmount>0?`buf ${Fc(ka.bufferedAmount)}`:"",ka.lastInputType||"ready"].filter(Boolean).join(" / "),Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy&&`${Math.round(Qe.inputFeedbackMs)}${Qe.inputFeedbackSeq||0}`,le&&[Aa,`context ${fn.audioContextState}`,`queue ${Math.round(fn.queuedMs)}ms`,`last ${Math.round(fn.lastPacketAgeMs)}ms`,`accepted ${Math.round(fn.lastAcceptedAgeMs)}ms`,`process ${Math.round(fn.localProcessingAgeMs)}ms`,`remote ${Math.round(fn.browserAgeMs)}/${Math.round(fn.captureAgeMs)}ms`,`heartbeat ${Math.round(fn.captureStatusAgeMs)}ms`,`capture ${fn.captureAlive&&fn.helperAlive?"alive":"down"}`,`drop ${fn.drops}`,`resync ${fn.resyncs}`,`restart ${fn.automaticRestarts}`,fn.pendingDecodes>0?`decode ${fn.pendingDecodes}`:"",ji?`#${ji.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Me&&`${Me.frameSeq}${sb(Me.receivedAt||Me.capturedAt)}`;const os=Math.max(0,ol.bytesPerSecond*8/1e6),br=mr?.atlasReadyTiles??ml,pl=mr?.atlasTileCount??ml,wr=br===pl?`${pl} tiles`:`${br}/${pl} tiles`,Sr=Gn.length>0;it?`${hl}${os.toFixed(os>=10?0:1)}`:Sr?`${wr}${hl}${os.toFixed(os>=10?0:1)}`:`${ml}${hl}${os.toFixed(os>=10?0:1)}`;const Cu=j?"offline":b?.started?"online":"starting",co=fa.length,jf=it?Le?Ka(Le):"No workstation":co===0?"No workstation":co>1?`${co} selected`:Le?Ka(Le):"No workstation",ju=it?[Le?.deviceId].filter(x=>!!x):fa.map(x=>x.deviceId),rn=Oo[Ee]||Oo.en,Cr=rn.sync||Oo.en.sync,gl=a||R?"checking":T?Ht==="pro"?"Pro LTD active":`Plus LTD ${at.length}/${Bc}`:hu?`Free ${at.length}/${Hc}`:`Upgrade ${at.length}/${Hc}`,ku=Ht==="pro"?"Pro active":fe==="checkout"?"Opening":Ht==="ltd"?"Pro $199":"Plus $79",lc=T?Ht==="pro"?"Pro active":"Upgrade to Pro LTD":n?fe==="checkout"?"Opening checkout":Ht==="ltd"?"Buy Pro LTD":"Buy Plus LTD":fe==="auth"?"Opening Google":"Sign in to buy",uo=Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,xl=n?.user?.user_metadata,yl=By(xl,"avatar_url","picture"),jr=By(xl,"full_name","name")||n?.user?.email||"Google",Js=jr.slice(0,1).toUpperCase(),Ni=b?.started?"Local app ready":"Start LiveDesk",Au=r?.active?"Published":n?"Not published":"Sign in required",Nu=/^\d{6}$/.test(b?.pairingPin||"")?b?.pairingPin:"------",kr=Yd.find(x=>x.width===Fe.maxWidth&&x.height===Fe.maxHeight)?.id||`${Fe.maxWidth}x${Fe.maxHeight}`,bl=Fe.atlasTileSizeMode==="auto"?"auto":yh.find(x=>x.width===Fe.atlasTileWidth&&x.height===Fe.atlasTileHeight)?.id||"320x180",fo=xh.find(x=>x.width===ut.maxWidth&&x.height===ut.maxHeight)?.id||`${ut.maxWidth}x${ut.maxHeight}`,wl=Wd.find(x=>x.id===Fe.frameMode)||Wd[0],Wn=x=>{Is(M=>{const D=x.frameMode?Wh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode;return{...M,...x,frameMode:D,fps:Kh(x.fps??(B?yw(D):M.fps),D)}})},Mu=x=>{const M=Yd.find(D=>D.id===x);M&&Wn({maxWidth:M.width,maxHeight:M.height})},Mi=x=>{if(x==="auto"){Wn({atlasTileSizeMode:"auto"});return}const M=yh.find(D=>D.id===x);!M?.width||!M?.height||Wn({atlasTileSizeMode:"fixed",atlasTileWidth:M.width,atlasTileHeight:M.height})},Ti=x=>{x.frameMode!==void 0&&(Q(""),me("")),ui(M=>{const D=x.frameMode?Yh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode,z=x.fps??(B?30:M.fps),ge=x.maxWidth??M.maxWidth,pe=x.maxHeight??M.maxHeight;return{...M,...x,frameMode:D,fps:ds(z,20,D==="mode3-h264-hw"?60:30,D==="mode3-h264-hw"?60:30),maxWidth:D==="mode3-h264-hw"?ge:Math.min(1920,ge),maxHeight:D==="mode3-h264-hw"?pe:Math.min(1080,pe)}})},ei=x=>{const M=xh.find(D=>D.id===x);M&&Ti({maxWidth:M.width,maxHeight:M.height})},Sl=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):ze==="support"&&window.history.pushState({},"","/")),x==="control"){const M=qn||lr;if(M&&(ba(!1),te(M.deviceId)),je(x),!Wt){Oe(!1),J(cr);return}Oe(!0);return}x==="agents"&&rt(null),x==="wall"&&Ut(M=>M+1),je(x),Oe(!1)},ti=fe==="update"||De?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(b?.update?.state||""),ni=!!(b?.update?.updateAvailable&&b.update.canApply||ti||!b&&De),ia=hC(Ee),Ei=u.useCallback(x=>{if(!De?.targetIds.includes(x))return;if(De.stage==="updated")return{state:"updated",label:"Updated"};if(De.stage==="restored"||De.stage==="failed")return{state:"failed",label:De.stage==="restored"?"Update restored":"Update failed",error:De.error};const M=b?.update?.operationId===De.operationId?b.update.targets?.find(D=>D.deviceId===x):void 0;switch(M?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:M.error||b?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return M.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[b?.update,De]);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(ib,{size:25})}),s.jsx("nav",{className:"rail-tools",children:MT.map(x=>{const M=x.icon,D=Xd(x.tooltip,Ee);return s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?Ns():Sl(x.id),"data-tooltip":x.id==="sync-server"&&$e?void 0:Th(x.label,x.tooltip,Ee),"aria-label":`${x.label}. ${D}`,type:"button",disabled:x.id==="sync-server"&&fe==="host","aria-busy":x.id==="sync-server"&&fe==="host","aria-expanded":x.id==="sync-server"?$e:void 0,"aria-haspopup":x.id==="sync-server"?"dialog":void 0,"aria-controls":x.id==="sync-server"&&$e?"hub-sync-popover":void 0,children:[x.id==="sync-server"&&fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(M,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&fe==="host"?"Syncing…":x.label})]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[TT.map(x=>{const M=x.icon;return s.jsxs("button",{className:`rail-tool compact ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>Sl(x.id),title:x.label,type:"button",children:[s.jsx(M,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${ar?"active":""}`,onClick:()=>{je("settings"),typeof window<"u"&&window.history.pushState({},"","/"),an(!1),Oe(!1),tt(!1)},title:"Settings",type:"button",children:[s.jsx(qy,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{an(x=>!x)},disabled:a||fe==="auth","aria-expanded":$t,title:n?`Account: ${n.user?.email||jr}`:"Sign in with Google",type:"button",children:[n?yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:Js}):s.jsx(Ol,{size:18}),s.jsx("span",{children:n?"Account":"Google"})]}),$t&&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:n&&yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):n?s.jsx("span",{children:Js}):s.jsx(Ol,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:n?jr:"Account"}),s.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:n?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:Ni}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:Au}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:Ht==="free"?"Standard banner":"Removed"})]}),n?s.jsxs("button",{className:"account-popover-action",onClick:Ks,disabled:fe==="auth",type:"button",children:[s.jsx(Gy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:zn,disabled:fe==="auth",type:"button",children:[s.jsx(Ol,{size:16}),"Sign in with Google"]})]})]})]}),$e&&s.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Gi,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:ia.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>sa(),"aria-label":ia.closeLabel,children:s.jsx(Ha,{size:17})})]}),s.jsx("h2",{id:"hub-sync-title",children:ia.title}),s.jsx("p",{id:"hub-sync-description",children:ia.description}),s.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[s.jsx(Lt,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:ia.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>sa(),children:ia.cancel}),s.jsxs("button",{ref:Mt,className:"primary",type:"button",onClick:wu,disabled:fe==="host",children:[s.jsx(Gi,{size:16}),ia.confirm]})]})]}),s.jsxs("section",{className:`desk-stage ${iu&&!Un?"dock-open":""} ${it?"control-stage":""} ${Vo?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(gn,{size:18})}),s.jsxs("div",{className:"brand-copy",children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]}),ni?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{nc()},title:De?.error||`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,"aria-label":ti?"LiveDesk update in progress":`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,type:"button",disabled:ti||!b?.update?.canApply,"aria-busy":ti,children:[ti?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Qh,{size:19,"aria-hidden":"true"}),ti&&b?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[b.update.completedCount||0,"/",b.update.targetCount]}):null]}):null]}),s.jsxs("div",{className:"topbar-tray",children:[ir&&!it&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(zl,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(Jh,{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:[ru," workstation",ru===1?"":"s"]}),s.jsx("em",{children:Xn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),iu&&!it&&s.jsxs("div",{className:"top-actions",children:[s.jsx(by,{controller:Zl,onError:J}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:NT.map(x=>s.jsx("button",{className:Xe===x.id?"active":"",onClick:()=>gt(x.id),type:"button",children:x.label},x.id))})]}),it&&s.jsx("div",{className:"top-actions",children:s.jsx(by,{controller:Zl,onError:J})})]})]}),sr?s.jsxs("section",{className:"doc-page",lang:Ee,dir:Ee==="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(Kd,{size:16}),rn.eyebrow]}),s.jsx("h2",{children:rn.title}),s.jsx("p",{children:rn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(h0,{size:17}),rn.languageLabel]}),s.jsx("select",{value:Ee,onChange:x=>ua(x.target.value),children:RT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:rn.sections.map((x,M)=>{const B=[Gi,Ud,Um,Lt,Hl][M]||Kd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(B,{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)})}),Cr&&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:Cr.title}),s.jsx("p",{children:Cr.body})]})]}),s.jsx("ul",{children:Cr.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:rn.firewall.title}),s.jsx("p",{children:rn.firewall.body})]})]}),s.jsx("ul",{children:rn.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(Ud,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:rn.commands.title}),s.jsx("p",{children:rn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[rn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.manager}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.primary}),s.jsx("code",{children:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.slot}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})]}):Vo?s.jsx(vy,{hubUrl:N,devices:C,launchRequest:Ye}):ir?s.jsx(xN,{hubUrl:N,devices:at,localFeatureAccess:Wt,upgradeNotice:cr,remoteDirectory:Xn,onRemoteDirectoryChange:Wi,targetMode:mi,selectedTargetIds:Jn,onTargetModeChange:Qr,onTargetToggle:x=>Xr(M=>M.includes(x)?M.filter(D=>D!==x):[...M,x]),filePickerRef:Wl,folderPickerRef:su,onBrowserFileImport:x=>{yr(x)},onBrowserFolderImport:x=>{yr(x)},onNotice:J,onTransferChange:x=>{if(!x){as(null);return}const M=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";as({id:x.id,status:M,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>as(D=>D?.id===x.id?null:D),4500)}}):Jr?s.jsx(tb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:zn}):ar?s.jsx(zj,{hubUrl:N,runtimeRole:b?.runtimeRole||"hub",runtimeDeviceId:b?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:s.jsxs(Ij,{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(Yt,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:Nu}),s.jsxs("button",{className:"text-button ghost compact",onClick:ac,disabled:!b?.started||fe==="pin",type:"button",children:[s.jsx(Ds,{size:15}),fe==="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:Cu})]}),s.jsx("span",{className:`settings-status-dot state-${Cu}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:N||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Ms,"/",Kl]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:b?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>Na({takeover:!0,requestLocalAccess:!0}),disabled:!n||fe==="host",type:"button",children:[fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),fe==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>ls(Ht==="ltd"?"pro":"ltd"),disabled:fe==="checkout"||Ht==="pro",type:"button",children:[s.jsx(Do,{size:16}),ku]})]})]})]}),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:Xn,onChange:x=>Wi(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(Oj,{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(Kc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Fe.frameMode,onChange:x=>Wn({frameMode:Wh(x.target.value)}),children:Wd.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:Fe.h264DecodeAcceleration,onChange:x=>Wn({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.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:Fe.fps,onChange:x=>Wn({fps:Kh(x.target.value,Fe.frameMode)}),children:bp.filter(x=>x<=bw(Fe.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ct?"Atlas tile":"Resolution"}),s.jsx("select",{value:ct?bl:kr,onChange:x=>ct?Mi(x.target.value):Mu(x.target.value),children:(ct?yh:Yd).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:Fe.quality,onChange:x=>Wn({quality:ds(x.target.value,20,95,xa.quality)}),children:Dy.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(gn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.autoStartLive,onChange:x=>Wn({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:Fe.visibleOnlyLive,onChange:x=>Wn({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ct&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveSizeByWall,onChange:x=>Wn({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:Fe.adaptiveLoadShedding,onChange:x=>Wn({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:Fe.showScreenStatus,onChange:x=>Wn({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:wl.label}),s.jsxs("strong",{children:[_n.maxWidth,"x",_n.maxHeight," / ",Tn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>Is(xa),type:"button",children:[s.jsx($c,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(Hj,{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($d,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ut.frameMode,onChange:x=>Ti({frameMode:Yh(x.target.value)}),children:WM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ut.h264DecodeAcceleration,onChange:x=>Ti({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.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:ut.fps,onChange:x=>Ti({fps:ds(x.target.value,20,60,Ia.fps)}),children:YM.filter(x=>ut.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:fo,onChange:x=>ei(x.target.value),children:xh.filter(x=>ut.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ut.quality,onChange:x=>Ti({quality:ds(x.target.value,20,95,Ia.quality)}),children:Dy.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(Yt,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ut.showScreenStatus,onChange:x=>Ti({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ut.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Ps.maxWidth,"x",Ps.maxHeight," / ",rr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>ui(Ia),type:"button",children:[s.jsx($c,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Bj,{hubUrl:N}),captureGallery:s.jsx(yM,{hubUrl:N,onToast:J}),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(Nl,{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:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy client command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy slot command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy Hub command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})}):Yl?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(Ah,{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:()=>Sl("wall"),title:"Close pricing",type:"button",children:s.jsx(Ha,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:or.name}),s.jsxs("small",{children:[at.length,"/",VM(Ql)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${Ht==="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:El.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:El.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Hc," 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:Ht==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${Ht==="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:El.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 ",Bc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",El.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("ltd"):zn,disabled:Ht!=="free"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${Ht==="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:El.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})," ",El.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("pro"):zn,disabled:Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(Yt,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx($d,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(rx,{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:n?()=>ls(Ht==="ltd"?"pro":"ltd"):zn,disabled:uo,type:"button",children:[s.jsx(Do,{size:18}),lc]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Un?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Go,className:`screen-wall-panel ${tr?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Et()},onDragEnter:x=>{x.preventDefault(),Bs(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&Bs(!1)},onDrop:sc,children:[Gn.length>0&&s.jsx("canvas",{ref:fr,className:"atlas-source-canvas",width:wi?.width||1920,height:wi?.height||1080,"aria-hidden":"true"}),it?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Le&&Zs.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Zs.map(x=>s.jsxs("button",{className:x.index===Ai?"active":"",onClick:()=>Ma(Le.deviceId,x.index),title:cT(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))}),Le?s.jsx(kh,{device:Le,frame:Me,selected:!1,controlEnabled:ws&&Se&&vr,showStatus:ut.showScreenStatus,monitorIndex:za(Kt[Le.deviceId],va(Le)),monitorCount:va(Le),onSelect:()=>{},onFocusDevice:()=>te(Le.deviceId),onOpenControl:()=>ki(Le.deviceId),onCycleMonitor:x=>rs(Le.deviceId,x),onCanvasReady:nl,sendInput:Ci,presentationReady:Ul},Le.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(Yt,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Le&&Yo&&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."})]}),Le&&!Yo&&!Ul&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[U!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:U==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:U==="error"?"See the notification for details. Reopen Control to retry.":Gs||de?"Control stream is recovering. See the notification for details.":hr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Xe==="list"?s.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[s.jsxs("div",{className:"wall-device-list-head",role:"row",children:[s.jsx("span",{role:"columnheader",children:"Computer"}),s.jsx("span",{role:"columnheader",children:"Status"}),s.jsx("span",{role:"columnheader",children:"CPU"}),s.jsx("span",{role:"columnheader",children:"GPU"}),s.jsx("span",{role:"columnheader",children:"RAM"}),s.jsx("span",{role:"columnheader",children:"VRAM"}),s.jsx("span",{role:"columnheader",children:"Network"}),s.jsx("span",{role:"columnheader",children:"HDD"}),s.jsx("span",{role:"columnheader",children:"Temp"})]}),ou.length>0?ou.map(({device:x,slotNumber:M})=>s.jsx(_T,{device:x,slotNumber:M,selected:ys.has(x.deviceId),updateIndicator:Ei(x.deviceId),onSelect:()=>yn(x.deviceId),onOpenControl:()=>ki(x.deviceId)},x.deviceId)):s.jsxs("div",{className:"wall-device-list-empty",children:[s.jsx(Yt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"No connected computers"})]})]}):ct?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:!1,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(x.platform)})==="direct"?na:il,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}):s.jsx("div",{className:`screen-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:ws&&Se&&vr&&Le?.deviceId===x.deviceId,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:na,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}),s.jsx(IT,{visible:ur&&!it})]}),!ar&&s.jsxs("aside",{className:`right-dock actions-mode ${Un?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>tt(x=>!x),"aria-label":Un?"Show control panel":"Hide control panel",title:Un?"Show control panel":"Hide control panel",type:"button",children:Un?s.jsx(Jy,{size:18}):s.jsx(ep,{size:18})}),!Un&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsx("input",{ref:Zr,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&ro(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual workstation controls",children:[s.jsx(Pr,{label:"Control",tooltip:Le?Yo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ws?vr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation":"Select a workstation to use Control",onClick:()=>{if(Le){if(it&&Se){Oe(!1),J("Remote control paused. Screen viewing stays on.");return}ki(Le.deviceId)}},disabled:!ws||!!Te,active:Se,pressed:it&&Se,children:s.jsx($d,{size:17})}),s.jsx(Pr,{label:"Audio",tooltip:Le?el?le?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation":"Select a workstation to use Audio",onClick:()=>{Qs()},disabled:!pu||!!Te,active:le,pressed:le,children:Te==="audio"?s.jsx(ii,{className:"spin",size:17}):s.jsx(rx,{size:17})}),s.jsx(Pr,{label:"Send files",tooltip:fa.length===0&&!it?"Select one or more workstations to send files":Le?"Choose files and send them to the selected workstation":"Select a workstation to send files",onClick:()=>{J(`Choose files to send to ${jf}.`),Zr.current?.click()},disabled:!!Te||!Wt||(it?!Le:fa.length===0),children:s.jsx(Lo,{size:17})}),s.jsx(Pr,{label:"Run command",tooltip:Le?fu?"Run command":"Command runner is not available on this workstation":"Select a workstation to run a command",onClick:xr,disabled:!Le||!Wt||!!Te||!fu,children:s.jsx(Ud,{size:17})}),s.jsx(Pr,{label:"Restart",tooltip:Le?du?"Restart workstation":"Restart is not available on this workstation":"Select a workstation to restart",onClick:()=>{fl("restart")},disabled:!Le||!Wt||!!Te||!du,children:Te==="restart"?s.jsx(ii,{className:"spin",size:17}):s.jsx($c,{size:17})}),s.jsx(Pr,{label:"Lock",tooltip:Le?"Lock workstation":"Select a workstation to lock",onClick:()=>{fl("lock")},disabled:!Le||!Wt||!!Te,children:Te==="lock"?s.jsx(ii,{className:"spin",size:17}):s.jsx(Ds,{size:17})}),s.jsx(Pr,{label:"Sleep",tooltip:Le?"Put workstation to sleep":"Select a workstation to put to sleep",onClick:()=>{fl("sleep")},disabled:!Le||!Wt||!!Te,children:Te==="sleep"?s.jsx(ii,{className:"spin",size:17}):s.jsx(g0,{size:17})}),s.jsx(Pr,{label:"Shut down",tooltip:Le?"Shut down workstation":"Select a workstation to shut down",onClick:()=>{fl("shutdown")},disabled:!Le||!Wt||!!Te,danger:!0,children:Te==="shutdown"?s.jsx(ii,{className:"spin",size:17}):s.jsx(v0,{size:17})})]})]}),s.jsx(vy,{hubUrl:N,devices:C,variant:"dock",selectedDeviceIds:ju})]})]})]})})]}),gs&&s.jsxs("aside",{className:`transfer-bar state-${gs.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:gs.status==="queued"?s.jsx(Hn,{size:18}):gs.status==="failed"?s.jsx(Ha,{size:18}):s.jsx(Qy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:gs.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,gs.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,gs.progress)),"%"]})]}),It&&s.jsxs("aside",{className:`livedesk-toast tone-${It.tone}`,role:It.tone==="error"?"alert":"status","aria-live":It.tone==="error"?"assertive":"polite","aria-busy":It.tone==="progress",children:[It.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:It.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>J(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ha,{size:15})})]})]})}function HT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function BT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const v of HT())try{const g=await fetch(`${v}/api/runtime`,{cache:"no-store"});if(!g.ok)continue;const y=(await g.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(jC,{}):s.jsx(OT,{}):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..."})]})}k0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(BT,{})}));
25
+ Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},g=c.recording?`Stop recording · ${Id(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Id(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":g,title:g,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(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.recordingStartedAt)})]}):s.jsx(Xy,{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 v(),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":w,title:w,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(ix,{size:14,fill:"currentColor"}),s.jsx("span",{children:Id(c.timelapseStartedAt)})]}):s.jsx(f0,{size:17})})]})}async function bM(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),v=Math.floor(c/m),g=document.createElement("canvas");g.width=Math.max(320,p*d),g.height=Math.max(180,v*m);const w=g.getContext("2d",{alpha:!1});if(!w)return g;w.fillStyle="#0b1220",w.fillRect(0,0,g.width,g.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let y=0;y<r.length;y+=1){const b=r[y],C=y%d,j=Math.floor(y/d),A=C*p,N=j*v,k=b.canvas,T=Math.min(p/k.width,v/k.height),R=Math.max(1,Math.floor(k.width*T)),q=Math.max(1,Math.floor(k.height*T)),O=A+Math.floor((p-R)/2),Y=N+Math.floor((v-q)/2);w.drawImage(k,O,Y,R,q),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,N+v-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,A+9,N+v-9))}return g}function wM(n){return n?.signature||"none"}function SM(n){return n?.label||"No capture target"}function wy(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function CM(){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 jM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function kM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${jM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${CM()}.png`}async function AM(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 lw(l,{kind:"screenshot",fileName:kM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function ow(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function NM(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 cw(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=ow();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await hM({kind:r,fileName:NM(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,v=!1,g=null,w=Promise.resolve();return d.ondataavailable=y=>{if(!y.data||y.data.size===0)return;const b=p++;w=w.then(()=>pM(l.sessionId,b,y.data,n.hubUrl).then(()=>{})).catch(C=>{g=g||(C instanceof Error?C:new Error(String(C))),n.onError?.(g)})},d.onerror=()=>{g=new Error("Video recording stopped unexpectedly."),n.onError?.(g)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!v){if(v=!0,await new Promise(y=>{d.addEventListener("stop",()=>y(),{once:!0}),d.stop()}),c.getTracks().forEach(y=>y.stop()),await w,g)throw await xy(l.sessionId,n.hubUrl).catch(()=>{}),g;await gM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{v||(v=!0,d.stop(),c.getTracks().forEach(y=>y.stop()),await xy(l.sessionId,n.hubUrl).catch(()=>{}))}}}class MM{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=ow();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 lw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function TM(n,a,r,l,c){const d=await cw({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 uw="livedesk.captureSettings";function EM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(uw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function RM(n){const[a,r]=u.useState(EM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,v]=u.useState(0),[g,w]=u.useState(!1),y=u.useRef(void 0),b=u.useRef(!1),C=u.useRef(""),j=u.useRef(null),A=u.useRef(null),N=u.useRef(null),k=u.useRef(null),T=u.useRef(new MM),R=n.sourceRegistry.resolveCurrentTarget(),q=wM(R),O=SM(R),Y=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(uw,JSON.stringify(a)),!b.current)return;const U=JSON.stringify(a);U!==C.current&&(C.current=U,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(W=>{y.current=Number(W.revision||y.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let U=!0;return Ge("/api/settings",void 0,n.hubUrl).then(W=>{if(!U)return;const ue=W.settings?.filesAudio||{},be=typeof ue.rollingBufferEnabled=="boolean"?ue.rollingBufferEnabled:a.rollingEnabled,X=ue.recordingQuality==="high"?"high":"standard",$=[5,10,30,60].includes(Number(ue.timelapseIntervalSeconds))?Number(ue.timelapseIntervalSeconds):a.timelapseIntervalSeconds,de=typeof ue.includeRemoteCursor=="boolean"?ue.includeRemoteCursor:a.includeRemoteCursor,me={rollingEnabled:be,recordingQuality:X,timelapseIntervalSeconds:$,includeRemoteCursor:de};y.current=Number(W.revision||0),C.current=JSON.stringify(me),b.current=!0,r(me)}).catch(()=>{b.current=!0}),()=>{U=!1}},[n.hubUrl]);const _=u.useCallback(async U=>{if(U.sourceCanvas&&U.sourceCanvas.width>0&&U.sourceCanvas.height>0)return{target:wy(U),canvas:U.sourceCanvas,cleanup:()=>{}};const W=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let ue=!1;const be=window.setInterval(async()=>{if(ue)return;const X=await n.sourceRegistry.composeWall(U.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!X||ue||((W.width!==X.width||W.height!==X.height)&&(W.width=X.width,W.height=X.height),W.getContext("2d")?.drawImage(X,0,0))},100);return{target:wy(U),canvas:W,cleanup:()=>{ue=!0,window.clearInterval(be)}}},[n.sourceRegistry]);u.useEffect(()=>{const U=T.current;if(!a.rollingEnabled||!R||!Y){U.stop(),v(0);return}let W=!1,ue=null;return(async()=>{try{if(ue=await _(R),W)return;await U.start(ue.canvas,ue.target);const X=window.setInterval(()=>v(Math.round(U.seconds)),500),$=()=>{window.clearInterval(X),ue?.cleanup()};U.__cleanup=$}catch(X){W||n.onToast(X instanceof Error?X.message:String(X))}})(),()=>{W=!0,U.stop(),U.__cleanup?.(),U.__cleanup=void 0,v(0)}},[_,n.onToast,a.rollingEnabled,q,Y]);const L=u.useCallback(U=>r(W=>({...W,rollingEnabled:U})),[]),ae=u.useCallback(U=>r(W=>({...W,recordingQuality:U})),[]),G=u.useCallback(U=>r(W=>({...W,timelapseIntervalSeconds:U})),[]),te=u.useCallback(async()=>{const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let W=null;try{W=await _(U),await AM(W.canvas,W.target,n.hubUrl),n.onToast("Screenshot saved")}finally{W?.cleanup(),w(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),P=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await cw({canvas:W.canvas,target:W.target,fps:U.type==="control"?30:15,hubUrl:n.hubUrl,onError:be=>n.onToast(be.message)});A.current=W.cleanup,j.current=ue,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),ye=u.useCallback(async()=>{const U=j.current;if(U){w(!0);try{await U.stop(),n.onToast("Recording saved")}finally{j.current=null,A.current?.(),A.current=null,c(0),w(!1)}}},[n.onToast]),ie=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(U,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const U=n.sourceRegistry.resolveCurrentTarget();if(!U)throw new Error("화면이 준비된 후 다시 시도하세요.");const W=await _(U),ue=await TM(W.canvas,W.target,a.timelapseIntervalSeconds,n.hubUrl,be=>n.onToast(be.message));k.current=W.cleanup,N.current=ue,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const U=N.current;if(U){w(!0);try{await U.stop(),n.onToast("Timelapse saved")}finally{N.current=null,k.current?.(),k.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const U=W=>{!j.current&&!N.current||(W.preventDefault(),W.returnValue="")};return window.addEventListener("beforeunload",U),()=>window.removeEventListener("beforeunload",U)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),A.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:g,targetLabel:O}),[p,g,l,a.rollingEnabled,O,d]),settings:a,videoSupported:Y,targetKey:q,setRollingEnabled:L,setRecordingQuality:ae,setTimelapseInterval:G,takeScreenshot:te,startRecording:P,stopRecording:ye,saveLast30Seconds:ie,startTimelapse:K,stopTimelapse:I}}const DM=120,LM=999,Hc=5,Bc=30,_M=Number.POSITIVE_INFINITY,dw="livedesk.remoteDirectory",$h="livedesk.localHubAccessEnabled",fw="livedesk.streamSettings",Uh=16,mw="livedesk.controlStreamSettings",qh=6,hw="livedesk.wallMonitorSelections",pw=1,hh=512*1024,Gh="".trim(),gw="".trim(),Sy="livedesk-adsense-script",ph=!!Gh&&!!gw,zM=1e3/60,gh=1500,IM=650,OM=1800,HM=650,BM=2500,Cy=1500,jy=15e3,FM=6e4,ky=240,PM=1024,$M=640,UM=360,Ay="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Od="LiveDesk is replacing the Hub and verifying the requested version.",Hd=5*6e4,qM=5e3;function Pr({label:n,tooltip:a,disabled:r=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){return s.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":a,children:s.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:r,"aria-label":n,"aria-pressed":d,type:"button",children:p})})}function GM(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 El={free:{name:"Free",price:"$0",limit:Hc,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Bc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:_M,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},vw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Ny(n,a){const r=m=>{const v=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(!v)return null;const g=v[4]?v[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return g.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(v[1]),Number(v[2]),Number(v[3])],prerelease:g}},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],v=c.prerelease[m];if(p===void 0||v===void 0)return v===void 0;if(p!==v){if(typeof p=="number"&&typeof v=="number")return p>v;if(typeof p=="number")return!1;if(typeof v=="number"||p>v)return!0;if(p<v)return!1}}return!0}function Rs(n,a){return`${n}:${a}`}const xa={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:vw["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},Ia={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function vh(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 xw(n,a){n.push(a),n.length>ky&&n.splice(0,n.length-ky)}function My(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 Ty(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),xw(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 Ey(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 Ry(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function VM(n){return Number.isFinite(n)?String(n):"30+"}const Wd=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Vh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],WM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],Yd=[{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}],xh=Yd.filter(n=>n.width>=1280),yh=[{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},{id:"640x360",label:"Crisp 640x360",width:640,height:360}],bp=[1,2,5,8,12,20,30],YM=[20,30,60],Dy=[45,60,75,90],Ly={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},list:{maxWidth:640,maxHeight:360}},ca={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallFramesPerSecond:li.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},_y=2200,KM=8e3,QM=3500,XM=7e3,ZM=2,JM=2600,eT=4200,tT=750,nT=2,zy=4200;function Iy(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Wc(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Ka(n){return n.deviceName||n.hostname||n.deviceId}function aT(){return"npx -y --prefer-online livedesk@latest client"}function sT(){return"npx -y --prefer-online livedesk@latest"}function iT(){try{return localStorage.getItem(dw)||""}catch{return""}}function rT(){try{return localStorage.getItem($h)==="1"}catch{return!1}}function To(n){try{n?localStorage.setItem($h,"1"):localStorage.removeItem($h)}catch{}}function ds(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function Wh(n){const a=String(n||"").trim();return Wd.some(r=>r.id===a)?a:xa.frameMode}function cf(n){const a=String(n||"").trim();return Vh.some(r=>r.id===a)?a:xa.h264DecodeAcceleration}function Yh(n){return n==="mode3-h264-hw"?n:Ia.frameMode}function yw(n){return vw[n]||12}function bw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Kh(n,a){return ds(n,1,bw(a),yw(a))}function Pl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function va(n){const a=Pl(n.status),r=Pl(a.screens),l=Pl(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 qr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function lT(n){const a=Pl(n.status),l=[Pl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>Pl(d));return[]}function ww(n,a){const r=lT(n),l=r.find(v=>Number(v.index)===a)||r[a]||r[0]||{},c=qr(l.width),d=qr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(v=>typeof v=="string"&&v.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 oT(n){const a=va(n);return Array.from({length:a},(r,l)=>ww(n,l))}function cT(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 Sw(n,a){const r=ww(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=Pl(n.status),c=qr(l.screenWidth||l.width),d=qr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Cw(n){if(!n)return null;const a=qr(n.sourceWidth)||qr(n.width),r=qr(n.sourceHeight)||qr(n.height);return a>0&&r>0?{width:a,height:r}:null}function uT(n,a,r){const d=((typeof a?.monitorIndex=="number"?za(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?Cw(a):null)||Sw(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Bd=16/9;function za(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 dT(){try{const n=localStorage.getItem(hw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==pw||!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 fT(n){try{localStorage.setItem(hw,JSON.stringify({version:pw,selections:n}))}catch{}}function mT(){try{const n=JSON.parse(localStorage.getItem(fw)||"{}"),a=Number(n.version);if(![Uh,15,14,13,12,11].includes(a))return xa;const r=Wh(n.frameMode),l=ds(n.maxWidth,320,3840,xa.maxWidth),c=ds(n.maxHeight,180,2160,xa.maxHeight),d=Number(n.atlasTileWidth),m=Number(n.atlasTileHeight),p=d>=640||m>=360?{width:640,height:360}:d>=480||m>=270?{width:480,height:270}:{width:320,height:180};return{frameMode:r,h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:a<Uh&&r==="mode3-h264-hw"?xa.fps:Kh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:p.width,atlasTileHeight:p.height,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:ds(n.quality,20,95,xa.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:xa.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:xa.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:xa.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:xa.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:xa.adaptiveSizeByWall}}catch{return xa}}function hT(n){try{localStorage.setItem(fw,JSON.stringify({...n,version:Uh}))}catch{}}function pT(){try{const n=JSON.parse(localStorage.getItem(mw)||"{}"),a=Number(n.version);if(![qh,5,4,3,2,1].includes(a))return Ia;const r=ds(n.fps,20,60,Ia.fps),l=a<qh;return{frameMode:l?Ia.frameMode:Yh(n.frameMode),h264DecodeAcceleration:l?Ia.h264DecodeAcceleration:cf(n.h264DecodeAcceleration),fps:l?Ia.fps:r,maxWidth:ds(n.maxWidth,1280,3840,Ia.maxWidth),maxHeight:ds(n.maxHeight,720,2160,Ia.maxHeight),quality:ds(n.quality,20,95,Ia.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ia.showScreenStatus}}catch{return Ia}}function gT(n){try{localStorage.setItem(mw,JSON.stringify({...n,version:qh}))}catch{}}function bh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function wh(n){return[...new Set(n.filter(Boolean))].sort()}function vT(n){return ca.fallbackVisibleCounts[n]||ca.fallbackVisibleCounts.large}function xT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Ly[a]||Ly.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function yT(n,a=ca.minFps){const r=[...bp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function bT(n,a){return[...bp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Fc(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 Oy(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 Sh(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`${Oy(r)} / ${Oy(n)}`}function wT(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 Hy(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 ST(n){return n===1?"middle":n===2?"right":"left"}function By(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Fy(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=LM?a:0}const CT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function jT(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=CT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function yf(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 pn(n,...a){for(const r of a){const l=yf(n,r),c=Number(l);if(Number.isFinite(c))return c}}function Qa(n,...a){for(const r of a){const l=yf(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function kT(n,...a){for(const r of a){const l=yf(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 Ui(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function Ch(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return Ui((n-Math.max(0,a))/n)}function Eo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function jh(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 Rl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function AT(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 Fd(n,a,r){const l=yf(n,`tools.${a}`),c=Qa(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=kT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=Qa(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=Qa(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let v="unknown";return c==="busy"?v="busy":["online","running","ready","active"].includes(c)||d===!0?v="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(v="offline"),{id:a,label:r,status:v,detail:v==="offline"?"offline":m||(p?`:${p}`:v==="unknown"?"not reported":v)}}function jw(n){const a=n.status||{},r=pn(a,"cpu.cores","cpuCores","processorCount"),l=pn(a,"loadavg.0","cpu.load1"),c=Ui(pn(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=pn(a,"memory.totalBytes","totalMem"),m=pn(a,"memory.freeBytes","freeMem"),p=Ui(pn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ch(d,m),v=pn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),g=pn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=Ui(pn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ch(v,g),y=pn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=Ui(pn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),C=Qa(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=pn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=pn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=Ui(pn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ch(j,A),k=pn(a,"gpu.temperatureC","thermal.gpuC"),T=Ui(pn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=Qa(a,"npu.name","npu.model","accelerators.npu.name"),q=pn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=pn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),Y=pn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=pn(a,"network.latencyMs","network.rttMs"),L=Ui(pn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ae=Qa(a,"network.link","network.interface","network.name"),G=Math.max(y??Number.NEGATIVE_INFINITY,k??Number.NEGATIVE_INFINITY),te=Number.isFinite(G)?G:void 0,P=te===void 0?void 0:Ui((te-35)/60),ye=y!==void 0&&k!==void 0?`CPU ${Math.round(y)}° · GPU ${Math.round(k)}°`:y!==void 0?`CPU ${Math.round(y)}°`:k!==void 0?`GPU ${Math.round(k)}°`:"-",ie=Qa(a,"workload.role","role","lane")||(Wc(n,"aiAssist")?"Agent worker":Wc(n,"taskDispatch")?"Task worker":"Local machine"),K=Qa(n.latestTask,"status")||Qa(a,"workload.status")||"idle",I=Qa(n.latestTask,"title","instructionPreview")||Qa(a,"workload.title"),Q=Qa(n.latestTask,"resultSummary","error","instructionPreview")||Qa(a,"workload.summary"),U=[Fd(a,"ollama","Ollama"),Fd(a,"lmStudio","LM Studio"),Fd(a,"comfyui","ComfyUI"),Fd(a,"stableDiffusion","Stable Diffusion")],W=U.some(me=>me.status!=="unknown"),ue=Date.parse(n.lastSeenAt||n.connectedAt||""),be=Number.isFinite(ue)?Date.now()-ue:0;let X="online";n.connected?be>5*6e4?X="stale":(y??0)>=86||(k??0)>=88||(c??0)>=.94||(b??0)>=.96||(N??0)>=.96||(T??0)>=.96||(p??0)>=.94||(w??0)>=.94||(_??0)>=200||K==="failed"?X="critical":(y??0)>=78||(k??0)>=80||(c??0)>=.82||(b??0)>=.86||(N??0)>=.88||(T??0)>=.86||(p??0)>=.82||(w??0)>=.86||(_??0)>=80?X="warn":(["queued","running","targeted"].includes(K)||U.some(me=>me.status==="busy"))&&(X="busy"):X="offline";const $=U.filter(me=>me.status==="online"||me.status==="busy").length,de=[{id:"cpu",label:"CPU",value:Eo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:Rl(c,.92,.78)},{id:"memory",label:"RAM",value:Eo(p),detail:Sh(d,m),ratio:p,state:Rl(p,.92,.78)},{id:"disk",label:"DISK",value:Eo(w),detail:Sh(v,g),ratio:w,state:Rl(w,.92,.82)},{id:"gpu",label:"GPU",value:Eo(b),detail:C||(j&&A!==void 0?`${Fc(A)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:b,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":Rl(b,.96,.86)},{id:"vram",label:"VRAM",value:Eo(N),detail:Sh(j,A),ratio:N,state:Rl(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?Eo(T):q!==void 0?`${Math.round(q)} TOPS`:"-",detail:R||(q!==void 0?"neural engine":"not reported"),ratio:T,state:Rl(T,.96,.86)},{id:"temp",label:"TEMP",value:ye,detail:$>0?`${$} local tools`:`uptime ${AT(pn(a,"uptimeSec"))}`,ratio:P,state:te===void 0?"unknown":te>=86?"critical":te>=78?"warn":"good"},{id:"network",label:"NET",value:jh(O)||(_!==void 0?`${Math.round(_)}ms`:ae||"-"),detail:jh(Y)?`${jh(Y)} up`:ae||"not reported",ratio:L,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":Rl(L,.9,.75)}];return{state:X,label:jT(X,de,K),role:ie,taskLabel:I||(K==="idle"?"idle":K),taskStatus:K,taskSummary:Q,tools:W?U:U.map(me=>({...me,detail:"not reported"})),metrics:de}}const NT=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],MT=[{id:"sync-server",label:"Hub",icon:Gi,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Kc,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:$d,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Pd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Ud,accent:"violet",tooltip:"agents"}],TT=[{id:"doc",label:"Doc",icon:Kd,accent:"amber"},{id:"support",label:"Support",icon:Pc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Do,accent:"green"}];function ET(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 ln(n){return ET(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 Dl(n){return n.map(a=>ln(a))}function la(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:ln(n.title),intro:ln(n.intro),sections:[{title:ln(n.managerTitle),body:ln(n.managerBody),points:Dl(n.managerPoints)},{title:ln(n.clientTitle),body:ln(n.clientBody),points:Dl(n.clientPoints)},{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:ln(n.agentTitle),body:ln(n.agentBody),points:Dl(n.agentPoints)}]:[],{title:ln(n.platformTitle),body:ln(n.platformBody),points:Dl(n.platformPoints)}],sync:{title:ln(n.syncTitle),body:ln(n.syncBody),points:Dl(n.syncPoints)},firewall:{title:ln(n.firewallTitle),body:ln(n.firewallBody),points:Dl(n.firewallPoints)},commands:{title:ln(n.commandsTitle),body:ln(n.commandsBody),manager:ln(n.managerCommandLabel),primary:ln(n.clientCommandLabel),slot:ln(n.slotCommandLabel),manual:ln(n.manualCommandLabel)}}}const Oo={ko:la({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:la({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:la({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":la({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":la({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:la({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:la({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:la({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":la({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:la({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:la({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:la({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:la({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:la({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:la({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:la({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ı"})},RT=Object.entries(Oo).map(([n,a])=>({id:n,label:a.languageName}));function DT(){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 Py({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(Yt,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}const LT=["cpu","gpu","memory","vram","network","disk","temp"];function _T({device:n,slotNumber:a,selected:r,updateIndicator:l,onSelect:c,onOpenControl:d}){const m=jw(n),p=new Map(m.metrics.map(g=>[g.id,g])),v=l?.label||m.label;return s.jsxs("div",{className:`wall-device-list-row state-${m.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:c,onDoubleClick:g=>{g.preventDefault(),d()},onKeyDown:g=>{(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),c())},children:[s.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[s.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:s.jsx(Yt,{size:17})}),s.jsxs("span",{children:[s.jsx("strong",{children:Ka(n)}),s.jsxs("small",{children:["Slot ",String(a).padStart(3,"0"),n.platform?` · ${n.platform}`:"",n.arch?` · ${n.arch}`:""]})]}),r&&s.jsx(ri,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),s.jsxs("span",{className:`wall-device-list-status state-${m.state} ${l?`update-${l.state}`:""}`,role:"gridcell",title:l?.error||v,children:[s.jsx("i",{"aria-hidden":"true"}),s.jsx("strong",{children:v})]}),LT.map(g=>{const w=p.get(g);return s.jsxs("span",{className:`wall-device-list-metric state-${w?.state||"unknown"}`,role:"gridcell",title:w?`${w.label}: ${w.value} · ${w.detail}`:"Not reported",children:[s.jsx("strong",{children:w?.value||"-"}),s.jsx("small",{children:w?.detail||"not reported"}),w?.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round(w.ratio*100)}%`},"aria-hidden":"true"})]},g)})]})}function zT(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 $y(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:qi(n.platform)}function kh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:v,onOpenControl:g,onCycleMonitor:w,onCanvasReady:y,sendInput:b,updateIndicator:C,presentationReady:j,showPresentationSpinner:A=!1}){const N=u.useRef(null),k=u.useRef(null),T=u.useRef(0),R=u.useRef(null),q=jw(n),O=["cpu","gpu","memory","vram"].map($=>q.metrics.find(de=>de.id===$)).filter($=>!!$),Y=za(d,m),_=m>1,L=j??!!a,ae=zT(n)&&!L,G=A&&n.connected&&!L&&!ae,te=uT(n,a,Y),P=te>=Bd?100:te/Bd*100,ye=te>=Bd?Bd/te*100:100,ie={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,P)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,ye)).toFixed(3)}%`},K=u.useCallback($=>{N.current=$,y(n.deviceId,$)},[n.deviceId,y]),I=$=>{const de=$.currentTarget.getBoundingClientRect();return Ej($.clientX,$.clientY,de)},Q=$=>({shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}),U=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),W=u.useCallback(()=>{const $=k.current;if(!$)return;k.current=null;const de=Number($.input.normalizedX),me=Number($.input.normalizedY);if(!Number.isFinite(de)||!Number.isFinite(me))return;b(n.deviceId,{...$.input,normalizedX:de,normalizedY:me})&&(T.current=performance.now())},[n.deviceId,b]),ue=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,W()}))},[W]);u.useEffect(()=>()=>{U(),k.current=null},[U]);const be=($,de)=>{if(!l)return;const me={type:de,monitorIndex:Y,...I($),button:ST($.button),...Q($)};if(de==="pointermove"){const ve=performance.now();k.current={input:me},ve-T.current>=zM&&(U(),W()),ue();return}k.current&&(U(),W()),b(n.deviceId,me)},X=u.useCallback($=>{const de=document.activeElement;de instanceof HTMLElement&&$.contains(de)&&de.classList.contains("monitor-cycle-button")&&de.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:ie,children:s.jsxs("div",{className:`tile-screen ${L?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||p()},onKeyDown:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),p())},onDoubleClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||($.preventDefault(),g())},onPointerLeave:$=>X($.currentTarget),children:[s.jsx("span",{className:`screen-content ${L?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:K,className:`remote-canvas ${L?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:$=>{l&&($.preventDefault(),$.stopPropagation(),v(),$.currentTarget.focus(),$.currentTarget.setPointerCapture($.pointerId),be($,"pointerdown"))},onPointerMove:$=>{l&&$.preventDefault(),be($,"pointermove")},onPointerLeave:$=>{l&&(be($,"pointermove"),U(),W())},onPointerUp:$=>{l&&($.preventDefault(),$.stopPropagation(),be($,"pointerup"),$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId))},onPointerCancel:$=>{$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId)},onWheel:$=>{l&&($.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:Y,...I($),deltaX:$.deltaX,deltaY:$.deltaY,...Q($)}))},onKeyDown:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:$.repeat,...Q($)}))},onKeyUp:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:!1,...Q($)}))},onContextMenu:$=>l&&$.preventDefault()})}),!L&&s.jsx("span",{className:"empty-screen",children:s.jsx(Yt,{size:26})}),G&&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"})]}),ae&&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."})]}),C&&s.jsxs("span",{className:`wall-update-status state-${C.state}`,role:"status","aria-live":"polite",title:C.error||C.label,children:[C.state==="updated"?s.jsx(Hn,{size:20,"aria-hidden":"true"}):C.state==="failed"?s.jsx(Ha,{size:22,"aria-hidden":"true"}):C.state==="offline"?s.jsx(Hl,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:C.label}),C.error?s.jsx("small",{children:C.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${q.state}`,children:q.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${Ka(n)} status`,children:O.map($=>s.jsxs("span",{className:`tile-metric state-${$.state}`,children:[s.jsx("b",{children:$.label}),s.jsx("em",{children:$.value}),$.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round($.ratio*100)}%`}})]},$.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${Ka(n)} display ${Y+1} of ${m}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>$.stopPropagation(),onDoubleClick:$=>$.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(-1),$.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Jy,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",Y+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(1),$.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(ep,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(ri,{size:23,strokeWidth:3.5})})]})})}function IT({visible:n}){return u.useEffect(()=>{if(!n||!ph)return;if(!document.getElementById(Sy)){const r=document.createElement("script");r.id=Sy,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent(Gh)}`,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":Gh,"data-ad-slot":gw,"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 OT(){const{session:n,loading:a}=oj(),{target:r,error:l,refresh:c}=uj(n),d=u.useMemo(()=>{if(!r?.active)return null;const x=r.expires_at?Date.parse(r.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(x)&&x<=Date.now()?null:r},[r]),m=u.useMemo(()=>xx(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,Cn])]:[Cn],[m]),[v,g]=u.useState(rT),w=u.useMemo(()=>p.some(x=>!!qc(x)),[p]),y=!w||v,{status:b,devices:C,error:j,refresh:A,hubBaseUrl:N}=cj(p,y),{entitlement:k,licensed:T,loading:R,error:q,refresh:O}=dj(n),[Y,_]=u.useState([]),[L,ae]=u.useState(""),[G,te]=u.useState(""),[P,ye]=u.useState(""),[ie,K]=u.useState(""),[I,Q]=u.useState(""),[U,W]=u.useState("idle"),[ue,be]=u.useState(!1),[X,$]=u.useState(null),[de,me]=u.useState(""),ve=u.useRef("");ve.current=ie;const[Se,Oe]=u.useState(!1),[le,Z]=u.useState(!1),He=u.useRef(""),_e=u.useRef(new Map),se=u.useRef(0),[fe,Ne]=u.useState(""),[Te,Be]=u.useState(""),[$e,et]=u.useState(!1),Mt=u.useRef(null),ke=u.useRef(null),[Ye,rt]=u.useState(null);u.useEffect(()=>{fe==="auth"&&n?.access_token&&Ne("")},[fe,n?.access_token]);const[vt,vn]=u.useState(""),[It,Zt]=u.useState(null),ht=u.useRef(null),$n=u.useRef(0),Gt=u.useCallback((x,M,D)=>{const B=String(x||"").trim();if(vn(B),ht.current!==null&&(window.clearTimeout(ht.current),ht.current=null),!B){Zt(null);return}const z=++$n.current;if(Zt({id:z,message:B,tone:M}),!D)return;const ge=window.setTimeout(()=>{Zt(pe=>pe?.id===z?null:pe),ht.current===ge&&(ht.current=null)},5e3);ht.current=ge},[]),J=u.useCallback((x,M="info")=>{Gt(x,M,!0)},[Gt]),Re=u.useCallback(x=>{Gt(x,"progress",!1)},[Gt]);u.useEffect(()=>()=>{ht.current!==null&&window.clearTimeout(ht.current)},[]);const[ze,je]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const x=()=>{je(window.location.pathname.startsWith("/support")?"support":M=>M==="support"?"wall":M)};return window.addEventListener("popstate",x),()=>window.removeEventListener("popstate",x)},[]);const[Xe,gt]=u.useState("large"),[Ee,ua]=u.useState(DT),[Un,tt]=u.useState(!1),[$t,an]=u.useState(!1),[Za,Ja]=u.useState(!1),[Xn,Wi]=u.useState(iT),[Fe,Is]=u.useState(mT),[ut,ui]=u.useState(pT),[Kt,H]=u.useState(dT),[De,st]=u.useState(null),[on,es]=u.useState([]),[Tn,da]=u.useState(Fe.fps),[ne,Ae]=u.useState(""),[qe,ot]=u.useState(0),[Jt,Ut]=u.useState(0),[Ze,jt]=u.useState(()=>new Set),Ot=u.useRef(new Map),Vt=u.useRef(new Map),sn=u.useRef(new Map),wt=u.useRef(new Map),cn=u.useRef(new Map),Tt=u.useRef(new Set),ts=u.useRef(new Map),xn=u.useRef(""),un=u.useRef(""),dn=u.useRef(null),Os=u.useRef(null),ya=u.useRef(new Map),Hs=u.useRef(null),Po=u.useRef(0),Yi=u.useRef(new Map),[Ki,ms]=u.useState({}),Zn=u.useRef(new Map),[$l,bf]=u.useState({}),[Ul,ba]=u.useState(!1),Qi=u.useRef(null),ns=u.useRef(null),Qt=u.useRef(0),hs=u.useRef(""),Xi=u.useRef(new Map),di=u.useRef(new Map),ps=u.useRef(performance.now()),Zi=u.useRef(new Map),fi=u.useRef(new Map),Fa=u.useRef(new Map),$o=u.useRef(new Map),Ji=u.useRef(0),Yr=u.useRef(0),er=u.useRef(0),ql=u.useRef(0),Uo=u.useRef(0),Kr=u.useRef(new Map),Ln=u.useRef(new Map),[gs,as]=u.useState(null),[tr,Bs]=u.useState(!1),[wf,qo]=u.useState([]),[mi,Qr]=u.useState("all"),[Jn,Xr]=u.useState([]),[Gl,hi]=u.useState(!1),[au,Vl]=u.useState(!0),Go=u.useRef(null),Zr=u.useRef(null),Wl=u.useRef(null),su=u.useRef(null),ea=u.useRef(!1),vs=u.useRef(!1),nr=u.useRef(!1),xs=u.useRef(0),Fs=u.useRef(0),ar=ze==="settings",Yl=ze==="pricing",sr=ze==="doc",Jr=ze==="support",ir=ze==="share-files",Vo=ze==="agents",iu=!ar&&!Yl&&!sr&&!Jr&&!ir&&!Vo,it=ze==="control",ct=Fe.frameMode==="mode4-h264-atlas",wa=I||ut.frameMode,rr=wa!=="mode3-h264-hw"?Math.min(30,ut.fps):ut.fps,Ps=wa!=="mode3-h264-hw"?{maxWidth:Math.min(1920,ut.maxWidth),maxHeight:Math.min(1080,ut.maxHeight)}:{maxWidth:ut.maxWidth,maxHeight:ut.maxHeight};u.useEffect(()=>{if(b?.started){if(!n?.access_token){Ge("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(x=>{console.warn("[LiveDesk] Hub license sync failed",x)})}},[k?.updated_at,N,n?.access_token,b?.started]),u.useEffect(()=>{!n?.access_token||!b?.started||b.runtimeRole!=="hub"||!b.deviceId||(async()=>{try{const{data:x,error:M}=await mt.rpc("register_livedesk_device",{p_device_id:b.deviceId,p_device_name:b.deviceName||b.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:b.managerVersion||b.managerPackage||""}),D=Array.isArray(x)?x[0]:x;(M||D?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",M||D?.reason||"unknown-error")}catch(x){console.warn("[LiveDesk] Hub device role registration failed",x)}})()},[n?.access_token,b?.deviceId,b?.deviceName,b?.managerPackage,b?.managerVersion,b?.runtimeRole,b?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!b?.started||b.runtimeRole!=="hub"||nr.current||(nr.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},N||Cn).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"),A()}).catch(x=>{console.warn("[LiveDesk] Hub session sync failed:",x)}).finally(()=>{nr.current=!1}))},[N,A,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,b?.runtimeRole,b?.started]);const at=u.useMemo(()=>C.filter(x=>x.connected),[C]),ru=mi==="all"?at.length:Jn.filter(x=>at.some(M=>M.deviceId===x)).length,lu=u.useMemo(()=>at.reduce((x,M)=>Math.max(x,Fy(M.slotNumber)),0),[at]),Kl=Math.max(DM,at.length,lu),pi=u.useMemo(()=>{const x=Array(Kl).fill(null),M=[];for(const D of at){const B=Fy(D.slotNumber);B>0&&B<=Kl&&!x[B-1]?x[B-1]=D:M.push(D)}for(const D of M){const B=x.findIndex(z=>!z);B<0?x.push(D):x[B]=D}return x},[at]),ou=u.useMemo(()=>pi.flatMap((x,M)=>x?[{device:x,slotNumber:M+1}]:[]),[pi]),Wo=u.useMemo(()=>at.map(x=>x.deviceId),[at]),ys=u.useMemo(()=>new Set(Y),[Y]),fa=u.useMemo(()=>at.filter(x=>ys.has(x.deviceId)),[at,ys]),lr=u.useMemo(()=>C.find(x=>x.deviceId===L)||fa[0]||null,[C,L,fa]),qn=u.useMemo(()=>C.find(x=>x.deviceId===G)||null,[G,C]),bs=qn?za(Kt[qn.deviceId],va(qn)):0,Le=it?qn:lr,cu=u.useMemo(()=>new Set(Jn),[Jn]),Sf=u.useMemo(()=>mi==="all"?at.map(x=>x.deviceId):at.filter(x=>cu.has(x.deviceId)).map(x=>x.deviceId),[at,cu,mi]),Cf=Le?Wc(Le,"control"):!1,Yo=qi(Le?.platform)&&(Le?.capabilities?.controlPermission===!1||Le?.capabilities?.accessibilityPermission===!1),el=Le?Wc(Le,"audio")||Wc(Le,"remoteAudio"):!1,uu=Array.isArray(Le?.capabilities?.agentTools)?Le.capabilities.agentTools.map(String):[],du=uu.includes("system.power"),fu=uu.includes("command.run"),Ht=T?k?.plan==="pro"?"pro":"ltd":"free",or=El[Ht],Ql=or.limit,gi=u.useMemo(()=>{if(!Number.isFinite(Ql))return new Set(at.map(M=>M.deviceId));const x=Le?[Le,...at.filter(M=>M.deviceId!==Le.deviceId)]:at;return new Set(x.slice(0,Ql).map(M=>M.deviceId))},[Ql,at,Le]),mu=!Le||gi.has(Le.deviceId),hu=Ht==="free",Wt=mu,cr=Ht==="ltd"?`Plus includes up to ${Bc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Hc} workstations. Upgrade to Plus for ${Bc} devices and no ads.`,ur=Ht==="free",ws=Wt&&!!Le&&Cf,pu=Wt&&!!Le&&el,Xl=u.useMemo(()=>pi.filter(x=>!!x?.connected).slice(0,vT(Xe)).map(x=>x.deviceId),[pi,Xe]),tl=u.useMemo(()=>Xe==="list"?[]:ct?Wo:Fe.visibleOnlyLive?on.length>0?on:Xl:Wo,[Xl,ct,on,Fe.visibleOnlyLive,Wo,Xe]),Sa=u.useMemo(()=>wh(tl.filter(x=>gi.has(x))),[gi,tl]),Ca=u.useMemo(()=>Sa.filter(x=>x!==ne),[Sa,ne]),$s=u.useMemo(()=>new Map(at.map(x=>[x.deviceId,x.platform])),[at]),ss=Rj(ct,Sa.length),Gn=u.useMemo(()=>ct?Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="atlas"):[],[ss,ct,$s,Ca]),ta=u.useMemo(()=>Ca.filter(x=>zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi($s.get(x))})==="direct"),[ss,ct,$s,Ca]);u.useEffect(()=>{const x=new Set(Sa);jt(M=>{let D=!1;const B=new Set;for(const z of M)x.has(z)?B.add(z):D=!0;return D?B:M})},[Sa]);const gu=u.useMemo(()=>{const x=z=>at.find(ge=>ge.deviceId===z)||null,M=z=>za(Kt[z],x(z)?va(x(z)):0),D=(z,ge=M(z))=>z===P&&(U==="connecting"||U==="active"||U==="warm")?wt.current.get(z)||Vt.current.get(z)||null:ct?ya.current.get(z)||Ot.current.get(z)||null:Ot.current.get(z)||null,B=(z,ge=M(z))=>{const pe=x(z);return`${pe?Ka(pe):z} · Monitor ${ge+1}`};return{resolveCurrentTarget(){if(it&&qn){const Ue=bs;return{type:"control",deviceIds:[qn.deviceId],monitorIndex:Ue,label:`${Ka(qn)} · Monitor ${Ue+1}`,sourceCanvas:D(qn.deviceId,Ue),signature:`control:${qn.deviceId}:${Ue}:${ut.frameMode}`}}const z=fa.map(Ue=>Ue.deviceId).filter(Ue=>Ca.includes(Ue)),ge=lr&&Ca.includes(lr.deviceId)?lr.deviceId:"",pe=z.length>0?z:ge?[ge]:Ca,Ie=z.length===0&&!ge;if(pe.length===0)return null;if(pe.length===1){const Ue=pe[0],Ke=M(Ue);return{type:Ie?"wall":z.length>1?"selection":"device",deviceIds:pe,monitorIndex:Ke,label:Ie?"Wall":B(Ue,Ke),sourceCanvas:Ie?null:D(Ue,Ke),signature:`${Ie?"wall":"device"}:${Ue}:${Ke}:${ct?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:pe,label:z.length>1?`${pe.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${pe.join(",")}:${Xe}`}},getDeviceCanvas:D,composeWall(z,ge={}){return bM(z.map(pe=>{const Ie=M(pe);return{deviceId:pe,label:B(pe,Ie),canvas:D(pe,Ie)}}),ge)}}},[at,qn,P,U,ut.frameMode,Ot,ct,Kt,bs,fa,it,Ca,lr,Xe]),Zl=RM({hubUrl:N,sourceRegistry:gu,onToast:J}),Us=u.useMemo(()=>Wt&&P&&gi.has(P)&&(U==="connecting"||U==="active"||U==="warm")?[P]:[],[P,U,Wt,gi]),vu=u.useMemo(()=>wh([...Sa,...Us]),[Us,Sa]),_n=u.useMemo(()=>xT(Fe,Xe),[Fe,Xe]),vi=Dj({mode4Enabled:ct,directMode4WallEnabled:ss,adaptiveFps:Tn,directDeviceCount:ta.length}),Ss=u.useCallback((x,M,D)=>{if(x.width<=0||x.height<=0)return!1;const B=D?Math.min(1,D.maxWidth/x.width,D.maxHeight/x.height):1,z=Math.max(1,Math.round(x.width*B)),ge=Math.max(1,Math.round(x.height*B));(M.width!==z||M.height!==ge)&&(M.width=z,M.height=ge);const pe=M.getContext("2d",{alpha:!1});return pe?(pe.imageSmoothingEnabled=!0,pe.imageSmoothingQuality="high",pe.drawImage(x,0,0,x.width,x.height,0,0,M.width,M.height),!0):!1},[]),dr=u.useCallback(x=>{x&&jt(M=>{if(M.has(x))return M;const D=new Set(M);return D.add(x),D})},[]),Jl=u.useCallback(x=>{x&&jt(M=>{if(!M.has(x))return M;const D=new Set(M);return D.delete(x),D})},[]),eo=u.useCallback((x,M)=>{if(!M||M.width<=0||M.height<=0)return!1;const D=document.createElement("canvas");return D.width=M.width,D.height=M.height,Ss(M,D)?(sn.current.set(x,D),dr(x),!0):!1},[dr,Ss]),Cs=u.useCallback((x,M=!1)=>{if(!Tt.current.has(x))return!1;const D=performance.now(),B=ts.current.get(x)||0,z=Math.max(1,Math.min(li.controlWallReuseMaxFps,rr)),ge=rr>z?Math.max(0,1e3/z-2):0;if(!M&&D-B<ge)return!1;const pe=wt.current.get(x)||Vt.current.get(x),Ie=Ot.current.get(x)||ya.current.get(x);return!pe||!Ie||!Ss(pe,Ie,_n)?!1:(ts.current.set(x,D),dr(x),!0)},[rr,_n,dr,Ss]);u.useEffect(()=>{xn.current=ne},[ne]);const na=u.useCallback((x,M)=>{const D=Ot.current.get(x);if(D&&D!==M&&(eo(x,D),_c(D)),M){Ot.current.set(x,M),sn.current.delete(x),Cs(x,!0);return}Ot.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,Cs,eo]),nl=u.useCallback((x,M)=>{const D=Vt.current.get(x);if(D&&D!==M&&_c(D),M){Vt.current.set(x,M);const B=wt.current.get(x)||sn.current.get(x)||Ot.current.get(x)||ya.current.get(x);B&&Ss(B,M)&&x===G&&ba(!0);return}Vt.current.delete(x)},[G,Ss]),al=u.useCallback((x,M,D)=>{const B=performance.now(),z=Rs(x,D.deviceId);let ge=D;if(x==="control"&&D.visualChanged){const Ie=vj(D.deviceId),Ue=Kr.current.get(D.deviceId)||0,Ke=Ie?B-Ie.sentAt:Number.POSITIVE_INFINITY;Ie&&Ie.inputSeq>Ue&&Ke<=Cy&&(ge={...D,inputFeedbackSeq:Ie.inputSeq,inputFeedbackMs:Math.max(0,Ke),inputFeedbackAt:B},Kr.current.set(D.deviceId,Ie.inputSeq))}di.current.set(z,B);const pe=Yi.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:B,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};x==="control"&&ge.inputFeedbackMs===void 0&&pe.lastInfo?.inputFeedbackMs!==void 0&&pe.lastInfo.inputFeedbackAt!==void 0&&B-pe.lastInfo.inputFeedbackAt<=Cy&&(ge={...ge,inputFeedbackSeq:pe.lastInfo.inputFeedbackSeq,inputFeedbackMs:pe.lastInfo.inputFeedbackMs,inputFeedbackAt:pe.lastInfo.inputFeedbackAt}),pe.totalFrames+=1,pe.sampleFrames+=1,Ty(pe,B,ge.frameSeq),ge.visualChanged&&(pe.totalChangedFrames+=1,pe.sampleChangedFrames+=1),pe.lastInfo=ge,Yi.current.set(z,pe)},[]),sl=u.useCallback((x,M)=>{al("wall",x,M),x.kind==="live"&&dr(x.deviceId);const D=ue&&P===x.deviceId;xn.current!==x.deviceId&&!D&&(Tt.current.delete(x.deviceId),ts.current.delete(x.deviceId))},[P,ue,dr,al]),Ko=u.useCallback((x,M)=>{al("control",x,M),me(ge=>ge&&"");const D=wt.current.get(x.deviceId),B=Vt.current.get(x.deviceId);D&&D.width>0&&D.height>0&&(B&&Ss(D,B),cn.current.set(x.deviceId,{...x,payload:new Uint8Array(0),byteLength:0}),sn.current.delete(x.deviceId),Tt.current.add(x.deviceId),x.deviceId===P&&(be(!0),W(ge=>ge==="connecting"?"active":ge)),Cs(x.deviceId));const z=Qi.current;!z||!GM(z,x)||ba(!0)},[P,Ss,Cs,al]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Yi.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/ge,changedFramesPerSecond:z.sampleChangedFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/ge),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/ge),sampleMs:ge,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,My(z,M)}ms(D)},1e3);return()=>window.clearInterval(x)},[]);const xi=u.useCallback((x,M)=>{const D=performance.now(),B=Rs(x,M.deviceId);Xi.current.set(B,D),Ln.current.delete(B),x==="control"&&fi.current.delete(B);const z=Zn.current.get(B)||{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(M.byteLength||0)),String(M.frameMode||M.mode||M.codec||M.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(M.byteLength||0)<=PM&&(z.sampleTinyFrames+=1);const Ue=String(M.contentHash||"");Ue&&z.lastContentHash===Ue&&(z.sampleRepeatedFrames+=1),z.lastContentHash=Ue}const Ie=Number(M.agentSendGapMs||0);Ie>0&&Ie<1e3&&xw(z.sourceSendIntervalsMs,Ie),z.lastFrame=M,Ty(z,D,M.frameSeq),Zn.current.set(B,z)},[]);u.useEffect(()=>{const x=window.setInterval(()=>{const M=performance.now(),D={};for(const[B,z]of Zn.current.entries()){const ge=Math.max(1,M-z.sampleStartedAt);D[B]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/ge,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:vh(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((pe,Ie)=>pe+Ie,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:vh(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:ge,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,My(z,M)}bf(D)},1e3);return()=>window.clearInterval(x)},[]);const to=u.useCallback(x=>{xi("wall",x);const M=Ot.current.get(x.deviceId);if(!M)return;const D=Lj(ct,Fe.h264DecodeAcceleration);nh(M,x,()=>Ot.current.get(x.deviceId)!==M,sl,D.acceleration,D.latencyMode).catch(()=>{})},[sl,ct,xi,Fe.h264DecodeAcceleration]),xu=u.useCallback(x=>{xi("control",x);let M=wt.current.get(x.deviceId);M||(M=document.createElement("canvas"),M.setAttribute("aria-hidden","true"),wt.current.set(x.deviceId,M));const D=M,B=ve.current;nh(D,x,()=>wt.current.get(x.deviceId)!==D,Ko,ut.h264DecodeAcceleration,"interactive").catch(z=>{ve.current!==B||wt.current.get(x.deviceId)!==D||P!==x.deviceId||me(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[P,ut.h264DecodeAcceleration,Ko,xi]),fr=u.useCallback(x=>{const M=Os.current;M&&M!==x&&_c(M),Os.current=x,Ji.current=0,Yr.current=0,er.current=0,ql.current=0,Uo.current=0,Po.current=0},[]),qs=u.useCallback(()=>{const x=Os.current,M=Hs.current;if(!(!x||!M||x.width<=0||x.height<=0||Po.current!==M.layoutVersion))for(const D of M.tiles){const B=ya.current.get(D.deviceId);if(!B||D.width<=0||D.height<=0)continue;const z=Math.max(1,Math.round(D.width)),ge=Math.max(1,Math.round(D.height)),pe=$M,Ie=UM;(B.width!==pe||B.height!==Ie)&&(B.width=pe,B.height=Ie);const Ue=B.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,ge,0,0,pe,Ie)}catch{}}}},[]),il=u.useCallback((x,M)=>{if(M){ya.current.set(x,M),sn.current.delete(x),window.requestAnimationFrame(qs),window.requestAnimationFrame(()=>Cs(x,!0));return}const D=ya.current.get(x);eo(x,D),ya.current.delete(x),sn.current.has(x)||Jl(x)},[Jl,qs,Cs,eo]),no=u.useCallback((x,M)=>{er.current=performance.now(),Po.current=Number(x.layoutVersion||0),qs();const D=Hs.current?.tiles||[],B=D.length>0?Math.round(x.byteLength/D.length):x.byteLength;for(const z of D){const ge={...x,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:B};sl(ge,{...M,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:B}),xn.current===z.deviceId&&Cs(z.deviceId,!0)}},[sl,qs,Cs]),yu=u.useCallback(x=>{const M=performance.now();Ji.current<=0&&(Ji.current=M),Yr.current=M;const D=Os.current;if(!D)return;const B=Hs.current?.tiles||[],z=B.length>0?Math.round(x.byteLength/B.length):x.byteLength;for(const ge of B)xi("wall",{...x,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:z});nh(D,x,()=>Os.current!==D,no).catch(()=>{})},[no,xi]),yi=u.useMemo(()=>({fps:vi,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorSelections:Kt,onFrame:to}),[vi,to,_n,ct,Kt,Fe]),bi=u.useCallback(x=>{if(x.deviceId!==P||x.streamPurpose!=="control"||x.monitorIndex!==bs)return;const M=at.find(D=>D.deviceId===x.deviceId);!M?.sessionId||M.sessionId!==x.sessionId||($(x),W(D=>D==="connecting"?"active":D))},[at,P,bs]);u.useEffect(()=>{$(null)},[P,ie,wa,bs]);const Qo=u.useMemo(()=>({fps:rr,maxWidth:Ps.maxWidth,maxHeight:Ps.maxHeight,quality:ut.quality,mode:wa,frameMode:wa,streamPurpose:"control",forceRestart:ie!=="",forceRestartToken:ie,restartReason:ie?"control-session-start":"",monitorSelections:Kt,onFrame:xu,onStreamReady:bi}),[ie,ut.quality,xu,rr,wa,Ps.maxHeight,Ps.maxWidth,bi,Kt]),{frames:Xo,state:Pa,error:Zo,stats:js,restartLive:rl}=Rx(ta,Fe.autoStartLive&&ta.length>0,N,yi),{frame:mr,layout:wi,state:Jo,stats:bu,refreshInputs:ec}=xj(Gn,ct&&Fe.autoStartLive&&Gn.length>0,N,{fps:li.atlasOutputFps,width:1920,height:1080,tileWidth:_n.maxWidth,tileHeight:_n.maxHeight,captureDeviceIds:Gn,monitorSelections:Kt,onFrame:yu});u.useEffect(()=>{Hs.current=wi,wi&&window.requestAnimationFrame(qs)},[wi,qs]),u.useEffect(()=>{if(!ct||Jo!=="open"){Ji.current=0,Yr.current=0,er.current=0;return}const x=window.setInterval(()=>{const M=Os.current,D=performance.now();if(!M||document.visibilityState!=="visible"||D-ps.current<gh)return;const B=Yr.current,z=Ji.current;if(B<=0||z<=0||D-B>500)return;const ge=er.current||z,pe=D-ge;if(pe>=OM&&D-Uo.current>=BM){eh(M)&&(Uo.current=D,ql.current=D);return}pe>=IM&&D-ql.current>=HM&&tj(M)&&(ql.current=D)},250);return()=>window.clearInterval(x)},[Jo,ct]);const{frames:ll,state:ma,error:Gs,stats:ja,restartLive:ks,reconnectLive:ao}=Rx(Us,Us.length>0,N,Qo),Si=u.useMemo(()=>{const x=new Map(Xo);if(ct&&mr&&Gn.length>0){const M=new Map((wi?.tiles||[]).map(B=>[B.deviceId,B])),D=Math.max(1,M.size);for(const B of Gn){const z=M.get(B);z&&x.set(B,{...mr,deviceId:B,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(mr.byteLength/D)})}}for(const[M,D]of ll.entries())x.set(M,D);for(const M of tl){if(!Tt.current.has(M)||x.has(M))continue;const D=cn.current.get(M);D&&x.set(M,D)}return x},[mr,wi,ll,Gn,ct,Xo,tl,Jt]),hr=it&&Us.length>0?ma:Gn.length>0?Jo:Pa,ol=it&&Us.length>0?ja:Gn.length>0?bu:js;u.useCallback((x,M="browser-stale")=>{const D=rl(x,M),B=ks(x,M);return D||B},[ks,rl]),u.useEffect(()=>{ct&&Gn.length>0&&!it&&ec()},[Gn.length,ct,ec,it]);const is=u.useCallback((x,M,D)=>{const B=M==="control"?wt.current.get(x)||null:Ot.current.get(x)||null;if(!B||!eh(B))return!1;const z=performance.now();return $o.current.set(Rs(M,x),z),!0},[]),cl=u.useCallback(x=>{if(wa!=="mode3-h264-hw"||!P||I)return!1;const M=at.find(Ie=>Ie.deviceId===P)||qn,D=String(M?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(D))return!1;const B="mode5-lzo-delta",z=Rs("control",P),ge=performance.now();Fa.current.set(z,ge),Xi.current.delete(z),di.current.delete(z),Zi.current.delete(z),fi.current.delete(z),Ln.current.delete(z),eh(wt.current.get(P)||null),ao([P],"control-decode-fallback"),Q(B),K(`control-${B}-fallback-${P}-${Date.now()}`),be(!1),ba(!1);const pe=x==="no first frame"||x==="control-first-frame-timeout";return me(Ie=>Ie||(pe?`Control frame transport timeout; retrying Control with Mode 5 (${x})`:`H.264 decode failed; retrying Control with Mode 5 (${x})`)),W("connecting"),!0},[at,qn,P,I,wa,ao]);u.useEffect(()=>{const x=it?qn:null;if(x){Qi.current={deviceId:x.deviceId,monitorIndex:bs,frameMode:wa,startedAtEpochMs:Date.now()},ba(P===x.deviceId&&ue||Ze.has(x.deviceId));return}Qi.current=null,ba(!1)},[qn?.sessionId,G,P,ue,wa,bs,it,Ze]);const Vs=u.useCallback(async x=>{const M=C.find(pe=>pe.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=za(Kt[x],M?va(M):1),z=D?{fps:li.scalableAtlasInputFps,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:B}:{fps:ct&&!D?vi:Tn,maxWidth:_n.maxWidth,maxHeight:_n.maxHeight,quality:Fe.quality,mode:ct?"mode3-h264-hw":Fe.frameMode,frameMode:ct?"mode3-h264-hw":Fe.frameMode,streamPurpose:"wall",monitorIndex:B},ge=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/start`,{method:"POST",body:JSON.stringify(z)},N);if(ge?.ok===!1)throw new Error(ge.error||"wall-stream-start-failed");return ge},[Tn,C,ss,vi,_n.maxHeight,_n.maxWidth,N,ct,Kt,Fe.frameMode,Fe.quality]),As=u.useCallback(async x=>{const M=C.find(z=>z.deviceId===x),D=zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(M?.platform)})==="atlas",B=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:D?"atlas":"wall",reason:"control-active"})},N);if(B?.ok===!1)throw new Error(B.error||"wall-stream-stop-failed");return B},[C,ss,N,ct]),pr=u.useCallback(async(x,M="control-session-stop")=>{const D=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:M})},N);if(D?.ok===!1)throw new Error(D.error||"control-stream-stop-failed");return D},[N]),jn=u.useCallback(x=>{const M=wt.current.get(x);M&&(_c(M),wt.current.delete(x));const D=Vt.current.get(x);D&&_c(D),cn.current.delete(x),Tt.current.delete(x),ts.current.delete(x)},[]);u.useEffect(()=>{const x=G&&at.find(z=>z.deviceId===G)||null;if(!it||!Wt||!x){hs.current&&(++Qt.current,hs.current="");return}if(P===x.deviceId&&(U==="active"||U==="warm"||U==="connecting")){W(z=>z==="warm"?"active":z);return}if(hs.current===x.deviceId)return;const M=++Qt.current,D=P;hs.current=x.deviceId,(async()=>{if(D){if(W("stopping"),await pr(D,"control-session-switch").catch(()=>{}),M!==Qt.current)return;const pe=xn.current;if(pe&&pe!==x.deviceId)try{await Vs(pe)}catch(Ie){J(Ie instanceof Error?Ie.message:String(Ie))}finally{xn.current===pe&&(xn.current="",Ae(""))}if(M!==Qt.current)return;jn(D)}if(M!==Qt.current)return;if($y(x)){try{await As(x.deviceId)}catch(pe){M===Qt.current&&(hs.current="",W("error"),J(pe instanceof Error?pe.message:String(pe)));return}if(M!==Qt.current){await Vs(x.deviceId).catch(()=>{});return}xn.current=x.deviceId,Ae(x.deviceId),Tt.current.add(x.deviceId)}const z=Rs("control",x.deviceId),ge=`control-session-${M}-${x.deviceId}`;Fa.current.set(z,performance.now()),Xi.current.delete(z),di.current.delete(z),Ln.current.delete(z),fi.current.delete(z),Q(""),me(""),K(ge),ye(x.deviceId),be(!1),W("connecting"),Qt.current===M&&hs.current===x.deviceId&&(hs.current="")})()},[at,G,P,U,Wt,jn,J,it,Vs,pr,As]),u.useEffect(()=>{if(!P||at.some(D=>D.deviceId===P))return;const x=P,M=++Qt.current;W("stopping"),pr(x,"control-device-disconnected").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},[at,P,jn,pr]);const so=$y(at.find(x=>x.deviceId===P));u.useEffect(()=>{if(ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null),!P||U==="idle"||U==="stopping"||U==="error"||it||ze==="wall"){P&&!it&&ze==="wall"&&W(D=>D==="warm"||D==="active"?"active":D);return}W(D=>D==="idle"||D==="stopping"?D:"warm");const x=P,M=++Qt.current;return ns.current=window.setTimeout(()=>{ns.current=null,W("stopping"),pr(x,"control-session-warm-timeout").catch(()=>{}).finally(()=>{M===Qt.current&&(jn(x),be(!1),K(""),Q(""),me(""),ye(D=>D===x?"":D),W("idle"))})},FM),()=>{ns.current!==null&&(window.clearTimeout(ns.current),ns.current=null)}},[ze,P,U,jn,it,pr]),u.useEffect(()=>()=>{ns.current!==null&&window.clearTimeout(ns.current)},[]),u.useEffect(()=>{const M=P&&(so&&(U==="connecting"||U==="active"||U==="warm"||U==="stopping")||ue&&(U==="active"||U==="warm"))?P:"";if(un.current=M,dn.current)return;const D=async()=>{for(;;){const z=un.current,ge=xn.current;if(ge===z)return;if(ge){try{await Vs(ge)}catch(pe){J(pe instanceof Error?pe.message:String(pe))}finally{xn.current===ge&&(xn.current="",Ae(""))}continue}if(!z)return;try{await As(z)}catch(pe){un.current=xn.current,J(pe instanceof Error?pe.message:String(pe));return}xn.current=z,Ae(z),Tt.current.add(z)}};let B;B=D().finally(()=>{dn.current===B&&(dn.current=null),xn.current!==un.current&&ot(z=>z+1)}),dn.current=B},[P,ue,U,so,ct,J,Vs,As,qe]);const Vn=P&&at.find(x=>x.deviceId===P)||null,ul=!!(it&&Se&&U==="active"&&Vn?.sessionId&&X?.deviceId===Vn.deviceId&&X.sessionId===Vn.sessionId&&X.streamPurpose==="control"&&X.commandId&&X.captureGeneration>0&&X.monitorIndex===bs),{state:gr,sendInput:Ws,stats:ka,error:tc}=yj(ws&&ul,N),Ci=u.useCallback((x,M)=>!ul||!Vn||!X||x!==Vn.deviceId?!1:Ws(x,{...M,controlSessionId:Vn.sessionId,controlCommandId:X.commandId,captureGeneration:X.captureGeneration}),[ul,Vn,X,Ws]),vr=ul&&gr==="open",{state:Aa,lastFrame:ji,stats:fn,error:dl}=Mj(Le?.deviceId||"",pu&&le,N),Ys=u.useRef(new Map);u.useEffect(()=>{const x=[["hub",j],["registry",l],["license",q],["wall-stream",Zo],["control-stream",Gs],["control-decode",de],["remote-input",tc],["remote-audio",dl]];for(const[M,D]of x){const B=String(D||"").trim();if(M==="hub"&&De?.requiresHubRestart&&De.stage==="updating"){Ys.current.delete(M);continue}if(!B){Ys.current.delete(M);continue}Ys.current.get(M)!==B&&(Ys.current.set(M,B),J(B))}},[dl,de,Gs,j,tc,q,l,J,Zo,De]),u.useEffect(()=>{if(!it||!Se||!ws||!vr||!Le)return;const x=(B,z)=>{const ge=B.target,pe=ge?.tagName?.toLowerCase();ge?.isContentEditable||pe==="input"||pe==="textarea"||pe==="select"||(B.preventDefault(),B.stopPropagation(),Ci(Le.deviceId,{type:z,monitorIndex:za(Kt[Le.deviceId],va(Le)),key:B.key,code:B.code,keyCode:B.keyCode||B.which||0,location:B.location,text:B.key.length===1?B.key:"",repeat:z==="keydown"?B.repeat:!1,shiftKey:B.shiftKey,ctrlKey:B.ctrlKey,altKey:B.altKey,metaKey:B.metaKey}))},M=B=>x(B,"keydown"),D=B=>x(B,"keyup");return window.addEventListener("keydown",M),window.addEventListener("keyup",D),()=>{window.removeEventListener("keydown",M),window.removeEventListener("keyup",D)}},[ws,vr,Se,Kt,Le,Ci,it]),u.useEffect(()=>{const x=()=>{document.visibilityState==="visible"&&(ps.current=performance.now())};return document.addEventListener("visibilitychange",x),window.addEventListener("pageshow",x),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pageshow",x)}},[]),u.useEffect(()=>{if(!P||U!=="connecting"&&U!=="active"&&U!=="warm"||ma!=="open")return;const x=P,M=Rs("control",x),D=window.setInterval(()=>{const B=performance.now();if(document.visibilityState!=="visible"||B-ps.current<gh)return;const z=Xi.current.get(M)||0,ge=di.current.get(M)||0,pe=Zi.current.get(M)||0,Ie=Fa.current.get(M)||B;Fa.current.has(M)||Fa.current.set(M,Ie);const Ue=z<=0,Ke=Ue?B-Ie>KM:B-z>_y,en=z>0&&(ge<=0||B-ge>_y);if(!Ke&&en){const Ar=$o.current.get(M)||0;B-Ar>=zy&&is(x,"control","decoder-paint-stale");return}if(!Ke)return;const Dt=fi.current.get(M)||0;if(Dt>0){if(B-Dt<XM)return;fi.current.delete(M)}const tn=Ln.current.get(M)||0;if(tn>=ZM){if(cl(Ue?"no first frame":"stale stream"))return;be(!1),ba(!1),W("error");return}if(B-pe<Iy(QM,tn))return;ks([x],Ue?"control-first-frame-timeout":"control-receive-stale")&&(Zi.current.set(M,B),fi.current.set(M,B),Fa.current.set(M,B),Ln.current.set(M,tn+1))},650);return()=>window.clearInterval(D)},[ma,P,U,cl,is,ks]),u.useEffect(()=>{!de||wa!=="mode3-h264-hw"||cl(de)||(be(!1),ba(!1),W("error"))},[de,wa,cl]),u.useEffect(()=>{!it||!P||!Gs||W(x=>x==="error"?x:"error")},[Gs,P,it]),u.useEffect(()=>{if(Pa!=="open"||!Fe.autoStartLive||ta.length===0)return;const x=window.setInterval(()=>{const M=performance.now();if(document.visibilityState!=="visible"||M-ps.current<gh)return;const D=1e3/Math.max(1,vi||Fe.fps||1),B=Math.max(JM,Math.ceil(D*4)),z=[];for(const ge of ta){if(z.length>=nT)break;const pe=Rs("wall",ge),Ie=Xi.current.get(pe)||0;if(Ie<=0)continue;const Ue=Zi.current.get(pe)||0,Ke=di.current.get(pe)||0,en=M-Ie>B,Dt=Ke<=0||M-Ke>B;if(!en&&Dt){const Ua=$o.current.get(pe)||0;M-Ua>=zy&&is(ge,"wall","decoder-paint-stale");continue}if(!en)continue;const tn=Ln.current.get(pe)||0;M-Ue>=Iy(eT,tn)&&z.push(ge)}if(z.length>0&&rl(z,"wall-frame-stale"))for(const ge of z){const pe=Rs("wall",ge);Zi.current.set(pe,M),Ln.current.set(pe,(Ln.current.get(pe)||0)+1)}},tT);return()=>window.clearInterval(x)},[vi,ta,is,rl,Fe.autoStartLive,Fe.fps,Pa]),u.useEffect(()=>{da(Fe.fps),xs.current=Date.now(),Fs.current=0},[Fe.fps,Fe.frameMode,Fe.adaptiveLoadShedding]),u.useEffect(()=>{WC({h264DecodeAcceleration:Fe.h264DecodeAcceleration})},[Fe.h264DecodeAcceleration]),u.useEffect(()=>{if(!Wt||it||Xe==="list"||!Fe.visibleOnlyLive){es([]);return}const x=Go.current;if(!x||typeof IntersectionObserver>"u"){es(Xl);return}const M=Array.from(x.querySelectorAll("[data-live-device-id]"));if(M.length===0){es([]);return}const D=new Map,B=()=>{const ge=wh(M.map(pe=>String(pe.dataset.liveDeviceId||"")).filter(pe=>(D.get(pe)||0)>0));es(pe=>bh(pe,ge)?pe:ge)},z=new IntersectionObserver(ge=>{for(const pe of ge){const Ie=String(pe.target.dataset.liveDeviceId||"");Ie&&D.set(Ie,pe.isIntersecting?pe.intersectionRatio||.01:0)}B()},{root:null,rootMargin:ca.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return M.forEach(ge=>z.observe(ge)),B(),()=>z.disconnect()},[Xl,Wt,it,pi,Fe.visibleOnlyLive,Xe]),u.useEffect(()=>{if(!Fe.adaptiveLoadShedding||!Fe.autoStartLive||ta.length===0)return;const x=Fe.fps;if(ta.length<=ca.preserveConfiguredFpsDeviceCount){Tn!==x&&(da(x),xs.current=Date.now(),Fs.current=0);return}if(Pa!=="open"||js.sampleMs<500)return;const M=Date.now(),D=ta.length*Tn,B=js.framesPerSecond,z=js.bytesPerSecond,ge=Math.max(0,...ta.map(en=>$l[Rs("wall",en)]?.maxIntervalMs||0)),pe=Math.max(0,...ta.map(en=>Ki[Rs("wall",en)]?.maxIntervalMs||0)),Ie=D>8&&B>0&&B<D*.72;if(B>ca.maxWallFramesPerSecond||z>ca.maxWallBytesPerSecond||ge>ca.maxFrameGapMs||pe>ca.maxFrameGapMs||Ie){Fs.current=0;const en=ca.minFps;if(M-xs.current>=ca.downshiftCooldownMs&&Tn>en){const Dt=Math.max(en,yT(Tn,en));Dt<Tn&&(da(Dt),xs.current=M)}return}const Ke=B<ca.maxWallFramesPerSecond*ca.lowLoadFrameRatio&&z<ca.maxWallBytesPerSecond*ca.lowLoadByteRatio;if(!Ke||Tn>=x){Ke||(Fs.current=0);return}if(!Fs.current){Fs.current=M;return}if(M-Fs.current>=ca.recoveryCooldownMs){const en=Math.min(x,bT(Tn,x));en>Tn&&(da(en),xs.current=M,Fs.current=0)}},[Tn,ta.length,ta,Ki,$l,Pa,js.bytesPerSecond,js.framesPerSecond,js.lastUpdatedAt,js.sampleMs,Fe.adaptiveLoadShedding,Fe.autoStartLive,Fe.frameMode,Fe.fps]),u.useEffect(()=>{const x=new URLSearchParams(window.location.search).get("checkout");if(x==="success"){J("Checkout returned. Waiting for Dodo confirmation."),O();const M=window.setInterval(()=>{O()},4e3),D=window.setTimeout(()=>{window.clearInterval(M)},45e3);return()=>{window.clearInterval(M),window.clearTimeout(D)}}x==="cancelled"&&J("Checkout cancelled.")},[O]),u.useEffect(()=>{!Wt&&Se&&Oe(!1),!Wt&&le&&Z(!1)},[le,Se,Wt]),u.useEffect(()=>{const x=Le?.deviceId||"",M=He.current;if(He.current=x,!M||M===x)return;const D=++se.current,B=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";x&&le&&_e.current.set(x,B);let z=!0;return(async()=>{try{const pe=_e.current.get(M);if(_e.current.delete(M),await Ge(`/api/remote/devices/${encodeURIComponent(M)}/audio/stop`,{method:"POST",body:JSON.stringify(pe?{streamId:pe}:{})},N),!z||D!==se.current||!le||!x||!Wt||!el)return;const Ie=await Ge(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:B,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(Ie.ok===!1)throw new Error(Ie.error||"Remote audio start failed.")}catch(pe){z&&(_e.current.delete(x),Z(!1),J(pe instanceof Error?pe.message:String(pe)))}})(),()=>{z=!1}},[le,Wt,N,el,Le?.deviceId]),u.useEffect(()=>{const x=at.map(B=>B.deviceId),M=new Set(x),D=new Map(at.map(B=>[B.deviceId,B]));_(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z}),ae(B=>B&&M.has(B)?B:""),te(B=>B&&M.has(B)?B:""),H(B=>{let z=!1;const ge={};for(const[pe,Ie]of Object.entries(B)){const Ue=D.get(pe);if(!Ue){ge[pe]=Ie;continue}const Ke=za(Ie,Ue?va(Ue):1);ge[pe]=Ke,Ke!==Ie&&(z=!0)}return z?ge:B}),Xr(B=>{const z=B.filter(ge=>M.has(ge));return bh(B,z)?B:z})},[at,Kl]),u.useEffect(()=>{qo([]),Vl(!1)},[Cs]),u.useEffect(()=>{!ir||mi!=="selected"||Jn.length>0||fa.length===0||Xr(fa.map(x=>x.deviceId))},[fa,Jn.length,mi,ir]),u.useEffect(()=>{try{localStorage.setItem(dw,Xn)}catch{}},[Xn]),u.useEffect(()=>{hT(Fe)},[Fe]),u.useEffect(()=>{gT(ut)},[ut]),u.useEffect(()=>{fT(Kt)},[Kt]);const aa=u.useCallback(async()=>{const x=new Set(p);x.add(Cn);try{const ge=await Ge("/api/remote/status",void 0,Cn);xx({endpoint:ge.agentEndpoint,endpoint_candidates:[...ge.agentEndpointCandidates||[],...ge.hostTargetEndpointCandidates||[]]}).forEach(pe=>x.add(pe))}catch{}const M=[...x].sort((ge,pe)=>{const Ie=Ue=>{const Ke=qc(Ue);return Ke==="local"?0:Ke==="loopback"?1:2};return Ie(ge)-Ie(pe)||ge.localeCompare(pe)});let D=!1,B="",z=!1;try{for(const ge of M){const pe=qc(ge);try{if(await Ge("/api/health",void 0,ge),pe==="local")return g(!0),To(!0),ge;pe==="loopback"&&(D=!0,B=ge)}catch{pe==="local"&&(z=!0)}}return D?(z&&J("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),g(!0),To(!0),B||Cn):(g(!1),To(!1),"")}catch{return g(!1),To(!1),""}},[p]),zn=async()=>{if(Ne("auth"),an(!1),await aa(),window.liveDesk?.auth?.signInWithGoogle){const D=await window.liveDesk.auth.signInWithGoogle();D?.ok===!1&&(J(D.error||"LiveDesk could not open the system browser for Google sign-in."),Ne(""));return}const{data:x,error:M}=await mt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});M&&(J(M.message),Ne(""))},Ks=async()=>{Ne("auth"),an(!1),await mt.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?J("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"},Cn).catch(()=>{}),Ne("")};u.useEffect(()=>{if(!$t)return;const x=D=>{D.target instanceof Element&&(D.target.closest(".account-popover, .rail-account")||an(!1))},M=D=>{D.key==="Escape"&&an(!1)};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",M),()=>{window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",M)}},[$t]);const Na=u.useCallback(async(x={})=>{const M=x.silent===!0,D=x.takeover===!0,B=x.requestLocalAccess===!0;if(!n?.user){M||J("Sign in before publishing this host.","error");return}if(!vs.current){vs.current=!0,M||(Ne("host"),Re("Hub · 1/4 · Checking the local runtime…"));try{const ge=(B?await aa():"")||N||Cn;if(!(b||await Ge("/api/remote/status",void 0,ge)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");M||Re("Hub · 2/4 · Sending the signed-in session to the Hub…");const Ie=await Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},ge);if(!Ie.ok||!Ie.authenticated)throw new Error(Ie.error||"hub-session-sync-failed");M||Re("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})},ge);if(!Ue.ok)throw new Error(Ue.error||"host-target-failed");if(!M){Re("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Ke=await Ge("/api/hub/status",void 0,ge);if(!Ke.hostTargetActive)throw new Error(Ke.hostTargetLease?.lastError||"host-target-not-active-after-sync");const en=Ke.hostTargetEndpoint||Ke.agentEndpoint||"endpoint ready",Dt=Number(Ke.connectedDeviceCount||0),tn=Dt>0?`${Dt} client${Dt===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";J(`Hub ready · ${en} · lease auto-renewal active. ${tn}`,"success"),(B||w)&&(g(!0),To(!0)),A()}c()}catch(z){if(!M){const ge=z instanceof Error?z.message:String(z);ge.includes("local network access")&&(g(!1),To(!1)),J(`Hub setup failed · ${ge}`,"error")}}finally{vs.current=!1,M||Ne("")}}},[N,w,A,c,aa,n,J,Re,b]),sa=u.useCallback((x=!0)=>{fe!=="host"&&(et(!1),x&&window.requestAnimationFrame(()=>ke.current?.focus()))},[fe]),Ns=u.useCallback(()=>{fe!=="host"&&(ke.current=document.activeElement instanceof HTMLElement?document.activeElement:null,an(!1),et(!0))},[fe]),wu=u.useCallback(()=>{et(!1),Na({takeover:!0,requestLocalAccess:!0})},[Na]);u.useEffect(()=>{if(!$e)return;const x=window.requestAnimationFrame(()=>Mt.current?.focus()),M=B=>{B.target instanceof Element&&B.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||sa(!1)},D=B=>{B.key==="Escape"&&sa()};return window.addEventListener("pointerdown",M),window.addEventListener("keydown",D),()=>{window.cancelAnimationFrame(x),window.removeEventListener("pointerdown",M),window.removeEventListener("keydown",D)}},[sa,$e]);const nc=u.useCallback(async()=>{if(!(!b?.update?.canApply||fe==="update")){Ne("update");try{const x=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||Cn);if(!x.ok)throw new Error(x.error||"LiveDesk update could not be started.");const M=[...new Set((x.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],D=!!(x.managerUpdateAvailable||x.clientPackageUpdateAvailable),B=x.state==="hub-restart-requested"?Date.now():void 0;(M.length>0||D)&&st({operationId:String(x.operationId||`wall-update-${Date.now()}`),targetIds:M,stage:x.state==="clients-updated"?"updated":"updating",requiresHubRestart:D,initialHostInstanceId:String(b.hostInstanceId||""),targetManagerVersion:String(x.latestVersion||b.update?.latestVersion||""),targetClientVersion:String(x.latestClientVersion||b.update?.latestClientVersion||""),restartRequestedAt:B,restartDeadlineAt:B?B+Hd:void 0}),Re(x.state==="hub-restart-requested"?Od:Ay),A()}catch(x){J(x instanceof Error?x.message:String(x),"error")}finally{Ne("")}}},[fe,N,A,J,Re,b]);u.useEffect(()=>{const x=De,M=b?.update;if(!x||x.stage!=="updating"||!M)return;const D=M.restartResult?.operationId===x.operationId?M.restartResult:null;if(D?.outcome==="restored"){const Ue=D.error||`The requested Hub ${D.targetVersion||x.targetManagerVersion||"version"} failed verification.`;st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"restored",error:Ue}:Ke),J(`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.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(`LiveDesk Hub update failed. ${Ue}`,"error");return}if(M.operationId===x.operationId&&M.state==="failed"){const Ue=M.error||"LiveDesk update failed before the Hub replacement completed.";st(Ke=>Ke?.operationId===x.operationId?{...Ke,stage:"failed",error:Ue}:Ke),J(Ue,"error");return}if(M.operationId===x.operationId){if(M.state==="hub-restart-requested"&&!x.restartDeadlineAt){const Ue=Date.now();st(Ke=>Ke?.operationId===x.operationId?{...Ke,restartRequestedAt:Ue,restartDeadlineAt:Ue+Hd}:Ke),Re(Od)}!x.requiresHubRestart&&M.state==="clients-updated"&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J("LiveDesk clients updated and reconnected successfully.","success"));return}if(!x.requiresHubRestart)return;const B=b.started===!0&&(!x.initialHostInstanceId||b.hostInstanceId&&b.hostInstanceId!==x.initialHostInstanceId),z=!!M.checkedAt,ge=Ny(M.currentVersion,x.targetManagerVersion),pe=!x.targetClientVersion||Ny(M.currentClientVersion,x.targetClientVersion),Ie=z&&M.state==="idle"&&M.updateAvailable===!1&&ge&&pe;B&&Ie&&(st(Ue=>Ue?.operationId===x.operationId?{...Ue,stage:"updated"}:Ue),J(`LiveDesk Hub ${M.currentVersion||D?.appVersion||x.targetManagerVersion} restarted and passed version verification.`,"success"))},[J,Re,b,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||x.restartDeadlineAt)return;const M=()=>{const B=Date.now();st(z=>z?.operationId===x.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:B,restartDeadlineAt:B+Hd}:z),Re(Od)};if(b?.update?.state==="hub-restart-requested"){M();return}if(!j)return;const D=window.setTimeout(M,qM);return()=>window.clearTimeout(D)},[j,Re,b?.update?.state,De]),u.useEffect(()=>{const x=De;if(!x||x.stage!=="updating"||!x.requiresHubRestart||!x.restartDeadlineAt)return;const M=Math.max(0,x.restartDeadlineAt-Date.now()),D=x.operationId,B=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${x.targetManagerVersion||"the requested version"} within ${Math.round(Hd/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;st(ge=>ge?.operationId===D&&ge.stage==="updating"?{...ge,stage:"failed",error:z}:ge),J(z,"error")},M);return()=>window.clearTimeout(B)},[J,De]),u.useEffect(()=>{if(!De||De.stage!=="updated")return;const x=De.operationId,M=window.setTimeout(()=>{st(D=>D?.operationId===x?null:D)},8e3);return()=>window.clearTimeout(M)},[De]),u.useEffect(()=>{if(vt!==Ay&&vt!==Od)return;const x=b?.update;if(String(x?.state||"")==="failed"){J(x?.error||"LiveDesk update failed.","error");return}De?.stage==="updated"&&J("")},[vt,J,b?.update?.error,b?.update?.state,De?.stage]);const ac=u.useCallback(async()=>{if(!fe){Ne("pin");try{const M=await Ge("/api/remote/pairing-pin",{method:"POST"},N||Cn);if(!M.ok)throw new Error(M.error||"pin-rotation-failed");await A(),J("New PIN published.")}catch(x){J(x instanceof Error?x.message:String(x))}finally{Ne("")}}},[fe,N,A]),io=u.useCallback(x=>{x&&(ae(x),_(M=>M.includes(x)?M:[...M,x]))},[]),yn=u.useCallback(x=>{if(!x)return;const M=ys.has(x);ae(D=>M?D===x?"":D:x),_(D=>M?D.filter(B=>B!==x):D.includes(x)?D:[...D,x])},[ys]),Et=u.useCallback(()=>{_([]),ae("")},[Ss]),xt=u.useCallback(()=>{_(at.map(x=>x.deviceId)),ae("")},[at]),rs=u.useCallback((x,M)=>{const D=at.find(z=>z.deviceId===x);if(!D)return;const B=va(D);B<=1||(H(z=>{const pe=(za(z[x],B)+M+B)%B;return{...z,[x]:pe}}),it&&(ba(!1),te(x)))},[at,it]);u.useEffect(()=>{const x=M=>{if(it&&Se&&ws)return;const D=M.target,B=D?.tagName?.toLowerCase();D?.isContentEditable||B==="input"||B==="textarea"||B==="select"||((M.ctrlKey||M.metaKey)&&M.key.toLowerCase()==="a"&&(M.preventDefault(),xt()),M.key==="Escape"&&Et())};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[ws,Et,Se,xt,it]);const Ma=(x,M)=>{const D=at.find(z=>z.deviceId===x),B=za(M,D?va(D):1);H(z=>({...z,[x]:B})),it?(ba(!1),te(x)):io(x)},ki=async x=>{if(ba(!1),te(x),je("control"),!gi.has(x)){Oe(!1),J(cr);return}const M=at.find(B=>B.deviceId===x);if(qi(M?.platform)&&(M?.capabilities?.controlPermission===!1||M?.capabilities?.accessibilityPermission===!1)){Oe(!1),J("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Oe(!0),J(`Opening remote control${M?` for ${Ka(M)}`:""}.`,"success")},Qs=async()=>{if(!Le){J("Select a workstation before playing audio.");return}if(!Wt){J(cr);return}if(!el){J("Selected workstation does not report remote audio support yet.");return}if(Te)return;const x=!le,M=x?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:_e.current.get(Le.deviceId);x&&M?_e.current.set(Le.deviceId,M):x||_e.current.delete(Le.deviceId),Be("audio"),Z(x);try{await Ge(`/api/remote/devices/${encodeURIComponent(Le.deviceId)}/audio/${x?"start":"stop"}`,{method:"POST",body:JSON.stringify({...M?{streamId:M}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),J(`${x?"Audio started":"Audio stopped"} for ${Ka(Le)}.`,"success")}catch(D){x&&_e.current.delete(Le.deviceId),Z(!1),J(D instanceof Error?D.message:String(D),"error")}finally{Be("")}},Su=x=>{const M=x instanceof Error?x.message:String(x);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(M)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(M)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(M)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(M)?"The workstation disconnected before the action could be sent.":M},fl=async x=>{if(!Le||Te)return;const M=Le,B={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[x];if(!(x!=="lock"&&!window.confirm(`${B} ${Ka(M)}? Unsaved work on that computer may be lost.`))){Be(x),J(`Sending ${B.toLowerCase()} request to ${Ka(M)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(M.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:x})},N);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");J(`${B} request sent to ${Ka(M)}.`,"success"),A()}catch(z){J(Su(z),"error")}finally{Be("")}}},xr=()=>{Le&&(rt({id:Date.now(),deviceId:Le.deviceId,instruction:"Run command "}),Oe(!1),je("agents"),J(`Command runner opened for ${Ka(Le)}.`))},Xs=async(x,M,D="files")=>{const B=x.filter(Ie=>Ie.file.size>=0);if(B.length===0)return{files:0,bytes:0};if(!Wt)throw new Error(cr);if(M.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),ge=B.reduce((Ie,Ue)=>Ie+Ue.file.size,0);let pe=0;as({id:z,status:"reading",progress:1,message:`Preparing ${B.length} ${D}`});try{for(let Ie=0;Ie<B.length;Ie+=1){const Ue=B[Ie],Ke=Ue.file,en=Math.max(1,Math.ceil(Ke.size/hh));for(let Dt=0;Dt<en;Dt+=1){const tn=Dt*hh,Ua=Math.min(Ke.size,tn+hh),Ar=Ke.size===0?new ArrayBuffer(0):await Ke.slice(tn,Ua).arrayBuffer(),Tu=Dt===en-1;as({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(pe/Math.max(1,ge)*96))),message:`${Ie+1}/${B.length} ${Ue.relativePath}`});const qa=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:M,remoteDirectory:Xn.trim(),name:Ke.name,relativePath:Ue.relativePath,size:Ke.size,type:Ke.type,lastModified:Ke.lastModified,offset:tn,totalBytes:Ke.size,final:Tu,dataBase64:wT(Ar)})},N);if(!qa.ok||qa.queued!==M.length)throw new Error(qa.error||`file-chunk-not-queued-${qa.queued}/${M.length}`);pe+=Ar.byteLength,await new Promise(pa=>window.setTimeout(pa,0))}}return as({id:z,status:"queued",progress:100,message:`Sent ${B.length} file${B.length===1?"":"s"} to ${M.length} workstation${M.length===1?"":"s"}`}),window.setTimeout(()=>{as(Ie=>Ie?.id===z&&Ie.status==="queued"?null:Ie)},4500),{files:B.length,bytes:ge}}catch(Ie){throw as({id:z,status:"failed",progress:100,message:Ie instanceof Error?Ie.message:String(Ie)}),Ie}},ro=async x=>{const M=fa.length>0?fa.map(D=>D.deviceId):Le?[Le.deviceId]:[];try{await Xs(Hy(x),M)}catch(D){J(D instanceof Error?D.message:String(D))}},yr=async x=>{try{await Xs(Hy(x),Sf)}catch(M){J(M instanceof Error?M.message:String(M))}};u.useEffect(()=>{ea.current=!1},[]);const sc=x=>{x.preventDefault(),x.stopPropagation(),Bs(!1),ro(x.dataTransfer.files)},ls=async(x="ltd")=>{if(!n){J("Sign in with Google before checkout.");return}if(T&&x===Ht){J("LiveDesk license is already active.");return}if(T&&Ht==="pro"){J("LiveDesk Pro is already active.");return}Ne("checkout");try{const{data:M,error:D}=await mt.functions.invoke("dodo-checkout",{body:{plan:x}});if(D)throw D;if(!M?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(M.checkout_url)}catch(M){J(M instanceof Error?M.message:String(M)),Ne("")}},In=aT(),$a=sT(),Ms=at.length,ml=vu.filter(x=>Si.has(x)).length,hl=hr==="open"&&ol.sampleMs>0?`${ol.framesPerSecond.toFixed(1)} fps`:hr,Me=Le?it?ll.get(Le.deviceId):Si.get(Le.deviceId):void 0,Ai=Le?za(Kt[Le.deviceId],va(Le)):0,Zs=Le?oT(Le):[],En=typeof Me?.monitorIndex=="number"?za(Me.monitorIndex,Math.max(1,Me.monitorCount||1)):Ai,lo=(Me&&En===Ai?Cw(Me):null)||(Le?Sw(Le,Ai):null);lo&&`${lo.width}${lo.height}`;const oo=Le?Rs(it?"control":"wall",Le.deviceId):"",Rn=oo?$l[oo]:void 0,ha=oo?Ki[oo]:void 0,Qe=ha?.lastInfo,rc=Rn&&Rn.sampleMs>0?`${Rn.framesPerSecond.toFixed(1)} fps`:"waiting";Rn&&`${Rn.totalFrames}${rc}`,ha&&ha.sampleMs>0&&`${ha.framesPerSecond.toFixed(1)}`,ha&&ha.sampleMs>0&&`${ha.changedFramesPerSecond.toFixed(1)}`,Qe&&(`${Qe.frameSeq}${Qe.decoderLabel}${Qe.queueSize}${Qe.renderQueueSize}${Qe.droppedForLatency}${Qe.decoderFlushCount}${Qe.decoderTimestampFallbacks}${Qe.decoderInputCount}${Qe.decoderOutputCount}`,Qe.visualChanged),Qe&&`${Math.round(Qe.queuedForMs)}${Math.round(Qe.decodedForMs)}${Math.round(Qe.scheduledForMs)}${Qe.drawMs.toFixed(1)}`,Qe?.targetPaintIntervalMs&&`${Qe.targetPaintIntervalMs.toFixed(1)}${(1e3/Qe.targetPaintIntervalMs).toFixed(1)}`,ha&&`${ha.decoderInputFps.toFixed(1)}${ha.decoderOutputFps.toFixed(1)}`,Qe?.canvasPresentation,Qe&&`${Qe.interactiveBufferWaitCount}${Math.round(Qe.interactiveBufferWaitMs)}${Qe.interactiveQueueDrainCount}`,Rn&&(Me?.frameMode==="mode5-lzo-delta"?`${Fc(Rn.averageFrameBytes)}${Me.deltaVisualTileCount||0}${Me.deltaRefreshTileCount||0}${Me.deltaTotalTiles||0}`:`${Fc(Rn.averageFrameBytes)}${Math.round(Rn.tinyFrameRatio*100)}${Math.round(Rn.repeatedFrameRatio*100)}`),Rn&&Rn.sourceSendSampleCount>0&&`${Rn.sourceSendAverageMs.toFixed(1)}${Rn.sourceSendP95Ms.toFixed(1)}`,Ey(Rn),Ey(ha),Rn&&ha&&`${Ry(Rn)}${Ry(ha)}`,Me?Me.frameMode||Me.mode||Me.codec||Me.mimeType:it?ut.frameMode:Fe.frameMode,it?ut.frameMode:Fe.frameMode,Me?`${Me.width}${Me.height}${Fc(Me.byteLength)}`:it?`${Ps.maxWidth}${Ps.maxHeight}`:`${Fe.maxWidth}${Fe.maxHeight}`,Me&&`${Me.isKeyFrame?"key":String(Me.chunkType||"delta")}`,Me&&Me.monitorCount&&((Me.monitorIndex??0)+1,`${Me.monitorCount}`),Me&&[`src ${Math.round(Me.sourceGapMs||0)}ms`,`gap ${Math.round(Me.agentSendGapMs||0)}ms`,`tx ${Math.round(Me.agentSendDurationMs||0)}ms`,`pace ${Math.round(Me.agentPaceMs||0)}ms`,`queue ${Math.round(Me.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Me.agentFrameAgeMs||0)}ms`,Me.browserReceivedEpochMs&&Me.receivedAt?`hub ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Date.parse(Me.receivedAt)))}ms`:"",Me.browserReceivedEpochMs&&Me.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Me.hubPacketEpochMs))}ms`:"",Me.droppedByAgent?`drop ${Me.droppedByAgent}`:"",Me.hubIngressDropped?`ingress-drop ${Me.hubIngressDropped}`:"",Me.hubClientDropped?`ws-drop ${Me.hubClientDropped}`:"",Me.captureStageMs?`capture ${Math.round(Me.captureStageMs)}ms`:"",Me.requestedFps?`req ${Math.round(Me.requestedFps)}fps`:"",Me.effectiveFps?`eff ${Math.round(Me.effectiveFps)}fps`:"",Me.captureAverageMs?`avg ${Math.round(Me.captureAverageMs)}ms`:"",Me.captureP95Ms?`p95 ${Math.round(Me.captureP95Ms)}ms`:"",Me.slowFrameCount?`slow ${Math.round(Me.slowFrameCount)}`:"",Me.captureHelperRestarts?`helper ${Math.round(Me.captureHelperRestarts)}`:"",Me.convertMs?`rgb565 ${Math.round(Me.convertMs)}ms`:"",Me.compressMs?`lzo ${Math.round(Me.compressMs)}ms`:"",Me.captureSourceSerial?`cap #${Me.captureSourceSerial}`:"",Me.captureSourceSkipped?`cap skip ${Me.captureSourceSkipped}`:"",Me.frameMode==="mode5-lzo-delta"?`tiles ${Me.deltaVisualTileCount||0}+${Me.deltaRefreshTileCount||0}/${Me.deltaTotalTiles||0}@${Me.deltaTileSize||0}`:"",Me.platformProfile||Me.hardwareEncoder||"-",Me.atlasComposeMs?`atlas ${Me.atlasComposeMs.toFixed(1)}ms`:"",Me.atlasPoolStarved?`pool ${Me.atlasPoolStarved}`:"",Me.atlasTileCount?`tiles ${Me.atlasReadyTiles||0}/${Me.atlasTileCount}`:"",Me.atlasInputRevision?`input #${Me.atlasInputRevision}`:"",Me.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Me.atlasSourceMaxAgeMs)}ms`:"",Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy?`feedback ${Math.round(Qe.inputFeedbackMs)}ms`:"",Me.contentHash?`enc ${Me.contentHash.slice(0,6)}`:"",Qe?.visualHash?`pix ${Qe.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),gr==="open"&&[`${ka.sentPerSecond.toFixed(1)} hz`,ka.lastInputSeq>0?`rtt ${Math.round(ka.lastRoundTripMs)}ms`:"",ka.lastInputSeq>0?`apply ${ka.lastAgentApplyMs.toFixed(1)}ms`:"",ka.droppedPerSecond>0?`drop ${ka.droppedPerSecond.toFixed(1)}/s`:"",ka.bufferedAmount>0?`buf ${Fc(ka.bufferedAmount)}`:"",ka.lastInputType||"ready"].filter(Boolean).join(" / "),Qe?.inputFeedbackMs!==void 0&&Qe.inputFeedbackAt!==void 0&&performance.now()-Qe.inputFeedbackAt<=jy&&`${Math.round(Qe.inputFeedbackMs)}${Qe.inputFeedbackSeq||0}`,le&&[Aa,`context ${fn.audioContextState}`,`queue ${Math.round(fn.queuedMs)}ms`,`last ${Math.round(fn.lastPacketAgeMs)}ms`,`accepted ${Math.round(fn.lastAcceptedAgeMs)}ms`,`process ${Math.round(fn.localProcessingAgeMs)}ms`,`remote ${Math.round(fn.browserAgeMs)}/${Math.round(fn.captureAgeMs)}ms`,`heartbeat ${Math.round(fn.captureStatusAgeMs)}ms`,`capture ${fn.captureAlive&&fn.helperAlive?"alive":"down"}`,`drop ${fn.drops}`,`resync ${fn.resyncs}`,`restart ${fn.automaticRestarts}`,fn.pendingDecodes>0?`decode ${fn.pendingDecodes}`:"",ji?`#${ji.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Me&&`${Me.frameSeq}${sb(Me.receivedAt||Me.capturedAt)}`;const os=Math.max(0,ol.bytesPerSecond*8/1e6),br=mr?.atlasReadyTiles??ml,pl=mr?.atlasTileCount??ml,wr=br===pl?`${pl} tiles`:`${br}/${pl} tiles`,Sr=Gn.length>0;it?`${hl}${os.toFixed(os>=10?0:1)}`:Sr?`${wr}${hl}${os.toFixed(os>=10?0:1)}`:`${ml}${hl}${os.toFixed(os>=10?0:1)}`;const Cu=j?"offline":b?.started?"online":"starting",co=fa.length,jf=it?Le?Ka(Le):"No workstation":co===0?"No workstation":co>1?`${co} selected`:Le?Ka(Le):"No workstation",ju=it?[Le?.deviceId].filter(x=>!!x):fa.map(x=>x.deviceId),rn=Oo[Ee]||Oo.en,Cr=rn.sync||Oo.en.sync,gl=a||R?"checking":T?Ht==="pro"?"Pro LTD active":`Plus LTD ${at.length}/${Bc}`:hu?`Free ${at.length}/${Hc}`:`Upgrade ${at.length}/${Hc}`,ku=Ht==="pro"?"Pro active":fe==="checkout"?"Opening":Ht==="ltd"?"Pro $199":"Plus $79",lc=T?Ht==="pro"?"Pro active":"Upgrade to Pro LTD":n?fe==="checkout"?"Opening checkout":Ht==="ltd"?"Buy Pro LTD":"Buy Plus LTD":fe==="auth"?"Opening Google":"Sign in to buy",uo=Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,xl=n?.user?.user_metadata,yl=By(xl,"avatar_url","picture"),jr=By(xl,"full_name","name")||n?.user?.email||"Google",Js=jr.slice(0,1).toUpperCase(),Ni=b?.started?"Local app ready":"Start LiveDesk",Au=r?.active?"Published":n?"Not published":"Sign in required",Nu=/^\d{6}$/.test(b?.pairingPin||"")?b?.pairingPin:"------",kr=Yd.find(x=>x.width===Fe.maxWidth&&x.height===Fe.maxHeight)?.id||`${Fe.maxWidth}x${Fe.maxHeight}`,bl=Fe.atlasTileSizeMode==="auto"?"auto":yh.find(x=>x.width===Fe.atlasTileWidth&&x.height===Fe.atlasTileHeight)?.id||"320x180",fo=xh.find(x=>x.width===ut.maxWidth&&x.height===ut.maxHeight)?.id||`${ut.maxWidth}x${ut.maxHeight}`,wl=Wd.find(x=>x.id===Fe.frameMode)||Wd[0],Wn=x=>{Is(M=>{const D=x.frameMode?Wh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode;return{...M,...x,frameMode:D,fps:Kh(x.fps??(B?yw(D):M.fps),D)}})},Mu=x=>{const M=Yd.find(D=>D.id===x);M&&Wn({maxWidth:M.width,maxHeight:M.height})},Mi=x=>{if(x==="auto"){Wn({atlasTileSizeMode:"auto"});return}const M=yh.find(D=>D.id===x);!M?.width||!M?.height||Wn({atlasTileSizeMode:"fixed",atlasTileWidth:M.width,atlasTileHeight:M.height})},Ti=x=>{x.frameMode!==void 0&&(Q(""),me("")),ui(M=>{const D=x.frameMode?Yh(x.frameMode):M.frameMode,B=x.frameMode!==void 0&&D!==M.frameMode,z=x.fps??(B?30:M.fps),ge=x.maxWidth??M.maxWidth,pe=x.maxHeight??M.maxHeight;return{...M,...x,frameMode:D,fps:ds(z,20,D==="mode3-h264-hw"?60:30,D==="mode3-h264-hw"?60:30),maxWidth:D==="mode3-h264-hw"?ge:Math.min(1920,ge),maxHeight:D==="mode3-h264-hw"?pe:Math.min(1080,pe)}})},ei=x=>{const M=xh.find(D=>D.id===x);M&&Ti({maxWidth:M.width,maxHeight:M.height})},Sl=x=>{if(typeof window<"u"&&(x==="support"?window.history.pushState({},"","/support"):ze==="support"&&window.history.pushState({},"","/")),x==="control"){const M=qn||lr;if(M&&(ba(!1),te(M.deviceId)),je(x),!Wt){Oe(!1),J(cr);return}Oe(!0);return}x==="agents"&&rt(null),x==="wall"&&Ut(M=>M+1),je(x),Oe(!1)},ti=fe==="update"||De?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(b?.update?.state||""),ni=!!(b?.update?.updateAvailable&&b.update.canApply||ti||!b&&De),ia=hC(Ee),Ei=u.useCallback(x=>{if(!De?.targetIds.includes(x))return;if(De.stage==="updated")return{state:"updated",label:"Updated"};if(De.stage==="restored"||De.stage==="failed")return{state:"failed",label:De.stage==="restored"?"Update restored":"Update failed",error:De.error};const M=b?.update?.operationId===De.operationId?b.update.targets?.find(D=>D.deviceId===x):void 0;switch(M?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:M.error||b?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return M.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[b?.update,De]);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(ib,{size:25})}),s.jsx("nav",{className:"rail-tools",children:MT.map(x=>{const M=x.icon,D=Xd(x.tooltip,Ee);return s.jsxs("button",{className:`rail-tool ${x.id==="sync-server"?"sync-server hub-sync-trigger":""} ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>x.id==="sync-server"?Ns():Sl(x.id),"data-tooltip":x.id==="sync-server"&&$e?void 0:Th(x.label,x.tooltip,Ee),"aria-label":`${x.label}. ${D}`,type:"button",disabled:x.id==="sync-server"&&fe==="host","aria-busy":x.id==="sync-server"&&fe==="host","aria-expanded":x.id==="sync-server"?$e:void 0,"aria-haspopup":x.id==="sync-server"?"dialog":void 0,"aria-controls":x.id==="sync-server"&&$e?"hub-sync-popover":void 0,children:[x.id==="sync-server"&&fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(M,{size:19}),s.jsx("span",{children:x.id==="sync-server"&&fe==="host"?"Syncing…":x.label})]},x.id)})}),s.jsxs("div",{className:"rail-footer",children:[TT.map(x=>{const M=x.icon;return s.jsxs("button",{className:`rail-tool compact ${ze===x.id?"active":""} accent-${x.accent}`,onClick:()=>Sl(x.id),title:x.label,type:"button",children:[s.jsx(M,{size:18}),s.jsx("span",{children:x.label})]},x.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${ar?"active":""}`,onClick:()=>{je("settings"),typeof window<"u"&&window.history.pushState({},"","/"),an(!1),Oe(!1),tt(!1)},title:"Settings",type:"button",children:[s.jsx(qy,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{an(x=>!x)},disabled:a||fe==="auth","aria-expanded":$t,title:n?`Account: ${n.user?.email||jr}`:"Sign in with Google",type:"button",children:[n?yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:Js}):s.jsx(Ol,{size:18}),s.jsx("span",{children:n?"Account":"Google"})]}),$t&&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:n&&yl?s.jsx("img",{src:yl,alt:jr,referrerPolicy:"no-referrer"}):n?s.jsx("span",{children:Js}):s.jsx(Ol,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:n?jr:"Account"}),s.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:n?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:Ni}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:Au}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:Ht==="free"?"Standard banner":"Removed"})]}),n?s.jsxs("button",{className:"account-popover-action",onClick:Ks,disabled:fe==="auth",type:"button",children:[s.jsx(Gy,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:zn,disabled:fe==="auth",type:"button",children:[s.jsx(Ol,{size:16}),"Sign in with Google"]})]})]})]}),$e&&s.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(Gi,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:ia.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>sa(),"aria-label":ia.closeLabel,children:s.jsx(Ha,{size:17})})]}),s.jsx("h2",{id:"hub-sync-title",children:ia.title}),s.jsx("p",{id:"hub-sync-description",children:ia.description}),s.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[s.jsx(Lt,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:ia.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>sa(),children:ia.cancel}),s.jsxs("button",{ref:Mt,className:"primary",type:"button",onClick:wu,disabled:fe==="host",children:[s.jsx(Gi,{size:16}),ia.confirm]})]})]}),s.jsxs("section",{className:`desk-stage ${iu&&!Un?"dock-open":""} ${it?"control-stage":""} ${Vo?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(gn,{size:18})}),s.jsxs("div",{className:"brand-copy",children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]}),ni?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{nc()},title:De?.error||`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,"aria-label":ti?"LiveDesk update in progress":`Update LiveDesk to ${b?.update?.latestVersion||De?.targetManagerVersion||"latest"}`,type:"button",disabled:ti||!b?.update?.canApply,"aria-busy":ti,children:[ti?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Qh,{size:19,"aria-hidden":"true"}),ti&&b?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[b.update.completedCount||0,"/",b.update.targetCount]}):null]}):null]}),s.jsxs("div",{className:"topbar-tray",children:[ir&&!it&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(zl,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(Jh,{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:[ru," workstation",ru===1?"":"s"]}),s.jsx("em",{children:Xn.trim()||"Desktop/LiveDeskFiles"})]})]})]}),iu&&!it&&s.jsxs("div",{className:"top-actions",children:[s.jsx(by,{controller:Zl,onError:J}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:NT.map(x=>s.jsx("button",{className:Xe===x.id?"active":"",onClick:()=>gt(x.id),type:"button",children:x.label},x.id))})]}),it&&s.jsx("div",{className:"top-actions",children:s.jsx(by,{controller:Zl,onError:J})})]})]}),sr?s.jsxs("section",{className:"doc-page",lang:Ee,dir:Ee==="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(Kd,{size:16}),rn.eyebrow]}),s.jsx("h2",{children:rn.title}),s.jsx("p",{children:rn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(h0,{size:17}),rn.languageLabel]}),s.jsx("select",{value:Ee,onChange:x=>ua(x.target.value),children:RT.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),s.jsx("section",{className:"doc-grid",children:rn.sections.map((x,M)=>{const B=[Gi,Ud,Um,Lt,Hl][M]||Kd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(B,{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)})}),Cr&&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:Cr.title}),s.jsx("p",{children:Cr.body})]})]}),s.jsx("ul",{children:Cr.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:rn.firewall.title}),s.jsx("p",{children:rn.firewall.body})]})]}),s.jsx("ul",{children:rn.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(Ud,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:rn.commands.title}),s.jsx("p",{children:rn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[rn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.manager}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.primary}),s.jsx("code",{children:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:rn.commands.slot}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})]}):Vo?s.jsx(vy,{hubUrl:N,devices:C,launchRequest:Ye}):ir?s.jsx(xN,{hubUrl:N,devices:at,localFeatureAccess:Wt,upgradeNotice:cr,remoteDirectory:Xn,onRemoteDirectoryChange:Wi,targetMode:mi,selectedTargetIds:Jn,onTargetModeChange:Qr,onTargetToggle:x=>Xr(M=>M.includes(x)?M.filter(D=>D!==x):[...M,x]),filePickerRef:Wl,folderPickerRef:su,onBrowserFileImport:x=>{yr(x)},onBrowserFolderImport:x=>{yr(x)},onNotice:J,onTransferChange:x=>{if(!x){as(null);return}const M=x.state==="failed"||x.state==="partially-failed"||x.state==="cancelled"?"failed":x.state==="completed"?"queued":x.state==="sending"?"sending":"reading";as({id:x.id,status:M,progress:x.progress,message:x.message}),["completed","partially-failed","failed","cancelled"].includes(x.state)&&window.setTimeout(()=>as(D=>D?.id===x.id?null:D),4500)}}):Jr?s.jsx(tb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:zn}):ar?s.jsx(zj,{hubUrl:N,runtimeRole:b?.runtimeRole||"hub",runtimeDeviceId:b?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:s.jsxs(Ij,{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(Yt,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:Nu}),s.jsxs("button",{className:"text-button ghost compact",onClick:ac,disabled:!b?.started||fe==="pin",type:"button",children:[s.jsx(Ds,{size:15}),fe==="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:Cu})]}),s.jsx("span",{className:`settings-status-dot state-${Cu}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:N||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[Ms,"/",Kl]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:b?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gl})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>Na({takeover:!0,requestLocalAccess:!0}),disabled:!n||fe==="host",type:"button",children:[fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Um,{size:16}),fe==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>ls(Ht==="ltd"?"pro":"ltd"),disabled:fe==="checkout"||Ht==="pro",type:"button",children:[s.jsx(Do,{size:16}),ku]})]})]})]}),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:Xn,onChange:x=>Wi(x.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(Oj,{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(Kc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:Fe.frameMode,onChange:x=>Wn({frameMode:Wh(x.target.value)}),children:Wd.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:Fe.h264DecodeAcceleration,onChange:x=>Wn({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.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:Fe.fps,onChange:x=>Wn({fps:Kh(x.target.value,Fe.frameMode)}),children:bp.filter(x=>x<=bw(Fe.frameMode)).map(x=>s.jsx("option",{value:x,children:x},x))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ct?"Atlas tile":"Resolution"}),s.jsx("select",{value:ct?bl:kr,onChange:x=>ct?Mi(x.target.value):Mu(x.target.value),children:(ct?yh:Yd).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:Fe.quality,onChange:x=>Wn({quality:ds(x.target.value,20,95,xa.quality)}),children:Dy.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(gn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.autoStartLive,onChange:x=>Wn({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:Fe.visibleOnlyLive,onChange:x=>Wn({visibleOnlyLive:x.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ct&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:Fe.adaptiveSizeByWall,onChange:x=>Wn({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:Fe.adaptiveLoadShedding,onChange:x=>Wn({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:Fe.showScreenStatus,onChange:x=>Wn({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:wl.label}),s.jsxs("strong",{children:[_n.maxWidth,"x",_n.maxHeight," / ",Tn,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>Is(xa),type:"button",children:[s.jsx($c,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(Hj,{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($d,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:ut.frameMode,onChange:x=>Ti({frameMode:Yh(x.target.value)}),children:WM.map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:ut.h264DecodeAcceleration,onChange:x=>Ti({h264DecodeAcceleration:cf(x.target.value)}),children:Vh.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:ut.fps,onChange:x=>Ti({fps:ds(x.target.value,20,60,Ia.fps)}),children:YM.filter(x=>ut.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:fo,onChange:x=>ei(x.target.value),children:xh.filter(x=>ut.frameMode==="mode3-h264-hw"||x.width<=1920).map(x=>s.jsx("option",{value:x.id,children:x.label},x.id))})]})]}),ut.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:ut.quality,onChange:x=>Ti({quality:ds(x.target.value,20,95,Ia.quality)}),children:Dy.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(Yt,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:ut.showScreenStatus,onChange:x=>Ti({showScreenStatus:x.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:ut.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[Ps.maxWidth,"x",Ps.maxHeight," / ",rr,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>ui(Ia),type:"button",children:[s.jsx($c,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(Bj,{hubUrl:N}),captureGallery:s.jsx(yM,{hubUrl:N,onToast:J}),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(Nl,{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:In}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(In),title:"Copy client command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${In} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Ll(`${In} 3`),title:"Copy slot command",type:"button",children:s.jsx(Nl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:$a}),s.jsx("button",{className:"icon-button",onClick:()=>Ll($a),title:"Copy Hub command",type:"button",children:s.jsx(Nl,{size:16})})]})]})]})}):Yl?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(Ah,{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:()=>Sl("wall"),title:"Close pricing",type:"button",children:s.jsx(Ha,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:or.name}),s.jsxs("small",{children:[at.length,"/",VM(Ql)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${Ht==="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:El.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:El.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Hn,{size:16})," Up to ",Hc," 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:Ht==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${Ht==="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:El.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 ",Bc," devices"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Hn,{size:16})," ",El.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("ltd"):zn,disabled:Ht!=="free"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${Ht==="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:El.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})," ",El.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>ls("pro"):zn,disabled:Ht==="pro"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Do,{size:16}),Ht==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(Yt,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx($d,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(rx,{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:n?()=>ls(Ht==="ltd"?"pro":"ltd"):zn,disabled:uo,type:"button",children:[s.jsx(Do,{size:18}),lc]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${Un?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:Go,className:`screen-wall-panel ${tr?"drop-active":""}`,onClick:x=>{x.currentTarget===x.target&&Et()},onDragEnter:x=>{x.preventDefault(),Bs(!0)},onDragOver:x=>{x.preventDefault(),x.dataTransfer.dropEffect="copy"},onDragLeave:x=>{x.currentTarget===x.target&&Bs(!1)},onDrop:sc,children:[Gn.length>0&&s.jsx("canvas",{ref:fr,className:"atlas-source-canvas",width:wi?.width||1920,height:wi?.height||1080,"aria-hidden":"true"}),it?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Le&&Zs.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Zs.map(x=>s.jsxs("button",{className:x.index===Ai?"active":"",onClick:()=>Ma(Le.deviceId,x.index),title:cT(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))}),Le?s.jsx(kh,{device:Le,frame:Me,selected:!1,controlEnabled:ws&&Se&&vr,showStatus:ut.showScreenStatus,monitorIndex:za(Kt[Le.deviceId],va(Le)),monitorCount:va(Le),onSelect:()=>{},onFocusDevice:()=>te(Le.deviceId),onOpenControl:()=>ki(Le.deviceId),onCycleMonitor:x=>rs(Le.deviceId,x),onCanvasReady:nl,sendInput:Ci,presentationReady:Ul},Le.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(Yt,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Le&&Yo&&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."})]}),Le&&!Yo&&!Ul&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[U!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:U==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:U==="error"?"See the notification for details. Reopen Control to retry.":Gs||de?"Control stream is recovering. See the notification for details.":hr==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Xe==="list"?s.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[s.jsxs("div",{className:"wall-device-list-head",role:"row",children:[s.jsx("span",{role:"columnheader",children:"Computer"}),s.jsx("span",{role:"columnheader",children:"Status"}),s.jsx("span",{role:"columnheader",children:"CPU"}),s.jsx("span",{role:"columnheader",children:"GPU"}),s.jsx("span",{role:"columnheader",children:"RAM"}),s.jsx("span",{role:"columnheader",children:"VRAM"}),s.jsx("span",{role:"columnheader",children:"Network"}),s.jsx("span",{role:"columnheader",children:"HDD"}),s.jsx("span",{role:"columnheader",children:"Temp"})]}),ou.length>0?ou.map(({device:x,slotNumber:M})=>s.jsx(_T,{device:x,slotNumber:M,selected:ys.has(x.deviceId),updateIndicator:Ei(x.deviceId),onSelect:()=>yn(x.deviceId),onOpenControl:()=>ki(x.deviceId)},x.deviceId)):s.jsxs("div",{className:"wall-device-list-empty",children:[s.jsx(Yt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"No connected computers"})]})]}):ct?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:!1,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:zc({mode4Enabled:ct,directMode4WallEnabled:ss,isMac:qi(x.platform)})==="direct"?na:il,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}):s.jsx("div",{className:`screen-wall size-${Xe}`,onClick:x=>{x.currentTarget===x.target&&Et()},children:pi.map((x,M)=>x?s.jsx(kh,{device:x,frame:Si.get(x.deviceId),selected:ys.has(x.deviceId),controlEnabled:ws&&Se&&vr&&Le?.deviceId===x.deviceId,showStatus:Fe.showScreenStatus,monitorIndex:za(Kt[x.deviceId],va(x)),monitorCount:va(x),onSelect:()=>yn(x.deviceId),onFocusDevice:()=>io(x.deviceId),onOpenControl:()=>ki(x.deviceId),onCycleMonitor:D=>rs(x.deviceId,D),onCanvasReady:na,sendInput:Ci,updateIndicator:Ei(x.deviceId),presentationReady:Fe.autoStartLive&&Sa.includes(x.deviceId)?Ze.has(x.deviceId):void 0,showPresentationSpinner:Fe.autoStartLive&&Sa.includes(x.deviceId)},x.deviceId):s.jsx(Py,{index:M},`slot-${M}`))}),s.jsx(IT,{visible:ur&&!it})]}),!ar&&s.jsxs("aside",{className:`right-dock actions-mode ${Un?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>tt(x=>!x),"aria-label":Un?"Show control panel":"Hide control panel",title:Un?"Show control panel":"Hide control panel",type:"button",children:Un?s.jsx(Jy,{size:18}):s.jsx(ep,{size:18})}),!Un&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsx("input",{ref:Zr,className:"hidden-file-input",type:"file",multiple:!0,onChange:x=>{x.currentTarget.files&&ro(x.currentTarget.files),x.currentTarget.value=""}}),s.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual workstation controls",children:[s.jsx(Pr,{label:"Control",tooltip:Le?Yo?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ws?vr?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation":"Select a workstation to use Control",onClick:()=>{if(Le){if(it&&Se){Oe(!1),J("Remote control paused. Screen viewing stays on.");return}ki(Le.deviceId)}},disabled:!ws||!!Te,active:Se,pressed:it&&Se,children:s.jsx($d,{size:17})}),s.jsx(Pr,{label:"Audio",tooltip:Le?el?le?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation":"Select a workstation to use Audio",onClick:()=>{Qs()},disabled:!pu||!!Te,active:le,pressed:le,children:Te==="audio"?s.jsx(ii,{className:"spin",size:17}):s.jsx(rx,{size:17})}),s.jsx(Pr,{label:"Send files",tooltip:fa.length===0&&!it?"Select one or more workstations to send files":Le?"Choose files and send them to the selected workstation":"Select a workstation to send files",onClick:()=>{J(`Choose files to send to ${jf}.`),Zr.current?.click()},disabled:!!Te||!Wt||(it?!Le:fa.length===0),children:s.jsx(Lo,{size:17})}),s.jsx(Pr,{label:"Run command",tooltip:Le?fu?"Run command":"Command runner is not available on this workstation":"Select a workstation to run a command",onClick:xr,disabled:!Le||!Wt||!!Te||!fu,children:s.jsx(Ud,{size:17})}),s.jsx(Pr,{label:"Restart",tooltip:Le?du?"Restart workstation":"Restart is not available on this workstation":"Select a workstation to restart",onClick:()=>{fl("restart")},disabled:!Le||!Wt||!!Te||!du,children:Te==="restart"?s.jsx(ii,{className:"spin",size:17}):s.jsx($c,{size:17})}),s.jsx(Pr,{label:"Lock",tooltip:Le?"Lock workstation":"Select a workstation to lock",onClick:()=>{fl("lock")},disabled:!Le||!Wt||!!Te,children:Te==="lock"?s.jsx(ii,{className:"spin",size:17}):s.jsx(Ds,{size:17})}),s.jsx(Pr,{label:"Sleep",tooltip:Le?"Put workstation to sleep":"Select a workstation to put to sleep",onClick:()=>{fl("sleep")},disabled:!Le||!Wt||!!Te,children:Te==="sleep"?s.jsx(ii,{className:"spin",size:17}):s.jsx(g0,{size:17})}),s.jsx(Pr,{label:"Shut down",tooltip:Le?"Shut down workstation":"Select a workstation to shut down",onClick:()=>{fl("shutdown")},disabled:!Le||!Wt||!!Te,danger:!0,children:Te==="shutdown"?s.jsx(ii,{className:"spin",size:17}):s.jsx(v0,{size:17})})]})]}),s.jsx(vy,{hubUrl:N,devices:C,variant:"dock",selectedDeviceIds:ju})]})]})]})})]}),gs&&s.jsxs("aside",{className:`transfer-bar state-${gs.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:gs.status==="queued"?s.jsx(Hn,{size:18}):gs.status==="failed"?s.jsx(Ha,{size:18}):s.jsx(Qy,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:gs.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,gs.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,gs.progress)),"%"]})]}),It&&s.jsxs("aside",{className:`livedesk-toast tone-${It.tone}`,role:It.tone==="error"?"alert":"status","aria-live":It.tone==="error"?"assertive":"polite","aria-busy":It.tone==="progress",children:[It.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:It.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>J(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ha,{size:15})})]})]})}function HT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function BT(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const v of HT())try{const g=await fetch(`${v}/api/runtime`,{cache:"no-store"});if(!g.ok)continue;const y=(await g.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(jC,{}):s.jsx(OT,{}):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..."})]})}k0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(BT,{})}));