livedesk 0.1.652 → 0.1.653
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/web/dist/app.html +4 -4
- package/web/dist/app.webmanifest +1 -1
- package/web/dist/assets/{AgentSettingsTab-SlFWbGlY.js → AgentSettingsTab-BBNQK3m_.js} +1 -1
- package/web/dist/assets/{AgentsPage-AoFB_KD4.js → AgentsPage-DUMU7WPH.js} +1 -1
- package/web/dist/assets/{App-smTkH_7F.js → App-WZAN0Iwh.js} +21 -21
- package/web/dist/assets/{CaptureGallery-bgLFx77c.js → CaptureGallery-Dgucz-9s.js} +1 -1
- package/web/dist/assets/{DesktopUpdatePanel-BDIHhw5J.js → DesktopUpdatePanel-BPD9IaXS.js} +1 -1
- package/web/dist/assets/{SettingsPage-DLhQYnES.js → SettingsPage-JYlSHnWI.js} +1 -1
- package/web/dist/assets/{SettingsTabs-C1ovcXzw.js → SettingsTabs-D75pwHMD.js} +1 -1
- package/web/dist/assets/{ShareFilesPage-rESjZP8s.js → ShareFilesPage-Bp5Dh9tQ.js} +1 -1
- package/web/dist/assets/{SupportPage-B90rx4D0.js → SupportPage-BwS_toBH.js} +1 -1
- package/web/dist/assets/{VuvoDeskApp-BM4kuSAh.js → VuvoDeskApp-BIrWZOFb.js} +1 -1
- package/web/dist/assets/{app-VTnPXosN.js → app-BJgxvk6P.js} +1 -1
- package/web/dist/assets/{main-DEpRH1th.js → main-DAAb7wf6.js} +2 -2
- package/web/dist/assets/{styles-CDIlHYlj.js → styles-CO6aHjLW.js} +1 -1
- package/web/dist/assets/{styles-BbMJwyw_.css → styles-DDKP4MTD.css} +1 -1
- package/web/dist/index.html +3 -3
- package/web/dist/sw.js +1 -1
- package/web/dist/vuvodesk-build-evidence.json +48 -48
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentsPage-
|
|
2
|
-
import{D as In,k as Kv,l as fl,i as yi,h as ze,m as Yv,e as Ss,o as Qv,q as xs,u as Rs,_ as mr,v as Kh,x as Xv,y as Jv,j as i,p as $e,z as Yh,A as Zv,B as Xp,C as Jp,g as ey,T as Zp,b as Lu,a as us,F as Ou,M as ef,f as _u,E as ty,L as ny}from"./styles-CDIlHYlj.js";import{a as s,am as ry,an as tf,p as ay,ao as oy,ap as iy,ae as Sl,X as Ma,U as As,aq as Qh,c as Ra,l as hl,ac as xa,ar as sy,as as cy,at as ly,au as uy,k as wo,av as Xh,g as Si,aw as dy,ax as my,b as Cn,y as py,ay as Jh,f as Cs,a0 as Zh,T as gl,aa as wd,ab as fy,ad as nf,a9 as hy,az as gy,D as rf,O as by,N as vy,A as yy,E as wy,aA as af,W as eg,aB as ju,Z as Sy,a2 as Bu,x as Cy,aC as of,aD as ky,aE as tg,C as ng,n as ds,aF as My,aG as xy,t as Ry,aH as Ay,a4 as Iy,G as Ty,Q as Py}from"./icons-CacEbnZu.js";import{c as Ey}from"./supabase-C7qjtLN3.js";import{c as Ny,a as Fy,f as Hu,b as Dy,r as Wu,t as $u,d as sf,e as Ly,i as cf,g as Oy,h as On,j as ya,s as dn,k as ho,l as Vu,m as zu,n as Uu,o as _y,p as Xc,q as lf,u as Jc,v as uf}from"./frame-lifecycle-esOdP-EY.js";const rg={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run approved commands on connected Clients through the Hub-hosted Codex Agent and VuvoDesk permission controls."},Sd={en:rg,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub의 Codex가 연결된 Client에서 VuvoDesk 권한과 승인 범위 안의 명령을 실행합니다."},ja:{hub:"このコンピューターを VuvoDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub の Codex Agent が、VuvoDesk の権限と承認の範囲内で接続中の Client にコマンドを実行します。"},zh:{hub:"将此电脑作为 VuvoDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。VuvoDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"Hub 的 Codex Agent 会在 VuvoDesk 权限与批准范围内,对已连接的 Client 执行命令。"},"zh-TW":{hub:"將此電腦作為 VuvoDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。VuvoDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"Hub 的 Codex Agent 會在 VuvoDesk 權限與核准範圍內,對已連線的 Client 執行命令。"},es:{hub:"Usa este equipo como VuvoDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. VuvoDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"El Codex Agent del Hub ejecuta comandos en los Clients conectados dentro de los permisos y aprobaciones de VuvoDesk."},fr:{hub:"Utilise cet ordinateur comme VuvoDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. VuvoDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Le Codex Agent du Hub exécute des commandes sur les Clients connectés selon les permissions et approbations de VuvoDesk."},de:{hub:"Verwendet diesen Computer als VuvoDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. VuvoDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Der Codex Agent des Hubs führt Befehle auf verbundenen Clients innerhalb der VuvoDesk-Berechtigungen und Freigaben aus."},"pt-BR":{hub:"Usa este computador como VuvoDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O VuvoDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"O Codex Agent do Hub executa comandos nos Clients conectados dentro das permissões e aprovações do VuvoDesk."},it:{hub:"Usa questo computer come VuvoDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. VuvoDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Il Codex Agent dell’Hub esegue comandi sui Client connessi entro i permessi e le approvazioni di VuvoDesk."},id:{hub:"Gunakan komputer ini sebagai VuvoDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. VuvoDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Codex Agent di Hub menjalankan perintah pada Client terhubung sesuai izin dan persetujuan VuvoDesk."},vi:{hub:"Dùng máy tính này làm VuvoDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. VuvoDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Codex Agent trên Hub chạy lệnh trên các Client đã kết nối trong phạm vi quyền và phê duyệt của VuvoDesk."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น VuvoDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย VuvoDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"Codex Agent บน Hub เรียกใช้คำสั่งบน Client ที่เชื่อมต่อภายใต้สิทธิ์และการอนุมัติของ VuvoDesk"},hi:{hub:"इस कंप्यूटर को VuvoDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। VuvoDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"Hub का Codex Agent VuvoDesk permissions और approvals के भीतर जुड़े Clients पर commands चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه VuvoDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ VuvoDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل Codex Agent على Hub الأوامر في Clients المتصلين ضمن صلاحيات وموافقات VuvoDesk."},tr:{hub:"Bu bilgisayarı VuvoDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. VuvoDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub Codex Agent, bağlı Client’larda VuvoDesk izinleri ve onayları kapsamında komut çalıştırır."}};function Hd(e){const t=e?[e]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const a of t){const r=String(a||"").trim(),c=r.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const u=c.split("-")[0];if(Sd[r])return r;if(Sd[u])return u}return"en"}function ag(e,t){const a=Hd(t);return Sd[a]?.[e]||rg[e]}function jy(e,t,a){return`${e}
|
|
3
|
-
${ag(t,a)}`}const og={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"VuvoDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while VuvoDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},By={en:og,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"VuvoDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"VuvoDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"VuvoDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"VuvoDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"VuvoDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"VuvoDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"VuvoDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras VuvoDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"VuvoDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de VuvoDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"VuvoDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des VuvoDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O VuvoDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o VuvoDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"VuvoDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di VuvoDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"VuvoDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat VuvoDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"VuvoDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi VuvoDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"VuvoDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ VuvoDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"VuvoDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"VuvoDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف VuvoDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل VuvoDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"VuvoDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"VuvoDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},ig={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},Hy={en:ig,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function rx(e){const t=Hd(e);return By[t]||og}function Wy(e){const t=Hd(e);return Hy[t]||ig}const $y="https://otbyfkjxrkngvjziawki.supabase.co",Vy="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",zy={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},qu=typeof window<"u"&&!!window.liveDesk,Ct=Ey($y,Vy,{auth:{autoRefreshToken:!qu,persistSession:!qu,storage:qu?zy:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}});function Uy({eligibleCandidates:e,fallbackHubBaseUrl:t,publicConsole:a,authenticated:r}){const c=String(t||"").trim();if(a&&r&&c)return Object.freeze({candidates:Object.freeze([c]),transport:"p2p",reason:"authenticated-public-console-p2p"});const u=[...new Set((Array.isArray(e)?e:[]).map(p=>String(p||"").trim()).filter(Boolean))];return u.length>0?Object.freeze({candidates:Object.freeze(u),transport:"auto",reason:"direct-candidate"}):Object.freeze({candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}function qy({expectedWorkspaceId:e,expectedWorkspaceKind:t,verifiedPublicDirect:a,statusWorkspace:r}){const c=String(e||"").trim(),u=String(t||"").trim().toLowerCase();if(!c)return!0;const p=String(r?.workspaceId||"").trim(),h=String(r?.kind||"").trim().toLowerCase();return p?p===c&&h===u:a===!0&&u==="personal"}function Gu(e,t){const a=e?.hasSnapshot===!0;switch(t){case"reset-idle":return Object.freeze({phase:"idle",hasSnapshot:!1});case"reset-enabled":return Object.freeze({phase:"connecting",hasSnapshot:!1});case"success":return Object.freeze({phase:"online",hasSnapshot:!0});case"failure":return Object.freeze({phase:a?"reconnecting":"unavailable",hasSnapshot:a});case"retry":return Object.freeze({phase:a?"reconnecting":"connecting",hasSnapshot:a});default:throw new Error(`Unknown Hub snapshot connection event: ${String(t||"")}`)}}function Gy({authLoading:e,phase:t,recoveryOverlayEligible:a=!1}){const r=String(t||"idle"),c=r==="reconnecting",u=c&&a===!0;return Object.freeze({statusVisible:e!==!0&&r!=="connecting"&&(!c||!u),recoveryVisible:u})}const Ky=Object.freeze([50,100,250,600,1e3,2e3,4e3]);function Yy(e={}){const t=typeof e.readVisible=="function"?e.readVisible:()=>document.visibilityState==="visible",a=typeof e.commitVisibility=="function"?e.commitVisibility:()=>{},r=typeof e.schedule=="function"?e.schedule:(te,Z)=>setTimeout(te,Z),c=typeof e.cancel=="function"?e.cancel:te=>clearTimeout(te),u=Array.isArray(e.recheckDelaysMs)&&e.recheckDelaysMs.length>0?e.recheckDelaysMs.map(te=>Math.max(1,Math.floor(Number(te)||1))):Ky;let p=!1,h=0,f=!1,k=null,M=0,b=0,T=Object.prototype.hasOwnProperty.call(e,"initialCommittedVisible")?e.initialCommittedVisible===!0:!!t();const I=()=>{k!==null&&(c(k),k=null)},x=te=>{const Z=te===!0;return T===Z?!1:(T=Z,a(Z),!0)},E=te=>{h+=1,f=!1,M=0,I(),x(te)},H=te=>{if(p||!f||te!==h)return!1;if(M>=u.length)return f=!1,M=0,!1;const Z=u[M];M+=1;const me=r(()=>{if(k===me&&(k=null,!(p||!f||te!==h))){if(b+=1,t()){E(!0);return}H(te)}},Z);return k=me,!0};return Object.freeze({handleForegroundHint:()=>{if(p)return!1;if(t())return E(!0),!0;if(x(!1),f)return!1;f=!0,M=0;const te=h+1;return h=te,H(te),!1},handlePageHide:()=>{p||E(!1)},handleVisibilityChange:()=>{if(p)return!1;const te=!!t();return E(te),te},dispose:()=>{p||(p=!0,h+=1,f=!1,M=0,I())},inspect:()=>Object.freeze({active:f,timerCount:k===null?0:1,runGeneration:h,checkCount:b,committedVisible:T})})}function Ca(e,t,a){if(a<0||t<0||t+a>e.length)throw new Error("Invalid LZO1X block: input overrun.")}function Ku(e,t,a){let r=0;for(;Ca(e,t.inputIndex,1),e[t.inputIndex]===0;)r+=1,t.inputIndex+=1;const c=r*255+a+e[t.inputIndex];return t.inputIndex+=1,c}function Zc(e,t,a,r){if(Ca(e,t.inputIndex,r),t.outputIndex+r>a.length)throw new Error("Invalid LZO1X block: output overrun.");a.set(e.subarray(t.inputIndex,t.inputIndex+r),t.outputIndex),t.inputIndex+=r,t.outputIndex+=r}function Qy(e,t,a,r){const c=t-a;if(c<=0||r<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(c,r);for(e.set(e.subarray(a,a+u),t);u<r;){const p=Math.min(u,r-u);e.copyWithin(t+u,t,t+p),u+=p}return t+r}function sg(e,t){if(!(e instanceof Uint8Array)||e.length<3||t<0)throw new Error("Invalid LZO1X block.");const a=new Uint8Array(t),r={inputIndex:0,outputIndex:0};let c=0,u=0;if(e[r.inputIndex]>=22){const p=e[r.inputIndex]-17;r.inputIndex+=1,Zc(e,r,a,p),c=4}else e[r.inputIndex]>=18&&(c=e[r.inputIndex]-17,r.inputIndex+=1,Zc(e,r,a,c));for(;;){Ca(e,r.inputIndex,1);const p=e[r.inputIndex];r.inputIndex+=1;let h,f;if((p&192)!==0)Ca(e,r.inputIndex,1),f=r.outputIndex-((e[r.inputIndex]<<3)+(p>>2&7)+1),r.inputIndex+=1,u=(p>>5)+1,h=p&3;else if((p&32)!==0){u=(p&31)+2,u===2&&(u+=Ku(e,r,31)),Ca(e,r.inputIndex,2);const k=e[r.inputIndex]|e[r.inputIndex+1]<<8;r.inputIndex+=2,f=r.outputIndex-((k>>2)+1),h=k&3}else if((p&16)!==0){u=(p&7)+2,u===2&&(u+=Ku(e,r,7)),Ca(e,r.inputIndex,2);const k=e[r.inputIndex]|e[r.inputIndex+1]<<8;if(r.inputIndex+=2,f=r.outputIndex-(((p&8)<<11)+(k>>2)),h=k&3,f===r.outputIndex)break;f-=16384}else if(c===0){let k=p+3;k===3&&(k+=Ku(e,r,15)),Zc(e,r,a,k),c=4;continue}else c!==4?(Ca(e,r.inputIndex,1),h=p&3,f=r.outputIndex-((p>>2)+(e[r.inputIndex]<<2)+1),r.inputIndex+=1,u=2):(Ca(e,r.inputIndex,1),h=p&3,f=r.outputIndex-((p>>2)+(e[r.inputIndex]<<2)+2049),r.inputIndex+=1,u=3);if(f<0||r.outputIndex+u+h>a.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");r.outputIndex=Qy(a,r.outputIndex,f,u),c=h,Zc(e,r,a,h)}if(u!==3||r.inputIndex!==e.length||r.outputIndex!==a.length)throw new Error("Invalid LZO1X block: incomplete output.");return a}const df=16,mf=8,Xy=24*1024*1024,cg=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Cd=new Uint32Array(65536);for(let e=0;e<Cd.length;e+=1){const t=Math.round((e>>11&31)*255/31),a=Math.round((e>>5&63)*255/63),r=Math.round((e&31)*255/31);Cd[e]=cg?(t|a<<8|r<<16|4278190080)>>>0:(t<<24|a<<16|r<<8|255)>>>0}function wa(e,t){return e[t]|e[t+1]<<8}function Jy(e,t){const a=Number(t);if(!Number.isSafeInteger(a)||a<df||a>Xy)throw new Error(`Invalid Mode 5 packet length: ${t}.`);const r=e instanceof Uint8Array?e:new Uint8Array(e),c=sg(r,a);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const u=(c[5]&1)!==0,p=wa(c,6),h=wa(c,8),f=wa(c,10),k=wa(c,12);if(p<=0||h<=0||p>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${p}x${h}.`);if(f<=0||f>256||k>8192)throw new Error(`Invalid Mode 5 tile header: ${f}/${k}.`);const M=[];let b=df;for(let T=0;T<k;T+=1){if(b+mf>c.length)throw new Error("Mode 5 tile header is truncated.");const I=wa(c,b),x=wa(c,b+2),E=wa(c,b+4),H=wa(c,b+6);b+=mf;const Q=E*H*2;if(E<=0||H<=0||E>f||H>f||I+E>p||x+H>h||b+Q>c.length)throw new Error(`Invalid Mode 5 tile ${T}.`);M.push({x:I,y:x,width:E,height:H,pixels:c.subarray(b,b+Q)}),b+=Q}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:u,width:p,height:h,tileSize:f,tiles:M}}function Zy(e,t,a,r){if(!(e instanceof Uint8ClampedArray)||e.length!==t*a*4||r.width!==t||r.height!==a)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=t,u=a,p=0,h=0;const f=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);for(const k of r.tiles){const M=cg&&(k.pixels.byteOffset&1)===0?new Uint16Array(k.pixels.buffer,k.pixels.byteOffset,k.pixels.byteLength>>>1):null;let b=0;for(let T=0;T<k.height;T+=1){let I=(k.y+T)*t+k.x;for(let x=0;x<k.width;x+=1){const E=b<<1,H=M?M[b]:k.pixels[E]|k.pixels[E+1]<<8;f[I]=Cd[H],b+=1,I+=1}}c=Math.min(c,k.x),u=Math.min(u,k.y),p=Math.max(p,k.x+k.width),h=Math.max(h,k.y+k.height)}return r.tiles.length>0?{x:c,y:u,width:p-c,height:h-u}:null}function ew(e){if(!e)return!0;const t=jt.get(e);return!t||t.hardwareAcceleration==="prefer-hardware"}const jt=new WeakMap,pf=854,ff=480,tw=3840,nw=2160,rw=500,Is=new WeakMap,kd=new WeakMap,xo=new Set,ko=new Set,Ta=new WeakMap,Mo=new Set,ki=new WeakMap,Md=new WeakMap,xd=new WeakMap,Cl=new WeakMap,lg=4,aw=2,bi=4,ow=2,iw=2,sw=18,cw=0,lw=250,ug=80,uw=5,dw=150,mw=1200,pw=18,fw=.65,dg=80,mg=125,hw=4,gw=2*1024*1024,bw=8,vw=16,yw=180,ww=3,Wd=2e3,pg=64,fg=32*1024*1024,Sw=500,Cw=25,kw=45,Mw=20,hg=new Uint8Array(0),$d=250,xw=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let gg=1,bg=0,vg=0,Rd=0,yg=0;const vs=[];let Es=0,wg=0,Sg,Cg=0,kg,Mg;function Ns(e,t){vs.push({sequence:++yg,type:e,canvasId:ki.get(t)||0,observedAt:Date.now(),activeDecoderCount:xo.size,hardwareLeaseCount:ko.size,hardwareReleaseGeneration:Es}),vs.length>256&&vs.splice(0,vs.length-256)}let ta={h264DecodeAcceleration:"prefer-hardware"};function Rw(e){e.h264DecodeAcceleration&&(ta={...ta,h264DecodeAcceleration:e.h264DecodeAcceleration})}function Aw(e){return e.payload.byteLength===0?e:{...e,payload:hg}}function xg(e,t){const a=String(e.streamPurpose||"").trim().toLowerCase();return a==="wall"?!0:a==="control"?!1:t>=45e3}function Rg(e){try{return e.paintIsCancelled()}catch{return!0}}function Tl(e,t){const a=e.pendingFrames.get(t);if(a)return e.pendingFrames.delete(t),e.pendingFrameBytes=Math.max(0,e.pendingFrameBytes-a.encodedByteLength),e.pendingFrames.size===0&&e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),a}function Iw(e){const t=e.pendingFrames.entries().next().value;return t?Tl(e,t[0]):void 0}function Ag(e){e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),e.pendingFrames.clear(),e.pendingFrameBytes=0,e.pendingFrameEvictedThroughTimestamp=-1}function Pl(e,t=performance.now()){for(;e.pendingFrames.size>0;){const a=e.pendingFrames.entries().next().value;if(!a)break;const r=t-a[1].queuedAt>Wd,c=e.pendingFrames.size>pg,u=e.pendingFrameBytes>fg;if(!r&&!c&&!u)break;e.pendingFrameEvictedThroughTimestamp=Math.max(e.pendingFrameEvictedThroughTimestamp,a[0]),Tl(e,a[0]),e.pendingFrameEvictionCount+=1}}function Tw(e,t,a,r,c,u=performance.now()){Tl(e,t);const p={frame:a,queuedAt:u,queueSize:r,encodedByteLength:Math.max(0,Math.floor(Number(a.payload.byteLength||0))),paintIsCancelled:c};e.pendingFrames.set(t,p),e.pendingFrameBytes+=p.encodedByteLength,Pl(e,u),e.pendingFrameHighWaterMark=Math.max(e.pendingFrameHighWaterMark,e.pendingFrames.size),e.pendingFrameByteHighWaterMark=Math.max(e.pendingFrameByteHighWaterMark,e.pendingFrameBytes)}function Ig(e,t){if(t.pendingTrimTimer!==null||t.pendingFrames.size===0)return;const a=t.pendingFrames.values().next().value;if(!a)return;const r=Math.max(1,Wd-(performance.now()-a.queuedAt)+1);t.pendingTrimTimer=window.setTimeout(()=>{t.pendingTrimTimer=null,jt.get(e)===t&&(Pl(t),Ig(e,t))},r)}function Tg(e){return ko.delete(e)?(Es+=1,Ns("hardware-release",e),!0):!1}function Pw(e,t,a){if(t!=="prefer-hardware"||!a)return!1;const r=Ta.get(e);return!r||r.requested!==t||r.actual!=="prefer-software"||Es<=r.failedHardwareReleaseGeneration?!1:(Ta.delete(e),Mo.delete(e),wg+=1,Sg=Date.now(),!0)}function Ad(e,t=ta.h264DecodeAcceleration){const a=Ta.get(e);return a?.requested===t?(a.actual!=="prefer-hardware"&&(ko.delete(e),Mo.add(e)),a.actual):(a&&(Ta.delete(e),Mo.delete(e)),t!=="prefer-hardware"?(Tg(e),Mo.delete(e),t):(ko.has(e)||ko.add(e),"prefer-hardware"))}function El(e,t,a){if(t!=="prefer-hardware")return!1;const r=Ta.get(e),c=jt.get(e),u=Date.now();return ki.has(e)||ki.set(e,gg++),Ta.set(e,{requested:t,actual:"prefer-software",reason:a,failedAt:u,failureCount:(r?.requested===t?r.failureCount:0)+1,codec:c?.codec||r?.codec||"",latencyMode:c?.latencyMode||r?.latencyMode||"smooth",inputCount:c?.inputSerial??r?.inputCount??0,outputCount:c?.outputSerial??r?.outputCount??0,lastInputAt:c?.lastInputAt??r?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??r?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??r?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(c?.decodeQueueHighWaterMark??0,r?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(c?.decodeQueueOverflowSamples??0,r?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:c?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-c.decodeQueueOverflowStartedAt):r?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:Es}),ko.delete(e),Mo.add(e),Cg+=1,kg=a,Mg=u,!0}function Pa(e){e.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(e.interactivePipelineFallbackTimer),e.interactivePipelineFallbackTimer=null),e.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(e.interactivePipelineFallbackFrame),e.interactivePipelineFallbackFrame=null),e.interactivePipelineRecoveryFrames=[],e.interactivePipelineRecoveryBytes=0,e.interactivePipelinePaintIsCancelled=void 0,e.interactivePipelineGuardTimestampUs=null}function Pg(e,t){const a=t.interactivePipelineRecoveryFrames,r=t.interactivePipelinePaintIsCancelled,c=t.onBeforePaint,u=t.onPaint;if(Pa(t),a.length===0||r?.()||jt.get(e)!==t||t.hardwareAcceleration!=="prefer-hardware"||!El(e,t.requestedAcceleration,"interactive-pipeline-latency"))return!1;const p=t.requestedAcceleration,h=t.latencyMode;Tn(e);try{for(const f of a)zd(e,f,u,p,h,r,!1,c)}catch{Tn(e)}return!0}function Ew(e,t,a){const r=Math.max(0,Number(t.payload.byteLength||0));return e.interactivePipelineRecoveryFrames.length>=hw||e.interactivePipelineRecoveryBytes+r>gw?(Pa(e),!1):(e.interactivePipelineRecoveryFrames.push({...t,payload:t.payload.slice()}),e.interactivePipelineRecoveryBytes+=r,e.interactivePipelinePaintIsCancelled=a,!0)}function Nw(e,t,a,r,c=performance.now()){const u=()=>{if(!(jt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==a)){if(!t.pendingFrames.has(a)){Pa(t);return}Pg(e,t)}},p=h=>{if(t.interactivePipelineFallbackFrame=null,!(jt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==a)){if(!t.pendingFrames.has(a)){Pa(t);return}if(h-c>=r){u();return}t.interactivePipelineFallbackFrame=window.requestAnimationFrame(p)}};t.interactivePipelineFallbackTimer=window.setTimeout(u,r),t.interactivePipelineFallbackFrame=window.requestAnimationFrame(p)}function Fw(e,t,a,r=64){try{let c=Md.get(e);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Md.set(e,c));const u=Math.max(8,Math.min(64,Math.round(r))),p=Math.max(1,Math.round(u*Math.max(1,a)/Math.max(1,t)));(c.canvas.width!==u||c.canvas.height!==p)&&(c.canvas.width=u,c.canvas.height=p);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(e,0,0,Math.max(1,t),Math.max(1,a),0,0,u,p);const f=h.getImageData(0,0,u,p).data;let k=2166136261;for(let T=0;T<f.length;T+=4)k^=f[T],k=Math.imul(k,16777619),k^=f[T+1],k=Math.imul(k,16777619),k^=f[T+2],k=Math.imul(k,16777619);const M=(k>>>0).toString(16).padStart(8,"0"),b=!c.initialized||M!==c.lastHash;return c.initialized=!0,c.lastHash=M,{visualHash:M,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function Id(e,t,a,r=$d,c=64,u){if(!xw&&u)return Eg(e,u);let p=xd.get(e);p||(p={lastHash:"",initialized:!1,lastCanvasSampleAt:0},xd.set(e,p));const h=performance.now();if(p.initialized&&r>0&&h-p.lastCanvasSampleAt<r)return{visualHash:p.lastHash,visualChanged:!1};const f=Fw(e,t,a,c);return p.initialized=!0,p.lastHash=f.visualHash,p.lastCanvasSampleAt=h,f}function Eg(e,t){let a=Cl.get(e);a||(a={lastHash:"",initialized:!1},Cl.set(e,a));const r=String(t.contentHash||""),c=!a.initialized||!r||r!==a.lastHash;return a.initialized=!0,a.lastHash=r,{visualHash:r,visualChanged:c}}function Ng(e,t,a=!1){const r=kd.get(e);if(r)return r;const c=e.getContext("2d",{alpha:!1,desynchronized:t==="interactive",willReadFrequently:a});if(c){const u=c.getContextAttributes?.(),p={context:c,presentation:u?.desynchronized?"desync":"sync"};return kd.set(e,p),p}return null}function Dw(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),a=String(e.compression||"").toLowerCase(),r=String(e.mimeType||"").toLowerCase();return t==="mode2-lzo"||a==="lzo1x"||r==="application/vnd.livedesk.lzo-rgb565"||t==="mode2-lz4"||String(e.compression||"").toLowerCase()==="lz4"||r==="application/vnd.livedesk.lz4-raw"}function Lw(e){return String(e.frameMode||e.mode||"").toLowerCase()==="mode3-h264-hw"||String(e.codec||"").toLowerCase()==="h264"||String(e.mimeType||"").toLowerCase()==="video/h264"}function Ow(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),a=String(e.mimeType||"").toLowerCase();return t==="mode5-lzo-delta"||a==="application/vnd.livedesk.lzo-rgb565-delta"}function hf(e,t,a){let r=a,c=t;if(r===15){let u=255;for(;u===255;){if(c>=e.length)throw new Error("Invalid LZ4 block: length overrun.");u=e[c],c+=1,r+=u}}return{length:r,cursor:c}}function _w(e,t){const a=new Uint8Array(t);let r=0,c=0;for(;r<e.length;){const u=e[r];r+=1;const p=hf(e,r,u>>4);r=p.cursor;const h=p.length;if(r+h>e.length||c+h>a.length)throw new Error("Invalid LZ4 block: literal overrun.");if(a.set(e.subarray(r,r+h),c),r+=h,c+=h,r>=e.length)break;if(r+2>e.length)throw new Error("Invalid LZ4 block: missing offset.");const f=e[r]|e[r+1]<<8;if(r+=2,f<=0||f>c)throw new Error("Invalid LZ4 block: bad match offset.");const k=hf(e,r,u&15);r=k.cursor;const M=k.length+4;if(c+M>a.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-f;for(let T=0;T<M;T+=1)a[c]=a[b],c+=1,b+=1}if(c!==a.length)throw new Error("Invalid LZ4 block: incomplete output.");return a}function jw(e){const t=Math.max(1,Math.floor(e.width||0)),a=Math.max(1,Math.floor(e.height||0)),r=String(e.compression||"").toLowerCase(),c=String(e.pixelFormat||e.codec||"").toLowerCase();if(r==="lzo1x"||String(e.frameMode||e.mode||"").toLowerCase()==="mode2-lzo"||String(e.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const M=Math.max(1,Math.floor(e.bytesPerPixel||2)),b=t*a*2,T=Math.floor(e.uncompressedByteLength||b);if(M!==2||T!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${T} for ${t}x${a}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const I=sg(e.payload,b),x=new Uint8ClampedArray(t*a*4);for(let E=0,H=0;E<I.length;E+=2,H+=4){const Q=I[E]|I[E+1]<<8,G=Q>>11&31,ne=Q>>5&63,ae=Q&31;x[H]=G<<3|G>>2,x[H+1]=ne<<2|ne>>4,x[H+2]=ae<<3|ae>>2,x[H+3]=255}return new ImageData(x,t,a)}const p=Math.max(1,Math.floor(e.bytesPerPixel||4)),h=Math.max(t*a*p,Math.floor(e.uncompressedByteLength||0)),f=_w(e.payload,h);if(p!==4)throw new Error(`Unsupported mode2 pixel size: ${p}`);const k=new Uint8ClampedArray(t*a*4);if(c==="rgba32"||c==="rgba")k.set(f.subarray(0,k.length));else for(let M=0,b=0;b<k.length;M+=4,b+=4)k[b]=f[M+2],k[b+1]=f[M+1],k[b+2]=f[M],k[b+3]=f[M+3];return new ImageData(k,t,a)}function gf(e,t="smooth",a=ta.h264DecodeAcceleration){const r=window.VideoDecoder;if(!r||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=jt.get(e);if(c&&c.decoder.state!=="closed"&&c.latencyMode===t)return c;c&&Tn(e);let u;const p=new r({output:h=>{if(jt.get(e)!==u){h.close();return}const f=Number(h.timestamp||0),k=performance.now();u.outputSerial+=1,Pl(u,k);let M=Tl(u,f);if(!M&&f>u.pendingFrameEvictedThroughTimestamp&&u.pendingFrames.size>0&&(M=Iw(u),u.timestampFallbacks+=1),!M){u.pendingFrameUnmatchedOutputCount+=1,u.droppedForLatency+=1,u.lastOutputAt=k,h.close();return}const b=u.interactivePipelineGuardTimestampUs===f;if(Rg(M)){b&&Pa(u),u.droppedForLatency+=1,u.lastOutputAt=k,h.close();return}const T=h.displayWidth||h.codedWidth||e.width||960,I=h.displayHeight||h.codedHeight||e.height||540,x=Number(M?.frame.durationUs||0),E=Number(h.duration||0),H=Math.max(16,Math.min(250,(x>0?x:E||83333)/1e3));u.targetPaintIntervalMs=H;const Q=Math.max(0,k-M.queuedAt),ne=xg(M.frame,x>0?x:Math.round(H*1e3))?mg:dg;if(u.latencyMode==="interactive"&&u.hardwareAcceleration==="prefer-hardware"&&b&&u.interactivePipelineRecoveryFrames.length>0&&Q>ne){h.close(),u.droppedForLatency+=1,Pg(e,u);return}b&&Pa(u),Math.abs(u.interactiveBurstOutputCadenceMs-H)>1&&(u.interactiveBurstOutputTimeCursor=0,u.interactiveBurstOutputTimeCount=0,u.interactiveBurstOutputCadenceMs=H,u.interactiveBurstOutputWindowMs=0),u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]=k,u.interactiveBurstOutputTimeCursor=(u.interactiveBurstOutputTimeCursor+1)%bi,u.interactiveBurstOutputTimeCount=Math.min(bi,u.interactiveBurstOutputTimeCount+1);const ae=u.interactiveBurstOutputTimeCount>=bi?k-u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]:0;for(u.interactiveBurstOutputWindowMs=Math.max(0,ae),u.decodedFrames.push({videoFrame:h,pending:M,decodedAt:k,width:T,height:I,durationMs:H}),u.latencyMode==="interactive"&&u.targetPaintIntervalMs>20&&u.interactiveBurstOutputTimeCount>=bi&&ae<=Math.min(kw,Math.max(Cw,u.targetPaintIntervalMs-5))&&(u.interactiveBurstTailHoldArmed=!0),u.lastOutputAt=k;u.decodedFrames.length>Vd(u);)kl(u,u.decodedFrames.shift(),"capacity");u.renderQueueHighWaterMark=Math.max(u.renderQueueHighWaterMark,u.decodedFrames.length),Dg(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>Sw&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=lg&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),Ml(e,u)},error:()=>{jt.get(e)===u&&(El(e,u.requestedAcceleration,"decoder-error"),Tn(e))}});return bg+=1,ki.has(e)||ki.set(e,gg++),u={decoder:p,configured:!1,configKey:"",codec:"",requestedAcceleration:a,hardwareAcceleration:Ad(e,a),latencyMode:t,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,pendingFrameBytes:0,pendingFrameHighWaterMark:0,pendingFrameByteHighWaterMark:0,pendingFrameEvictionCount:0,pendingFrameUnmatchedOutputCount:0,pendingFrameEvictedThroughTimestamp:-1,pendingTrimTimer:null,decodedFrames:[],renderQueueHighWaterMark:0,renderQueueCapacityDropCount:0,renderQueueAgeDropCount:0,renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array(bi),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 0,interactiveBackingWidth:0,interactiveBackingHeight:0,interactiveBackingSourceWidth:0,interactiveBackingSourceHeight:0,interactiveBackingMeasuredAt:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0,decodeQueueHighWaterMark:0,decodeQueueOverflowStartedAt:0,decodeQueueOverflowSamples:0},jt.set(e,u),xo.add(e),Rd=Math.max(Rd,xo.size),Ns("create",e),u}function Fg(e){Pa(e),e.renderTimer!==null&&(window.cancelAnimationFrame(e.renderTimer),e.renderTimer=null),e.renderScheduledAt=0,e.flushTimer!==null&&(window.clearTimeout(e.flushTimer),e.flushTimer=null),e.flushInFlight=!1;const t=e.decodedFrames;e.decodedFrames=[];for(const a of t)try{a.videoFrame.close()}catch{}e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.interactiveBurstTailHoldArmed=!1,e.interactiveBurstOutputTimeCursor=0,e.interactiveBurstOutputTimeCount=0,e.interactiveBurstOutputCadenceMs=0,e.interactiveBurstOutputWindowMs=0}function kl(e,t,a="other"){t&&(t.videoFrame.close(),e.droppedForLatency+=1,a==="capacity"?e.renderQueueCapacityDropCount+=1:a==="age"&&(e.renderQueueAgeDropCount+=1))}function Vd(e){return e.latencyMode==="interactive"?e.targetPaintIntervalMs<=20?ow:bi:String(e.decodedFrames[0]?.pending?.frame.frameMode||e.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?aw:lg}function Dg(e,t=performance.now()){const a=Vd(e);for(;e.decodedFrames.length>a;)kl(e,e.decodedFrames.shift(),"capacity");const r=e.latencyMode==="interactive"?ug:lw;let c=e.decodedFrames[0];for(;e.decodedFrames.length>0&&c&&t-c.decodedAt>r;)kl(e,e.decodedFrames.shift(),"age"),c=e.decodedFrames[0]}function Lg(e,t){if(t.hardwareAcceleration!=="prefer-hardware"||t.latencyMode==="interactive"||t.flushTimer!==null||t.flushInFlight)return;const a=dw;t.flushTimer=window.setTimeout(async()=>{t.flushTimer=null;const r=performance.now();if(Pl(t,r),jt.get(e)!==t||t.decoder.state!=="configured"||t.pendingFrames.size===0||t.inputSerial<=t.lastFlushInputSerial||t.lastOutputAt>0&&r-t.lastOutputAt<a)return;const c=t.inputSerial;t.flushInFlight=!0,t.flushCount+=1,t.keyFrameSeen=!1;try{await t.decoder.flush(),t.lastFlushInputSerial=Math.max(t.lastFlushInputSerial,c)}catch{jt.get(e)===t&&bl(t)}finally{t.flushInFlight=!1,jt.get(e)===t&&t.inputSerial>c&&t.pendingFrames.size>0&&performance.now()-t.lastOutputAt>=a&&Lg(e,t)}},a)}function Bw(e,t,a,r){const c=performance.now();if(t.interactiveBackingWidth>0&&t.interactiveBackingHeight>0&&c-t.interactiveBackingMeasuredAt<rw)return{width:Math.min(a,t.interactiveBackingWidth),height:Math.min(r,t.interactiveBackingHeight)};const u=typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect():{width:Number(e.clientWidth||e.width||0),height:Number(e.clientHeight||e.height||0)},p=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),h=Math.max(0,Number(e.width||0)),f=Math.max(0,Number(e.height||0)),k=u.width>0?Math.round(u.width*p):h||pf,M=u.height>0?Math.round(u.height*p):f||ff,b=Math.min(1,k/a,M/r),T=Math.min(1,Math.max(pf/a,ff/r)),I=Math.min(1,tw/a,nw/r),x=Math.max(.01,Math.min(I,Math.max(T,b)));return t.interactiveBackingWidth=Math.max(1,Math.round(a*x)),t.interactiveBackingHeight=Math.max(1,Math.round(r*x)),t.interactiveBackingMeasuredAt=c,{width:t.interactiveBackingWidth,height:t.interactiveBackingHeight}}function bf(e,t,a){const r=performance.now();try{if(!a.pending||Rg(a.pending)){t.droppedForLatency+=1;return}let c=1;try{const M=t.onBeforePaint?.(a.pending.frame);typeof M=="number"&&Number.isFinite(M)&&(c=Math.max(.05,Math.min(1,M)))}catch{}const u=t.latencyMode==="interactive"?Bw(e,t,a.width,a.height):{width:a.width,height:a.height},p=u.width,h=u.height,f=e.width!==p||e.height!==h;f&&(e.width=p,e.height=h);const k=Ng(e,t.latencyMode,t.hardwareAcceleration==="prefer-software");if(k){const M=k.context.globalAlpha;k.context.globalAlpha=f||t.lastPaintAt<=0||t.hardwareAcceleration!=="prefer-hardware"?1:c;try{k.context.drawImage(a.videoFrame,0,0,a.width,a.height,0,0,p,h)}finally{k.context.globalAlpha=M}}if(a.pending){const M=performance.now(),T=t.latencyMode==="interactive"?Eg(e,a.pending.frame):Id(e,a.width,a.height,$d,64,a.pending.frame),I=Aw(a.pending.frame);try{t.onPaint?.(I,{deviceId:I.deviceId,frameSeq:I.frameSeq,mode:I.frameMode||I.mode||I.codec||I.mimeType,width:a.width,height:a.height,byteLength:I.byteLength,queuedForMs:Math.max(0,r-a.pending.queuedAt),decodedForMs:Math.max(0,a.decodedAt-a.pending.queuedAt),scheduledForMs:Math.max(0,r-a.decodedAt),drawMs:Math.max(0,M-r),queueSize:a.pending.queueSize,renderQueueSize:t.decodedFrames.length,droppedForLatency:t.droppedForLatency,h264DecodeAcceleration:t.hardwareAcceleration,decoderLabel:t.hardwareAcceleration,decoderFlushCount:t.flushCount,decoderTimestampFallbacks:t.timestampFallbacks,decoderInputCount:t.inputSerial,decoderOutputCount:t.outputSerial,targetPaintIntervalMs:t.targetPaintIntervalMs,canvasPresentation:k?.presentation||"sync",interactiveBufferWaitCount:t.interactiveBufferWaitCount,interactiveBufferWaitMs:t.interactiveBufferWaitMs,interactiveQueueDrainCount:t.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:t.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:t.interactiveBurstTailHoldCount,visualHash:T.visualHash,visualChanged:T.visualChanged,paintedAt:M})}catch{}}t.lastPaintAt=performance.now()}finally{a.videoFrame.close()}}function Ml(e,t){if(t.renderTimer!==null||t.decodedFrames.length===0)return;const a=Math.max(16,Math.min(250,t.targetPaintIntervalMs||1e3/12)),r=()=>{if(t.renderTimer=null,t.renderScheduledAt=0,t.decodedFrames.length===0)return;const c=performance.now();if(Dg(t,c),t.decodedFrames.length===0){t.interactiveBurstTailHoldArmed=!1;return}if(t.latencyMode==="interactive"){const f=t.targetPaintIntervalMs<=20;if(f&&!t.interactiveBufferPrimed){t.interactiveBufferStartedAt<=0&&(t.interactiveBufferStartedAt=c,t.interactiveBufferWaitCount+=1);const M=t.decodedFrames.length>=iw,b=c-t.interactiveBufferStartedAt>=sw;if(!M&&!b){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}t.interactiveBufferWaitMs+=Math.max(0,c-t.interactiveBufferStartedAt),t.interactiveBufferPrimed=!0}else f||(t.interactiveBufferPrimed=!0);if(!f&&t.interactiveBurstTailHoldArmed&&t.decodedFrames.length===1&&c-t.decodedFrames[0].decodedAt<=ug-Mw){t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstTailHoldCount+=1,t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}const k=t.decodedFrames.shift();if(k)try{bf(e,t,k)}catch{}t.decodedFrames.length===0&&(t.interactiveQueueDrainCount+=1,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1),Ml(e,t);return}const u=t.lastPaintAt>0?t.lastPaintAt+a:c+cw;if(!(c+uw>=u||t.decodedFrames.length>=Math.max(1,Vd(t)-1))){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}const h=t.decodedFrames.shift();if(h)try{bf(e,t,h)}catch{}Ml(e,t)};t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r)}function Og(e,t){if(jt.get(e)!==t||t.decoder.state==="closed")return!1;for(t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0;t.decodedFrames.length>1;)kl(t,t.decodedFrames.shift());return t.lastPaintAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0,Ml(e,t),!0}function Yu(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const e of xo){const t=jt.get(e);if(!t||t.decoder.state==="closed"){xo.delete(e);continue}Og(e,t)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Yu),window.addEventListener("focus",Yu),window.addEventListener("pageshow",Yu));function Tn(e){Tg(e),xo.delete(e),Cl.delete(e);const t=jt.get(e);if(t){jt.delete(e),vg+=1,Ag(t),t.onBeforePaint=void 0,t.onPaint=void 0,Fg(t);try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}try{t.decoder.state!=="closed"&&t.decoder.close()}catch{}Ns("close",e)}}function pi(e){e&&(Ta.delete(e),Mo.delete(e),kd.delete(e),xd.delete(e),Md.delete(e),Cl.delete(e),Is.delete(e),Tn(e))}function Hw(e,t){const a=jt.get(e),r=Ta.get(e);if(!a&&!r)return null;const c=p=>p>0?Math.max(0,t-p):void 0,u=a?.pendingFrames.values().next().value;return{canvasId:ki.get(e)||0,canvasWidth:Math.max(0,Number(e.width||0)),canvasHeight:Math.max(0,Number(e.height||0)),decoderState:a?.decoder.state||"fallback-pending",configured:a?.configured||!1,keyFrameSeen:a?.keyFrameSeen||!1,codec:a?.codec||r?.codec||"",requestedAcceleration:a?.requestedAcceleration||r?.requested||ta.h264DecodeAcceleration,configuredAcceleration:a?.hardwareAcceleration||r?.actual||ta.h264DecodeAcceleration,latencyMode:a?.latencyMode||r?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(a?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(a?.decodeQueueHighWaterMark??0),Number(r?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(a?.decodeQueueOverflowSamples??0),Number(r?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:a?.decodeQueueOverflowStartedAt?Math.max(0,t-a.decodeQueueOverflowStartedAt):r?.decodeQueueOverflowAgeMs,pendingFrameCount:a?.pendingFrames.size||0,pendingFrameBytes:a?.pendingFrameBytes||0,pendingFrameHighWaterMark:a?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:a?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:a?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:a?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:u?Math.max(0,t-u.queuedAt):void 0,pendingFrameMaxCount:pg,pendingFrameMaxBytes:fg,pendingFrameMaxAgeMs:Wd,renderQueueSize:a?.decodedFrames.length||0,renderQueueHighWaterMark:a?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:a?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:a?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:a?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(a?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(a?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(a?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(a?.droppedForLatency||0)),inputCount:a?.inputSerial??r?.inputCount??0,outputCount:a?.outputSerial??r?.outputCount??0,lastInputAgeMs:c(a?.lastInputAt??r?.lastInputAt??0),lastOutputAgeMs:c(a?.lastOutputAt??r?.lastOutputAt??0),lastPaintAgeMs:c(a?.lastPaintAt??r?.lastPaintAt??0),softwareFallbackReason:r?.reason,softwareFallbackAt:r?.failedAt,softwareFallbackCount:r?.failureCount||0}}function el(e,t={}){const a=performance.now(),c=(e?[e]:[...new Set([...xo,...Mo])]).map(h=>Hw(h,a)).filter(h=>h!==null),u=c.reduce((h,f)=>h+f.pendingFrameCount,0),p=c.reduce((h,f)=>h+f.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:c.filter(h=>h.decoderState!=="fallback-pending").length,hardwareLeaseCount:ko.size,hardwareReleaseGeneration:Es,hardwareRecoveryProbeCount:wg,lastHardwareRecoveryProbeAt:Sg,activeSoftwareFallbackCount:c.filter(h=>h.configuredAcceleration==="prefer-software"&&h.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:bg,decoderCloseCount:vg,activeDecoderHighWaterMark:Rd,decoderLifecycleSequence:yg,decoderLifecycleEvents:t.includeLifecycleEvents===!1?[]:vs.map(h=>({...h})),softwareFallbackEventCount:Cg,lastSoftwareFallbackReason:kg,lastSoftwareFallbackAt:Mg,pendingFrameCount:u,pendingFrameBytes:p,canvases:c}}function bl(e,t=1){try{e.decoder.state!=="closed"&&e.decoder.reset()}catch{}e.configured=!1,e.configKey="",e.keyFrameSeen=!1,Ag(e),Fg(e),e.lastPaintAt=0,e.lastOutputAt=0,e.lastInputAt=0,e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.lastInputFrameSeq=void 0,e.nextChunkTimestampUs=0,e.healthSampleStartedAt=performance.now(),e.healthInputSerial=e.inputSerial,e.healthOutputSerial=e.outputSerial,e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,e.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t)))}function Ww(e,t,a=performance.now()){const r=Math.max(0,Number.isFinite(t)?t:0);if(e.decodeQueueHighWaterMark=Math.max(e.decodeQueueHighWaterMark,r),r<=bw)return e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,!1;e.decodeQueueOverflowStartedAt<=0?(e.decodeQueueOverflowStartedAt=a,e.decodeQueueOverflowSamples=1):e.decodeQueueOverflowSamples+=1;const c=Math.max(0,a-e.decodeQueueOverflowStartedAt);return r>=vw||e.decodeQueueOverflowSamples>=ww&&c>=yw}function $w(e,t,a,r,c,u){t.decoder.configure(a),t.configured=!0,t.configKey=r,t.codec=a.codec,t.requestedAcceleration=u,t.hardwareAcceleration=c,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0,Ns("configure",e)}function Vw(e,t){if(t.latencyMode!=="interactive"||t.hardwareAcceleration!=="prefer-hardware")return!1;const a=performance.now();if(a-t.healthSampleStartedAt<mw)return!1;const r=t.inputSerial-t.healthInputSerial,c=t.outputSerial-t.healthOutputSerial;return t.healthSampleStartedAt=a,t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,r<pw||c/Math.max(1,r)>=fw?!1:(El(e,t.requestedAcceleration,"interactive-health"),Tn(e),!0)}function fi(e,t=1){if(!e)return!1;const a=jt.get(e);return a?(a.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t))),Tn(e),!0):!1}function zw(e){if(!e)return!1;const t=jt.get(e);return t?Og(e,t):!1}function Uw(e,t,a,r="interactive",c){Tn(e);const u=performance.now(),p=Jy(t.payload,t.uncompressedByteLength||0),h=String(t.streamId||"mode5");let f=Is.get(e);if(!f||f.streamId!==h||f.width!==p.width||f.height!==p.height){const H=new Uint8ClampedArray(p.width*p.height*4);for(let Q=3;Q<H.length;Q+=4)H[Q]=255;f={streamId:h,width:p.width,height:p.height,rgba:H,imageData:new ImageData(H,p.width,p.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Is.set(e,f)}if(!f)throw new Error("Mode 5 canvas state could not be initialized.");f.inputSerial+=1;const M=Number(t.streamFrameSeq||0);if(M>0&&(f.lastStreamFrameSeq=M),!p.keyFrame&&!f.keyFrameSeen)return;p.keyFrame&&(f.keyFrameSeen=!0);const b=Zy(f.rgba,f.width,f.height,p),T=performance.now();try{c?.(t)}catch{}(e.width!==f.width||e.height!==f.height)&&(e.width=f.width,e.height=f.height);const I=Ng(e,r),x=performance.now();b&&I?.context.putImageData(f.imageData,0,0,b.x,b.y,b.width,b.height);const E=performance.now();f.outputSerial+=1,a?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.mimeType,width:f.width,height:f.height,byteLength:t.byteLength,queuedForMs:Math.max(0,E-u),decodedForMs:Math.max(0,T-u),scheduledForMs:0,drawMs:Math.max(0,E-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:f.inputSerial,decoderOutputCount:f.outputSerial,targetPaintIntervalMs:Math.max(1,Number(t.durationUs||0)/1e3||1e3/30),canvasPresentation:I?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(t.contentHash||""),visualChanged:Number(t.deltaVisualTileCount||0)>0,paintedAt:E})}const Qu=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function vf(e,t){for(let a=Math.max(0,t);a+3<e.length;a+=1)if(!(e[a]!==0||e[a+1]!==0)){if(e[a+2]===1)return{index:a,length:3};if(e[a+2]===0&&e[a+3]===1)return{index:a,length:4}}return null}function qw(e){let t=0;for(;t<e.length;){const a=vf(e,t);if(!a)break;const r=a.index+a.length,c=vf(e,r),u=c?.index??e.length;if(r<u&&(e[r]&31)===7){const p=[];let h=0;for(let f=r+1;f<u;f+=1){const k=e[f];if(h>=2&&k===3){h=0;continue}p.push(k),h=k===0?h+1:0}if(p.length>=3)return`avc1.${p.slice(0,3).map(f=>f.toString(16).toUpperCase().padStart(2,"0")).join("")}`}t=c?c.index:e.length}return""}function Gw(e,t,a,r,c=""){const u=Math.ceil(e/16)*Math.ceil(t/16),p=a>0?1e6/a:30,h=u*p,f=Qu.find(k=>u<=k.maxFrameSize&&h<=k.maxMacroblocksPerSecond)||Qu[Qu.length-1];return qw(r)||c||`avc1.42E0${f.code.toString(16).toUpperCase().padStart(2,"0")}`}function zd(e,t,a,r,c="smooth",u=()=>!1,p=!0,h){Is.delete(e);const f=String(t.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",k=Math.max(1,Math.floor(t.width||960)),M=Math.max(1,Math.floor(t.height||540)),b=Math.max(1,Math.floor(t.durationUs||1e6/12)),T=r||ta.h264DecodeAcceleration,I=t.isKeyFrame===!0||String(t.chunkType||"").toLowerCase()==="key";Pw(e,T,I);let x=gf(e,c,T);const E=Gw(k,M,b,t.payload,x.codec);let H=Ad(e,T),Q="";const G=()=>{Q=[t.streamId||"",t.commandId||"",k,M,E,f,T,H,c].join("|")};G(),x.onBeforePaint=h,x.onPaint=a,x.configured&&x.decoder.state!=="configured"&&(x.configured=!1,x.configKey=""),x.configured&&x.configKey!==Q&&(Tn(e),x=gf(e,c,T),x.onBeforePaint=h,x.onPaint=a,H=Ad(e,T),G());const ne=()=>({codec:E,codedWidth:k,codedHeight:M,hardwareAcceleration:H,optimizeForLatency:!0,avc:{format:f}}),ae=P=>x.hardwareAcceleration!=="prefer-hardware"||!El(e,x.requestedAcceleration,P)?!1:(Tn(e),p&&I&&zd(e,t,a,T,c,u,!1,h),!0),O=()=>{try{return $w(e,x,ne(),Q,H,T),!0}catch(P){if(ae("configure-error"))return!1;throw Tn(e),P}};if(!x.configured&&!O())return;const te=Number(t.streamFrameSeq||0);if(te>0&&x.lastInputFrameSeq!==void 0&&(te<=x.lastInputFrameSeq&&(!I||te===x.lastInputFrameSeq||(bl(x,x.lastInputFrameSeq-te+1),!O()))||te>x.lastInputFrameSeq+1&&(bl(x,te-x.lastInputFrameSeq-1),!I||!O()))||(te>0&&(x.lastInputFrameSeq=te),!I&&!x.keyFrameSeen))return;I&&(x.keyFrameSeen=!0);const Z=Number(x.decoder.decodeQueueSize||0);if(Ww(x,Z)){if(x.latencyMode==="interactive"&&x.hardwareAcceleration==="prefer-hardware"){ae("decode-queue-overflow");return}if(bl(x),!I||!O())return;x.keyFrameSeen=!0}const me=x.nextChunkTimestampUs;x.nextChunkTimestampUs+=b,Tw(x,me,t,Z,u),Ig(e,x),x.inputSerial+=1,x.lastInputAt=performance.now(),x.inputSerial===1&&Ns("first-input",e);const le=t.payload.buffer,pe=le instanceof ArrayBuffer?[le]:[],se=xg(t,b),W=!se&&x.outputSerial>0,re=I&&x.latencyMode==="interactive"&&x.hardwareAcceleration==="prefer-hardware"&&(se||W),L=se?mg:dg;re&&(Pa(x),x.interactivePipelineGuardTimestampUs=me);const _=x.interactivePipelineGuardTimestampUs!==null&&x.interactivePipelineRecoveryFrames.length>0,q=re||_?Ew(x,t,u):!1,ue=new EncodedVideoChunk({type:I?"key":"delta",timestamp:me,duration:b,data:t.payload,transfer:pe});t.payload=hg;try{x.decoder.decode(ue)}catch(P){if(ae("decode-error"))return;throw Tn(e),P}q&&jt.get(e)===x&&x.interactivePipelineGuardTimestampUs===me&&re&&Nw(e,x,me,L),Lg(e,x),Vw(e,x)}async function Xu(e,t,a,r,c,u="smooth",p=a,h){if(Ow(t)){a()||Uw(e,t,r,u,h);return}if(Lw(t)){a()||zd(e,t,r,c,u,p,!0,h);return}if(Is.delete(e),Dw(t)){Tn(e);const I=jw(t);if(a())return;try{h?.(t)}catch{}(e.width!==I.width||e.height!==I.height)&&(e.width=I.width,e.height=I.height);const x=e.getContext("2d"),E=performance.now();x?.putImageData(I,0,0);const H=performance.now(),Q=Id(e,I.width,I.height,$d,64,t);r?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:I.width,height:I.height,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,H-E),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ta.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:Q.visualHash,visualChanged:Q.visualChanged,paintedAt:H});return}Tn(e);const f=new Blob([t.payload],{type:t.mimeType}),k=await createImageBitmap(f);if(a()){k.close();return}const M=t.width||k.width||960,b=t.height||k.height||540;try{h?.(t)}catch{}(e.width!==M||e.height!==b)&&(e.width=M,e.height=b);const T=e.getContext("2d");if(T){const I=performance.now();T.clearRect(0,0,M,b),T.drawImage(k,0,0,M,b);const x=performance.now(),E=Id(e,M,b);r?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:M,height:b,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,x-I),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ta.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:E.visualHash,visualChanged:E.visualChanged,paintedAt:x})}k.close()}function Kw(e){queueMicrotask(e)}function Yw(e){return e?(e.width=0,e.height=0,!0):!1}function Nl(e,t){if(!e)return!1;try{t?.(e)}finally{Yw(e)}return!0}function Ud(e,t){if(!e||!t)return 0;const a=Math.max(0,Number(e.get(t)||0))+1;return e.set(t,a),a}function Qw(e,t){if(!e||!t)return 0;const a=Number(e.get(t)||0);return Number.isSafeInteger(a)&&a>0?a:Ud(e,t)}function yf(e,t){return Ud(e,t)}function wf(e,t,a){return!!e&&!!t&&Number(a)>0&&Number(e.get(t)||0)===Number(a)}function Xw(e,t,a){if(!e||!e.has(t))return!1;const r=e.get(t);return e.delete(t),Nl(r,a)}function Jw(e,t,a){const r=new Set;for(const c of e||[])if(c){for(const u of c.values())u&&r.add(u);c.clear()}for(const c of t||[])c&&r.add(c);for(const c of r)Nl(c,a);return r.size}function Zw(e,{isCurrent:t,dispose:a,schedule:r=Kw}){return!e||typeof t!="function"?!1:(r(()=>{t(e)||Nl(e,a)}),!0)}const eS=new Uint8Array(0);function So(e){if(!e||typeof e!="object")return e;const t=e.payload;return t instanceof Uint8Array&&t.byteLength===0?e:{...e,payload:eS}}function tS(e,t){const a=So(t);return e.set(t.deviceId,a),a}function nS(e,t){for(const[a,r]of t.entries())e.set(a,So(r));return t.clear(),new Map(e)}function tl(e){return!!e&&typeof e=="object"}function Ju(e){let t=e;return tl(t)&&"data"in t&&(t=t.data),tl(t)&&"session"in t&&(t=t.session),!tl(t)||typeof t.access_token!="string"||!t.access_token||!tl(t.user)||typeof t.user.id!="string"||!t.user.id?null:t}function ax(e){return e?.access_token?e.refresh_token?"":"refresh-token-required":"access-token-required"}const Sf=Object.freeze(["nativeCaptureTelemetryAvailable","nativeCaptureTelemetryVersion","nativeEncoderHardwareAccelerationKnown","nativeEncoderHardwareAccelerated","nativeEncoderHardwareQueryStatus","nativeCaptureDisplayId","nativeCaptureFps","nativeCompressionFps","nativeEncodedFps","nativeCaptureSampleCount","nativeEncodableFrameCount","nativeSkippedFrameCount","nativeCompressionOutputCount","nativeEncodedFrameCount","nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs","nativeCaptureResourceTelemetryAvailable","nativeCaptureTelemetryAt"]),rS=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function aS(e){return[String(e?.deviceId||""),String(e?.sessionId||""),String(e?.streamId||""),String(e?.commandId||""),String(Number(e?.captureGeneration||0)||0),String(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1),String(e?.streamPurpose||"")].join("\0")}function oS(e,t){return!!t&&String(e?.deviceId||"")===String(t.deviceId||"")&&String(e?.sessionId||"")===String(t.sessionId||"")&&String(e?.streamId||"")===String(t.streamId||"")&&String(e?.commandId||"")===String(t.commandId||"")&&(Number(e?.captureGeneration||0)||0)===(Number(t.captureGeneration||0)||0)&&(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1)===(Number.isFinite(Number(t.monitorIndex))?Number(t.monitorIndex):-1)&&String(e?.streamPurpose||"")===String(t.streamPurpose||"")}function iS(){return{ownerKey:"",values:Object.create(null)}}function Cf(e){e&&(e.ownerKey="",e.values=Object.create(null))}function sS(e,t,a){if(!e||!t||!oS(e,a))return!1;const r=aS(a);if(t.ownerKey!==r&&(t.ownerKey=r,t.values=Object.create(null)),e.nativeCaptureTelemetryAvailable===!1){for(const c of Sf)c!=="nativeCaptureTelemetryAvailable"&&(delete t.values[c],delete e[c]);return t.values.nativeCaptureTelemetryAvailable=!1,!0}if(e.nativeCaptureResourceTelemetryAvailable===!1)for(const c of rS)delete t.values[c],delete e[c];for(const c of Sf)Object.prototype.hasOwnProperty.call(e,c)?t.values[c]=e[c]:Object.prototype.hasOwnProperty.call(t.values,c)&&(e[c]=t.values[c]);return!0}const _g=new ArrayBuffer(0);function cS(e){return`${String(e?.streamId||"")}:${Number(e?.frameSeq||0)}`}function lS(e){return!e||typeof e!="object"||e.payload instanceof ArrayBuffer&&e.payload.byteLength===0?e:{...e,payload:_g}}function uS(){let e=null,t="";return{accept(a){e=lS(a)},publish(){const a=e;if(e=null,!a)return null;const r=cS(a);return r===t?null:(t=r,a)},clear(){e=null,t=""},inspect(){return{pending:e?1:0,pendingPayloadBytes:Number(e?.payload?.byteLength||0),publishedKey:t}}}}const dS=0,mS=1,kf=3,Mf=Object.freeze([750,1500,3e3,5e3]);function mn(e){return Math.max(0,Math.floor(Number(e)||0))}function Zn(e,t){return!t||t.active||t.socket!==null||t.audioContext!==null||t.reconnectTimer!==null||t.statsTimer!==null||t.scheduledSourceCount!==0||t.pendingDecodeCount!==0||t.workletNodeCount!==0||t.workletPortCount!==0||t.pcmRingCapacityBytes!==0||t.pcmRingBufferedBytes!==0||t.pendingWorkletPacketCount!==0||t.pendingWorkletPacketBytes!==0||t.retainedFrameCount!==0||t.retainedPayloadBytes!==0?!1:e.delete(t)}function pS(){const e=new Set;let t=null;const a={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},r=()=>{let c=0,u=0,p=0,h=0;for(const f of e){const k=Number(f.socket?.readyState);c+=f.socket&&k!==kf?1:0,u+=f.audioContext===null?0:1,p+=mn(f.workletNodeCount),h+=mn(f.workletPortCount)}a.ownerCount=Math.max(a.ownerCount,e.size),a.socketCount=Math.max(a.socketCount,c),a.audioContextCount=Math.max(a.audioContextCount,u),a.workletNodeCount=Math.max(a.workletNodeCount,p),a.workletPortCount=Math.max(a.workletPortCount,h)};return{createOwner({deviceId:c,socket:u,audioContext:p,reconnectTimer:h=null,statsTimer:f=null}){t=null;const k={deviceId:String(c||""),active:!0,socket:u||null,audioContext:p||null,reconnectTimer:h,statsTimer:f,scheduledSourceCount:0,pendingDecodeCount:0,workletNodeCount:0,workletPortCount:0,workletNodeCreateCount:0,pcmRingCapacityBytes:0,pcmRingBufferedBytes:0,pendingWorkletPacketCount:0,pendingWorkletPacketBytes:0,pendingWorkletPacketHighWater:0,pendingWorkletByteHighWater:0,retainedFrameCount:0,retainedPayloadBytes:0};return e.add(k),r(),k},recordTerminalFailure(c,u,p="playback"){return e.has(c)?(t={deviceId:c.deviceId,phase:String(p||"playback").slice(0,64),message:String(u||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(c){return e.has(c)?(c.active=!1,Zn(e,c)):!1},setSocket(c,u){return e.has(c)?(c.socket=u||null,r(),Zn(e,c)):!1},setAudioContext(c,u){return e.has(c)?(c.audioContext=u||null,r(),Zn(e,c)):!1},setReconnectTimer(c,u){return e.has(c)?(c.reconnectTimer=u??null,Zn(e,c)):!1},setStatsTimer(c,u){return e.has(c)?(c.statsTimer=u??null,Zn(e,c)):!1},setScheduledSourceCount(c,u){return e.has(c)?(c.scheduledSourceCount=mn(u),Zn(e,c)):!1},setPendingDecodeCount(c,u){return e.has(c)?(c.pendingDecodeCount=mn(u),Zn(e,c)):!1},setWorkletNode(c,u,p,h=c?.workletNodeCreateCount){return e.has(c)?(c.workletNodeCount=mn(u),c.workletPortCount=mn(p),c.workletNodeCreateCount=mn(h),r(),Zn(e,c)):!1},setPcmRing(c,u,p){return e.has(c)?(c.pcmRingCapacityBytes=mn(u),c.pcmRingBufferedBytes=Math.min(c.pcmRingCapacityBytes,mn(p)),Zn(e,c)):!1},setPendingWorkletPackets(c,u,p,h=c?.pendingWorkletPacketHighWater,f=c?.pendingWorkletByteHighWater){return e.has(c)?(c.pendingWorkletPacketCount=mn(u),c.pendingWorkletPacketBytes=mn(p),c.pendingWorkletPacketHighWater=Math.max(c.pendingWorkletPacketHighWater,mn(h)),c.pendingWorkletByteHighWater=Math.max(c.pendingWorkletByteHighWater,mn(f)),Zn(e,c)):!1},setRetainedFrame(c,u,p=0){return e.has(c)?(c.retainedFrameCount=mn(u),c.retainedPayloadBytes=mn(p),Zn(e,c)):!1},releaseIfDrained(c){return Zn(e,c)},hasOwner(c){return e.has(c)},snapshot(){const c=[...e].map(p=>{const h=Number(p.socket?.readyState),f=p.socket&&h!==kf?1:0;return{deviceId:p.deviceId,active:p.active,socketCount:f,openSocketCount:h===mS?1:0,connectingSocketCount:h===dS?1:0,audioContextCount:p.audioContext===null?0:1,reconnectTimerCount:p.reconnectTimer===null?0:1,statsTimerCount:p.statsTimer===null?0:1,scheduledSourceCount:p.scheduledSourceCount,pendingDecodeCount:p.pendingDecodeCount,workletNodeCount:p.workletNodeCount,workletPortCount:p.workletPortCount,workletNodeCreateCount:p.workletNodeCreateCount,pcmRingCapacityBytes:p.pcmRingCapacityBytes,pcmRingBufferedBytes:p.pcmRingBufferedBytes,pendingWorkletPacketCount:p.pendingWorkletPacketCount,pendingWorkletPacketBytes:p.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:p.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:p.pendingWorkletByteHighWater,retainedFrameCount:p.retainedFrameCount,retainedPayloadBytes:p.retainedPayloadBytes}}),u=p=>c.reduce((h,f)=>h+mn(f[p]),0);return{ownerCount:c.length,activeOwnerCount:c.filter(p=>p.active).length,socketCount:u("socketCount"),openSocketCount:u("openSocketCount"),connectingSocketCount:u("connectingSocketCount"),audioContextCount:u("audioContextCount"),reconnectTimerCount:u("reconnectTimerCount"),statsTimerCount:u("statsTimerCount"),scheduledSourceCount:u("scheduledSourceCount"),pendingDecodeCount:u("pendingDecodeCount"),workletNodeCount:u("workletNodeCount"),workletPortCount:u("workletPortCount"),workletNodeCreateCount:u("workletNodeCreateCount"),pcmRingCapacityBytes:u("pcmRingCapacityBytes"),pcmRingBufferedBytes:u("pcmRingBufferedBytes"),pendingWorkletPacketCount:u("pendingWorkletPacketCount"),pendingWorkletPacketBytes:u("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:u("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:u("pendingWorkletByteHighWater"),retainedFrameCount:u("retainedFrameCount"),retainedPayloadBytes:u("retainedPayloadBytes"),ownerHighWater:a.ownerCount,socketHighWater:a.socketCount,audioContextHighWater:a.audioContextCount,workletNodeHighWater:a.workletNodeCount,workletPortHighWater:a.workletPortCount,lastTerminalFailure:t,owners:c}}}}function fS(e){const t=Math.max(0,Math.floor(Number(e)||0));return Mf[Math.min(t,Mf.length-1)]}function hS({schedule:e=(c,u)=>setTimeout(c,u),cancel:t=c=>clearTimeout(c),onTimerChange:a=()=>{},onReconnect:r=()=>{}}={}){let c=null,u=null,p=null,h=0,f=!1;const k=()=>{if(p===null)return!1;const b=p;return p=null,t(b),a(null),!0},M={replaceSocket(b){return f||!b?!1:(c=b,u=null,!0)},isCurrent(b){return!f&&c===b},markHealthy(b){return M.isCurrent(b)?(h=0,!0):!1},isTerminalSocket(b){return f&&u===b},retireTerminalSocket(b){return M.isTerminalSocket(b)?(u=null,!0):!1},scheduleReconnect(b){if(!M.isCurrent(b)||p!==null)return!1;const T=fS(h);h+=1;let I=null;return I=e(()=>{if(p===I&&(p=null,a(null),!!M.isCurrent(b)))try{r(b)}catch{M.scheduleReconnect(b)}},T),p=I,a(I),!0},stop(){return f?!1:(f=!0,k(),u=c,c=null,!0)},inspect(){return Object.freeze({active:!f,hasSocket:c!==null,hasTerminalSocket:u!==null,reconnectTimerCount:p===null?0:1,reconnectAttempt:h})}};return M}function xf({reconnectOwner:e,lifecycleLedger:t,lifecycleOwner:a,socket:r}){const c=e?.isCurrent?.(r)===!0,u=e?.isTerminalSocket?.(r)===!0;return!c&&!u||u&&e.retireTerminalSocket(r)!==!0?"stale":(t?.setSocket?.(a,null),c?"current":"terminal")}const Ot=pS();function gS(){let e=Promise.resolve(),t=0,a=0,r=0;return{acquire(c){const u=++r;let p=!1,h=!1,f=!1,k;const M=new Promise(x=>{k=x}),b=Promise.resolve(e).catch(()=>{});e=b.then(()=>M);const T=()=>f?!1:(f=!0,p&&(t=Math.max(0,t-1)),k(),!0),I=b.then(async()=>{if(h||f)return T(),null;p=!0,t+=1,a=Math.max(a,t);try{return await c({ownerId:u,release:T})}catch(x){throw T(),x}});return{ownerId:u,ready:I,release:T,cancel(){h=!0,p||T()}}},snapshot(){return{activeOwnerCount:t,ownerHighWater:a,nextOwnerId:r}}}}const bS=gS(),Rf=1e3;function vS({enabled:e,now:t,lastPublishedAt:a,intervalMs:r=Rf}){if(!e)return!1;const c=Math.max(0,Number(t)||0),u=Math.max(0,Number(a)||0),p=Math.max(1,Number(r)||Rf);return u<=0||c-u>=p}const jg="livedesk-remote-audio-v1",yS=250,wS=160,Td=4;function SS(e){const t=String(e||"").toLowerCase();return t.includes("audio/pcm")||t.includes("f32le")||t.includes("s16le")}function Pd(e={},t={}){const a=String(t.deviceId||""),r=String(t.streamId||"");return!!a&&!!r&&String(e.deviceId||"")===a&&String(e.streamId||"")===r}function CS(e={},t={}){if(!Pd(e,t))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(t.lastFrameSeq)||0))};const a=Math.max(0,Math.floor(Number(e.frameSeq)||0)),r=Math.max(0,Math.floor(Number(t.lastFrameSeq)||0));return a>0&&a<=r?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:r}:{accepted:!0,reason:"",nextFrameSeq:a}}function kS(e={}){const t=String(e.capturePhase||"").toLowerCase(),a=String(e.backendKind||"").toLowerCase(),r=e.captureAlive===!0?!0:e.captureAlive===!1?!1:null,c=e.helperAlive===!0?!0:e.helperAlive===!1?!1:null,u=Math.max(0,Math.floor(Number(e.helperPid)||0)),p=a==="windows-wasapi-in-process",h=a==="macos-screencapturekit-helper"||a==="linux-system-audio-helper",f=p||h,k=e.helperRequired===!0?!0:e.helperRequired===!1?!1:h?!0:p?!1:null,M=k===!1?!0:k===!0?c===!0&&u>0:!1,b=t==="starting"||t==="capture-active-awaiting-current-pcm",T=t==="active"&&r===!0&&f&&M,I=t==="failed"||t==="stopped"||r===!1||t==="active"&&(!f||!M);let x="";return b?x="awaiting-current-pcm":!p&&!h?x="backend-unknown":t!=="active"?x=t?`phase-${t}`:"phase-unknown":r!==!0?x="capture-not-alive":k===!0&&c!==!0?x="external-helper-not-alive":k===!0&&u<=0&&(x="external-helper-pid-missing"),{capturePhase:t,backendKind:a,captureAlive:r,helperAlive:c,helperPid:u,helperRequired:k,inProcessBackend:p,externalHelperBackend:h,backendKnown:f,helperReady:M,awaitingCurrentPcm:b,healthy:T,failed:I,reason:x}}function Ea(e,t){const a=Math.floor(Number(e));return Number.isFinite(a)&&a>0?a:t}function qd(e={}){const t=Math.max(8e3,Math.min(192e3,Ea(e.sampleRate,48e3))),a=Math.max(1,Math.min(8,Ea(e.channels,2))),r=String(e.mimeType||"").toLowerCase(),u=String(e.sampleFormat||"").toLowerCase()==="s16le"||r.includes("s16le")||r.includes("audio/l16")?"s16le":"f32le";return{sampleRate:t,channels:a,sampleFormat:u}}function Gd(e={}){const t=qd(e),a=Math.max(1,Math.min(250,Ea(e.maxDurationMs,250))),r=Math.max(1,Math.ceil(t.sampleRate*a/1e3));return{...t,maxDurationMs:a,capacityFrames:r,capacityBytes:r*t.channels*Float32Array.BYTES_PER_ELEMENT}}function MS(e={}){const t=Gd(e),a=Math.max(0,Math.min(t.maxDurationMs,Ea(e.targetLeadMs,160))),r=Math.min(t.capacityFrames,Math.max(1,Math.ceil(t.sampleRate*a/1e3)));let c=new Float32Array(t.capacityFrames*t.channels),u=0,p=0,h=0,f=0,k=!1,M=!1,b=0,T=0,I=0;const x={acceptedFrames:0,droppedFrames:0},E=()=>(I+=1,{sampleRate:t.sampleRate,channels:t.channels,sampleFormat:t.sampleFormat,maxDurationMs:t.maxDurationMs,targetLeadMs:a,capacityFrames:M?0:t.capacityFrames,capacityBytes:M?0:t.capacityBytes,bufferedFrames:M?0:h,bufferedBytes:M?0:h*t.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:M?0:h*1e3/t.sampleRate,droppedFrames:b,underflowCount:T,started:!M&&k,disposed:M}),H=()=>{u=0,p=0,h=0,f=0,k=!1},Q=()=>{M||(H(),c=new Float32Array(0),M=!0)},G=(O,te=0,Z,me=t.sampleFormat)=>{if(x.acceptedFrames=0,x.droppedFrames=0,M||!(O instanceof ArrayBuffer))return x;const le=Math.max(0,Math.floor(Number(te)||0)),pe=Math.max(0,O.byteLength-le),se=Math.min(pe,Math.max(0,Math.floor(Number(Z??pe)||0))),W=me==="s16le",re=W?2:4,L=re*t.channels,_=Math.floor(se/L);if(_<=0)return x;const q=Math.min(_,t.capacityFrames),ue=_-q,P=Math.max(0,h+q-t.capacityFrames);P>0&&(u=(u+P)%t.capacityFrames,h-=P);const F=ue+P;b+=F;const ee=new DataView(O,le,se);for(let Se=ue;Se<_;Se+=1){const de=p*t.channels,Fe=Se*t.channels;for(let j=0;j<t.channels;j+=1){const Ce=(Fe+j)*re,we=W?ee.getInt16(Ce,!0)/32768:ee.getFloat32(Ce,!0);c[de+j]=Number.isFinite(we)?Math.max(-1,Math.min(1,we)):0}p=(p+1)%t.capacityFrames}return h+=q,!k&&h>=r&&(k=!0),x.acceptedFrames=q,x.droppedFrames=F,x};return{writePcm:(O={})=>G(O.buffer,O.byteOffset,O.byteLength,O.sampleFormat),writePcmBuffer:G,readToChannels:(O,te=t.sampleRate)=>{if(!Array.isArray(O)||O.length===0)return;let Z=Number.POSITIVE_INFINITY;for(let pe=0;pe<O.length;pe+=1){const se=O[pe];Z=Math.min(Z,se?.length||0)}if(M||!Number.isFinite(Z)||Z<=0||!k){for(let pe=0;pe<O.length;pe+=1)O[pe]?.fill?.(0);return}const me=Math.max(8e3,Math.min(192e3,Ea(te,t.sampleRate))),le=t.sampleRate/me;for(let pe=0;pe<Z;pe+=1){if(h<=0){k=!1,T+=1,f=0;for(let re=0;re<O.length;re+=1)O[re].fill(0,pe);break}const se=u*t.channels;for(let re=0;re<O.length;re+=1){const L=Math.min(re,t.channels-1);O[re][pe]=c[se+L]}f+=le;const W=Math.min(h,Math.floor(f));W>0&&(u=(u+W)%t.capacityFrames,h-=W,f-=W)}},flush:H,dispose:Q,snapshot:E,getSnapshotCount:()=>I}}function xS(e={}){const t=Math.max(1,Math.min(Td,Ea(e.maxPendingPackets,Td))),a=Math.max(1,Ea(e.maxPendingBytes,1)),r=new Map;let c=0,u=0,p=0,h=0,f=0,k=!1;const M=()=>({terminal:k,maxPendingPackets:t,maxPendingBytes:a,pendingPacketCount:r.size,pendingPacketBytes:c,pendingPacketHighWater:u,pendingByteHighWater:p,acceptedCount:h,droppedCount:f});return{claim(b,T){const I=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),x=Math.max(0,Math.floor(Number(T)||0));return k||!I||x<=0||r.has(I)||r.size>=t||c+x>a?(f+=1,!1):(r.set(I,x),c+=x,u=Math.max(u,r.size),p=Math.max(p,c),h+=1,!0)},acknowledge(b){const T=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),I=r.get(T);return I===void 0?!1:(r.delete(T),c=Math.max(0,c-I),!0)},terminate(){return r.clear(),c=0,k=!0,M()},getPendingPacketCount:()=>r.size,getPendingPacketBytes:()=>c,getPendingPacketHighWater:()=>u,getPendingByteHighWater:()=>p,snapshot:M}}function Fl(e,t){const a=String(e?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(a)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))throw new Error("Remote Audio worklet function binding name is invalid.");const r=`const ${a} = ${Function.prototype.toString.call(e)};`;return a===t?r:`${r}
|
|
4
|
-
const ${t} = ${a};`}const
|
|
5
|
-
const REMOTE_AUDIO_PCM_RING_MAX_MS = ${
|
|
6
|
-
const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${
|
|
7
|
-
${RS}
|
|
8
|
-
${AS}
|
|
9
|
-
${IS}
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentsPage-DUMU7WPH.js","assets/styles-CO6aHjLW.js","assets/icons-CacEbnZu.js","assets/react-Cfedt3N5.js","assets/styles-DDKP4MTD.css","assets/AgentsPage-D29gvPcH.css","assets/ShareFilesPage-Bp5Dh9tQ.js","assets/ShareFilesPage-BCCMoGKE.css","assets/SupportPage-BwS_toBH.js","assets/supabase-C7qjtLN3.js","assets/frame-lifecycle-esOdP-EY.js","assets/SupportPage-Cxx61WwR.css","assets/SettingsPage-JYlSHnWI.js","assets/SettingsTabs-D75pwHMD.js","assets/AgentSettingsTab-BBNQK3m_.js","assets/DesktopUpdatePanel-BPD9IaXS.js","assets/CaptureGallery-Dgucz-9s.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{D as In,k as Xv,l as fl,i as yi,h as ze,m as Jv,e as Ss,o as Zv,q as xs,u as Rs,_ as mr,v as Kh,x as ey,y as ty,j as i,p as $e,z as Yh,A as ny,B as Xp,C as Jp,g as ry,T as Zp,b as Ou,a as us,F as _u,M as ef,f as ju,E as ay,L as oy}from"./styles-CO6aHjLW.js";import{a as s,am as iy,an as tf,p as sy,ao as cy,ap as ly,ae as Sl,X as Ma,U as As,aq as Qh,c as Ra,l as hl,ac as xa,ar as uy,as as dy,at as my,au as py,k as wo,av as Xh,g as Si,aw as fy,ax as hy,b as Cn,y as gy,ay as Jh,f as Cs,a0 as Zh,T as gl,aa as Sd,ab as by,ad as nf,a9 as vy,az as yy,D as rf,O as wy,N as Sy,A as Cy,E as ky,aA as af,W as eg,aB as Bu,Z as My,a2 as Hu,x as xy,aC as of,aD as Ry,aE as tg,C as ng,n as ds,aF as Ay,aG as Iy,t as Ty,aH as Py,a4 as Ey,G as Ny,Q as Fy}from"./icons-CacEbnZu.js";import{c as Dy}from"./supabase-C7qjtLN3.js";import{c as Ly,a as Oy,f as Wu,b as _y,r as $u,t as Vu,d as sf,e as jy,i as cf,g as By,h as On,j as ya,s as dn,k as ho,l as zu,m as Uu,n as qu,o as Hy,p as Xc,q as lf,u as Jc,v as uf}from"./frame-lifecycle-esOdP-EY.js";const rg={hub:"Use this computer as Hub. Hub connects to and manages Client computers.","switch-to-hub":"Switch this computer from Client to Hub. It will manage Client computers instead of sharing its own screen.",client:"Keep this computer in Client mode so its screens, files, audio, and remote controls remain available to the active Hub.",wall:"Show live thumbnails from every connected Client. Choose a display, change tile size, or move into Control without opening another connection.",control:"Open the selected Client at full resolution and send mouse and keyboard input through the existing Hub session.","share-files":"Browse files on the Hub, send files to selected Clients, and manage shared folders and transfer progress.",agents:"Run approved commands on connected Clients through the Hub-hosted Codex Agent and VuvoDesk permission controls."},Cd={en:rg,ko:{hub:"이 컴퓨터를 Hub로 사용합니다. Hub는 Client 컴퓨터를 연결하고 관리합니다.","switch-to-hub":"이 컴퓨터를 Client에서 Hub로 바꿉니다. 자신의 화면 공유를 멈추고 Client 컴퓨터를 관리합니다.",client:"이 컴퓨터를 Client 모드로 유지합니다. 화면, 파일, 오디오와 원격 제어 기능이 활성 Hub에서 계속 사용 가능하도록 연결합니다.",wall:"연결된 모든 Client의 실시간 화면을 한곳에 표시합니다. 모니터와 타일 크기를 선택하고 새 연결 없이 Control로 이동할 수 있습니다.",control:"선택한 Client 화면을 전체 해상도로 열고 기존 Hub 세션을 통해 마우스와 키보드 입력을 전송합니다.","share-files":"Hub의 파일을 탐색하고 선택한 Client로 전송하며 공유 폴더와 전송 진행 상태를 관리합니다.",agents:"Hub의 Codex가 연결된 Client에서 VuvoDesk 권한과 승인 범위 안의 명령을 실행합니다."},ja:{hub:"このコンピューターを VuvoDesk Hub として運用します。Hub は Client 接続、Wall、Control、ファイル共有、Agents を一か所で管理する統合コントロールセンターで、ネットワーク変更後に押すと安全な接続情報も更新します。","switch-to-hub":"このコンピューターを Client から Hub に切り替えます。新しい役割を保存して同じデスクトップランタイムを再起動し、Wall を開きます。Client としての共有は停止します。",client:"このコンピューターを Client モードで維持し、画面、ファイル、音声、リモート操作をアクティブ Hub から利用できるようにします。",wall:"接続中のすべての Client のライブ画面を一覧表示します。ディスプレイやタイルサイズを選び、新しい接続なしで Control に移動できます。",control:"選択した Client をフル解像度で開き、既存の Hub セッションからマウスとキーボード入力を送信します。","share-files":"Hub のファイルを参照し、選択した Client への送信、共有フォルダー、転送状況を管理します。",agents:"Hub の Codex Agent が、VuvoDesk の権限と承認の範囲内で接続中の Client にコマンドを実行します。"},zh:{hub:"将此电脑作为 VuvoDesk Hub 运行。Hub 是统一控制中心,可集中管理 Client 连接、Wall、Control、文件共享和 Agents;网络变化后按下此按钮还会刷新安全连接信息。","switch-to-hub":"将此电脑从 Client 切换为 Hub。VuvoDesk 保存新角色、重启同一桌面运行时并打开 Wall;此电脑将停止作为 Client 共享。",client:"让此电脑保持 Client 模式,使活动 Hub 可以继续使用它的屏幕、文件、音频和远程控制。",wall:"集中显示所有已连接 Client 的实时缩略图。可以选择显示器、调整磁贴大小,并在不新建连接的情况下进入 Control。",control:"以完整分辨率打开所选 Client,并通过现有 Hub 会话发送鼠标和键盘输入。","share-files":"浏览 Hub 文件、向所选 Client 发送文件,并管理共享文件夹和传输进度。",agents:"Hub 的 Codex Agent 会在 VuvoDesk 权限与批准范围内,对已连接的 Client 执行命令。"},"zh-TW":{hub:"將此電腦作為 VuvoDesk Hub 運作。Hub 是統一控制中心,可集中管理 Client 連線、Wall、Control、檔案分享與 Agents;網路變更後按下此按鈕也會更新安全連線資訊。","switch-to-hub":"將此電腦從 Client 切換為 Hub。VuvoDesk 會儲存新角色、重新啟動同一桌面執行階段並開啟 Wall;此電腦將停止以 Client 身分共享。",client:"讓此電腦維持 Client 模式,使作用中 Hub 可繼續使用它的畫面、檔案、音訊與遠端控制。",wall:"集中顯示所有已連線 Client 的即時縮圖。可選擇顯示器、調整圖塊大小,並在不建立新連線的情況下進入 Control。",control:"以完整解析度開啟所選 Client,並透過現有 Hub 工作階段傳送滑鼠與鍵盤輸入。","share-files":"瀏覽 Hub 檔案、傳送檔案到所選 Client,並管理共享資料夾與傳輸進度。",agents:"Hub 的 Codex Agent 會在 VuvoDesk 權限與核准範圍內,對已連線的 Client 執行命令。"},es:{hub:"Usa este equipo como VuvoDesk Hub. Hub es el centro de control unificado para conexiones Client, Wall, Control, archivos y Agents; púlsalo tras cambios de red para actualizar el acceso seguro.","switch-to-hub":"Cambia este equipo de Client a Hub. VuvoDesk guarda el nuevo rol, reinicia el mismo entorno de escritorio y abre Wall; el equipo deja de compartirse como Client.",client:"Mantiene este equipo en modo Client para que sus pantallas, archivos, audio y control remoto sigan disponibles desde el Hub activo.",wall:"Muestra miniaturas en vivo de todos los Clients conectados. Elige pantalla y tamaño, o entra en Control sin abrir otra conexión.",control:"Abre el Client seleccionado a resolución completa y envía ratón y teclado por la sesión Hub existente.","share-files":"Explora archivos del Hub, envíalos a los Clients seleccionados y administra carpetas compartidas y transferencias.",agents:"El Codex Agent del Hub ejecuta comandos en los Clients conectados dentro de los permisos y aprobaciones de VuvoDesk."},fr:{hub:"Utilise cet ordinateur comme VuvoDesk Hub. Hub est le centre de contrôle unifié des connexions Client, de Wall, Control, des fichiers et des Agents ; appuyez après un changement réseau pour actualiser l’accès sécurisé.","switch-to-hub":"Bascule cet ordinateur de Client vers Hub. VuvoDesk enregistre le nouveau rôle, redémarre le même environnement de bureau et ouvre Wall ; le partage Client s’arrête.",client:"Maintient cet ordinateur en mode Client afin que ses écrans, fichiers, sons et commandes à distance restent disponibles depuis le Hub actif.",wall:"Affiche les miniatures en direct de tous les Clients connectés. Choisissez l’écran et la taille, ou passez à Control sans nouvelle connexion.",control:"Ouvre le Client sélectionné en pleine résolution et transmet souris et clavier via la session Hub existante.","share-files":"Parcourez les fichiers du Hub, envoyez-les aux Clients sélectionnés et gérez dossiers partagés et transferts.",agents:"Le Codex Agent du Hub exécute des commandes sur les Clients connectés selon les permissions et approbations de VuvoDesk."},de:{hub:"Verwendet diesen Computer als VuvoDesk Hub. Hub ist die gemeinsame Steuerzentrale für Client-Verbindungen, Wall, Control, Dateien und Agents; nach Netzwerkänderungen aktualisiert ein Klick den sicheren Zugriff.","switch-to-hub":"Wechselt diesen Computer von Client zu Hub. VuvoDesk speichert die neue Rolle, startet dieselbe Desktop-Laufzeit neu und öffnet Wall; die Client-Freigabe endet.",client:"Hält diesen Computer im Client-Modus, damit Bildschirme, Dateien, Audio und Fernsteuerung am aktiven Hub verfügbar bleiben.",wall:"Zeigt Live-Vorschaubilder aller verbundenen Clients. Display und Kachelgröße wählen oder ohne neue Verbindung zu Control wechseln.",control:"Öffnet den gewählten Client in voller Auflösung und sendet Maus- und Tastatureingaben über die bestehende Hub-Sitzung.","share-files":"Dateien auf dem Hub durchsuchen, an gewählte Clients senden sowie Freigaben und Übertragungen verwalten.",agents:"Der Codex Agent des Hubs führt Befehle auf verbundenen Clients innerhalb der VuvoDesk-Berechtigungen und Freigaben aus."},"pt-BR":{hub:"Usa este computador como VuvoDesk Hub. Hub é o centro de controle unificado para conexões Client, Wall, Control, arquivos e Agents; após mudanças de rede, pressione para atualizar o acesso seguro.","switch-to-hub":"Muda este computador de Client para Hub. O VuvoDesk salva a nova função, reinicia o mesmo runtime de desktop e abre o Wall; o compartilhamento como Client é encerrado.",client:"Mantém este computador no modo Client para que telas, arquivos, áudio e controle remoto continuem disponíveis no Hub ativo.",wall:"Mostra miniaturas ao vivo de todos os Clients conectados. Escolha a tela e o tamanho ou entre em Control sem criar outra conexão.",control:"Abre o Client selecionado em resolução total e envia mouse e teclado pela sessão Hub existente.","share-files":"Navegue pelos arquivos do Hub, envie para Clients selecionados e gerencie pastas compartilhadas e transferências.",agents:"O Codex Agent do Hub executa comandos nos Clients conectados dentro das permissões e aprovações do VuvoDesk."},it:{hub:"Usa questo computer come VuvoDesk Hub. Hub è il centro di controllo unificato per connessioni Client, Wall, Control, file e Agents; dopo modifiche di rete, premilo per aggiornare l’accesso sicuro.","switch-to-hub":"Passa questo computer da Client a Hub. VuvoDesk salva il nuovo ruolo, riavvia lo stesso runtime desktop e apre Wall; la condivisione come Client termina.",client:"Mantiene questo computer in modalità Client, rendendo schermi, file, audio e controllo remoto disponibili all’Hub attivo.",wall:"Mostra le anteprime live di tutti i Client connessi. Scegli display e dimensione oppure passa a Control senza una nuova connessione.",control:"Apre il Client selezionato a piena risoluzione e invia mouse e tastiera tramite la sessione Hub esistente.","share-files":"Esplora i file dell’Hub, inviali ai Client selezionati e gestisci cartelle condivise e trasferimenti.",agents:"Il Codex Agent dell’Hub esegue comandi sui Client connessi entro i permessi e le approvazioni di VuvoDesk."},id:{hub:"Gunakan komputer ini sebagai VuvoDesk Hub. Hub adalah pusat kendali terpadu untuk koneksi Client, Wall, Control, file, dan Agents; tekan setelah perubahan jaringan untuk memperbarui akses aman.","switch-to-hub":"Alihkan komputer ini dari Client menjadi Hub. VuvoDesk menyimpan peran baru, memulai ulang runtime desktop yang sama, lalu membuka Wall; berbagi sebagai Client berhenti.",client:"Pertahankan komputer ini dalam mode Client agar layar, file, audio, dan kendali jarak jauh tetap tersedia bagi Hub aktif.",wall:"Tampilkan thumbnail live semua Client yang terhubung. Pilih layar dan ukuran tile atau masuk ke Control tanpa koneksi baru.",control:"Buka Client terpilih pada resolusi penuh dan kirim input mouse serta keyboard melalui sesi Hub yang ada.","share-files":"Jelajahi file Hub, kirim ke Client terpilih, serta kelola folder bersama dan progres transfer.",agents:"Codex Agent di Hub menjalankan perintah pada Client terhubung sesuai izin dan persetujuan VuvoDesk."},vi:{hub:"Dùng máy tính này làm VuvoDesk Hub. Hub là trung tâm điều khiển hợp nhất cho kết nối Client, Wall, Control, tệp và Agents; nhấn sau khi đổi mạng để làm mới quyền truy cập an toàn.","switch-to-hub":"Chuyển máy tính này từ Client sang Hub. VuvoDesk lưu vai trò mới, khởi động lại cùng môi trường desktop và mở Wall; việc chia sẻ dưới dạng Client sẽ dừng.",client:"Giữ máy tính này ở chế độ Client để màn hình, tệp, âm thanh và điều khiển từ xa luôn sẵn sàng cho Hub đang hoạt động.",wall:"Hiển thị ảnh thu nhỏ trực tiếp của mọi Client đã kết nối. Chọn màn hình, cỡ ô hoặc vào Control mà không tạo kết nối mới.",control:"Mở Client đã chọn ở độ phân giải đầy đủ và gửi chuột, bàn phím qua phiên Hub hiện có.","share-files":"Duyệt tệp trên Hub, gửi tới Client đã chọn và quản lý thư mục chia sẻ cùng tiến trình truyền.",agents:"Codex Agent trên Hub chạy lệnh trên các Client đã kết nối trong phạm vi quyền và phê duyệt của VuvoDesk."},th:{hub:"ใช้คอมพิวเตอร์เครื่องนี้เป็น VuvoDesk Hub โดย Hub คือศูนย์ควบคุมรวมสำหรับการเชื่อมต่อ Client, Wall, Control, ไฟล์ และ Agents และกดหลังเปลี่ยนเครือข่ายเพื่อรีเฟรชการเข้าถึงที่ปลอดภัย","switch-to-hub":"เปลี่ยนคอมพิวเตอร์นี้จาก Client เป็น Hub โดย VuvoDesk จะบันทึกบทบาทใหม่ รีสตาร์ต desktop runtime เดิม และเปิด Wall พร้อมหยุดแชร์ในฐานะ Client",client:"ให้คอมพิวเตอร์นี้อยู่ในโหมด Client เพื่อให้ Hub ที่ใช้งานเข้าถึงหน้าจอ ไฟล์ เสียง และการควบคุมระยะไกลได้ต่อเนื่อง",wall:"แสดงภาพสดแบบย่อของ Client ที่เชื่อมต่อทั้งหมด เลือกจอและขนาด tile หรือเข้า Control ได้โดยไม่เปิดการเชื่อมต่อใหม่",control:"เปิด Client ที่เลือกแบบความละเอียดเต็ม และส่งเมาส์กับคีย์บอร์ดผ่าน session ของ Hub ที่มีอยู่","share-files":"เรียกดูไฟล์บน Hub ส่งไปยัง Client ที่เลือก และจัดการโฟลเดอร์แชร์กับความคืบหน้าการโอน",agents:"Codex Agent บน Hub เรียกใช้คำสั่งบน Client ที่เชื่อมต่อภายใต้สิทธิ์และการอนุมัติของ VuvoDesk"},hi:{hub:"इस कंप्यूटर को VuvoDesk Hub के रूप में उपयोग करें। Hub, Client कनेक्शन, Wall, Control, फ़ाइल और Agents का एकीकृत नियंत्रण केंद्र है; नेटवर्क बदलने के बाद सुरक्षित पहुँच ताज़ा करने के लिए इसे दबाएँ।","switch-to-hub":"इस कंप्यूटर को Client से Hub में बदलता है। VuvoDesk नई भूमिका सहेजता है, उसी desktop runtime को restart करके Wall खोलता है और Client sharing रोक देता है।",client:"इस कंप्यूटर को Client मोड में रखता है ताकि इसकी स्क्रीन, फ़ाइलें, ऑडियो और remote control सक्रिय Hub पर उपलब्ध रहें।",wall:"सभी जुड़े Clients के live thumbnail दिखाता है। स्क्रीन और tile आकार चुनें या नया connection खोले बिना Control में जाएँ।",control:"चुने हुए Client को पूर्ण resolution में खोलता है और मौजूदा Hub session से mouse तथा keyboard input भेजता है।","share-files":"Hub की फ़ाइलें देखें, चुने हुए Clients को भेजें और shared folders तथा transfer progress प्रबंधित करें।",agents:"Hub का Codex Agent VuvoDesk permissions और approvals के भीतर जुड़े Clients पर commands चलाता है।"},ar:{hub:"استخدم هذا الكمبيوتر بوصفه VuvoDesk Hub. يمثّل Hub مركز التحكم الموحّد لاتصالات Client وWall وControl والملفات وAgents؛ اضغط عليه بعد تغييرات الشبكة لتحديث الوصول الآمن.","switch-to-hub":"يحوّل هذا الكمبيوتر من Client إلى Hub. يحفظ VuvoDesk الدور الجديد ويعيد تشغيل بيئة سطح المكتب نفسها ويفتح Wall، ويتوقف الجهاز عن المشاركة كـ Client.",client:"يبقي هذا الكمبيوتر في وضع Client لتظل شاشاته وملفاته وصوته والتحكم عن بعد متاحة من Hub النشط.",wall:"يعرض صورا حية مصغرة لكل Clients المتصلين. اختر الشاشة وحجم البلاطات أو انتقل إلى Control من دون اتصال جديد.",control:"يفتح Client المحدد بالدقة الكاملة ويرسل إدخال الماوس ولوحة المفاتيح عبر جلسة Hub الحالية.","share-files":"استعرض ملفات Hub وأرسلها إلى Clients المحددين وأدر المجلدات المشتركة وتقدم النقل.",agents:"يشغّل Codex Agent على Hub الأوامر في Clients المتصلين ضمن صلاحيات وموافقات VuvoDesk."},tr:{hub:"Bu bilgisayarı VuvoDesk Hub olarak kullanır. Hub; Client bağlantıları, Wall, Control, dosyalar ve Agents için birleşik kontrol merkezidir; ağ değişikliklerinden sonra güvenli erişimi yenilemek için basın.","switch-to-hub":"Bu bilgisayarı Client rolünden Hub rolüne geçirir. VuvoDesk yeni rolü kaydeder, aynı masaüstü runtime’ını yeniden başlatıp Wall’u açar; Client paylaşımı durur.",client:"Bu bilgisayarı Client modunda tutar; ekran, dosya, ses ve uzaktan kontrol özellikleri etkin Hub tarafından kullanılabilir kalır.",wall:"Bağlı tüm Client ekranlarının canlı küçük görüntülerini gösterir. Ekran ve kutu boyutunu seçin veya yeni bağlantı açmadan Control’e geçin.",control:"Seçili Client’ı tam çözünürlükte açar ve mevcut Hub oturumu üzerinden fare ile klavye girdisi gönderir.","share-files":"Hub dosyalarını gezin, seçili Client’lara gönderin ve paylaşılan klasörlerle aktarım ilerlemesini yönetin.",agents:"Hub Codex Agent, bağlı Client’larda VuvoDesk izinleri ve onayları kapsamında komut çalıştırır."}};function Wd(e){const t=e?[e]:typeof navigator>"u"?["en"]:navigator.languages?.length?navigator.languages:[navigator.language];for(const a of t){const r=String(a||"").trim(),c=r.toLowerCase();if(!c)continue;if(c.startsWith("zh-tw")||c.startsWith("zh-hk"))return"zh-TW";if(c.startsWith("zh"))return"zh";if(c.startsWith("pt"))return"pt-BR";const u=c.split("-")[0];if(Cd[r])return r;if(Cd[u])return u}return"en"}function ag(e,t){const a=Wd(t);return Cd[a]?.[e]||rg[e]}function Wy(e,t,a){return`${e}
|
|
3
|
+
${ag(t,a)}`}const og={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"VuvoDesk will stop sharing this computer as a Client, save the Hub role, restart the local runtime, and open Wall in this same window.",restartNotice:"Remote streams from this computer will end while VuvoDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},$y={en:og,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"VuvoDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"VuvoDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"VuvoDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"VuvoDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"VuvoDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"VuvoDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"VuvoDesk dejará de compartir este equipo como Client, guardará la función Hub, reiniciará el entorno local y abrirá Wall en esta misma ventana.",restartNotice:"Los streams remotos de este equipo terminarán mientras VuvoDesk se reinicia.",cancel:"Cancelar",confirm:"Cambiar a Hub",closeLabel:"Cerrar confirmación de cambio a Hub"},fr:{eyebrow:"Changer le rôle de l’ordinateur",title:"Basculer cet ordinateur vers Hub ?",description:"VuvoDesk arrêtera le partage Client de cet ordinateur, enregistrera le rôle Hub, redémarrera le runtime local et ouvrira Wall dans cette même fenêtre.",restartNotice:"Les flux distants de cet ordinateur prendront fin pendant le redémarrage de VuvoDesk.",cancel:"Annuler",confirm:"Basculer vers Hub",closeLabel:"Fermer la confirmation de bascule vers Hub"},de:{eyebrow:"Computerrolle ändern",title:"Diesen Computer auf Hub umstellen?",description:"VuvoDesk beendet die Client-Freigabe dieses Computers, speichert die Hub-Rolle, startet die lokale Laufzeit neu und öffnet Wall im selben Fenster.",restartNotice:"Die Remote-Streams dieses Computers enden während des VuvoDesk-Neustarts.",cancel:"Abbrechen",confirm:"Auf Hub umstellen",closeLabel:"Bestätigung für Hub-Wechsel schließen"},"pt-BR":{eyebrow:"Alterar função do computador",title:"Mudar este computador para Hub?",description:"O VuvoDesk interromperá o compartilhamento deste computador como Client, salvará a função Hub, reiniciará o runtime local e abrirá o Wall nesta mesma janela.",restartNotice:"Os streams remotos deste computador serão encerrados enquanto o VuvoDesk reinicia.",cancel:"Cancelar",confirm:"Mudar para Hub",closeLabel:"Fechar confirmação de mudança para Hub"},it:{eyebrow:"Cambia ruolo del computer",title:"Passare questo computer a Hub?",description:"VuvoDesk interromperà la condivisione Client di questo computer, salverà il ruolo Hub, riavvierà il runtime locale e aprirà Wall nella stessa finestra.",restartNotice:"Gli stream remoti di questo computer termineranno durante il riavvio di VuvoDesk.",cancel:"Annulla",confirm:"Passa a Hub",closeLabel:"Chiudi la conferma del passaggio a Hub"},id:{eyebrow:"Ubah peran komputer",title:"Alihkan komputer ini menjadi Hub?",description:"VuvoDesk akan menghentikan berbagi komputer ini sebagai Client, menyimpan peran Hub, memulai ulang runtime lokal, lalu membuka Wall di jendela yang sama.",restartNotice:"Stream jarak jauh dari komputer ini akan berakhir saat VuvoDesk dimulai ulang.",cancel:"Batal",confirm:"Alihkan ke Hub",closeLabel:"Tutup konfirmasi peralihan Hub"},vi:{eyebrow:"Đổi vai trò máy tính",title:"Chuyển máy tính này thành Hub?",description:"VuvoDesk sẽ dừng chia sẻ máy tính này dưới dạng Client, lưu vai trò Hub, khởi động lại runtime cục bộ và mở Wall trong cùng cửa sổ.",restartNotice:"Các luồng từ xa của máy tính này sẽ kết thúc trong khi VuvoDesk khởi động lại.",cancel:"Hủy",confirm:"Chuyển sang Hub",closeLabel:"Đóng xác nhận chuyển sang Hub"},th:{eyebrow:"เปลี่ยนบทบาทคอมพิวเตอร์",title:"เปลี่ยนคอมพิวเตอร์เครื่องนี้เป็น Hub หรือไม่",description:"VuvoDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ VuvoDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"VuvoDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"VuvoDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف VuvoDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل VuvoDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"VuvoDesk bu bilgisayarın Client paylaşımını durdurur, Hub rolünü kaydeder, yerel çalışma zamanını yeniden başlatır ve Wall’u aynı pencerede açar.",restartNotice:"VuvoDesk yeniden başlatılırken bu bilgisayarın uzak akışları sona erer.",cancel:"İptal",confirm:"Hub’a geçir",closeLabel:"Hub geçişi onayını kapat"}},ig={eyebrow:"Computer role",title:"Use this computer as Hub?",description:"Hub connects to and manages Client computers.",restartNotice:"If another computer is Hub, this computer will become the new Hub.",cancel:"Cancel",confirm:"Use as Hub",closeLabel:"Close Hub confirmation"},Vy={en:ig,ko:{eyebrow:"컴퓨터 역할",title:"이 컴퓨터를 Hub로 사용할까요?",description:"Hub는 Client 컴퓨터를 연결하고 관리합니다.",restartNotice:"다른 컴퓨터가 Hub라면 이 컴퓨터가 새 Hub가 됩니다.",cancel:"취소",confirm:"Hub로 설정",closeLabel:"Hub 설정 확인 닫기"}};function sx(e){const t=Wd(e);return $y[t]||og}function zy(e){const t=Wd(e);return Vy[t]||ig}const Uy="https://otbyfkjxrkngvjziawki.supabase.co",qy="sb_publishable_NpUs0RDJH2YnllsqTKO6TQ_1jTdSsNQ",Gy={getItem:()=>null,setItem:()=>{},removeItem:()=>{}},Gu=typeof window<"u"&&!!window.liveDesk,Ct=Dy(Uy,qy,{auth:{autoRefreshToken:!Gu,persistSession:!Gu,storage:Gu?Gy:void 0,detectSessionInUrl:!0,flowType:"pkce",storageKey:"livedesk.mindexec.supabase.auth"}});function Ky({eligibleCandidates:e,fallbackHubBaseUrl:t,publicConsole:a,authenticated:r}){const c=String(t||"").trim();if(a&&r&&c)return Object.freeze({candidates:Object.freeze([c]),transport:"p2p",reason:"authenticated-public-console-p2p"});const u=[...new Set((Array.isArray(e)?e:[]).map(p=>String(p||"").trim()).filter(Boolean))];return u.length>0?Object.freeze({candidates:Object.freeze(u),transport:"auto",reason:"direct-candidate"}):Object.freeze({candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}function Yy({expectedWorkspaceId:e,expectedWorkspaceKind:t,verifiedPublicDirect:a,statusWorkspace:r}){const c=String(e||"").trim(),u=String(t||"").trim().toLowerCase();if(!c)return!0;const p=String(r?.workspaceId||"").trim(),h=String(r?.kind||"").trim().toLowerCase();return p?p===c&&h===u:a===!0&&u==="personal"}function Ku(e,t){const a=e?.hasSnapshot===!0;switch(t){case"reset-idle":return Object.freeze({phase:"idle",hasSnapshot:!1});case"reset-enabled":return Object.freeze({phase:"connecting",hasSnapshot:!1});case"success":return Object.freeze({phase:"online",hasSnapshot:!0});case"failure":return Object.freeze({phase:a?"reconnecting":"unavailable",hasSnapshot:a});case"retry":return Object.freeze({phase:a?"reconnecting":"connecting",hasSnapshot:a});default:throw new Error(`Unknown Hub snapshot connection event: ${String(t||"")}`)}}function Qy({authLoading:e,phase:t,recoveryOverlayEligible:a=!1}){const r=String(t||"idle"),c=r==="reconnecting",u=c&&a===!0;return Object.freeze({statusVisible:e!==!0&&r!=="connecting"&&(!c||!u),recoveryVisible:u})}const Xy=Object.freeze([50,100,250,600,1e3,2e3,4e3]);function Jy(e={}){const t=typeof e.readVisible=="function"?e.readVisible:()=>document.visibilityState==="visible",a=typeof e.commitVisibility=="function"?e.commitVisibility:()=>{},r=typeof e.schedule=="function"?e.schedule:(ie,J)=>setTimeout(ie,J),c=typeof e.cancel=="function"?e.cancel:ie=>clearTimeout(ie),u=Array.isArray(e.recheckDelaysMs)&&e.recheckDelaysMs.length>0?e.recheckDelaysMs.map(ie=>Math.max(1,Math.floor(Number(ie)||1))):Xy;let p=!1,h=0,f=!1,k=null,M=0,b=0,T=Object.prototype.hasOwnProperty.call(e,"initialCommittedVisible")?e.initialCommittedVisible===!0:!!t();const A=()=>{k!==null&&(c(k),k=null)},x=ie=>{const J=ie===!0;return T===J?!1:(T=J,a(J),!0)},E=ie=>{h+=1,f=!1,M=0,A(),x(ie)},B=ie=>{if(p||!f||ie!==h)return!1;if(M>=u.length)return f=!1,M=0,!1;const J=u[M];M+=1;const de=r(()=>{if(k===de&&(k=null,!(p||!f||ie!==h))){if(b+=1,t()){E(!0);return}B(ie)}},J);return k=de,!0};return Object.freeze({handleForegroundHint:()=>{if(p)return!1;if(t())return E(!0),!0;if(x(!1),f)return!1;f=!0,M=0;const ie=h+1;return h=ie,B(ie),!1},handlePageHide:()=>{p||E(!1)},handleVisibilityChange:()=>{if(p)return!1;const ie=!!t();return E(ie),ie},dispose:()=>{p||(p=!0,h+=1,f=!1,M=0,A())},inspect:()=>Object.freeze({active:f,timerCount:k===null?0:1,runGeneration:h,checkCount:b,committedVisible:T})})}function Ca(e,t,a){if(a<0||t<0||t+a>e.length)throw new Error("Invalid LZO1X block: input overrun.")}function Yu(e,t,a){let r=0;for(;Ca(e,t.inputIndex,1),e[t.inputIndex]===0;)r+=1,t.inputIndex+=1;const c=r*255+a+e[t.inputIndex];return t.inputIndex+=1,c}function Zc(e,t,a,r){if(Ca(e,t.inputIndex,r),t.outputIndex+r>a.length)throw new Error("Invalid LZO1X block: output overrun.");a.set(e.subarray(t.inputIndex,t.inputIndex+r),t.outputIndex),t.inputIndex+=r,t.outputIndex+=r}function Zy(e,t,a,r){const c=t-a;if(c<=0||r<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let u=Math.min(c,r);for(e.set(e.subarray(a,a+u),t);u<r;){const p=Math.min(u,r-u);e.copyWithin(t+u,t,t+p),u+=p}return t+r}function sg(e,t){if(!(e instanceof Uint8Array)||e.length<3||t<0)throw new Error("Invalid LZO1X block.");const a=new Uint8Array(t),r={inputIndex:0,outputIndex:0};let c=0,u=0;if(e[r.inputIndex]>=22){const p=e[r.inputIndex]-17;r.inputIndex+=1,Zc(e,r,a,p),c=4}else e[r.inputIndex]>=18&&(c=e[r.inputIndex]-17,r.inputIndex+=1,Zc(e,r,a,c));for(;;){Ca(e,r.inputIndex,1);const p=e[r.inputIndex];r.inputIndex+=1;let h,f;if((p&192)!==0)Ca(e,r.inputIndex,1),f=r.outputIndex-((e[r.inputIndex]<<3)+(p>>2&7)+1),r.inputIndex+=1,u=(p>>5)+1,h=p&3;else if((p&32)!==0){u=(p&31)+2,u===2&&(u+=Yu(e,r,31)),Ca(e,r.inputIndex,2);const k=e[r.inputIndex]|e[r.inputIndex+1]<<8;r.inputIndex+=2,f=r.outputIndex-((k>>2)+1),h=k&3}else if((p&16)!==0){u=(p&7)+2,u===2&&(u+=Yu(e,r,7)),Ca(e,r.inputIndex,2);const k=e[r.inputIndex]|e[r.inputIndex+1]<<8;if(r.inputIndex+=2,f=r.outputIndex-(((p&8)<<11)+(k>>2)),h=k&3,f===r.outputIndex)break;f-=16384}else if(c===0){let k=p+3;k===3&&(k+=Yu(e,r,15)),Zc(e,r,a,k),c=4;continue}else c!==4?(Ca(e,r.inputIndex,1),h=p&3,f=r.outputIndex-((p>>2)+(e[r.inputIndex]<<2)+1),r.inputIndex+=1,u=2):(Ca(e,r.inputIndex,1),h=p&3,f=r.outputIndex-((p>>2)+(e[r.inputIndex]<<2)+2049),r.inputIndex+=1,u=3);if(f<0||r.outputIndex+u+h>a.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");r.outputIndex=Zy(a,r.outputIndex,f,u),c=h,Zc(e,r,a,h)}if(u!==3||r.inputIndex!==e.length||r.outputIndex!==a.length)throw new Error("Invalid LZO1X block: incomplete output.");return a}const df=16,mf=8,ew=24*1024*1024,cg=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,kd=new Uint32Array(65536);for(let e=0;e<kd.length;e+=1){const t=Math.round((e>>11&31)*255/31),a=Math.round((e>>5&63)*255/63),r=Math.round((e&31)*255/31);kd[e]=cg?(t|a<<8|r<<16|4278190080)>>>0:(t<<24|a<<16|r<<8|255)>>>0}function wa(e,t){return e[t]|e[t+1]<<8}function tw(e,t){const a=Number(t);if(!Number.isSafeInteger(a)||a<df||a>ew)throw new Error(`Invalid Mode 5 packet length: ${t}.`);const r=e instanceof Uint8Array?e:new Uint8Array(e),c=sg(r,a);if(c[0]!==76||c[1]!==68||c[2]!==53||c[3]!==68)throw new Error("Invalid Mode 5 packet magic.");if(c[4]!==1)throw new Error(`Unsupported Mode 5 packet version: ${c[4]}.`);const u=(c[5]&1)!==0,p=wa(c,6),h=wa(c,8),f=wa(c,10),k=wa(c,12);if(p<=0||h<=0||p>3840||h>2160)throw new Error(`Invalid Mode 5 frame size: ${p}x${h}.`);if(f<=0||f>256||k>8192)throw new Error(`Invalid Mode 5 tile header: ${f}/${k}.`);const M=[];let b=df;for(let T=0;T<k;T+=1){if(b+mf>c.length)throw new Error("Mode 5 tile header is truncated.");const A=wa(c,b),x=wa(c,b+2),E=wa(c,b+4),B=wa(c,b+6);b+=mf;const q=E*B*2;if(E<=0||B<=0||E>f||B>f||A+E>p||x+B>h||b+q>c.length)throw new Error(`Invalid Mode 5 tile ${T}.`);M.push({x:A,y:x,width:E,height:B,pixels:c.subarray(b,b+q)}),b+=q}if(b!==c.length)throw new Error(`Mode 5 packet has ${c.length-b} trailing bytes.`);return{keyFrame:u,width:p,height:h,tileSize:f,tiles:M}}function nw(e,t,a,r){if(!(e instanceof Uint8ClampedArray)||e.length!==t*a*4||r.width!==t||r.height!==a)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=t,u=a,p=0,h=0;const f=new Uint32Array(e.buffer,e.byteOffset,e.byteLength>>>2);for(const k of r.tiles){const M=cg&&(k.pixels.byteOffset&1)===0?new Uint16Array(k.pixels.buffer,k.pixels.byteOffset,k.pixels.byteLength>>>1):null;let b=0;for(let T=0;T<k.height;T+=1){let A=(k.y+T)*t+k.x;for(let x=0;x<k.width;x+=1){const E=b<<1,B=M?M[b]:k.pixels[E]|k.pixels[E+1]<<8;f[A]=kd[B],b+=1,A+=1}}c=Math.min(c,k.x),u=Math.min(u,k.y),p=Math.max(p,k.x+k.width),h=Math.max(h,k.y+k.height)}return r.tiles.length>0?{x:c,y:u,width:p-c,height:h-u}:null}function rw(e){if(!e)return!0;const t=jt.get(e);return!t||t.hardwareAcceleration==="prefer-hardware"}const jt=new WeakMap,pf=854,ff=480,aw=3840,ow=2160,iw=500,Is=new WeakMap,Md=new WeakMap,xo=new Set,ko=new Set,Ta=new WeakMap,Mo=new Set,ki=new WeakMap,xd=new WeakMap,Rd=new WeakMap,Cl=new WeakMap,lg=4,sw=2,bi=4,cw=2,lw=2,uw=18,dw=0,mw=250,ug=80,pw=5,fw=150,hw=1200,gw=18,bw=.65,dg=80,mg=125,vw=4,yw=2*1024*1024,ww=8,Sw=16,Cw=180,kw=3,$d=2e3,pg=64,fg=32*1024*1024,Mw=500,xw=25,Rw=45,Aw=20,hg=new Uint8Array(0),Vd=250,Iw=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let gg=1,bg=0,vg=0,Ad=0,yg=0;const vs=[];let Es=0,wg=0,Sg,Cg=0,kg,Mg;function Ns(e,t){vs.push({sequence:++yg,type:e,canvasId:ki.get(t)||0,observedAt:Date.now(),activeDecoderCount:xo.size,hardwareLeaseCount:ko.size,hardwareReleaseGeneration:Es}),vs.length>256&&vs.splice(0,vs.length-256)}let ta={h264DecodeAcceleration:"prefer-hardware"};function Tw(e){e.h264DecodeAcceleration&&(ta={...ta,h264DecodeAcceleration:e.h264DecodeAcceleration})}function Pw(e){return e.payload.byteLength===0?e:{...e,payload:hg}}function xg(e,t){const a=String(e.streamPurpose||"").trim().toLowerCase();return a==="wall"?!0:a==="control"?!1:t>=45e3}function Rg(e){try{return e.paintIsCancelled()}catch{return!0}}function Tl(e,t){const a=e.pendingFrames.get(t);if(a)return e.pendingFrames.delete(t),e.pendingFrameBytes=Math.max(0,e.pendingFrameBytes-a.encodedByteLength),e.pendingFrames.size===0&&e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),a}function Ew(e){const t=e.pendingFrames.entries().next().value;return t?Tl(e,t[0]):void 0}function Ag(e){e.pendingTrimTimer!==null&&(window.clearTimeout(e.pendingTrimTimer),e.pendingTrimTimer=null),e.pendingFrames.clear(),e.pendingFrameBytes=0,e.pendingFrameEvictedThroughTimestamp=-1}function Pl(e,t=performance.now()){for(;e.pendingFrames.size>0;){const a=e.pendingFrames.entries().next().value;if(!a)break;const r=t-a[1].queuedAt>$d,c=e.pendingFrames.size>pg,u=e.pendingFrameBytes>fg;if(!r&&!c&&!u)break;e.pendingFrameEvictedThroughTimestamp=Math.max(e.pendingFrameEvictedThroughTimestamp,a[0]),Tl(e,a[0]),e.pendingFrameEvictionCount+=1}}function Nw(e,t,a,r,c,u=performance.now()){Tl(e,t);const p={frame:a,queuedAt:u,queueSize:r,encodedByteLength:Math.max(0,Math.floor(Number(a.payload.byteLength||0))),paintIsCancelled:c};e.pendingFrames.set(t,p),e.pendingFrameBytes+=p.encodedByteLength,Pl(e,u),e.pendingFrameHighWaterMark=Math.max(e.pendingFrameHighWaterMark,e.pendingFrames.size),e.pendingFrameByteHighWaterMark=Math.max(e.pendingFrameByteHighWaterMark,e.pendingFrameBytes)}function Ig(e,t){if(t.pendingTrimTimer!==null||t.pendingFrames.size===0)return;const a=t.pendingFrames.values().next().value;if(!a)return;const r=Math.max(1,$d-(performance.now()-a.queuedAt)+1);t.pendingTrimTimer=window.setTimeout(()=>{t.pendingTrimTimer=null,jt.get(e)===t&&(Pl(t),Ig(e,t))},r)}function Tg(e){return ko.delete(e)?(Es+=1,Ns("hardware-release",e),!0):!1}function Fw(e,t,a){if(t!=="prefer-hardware"||!a)return!1;const r=Ta.get(e);return!r||r.requested!==t||r.actual!=="prefer-software"||Es<=r.failedHardwareReleaseGeneration?!1:(Ta.delete(e),Mo.delete(e),wg+=1,Sg=Date.now(),!0)}function Id(e,t=ta.h264DecodeAcceleration){const a=Ta.get(e);return a?.requested===t?(a.actual!=="prefer-hardware"&&(ko.delete(e),Mo.add(e)),a.actual):(a&&(Ta.delete(e),Mo.delete(e)),t!=="prefer-hardware"?(Tg(e),Mo.delete(e),t):(ko.has(e)||ko.add(e),"prefer-hardware"))}function El(e,t,a){if(t!=="prefer-hardware")return!1;const r=Ta.get(e),c=jt.get(e),u=Date.now();return ki.has(e)||ki.set(e,gg++),Ta.set(e,{requested:t,actual:"prefer-software",reason:a,failedAt:u,failureCount:(r?.requested===t?r.failureCount:0)+1,codec:c?.codec||r?.codec||"",latencyMode:c?.latencyMode||r?.latencyMode||"smooth",inputCount:c?.inputSerial??r?.inputCount??0,outputCount:c?.outputSerial??r?.outputCount??0,lastInputAt:c?.lastInputAt??r?.lastInputAt??0,lastOutputAt:c?.lastOutputAt??r?.lastOutputAt??0,lastPaintAt:c?.lastPaintAt??r?.lastPaintAt??0,decodeQueueHighWaterMark:Math.max(c?.decodeQueueHighWaterMark??0,r?.decodeQueueHighWaterMark??0),decodeQueueOverflowSamples:Math.max(c?.decodeQueueOverflowSamples??0,r?.decodeQueueOverflowSamples??0),decodeQueueOverflowAgeMs:c?.decodeQueueOverflowStartedAt?Math.max(0,performance.now()-c.decodeQueueOverflowStartedAt):r?.decodeQueueOverflowAgeMs,failedHardwareReleaseGeneration:Es}),ko.delete(e),Mo.add(e),Cg+=1,kg=a,Mg=u,!0}function Pa(e){e.interactivePipelineFallbackTimer!==null&&(window.clearTimeout(e.interactivePipelineFallbackTimer),e.interactivePipelineFallbackTimer=null),e.interactivePipelineFallbackFrame!==null&&(window.cancelAnimationFrame(e.interactivePipelineFallbackFrame),e.interactivePipelineFallbackFrame=null),e.interactivePipelineRecoveryFrames=[],e.interactivePipelineRecoveryBytes=0,e.interactivePipelinePaintIsCancelled=void 0,e.interactivePipelineGuardTimestampUs=null}function Pg(e,t){const a=t.interactivePipelineRecoveryFrames,r=t.interactivePipelinePaintIsCancelled,c=t.onBeforePaint,u=t.onPaint;if(Pa(t),a.length===0||r?.()||jt.get(e)!==t||t.hardwareAcceleration!=="prefer-hardware"||!El(e,t.requestedAcceleration,"interactive-pipeline-latency"))return!1;const p=t.requestedAcceleration,h=t.latencyMode;Tn(e);try{for(const f of a)Ud(e,f,u,p,h,r,!1,c)}catch{Tn(e)}return!0}function Dw(e,t,a){const r=Math.max(0,Number(t.payload.byteLength||0));return e.interactivePipelineRecoveryFrames.length>=vw||e.interactivePipelineRecoveryBytes+r>yw?(Pa(e),!1):(e.interactivePipelineRecoveryFrames.push({...t,payload:t.payload.slice()}),e.interactivePipelineRecoveryBytes+=r,e.interactivePipelinePaintIsCancelled=a,!0)}function Lw(e,t,a,r,c=performance.now()){const u=()=>{if(!(jt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==a)){if(!t.pendingFrames.has(a)){Pa(t);return}Pg(e,t)}},p=h=>{if(t.interactivePipelineFallbackFrame=null,!(jt.get(e)!==t||t.interactivePipelineGuardTimestampUs!==a)){if(!t.pendingFrames.has(a)){Pa(t);return}if(h-c>=r){u();return}t.interactivePipelineFallbackFrame=window.requestAnimationFrame(p)}};t.interactivePipelineFallbackTimer=window.setTimeout(u,r),t.interactivePipelineFallbackFrame=window.requestAnimationFrame(p)}function Ow(e,t,a,r=64){try{let c=xd.get(e);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},xd.set(e,c));const u=Math.max(8,Math.min(64,Math.round(r))),p=Math.max(1,Math.round(u*Math.max(1,a)/Math.max(1,t)));(c.canvas.width!==u||c.canvas.height!==p)&&(c.canvas.width=u,c.canvas.height=p);const h=c.canvas.getContext("2d",{willReadFrequently:!0});if(!h)return{visualHash:"",visualChanged:!0};h.drawImage(e,0,0,Math.max(1,t),Math.max(1,a),0,0,u,p);const f=h.getImageData(0,0,u,p).data;let k=2166136261;for(let T=0;T<f.length;T+=4)k^=f[T],k=Math.imul(k,16777619),k^=f[T+1],k=Math.imul(k,16777619),k^=f[T+2],k=Math.imul(k,16777619);const M=(k>>>0).toString(16).padStart(8,"0"),b=!c.initialized||M!==c.lastHash;return c.initialized=!0,c.lastHash=M,{visualHash:M,visualChanged:b}}catch{return{visualHash:"",visualChanged:!0}}}function Td(e,t,a,r=Vd,c=64,u){if(!Iw&&u)return Eg(e,u);let p=Rd.get(e);p||(p={lastHash:"",initialized:!1,lastCanvasSampleAt:0},Rd.set(e,p));const h=performance.now();if(p.initialized&&r>0&&h-p.lastCanvasSampleAt<r)return{visualHash:p.lastHash,visualChanged:!1};const f=Ow(e,t,a,c);return p.initialized=!0,p.lastHash=f.visualHash,p.lastCanvasSampleAt=h,f}function Eg(e,t){let a=Cl.get(e);a||(a={lastHash:"",initialized:!1},Cl.set(e,a));const r=String(t.contentHash||""),c=!a.initialized||!r||r!==a.lastHash;return a.initialized=!0,a.lastHash=r,{visualHash:r,visualChanged:c}}function Ng(e,t,a=!1){const r=Md.get(e);if(r)return r;const c=e.getContext("2d",{alpha:!1,desynchronized:t==="interactive",willReadFrequently:a});if(c){const u=c.getContextAttributes?.(),p={context:c,presentation:u?.desynchronized?"desync":"sync"};return Md.set(e,p),p}return null}function _w(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),a=String(e.compression||"").toLowerCase(),r=String(e.mimeType||"").toLowerCase();return t==="mode2-lzo"||a==="lzo1x"||r==="application/vnd.livedesk.lzo-rgb565"||t==="mode2-lz4"||String(e.compression||"").toLowerCase()==="lz4"||r==="application/vnd.livedesk.lz4-raw"}function jw(e){return String(e.frameMode||e.mode||"").toLowerCase()==="mode3-h264-hw"||String(e.codec||"").toLowerCase()==="h264"||String(e.mimeType||"").toLowerCase()==="video/h264"}function Bw(e){const t=String(e.frameMode||e.mode||"").toLowerCase(),a=String(e.mimeType||"").toLowerCase();return t==="mode5-lzo-delta"||a==="application/vnd.livedesk.lzo-rgb565-delta"}function hf(e,t,a){let r=a,c=t;if(r===15){let u=255;for(;u===255;){if(c>=e.length)throw new Error("Invalid LZ4 block: length overrun.");u=e[c],c+=1,r+=u}}return{length:r,cursor:c}}function Hw(e,t){const a=new Uint8Array(t);let r=0,c=0;for(;r<e.length;){const u=e[r];r+=1;const p=hf(e,r,u>>4);r=p.cursor;const h=p.length;if(r+h>e.length||c+h>a.length)throw new Error("Invalid LZ4 block: literal overrun.");if(a.set(e.subarray(r,r+h),c),r+=h,c+=h,r>=e.length)break;if(r+2>e.length)throw new Error("Invalid LZ4 block: missing offset.");const f=e[r]|e[r+1]<<8;if(r+=2,f<=0||f>c)throw new Error("Invalid LZ4 block: bad match offset.");const k=hf(e,r,u&15);r=k.cursor;const M=k.length+4;if(c+M>a.length)throw new Error("Invalid LZ4 block: match overrun.");let b=c-f;for(let T=0;T<M;T+=1)a[c]=a[b],c+=1,b+=1}if(c!==a.length)throw new Error("Invalid LZ4 block: incomplete output.");return a}function Ww(e){const t=Math.max(1,Math.floor(e.width||0)),a=Math.max(1,Math.floor(e.height||0)),r=String(e.compression||"").toLowerCase(),c=String(e.pixelFormat||e.codec||"").toLowerCase();if(r==="lzo1x"||String(e.frameMode||e.mode||"").toLowerCase()==="mode2-lzo"||String(e.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const M=Math.max(1,Math.floor(e.bytesPerPixel||2)),b=t*a*2,T=Math.floor(e.uncompressedByteLength||b);if(M!==2||T!==b)throw new Error(`Invalid mode2 RGB565 frame size: ${T} for ${t}x${a}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const A=sg(e.payload,b),x=new Uint8ClampedArray(t*a*4);for(let E=0,B=0;E<A.length;E+=2,B+=4){const q=A[E]|A[E+1]<<8,G=q>>11&31,ne=q>>5&63,re=q&31;x[B]=G<<3|G>>2,x[B+1]=ne<<2|ne>>4,x[B+2]=re<<3|re>>2,x[B+3]=255}return new ImageData(x,t,a)}const p=Math.max(1,Math.floor(e.bytesPerPixel||4)),h=Math.max(t*a*p,Math.floor(e.uncompressedByteLength||0)),f=Hw(e.payload,h);if(p!==4)throw new Error(`Unsupported mode2 pixel size: ${p}`);const k=new Uint8ClampedArray(t*a*4);if(c==="rgba32"||c==="rgba")k.set(f.subarray(0,k.length));else for(let M=0,b=0;b<k.length;M+=4,b+=4)k[b]=f[M+2],k[b+1]=f[M+1],k[b+2]=f[M],k[b+3]=f[M+3];return new ImageData(k,t,a)}function gf(e,t="smooth",a=ta.h264DecodeAcceleration){const r=window.VideoDecoder;if(!r||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const c=jt.get(e);if(c&&c.decoder.state!=="closed"&&c.latencyMode===t)return c;c&&Tn(e);let u;const p=new r({output:h=>{if(jt.get(e)!==u){h.close();return}const f=Number(h.timestamp||0),k=performance.now();u.outputSerial+=1,Pl(u,k);let M=Tl(u,f);if(!M&&f>u.pendingFrameEvictedThroughTimestamp&&u.pendingFrames.size>0&&(M=Ew(u),u.timestampFallbacks+=1),!M){u.pendingFrameUnmatchedOutputCount+=1,u.droppedForLatency+=1,u.lastOutputAt=k,h.close();return}const b=u.interactivePipelineGuardTimestampUs===f;if(Rg(M)){b&&Pa(u),u.droppedForLatency+=1,u.lastOutputAt=k,h.close();return}const T=h.displayWidth||h.codedWidth||e.width||960,A=h.displayHeight||h.codedHeight||e.height||540,x=Number(M?.frame.durationUs||0),E=Number(h.duration||0),B=Math.max(16,Math.min(250,(x>0?x:E||83333)/1e3));u.targetPaintIntervalMs=B;const q=Math.max(0,k-M.queuedAt),ne=xg(M.frame,x>0?x:Math.round(B*1e3))?mg:dg;if(u.latencyMode==="interactive"&&u.hardwareAcceleration==="prefer-hardware"&&b&&u.interactivePipelineRecoveryFrames.length>0&&q>ne){h.close(),u.droppedForLatency+=1,Pg(e,u);return}b&&Pa(u),Math.abs(u.interactiveBurstOutputCadenceMs-B)>1&&(u.interactiveBurstOutputTimeCursor=0,u.interactiveBurstOutputTimeCount=0,u.interactiveBurstOutputCadenceMs=B,u.interactiveBurstOutputWindowMs=0),u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]=k,u.interactiveBurstOutputTimeCursor=(u.interactiveBurstOutputTimeCursor+1)%bi,u.interactiveBurstOutputTimeCount=Math.min(bi,u.interactiveBurstOutputTimeCount+1);const re=u.interactiveBurstOutputTimeCount>=bi?k-u.interactiveBurstOutputTimes[u.interactiveBurstOutputTimeCursor]:0;for(u.interactiveBurstOutputWindowMs=Math.max(0,re),u.decodedFrames.push({videoFrame:h,pending:M,decodedAt:k,width:T,height:A,durationMs:B}),u.latencyMode==="interactive"&&u.targetPaintIntervalMs>20&&u.interactiveBurstOutputTimeCount>=bi&&re<=Math.min(Rw,Math.max(xw,u.targetPaintIntervalMs-5))&&(u.interactiveBurstTailHoldArmed=!0),u.lastOutputAt=k;u.decodedFrames.length>zd(u);)kl(u,u.decodedFrames.shift(),"capacity");u.renderQueueHighWaterMark=Math.max(u.renderQueueHighWaterMark,u.decodedFrames.length),Dg(u),u.renderTimer!==null&&u.renderScheduledAt>0&&performance.now()-u.renderScheduledAt>Mw&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),u.renderTimer!==null&&u.decodedFrames.length>=lg&&(window.cancelAnimationFrame(u.renderTimer),u.renderTimer=null,u.renderScheduledAt=0),Ml(e,u)},error:()=>{jt.get(e)===u&&(El(e,u.requestedAcceleration,"decoder-error"),Tn(e))}});return bg+=1,ki.has(e)||ki.set(e,gg++),u={decoder:p,configured:!1,configKey:"",codec:"",requestedAcceleration:a,hardwareAcceleration:Id(e,a),latencyMode:t,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,pendingFrameBytes:0,pendingFrameHighWaterMark:0,pendingFrameByteHighWaterMark:0,pendingFrameEvictionCount:0,pendingFrameUnmatchedOutputCount:0,pendingFrameEvictedThroughTimestamp:-1,pendingTrimTimer:null,decodedFrames:[],renderQueueHighWaterMark:0,renderQueueCapacityDropCount:0,renderQueueAgeDropCount:0,renderTimer:null,renderScheduledAt:0,flushTimer:null,flushInFlight:!1,flushCount:0,timestampFallbacks:0,inputSerial:0,outputSerial:0,lastFlushInputSerial:0,lastOutputAt:0,lastPaintAt:0,lastInputAt:0,interactiveBufferPrimed:!1,interactiveBufferStartedAt:0,interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,interactiveBurstTailHoldArmed:!1,interactiveBurstTailHoldCount:0,interactiveBurstOutputTimes:new Float64Array(bi),interactiveBurstOutputTimeCursor:0,interactiveBurstOutputTimeCount:0,interactiveBurstOutputCadenceMs:0,interactiveBurstOutputWindowMs:0,interactivePipelineFallbackTimer:null,interactivePipelineFallbackFrame:null,interactivePipelineGuardTimestampUs:null,interactivePipelineRecoveryFrames:[],interactivePipelineRecoveryBytes:0,interactivePipelinePaintIsCancelled:void 0,interactiveBackingWidth:0,interactiveBackingHeight:0,interactiveBackingSourceWidth:0,interactiveBackingSourceHeight:0,interactiveBackingMeasuredAt:0,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0,decodeQueueHighWaterMark:0,decodeQueueOverflowStartedAt:0,decodeQueueOverflowSamples:0},jt.set(e,u),xo.add(e),Ad=Math.max(Ad,xo.size),Ns("create",e),u}function Fg(e){Pa(e),e.renderTimer!==null&&(window.cancelAnimationFrame(e.renderTimer),e.renderTimer=null),e.renderScheduledAt=0,e.flushTimer!==null&&(window.clearTimeout(e.flushTimer),e.flushTimer=null),e.flushInFlight=!1;const t=e.decodedFrames;e.decodedFrames=[];for(const a of t)try{a.videoFrame.close()}catch{}e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.interactiveBurstTailHoldArmed=!1,e.interactiveBurstOutputTimeCursor=0,e.interactiveBurstOutputTimeCount=0,e.interactiveBurstOutputCadenceMs=0,e.interactiveBurstOutputWindowMs=0}function kl(e,t,a="other"){t&&(t.videoFrame.close(),e.droppedForLatency+=1,a==="capacity"?e.renderQueueCapacityDropCount+=1:a==="age"&&(e.renderQueueAgeDropCount+=1))}function zd(e){return e.latencyMode==="interactive"?e.targetPaintIntervalMs<=20?cw:bi:String(e.decodedFrames[0]?.pending?.frame.frameMode||e.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?sw:lg}function Dg(e,t=performance.now()){const a=zd(e);for(;e.decodedFrames.length>a;)kl(e,e.decodedFrames.shift(),"capacity");const r=e.latencyMode==="interactive"?ug:mw;let c=e.decodedFrames[0];for(;e.decodedFrames.length>0&&c&&t-c.decodedAt>r;)kl(e,e.decodedFrames.shift(),"age"),c=e.decodedFrames[0]}function Lg(e,t){if(t.hardwareAcceleration!=="prefer-hardware"||t.latencyMode==="interactive"||t.flushTimer!==null||t.flushInFlight)return;const a=fw;t.flushTimer=window.setTimeout(async()=>{t.flushTimer=null;const r=performance.now();if(Pl(t,r),jt.get(e)!==t||t.decoder.state!=="configured"||t.pendingFrames.size===0||t.inputSerial<=t.lastFlushInputSerial||t.lastOutputAt>0&&r-t.lastOutputAt<a)return;const c=t.inputSerial;t.flushInFlight=!0,t.flushCount+=1,t.keyFrameSeen=!1;try{await t.decoder.flush(),t.lastFlushInputSerial=Math.max(t.lastFlushInputSerial,c)}catch{jt.get(e)===t&&bl(t)}finally{t.flushInFlight=!1,jt.get(e)===t&&t.inputSerial>c&&t.pendingFrames.size>0&&performance.now()-t.lastOutputAt>=a&&Lg(e,t)}},a)}function $w(e,t,a,r){const c=performance.now();if(t.interactiveBackingWidth>0&&t.interactiveBackingHeight>0&&c-t.interactiveBackingMeasuredAt<iw)return{width:Math.min(a,t.interactiveBackingWidth),height:Math.min(r,t.interactiveBackingHeight)};const u=typeof e.getBoundingClientRect=="function"?e.getBoundingClientRect():{width:Number(e.clientWidth||e.width||0),height:Number(e.clientHeight||e.height||0)},p=Math.max(1,Math.min(2,Number(globalThis.devicePixelRatio)||1)),h=Math.max(0,Number(e.width||0)),f=Math.max(0,Number(e.height||0)),k=u.width>0?Math.round(u.width*p):h||pf,M=u.height>0?Math.round(u.height*p):f||ff,b=Math.min(1,k/a,M/r),T=Math.min(1,Math.max(pf/a,ff/r)),A=Math.min(1,aw/a,ow/r),x=Math.max(.01,Math.min(A,Math.max(T,b)));return t.interactiveBackingWidth=Math.max(1,Math.round(a*x)),t.interactiveBackingHeight=Math.max(1,Math.round(r*x)),t.interactiveBackingMeasuredAt=c,{width:t.interactiveBackingWidth,height:t.interactiveBackingHeight}}function bf(e,t,a){const r=performance.now();try{if(!a.pending||Rg(a.pending)){t.droppedForLatency+=1;return}let c=1;try{const M=t.onBeforePaint?.(a.pending.frame);typeof M=="number"&&Number.isFinite(M)&&(c=Math.max(.05,Math.min(1,M)))}catch{}const u=t.latencyMode==="interactive"?$w(e,t,a.width,a.height):{width:a.width,height:a.height},p=u.width,h=u.height,f=e.width!==p||e.height!==h;f&&(e.width=p,e.height=h);const k=Ng(e,t.latencyMode,t.hardwareAcceleration==="prefer-software");if(k){const M=k.context.globalAlpha;k.context.globalAlpha=f||t.lastPaintAt<=0||t.hardwareAcceleration!=="prefer-hardware"?1:c;try{k.context.drawImage(a.videoFrame,0,0,a.width,a.height,0,0,p,h)}finally{k.context.globalAlpha=M}}if(a.pending){const M=performance.now(),T=t.latencyMode==="interactive"?Eg(e,a.pending.frame):Td(e,a.width,a.height,Vd,64,a.pending.frame),A=Pw(a.pending.frame);try{t.onPaint?.(A,{deviceId:A.deviceId,frameSeq:A.frameSeq,mode:A.frameMode||A.mode||A.codec||A.mimeType,width:a.width,height:a.height,byteLength:A.byteLength,queuedForMs:Math.max(0,r-a.pending.queuedAt),decodedForMs:Math.max(0,a.decodedAt-a.pending.queuedAt),scheduledForMs:Math.max(0,r-a.decodedAt),drawMs:Math.max(0,M-r),queueSize:a.pending.queueSize,renderQueueSize:t.decodedFrames.length,droppedForLatency:t.droppedForLatency,h264DecodeAcceleration:t.hardwareAcceleration,decoderLabel:t.hardwareAcceleration,decoderFlushCount:t.flushCount,decoderTimestampFallbacks:t.timestampFallbacks,decoderInputCount:t.inputSerial,decoderOutputCount:t.outputSerial,targetPaintIntervalMs:t.targetPaintIntervalMs,canvasPresentation:k?.presentation||"sync",interactiveBufferWaitCount:t.interactiveBufferWaitCount,interactiveBufferWaitMs:t.interactiveBufferWaitMs,interactiveQueueDrainCount:t.interactiveQueueDrainCount,interactiveBurstOutputWindowMs:t.interactiveBurstOutputWindowMs,interactiveBurstTailHoldCount:t.interactiveBurstTailHoldCount,visualHash:T.visualHash,visualChanged:T.visualChanged,paintedAt:M})}catch{}}t.lastPaintAt=performance.now()}finally{a.videoFrame.close()}}function Ml(e,t){if(t.renderTimer!==null||t.decodedFrames.length===0)return;const a=Math.max(16,Math.min(250,t.targetPaintIntervalMs||1e3/12)),r=()=>{if(t.renderTimer=null,t.renderScheduledAt=0,t.decodedFrames.length===0)return;const c=performance.now();if(Dg(t,c),t.decodedFrames.length===0){t.interactiveBurstTailHoldArmed=!1;return}if(t.latencyMode==="interactive"){const f=t.targetPaintIntervalMs<=20;if(f&&!t.interactiveBufferPrimed){t.interactiveBufferStartedAt<=0&&(t.interactiveBufferStartedAt=c,t.interactiveBufferWaitCount+=1);const M=t.decodedFrames.length>=lw,b=c-t.interactiveBufferStartedAt>=uw;if(!M&&!b){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}t.interactiveBufferWaitMs+=Math.max(0,c-t.interactiveBufferStartedAt),t.interactiveBufferPrimed=!0}else f||(t.interactiveBufferPrimed=!0);if(!f&&t.interactiveBurstTailHoldArmed&&t.decodedFrames.length===1&&c-t.decodedFrames[0].decodedAt<=ug-Aw){t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstTailHoldCount+=1,t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}const k=t.decodedFrames.shift();if(k)try{bf(e,t,k)}catch{}t.decodedFrames.length===0&&(t.interactiveQueueDrainCount+=1,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1),Ml(e,t);return}const u=t.lastPaintAt>0?t.lastPaintAt+a:c+dw;if(!(c+pw>=u||t.decodedFrames.length>=Math.max(1,zd(t)-1))){t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r);return}const h=t.decodedFrames.shift();if(h)try{bf(e,t,h)}catch{}Ml(e,t)};t.renderScheduledAt=performance.now(),t.renderTimer=window.requestAnimationFrame(r)}function Og(e,t){if(jt.get(e)!==t||t.decoder.state==="closed")return!1;for(t.renderTimer!==null&&(window.cancelAnimationFrame(t.renderTimer),t.renderTimer=null),t.renderScheduledAt=0;t.decodedFrames.length>1;)kl(t,t.decodedFrames.shift());return t.lastPaintAt=0,t.interactiveBufferPrimed=!1,t.interactiveBufferStartedAt=0,t.interactiveBurstTailHoldArmed=!1,t.interactiveBurstOutputTimeCursor=0,t.interactiveBurstOutputTimeCount=0,t.interactiveBurstOutputCadenceMs=0,t.interactiveBurstOutputWindowMs=0,Ml(e,t),!0}function Qu(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const e of xo){const t=jt.get(e);if(!t||t.decoder.state==="closed"){xo.delete(e);continue}Og(e,t)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Qu),window.addEventListener("focus",Qu),window.addEventListener("pageshow",Qu));function Tn(e){Tg(e),xo.delete(e),Cl.delete(e);const t=jt.get(e);if(t){jt.delete(e),vg+=1,Ag(t),t.onBeforePaint=void 0,t.onPaint=void 0,Fg(t);try{t.decoder.state!=="closed"&&t.decoder.reset()}catch{}try{t.decoder.state!=="closed"&&t.decoder.close()}catch{}Ns("close",e)}}function pi(e){e&&(Ta.delete(e),Mo.delete(e),Md.delete(e),Rd.delete(e),xd.delete(e),Cl.delete(e),Is.delete(e),Tn(e))}function Vw(e,t){const a=jt.get(e),r=Ta.get(e);if(!a&&!r)return null;const c=p=>p>0?Math.max(0,t-p):void 0,u=a?.pendingFrames.values().next().value;return{canvasId:ki.get(e)||0,canvasWidth:Math.max(0,Number(e.width||0)),canvasHeight:Math.max(0,Number(e.height||0)),decoderState:a?.decoder.state||"fallback-pending",configured:a?.configured||!1,keyFrameSeen:a?.keyFrameSeen||!1,codec:a?.codec||r?.codec||"",requestedAcceleration:a?.requestedAcceleration||r?.requested||ta.h264DecodeAcceleration,configuredAcceleration:a?.hardwareAcceleration||r?.actual||ta.h264DecodeAcceleration,latencyMode:a?.latencyMode||r?.latencyMode||"smooth",decodeQueueSize:Math.max(0,Number(a?.decoder.decodeQueueSize||0)),decodeQueueHighWaterMark:Math.max(0,Number(a?.decodeQueueHighWaterMark??0),Number(r?.decodeQueueHighWaterMark??0)),decodeQueueOverflowSamples:Math.max(0,Number(a?.decodeQueueOverflowSamples??0),Number(r?.decodeQueueOverflowSamples??0)),decodeQueueOverflowAgeMs:a?.decodeQueueOverflowStartedAt?Math.max(0,t-a.decodeQueueOverflowStartedAt):r?.decodeQueueOverflowAgeMs,pendingFrameCount:a?.pendingFrames.size||0,pendingFrameBytes:a?.pendingFrameBytes||0,pendingFrameHighWaterMark:a?.pendingFrameHighWaterMark||0,pendingFrameByteHighWaterMark:a?.pendingFrameByteHighWaterMark||0,pendingFrameEvictionCount:a?.pendingFrameEvictionCount||0,pendingFrameUnmatchedOutputCount:a?.pendingFrameUnmatchedOutputCount||0,pendingFrameOldestAgeMs:u?Math.max(0,t-u.queuedAt):void 0,pendingFrameMaxCount:pg,pendingFrameMaxBytes:fg,pendingFrameMaxAgeMs:$d,renderQueueSize:a?.decodedFrames.length||0,renderQueueHighWaterMark:a?.renderQueueHighWaterMark||0,renderQueueCapacityDropCount:a?.renderQueueCapacityDropCount||0,renderQueueAgeDropCount:a?.renderQueueAgeDropCount||0,interactiveBurstTailHoldCount:a?.interactiveBurstTailHoldCount||0,interactiveBurstOutputWindowMs:Math.max(0,Number(a?.interactiveBurstOutputWindowMs||0)),interactivePipelineRecoveryBytes:Math.max(0,Number(a?.interactivePipelineRecoveryBytes||0)),targetPaintIntervalMs:Math.max(0,Number(a?.targetPaintIntervalMs||0)),droppedForLatency:Math.max(0,Number(a?.droppedForLatency||0)),inputCount:a?.inputSerial??r?.inputCount??0,outputCount:a?.outputSerial??r?.outputCount??0,lastInputAgeMs:c(a?.lastInputAt??r?.lastInputAt??0),lastOutputAgeMs:c(a?.lastOutputAt??r?.lastOutputAt??0),lastPaintAgeMs:c(a?.lastPaintAt??r?.lastPaintAt??0),softwareFallbackReason:r?.reason,softwareFallbackAt:r?.failedAt,softwareFallbackCount:r?.failureCount||0}}function el(e,t={}){const a=performance.now(),c=(e?[e]:[...new Set([...xo,...Mo])]).map(h=>Vw(h,a)).filter(h=>h!==null),u=c.reduce((h,f)=>h+f.pendingFrameCount,0),p=c.reduce((h,f)=>h+f.pendingFrameBytes,0);return{capturedAt:Date.now(),hardwareRequestPolicy:"all-active",activeDecoderCount:c.filter(h=>h.decoderState!=="fallback-pending").length,hardwareLeaseCount:ko.size,hardwareReleaseGeneration:Es,hardwareRecoveryProbeCount:wg,lastHardwareRecoveryProbeAt:Sg,activeSoftwareFallbackCount:c.filter(h=>h.configuredAcceleration==="prefer-software"&&h.requestedAcceleration==="prefer-hardware").length,decoderCreateCount:bg,decoderCloseCount:vg,activeDecoderHighWaterMark:Ad,decoderLifecycleSequence:yg,decoderLifecycleEvents:t.includeLifecycleEvents===!1?[]:vs.map(h=>({...h})),softwareFallbackEventCount:Cg,lastSoftwareFallbackReason:kg,lastSoftwareFallbackAt:Mg,pendingFrameCount:u,pendingFrameBytes:p,canvases:c}}function bl(e,t=1){try{e.decoder.state!=="closed"&&e.decoder.reset()}catch{}e.configured=!1,e.configKey="",e.keyFrameSeen=!1,Ag(e),Fg(e),e.lastPaintAt=0,e.lastOutputAt=0,e.lastInputAt=0,e.interactiveBufferPrimed=!1,e.interactiveBufferStartedAt=0,e.lastInputFrameSeq=void 0,e.nextChunkTimestampUs=0,e.healthSampleStartedAt=performance.now(),e.healthInputSerial=e.inputSerial,e.healthOutputSerial=e.outputSerial,e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,e.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t)))}function zw(e,t,a=performance.now()){const r=Math.max(0,Number.isFinite(t)?t:0);if(e.decodeQueueHighWaterMark=Math.max(e.decodeQueueHighWaterMark,r),r<=ww)return e.decodeQueueOverflowStartedAt=0,e.decodeQueueOverflowSamples=0,!1;e.decodeQueueOverflowStartedAt<=0?(e.decodeQueueOverflowStartedAt=a,e.decodeQueueOverflowSamples=1):e.decodeQueueOverflowSamples+=1;const c=Math.max(0,a-e.decodeQueueOverflowStartedAt);return r>=Sw||e.decodeQueueOverflowSamples>=kw&&c>=Cw}function Uw(e,t,a,r,c,u){t.decoder.configure(a),t.configured=!0,t.configKey=r,t.codec=a.codec,t.requestedAcceleration=u,t.hardwareAcceleration=c,t.keyFrameSeen=!1,t.nextChunkTimestampUs=0,t.lastInputFrameSeq=void 0,Ns("configure",e)}function qw(e,t){if(t.latencyMode!=="interactive"||t.hardwareAcceleration!=="prefer-hardware")return!1;const a=performance.now();if(a-t.healthSampleStartedAt<hw)return!1;const r=t.inputSerial-t.healthInputSerial,c=t.outputSerial-t.healthOutputSerial;return t.healthSampleStartedAt=a,t.healthInputSerial=t.inputSerial,t.healthOutputSerial=t.outputSerial,r<gw||c/Math.max(1,r)>=bw?!1:(El(e,t.requestedAcceleration,"interactive-health"),Tn(e),!0)}function fi(e,t=1){if(!e)return!1;const a=jt.get(e);return a?(a.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(t))),Tn(e),!0):!1}function Gw(e){if(!e)return!1;const t=jt.get(e);return t?Og(e,t):!1}function Kw(e,t,a,r="interactive",c){Tn(e);const u=performance.now(),p=tw(t.payload,t.uncompressedByteLength||0),h=String(t.streamId||"mode5");let f=Is.get(e);if(!f||f.streamId!==h||f.width!==p.width||f.height!==p.height){const B=new Uint8ClampedArray(p.width*p.height*4);for(let q=3;q<B.length;q+=4)B[q]=255;f={streamId:h,width:p.width,height:p.height,rgba:B,imageData:new ImageData(B,p.width,p.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Is.set(e,f)}if(!f)throw new Error("Mode 5 canvas state could not be initialized.");f.inputSerial+=1;const M=Number(t.streamFrameSeq||0);if(M>0&&(f.lastStreamFrameSeq=M),!p.keyFrame&&!f.keyFrameSeen)return;p.keyFrame&&(f.keyFrameSeen=!0);const b=nw(f.rgba,f.width,f.height,p),T=performance.now();try{c?.(t)}catch{}(e.width!==f.width||e.height!==f.height)&&(e.width=f.width,e.height=f.height);const A=Ng(e,r),x=performance.now();b&&A?.context.putImageData(f.imageData,0,0,b.x,b.y,b.width,b.height);const E=performance.now();f.outputSerial+=1,a?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.mimeType,width:f.width,height:f.height,byteLength:t.byteLength,queuedForMs:Math.max(0,E-u),decodedForMs:Math.max(0,T-u),scheduledForMs:0,drawMs:Math.max(0,E-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:f.inputSerial,decoderOutputCount:f.outputSerial,targetPaintIntervalMs:Math.max(1,Number(t.durationUs||0)/1e3||1e3/30),canvasPresentation:A?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(t.contentHash||""),visualChanged:Number(t.deltaVisualTileCount||0)>0,paintedAt:E})}const Xu=[{code:30,maxFrameSize:1620,maxMacroblocksPerSecond:40500},{code:31,maxFrameSize:3600,maxMacroblocksPerSecond:108e3},{code:32,maxFrameSize:5120,maxMacroblocksPerSecond:216e3},{code:40,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:41,maxFrameSize:8192,maxMacroblocksPerSecond:245760},{code:42,maxFrameSize:8704,maxMacroblocksPerSecond:522240},{code:50,maxFrameSize:22080,maxMacroblocksPerSecond:589824},{code:51,maxFrameSize:36864,maxMacroblocksPerSecond:983040},{code:52,maxFrameSize:36864,maxMacroblocksPerSecond:2073600}];function vf(e,t){for(let a=Math.max(0,t);a+3<e.length;a+=1)if(!(e[a]!==0||e[a+1]!==0)){if(e[a+2]===1)return{index:a,length:3};if(e[a+2]===0&&e[a+3]===1)return{index:a,length:4}}return null}function Yw(e){let t=0;for(;t<e.length;){const a=vf(e,t);if(!a)break;const r=a.index+a.length,c=vf(e,r),u=c?.index??e.length;if(r<u&&(e[r]&31)===7){const p=[];let h=0;for(let f=r+1;f<u;f+=1){const k=e[f];if(h>=2&&k===3){h=0;continue}p.push(k),h=k===0?h+1:0}if(p.length>=3)return`avc1.${p.slice(0,3).map(f=>f.toString(16).toUpperCase().padStart(2,"0")).join("")}`}t=c?c.index:e.length}return""}function Qw(e,t,a,r,c=""){const u=Math.ceil(e/16)*Math.ceil(t/16),p=a>0?1e6/a:30,h=u*p,f=Xu.find(k=>u<=k.maxFrameSize&&h<=k.maxMacroblocksPerSecond)||Xu[Xu.length-1];return Yw(r)||c||`avc1.42E0${f.code.toString(16).toUpperCase().padStart(2,"0")}`}function Ud(e,t,a,r,c="smooth",u=()=>!1,p=!0,h){Is.delete(e);const f=String(t.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",k=Math.max(1,Math.floor(t.width||960)),M=Math.max(1,Math.floor(t.height||540)),b=Math.max(1,Math.floor(t.durationUs||1e6/12)),T=r||ta.h264DecodeAcceleration,A=t.isKeyFrame===!0||String(t.chunkType||"").toLowerCase()==="key";Fw(e,T,A);let x=gf(e,c,T);const E=Qw(k,M,b,t.payload,x.codec);let B=Id(e,T),q="";const G=()=>{q=[t.streamId||"",t.commandId||"",k,M,E,f,T,B,c].join("|")};G(),x.onBeforePaint=h,x.onPaint=a,x.configured&&x.decoder.state!=="configured"&&(x.configured=!1,x.configKey=""),x.configured&&x.configKey!==q&&(Tn(e),x=gf(e,c,T),x.onBeforePaint=h,x.onPaint=a,B=Id(e,T),G());const ne=()=>({codec:E,codedWidth:k,codedHeight:M,hardwareAcceleration:B,optimizeForLatency:!0,avc:{format:f}}),re=P=>x.hardwareAcceleration!=="prefer-hardware"||!El(e,x.requestedAcceleration,P)?!1:(Tn(e),p&&A&&Ud(e,t,a,T,c,u,!1,h),!0),O=()=>{try{return Uw(e,x,ne(),q,B,T),!0}catch(P){if(re("configure-error"))return!1;throw Tn(e),P}};if(!x.configured&&!O())return;const ie=Number(t.streamFrameSeq||0);if(ie>0&&x.lastInputFrameSeq!==void 0&&(ie<=x.lastInputFrameSeq&&(!A||ie===x.lastInputFrameSeq||(bl(x,x.lastInputFrameSeq-ie+1),!O()))||ie>x.lastInputFrameSeq+1&&(bl(x,ie-x.lastInputFrameSeq-1),!A||!O()))||(ie>0&&(x.lastInputFrameSeq=ie),!A&&!x.keyFrameSeen))return;A&&(x.keyFrameSeen=!0);const J=Number(x.decoder.decodeQueueSize||0);if(zw(x,J)){if(x.latencyMode==="interactive"&&x.hardwareAcceleration==="prefer-hardware"){re("decode-queue-overflow");return}if(bl(x),!A||!O())return;x.keyFrameSeen=!0}const de=x.nextChunkTimestampUs;x.nextChunkTimestampUs+=b,Nw(x,de,t,J,u),Ig(e,x),x.inputSerial+=1,x.lastInputAt=performance.now(),x.inputSerial===1&&Ns("first-input",e);const se=t.payload.buffer,pe=se instanceof ArrayBuffer?[se]:[],ce=xg(t,b),W=!ce&&x.outputSerial>0,ee=A&&x.latencyMode==="interactive"&&x.hardwareAcceleration==="prefer-hardware"&&(ce||W),L=ce?mg:dg;ee&&(Pa(x),x.interactivePipelineGuardTimestampUs=de);const _=x.interactivePipelineGuardTimestampUs!==null&&x.interactivePipelineRecoveryFrames.length>0,K=ee||_?Dw(x,t,u):!1,ue=new EncodedVideoChunk({type:A?"key":"delta",timestamp:de,duration:b,data:t.payload,transfer:pe});t.payload=hg;try{x.decoder.decode(ue)}catch(P){if(re("decode-error"))return;throw Tn(e),P}K&&jt.get(e)===x&&x.interactivePipelineGuardTimestampUs===de&&ee&&Lw(e,x,de,L),Lg(e,x),qw(e,x)}async function Ju(e,t,a,r,c,u="smooth",p=a,h){if(Bw(t)){a()||Kw(e,t,r,u,h);return}if(jw(t)){a()||Ud(e,t,r,c,u,p,!0,h);return}if(Is.delete(e),_w(t)){Tn(e);const A=Ww(t);if(a())return;try{h?.(t)}catch{}(e.width!==A.width||e.height!==A.height)&&(e.width=A.width,e.height=A.height);const x=e.getContext("2d"),E=performance.now();x?.putImageData(A,0,0);const B=performance.now(),q=Td(e,A.width,A.height,Vd,64,t);r?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:A.width,height:A.height,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,B-E),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ta.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:q.visualHash,visualChanged:q.visualChanged,paintedAt:B});return}Tn(e);const f=new Blob([t.payload],{type:t.mimeType}),k=await createImageBitmap(f);if(a()){k.close();return}const M=t.width||k.width||960,b=t.height||k.height||540;try{h?.(t)}catch{}(e.width!==M||e.height!==b)&&(e.width=M,e.height=b);const T=e.getContext("2d");if(T){const A=performance.now();T.clearRect(0,0,M,b),T.drawImage(k,0,0,M,b);const x=performance.now(),E=Td(e,M,b);r?.(t,{deviceId:t.deviceId,frameSeq:t.frameSeq,mode:t.frameMode||t.mode||t.codec||t.mimeType,width:M,height:b,byteLength:t.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,x-A),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:ta.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:E.visualHash,visualChanged:E.visualChanged,paintedAt:x})}k.close()}function Xw(e){queueMicrotask(e)}function Jw(e){return e?(e.width=0,e.height=0,!0):!1}function Nl(e,t){if(!e)return!1;try{t?.(e)}finally{Jw(e)}return!0}function qd(e,t){if(!e||!t)return 0;const a=Math.max(0,Number(e.get(t)||0))+1;return e.set(t,a),a}function Zw(e,t){if(!e||!t)return 0;const a=Number(e.get(t)||0);return Number.isSafeInteger(a)&&a>0?a:qd(e,t)}function yf(e,t){return qd(e,t)}function wf(e,t,a){return!!e&&!!t&&Number(a)>0&&Number(e.get(t)||0)===Number(a)}function eS(e,t,a){if(!e||!e.has(t))return!1;const r=e.get(t);return e.delete(t),Nl(r,a)}function tS(e,t,a){const r=new Set;for(const c of e||[])if(c){for(const u of c.values())u&&r.add(u);c.clear()}for(const c of t||[])c&&r.add(c);for(const c of r)Nl(c,a);return r.size}function nS(e,{isCurrent:t,dispose:a,schedule:r=Xw}){return!e||typeof t!="function"?!1:(r(()=>{t(e)||Nl(e,a)}),!0)}const rS=new Uint8Array(0);function So(e){if(!e||typeof e!="object")return e;const t=e.payload;return t instanceof Uint8Array&&t.byteLength===0?e:{...e,payload:rS}}function aS(e,t){const a=So(t);return e.set(t.deviceId,a),a}function oS(e,t){for(const[a,r]of t.entries())e.set(a,So(r));return t.clear(),new Map(e)}function tl(e){return!!e&&typeof e=="object"}function Zu(e){let t=e;return tl(t)&&"data"in t&&(t=t.data),tl(t)&&"session"in t&&(t=t.session),!tl(t)||typeof t.access_token!="string"||!t.access_token||!tl(t.user)||typeof t.user.id!="string"||!t.user.id?null:t}function cx(e){return e?.access_token?e.refresh_token?"":"refresh-token-required":"access-token-required"}const Sf=Object.freeze(["nativeCaptureTelemetryAvailable","nativeCaptureTelemetryVersion","nativeEncoderHardwareAccelerationKnown","nativeEncoderHardwareAccelerated","nativeEncoderHardwareQueryStatus","nativeCaptureDisplayId","nativeCaptureFps","nativeCompressionFps","nativeEncodedFps","nativeCaptureSampleCount","nativeEncodableFrameCount","nativeSkippedFrameCount","nativeCompressionOutputCount","nativeEncodedFrameCount","nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs","nativeCaptureResourceTelemetryAvailable","nativeCaptureTelemetryAt"]),iS=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeOutputQueueAwaitingKeyFrame","nativeCopyTelemetryAvailable","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function sS(e){return[String(e?.deviceId||""),String(e?.sessionId||""),String(e?.streamId||""),String(e?.commandId||""),String(Number(e?.captureGeneration||0)||0),String(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1),String(e?.streamPurpose||"")].join("\0")}function cS(e,t){return!!t&&String(e?.deviceId||"")===String(t.deviceId||"")&&String(e?.sessionId||"")===String(t.sessionId||"")&&String(e?.streamId||"")===String(t.streamId||"")&&String(e?.commandId||"")===String(t.commandId||"")&&(Number(e?.captureGeneration||0)||0)===(Number(t.captureGeneration||0)||0)&&(Number.isFinite(Number(e?.monitorIndex))?Number(e.monitorIndex):-1)===(Number.isFinite(Number(t.monitorIndex))?Number(t.monitorIndex):-1)&&String(e?.streamPurpose||"")===String(t.streamPurpose||"")}function lS(){return{ownerKey:"",values:Object.create(null)}}function Cf(e){e&&(e.ownerKey="",e.values=Object.create(null))}function uS(e,t,a){if(!e||!t||!cS(e,a))return!1;const r=sS(a);if(t.ownerKey!==r&&(t.ownerKey=r,t.values=Object.create(null)),e.nativeCaptureTelemetryAvailable===!1){for(const c of Sf)c!=="nativeCaptureTelemetryAvailable"&&(delete t.values[c],delete e[c]);return t.values.nativeCaptureTelemetryAvailable=!1,!0}if(e.nativeCaptureResourceTelemetryAvailable===!1)for(const c of iS)delete t.values[c],delete e[c];for(const c of Sf)Object.prototype.hasOwnProperty.call(e,c)?t.values[c]=e[c]:Object.prototype.hasOwnProperty.call(t.values,c)&&(e[c]=t.values[c]);return!0}const _g=new ArrayBuffer(0);function dS(e){return`${String(e?.streamId||"")}:${Number(e?.frameSeq||0)}`}function mS(e){return!e||typeof e!="object"||e.payload instanceof ArrayBuffer&&e.payload.byteLength===0?e:{...e,payload:_g}}function pS(){let e=null,t="";return{accept(a){e=mS(a)},publish(){const a=e;if(e=null,!a)return null;const r=dS(a);return r===t?null:(t=r,a)},clear(){e=null,t=""},inspect(){return{pending:e?1:0,pendingPayloadBytes:Number(e?.payload?.byteLength||0),publishedKey:t}}}}const fS=0,hS=1,kf=3,Mf=Object.freeze([750,1500,3e3,5e3]);function mn(e){return Math.max(0,Math.floor(Number(e)||0))}function Zn(e,t){return!t||t.active||t.socket!==null||t.audioContext!==null||t.reconnectTimer!==null||t.statsTimer!==null||t.scheduledSourceCount!==0||t.pendingDecodeCount!==0||t.workletNodeCount!==0||t.workletPortCount!==0||t.pcmRingCapacityBytes!==0||t.pcmRingBufferedBytes!==0||t.pendingWorkletPacketCount!==0||t.pendingWorkletPacketBytes!==0||t.retainedFrameCount!==0||t.retainedPayloadBytes!==0?!1:e.delete(t)}function gS(){const e=new Set;let t=null;const a={ownerCount:0,socketCount:0,audioContextCount:0,workletNodeCount:0,workletPortCount:0},r=()=>{let c=0,u=0,p=0,h=0;for(const f of e){const k=Number(f.socket?.readyState);c+=f.socket&&k!==kf?1:0,u+=f.audioContext===null?0:1,p+=mn(f.workletNodeCount),h+=mn(f.workletPortCount)}a.ownerCount=Math.max(a.ownerCount,e.size),a.socketCount=Math.max(a.socketCount,c),a.audioContextCount=Math.max(a.audioContextCount,u),a.workletNodeCount=Math.max(a.workletNodeCount,p),a.workletPortCount=Math.max(a.workletPortCount,h)};return{createOwner({deviceId:c,socket:u,audioContext:p,reconnectTimer:h=null,statsTimer:f=null}){t=null;const k={deviceId:String(c||""),active:!0,socket:u||null,audioContext:p||null,reconnectTimer:h,statsTimer:f,scheduledSourceCount:0,pendingDecodeCount:0,workletNodeCount:0,workletPortCount:0,workletNodeCreateCount:0,pcmRingCapacityBytes:0,pcmRingBufferedBytes:0,pendingWorkletPacketCount:0,pendingWorkletPacketBytes:0,pendingWorkletPacketHighWater:0,pendingWorkletByteHighWater:0,retainedFrameCount:0,retainedPayloadBytes:0};return e.add(k),r(),k},recordTerminalFailure(c,u,p="playback"){return e.has(c)?(t={deviceId:c.deviceId,phase:String(p||"playback").slice(0,64),message:String(u||"Remote audio playback failed.").slice(0,512)},!0):!1},deactivate(c){return e.has(c)?(c.active=!1,Zn(e,c)):!1},setSocket(c,u){return e.has(c)?(c.socket=u||null,r(),Zn(e,c)):!1},setAudioContext(c,u){return e.has(c)?(c.audioContext=u||null,r(),Zn(e,c)):!1},setReconnectTimer(c,u){return e.has(c)?(c.reconnectTimer=u??null,Zn(e,c)):!1},setStatsTimer(c,u){return e.has(c)?(c.statsTimer=u??null,Zn(e,c)):!1},setScheduledSourceCount(c,u){return e.has(c)?(c.scheduledSourceCount=mn(u),Zn(e,c)):!1},setPendingDecodeCount(c,u){return e.has(c)?(c.pendingDecodeCount=mn(u),Zn(e,c)):!1},setWorkletNode(c,u,p,h=c?.workletNodeCreateCount){return e.has(c)?(c.workletNodeCount=mn(u),c.workletPortCount=mn(p),c.workletNodeCreateCount=mn(h),r(),Zn(e,c)):!1},setPcmRing(c,u,p){return e.has(c)?(c.pcmRingCapacityBytes=mn(u),c.pcmRingBufferedBytes=Math.min(c.pcmRingCapacityBytes,mn(p)),Zn(e,c)):!1},setPendingWorkletPackets(c,u,p,h=c?.pendingWorkletPacketHighWater,f=c?.pendingWorkletByteHighWater){return e.has(c)?(c.pendingWorkletPacketCount=mn(u),c.pendingWorkletPacketBytes=mn(p),c.pendingWorkletPacketHighWater=Math.max(c.pendingWorkletPacketHighWater,mn(h)),c.pendingWorkletByteHighWater=Math.max(c.pendingWorkletByteHighWater,mn(f)),Zn(e,c)):!1},setRetainedFrame(c,u,p=0){return e.has(c)?(c.retainedFrameCount=mn(u),c.retainedPayloadBytes=mn(p),Zn(e,c)):!1},releaseIfDrained(c){return Zn(e,c)},hasOwner(c){return e.has(c)},snapshot(){const c=[...e].map(p=>{const h=Number(p.socket?.readyState),f=p.socket&&h!==kf?1:0;return{deviceId:p.deviceId,active:p.active,socketCount:f,openSocketCount:h===hS?1:0,connectingSocketCount:h===fS?1:0,audioContextCount:p.audioContext===null?0:1,reconnectTimerCount:p.reconnectTimer===null?0:1,statsTimerCount:p.statsTimer===null?0:1,scheduledSourceCount:p.scheduledSourceCount,pendingDecodeCount:p.pendingDecodeCount,workletNodeCount:p.workletNodeCount,workletPortCount:p.workletPortCount,workletNodeCreateCount:p.workletNodeCreateCount,pcmRingCapacityBytes:p.pcmRingCapacityBytes,pcmRingBufferedBytes:p.pcmRingBufferedBytes,pendingWorkletPacketCount:p.pendingWorkletPacketCount,pendingWorkletPacketBytes:p.pendingWorkletPacketBytes,pendingWorkletPacketHighWater:p.pendingWorkletPacketHighWater,pendingWorkletByteHighWater:p.pendingWorkletByteHighWater,retainedFrameCount:p.retainedFrameCount,retainedPayloadBytes:p.retainedPayloadBytes}}),u=p=>c.reduce((h,f)=>h+mn(f[p]),0);return{ownerCount:c.length,activeOwnerCount:c.filter(p=>p.active).length,socketCount:u("socketCount"),openSocketCount:u("openSocketCount"),connectingSocketCount:u("connectingSocketCount"),audioContextCount:u("audioContextCount"),reconnectTimerCount:u("reconnectTimerCount"),statsTimerCount:u("statsTimerCount"),scheduledSourceCount:u("scheduledSourceCount"),pendingDecodeCount:u("pendingDecodeCount"),workletNodeCount:u("workletNodeCount"),workletPortCount:u("workletPortCount"),workletNodeCreateCount:u("workletNodeCreateCount"),pcmRingCapacityBytes:u("pcmRingCapacityBytes"),pcmRingBufferedBytes:u("pcmRingBufferedBytes"),pendingWorkletPacketCount:u("pendingWorkletPacketCount"),pendingWorkletPacketBytes:u("pendingWorkletPacketBytes"),pendingWorkletPacketHighWater:u("pendingWorkletPacketHighWater"),pendingWorkletByteHighWater:u("pendingWorkletByteHighWater"),retainedFrameCount:u("retainedFrameCount"),retainedPayloadBytes:u("retainedPayloadBytes"),ownerHighWater:a.ownerCount,socketHighWater:a.socketCount,audioContextHighWater:a.audioContextCount,workletNodeHighWater:a.workletNodeCount,workletPortHighWater:a.workletPortCount,lastTerminalFailure:t,owners:c}}}}function bS(e){const t=Math.max(0,Math.floor(Number(e)||0));return Mf[Math.min(t,Mf.length-1)]}function vS({schedule:e=(c,u)=>setTimeout(c,u),cancel:t=c=>clearTimeout(c),onTimerChange:a=()=>{},onReconnect:r=()=>{}}={}){let c=null,u=null,p=null,h=0,f=!1;const k=()=>{if(p===null)return!1;const b=p;return p=null,t(b),a(null),!0},M={replaceSocket(b){return f||!b?!1:(c=b,u=null,!0)},isCurrent(b){return!f&&c===b},markHealthy(b){return M.isCurrent(b)?(h=0,!0):!1},isTerminalSocket(b){return f&&u===b},retireTerminalSocket(b){return M.isTerminalSocket(b)?(u=null,!0):!1},scheduleReconnect(b){if(!M.isCurrent(b)||p!==null)return!1;const T=bS(h);h+=1;let A=null;return A=e(()=>{if(p===A&&(p=null,a(null),!!M.isCurrent(b)))try{r(b)}catch{M.scheduleReconnect(b)}},T),p=A,a(A),!0},stop(){return f?!1:(f=!0,k(),u=c,c=null,!0)},inspect(){return Object.freeze({active:!f,hasSocket:c!==null,hasTerminalSocket:u!==null,reconnectTimerCount:p===null?0:1,reconnectAttempt:h})}};return M}function xf({reconnectOwner:e,lifecycleLedger:t,lifecycleOwner:a,socket:r}){const c=e?.isCurrent?.(r)===!0,u=e?.isTerminalSocket?.(r)===!0;return!c&&!u||u&&e.retireTerminalSocket(r)!==!0?"stale":(t?.setSocket?.(a,null),c?"current":"terminal")}const Ot=gS();function yS(){let e=Promise.resolve(),t=0,a=0,r=0;return{acquire(c){const u=++r;let p=!1,h=!1,f=!1,k;const M=new Promise(x=>{k=x}),b=Promise.resolve(e).catch(()=>{});e=b.then(()=>M);const T=()=>f?!1:(f=!0,p&&(t=Math.max(0,t-1)),k(),!0),A=b.then(async()=>{if(h||f)return T(),null;p=!0,t+=1,a=Math.max(a,t);try{return await c({ownerId:u,release:T})}catch(x){throw T(),x}});return{ownerId:u,ready:A,release:T,cancel(){h=!0,p||T()}}},snapshot(){return{activeOwnerCount:t,ownerHighWater:a,nextOwnerId:r}}}}const wS=yS(),Rf=1e3;function SS({enabled:e,now:t,lastPublishedAt:a,intervalMs:r=Rf}){if(!e)return!1;const c=Math.max(0,Number(t)||0),u=Math.max(0,Number(a)||0),p=Math.max(1,Number(r)||Rf);return u<=0||c-u>=p}const jg="livedesk-remote-audio-v1",CS=250,kS=160,Pd=4;function MS(e){const t=String(e||"").toLowerCase();return t.includes("audio/pcm")||t.includes("f32le")||t.includes("s16le")}function Ed(e={},t={}){const a=String(t.deviceId||""),r=String(t.streamId||"");return!!a&&!!r&&String(e.deviceId||"")===a&&String(e.streamId||"")===r}function xS(e={},t={}){if(!Ed(e,t))return{accepted:!1,reason:"owner-mismatch",nextFrameSeq:Math.max(0,Math.floor(Number(t.lastFrameSeq)||0))};const a=Math.max(0,Math.floor(Number(e.frameSeq)||0)),r=Math.max(0,Math.floor(Number(t.lastFrameSeq)||0));return a>0&&a<=r?{accepted:!1,reason:"sequence-not-newer",nextFrameSeq:r}:{accepted:!0,reason:"",nextFrameSeq:a}}function RS(e={}){const t=String(e.capturePhase||"").toLowerCase(),a=String(e.backendKind||"").toLowerCase(),r=e.captureAlive===!0?!0:e.captureAlive===!1?!1:null,c=e.helperAlive===!0?!0:e.helperAlive===!1?!1:null,u=Math.max(0,Math.floor(Number(e.helperPid)||0)),p=a==="windows-wasapi-in-process",h=a==="macos-screencapturekit-helper"||a==="linux-system-audio-helper",f=p||h,k=e.helperRequired===!0?!0:e.helperRequired===!1?!1:h?!0:p?!1:null,M=k===!1?!0:k===!0?c===!0&&u>0:!1,b=t==="starting"||t==="capture-active-awaiting-current-pcm",T=t==="active"&&r===!0&&f&&M,A=t==="failed"||t==="stopped"||r===!1||t==="active"&&(!f||!M);let x="";return b?x="awaiting-current-pcm":!p&&!h?x="backend-unknown":t!=="active"?x=t?`phase-${t}`:"phase-unknown":r!==!0?x="capture-not-alive":k===!0&&c!==!0?x="external-helper-not-alive":k===!0&&u<=0&&(x="external-helper-pid-missing"),{capturePhase:t,backendKind:a,captureAlive:r,helperAlive:c,helperPid:u,helperRequired:k,inProcessBackend:p,externalHelperBackend:h,backendKnown:f,helperReady:M,awaitingCurrentPcm:b,healthy:T,failed:A,reason:x}}function Ea(e,t){const a=Math.floor(Number(e));return Number.isFinite(a)&&a>0?a:t}function Gd(e={}){const t=Math.max(8e3,Math.min(192e3,Ea(e.sampleRate,48e3))),a=Math.max(1,Math.min(8,Ea(e.channels,2))),r=String(e.mimeType||"").toLowerCase(),u=String(e.sampleFormat||"").toLowerCase()==="s16le"||r.includes("s16le")||r.includes("audio/l16")?"s16le":"f32le";return{sampleRate:t,channels:a,sampleFormat:u}}function Kd(e={}){const t=Gd(e),a=Math.max(1,Math.min(250,Ea(e.maxDurationMs,250))),r=Math.max(1,Math.ceil(t.sampleRate*a/1e3));return{...t,maxDurationMs:a,capacityFrames:r,capacityBytes:r*t.channels*Float32Array.BYTES_PER_ELEMENT}}function AS(e={}){const t=Kd(e),a=Math.max(0,Math.min(t.maxDurationMs,Ea(e.targetLeadMs,160))),r=Math.min(t.capacityFrames,Math.max(1,Math.ceil(t.sampleRate*a/1e3)));let c=new Float32Array(t.capacityFrames*t.channels),u=0,p=0,h=0,f=0,k=!1,M=!1,b=0,T=0,A=0;const x={acceptedFrames:0,droppedFrames:0},E=()=>(A+=1,{sampleRate:t.sampleRate,channels:t.channels,sampleFormat:t.sampleFormat,maxDurationMs:t.maxDurationMs,targetLeadMs:a,capacityFrames:M?0:t.capacityFrames,capacityBytes:M?0:t.capacityBytes,bufferedFrames:M?0:h,bufferedBytes:M?0:h*t.channels*Float32Array.BYTES_PER_ELEMENT,bufferedMs:M?0:h*1e3/t.sampleRate,droppedFrames:b,underflowCount:T,started:!M&&k,disposed:M}),B=()=>{u=0,p=0,h=0,f=0,k=!1},q=()=>{M||(B(),c=new Float32Array(0),M=!0)},G=(O,ie=0,J,de=t.sampleFormat)=>{if(x.acceptedFrames=0,x.droppedFrames=0,M||!(O instanceof ArrayBuffer))return x;const se=Math.max(0,Math.floor(Number(ie)||0)),pe=Math.max(0,O.byteLength-se),ce=Math.min(pe,Math.max(0,Math.floor(Number(J??pe)||0))),W=de==="s16le",ee=W?2:4,L=ee*t.channels,_=Math.floor(ce/L);if(_<=0)return x;const K=Math.min(_,t.capacityFrames),ue=_-K,P=Math.max(0,h+K-t.capacityFrames);P>0&&(u=(u+P)%t.capacityFrames,h-=P);const N=ue+P;b+=N;const te=new DataView(O,se,ce);for(let we=ue;we<_;we+=1){const me=p*t.channels,Fe=we*t.channels;for(let H=0;H<t.channels;H+=1){const Se=(Fe+H)*ee,Ce=W?te.getInt16(Se,!0)/32768:te.getFloat32(Se,!0);c[me+H]=Number.isFinite(Ce)?Math.max(-1,Math.min(1,Ce)):0}p=(p+1)%t.capacityFrames}return h+=K,!k&&h>=r&&(k=!0),x.acceptedFrames=K,x.droppedFrames=N,x};return{writePcm:(O={})=>G(O.buffer,O.byteOffset,O.byteLength,O.sampleFormat),writePcmBuffer:G,readToChannels:(O,ie=t.sampleRate)=>{if(!Array.isArray(O)||O.length===0)return;let J=Number.POSITIVE_INFINITY;for(let pe=0;pe<O.length;pe+=1){const ce=O[pe];J=Math.min(J,ce?.length||0)}if(M||!Number.isFinite(J)||J<=0||!k){for(let pe=0;pe<O.length;pe+=1)O[pe]?.fill?.(0);return}const de=Math.max(8e3,Math.min(192e3,Ea(ie,t.sampleRate))),se=t.sampleRate/de;for(let pe=0;pe<J;pe+=1){if(h<=0){k=!1,T+=1,f=0;for(let ee=0;ee<O.length;ee+=1)O[ee].fill(0,pe);break}const ce=u*t.channels;for(let ee=0;ee<O.length;ee+=1){const L=Math.min(ee,t.channels-1);O[ee][pe]=c[ce+L]}f+=se;const W=Math.min(h,Math.floor(f));W>0&&(u=(u+W)%t.capacityFrames,h-=W,f-=W)}},flush:B,dispose:q,snapshot:E,getSnapshotCount:()=>A}}function IS(e={}){const t=Math.max(1,Math.min(Pd,Ea(e.maxPendingPackets,Pd))),a=Math.max(1,Ea(e.maxPendingBytes,1)),r=new Map;let c=0,u=0,p=0,h=0,f=0,k=!1;const M=()=>({terminal:k,maxPendingPackets:t,maxPendingBytes:a,pendingPacketCount:r.size,pendingPacketBytes:c,pendingPacketHighWater:u,pendingByteHighWater:p,acceptedCount:h,droppedCount:f});return{claim(b,T){const A=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),x=Math.max(0,Math.floor(Number(T)||0));return k||!A||x<=0||r.has(A)||r.size>=t||c+x>a?(f+=1,!1):(r.set(A,x),c+=x,u=Math.max(u,r.size),p=Math.max(p,c),h+=1,!0)},acknowledge(b){const T=typeof b=="number"&&Number.isFinite(b)?b:String(b||""),A=r.get(T);return A===void 0?!1:(r.delete(T),c=Math.max(0,c-A),!0)},terminate(){return r.clear(),c=0,k=!0,M()},getPendingPacketCount:()=>r.size,getPendingPacketBytes:()=>c,getPendingPacketHighWater:()=>u,getPendingByteHighWater:()=>p,snapshot:M}}function Fl(e,t){const a=String(e?.name||"");if(!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(a)||!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t))throw new Error("Remote Audio worklet function binding name is invalid.");const r=`const ${a} = ${Function.prototype.toString.call(e)};`;return a===t?r:`${r}
|
|
4
|
+
const ${t} = ${a};`}const TS=Fl(Ea,"positiveInteger"),PS=Fl(Gd,"normalizeRemoteAudioPcmFormat"),ES=Fl(Kd,"remoteAudioPcmRingCapacity"),NS=Fl(AS,"createRemoteAudioPcmRing"),FS=`
|
|
5
|
+
const REMOTE_AUDIO_PCM_RING_MAX_MS = ${CS};
|
|
6
|
+
const REMOTE_AUDIO_PCM_TARGET_LEAD_MS = ${kS};
|
|
10
7
|
${TS}
|
|
8
|
+
${PS}
|
|
9
|
+
${ES}
|
|
10
|
+
${NS}
|
|
11
11
|
|
|
12
12
|
class LiveDeskRemoteAudioProcessor extends AudioWorkletProcessor {
|
|
13
13
|
constructor() {
|
|
@@ -161,22 +161,22 @@ registerProcessor(
|
|
|
161
161
|
'${jg}',
|
|
162
162
|
LiveDeskRemoteAudioProcessor
|
|
163
163
|
);
|
|
164
|
-
`;function Xt(e,t){const a=s.useRef(e),r=s.useRef(t);a.current=e,r.current=t;const[c,u]=s.useState(()=>({ownerKey:e,value:t})),p=s.useCallback((h,f)=>{h===a.current&&u(k=>{if(h!==a.current)return k;const M=k.ownerKey===h?k.value:r.current,b=typeof f=="function"?f(M):f;return{ownerKey:h,value:b}})},[]);return[c.ownerKey===e?c.value:t,p]}const
|
|
165
|
-
`):String(e||""),
|
|
164
|
+
`;class DS extends Error{constructor(t,a){super(`${t}:${a}`),this.name="StartupOwnerDeadlineError",this.code=t,this.timeoutMs=a}}function Bg({timeoutMs:e,code:t,setTimer:a=setTimeout,clearTimer:r=clearTimeout}){const c=Number(e);if(!Number.isSafeInteger(c)||c<1)throw new Error("startup-owner-deadline-timeout-invalid");const u=String(t||"").trim();if(!u)throw new Error("startup-owner-deadline-code-invalid");let p=!1,h=!1,f=null;const k=new Promise((T,A)=>{f=a(()=>{f=null,!p&&(h=!0,A(new DS(u,c)))},c)});return Object.freeze({waitFor:T=>p?Promise.reject(new Error("startup-owner-deadline-disposed")):Promise.race([Promise.resolve().then(T),k]),dispose:()=>{p||(p=!0,f!==null&&(r(f),f=null))},snapshot:()=>Object.freeze({active:!p&&f!==null,disposed:p,timedOut:h})})}function Xt(e,t){const a=s.useRef(e),r=s.useRef(t);a.current=e,r.current=t;const[c,u]=s.useState(()=>({ownerKey:e,value:t})),p=s.useCallback((h,f)=>{h===a.current&&u(k=>{if(h!==a.current)return k;const M=k.ownerKey===h?k.value:r.current,b=typeof f=="function"?f(M):f;return{ownerKey:h,value:b}})},[]);return[c.ownerKey===e?c.value:t,p]}const LS=5e3,OS=150,_S=1200,Af=5e3;function jS(e=0){const t=Math.max(0,Math.floor(Number(e)||0)),a=Math.min(3,Math.max(0,t-1));return Math.min(_S,OS*2**a)}const If=2,BS=new Set(["control_not_ready","capture_transition_in_progress","device-not-connected","input_channel_reconnecting","not-connected","remote-input-ready-timeout","remote-input-socket-closed","remote-input-timeout","remote-input-transport-error","stale_capture_generation","stale_control_monitor","stale_control_session"]),HS=new Set(["device-not-connected","input_channel_reconnecting","not-connected","remote-input-socket-closed","remote-input-timeout","remote-input-transport-error"]);function WS(e){return HS.has(String(e||"").trim().toLowerCase())}function $S(e){return BS.has(String(e||"").trim().toLowerCase())}function ed(e,t="en",a=""){const r=String(e||"").trim().toLowerCase(),c=String(a||"").trim().toLowerCase(),u=/^ko(?:-|$)/i.test(String(t||"").trim());return r==="input_permission_denied"||r==="accessibility-permission-required"?u?"원격 입력 권한이 필요합니다. Client 컴퓨터의 접근성 권한을 확인해주세요.":"Remote input permission is required. Check Accessibility on the Client.":$S(r)?u?"입력 연결을 복구하고 있습니다. 잠시 후 자동으로 다시 연결됩니다.":"Remote input is recovering and will reconnect automatically.":c==="native-apply"?u?"원격 컴퓨터가 입력을 적용하지 못했습니다. Client의 권한과 입력 후킹 앱을 확인해주세요.":"The remote computer could not apply the input. Check Client permissions and any input-hooking app.":u?"원격 입력 경로를 사용할 수 없습니다. Client 연결 상태를 확인해주세요.":"The remote input route is unavailable. Check the Client connection."}const Tf=4e3,VS=2500,zS=1e4,Yd=new TextDecoder,nl=[],Pf=new Map,Nd=new Set;function US(){const e=[...Nd].map(a=>a()),t=a=>e.reduce((r,c)=>r+Number(c[a]||0),0);return{ownerCount:e.length,activeOwnerCount:e.filter(a=>a.active).length,socketCount:t("socketCount"),openSocketCount:t("openSocketCount"),connectingSocketCount:t("connectingSocketCount"),closingSocketCount:t("closingSocketCount"),closingSocketTimerCount:t("closingSocketTimerCount"),closingSocketTimeoutCount:t("closingSocketTimeoutCount"),expectedBindingCount:t("expectedBindingCount"),reconnectTimerCount:t("reconnectTimerCount"),statsTimerCount:t("statsTimerCount"),configurationRefreshTimerCount:t("configurationRefreshTimerCount"),handoffDeadlineTimerCount:t("handoffDeadlineTimerCount"),restartTokenCount:t("restartTokenCount"),retainedFrameCount:t("retainedFrameCount"),retainedPayloadBytes:t("retainedPayloadBytes"),owners:e}}function qS(){return Ot.snapshot()}function GS(e){const a=(Array.isArray(e)?e:[e||In]).map(r=>Kh(r||In));return[...new Set(a.filter(Boolean))]}function KS(){const[e,t]=s.useState(null),[a,r]=s.useState(0),[c,u]=s.useState(!0),[p,h]=s.useState(!1),[f,k]=s.useState(!1),[M,b]=s.useState(""),T=s.useRef(0),A=s.useRef(Promise.resolve()),x=s.useCallback(async()=>{k(!0),h(!0),b("");try{await Xv()}catch(E){const B=E instanceof Error?E.message:String(E);throw b(B||"VuvoDesk Hub sign-out could not be confirmed."),E}finally{h(!1)}},[]);return s.useEffect(()=>{let E=!0,B=0;const q=(J,de=!1)=>{const se=T.current+1;T.current=se;const pe=A.current.catch(()=>{}).then(async()=>{let ce=null;try{if(!E||se!==T.current)return;ce=Bg({timeoutMs:6e3,code:"auth-session-restore-timeout"});const W=await ce.waitFor(J);if(!E||se!==T.current)return;let ee=Zu(W);if(window.liveDesk?.auth&&ee){const{hydrateDesktopRendererAuthSession:L,persistRotatedDesktopAuthSession:_}=await mr(async()=>{const{hydrateDesktopRendererAuthSession:P,persistRotatedDesktopAuthSession:N}=await import("./desktop-auth-renderer-contract-CBeQI8Qu.js");return{hydrateDesktopRendererAuthSession:P,persistRotatedDesktopAuthSession:N}},[]),K=ee,ue=Zu(await L(ee,P=>Ct.auth.setSession(P)));if(!ue)return;ee=Zu(await _(K,ue,window.liveDesk.auth.persistSession))}if(!E||se!==T.current)return;(de||ee)&&(t(ee),ee&&r(L=>L+1)),ee&&(k(!1),b(""))}finally{ce?.dispose(),E&&se===T.current&&u(!1)}});return A.current=pe,pe},G=()=>{if(document.visibilityState==="hidden")return;const J=Date.now();J-B<1e3||(B=J,q(()=>window.liveDesk?.auth?.getSession?.()||Ct.auth.getSession(),!1).catch(()=>{}))},{data:{subscription:ne}}=Ct.auth.onAuthStateChange((J,de)=>{window.liveDesk?.auth||(T.current+=1,!de&&J==="SIGNED_OUT"?x().catch(()=>{}):de&&J==="SIGNED_IN"&&(k(!1),b("")),t(de),de&&r(se=>se+1),u(!1))}),re=window.liveDesk?.auth?.onComplete?.(J=>{if(J.ok&&J.session)q(()=>J.session,!1).catch(()=>{});else if(J.ok&&J.signedOut){T.current+=1,t(null),u(!1);const de=A.current.catch(()=>{}).then(async()=>{await Ct.auth.signOut({scope:"local"})});A.current=de,de.catch(()=>{})}}),O=()=>window.liveDesk?.auth?.getSession?.()||Ct.auth.getSession();q(O,!0).catch(()=>{E&&q(O,!1).catch(()=>{})});const ie=()=>G();return window.addEventListener("pageshow",G),window.addEventListener("online",G),window.addEventListener("focus",G),document.addEventListener("visibilitychange",ie),()=>{E=!1,T.current+=1,re?.(),ne.unsubscribe(),window.removeEventListener("pageshow",G),window.removeEventListener("online",G),window.removeEventListener("focus",G),document.removeEventListener("visibilitychange",ie)}},[x]),{session:e,sessionHydrationRevision:a,loading:c,hubSessionRevoking:p,hubSessionBlocked:f,hubSessionRevocationError:M,revokeHubSession:x}}function YS(e,t=!0,a="",r=a,c="",u=""){const[p,h]=s.useState(""),[f,k]=s.useState(t?"connecting":"idle"),[M,b]=s.useState(null),[T,A]=s.useState(""),x=s.useRef(new Map),E=s.useRef(null),B=s.useRef(Ku(null,t?"reset-enabled":"reset-idle")),q=s.useRef(0),G=s.useRef(""),ne=s.useRef(0),re=s.useCallback(P=>{const N=Ku(B.current,P);return B.current=N,k(N.phase),N},[]),O=Array.isArray(e)?e.join(`
|
|
165
|
+
`):String(e||""),ie=s.useMemo(()=>GS(e),[O]),J=s.useMemo(()=>ie.find(P=>fl(P)==="loopback")||ie[0]||In,[ie]),de=`${t?"enabled":"disabled"}
|
|
166
166
|
${r}
|
|
167
167
|
${c}
|
|
168
168
|
${u}
|
|
169
|
-
${O}`,[
|
|
169
|
+
${O}`,[se,pe]=Xt(de,null),[ce,W]=Xt(de,nl);s.useEffect(()=>{const P=q.current+1;return q.current=P,G.current=de,ne.current+=1,E.current=null,x.current.clear(),B.current=Ku(null,t?"reset-enabled":"reset-idle"),pe(de,null),W(de,nl),A(""),h(""),b(null),k(B.current.phase),()=>{q.current===P&&(q.current+=1)}},[t,de]);const ee=s.useCallback(async P=>{const N=q.current,te=()=>N===q.current&&G.current===de;if(!t){pe(de,null),W(de,nl),A(""),h(""),re("reset-idle"),b(null);return}let we=null;const me=Date.now(),Fe=ie.filter(R=>(x.current.get(R)||0)<=me),H=Ky({eligibleCandidates:Fe,fallbackHubBaseUrl:J,publicConsole:yi(),authenticated:!!a});if(H.candidates.length===0){if(!te())return;throw new Error("No VuvoDesk Hub endpoint is reachable. Retrying shortly.")}for(const R of H.candidates)try{const[Se,Ce]=await Promise.all([ze("/api/remote/status",{signal:P,timeoutMs:Tf,transport:H.transport},R),ze("/api/remote/devices",{signal:P,timeoutMs:Tf,transport:H.transport},R)]);if(P?.aborted)throw P.reason||new Error("VuvoDesk Hub snapshot cancelled.");if(!te())return;if(!Array.isArray(Ce.devices))throw new Error("Invalid Hub devices response.");if(!Yy({expectedWorkspaceId:c,expectedWorkspaceKind:u,verifiedPublicDirect:H.transport==="p2p",statusWorkspace:Se.workspace}))throw new Error("The Hub is connected to a different VuvoDesk workspace.");x.current.delete(R),pe(de,Se),W(de,Ce.devices),A(R),h(""),b(null),re("success");return}catch(Se){if(!te())return;if(P?.aborted)throw Se;we=Se,H.transport==="auto"&&x.current.set(R,Date.now()+1e4)}if(te())throw A(""),we||new Error("No VuvoDesk Hub endpoint is reachable.")},[re,a,t,c,u,J,ie,W,pe,de]),L=s.useCallback(P=>{const N=Jv(P);h(N.message),b(N),re("failure")},[re]),_=s.useCallback(()=>{const P=ne.current;x.current.clear(),Ss(E,()=>ee()).catch(N=>{ne.current===P&&L(N)})},[L,ee]),K=s.useCallback(P=>{const N=()=>{ne.current===P&&Ss(E,()=>ee()).catch(we=>{ne.current===P&&L(we)})},te=E.current;te?te.then(N,N):N()},[L,ee]),ue=s.useCallback(()=>{const P=ne.current+1;ne.current=P,x.current.clear(),yi()&&(M?.kind==="signal-service-unavailable"||M?.kind==="p2p-unavailable")&&Zv(),h(""),b(null),re("retry"),K(P)},[re,M?.kind,K]);return s.useEffect(()=>{if(x.current.clear(),!t){pe(de,null),W(de,nl),A(""),h(""),re("reset-idle"),b(null);return}B.current.hasSnapshot||re("retry");let P=!0,N=null;const te=new AbortController,we=()=>{const me=ne.current;Ss(E,()=>ee(te.signal)).catch(H=>{P&&!te.signal.aborted&&ne.current===me&&L(H)}).finally(()=>{P&&!te.signal.aborted&&(N=window.setTimeout(we,VS))})};return we(),()=>{P=!1,ne.current+=1,te.abort(new Error("VuvoDesk Hub snapshot polling stopped.")),N!==null&&window.clearTimeout(N)}},[re,t,W,pe,L,ee,de]),s.useEffect(()=>{if(!t)return;let P=0;const N=()=>{if(document.visibilityState==="hidden")return;const me=Date.now();if(!(me-P<1e3))if(P=me,x.current.clear(),yi()){const Fe=ne.current+1;ne.current=Fe,ey(),K(Fe)}else _()},te=()=>{yi()&&ty()},we=()=>{if(document.visibilityState==="hidden"){te();return}N()};return window.addEventListener("pageshow",N),window.addEventListener("pagehide",te),window.addEventListener("online",N),window.addEventListener("focus",N),document.addEventListener("visibilitychange",we),()=>{window.removeEventListener("pageshow",N),window.removeEventListener("pagehide",te),window.removeEventListener("online",N),window.removeEventListener("focus",N),document.removeEventListener("visibilitychange",we)}},[t,K,_]),{status:se,devices:ce,error:p,connectionState:f,failure:M,refresh:_,retry:ue,hubBaseUrl:T||J,hubCandidates:ie}}function QS(e,t=e?.user?.id||"",a=0){const[r,c]=s.useState(""),u=e?.user?.id||"",p=s.useRef(null),h=s.useRef(0),f=`${u}
|
|
170
170
|
${t}
|
|
171
|
-
${a}`,[k,M]=Xt(f,null);s.useEffect(()=>{h.current+=1,p.current=null,M(f,null),c("")},[f]);const b=s.useCallback(async()=>{const T=h.current;if(!u||!t){M(f,null);return}const{data:
|
|
171
|
+
${a}`,[k,M]=Xt(f,null);s.useEffect(()=>{h.current+=1,p.current=null,M(f,null),c("")},[f]);const b=s.useCallback(async()=>{const T=h.current;if(!u||!t){M(f,null);return}const{data:A,error:x}=await Ct.rpc("get_livedesk_workspace_remote_host_status",{p_workspace_id:t});if(T!==h.current)return;if(x){c(x.message);return}const E=Array.isArray(A)?A[0]:A;if(!E||E.ok!==!0){M(f,null),c(E?.reason?String(E.reason).replaceAll("-"," "):"VuvoDesk Hub discovery is unavailable.");return}M(f,{workspace_id:String(E.workspace_id||""),node_id:String(E.node_id||""),endpoint:String(E.endpoint||""),endpoint_candidates:Array.isArray(E.endpoint_candidates)?E.endpoint_candidates.map(String):[],manager_package:String(E.manager_package||""),manager_version:String(E.manager_version||""),agent_package:String(E.agent_package||""),active:E.active===!0,activated_at:E.activated_at?String(E.activated_at):null,updated_at:String(E.updated_at||""),expires_at:E.expires_at?String(E.expires_at):null}),c("")},[f,M,u,t]);return s.useEffect(()=>{if(!u||!t)return;let T=!0,A=null;const x=()=>{Ss(p,b).catch(()=>{}).finally(()=>{T&&(A=window.setTimeout(x,zS))})};return x(),()=>{T=!1,A!==null&&window.clearTimeout(A)}},[b,u,t]),s.useEffect(()=>{if(!u||!t)return;let T=0;const A=()=>{if(document.visibilityState==="hidden")return;const E=Date.now();E-T<1e3||(T=E,Ss(p,b).catch(()=>{}))},x=()=>A();return window.addEventListener("pageshow",A),window.addEventListener("online",A),window.addEventListener("focus",A),document.addEventListener("visibilitychange",x),()=>{window.removeEventListener("pageshow",A),window.removeEventListener("online",A),window.removeEventListener("focus",A),document.removeEventListener("visibilitychange",x)}},[b,u,t]),{target:k,error:r,refresh:b}}function XS(e,t=e?.user?.id||"",a=0,r="free",c="free",u){const h=`${e?.user?.id||""}
|
|
172
172
|
${t}
|
|
173
|
-
${a}`,[f,k]=Xt(h,null),M=r!=="free"?{workspace_id:t,plan:r,status:c==="active"?"active":["refunded","cancelled"].includes(c)?c:"inactive"}:null;s.useLayoutEffect(()=>{k(h,M)},[c,h,k,t,r]);const b=s.useCallback(async()=>{await u?.()},[u]),T=s.useMemo(()=>!(!f||f.status!=="active"),[f]);return{entitlement:f,licensed:T,loading:!1,error:"",refresh:b}}const ks={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},KS=2500,YS=3e4,QS=750,XS=2e3,JS=8*1024,ZS=32*1024,eC=6,Bg=new Map;function tC(e){return Bg.get(e)}const ed={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function nC(e,t,a){const r=Number(t);if(!Number.isFinite(r)||r<=0)return 0;const c=a-r,u=e.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return e.minimumHubClockOffsetMs=c,0;const p=Math.max(0,c-Number(u));return p>YS?(e.minimumHubClockOffsetMs=c,0):p}function Ae(e){if(e==null||e==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}const rC=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function aC(e){return Number(e.nativeCaptureTelemetryVersion)>=5&&rC.every(t=>Ae(e[t])!==void 0)&&typeof e.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e.nativeCopyTelemetryAvailable===!0}function oC(e,t,a){if(!e||typeof e!="object")return null;const r=e,c=String(r.deviceId||t||"").trim(),u=String(r.sessionId||"").trim(),p=String(r.streamId||"").trim(),h=r.streamPurpose==="control"?"control":r.streamPurpose==="wall"?"wall":null,f=String(r.commandId||"").trim(),k=Number(r.captureGeneration||0),M=Number(r.monitorIndex??-1),b=r.readOnlyControlBorrow===!0,T=r.presentationPurpose==="wall"?"wall":void 0;return!c||c!==t||!h||!(h===a||a==="wall"&&h==="control"&&b&&T==="wall")||!u||!p||!f||!Number.isSafeInteger(k)||k<=0||!Number.isSafeInteger(M)||M<0?null:{deviceId:c,sessionId:u,streamId:p,streamPurpose:h,commandId:f,captureGeneration:k,monitorIndex:M,readOnlyControlBorrow:b,presentationPurpose:T,effectiveProfile:r.effectiveProfile&&typeof r.effectiveProfile=="object"?r.effectiveProfile:null}}function Ef(e,t,a=In,r={},c=""){const[u,p]=Xt(c,Pf),[h,f]=s.useState("idle"),[k,M]=s.useState(""),[b,T]=s.useState(ks),I=s.useRef(new Map),x=s.useRef(new Map),E=s.useRef(new Map),H=s.useRef(null);H.current===null&&(H.current=Ny());const Q=s.useRef(0),G=s.useRef(new Map),ne=s.useRef(new Map),ae=s.useRef({enabled:!1,token:"",reason:""}),O=s.useRef(new Map),te=s.useRef(null),Z=s.useRef(new Map),[me,le]=s.useState(0),pe=s.useRef(r.onFrame),se=s.useRef(r.onStreamBound),W=s.useRef(r.onStreamReady),re=s.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),L=s.useMemo(()=>[...e].sort().join(","),[e]),_=t&&L.length>0,q=s.useRef(!1),ue=s.useRef(L),P=s.useRef(c);ue.current=L,P.current=c,s.useLayoutEffect(()=>(q.current=_,()=>{q.current=!1}),[_]);const F=Number.isFinite(r.fps)?Number(r.fps):2,ee=Number.isFinite(r.maxWidth)?Number(r.maxWidth):640,Se=Number.isFinite(r.maxHeight)?Number(r.maxHeight):360,de=Number.isFinite(r.quality)?Number(r.quality):45,Fe=Number.isFinite(r.configurationRefreshMs)?Math.max(0,Math.round(Number(r.configurationRefreshMs))):0,j=String(r.frameMode||r.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",R=r.streamPurpose==="control"?"control":"wall",Ce=r.allowReadOnlyControlBorrow===!0,we=r.forceRestart===!0,Ve=String(r.forceRestartToken||"").trim(),Oe=String(r.restartReason||"").trim();ae.current={enabled:we,token:Ve,reason:Oe};const it=s.useMemo(()=>{const oe=Object.entries(r.monitorSelections||{}).filter(([$])=>!!$).sort(([$],[ye])=>$.localeCompare(ye));return JSON.stringify(Object.fromEntries(oe))},[r.monitorSelections]),z=s.useMemo(()=>{const oe=Object.entries(r.connectionSessionIds||{}).filter(([$])=>!!$).map(([$,ye])=>[$,String(ye||"").trim()]).sort(([$],[ye])=>$.localeCompare(ye));return JSON.stringify(Object.fromEntries(oe))},[r.connectionSessionIds]);s.useEffect(()=>{pe.current=r.onFrame},[r.onFrame]),s.useEffect(()=>{se.current=r.onStreamBound},[r.onStreamBound]),s.useEffect(()=>{W.current=r.onStreamReady},[r.onStreamReady]);const Me=s.useCallback((oe,$="livedesk-frame-socket-release")=>{Fy(oe,$,H.current)},[]),je=s.useCallback(oe=>{const $=O.current.get(oe);$!==void 0&&(window.clearTimeout($),O.current.delete(oe))},[]),qe=s.useCallback((oe,$)=>{const ye=String(oe||"").trim();if(!ye||O.current.has(ye))return!1;const V=window.setTimeout(()=>{O.current.get(ye)===V&&(O.current.delete(ye),!(!q.current||P.current!==$||!ue.current.split(",").includes(ye)||Hu(E.current.get(ye),$))&&le(Ge=>Ge+1))},QS);return O.current.set(ye,V),!0},[]),kt=s.useCallback(()=>{if(!_)return[];const oe=L.split(",").filter(Boolean),$=Dy(oe,E.current,O.current,c);for(const ye of $)qe(ye,c);return $.length===oe.length&&$.length>0&&f("connecting"),$},[L,qe,_,c]),Te=s.useCallback(oe=>{const $=Z.current.get(oe);$!==void 0&&(window.clearTimeout($),Z.current.delete(oe))},[]),Be=s.useCallback((oe,$=!0)=>{for(const ye of O.current.values())window.clearTimeout(ye);O.current.clear();for(const ye of Z.current.values())window.clearTimeout(ye);Z.current.clear();for(const ye of E.current.values())ye.expectedBinding=void 0,Me(ye,oe);E.current.clear(),G.current.clear(),ne.current.clear(),I.current=new Map,x.current.clear(),re.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},$&&(p(c,Pf),M(""),T(ks),f("idle"))},[Me,p,c]),K=s.useCallback(()=>{const oe=[...E.current.values()].map($=>$.socket);if(oe.length===0){f("idle");return}if(oe.some($=>$.readyState===WebSocket.OPEN)){f("open");return}if(oe.some($=>$.readyState===WebSocket.CONNECTING)){f("connecting");return}f("closed")},[]),ve=s.useCallback((oe,$,ye,V)=>{if($.disposed||$.socket.readyState!==WebSocket.OPEN)return!1;try{return $.socket.send(JSON.stringify({...$.payload,type:"restart-live",deviceIds:[oe],forceRestart:!0,restartReason:ye,restartToken:V})),$.restartMayHaveApplied=!0,$.expectedBinding=void 0,Cf($.sparseTelemetry),!0}catch{return!1}},[]),st=s.useCallback((oe,$)=>{if($.disposed||E.current.get(oe)!==$||$.socket.readyState!==WebSocket.OPEN)return!1;try{return $.socket.send(JSON.stringify({...$.payload,type:"refresh-live",deviceIds:[oe],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{$.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),ot=s.useCallback((oe,$)=>{if(!q.current||$.workspaceOwnerKey!==P.current||$.disposed||!oe||oe.byteLength<5)return;const ye=Date.now(),Ge=new DataView(oe).getUint32(0,!1);if(Ge<=0||Ge+4>oe.byteLength)return;const St=new Uint8Array(oe,4,Ge),A=JSON.parse(Kd.decode(St));sS(A,$.sparseTelemetry,$.expectedBinding);const ie=Ae(A.hubPacketEpochMs),Pe=ie!==void 0&&ie>0?ie:void 0,He=nC($,Pe,ye);if(He>KS)return;const vt=new Uint8Array(oe,4+Ge),Je=Ae(A.nativeCaptureTelemetryVersion),At=Ae(A.nativeCaptureTelemetryAgeMs),_t=Ae(A.hubClientDropped),Jt=Ae(A.hubClientQueueDepth),xt=Ae(A.hubClientQueueLimit),Vt=Ae(A.hubClientBufferedBytes),g=_t!==void 0&&Jt!==void 0&&xt!==void 0&&Vt!==void 0,U={deviceId:String(A.deviceId||""),kind:A.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(A.frameSeq||0),streamFrameSeq:Number(A.streamFrameSeq||0)||void 0,streamId:String(A.streamId||""),commandId:A.commandId?String(A.commandId):void 0,sessionId:A.sessionId?String(A.sessionId):void 0,captureGeneration:Number(A.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:A.streamPurpose?String(A.streamPurpose):void 0,width:Number(A.width||0),height:Number(A.height||0),sourceWidth:Number(A.sourceWidth||0)||void 0,sourceHeight:Number(A.sourceHeight||0)||void 0,mimeType:String(A.mimeType||"image/jpeg"),mode:A.mode?String(A.mode):void 0,frameMode:A.frameMode?String(A.frameMode):void 0,frameProfile:A.frameProfile?String(A.frameProfile):void 0,encoding:A.encoding?String(A.encoding):void 0,codec:A.codec?String(A.codec):void 0,compression:A.compression?String(A.compression):void 0,pixelFormat:A.pixelFormat?String(A.pixelFormat):void 0,bytesPerPixel:Number(A.bytesPerPixel||0)||0,uncompressedByteLength:Number(A.uncompressedByteLength||0)||0,h264Format:A.h264Format?String(A.h264Format):void 0,isKeyFrame:A.isKeyFrame===!0,chunkType:A.chunkType?String(A.chunkType):void 0,timestampUs:Number(A.timestampUs||0)||0,durationUs:Number(A.durationUs||0)||0,sourceGapMs:Number(A.sourceGapMs||0)||0,agentSendGapMs:Number(A.agentSendGapMs||0)||0,agentSendDurationMs:Number(A.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(A.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(A.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(A.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(A.agentFrameAgeMs||0)||0,inputFeedbackEventId:A.inputFeedbackEventId?String(A.inputFeedbackEventId):void 0,inputFeedbackInputSeq:Ae(A.inputFeedbackInputSeq),inputFeedbackInputType:A.inputFeedbackInputType?String(A.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:Ae(A.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:Ae(A.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:Ae(A.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:Ae(A.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:Ae(A.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:Ae(A.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:Ae(A.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof A.inputFeedbackCaptureTimestampAvailable=="boolean"?A.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof A.nativeCaptureTelemetryAvailable=="boolean"?A.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:Je===void 0?void 0:Math.max(0,Je),nativeCaptureTelemetryAgeMs:At===void 0?void 0:Math.max(0,At),nativeEncoderHardwareAccelerationKnown:typeof A.nativeEncoderHardwareAccelerationKnown=="boolean"?A.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof A.nativeEncoderHardwareAccelerated=="boolean"?A.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:A.nativeEncoderHardwareQueryStatus?String(A.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:Ae(A.nativeCaptureDisplayId),nativeCaptureFps:Ae(A.nativeCaptureFps),nativeCompressionFps:Ae(A.nativeCompressionFps),nativeEncodedFps:Ae(A.nativeEncodedFps),nativeCaptureSampleCount:Ae(A.nativeCaptureSampleCount),nativeEncodableFrameCount:Ae(A.nativeEncodableFrameCount),nativeSkippedFrameCount:Ae(A.nativeSkippedFrameCount),nativeCompressionOutputCount:Ae(A.nativeCompressionOutputCount),nativeEncodedFrameCount:Ae(A.nativeEncodedFrameCount),nativeEncodeFramesInFlight:Ae(A.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:Ae(A.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:Ae(A.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:Ae(A.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:Ae(A.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:Ae(A.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:Ae(A.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:Ae(A.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:Ae(A.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:Ae(A.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:Ae(A.nativeOutputQueueDepth),nativeOutputQueueBytes:Ae(A.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:Ae(A.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:Ae(A.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:Ae(A.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof A.nativeOutputQueueAwaitingKeyFrame=="boolean"?A.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof A.nativeCopyTelemetryAvailable=="boolean"?A.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:Ae(A.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:Ae(A.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:Ae(A.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:Ae(A.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:Ae(A.pipePayloadAllocationCount),pipePayloadCopyCount:Ae(A.pipePayloadCopyCount),pipePayloadCopiedBytes:Ae(A.pipePayloadCopiedBytes),handoffDroppedFrameCount:Ae(A.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:Ae(A.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:Ae(A.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:A.nativeCaptureResourceTelemetryAvailable===!0?aC(A):A.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:A.nativeCaptureTelemetryAt?String(A.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(A.droppedByAgent||0)||0,hubIngressDropped:Number(A.hubIngressDropped||0)||0,hubClientDropped:_t,transport:A.transport?String(A.transport):void 0,videoTransport:A.videoTransport?String(A.videoTransport):void 0,frameTransportActive:A.frameTransportActive?String(A.frameTransportActive):void 0,frameTransportProtocol:A.frameTransportProtocol?String(A.frameTransportProtocol):void 0,frameTransportState:A.frameTransportState?String(A.frameTransportState):void 0,frameTransportReason:A.frameTransportReason?String(A.frameTransportReason):void 0,frameTransportChangedAt:A.frameTransportChangedAt?String(A.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(A.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(A.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:A.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:g,hubClientQueueDepth:Jt,hubClientQueueLimit:xt,hubClientBufferedBytes:Vt,udpIncompleteFrames:Number(A.udpIncompleteFrames||0)||0,hardwareEncoder:A.hardwareEncoder?String(A.hardwareEncoder):void 0,platformProfile:A.platformProfile?String(A.platformProfile):void 0,monitorIndex:Number.isFinite(Number(A.monitorIndex))?Number(A.monitorIndex):void 0,monitorCount:Number.isFinite(Number(A.monitorCount))?Number(A.monitorCount):void 0,requestedFps:Number(A.requestedFps||0)||0,effectiveFps:Number(A.effectiveFps||0)||0,captureTimingAvailable:A.captureTimingAvailable===!0,captureAverageMs:Ae(A.captureAverageMs),captureP95Ms:Ae(A.captureP95Ms),slowFrameCount:Number(A.slowFrameCount||0)||0,captureHelperRestarts:Number(A.captureHelperRestarts||0)||0,capturedAt:String(A.capturedAt||""),receivedAt:String(A.receivedAt||""),hubPacketAt:A.hubPacketAt?String(A.hubPacketAt):void 0,hubPacketEpochMs:Pe,browserReceivedEpochMs:ye,hubPacketTransitAgeMs:Pe!==void 0?He:void 0,byteLength:Number(A.byteLength||vt.byteLength),contentHash:A.contentHash?String(A.contentHash):void 0,captureMs:Ae(A.captureMs),captureStageMs:Ae(A.captureStageMs),convertMs:Number(A.convertMs||0)||0,compressMs:Number(A.compressMs||0)||0,captureSourceSerial:Number(A.captureSourceSerial||0)||0,captureSourceSkipped:Number(A.captureSourceSkipped||0)||0,deltaTileSize:Number(A.deltaTileSize||0)||0,deltaTileCount:Number(A.deltaTileCount||0)||0,deltaVisualTileCount:Number(A.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(A.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(A.deltaTotalTiles||0)||0,payload:vt};if(!U.deviceId)return;const N=$.expectedBinding;if(!N)return;const he=U.deviceId===N.deviceId&&String(U.sessionId||"")===N.sessionId&&U.streamId===N.streamId&&String(U.commandId||"")===N.commandId&&Number(U.captureGeneration||0)===N.captureGeneration&&Number(U.monitorIndex??-1)===N.monitorIndex&&String(U.streamPurpose||"")===N.streamPurpose;if(!he)return;U.currentGenerationVerified=he;const Y=Number($.payload.monitorSelections?.[U.deviceId]);if(Number.isFinite(Y)&&Number.isFinite(Number(U.monitorIndex))&&Number(U.monitorIndex)!==Y)return;const Ie={streamId:$.lastFrameStreamId,commandId:$.lastFrameCommandId,order:$.lastFrameOrder},be=Number(U.streamFrameSeq||U.frameSeq||0),Ke=!!Ie.commandId&&!!U.commandId,ut=Ie.streamId===U.streamId&&(!Ke||Ie.commandId===U.commandId),xe=Ie.order;if(ut&&xe>=be&&(xe===be||Ke))return;$.lastFrameStreamId=U.streamId,$.lastFrameCommandId=U.commandId||"",$.lastFrameOrder=be;const Ye=re.current;Ye.totalFrames+=1,Ye.totalBytes+=vt.byteLength,Ye.sampleFrames+=1,Ye.sampleBytes+=vt.byteLength;const _e=!I.current.has(U.deviceId)&&!x.current.has(U.deviceId),Wt=tS(x.current,U);_e&&(I.current.set(U.deviceId,Wt),x.current.delete(U.deviceId),p($.workspaceOwnerKey,new Map(I.current))),pe.current?.(U)},[p]);s.useEffect(()=>{if(!t||!L)return;re.current.sampleStartedAt=performance.now();const oe=window.setInterval(()=>{if(!q.current||P.current!==c)return;kt();const $=performance.now(),ye=re.current,V=Math.max(1,$-ye.sampleStartedAt);T({totalFrames:ye.totalFrames,totalBytes:ye.totalBytes,framesPerSecond:ye.sampleFrames*1e3/V,bytesPerSecond:ye.sampleBytes*1e3/V,sampleMs:V,lastUpdatedAt:Date.now()}),p(c,nS(I.current,x.current)),ye.sampleFrames=0,ye.sampleBytes=0,ye.sampleStartedAt=$},XS);return te.current=oe,()=>{window.clearInterval(oe),te.current===oe&&(te.current=null)}},[t,L,p,kt,c]),s.useEffect(()=>{const oe=()=>{const $=new Set,ye=[...E.current.values()];for(;ye.length>0;){const A=ye.pop();!A||$.has(A)||($.add(A),A.handoffFrom&&ye.push(A.handoffFrom))}const V=[...I.current.values(),...x.current.values()],Ge=[...$],St=H.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:L,active:q.current,socketCount:Ge.length+St.closingSocketCount,openSocketCount:Ge.filter(A=>A.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Ge.filter(A=>A.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:St.closingSocketCount,closingSocketTimerCount:St.closingSocketTimerCount,closingSocketTimeoutCount:St.closingSocketTimeoutCount,expectedBindingCount:Ge.filter(A=>!!A.expectedBinding).length,reconnectTimerCount:O.current.size,statsTimerCount:te.current===null?0:1,configurationRefreshTimerCount:Z.current.size,handoffDeadlineTimerCount:Ge.filter(A=>A.handoffDeadlineTimer!==void 0).length,restartTokenCount:ne.current.size,retainedFrameCount:V.length,retainedPayloadBytes:V.reduce((A,ie)=>A+Math.max(0,Number(ie.payload?.byteLength||0)),0)}};return Ed.add(oe),()=>{Ed.delete(oe)}},[L]),s.useEffect(()=>{const oe=L?L.split(",").filter(Boolean):[];if(!_){Be(t?"livedesk-no-devices":"livedesk-stream-inactive");return}const $=new Set(oe),ye=performance.now();for(const V of O.current.keys())$.has(V)||je(V);for(const V of Z.current.keys())$.has(V)||Te(V);for(const[V,Ge]of E.current.entries())$.has(V)||(je(V),Me(Ge,"livedesk-device-unsubscribed"),E.current.delete(V),G.current.delete(V),ne.current.delete(V),I.current.delete(V),x.current.delete(V));re.current.sampleStartedAt<=0&&(re.current.sampleStartedAt=ye,T({...ks,lastUpdatedAt:Date.now()}));for(const V of oe){je(V);const Ge=Number(r.monitorSelections?.[V]),St=Number.isInteger(Ge)&&Ge>=0?Ge:0,A={[V]:St},ie={type:"subscribe",deviceIds:[V],autoStartLive:t,fps:F,maxWidth:ee,maxHeight:Se,quality:de,mode:j,frameMode:j,streamPurpose:R,allowReadOnlyControlBorrow:Ce,monitorSelections:A},Pe=String(r.connectionSessionIds?.[V]||"").trim(),He=G.current.get(V)||0,vt=JSON.stringify({subscribePayload:ie,connectionSessionId:Pe}),Je=E.current.get(V),At=Number(Je?.payload.monitorSelections?.[V]),_t=Number(A[V]),Jt=!!Je&&Number.isFinite(At)&&Number.isFinite(_t)&&At!==_t,xt=!!Je&&Je?.connectionSessionId!==Pe;if(Je&&Je.payloadKey===vt&&Je.reconnectRevision===He&&Hu(Je,c))continue;Te(V);const Vt=Je&&(Je.socket.readyState===WebSocket.CONNECTING||Je.socket.readyState===WebSocket.OPEN)&&!Je.disposed?Je.handoffFrom&&!Je.handoffCompleted?Je.handoffFrom:Je:void 0,g=Je&&Je!==Vt?Je:void 0,U=`/api/remote/frames/ws?devices=${encodeURIComponent(V)}`,N=xs(Rs(U,a),U,"frame");N.binaryType="arraybuffer";const he=iS();let Y;Y={socket:N,workspaceOwnerKey:c,payload:ie,payloadKey:vt,reconnectRevision:He,connectionSessionId:Pe,restartMayHaveApplied:g?.restartMayHaveApplied===!0,generation:Q.current+1,monitorRestartToken:Jt?`monitor-${V}-${_t}-${Q.current+1}`:"",disposed:!1,handoffFrom:Vt,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:he,releaseOwnedState:()=>{Y.handoffDeadlineTimer!==void 0&&(window.clearTimeout(Y.handoffDeadlineTimer),Y.handoffDeadlineTimer=void 0),Cf(he)}},Q.current=Y.generation,(Jt||xt)&&(I.current.delete(V),x.current.delete(V),p(c,new Map(I.current))),E.current.set(V,Y),g&&(g.handoffFrom=void 0,Wu(g,V,ne.current),Me(g,"livedesk-subscription-superseded"));const Ie=()=>{Y.handoffDeadlineTimer!==void 0&&(window.clearTimeout(Y.handoffDeadlineTimer),Y.handoffDeadlineTimer=void 0)},be=()=>{Ie();const _e=$u(Y);Y.handoffCompleted=!0,Y.sentForceRestartToken=void 0,_e&&!_e.disposed&&Me(_e,"livedesk-subscription-replaced")},Ke=()=>{if(!q.current||Y.workspaceOwnerKey!==P.current||Y.disposed||E.current.get(V)!==Y){Me(Y,"livedesk-stale-frame-socket");return}je(V),M("");const _e=ae.current,Wt=_e.enabled&&(!_e.token||ne.current.get(V)!==_e.token),lt=Wt||Y.monitorRestartToken!=="",ct=Wt?_e.token:Y.monitorRestartToken,ht=Wt?_e.reason:Y.monitorRestartToken?"monitor-selection-change":"";if(N.send(JSON.stringify({...Y.payload,forceRestart:lt,restartReason:lt?ht:"",restartToken:lt?ct:""})),lt&&(Y.restartMayHaveApplied=!0),Fe>0){const nt=window.setTimeout(()=>{Z.current.get(V)===nt&&Z.current.delete(V),!(!q.current||Y.workspaceOwnerKey!==P.current)&&st(V,Y)},Math.max(1e3,Fe));Z.current.set(V,nt)}if(Wt&&_e.token&&(Y.sentForceRestartToken=_e.token,ne.current.set(V,_e.token)),Y.handoffFrom){const nt=window.setTimeout(()=>{if(Y.handoffDeadlineTimer!==nt||Y.disposed||E.current.get(V)!==Y||!Y.handoffFrom)return;Ie();const Pt=$u(Y),zt=sf(Y,Pt,c);Te(V),Wu(Y,V,ne.current),zt?E.current.set(V,Pt):(E.current.delete(V),Pt&&Me(Pt,"livedesk-handoff-owner-changed"),I.current.delete(V),x.current.delete(V),p(c,new Map(I.current)),qe(V,c)),Me(Y,"livedesk-handoff-timeout"),K()},5e3);Y.handoffDeadlineTimer=nt}else Y.handoffCompleted=!0;K()},ut=_e=>{if(!q.current||Y.workspaceOwnerKey!==P.current||Y.disposed||E.current.get(V)!==Y)return;if(typeof _e.data=="string"){try{const lt=JSON.parse(_e.data),ct=(ht,nt=!0)=>{const Pt=Y.payload.streamPurpose==="control"?"control":"wall",zt=oC(ht,V,Pt),xi=Number(Y.payload.monitorSelections?.[V]);return!zt||!Ly(zt,{deviceId:V,connectionSessionId:Y.connectionSessionId,monitorIndex:xi,streamPurpose:Pt,allowReadOnlyControlBorrow:Y.payload.allowReadOnlyControlBorrow===!0})?!1:(Y.expectedBinding=zt,se.current?.(zt),nt&&W.current?.(zt),!0)};if(lt?.type==="RemoteFrameSubscriptionError"){const ht=String(lt.error||"control-stream-start-failed");cf(ht,lt.retryScheduled===!0)?(M(""),K()):M(ht)}else if(lt?.type==="RemoteFrameLiveAutoStart"){const nt=(Array.isArray(lt.skipped)?lt.skipped:[]).find(Pt=>Pt?.deviceId===V);if(nt)cf(nt.reason,nt.retryScheduled===!0)?(M(""),K()):M(String(nt.reason||"control-stream-start-failed"));else if(Array.isArray(lt.started)){const Pt=lt.started.find(zt=>zt?.deviceId===V);Pt&&(M(""),ct(Pt,Pt.ready===!0)&&be())}}else lt?.type==="RemoteFrameStreamReady"&<.deviceId===V&&ct(lt)&&(M(""),be())}catch{}return}const Wt=_e.data instanceof ArrayBuffer?_e.data:null;Wt&&(M(""),ot(Wt,Y))},xe=()=>{!q.current||Y.workspaceOwnerKey!==P.current||Y.disposed||E.current.get(V)!==Y||f("connecting")},Ye=()=>{Ie();const _e=!Y.disposed;Y.disposed=!0,Y.handoffCompleted=!0;const Wt=Y.detachListeners;Y.detachListeners=void 0,Wt?.();const lt=E.current.get(V);lt===Y&&Te(V);let ct=!1;if(lt===Y){const ht=$u(Y);sf(Y,ht,c)?(E.current.set(V,ht),ct=!0):(E.current.delete(V),ht&&(Me(ht,"livedesk-handoff-owner-changed"),I.current.delete(V),x.current.delete(V),p(c,new Map(I.current))))}_e&<===Y&&Wu(Y,V,ne.current),K(),_e&&q.current&&Y.workspaceOwnerKey===P.current&<===Y&&!ct&&(je(V),qe(V,Y.workspaceOwnerKey))};Y.detachListeners=()=>{N.removeEventListener("open",Ke),N.removeEventListener("message",ut),N.removeEventListener("error",xe),N.removeEventListener("close",Ye)},N.addEventListener("open",Ke),N.addEventListener("message",ut),N.addEventListener("error",xe),N.addEventListener("close",Ye)}K()},[Ce,t,Te,je,Me,Fe,z,L,F,j,ot,a,Se,ee,it,r.monitorSelections,p,de,me,Be,qe,st,R,_,K,c]),s.useEffect(()=>{if(!_)return;const oe=()=>{document.visibilityState==="visible"&&kt()};return oe(),document.addEventListener("visibilitychange",oe),window.addEventListener("pageshow",oe),window.addEventListener("focus",oe),()=>{document.removeEventListener("visibilitychange",oe),window.removeEventListener("pageshow",oe),window.removeEventListener("focus",oe)}},[kt,_]),s.useEffect(()=>{if(!_||!we||!Ve)return;const oe=L?L.split(",").filter(Boolean):[];for(const $ of oe){if(ne.current.get($)===Ve)continue;const ye=E.current.get($);!ye||!ve($,ye,Oe,Ve)||(ye.sentForceRestartToken=Ve,ne.current.set($,Ve))}},[L,we,Ve,Oe,ve,_]),s.useEffect(()=>()=>{Be("livedesk-hook-unmount",!1)},[Be]);const bt=s.useCallback((oe,$="browser-stale")=>{if(!_)return!1;const ye=Array.isArray(oe)&&oe.length>0?oe:L.split(",").filter(Boolean);if(ye.length===0)return!1;let V=!1;for(const Ge of ye){const St=E.current.get(Ge);!St||St.socket.readyState!==WebSocket.OPEN||(V=ve(Ge,St,$,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||V)}return V},[L,ve,_]),Mt=s.useCallback((oe,$="browser-reconnect")=>{if(!_)return!1;const ye=Array.isArray(oe)&&oe.length>0?oe:L.split(",").filter(Boolean);if(ye.length===0)return!1;for(const V of ye){const Ge=E.current.get(V);je(V),Ge&&!Hu(Ge,c)&&(Me(Ge,`livedesk-${$}`),E.current.delete(V)),G.current.set(V,(G.current.get(V)||0)+1),I.current.delete(V),x.current.delete(V)}return p(c,new Map(I.current)),le(V=>V+1),K(),!0},[je,Me,L,p,_,K,c]);return{frames:u,state:h,error:k,stats:b,restartLive:bt,reconnectLive:Mt}}function iC(e,t,a=In,r={},c=""){const[u,p]=Xt(c,null),[h,f]=Xt(c,null),[k,M]=Xt(c,"idle"),[b,T]=Xt(c,ks),I=s.useRef(null),x=s.useRef(""),E=s.useRef(c);E.current=c;const H=s.useRef(r.onFrame),Q=s.useRef(null),G=s.useRef(0),ne=s.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),ae=s.useMemo(()=>[...new Set(e.filter(Boolean))].join(","),[e]),O=s.useMemo(()=>[...new Set((r.captureDeviceIds||e).filter(Boolean))].join(","),[e,r.captureDeviceIds]),te=s.useMemo(()=>JSON.stringify(r.monitorSelections||{}),[r.monitorSelections]),Z=s.useMemo(()=>{const L=Object.entries(r.connectionSessionIds||{}).filter(([_])=>!!_).map(([_,q])=>[_,String(q||"").trim()]).sort(([_],[q])=>_.localeCompare(q));return JSON.stringify(Object.fromEntries(L))},[r.connectionSessionIds]),me=s.useMemo(()=>({deviceIds:ae.split(",").filter(Boolean),captureDeviceIds:O.split(",").filter(Boolean),fps:Number(r.fps||20),inputFps:Number(r.inputFps||8),width:Number(r.width||1920),height:Number(r.height||1080),tileWidth:Number(r.tileWidth||320),tileHeight:Number(r.tileHeight||180),monitorSelections:r.monitorSelections||{}}),[O,ae,te,r.fps,r.height,r.inputFps,r.monitorSelections,r.tileHeight,r.tileWidth,r.width]),le=s.useMemo(()=>JSON.stringify({atlasConfiguration:me,connectionSessionKey:Z}),[me,Z]),pe=s.useRef(me);pe.current=me;const se=t&&me.deviceIds.length>0,W=s.useCallback(L=>L.readyState!==WebSocket.OPEN?!1:(L.send(JSON.stringify({type:"configure",...pe.current})),!0),[]);s.useEffect(()=>{H.current=r.onFrame},[r.onFrame]),s.useEffect(()=>{if(!se)return;const L=c;ne.current.sampleStartedAt=performance.now();const _=window.setInterval(()=>{if(E.current!==L)return;const q=ne.current,ue=performance.now(),P=Math.max(1,ue-q.sampleStartedAt);T(L,{totalFrames:q.totalFrames,totalBytes:q.totalBytes,framesPerSecond:q.sampleFrames*1e3/P,bytesPerSecond:q.sampleBytes*1e3/P,sampleMs:P,lastUpdatedAt:Date.now()});const F=Q.current;F&&F.frameSeq!==G.current&&(G.current=F.frameSeq,p(L,F)),q.sampleFrames=0,q.sampleBytes=0,q.sampleStartedAt=ue},1e3);return()=>window.clearInterval(_)},[se,p,T,c]),s.useEffect(()=>{const L=c;if(!se){I.current?.close(),I.current=null,x.current="",p(L,null),Q.current=null,G.current=0,f(L,null),M(L,"idle"),T(L,ks);return}p(L,null),f(L,null),Q.current=null,G.current=0,ne.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:performance.now()};let _=!1,q=0;const ue=()=>{if(_||E.current!==L)return;const P=xs(Rs("/api/remote/atlas/ws",a),"/api/remote/atlas/ws","atlas");P.binaryType="arraybuffer",I.current=P,x.current=L,M(L,"connecting"),P.addEventListener("open",()=>{_||I.current!==P||E.current!==L||(ne.current.sampleStartedAt=performance.now(),M(L,"open"),W(P))}),P.addEventListener("message",F=>{if(_||I.current!==P||E.current!==L)return;if(typeof F.data=="string"){try{const Se=JSON.parse(F.data);Se?.type==="Mode4AtlasLayout"&&f(L,{layoutVersion:Number(Se.layoutVersion||0),width:Number(Se.width||1920),height:Number(Se.height||1080),columns:Number(Se.columns||1),rows:Number(Se.rows||1),tiles:Array.isArray(Se.tiles)?Se.tiles:[]})}catch{}return}const ee=F.data instanceof ArrayBuffer?F.data:null;if(!(!ee||ee.byteLength<5))try{const Se=Date.now(),Fe=new DataView(ee).getUint32(0,!1);if(Fe<=0||Fe+4>ee.byteLength)return;const j=JSON.parse(Kd.decode(new Uint8Array(ee,4,Fe))),R=new Uint8Array(ee,4+Fe),Ce=Ae(j.hubClientDropped),we=Ae(j.hubClientQueueDepth),Ve=Ae(j.hubClientQueueLimit),Oe=Ae(j.hubClientBufferedBytes),it={deviceId:String(j.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(j.frameSeq||0),streamFrameSeq:Number(j.streamFrameSeq||0)||void 0,streamId:String(j.streamId||"mode4-atlas"),commandId:j.commandId?String(j.commandId):void 0,width:Number(j.width||1920),height:Number(j.height||1080),sourceWidth:Number(j.sourceWidth||j.width||1920),sourceHeight:Number(j.sourceHeight||j.height||1080),mimeType:String(j.mimeType||"video/h264"),mode:String(j.mode||"mode4-h264-atlas"),frameMode:String(j.frameMode||"mode4-h264-atlas"),frameProfile:String(j.frameProfile||"mode4-h264-atlas-v1"),encoding:String(j.encoding||"video-atlas"),codec:String(j.codec||"h264"),compression:String(j.compression||"video/h264"),h264Format:String(j.h264Format||"annexb"),isKeyFrame:j.isKeyFrame===!0,chunkType:String(j.chunkType||""),timestampUs:Number(j.timestampUs||0),durationUs:Number(j.durationUs||0),transport:j.transport?String(j.transport):void 0,videoTransport:j.videoTransport?String(j.videoTransport):void 0,frameTransportActive:j.frameTransportActive?String(j.frameTransportActive):void 0,frameTransportProtocol:j.frameTransportProtocol?String(j.frameTransportProtocol):void 0,frameTransportState:j.frameTransportState?String(j.frameTransportState):void 0,frameTransportReason:j.frameTransportReason?String(j.frameTransportReason):void 0,frameTransportChangedAt:j.frameTransportChangedAt?String(j.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(j.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(j.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:j.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:Ce!==void 0&&we!==void 0&&Ve!==void 0&&Oe!==void 0,hubClientDropped:Ce,hubClientQueueDepth:we,hubClientQueueLimit:Ve,hubClientBufferedBytes:Oe,udpIncompleteFrames:Number(j.udpIncompleteFrames||0)||0,hardwareEncoder:j.hardwareEncoder?String(j.hardwareEncoder):void 0,platformProfile:j.platformProfile?String(j.platformProfile):void 0,capturedAt:String(j.capturedAt||""),receivedAt:String(j.receivedAt||""),hubPacketAt:j.hubPacketAt?String(j.hubPacketAt):void 0,hubPacketEpochMs:Number(j.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:Se,byteLength:R.byteLength,layoutVersion:Number(j.layoutVersion||0),atlasComposeMs:Number(j.atlasComposeMs||0),atlasPoolStarved:Number(j.atlasPoolStarved||0),atlasReadyTiles:Number(j.atlasReadyTiles||0),atlasTileCount:Number(j.atlasTileCount||0),atlasInputRevision:Number(j.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(j.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(j.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(j.atlasSourceMaxAgeMs||0),payload:R},z=ne.current;z.totalFrames+=1,z.totalBytes+=R.byteLength,z.sampleFrames+=1,z.sampleBytes+=R.byteLength,Q.current=it,G.current===0&&(G.current=it.frameSeq,p(L,it)),H.current?.(it)}catch{}}),P.addEventListener("error",()=>{_||I.current!==P||E.current!==L||M(L,"error")}),P.addEventListener("close",()=>{I.current===P&&(I.current=null),x.current===L&&(x.current=""),!(_||E.current!==L)&&(M(L,"closed"),q=window.setTimeout(ue,1200))})};return ue(),()=>{_=!0,window.clearTimeout(q),x.current===L&&(I.current?.close(),I.current=null,x.current="")}},[se,a,p,f,M,T,W,c]),s.useEffect(()=>{if(!se)return;const L=I.current;L&&x.current===c&&W(L)},[le,se,W,c]);const re=s.useCallback(()=>{const L=I.current;return L&&x.current===E.current?W(L):!1},[W]);return{frame:u,layout:h,state:k,stats:b,refreshInputs:re}}function sC(e,t=In,a="",r=""){const c=String(a||"").trim(),u=s.useRef(null),p=s.useRef(null),h=s.useRef(0),f=s.useRef(0),k=s.useRef(c),M=s.useRef(!1),b=s.useRef(new Map),T=s.useRef(""),I=s.useRef(new Map),x=s.useRef(r),E=s.useRef("");x.current=r;const[H,Q]=s.useState(r),[G,ne]=s.useState("idle"),[ae,O]=s.useState(""),[te,Z]=s.useState(""),[me,le]=s.useState(!1),[pe,se]=s.useState(ed),[W,re]=s.useState(null),L=s.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});k.current!==c&&(k.current=c,M.current=!1),s.useEffect(()=>{const ue=r;if(E.current=ue,Q(ue),!e){u.current?.close(),u.current=null,p.current=null,f.current=0,M.current=!1,T.current="",I.current.clear(),b.current.clear(),ne("idle"),O(""),Z(""),le(!1),se(ed),re(null);return}let P=!1,F=0,ee=0,Se=0;const de=()=>!P&&E.current===ue&&x.current===ue,Fe=()=>{window.clearTimeout(ee),ee=0},j=we=>{de()&&(Se+=1,Se>=If&&O(Zu(we,navigator.language)))},R=we=>{de()&&(window.clearTimeout(F),F=window.setTimeout(we,DS(Se)))},Ce=()=>{if(!de())return;let we;try{we=xs(Rs("/api/remote/input/ws",t),"/api/remote/input/ws","input")}catch{j("remote-input-transport-error"),ne("error"),R(Ce);return}let Ve=!1,Oe=!1;const it=z=>{Oe||(Oe=!0,j(z))};u.current=we,p.current=null,M.current=!1,Z(""),le(!1),L.current.sampleStartedAt=performance.now(),ne("connecting"),ee=window.setTimeout(()=>{if(!(!de()||u.current!==we||Ve)){it("remote-input-ready-timeout"),ne("error");try{we.close(4e3,"remote-input-ready-timeout")}catch{u.current===we&&(u.current=null,R(Ce))}}},ES),we.addEventListener("open",()=>{!de()||u.current!==we||ne("connecting")}),we.addEventListener("message",z=>{if(!(!de()||u.current!==we||typeof z.data!="string"))try{const Me=JSON.parse(z.data);if(Me?.type==="RemoteInputSocketReady"){const K=String(Me.clientId||"").trim();if(!K){it("remote-input-ready-timeout"),we.close(4e3,"remote-input-ready-missing-owner");return}Ve=!0,Se=0,Fe(),p.current=we,Z(K),O(""),ne("open");const ve=k.current;if(ve)try{we.send(JSON.stringify({type:"watch",deviceId:ve}))}catch{we.close(4002,"input-watch-send-failed")}return}if(Me?.type==="RemoteInputRouteState"){const K=String(Me.deviceId||"").trim();if(!K||K!==k.current)return;const ve=Me.ready===!0;M.current=ve,le(ve),ve||re(null),!ve&&Se>=If?O(Zu("INPUT_CHANNEL_RECONNECTING",navigator.language)):ve&&O("");return}const je=Number(Me.inputSeq||Me.result?.inputSeq||0),qe=String(Me.deviceId||Me.result?.deviceId||""),kt=String(Me.inputEventId||Me.result?.inputEventId||""),Te=b.current.get(je);if(qe&&(Te&&Te.deviceId!==qe||!Te&&T.current&&T.current!==qe)||Te?.inputEventId&&kt&&Te.inputEventId!==kt)return;if(Me?.type==="RemoteInputError"){je>0&&b.current.delete(je);const K=String(Me.error||Me.result?.error||"remote-input-failed"),ve=String(Me.errorKind||Me.result?.errorKind||"").trim().toLowerCase(),st=_S(K),ot=ve==="native-apply";if(st&&(M.current=!1,le(!1)),ot){const bt=qe||k.current,Mt=`${bt}
|
|
174
|
-
${K}`,oe=performance.now(),$=I.current;for(const[V,Ge]of $)oe-Ge>=Af&&$.delete(V);const ye=$.get(Mt);(ye===void 0||oe-ye>=Af)&&($.set(Mt,oe),console.warn("[VuvoDesk remote input] native apply rejected",{deviceId:bt,inputSeq:je,error:K}))}O(Zu(K,navigator.language,ve)),p.current===we&&ne("open");return}if(Me?.type!=="RemoteInputApplied")return;Te&&(L.current.lastRoundTripMs=Math.max(0,performance.now()-Te.sentAt),b.current.delete(je)),L.current.lastInputSeq=je,L.current.lastAgentApplyMs=Math.max(0,Number(Me.agentApplyMs||0));const Be=String(Me.nativeInputBackend||Me.result?.nativeInputBackend||"").trim();if(Te&&Be&&Te.normalizedX!==null&&Te.normalizedY!==null)if(Be==="win32-window-message"){const K={deviceId:Te.deviceId,monitorIndex:Te.monitorIndex,normalizedX:Te.normalizedX,normalizedY:Te.normalizedY,inputSeq:je,inputType:Te.inputType,nativeInputBackend:Be,controlSessionId:Te.controlSessionId,controlCommandId:Te.controlCommandId,captureGeneration:Te.captureGeneration};re(ve=>ve&&ve.deviceId===K.deviceId&&ve.inputSeq>je?ve:K)}else re(null);O(""),ne("open")}catch{}}),we.addEventListener("close",z=>{!de()||u.current!==we||(Fe(),Ve||it(z.reason||"remote-input-socket-closed"),u.current=null,p.current===we&&(p.current=null),f.current=0,M.current=!1,T.current="",I.current.clear(),b.current.clear(),Z(""),le(!1),re(null),ne("closed"),R(Ce))}),we.addEventListener("error",()=>{de()&&u.current===we&&ne("error")})};return Ce(),()=>{P=!0,window.clearTimeout(F),Fe();const we=u.current;u.current=null,p.current=null,f.current=0,M.current=!1,I.current.clear(),Z(""),le(!1),re(null),we?.close(),b.current.clear(),E.current===ue&&(E.current="")}},[e,t,r]),s.useEffect(()=>{if(E.current!==x.current||(M.current=!1,le(!1),re(null),!e||!c))return;const ue=p.current;if(!(!ue||ue.readyState!==WebSocket.OPEN))try{ue.send(JSON.stringify({type:"watch",deviceId:c}))}catch{ue.close(4002,"input-watch-send-failed")}},[e,c,r]),s.useEffect(()=>{if(!e)return;const ue=window.setInterval(()=>{if(E.current!==x.current)return;const P=performance.now(),F=L.current,ee=Math.max(1,P-F.sampleStartedAt);se({totalSent:F.totalSent,totalDropped:F.totalDropped,sentPerSecond:F.sampleSent*1e3/ee,droppedPerSecond:F.sampleDropped*1e3/ee,bufferedAmount:u.current?.bufferedAmount||0,lastInputType:F.lastInputType,lastInputSeq:F.lastInputSeq,lastRoundTripMs:F.lastRoundTripMs,lastAgentApplyMs:F.lastAgentApplyMs,lastUpdatedAt:Date.now()}),F.sampleSent=0,F.sampleDropped=0,F.sampleStartedAt=P},1e3);return()=>window.clearInterval(ue)},[e,r]);const _=s.useCallback((ue,P)=>{const F=u.current;if(!F||E.current!==x.current||p.current!==F||F.readyState!==WebSocket.OPEN||M.current!==!0||k.current!==ue||!ue)return!1;const ee=String(P.type||"").toLowerCase(),Fe=ee==="pointermove"||ee==="wheel",j=L.current,R=performance.now();if(Fe&&F.bufferedAmount>JS)return j.totalDropped+=1,j.sampleDropped+=1,j.lastInputType=`${ee}-coalescible-drop`,!1;if(!Fe&&F.bufferedAmount>ZS){j.lastInputType=`${ee||"input"}-fail-closed`,O("Remote input channel was reset because ordered input could not drain.");try{F.close(4001,"ordered-input-backpressure")}catch{}return!1}const Ce=h.current+1;h.current=Ce;const we=`${Ce}-${crypto.randomUUID()}`,Ve=Date.now(),Oe=Number(P.normalizedX),it=Number(P.normalizedY),z=Number.isFinite(Oe)?Math.max(0,Math.min(1,Oe)):null,Me=Number.isFinite(it)?Math.max(0,Math.min(1,it)):null,je=!Fe||Ce-f.current>=eC;for(je&&b.current.set(Ce,{sentAt:R,deviceId:ue,inputEventId:we,inputType:ee,monitorIndex:Math.max(0,Math.trunc(Number(P.monitorIndex)||0)),normalizedX:z,normalizedY:Me,controlSessionId:String(P.controlSessionId||""),controlCommandId:String(P.controlCommandId||""),captureGeneration:Math.max(0,Math.trunc(Number(P.captureGeneration)||0))}),T.current=ue,Bg.set(ue,{inputSeq:Ce,inputType:ee||"input",sentAt:performance.now()});b.current.size>256;){const qe=b.current.keys().next().value;if(qe===void 0)break;b.current.delete(qe)}try{F.send(JSON.stringify({type:"input",requestId:Fe?"":crypto.randomUUID(),fireAndForget:Fe,deviceId:ue,input:{...P,inputEventId:we,inputSeq:Ce,requestAck:je,issuedAtEpochMs:Ve,issuedAt:new Date(Ve).toISOString()}}))}catch{b.current.delete(Ce),O("Remote input channel closed before the ordered input was queued.");try{F.close(4002,"input-send-failed")}catch{}return!1}return Fe&&je&&(f.current=Ce),j.totalSent+=1,j.sampleSent+=1,j.lastInputType=ee||"input",!0},[]),q=H===r;return{state:q?G:"idle",connectionId:q?te:"",routeReady:q?me:!1,sendInput:_,stats:q?pe:ed,error:q?ae:"",remotePointerFeedback:q?W:null}}const go={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},cC=.25,Nf=300,Ff=2,rl=1500,td=5e3,lC=2e3,Df=1e4,ms=[0,1e3,3e3];function Lf(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?Math.max(0,Date.now()-t):0}function uC(e,t,a=In,r=0,c=!1,u="",p,h,f=""){const k=s.useRef(null),M=s.useRef(""),b=s.useRef(f);b.current=f;const[T,I]=s.useState(f),[x,E]=s.useState("idle"),[H,Q]=s.useState(null),[G,ne]=s.useState(go),[ae,O]=s.useState(""),te=s.useRef(c);te.current=c,s.useLayoutEffect(()=>{const me=f;return()=>{const le=k.current;!le||M.current!==me||(k.current=null,M.current="",le.close().catch(()=>{}))}},[f]),s.useEffect(()=>{c||(Q(me=>me===null?me:null),ne(me=>me===go?me:go))},[c]),s.useEffect(()=>{const me=f;if(I(me),!t||!e){E("idle"),Q(null),ne(go),O("");return}E("connecting"),Q(null),ne(go),O("");const le=window.AudioContext||window.webkitAudioContext;if(!le){E("unsupported"),ne(go),O("Audio playback is not supported in this browser.");return}let pe=!1;const se=()=>!pe&&b.current===me;let W=null;const re=bS.acquire(({release:L})=>{if(!se()){L();return}const _=new le({latencyHint:"interactive"});k.current=_,M.current=me;let q=String(u||"").trim();const ue="/api/remote/audio/ws?devices="+encodeURIComponent(e)+(q?"&streamId="+encodeURIComponent(q):"");let P=xs(Rs(ue,a),ue,"audio");P.binaryType="arraybuffer";const F=Ot.createOwner({deviceId:e,socket:P,audioContext:_,statsTimer:null});let ee=!1;const Se=()=>{const N=Ot.releaseIfDrained(F);return(N||!Ot.hasOwner(F))&&!ee&&(ee=!0,L()),N},de=Gd({sampleRate:192e3,channels:8}).capacityBytes,Fe=xS({maxPendingPackets:Td,maxPendingBytes:de}),j=uS(),R={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(_.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:q,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let Ce=!1,we=!1,Ve=null,Oe=0,it=0,z="",Me=!1,je=()=>{},qe="connecting",kt="",Te=()=>{};const Be=N=>{Ce||!se()||N===qe||(qe=N,E(N))},K=N=>{Ce||!se()||N===kt||(kt=N,O(N))},ve=hS({schedule:(N,he)=>window.setTimeout(N,he),cancel:N=>window.clearTimeout(N),onTimerChange:N=>{Ot.setReconnectTimer(F,N),Se()},onReconnect:()=>{try{const N=xs(Rs(ue,a),ue,"audio");if(N.binaryType="arraybuffer",!ve.replaceSocket(N)){N.close();return}P=N,Ot.setSocket(F,N),Be("connecting"),Te(N)}catch(N){throw Be("error"),K(N instanceof Error?`Remote audio reconnect failed: ${N.message}`:"Remote audio reconnect failed."),N}}});ve.replaceSocket(P);let st=0,ot=!1,bt=0,Mt=0,oe=0,$=!1;const ye=()=>{Ot.setPendingWorkletPackets(F,Fe.getPendingPacketCount(),Fe.getPendingPacketBytes(),Fe.getPendingPacketHighWater(),Fe.getPendingByteHighWater())},V=N=>{R.workletRingCapacityBytes=Math.max(0,Math.min(de,Number(N.ringCapacityBytes||0)||0)),R.workletRingBufferedBytes=Math.max(0,Math.min(R.workletRingCapacityBytes,Number(N.ringBufferedBytes||0)||0)),R.workletRingBufferedMs=Math.max(0,Math.min(cC*1e3,Number(N.ringBufferedMs||0)||0)),R.workletRingDroppedFrames=Math.max(R.workletRingDroppedFrames,Number(N.ringDroppedFrames||0)||0),R.workletRingUnderflowCount=Math.max(R.workletRingUnderflowCount,Number(N.ringUnderflowCount||0)||0),Ot.setPcmRing(F,R.workletRingCapacityBytes,R.workletRingBufferedBytes)},Ge=()=>{const N=Ve;if(Ve=null,Me=!1,N){N.onprocessorerror=null,N.port.onmessage=null;try{N.disconnect()}catch{}try{N.port.close()}catch{}}Fe.terminate(),ye(),R.workletRingCapacityBytes=0,R.workletRingBufferedBytes=0,R.workletRingBufferedMs=0,Ot.setPcmRing(F,0,0),Ot.setWorkletNode(F,0,0,Oe),Se()},St=N=>{const he=N.data||{},Y=String(he.type||"");if((Y==="packet-terminal"||Y==="processor-error")&&(Fe.acknowledge(typeof he.packetId=="number"?he.packetId:String(he.packetId||"")),ye()),Y==="packet-terminal"){const Ie=Math.max(0,Number(he.droppedFrames||0)||0);Ie>0&&(R.workletRingDroppedFrames+=Ie,R.resyncs+=1)}if(Y==="ring-configured"||Y==="ring-state"||Y==="disposed"){const Ie=R.workletRingDroppedFrames;V(he),R.workletRingDroppedFrames>Ie&&(R.resyncs+=1)}Y==="disposed"?Ge():Y==="processor-error"&&je(String(he.error||"Remote audio worklet processing failed."))},A=()=>{if(!(!Ve||!Me))try{Ve.port.postMessage({type:"flush"})}catch{je("Remote audio worklet could not be flushed.")}},ie=()=>{P.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"subscribe",deviceIds:[e],streamIdsByDeviceId:q?{[e]:q}:{}}))},Pe=()=>{R.audioContextState=String(_.state),!Ce&&(R.audioContextState==="suspended"||R.audioContextState==="interrupted"?Be("suspended"):R.audioContextState==="closed"&&(Be("error"),K("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},He=async()=>{if(Ce||String(_.state)==="closed")return!1;try{if(String(_.state)!=="running"&&await _.resume(),R.audioContextState=String(_.state),!Ce&&!ot&&R.audioContextState==="running"){const N=R.lastAcceptedAt>0&&performance.now()-R.lastAcceptedAt<=rl,he=R.lastCaptureStatusAt>0&&performance.now()-R.lastCaptureStatusAt<=td&&R.captureHealthy;Be(N?"playing":he?"silent":"open")}return R.audioContextState==="running"}catch(N){return Ce||(Be("suspended"),K(N instanceof Error?"Audio playback is suspended: "+N.message:"Audio playback is suspended.")),!1}},vt=async()=>{if(!_.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const N=new Blob([PS],{type:"text/javascript"});z=URL.createObjectURL(N);try{await _.audioWorklet.addModule(z)}finally{URL.revokeObjectURL(z),z=""}if(Ce||String(_.state)==="closed")return;const he=new AudioWorkletNode(_,jg,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[Ff],channelCount:Ff,channelCountMode:"explicit"});Oe+=1,Ve=he,he.port.onmessage=St,he.onprocessorerror=()=>{je("Remote audio worklet stopped unexpectedly.")},he.connect(_.destination),Me=!0,Ot.setWorkletNode(F,1,1,Oe)},Je=(N,he,Y,Ie)=>{const be=Ve;if(Ce||!Me||!be||he.byteLength<=0)return!1;const Ke=qd({sampleRate:N.sampleRate,channels:N.channels,mimeType:N.mimeType}),ut=++it;if(!Fe.claim(ut,he.byteLength))return ye(),!1;ye();try{return be.port.postMessage({type:"pcm",packetId:ut,buffer:he,byteOffset:Y,byteLength:Ie,sampleRate:Ke.sampleRate,channels:Ke.channels,mimeType:N.mimeType,sampleFormat:Ke.sampleFormat},[he]),!0}catch{return Fe.acknowledge(ut),ye(),!1}},At=async()=>{if(Ce||ot||P.readyState!==WebSocket.OPEN)return;if(bt>=ms.length){Be("error"),K("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const N=bt;bt+=1,ot=!0,R.stalledCount+=1,R.automaticRestarts+=1,Be("reconnecting");try{if(!p)throw new Error("Remote audio restart owner is unavailable.");const he=await p(e);if(Ce||!he)return;q=he,ie();const Y=performance.now();st=Y,R.lastPacketAt=Y,R.lastAcceptedAt=0,R.lastCaptureStatusAt=0,R.lastPcmAtEpochMs=0,R.captureAlive=null,R.helperAlive=null,R.helperReady=!1,R.captureHealthy=!1,R.captureStatusFailed=!1,R.captureAwaitingCurrentPcm=!1,R.captureAwaitingSinceAt=0,R.capturePhase="",R.backendKind="",R.helperRequired=!1,R.helperPid=0,R.nativeCallbackDiagnosticsAvailable=!1,R.nativeRejectedCallbackCount=0,R.nativeCurrentnessDropCount=0,R.nativeLastDropReason="",R.silentForMs=0,R.activeStreamId=q,R.lastFrameSeq=0,R.maximumAcceptedGapMs=0,A(),Mt=Y+(ms[N+1]??3e3),K(""),Ce||Be("open")}catch(he){Ce||(Mt=performance.now()+(ms[N+1]??3e3),Be("error"),K(he instanceof Error?"Remote audio restart failed: "+he.message:"Remote audio restart failed."))}finally{ot=!1}},_t=()=>{R.drops+=1},Jt=window.setInterval(()=>{if(Ce||!se())return;const N=performance.now(),he=R.lastPacketAt>0?Math.max(0,N-R.lastPacketAt):st>0?Math.max(0,N-st):0,Y=R.lastAcceptedAt>0?Math.max(0,N-R.lastAcceptedAt):0,Ie=R.lastCaptureStatusAt>0?Math.max(0,N-R.lastCaptureStatusAt):0,be=P.readyState===WebSocket.OPEN,Ke=R.lastCaptureStatusAt>0,ut=Ke&&Ie<=td&&R.captureHealthy,xe=Ke&&R.captureStatusFailed&&Ie>lC,Ye=Ke&&Ie>td,_e=!Ke&&st>0&&N-st>Df,Wt=R.captureAwaitingCurrentPcm&&R.captureAwaitingSinceAt>0&&N-R.captureAwaitingSinceAt>Df,lt=st>0&&(R.lastAcceptedAt<=0?N-st>rl:Y>rl);if(be&&st>0&&(xe||Ye||_e||Wt)?bt>=ms.length&&!ot?(Be("error"),K("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!ot&&N>=Mt?At():ot||Be("stalled"):be&<&&!ot&&R.audioContextState!=="suspended"&&R.audioContextState!=="interrupted"&&Be(ut?"silent":"open"),vS({enabled:te.current,now:N,lastPublishedAt:oe})){oe=N,ne({queuedMs:R.workletRingBufferedMs,browserAgeMs:R.browserAgeMs,captureAgeMs:R.captureAgeMs,captureStatusAgeMs:Ie,silentForMs:R.silentForMs,captureAlive:R.captureAlive,helperAlive:R.helperAlive,helperReady:R.helperReady,captureHealthy:R.captureHealthy,captureAwaitingCurrentPcm:R.captureAwaitingCurrentPcm,capturePhase:R.capturePhase,backendKind:R.backendKind,helperRequired:R.helperRequired,helperPid:R.helperPid,captureRestartCount:R.captureRestartCount,nativeCallbackDiagnosticsAvailable:R.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:R.nativeRejectedCallbackCount,nativeCurrentnessDropCount:R.nativeCurrentnessDropCount,nativeLastDropReason:R.nativeLastDropReason,localProcessingAgeMs:R.localProcessingAgeMs,lastPacketAgeMs:he,lastAcceptedAgeMs:Y,framesReceived:R.framesReceived,drops:R.drops,resyncs:R.resyncs,pendingDecodes:R.pendingDecodes,lastFrameSeq:R.lastFrameSeq,audioContextState:R.audioContextState,stalledCount:R.stalledCount,automaticRestarts:R.automaticRestarts,maximumAcceptedGapMs:R.maximumAcceptedGapMs,workletRingCapacityBytes:R.workletRingCapacityBytes,workletRingBufferedBytes:R.workletRingBufferedBytes,workletRingDroppedFrames:R.workletRingDroppedFrames,workletRingUnderflowCount:R.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const ct=j.publish();ct&&($=!0,Ot.setRetainedFrame(F,1,ct.payload.byteLength),Q(ct))}else!te.current&&$&&($=!1,j.clear(),Ot.setRetainedFrame(F,0,0))},250);Ot.setStatsTimer(F,Jt);const xt=()=>{Pe(),(String(_.state)==="suspended"||String(_.state)==="interrupted")&&He()},Vt=()=>{document.visibilityState==="visible"&&He()},g=()=>{He()};_.addEventListener("statechange",xt),document.addEventListener("visibilitychange",Vt),window.addEventListener("pageshow",g),window.addEventListener("pointerdown",g),window.addEventListener("keydown",g),Be("connecting"),K(""),Pe();const U=(N,he,Y,Ie,be)=>{if(R.localProcessingAgeMs=Math.max(0,performance.now()-be),Ce||!se()||R.localProcessingAgeMs>Nf||!Pd(N,{deviceId:e,streamId:q}))return _t(),!1;R.activeStreamId!==q&&(R.activeStreamId=q,R.lastFrameSeq=0,R.maximumAcceptedGapMs=0,A());const Ke=CS(N,{deviceId:e,streamId:q,lastFrameSeq:R.lastFrameSeq});if(!Ke.accepted||!Je(N,he,Y,Ie))return _t(),!1;R.browserAgeMs=Lf(N.receivedAt),R.captureAgeMs=Lf(N.capturedAt);const ut=performance.now();R.lastAcceptedAt>0&&(R.maximumAcceptedGapMs=Math.max(R.maximumAcceptedGapMs,ut-R.lastAcceptedAt)),R.lastAcceptedAt=ut,R.framesReceived+=1,R.lastFrameSeq=Ke.nextFrameSeq,bt=0,Mt=0,te.current&&(j.accept(N),$=!0,Ot.setRetainedFrame(F,1,0)),String(_.state)!=="running"&&He();const xe=String(_.state)==="running";return xe&&K(""),Be(xe?"playing":"suspended"),!0};je=(N="")=>{if(!we){if(we=!0,N&&(Ot.recordTerminalFailure(F,N,N.includes("setup failed")?"setup":"processor"),Be(N.includes("AudioWorklet is unavailable")?"unsupported":"error"),K(N),h?.(e,q,"browser-audio-playback-failed").catch(()=>{})),Ce=!0,ve.stop(),Ot.deactivate(F),window.clearInterval(Jt),Ot.setStatsTimer(F,null),_.removeEventListener("statechange",xt),document.removeEventListener("visibilitychange",Vt),window.removeEventListener("pageshow",g),window.removeEventListener("pointerdown",g),window.removeEventListener("keydown",g),j.clear(),Ot.setRetainedFrame(F,0,0),Ve)try{Ve.port.postMessage({type:"dispose"})}catch{}try{P.close()}catch{}P.readyState===WebSocket.CLOSED&&xf({reconnectOwner:ve,lifecycleLedger:Ot,lifecycleOwner:F,socket:P}),_.close().catch(()=>{}).finally(()=>{Ge(),String(_.state)==="closed"&&Ot.setAudioContext(F,null),Se()}),k.current===_&&(k.current=null,M.current=""),Se()}},vt().catch(N=>{je(N instanceof Error?`Remote audio worklet setup failed: ${N.message}`:"Remote audio worklet setup failed.")}),Te=N=>{let he=!1;N.addEventListener("open",()=>{he||Ce||!se()||!ve.isCurrent(N)||(ie(),st=performance.now(),R.lastPacketAt=st,R.lastAcceptedAt=0,R.lastCaptureStatusAt=0,R.lastPcmAtEpochMs=0,R.captureAlive=null,R.helperAlive=null,R.helperReady=!1,R.captureHealthy=!1,R.captureStatusFailed=!1,R.captureAwaitingCurrentPcm=!1,R.captureAwaitingSinceAt=0,R.capturePhase="",R.backendKind="",R.helperRequired=!1,R.helperPid=0,R.maximumAcceptedGapMs=0,R.silentForMs=0,Be("open"),K(""),He())}),N.addEventListener("message",Y=>{if(he||Ce||!se()||!ve.isCurrent(N)||typeof Y.data=="string")return;const Ie=Y.data instanceof ArrayBuffer?Y.data:null;if(!Ie||Ie.byteLength<5)return;const be=performance.now();R.lastPacketAt=be;try{const ut=new DataView(Ie).getUint32(0,!1);if(ut<=0||ut+4>Ie.byteLength){_t();return}const xe=new Uint8Array(Ie,4,ut),Ye=JSON.parse(Kd.decode(xe)),_e=new Uint8Array(Ie,4+ut),Wt=String(Ye.deviceId||""),lt=String(Ye.streamId||"");if(!Pd({deviceId:Wt,streamId:lt},{deviceId:e,streamId:q})){_t();return}const ct=String(Ye.frameKind||Ye.kind||"").toLowerCase();if(Ye.type==="remote.audio.status"||ct==="audio-status"){ve.markHealthy(N),R.lastCaptureStatusAt=be;const nt=kS(Ye);if(R.captureAlive=nt.captureAlive,R.helperAlive=nt.helperAlive,R.helperReady=nt.helperReady,R.captureHealthy=nt.healthy,R.captureStatusFailed=nt.failed,R.captureAwaitingCurrentPcm=nt.awaitingCurrentPcm,nt.awaitingCurrentPcm?R.captureAwaitingSinceAt||=be:R.captureAwaitingSinceAt=0,R.capturePhase=nt.capturePhase,R.backendKind=nt.backendKind,R.helperRequired=nt.helperRequired===!0,R.helperPid=nt.helperPid,R.captureRestartCount=Math.max(0,Number(Ye.restartCount||0)||0),R.nativeCallbackDiagnosticsAvailable=Ye.callbackDiagnosticsAvailable===!0,R.nativeRejectedCallbackCount=R.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.rejectedCallbackCount||0)||0):0,R.nativeCurrentnessDropCount=R.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.currentnessDropCount||0)||0):0,R.nativeLastDropReason=R.nativeCallbackDiagnosticsAvailable?String(Ye.lastDropReason||""):"",R.lastPcmAtEpochMs=Math.max(0,Number(Ye.lastPcmAtEpochMs||0)||0),R.silentForMs=Math.max(0,Number(Ye.silentForMs||0)||0),R.captureAgeMs=R.lastPcmAtEpochMs>0?Math.max(0,Date.now()-R.lastPcmAtEpochMs):R.silentForMs,R.captureHealthy){if(bt=0,Mt=0,!ot){K("");const Pt=String(_.state)==="running",zt=R.lastAcceptedAt>0&&performance.now()-R.lastAcceptedAt<=rl;Be(Pt?zt?"playing":"silent":"suspended")}}else R.captureAwaitingCurrentPcm&&!ot?Be("open"):R.captureStatusFailed&&!ot&&Be("stalled");return}const ht={deviceId:Wt,frameSeq:Number(Ye.frameSeq||0),streamId:lt,mimeType:String(Ye.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ye.sampleRate||48e3),channels:Number(Ye.channels||2),capturedAt:String(Ye.capturedAt||""),receivedAt:String(Ye.receivedAt||""),byteLength:Number(Ye.byteLength||_e.byteLength),payload:_g};if(!ht.deviceId||Ce)return;if(performance.now()-be>Nf){_t();return}if(SS(ht.mimeType)){U(ht,Ie,_e.byteOffset,_e.byteLength,be)&&ve.markHealthy(N);return}_t(),Be("error"),K(`Unsupported remote audio format "${ht.mimeType}". Requesting a bounded PCM restart.`),!ot&&bt<ms.length&&(Mt=0,At());return}catch(Ke){Ce||(Be("error"),K(Ke instanceof Error?Ke.message:String(Ke)))}}),N.addEventListener("error",()=>{!he&&!Ce&&se()&&ve.isCurrent(N)&&(Be("error"),K("Remote audio WebSocket error."))}),N.addEventListener("close",()=>{if(he)return;const Y=xf({reconnectOwner:ve,lifecycleLedger:Ot,lifecycleOwner:F,socket:N});Y!=="stale"&&(he=!0,Se(),!Ce&&se()&&Y==="current"&&(A(),Be("closed"),ve.scheduleReconnect(N)))})},Te(P),W=()=>{je()}});return re.ready.catch(L=>{se()&&(E("error"),O(L instanceof Error?`Remote audio owner setup failed: ${L.message}`:"Remote audio owner setup failed."))}),()=>{pe=!0,W?W():re.cancel()}},[e,t,a,r,p,h,f]);const Z=T===f;return{state:Z?x:"idle",lastFrame:Z?H:null,stats:Z?G:go,error:Z?ae:""}}function dC({workspaceReady:e,desktopShell:t,publicConsole:a,authenticated:r,managerNeedsLocalAccess:c,localHubAccessEnabled:u}){return e?t?!0:a?r:!c||u:!1}const vl=384e3,mC=1024*1024,pC=24*1024*1024,fC=256*1024*1024,hC=24;function gC(e,t){if(!e||e.repeat||e.altKey||e.shiftKey)return"";const a=String(e.key||"").toLowerCase();return a!=="c"&&a!=="v"||!(t?e.metaKey===!0&&e.ctrlKey!==!0:e.ctrlKey===!0&&e.metaKey!==!0)?"":a==="c"?"copy":"paste"}function bC(e){return`clipboard-${e==="copy"?"copy":"paste"}-${Date.now()}-${crypto.randomUUID()}`}function Nd(e,t=""){const a=e&&typeof e=="object"?e:{},r=String(a.operationId||""),c=String(a.contentKind||"").toLowerCase(),u=Array.isArray(a.items)?a.items:[];if(!r||t&&r!==t||!["text","image","files"].includes(c)||u.length<1||u.length>hC)throw new Error("clipboard-manifest-invalid");let p=0;const h=u.map((f,k)=>{const M=Number(f?.itemIndex),b=Number(f?.size),T=String(f?.kind||"").toLowerCase();if(M!==k||!Number.isSafeInteger(b)||b<0||T!=="file"&&b===0||!["text","image","file"].includes(T)||T!==(c==="files"?"file":c))throw new Error("clipboard-item-invalid");p+=b;const I=String(f?.sha256||"").toLowerCase(),x=String(f?.storageName||`item-${k}.bin`);if(!/^[a-f0-9]{64}$/.test(I)||x!==`item-${k}.bin`||String(f?.name||"").includes("\0"))throw new Error("clipboard-item-metadata-invalid");return{itemIndex:M,kind:T,name:String(f?.name||"").slice(0,240),mimeType:String(f?.mimeType||"").slice(0,160),size:b,lastModified:Math.max(0,Number(f?.lastModified||0)||0),sha256:I,storageName:x}});if(p!==Number(a.totalBytes)||p>fC||c==="text"&&p>mC||c==="image"&&p>pC)throw new Error("clipboard-size-limit");return{operationId:r,contentKind:c,totalBytes:p,items:h}}function nd(e,t=vl){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw new Error("clipboard-chunk-plan-invalid");if(e===0)return[{offset:0,byteLength:0,final:!0}];const a=[];for(let r=0;r<e;r+=t){const c=Math.min(t,e-r);a.push({offset:r,byteLength:c,final:r+c===e})}return a}const vC=80,Of=new Set(["down","move","up","leave"]);function ps(e,t=0){const a=Number(e);return Number.isFinite(a)?a:t}function _f(e){return{at:ps(e?.timeStamp),clientX:ps(e?.clientX),clientY:ps(e?.clientY),button:ps(e?.button),buttons:ps(e?.buttons)}}function yC(e,t,a){const r=a.at-t.at;return r>=0&&r<=vC&&Math.abs(a.clientX-t.clientX)<=1&&Math.abs(a.clientY-t.clientY)<=1&&a.buttons===t.buttons&&(e==="move"||e==="leave"||a.button===t.button)}function wC(){const e=new Map;return{observePointerEvent(t,a){Of.has(t)&&e.set(t,_f(a))},shouldHandleMouseEvent(t,a){if(!Of.has(t))return!1;const r=e.get(t);return e.delete(t),!r||!yC(t,r,_f(a))},reset(){e.clear()}}}const SC=3;function jf(e,t,a){const r=Math.max(1,Number(a)||1),c=Math.max(0,Math.min(r,Number(e)-Number(t))),u=Math.min(r/2,SC);return c<=u?0:c>=r-u?1:c/r}function CC(e,t,a){return{normalizedX:jf(e,a.left,a.width),normalizedY:jf(t,a.top,a.height)}}const Bf=8,Fd=320,Hf=28,Ts=1,Hg=4;function kC(){let e=!1;return{claimNativeTouchEvents(){e=!0},shouldHandlePointerEvent(){return!e}}}function at(e,t=0){const a=Number(e);return Number.isFinite(a)?a:t}function Yd(e,t){const a=at(e?.clientX)-at(t?.clientX),r=at(e?.clientY)-at(t?.clientY);return a*a+r*r}function yl(e,t,a){return Math.min(a,Math.max(t,e))}function Wg(e,t){return{clientX:(at(e?.clientX)+at(t?.clientX))/2,clientY:(at(e?.clientY)+at(t?.clientY))/2}}function $g(e,t){return Math.sqrt(Yd(e,t))}function xl(){return{scale:Ts,translateX:0,translateY:0}}function MC(e,t,a,r){const c=a||xl(),u=yl(at(c.scale,Ts),Ts,Hg),p={left:at(r?.left),top:at(r?.top),width:Math.max(1,at(r?.width,1)),height:Math.max(1,at(r?.height,1))},h=Wg(e,t);return{startDistance:Math.max(1,$g(e,t)),startScale:u,anchorX:(h.clientX-p.left-at(c.translateX))/u,anchorY:(h.clientY-p.top-at(c.translateY))/u,bounds:p}}function xC(e,t,a){if(!e)return xl();const r=Wg(t,a),c=yl(at(e.startScale,Ts)*$g(t,a)/Math.max(1,at(e.startDistance,1)),Ts,Hg),u=Math.max(1,at(e.bounds?.width,1)),p=Math.max(1,at(e.bounds?.height,1)),h=yl(r.clientX-at(e.bounds?.left)-at(e.anchorX)*c,u*(1-c),0),f=yl(r.clientY-at(e.bounds?.top)-at(e.anchorY)*c,p*(1-c),0);return{scale:c,translateX:h,translateY:f}}function RC(e,t,a){return{pointerId:at(e,-1),startClientX:at(t),startClientY:at(a),clientX:at(t),clientY:at(a),dragged:!1}}function Vg(e,t,a,r){if(!e||e.pointerId!==at(t,-1))return e;const c={...e,clientX:at(a,e.clientX),clientY:at(r,e.clientY)},u=Bf*Bf;return{...c,dragged:e.dragged||Yd({clientX:e.startClientX,clientY:e.startClientY},c)>=u}}function AC(e,t,a,r,c){if(!e||e.pointerId!==at(t,-1))return{kind:"ignore",gesture:e,tap:null};const u=Vg(e,t,a,r);return{kind:u.dragged?"drag":"tap",gesture:u,tap:u.dragged?null:{clientX:u.clientX,clientY:u.clientY,at:at(c)}}}function Wf(e,t){if(!e||!t)return!1;const a=at(t.at)-at(e.at);if(a<0||a>Fd)return!1;const r=Hf*Hf;return Yd(e,t)<=r}const Rl=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),IC=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),$f=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),Dd=64,TC=256,Vf=Object.freeze({Backspace:Object.freeze({key:"Backspace",code:"Backspace",keyCode:8,location:0}),Tab:Object.freeze({key:"Tab",code:"Tab",keyCode:9,location:0}),Enter:Object.freeze({key:"Enter",code:"Enter",keyCode:13,location:0}),Escape:Object.freeze({key:"Escape",code:"Escape",keyCode:27,location:0}),PageUp:Object.freeze({key:"PageUp",code:"PageUp",keyCode:33,location:0}),PageDown:Object.freeze({key:"PageDown",code:"PageDown",keyCode:34,location:0}),End:Object.freeze({key:"End",code:"End",keyCode:35,location:0}),Home:Object.freeze({key:"Home",code:"Home",keyCode:36,location:0}),ArrowLeft:Object.freeze({key:"ArrowLeft",code:"ArrowLeft",keyCode:37,location:0}),ArrowUp:Object.freeze({key:"ArrowUp",code:"ArrowUp",keyCode:38,location:0}),ArrowRight:Object.freeze({key:"ArrowRight",code:"ArrowRight",keyCode:39,location:0}),ArrowDown:Object.freeze({key:"ArrowDown",code:"ArrowDown",keyCode:40,location:0}),Delete:Object.freeze({key:"Delete",code:"Delete",keyCode:46,location:0})}),zf=Object.freeze({deleteContentBackward:"Backspace",deleteWordBackward:"Backspace",deleteSoftLineBackward:"Backspace",deleteHardLineBackward:"Backspace",deleteContentForward:"Delete",deleteWordForward:"Delete",deleteSoftLineForward:"Delete",deleteHardLineForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"});function Qd(e,t=80){return String(e||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,t)}function zg(e){const t=String(e??"");return t===" "?" ":Qd(t)}function Ld(e){const t=Qd(e);return Object.prototype.hasOwnProperty.call($f,t)?$f[t]:t}function rd(e={}){const t=zg(e.key),a=Number(e.keyCode??e.which);if(t===" "||t==="Spacebar"||a===32)return"Space";const r=Number.isFinite(Number(e.location))?Math.max(0,Math.min(3,Math.trunc(Number(e.location)))):0,c=r===2?"Right":"Left";return t==="Shift"?`Shift${c}`:t==="Control"?`Control${c}`:t==="Alt"||t==="AltGraph"?`Alt${c}`:t==="Meta"||t==="OS"?`Meta${c}`:t?`Key:${r}:${t}`.slice(0,80):""}function Od(e={}){const t=Ld(e.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(t)?rd({...e,key:t}):t==="Unidentified"?rd(e):t||rd(e)}function wl(e){for(const[t,a]of Object.entries(Rl))if(a.includes(e))return t;return""}function Aa(e,t){return Rl[t].some(a=>e.has(a))}function al(e,t,a={},r="",c=""){for(const u of Object.keys(Rl)){const p=a[u]===!0,h=Rl[u];if(u===r){if(c==="keyup"&&!p)for(const f of h)t.has(f)||e.delete(f);continue}if(p){!Aa(e,u)&&e.size<Dd&&e.add(IC[u]);continue}for(const f of h)t.has(f)||e.delete(f)}}function PC(e,t){if(e.length!==t.size)return!1;let a=0;for(const r of t){if(e[a]!==r)return!1;a+=1}return!0}function Uf(e){for(const t of[...e])wl(t)||e.delete(t)}function _d(e){return{shiftKey:Aa(e,"shiftKey"),ctrlKey:Aa(e,"ctrlKey"),altKey:Aa(e,"altKey"),metaKey:Aa(e,"metaKey")}}function EC(e={},t={}){return{shiftKey:e.shiftKey===!0||t.shiftKey===!0,ctrlKey:e.ctrlKey===!0||t.ctrlKey===!0,altKey:e.altKey===!0||t.altKey===!0,metaKey:e.metaKey===!0||t.metaKey===!0}}function ol(e){const t=String(e||""),a=Object.prototype.hasOwnProperty.call(zf,t)?zf[t]:t;return Object.prototype.hasOwnProperty.call(Vf,a)?{...Vf[a],repeat:!1}:null}function NC(e){const t=String(e??"").replace(/\0/g,"");if(!t)return[];const a=[];let r=t;for(;r.length>0;){let c=Math.min(TC,r.length);c<r.length&&/[\uD800-\uDBFF]/.test(r[c-1])&&/[\uDC00-\uDFFF]/.test(r[c])&&(c-=1),a.push(r.slice(0,c)),r=r.slice(c)}return a}function FC(e,t,a){const r=Od(e),c=zg(e.key),u=Number(e.keyCode??e.which),p=Number(e.location);return{type:t,key:c,code:r,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(p)?Math.max(0,Math.min(255,Math.trunc(p))):0,text:c.length===1?c:"",repeat:t==="keydown"&&e.repeat===!0,pressedCodes:[...a],..._d(a)}}function DC(){const e=new Set,t=new Set,a=()=>({pressedCodes:[...e]});return{event(r={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=Od(r);if(!u)return null;const p=wl(u),h=e.has(u),f=[...e];return p?c==="keydown"?(al(e,t,r,p,c),e.size<Dd&&e.add(u)):(t.has(u)||e.delete(u),al(e,t,r,p,c)):(al(e,t,r),c==="keydown"?e.size<Dd&&e.add(u):e.delete(u)),c==="keyup"&&p==="metaKey"&&!Aa(e,"metaKey")&&Uf(e),c==="keydown"&&h&&r.repeat!==!0&&PC(f,e)?null:FC(r,c,e)},modifier(r,c){const u=Ld(r),p=wl(u);if(!p)return null;const h=t.has(u);return c===h?null:(c?(t.add(u),e.add(u)):(t.delete(u),e.delete(u),p==="metaKey"&&!Aa(e,"metaKey")&&Uf(e)),{type:c?"keydown":"keyup",key:p==="metaKey"?"Meta":p==="ctrlKey"?"Control":p==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...a(),..._d(e)})},reset(r="keyboard-owner-reset",c=!1){const u=e.size>0;return e.clear(),t.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Qd(r,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(r={}){const c=typeof r=="string"?Ld(r):Od(r);if(e.has(c))return!0;const u=wl(c);return!!u&&Aa(e,u)},snapshot(){return{...a(),latchedCodes:[...t],..._d(e)}}}}const Ug=64,LC=2;function qg(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(1,Math.min(Ug,t)):1}function Xd(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(0,Math.min(Ug-1,t)):0}function Gg(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"||t==="linux"||t.startsWith("linux ")}function OC(e,t,a){const r=String(t||"").trim();if(!r)return e||null;const c=String(a||"").trim();return e&&e.fingerprint===r&&(c?e.sampleId===c:e.sampleId==="")?e:{fingerprint:r,sampleId:c,consecutiveSamples:e?.fingerprint===r?e.consecutiveSamples+1:1}}function Kg({platform:e,topologyFingerprint:t,consecutiveTopologySamples:a}){return Gg(e)?!!String(t||"").trim()&&Number(a)>=LC:!0}function _C({requestedIndex:e,monitorCount:t,platform:a,topologyFingerprint:r,consecutiveTopologySamples:c}){const u=Xd(e),p=qg(t);return u<p||!Kg({platform:a,topologyFingerprint:r,consecutiveTopologySamples:c})?u:p-1}function jC(e,t,a){const r=Xd(e),c=qg(t);return r<c||Gg(a)?r:c-1}const BC=820,HC=500,qf=`(max-width: ${BC}px), (orientation: landscape) and (max-height: ${HC}px) and (pointer: coarse)`,WC="1200px 0px 1800px 0px",$C=960,VC=540,zC=68,Gf=6,UC=30,Kf=24,qC=16;function GC(e,t,a,r){return/iPad|iPhone|iPod/i.test(String(e||""))||t==="MacIntel"&&Number(a)>1||typeof r=="boolean"}function KC(e,t,a=""){const r=[...new Set((Array.isArray(e)?e:[]).map(u=>String(u||"").trim()).filter(Boolean))];if(!t)return r;const c=String(a||"").trim();return!c||!r.includes(c)?r.slice(0,Gf):[c,...r.filter(u=>u!==c)].slice(0,Gf)}function YC(e,t){const a=Math.max(1,Math.floor(Number(e)||1));return t?Math.min(a,UC):a}function QC(e,t,a=1){const r=e&&typeof e=="object"?e:{},c={fps:Math.max(1,Math.floor(Number(r.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(r.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(r.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(r.quality)||1)))};return t?{...c,maxWidth:Math.min(c.maxWidth,$C),maxHeight:Math.min(c.maxHeight,VC),quality:Math.min(c.quality,zC)}:c}function XC(e,t){return!t||!e||typeof e.closest!="function"?null:e.closest(".desk-stage")}function Yf(e,t,a){return!!(e||t&&a)}function JC({isIos:e,standalone:t,safeAreaTop:a,screenHeight:r,layoutViewportHeight:c}){if(!e||!t)return 0;const u=Number(r),p=Number(c);if((Number.isFinite(u)&&u>0&&Number.isFinite(p)&&p>0?Math.max(0,u-p):0)>=qC)return 0;const f=Number(a);return Number.isFinite(f)&&f>0?Math.max(Kf,Math.round(f)-20):Kf}function ZC(e,t,a,r=!1,c=r){const u=Number(e?.height),p=Number(t),h=Number(e?.offsetTop),f=r&&Number.isFinite(p)&&p>0,k=f?0:Number.isFinite(h)?Math.max(0,Math.round(h)):0,M=f?p:Number.isFinite(u)&&u>0?u:Number.isFinite(p)&&p>0?p:1,b=Number(e?.width),T=Number(a),I=c&&Number.isFinite(T)&&T>0,x=I?T:Number.isFinite(b)&&b>0?b:Number.isFinite(T)&&T>0?T:1,E=Number(e?.offsetLeft);return{height:Math.max(1,Math.round(M)),width:Math.max(1,Math.round(x)),offsetTop:k,offsetLeft:I?0:Number.isFinite(E)?Math.max(0,Math.round(E)):0}}const jd=3e4;function Yg(e={},t={}){const a=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=t?.cadence==="slow"?"slow":"fast",c=Number.isFinite(Number(t?.viewScale))?Math.max(0,Math.min(100,Math.round(Number(t.viewScale)))):100;return{cadence:a.cadence==="slow"||a.cadence==="fast"?a.cadence:r,viewScale:Number.isFinite(Number(a.viewScale))?Math.max(0,Math.min(100,Math.round(Number(a.viewScale)))):c}}function e0(e){return Number(e)<=0?"list":"large"}function t0(e,t){return!e||typeof e!="object"||Array.isArray(e)||!t||typeof t!="object"||Array.isArray(t)?!1:e.cadence===t.cadence&&Number.isFinite(Number(e.viewScale))&&Math.round(Number(e.viewScale))===t.viewScale}function n0({error:e,publicConsole:t,workspaceKind:a,workspaceRole:r,workspaceId:c,userId:u}){const p=String(e instanceof Error?e.message:e||"").trim().toLowerCase(),h=String(c||"").trim().toLowerCase(),f=String(u||"").trim().toLowerCase();return t===!0&&String(a||"").trim().toLowerCase()==="personal"&&String(r||"").trim().toLowerCase()==="owner"&&!!h&&h===f&&p==="502 console-route-not-allowed"}function ad(e=!1){return e?"/api/settings":"/api/remote/wall-preferences"}function r0({legacy:e=!1,revision:t,preferences:a}){const r=Yg(a);return e?{revision:t,wall:r}:{revision:t,cadence:r.cadence,viewScale:r.viewScale}}function a0(e,t=!1){if(!(!e||typeof e!="object"||Array.isArray(e)))return t?e.settings?.wall:e.wallPreferences}function o0({wallSize:e,elapsedMs:t}){return e==="list"&&Number.isFinite(Number(t))&&Number(t)>=jd}function Qf(e){const t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:0}function i0(e=""){let t=String(e||""),a,r=0;const c=h=>{const f=String(h||"");return f===t?!1:(t=f,a=void 0,r+=1,!0)},u=h=>String(h||"")!==t||!t?null:(r+=1,Object.freeze({ownerKey:t,generation:r})),p=h=>!!h&&h.ownerKey===t&&h.generation===r;return{switchOwner:c,beginWrite:u,ownsWrite:p,readRevision(h){return String(h||"")===t?a:void 0},acceptSnapshot(h,f){if(String(h||"")!==t)return!1;const k=Qf(f);return a!==void 0&&k<a?!1:(a=k,!0)},commitWriteRevision(h,f){return p(h)?(a=Qf(f),!0):!1},inspect(){return{ownerKey:t,revision:a,writeGeneration:r}}}}function s0(e,t){const a=Promise.resolve(e).catch(()=>{}).then(t);return{result:a,tail:a.then(()=>{},()=>{})}}function c0(){let e=Promise.resolve(),t=Promise.resolve();const a=r=>{const c=s0(e,r);return e=c.tail,c.result};return{enqueue:a,enqueueStop(r){const c=a(r);return t=c.then(()=>{}),t.catch(()=>{}),c},enqueueStart(r){const c=t;return a(async()=>(await c,r()))}}}function l0(e={}){return Number(e.generation)===Number(e.currentGeneration)&&e.enabled===!0&&String(e.deviceId||"")!==""&&String(e.deviceId||"")===String(e.currentDeviceId||"")&&e.documentVisible===!0&&e.presentationVisible===!0&&String(e.streamId||"")!==""&&String(e.streamId||"")===String(e.currentStreamId||"")}function u0(e={}){const t=e.ok!==!1,a=t&&e.staleOwner===!0;return{confirmed:t&&(a||e.captureStopConfirmed===!0||e.alreadyStopped===!0),staleOwner:a,preserveNewerOwner:a&&(e.retainedNewerOwner===!0||String(e.activeStreamId||"")!=="")}}const wt=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,intentionalIdleTelemetryFreshMs:3e3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function Ms(e){return e==="slow"?wt.slowWallFps:wt.fastWallFps}function Xf(e,t){const a=e&&typeof e=="object"?e:{};return Object.entries(t&&typeof t=="object"?t:{}).some(([c,u])=>{const p=String(u||"").trim();return p.length>0&&String(a[c]||"").trim()!==p})}function Jf({paintStale:e,lastRecoveryAt:t,now:a,recoveryCooldownMs:r,transportRecoveryAfterMs:c}){if(e!==!0)return"none";const u=Math.max(0,Number(a)||0),p=Math.max(0,Number(t)||0),h=p>0?u-p:Number.POSITIVE_INFINITY;return p>0&&h>=Math.max(1,Number(c)||1)?"recover-transport":p<=0||h>=Math.max(1,Number(r)||1)?"reset-decoder":"wait"}function Zf({lastReceivedAt:e,lastPaintedAt:t,now:a,staleAfterMs:r}){const c=Math.max(0,Number(e)||0);if(c<=0)return!1;const u=Math.max(0,Number(t)||0),p=u>0?u:c;return Math.max(0,Number(a)||0)-p>Math.max(1,Number(r)||1)}function d0(e,t){const a=e&&typeof e=="object"?e:{},r=t&&typeof t=="object"?t:{},c=Object.keys(a),u=Object.keys(r);return c.length!==u.length?r:u.every(p=>Object.prototype.hasOwnProperty.call(a,p)&&String(a[p]||"").trim()===String(r[p]||"").trim())?a:r}function eh({presentationOwnerActive:e,desiredDeviceCount:t}){return e===!0&&Math.max(0,Math.floor(Number(t)||0))>0}function m0(e){return e==="share-files"||e==="agents"}function p0({captureOwnershipActive:e,localFeatureAccess:t,controlSessionDeviceId:a,planAllowed:r,sessionState:c,controlFocusVisible:u,presentationCanvasMounted:p,wallPresentationVisible:h,wallPresentationCanvasMounted:f,decoderOwnerExists:k}){const M=c==="connecting"||c==="active"||c==="warm";return e!==!0||t!==!0||!String(a||"").trim()||r!==!0||!M?!1:k===!0||u===!0&&p===!0||h===!0&&f===!0}function f0({decodeWidth:e,decodeHeight:t,presentationCssWidth:a,presentationCssHeight:r,devicePixelRatio:c,sourceWidth:u,sourceHeight:p}){const h=Math.max(0,Number(e)||0),f=Math.max(0,Number(t)||0),k=Math.max(0,Number(a)||0),M=Math.max(0,Number(r)||0),b=Math.max(1,Math.min(2,Number(c)||1)),T=Math.max(0,Number(u)||0),I=Math.max(0,Number(p)||0);if(h<=0||f<=0||k<=0||M<=0||T<=0||I<=0)return!1;const x=k*b,E=M*b,H=Math.min(1,x/T,E/I),Q=Math.max(1,Math.round(T*H)),G=Math.max(1,Math.round(I*H));return h<Q*.9||f<G*.9}function h0({cadenceCredit:e,targetFps:t,sourceFps:a,elapsedSincePaintMs:r=0,nowMs:c=0,scheduledPaintAtMs:u=0,force:p=!1}){const h=Math.max(1,Number(t)||1),f=Math.max(1,Number(a)||1);if(h>=f)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const k=Math.max(0,Number(c)||0),M=Math.max(0,Number(u)||0),b=k>0&&M>0,T=1e3/h,I=Math.min(T/3,1e3/f*.5),x=Number.isFinite(Number(e))?Math.max(0,Math.min(f-Number.EPSILON,Number(e))):0;if(p)return{shouldPaint:!0,nextCadenceCredit:x,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:b?M:k>0?k+T:0};const E=x+h,H=E>=f,Q=1e3/h*wt.controlWallReuseStarvationFactor,G=!H&&Number(r)>=Q,ne=b&&k+I>=M,ae=b?ne||G:H||G;let O=M;return ae&&k>0&&(!b||G?O=k+T:(O=M+T,O<=k-T&&(O=k+T))),{shouldPaint:ae,nextCadenceCredit:G?0:H&&ae?E-f:Math.min(f-Number.EPSILON,E),sourceCadencePassthrough:!1,deadlineForced:G,scheduleSelected:ne,nextScheduledPaintAtMs:O}}function g0(e,t){const a=Number.isFinite(Number(t))?Math.max(0,Math.floor(Number(t))):Number.POSITIVE_INFINITY;if(a<=0)return[];const r=(Array.isArray(e)?e:[]).filter(p=>p&&String(p.deviceId||"").trim()).slice().sort((p,h)=>{const f=Number.isFinite(Number(p.slotNumber))?Number(p.slotNumber):Number.MAX_SAFE_INTEGER,k=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return f!==k?f-k:String(p.deviceId).localeCompare(String(h.deviceId))}),c=[],u=new Set;for(const p of r){const h=String(p.deviceId).trim();if(!u.has(h)&&(u.add(h),c.push(h),c.length>=a))break}return c}function b0(e,t){const a=Math.max(0,Math.floor(Number(t)||0));return e===!0&&a>0}function fs({mode4Enabled:e,directMode4WallEnabled:t,isMac:a}){return"direct"}function v0({mode4Enabled:e,directMode4WallEnabled:t,adaptiveFps:a,directDeviceCount:r,adaptive:c=!0}){return Math.max(1,Math.floor(Number(a)||1))}function y0({directDeviceCount:e,requestedFps:t,measuredFramesPerSecond:a,measuredPaintFramesPerSecond:r,measuredBytesPerSecond:c,maxBytesPerSecond:u,worstReceiveGapMs:p,worstPaintP95Ms:h,maxFrameGapMs:f}){const k=Math.max(1,Math.floor(Number(e)||1)),M=Math.max(1,Number(t)||1),b=Math.max(0,Number(a)||0),T=Math.max(0,Number(r)||0),I=Math.max(0,Number(c)||0),x=Math.max(1,Number(u)||1),E=Math.max(0,Number(p)||0),H=Math.max(0,Number(h)||0),Q=Math.max(1,Number(f)||1),G=k*M,ne=G>8&&b<G*wt.missingDeliveryRatio,ae=G>8&&T<G*wt.missingDeliveryRatio,O=I>x||E>Q||ne||ae,te=b>=G*wt.recoveryDeliveryRatio&&T>=G*wt.recoveryDeliveryRatio&&I<x*wt.recoveryByteRatio&&E<Q*wt.recoveryGapRatio&&H<Q*wt.recoveryGapRatio;return{expectedFramesPerSecond:G,estimatedMissingFrames:ne,estimatedMissingPaints:ae,overloaded:O,healthyForRecovery:te}}function w0({receiveSampleMs:e,paintSampleMs:t,currentGenerationVerified:a,frameRequestedFps:r,adaptiveFps:c}){const u=Number(e),p=Number(t),h=Number(r),f=Number(c);return a===!0&&Number.isFinite(u)&&u>=wt.adaptiveMinimumCurrentSampleMs&&Number.isFinite(p)&&p>=wt.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===f}function S0(e,t=Date.now()){const a=e&&typeof e=="object"?e:{},r=Number(t),c=Number(a.browserReceivedEpochMs),u=Number(a.nativeCaptureTelemetryAgeMs),p=a.nativeCaptureTelemetryAvailable===!0&&a.nativeCaptureResourceTelemetryAvailable===!0&&Number(a.nativeCaptureTelemetryVersion)>=5&&Number.isFinite(r)&&Number.isFinite(c)&&c>0&&r>=c&&Number.isFinite(u)&&u>=0&&u+(r-c)<=wt.intentionalIdleTelemetryFreshMs,h=Math.max(0,Number(a.requestedFps||a.effectiveFps||0)),f=Math.max(0,Number(a.nativeCaptureFps||0)),k=Math.max(0,Number(a.nativeEncodedFps||0)),M=Math.max(0,Number(a.nativeCaptureSampleCount||0)),b=Math.max(0,Number(a.nativeIdleSkippedFrameCount||0)),T=Math.max(0,Number(a.nativeBackpressureSkippedFrameCount||0)),I=h>0&&f>=h*wt.missingDeliveryRatio,x=k>=1&&k<h*wt.missingDeliveryRatio;return p&&M>0&&I&&x&&b>=Math.max(1,f*.6)&&T===0}function C0({deviceCount:e,targetFps:t,adaptive:a=!0}){const r=Math.max(1,Math.floor(Number(e)||1)),c=Math.max(1,Math.min(wt.scalableAtlasMaxInputFps,Math.floor(Number(t)||wt.scalableAtlasMaxInputFps)));if(!a)return c;const u=Math.max(wt.scalableAtlasMinInputFps,Math.min(wt.scalableAtlasMaxInputFps,Math.floor(wt.scalableAtlasAggregateInputFps/r)));return Math.min(c,u)}function k0(e,t){return{acceleration:wt.directDecodeAcceleration,latencyMode:wt.directLatencyMode}}const Al=0,ea=100,M0=25,x0=50,th=300,R0=560;function Mi(e){return Number.isFinite(e)?Math.min(ea,Math.max(Al,Math.round(e))):ea}function A0(e){const t=Mi(e);return t===Al?"list":t<x0?"medium":"large"}function I0(e){const a=(Math.max(1,Mi(e))-1)/(ea-1);return Math.round(th+a*(R0-th))}function il(e){if(!e)return"";const t=Math.max(0,Math.floor((Date.now()-e)/1e3)),a=Math.floor(t/3600),r=Math.floor(t%3600/60),c=t%60;return a>0?`${String(a).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(r).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function nh({controller:e,compact:t=!1,onFirstRollingUse:a,onError:r}){const{state:c,settings:u,videoSupported:p}=e,h=async b=>{try{await b()}catch(T){r?.(T instanceof Error?T.message:String(T))}},f=async()=>{if(u.rollingEnabled){e.setRollingEnabled(!1);return}(a?await a():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
175
|
-
Nothing is saved until you press Save Last 30s.`))&&e.setRollingEnabled(!0)},k=c.recording?`Stop recording · ${il(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,M=c.timelapse?`Stop timelapse · ${il(c.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return i.jsxs("div",{className:`capture-toolbar ${t?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[i.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{h(e.takeScreenshot)},type:"button",children:i.jsx(
|
|
176
|
-
${
|
|
177
|
-
${le?.currentUserRole||""}`:"",Ce=s.useRef({key:R,generation:0});Ce.current.key!==R&&(Ce.current={key:R,generation:Ce.current.generation+1});const[we,Ve]=s.useState(!1),[Oe,it]=s.useState(""),[z,Me]=s.useState(null),[je,qe]=s.useState(!1),[kt,Te]=s.useState(""),[Be,K]=s.useState(le?.name||""),[ve,st]=s.useState(""),ot=()=>({...Ce.current}),bt=ie=>Ce.current.generation===ie.generation&&Ce.current.key===ie.key&&ie.key===R,Mt=ll[p],oe=s.useMemo(()=>!Number.isFinite(k)||k<=0?0:Math.min(100,Math.round(f/k*100)),[f,k]),$=()=>{Ce.current={key:"",generation:Ce.current.generation+1},pe()};if(j.current=$,s.useEffect(()=>{if(!e)return;Fe.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const ie=window.requestAnimationFrame(()=>de.current?.focus()),Pe=He=>{if(He.key==="Escape"){He.preventDefault(),j.current();return}if(He.key!=="Tab"||!Se.current)return;const vt=Array.from(Se.current.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));if(vt.length===0){He.preventDefault(),Se.current.focus();return}const Je=vt[0],At=vt[vt.length-1];He.shiftKey&&document.activeElement===Je?(He.preventDefault(),At.focus()):!He.shiftKey&&document.activeElement===At&&(He.preventDefault(),Je.focus())};return window.addEventListener("keydown",Pe),()=>{window.cancelAnimationFrame(ie),window.removeEventListener("keydown",Pe),Fe.current?.focus(),Fe.current=null}},[e]),s.useEffect(()=>{Me(null),it(""),qe(!1),Te(""),Ve(!1),st(""),K(le?.name||"")},[R,le?.name]),s.useEffect(()=>{ve||K(le?.name||"")},[ve,le?.name]),!e)return null;const ye=async()=>{if(!q||we||x||!R)return;const ie=ot(),Pe=()=>bt(ie);Ve(!0),it(""),qe(!1);try{const He=await q(kt);if(!Pe())return;if(!He?.url)throw new Error("The invite link was not returned.");Me(He),Te("")}catch(He){if(!Pe())return;it(He instanceof Error?He.message:"The invite link could not be created.")}finally{Pe()&&Ve(!1)}},V=async()=>{if(!F||ve)return;const ie=ot(),Pe=Be.trim();if(!Pe){it("Enter a Team Space name.");return}st("rename"),it("");try{if(await F(Pe),!bt(ie))return}catch(He){if(!bt(ie))return;it(He instanceof Error?He.message:"The Team Space could not be renamed.")}finally{bt(ie)&&st("")}},Ge=async()=>{if(!ee||ve)return;const ie=ot();st("leave"),it("");try{if(await ee(),!bt(ie))return;$()}catch(Pe){if(!bt(ie))return;it(Pe instanceof Error?Pe.message:"The Team Space could not be left.")}finally{bt(ie)&&st("")}},St=async ie=>{if(ve)return;const Pe=ot(),He=ie.status==="invited"?P:ue;if(He){st(`member:${ie.id}`),it("");try{if(await He(ie.id),!bt(Pe))return}catch(vt){if(!bt(Pe))return;it(vt instanceof Error?vt.message:"The Team member could not be changed.")}finally{bt(Pe)&&st("")}}},A=async()=>{if(z?.url)try{await navigator.clipboard.writeText(z.url),qe(!0),window.setTimeout(()=>qe(!1),1800)}catch{it("Copy failed. Select and copy the invite link manually.")}};return i.jsx("div",{className:"account-dialog-backdrop",role:"presentation",onPointerDown:ie=>{ie.currentTarget===ie.target&&$()},children:i.jsxs("section",{id:"vuvodesk-account-dialog",ref:Se,className:"account-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"account-dialog-title",tabIndex:-1,onPointerDown:ie=>ie.stopPropagation(),children:[i.jsxs("header",{className:"account-dialog-header",children:[i.jsxs("div",{className:"account-dialog-identity",children:[i.jsx("span",{className:"account-dialog-avatar",children:t&&u?i.jsx("img",{src:u,alt:"",referrerPolicy:"no-referrer"}):t?i.jsx("span",{children:c}):i.jsx(Sl,{size:21,"aria-hidden":"true"})}),i.jsxs("span",{children:[i.jsx("small",{children:"VuvoDesk account"}),i.jsx("strong",{id:"account-dialog-title",children:t?a:"Sign in to manage VuvoDesk"}),i.jsx("span",{children:r||"Your computers and plan stay with your account."})]})]}),i.jsx("button",{ref:de,className:"account-dialog-close",onClick:$,type:"button","aria-label":"Close account",children:i.jsx(Ma,{size:20,"aria-hidden":"true"})})]}),i.jsxs("div",{className:"account-dialog-body",children:[te&&i.jsxs("div",{className:"account-session-revocation-error",role:"alert",children:[i.jsx("strong",{children:"Hub sign-out is not confirmed"}),i.jsx("span",{children:"Wall and Control stay blocked. Retry when the Hub is reachable so its browser permission is removed."}),re&&i.jsx("button",{onClick:()=>{re()},disabled:I,type:"button",children:I?"Retrying…":"Retry Hub sign-out"})]}),O&&i.jsxs("section",{className:"account-workspace-switcher","aria-labelledby":"account-workspace-title","aria-busy":x,children:[i.jsxs("div",{children:[i.jsx("span",{id:"account-workspace-title",children:"Workspaces"}),i.jsx("small",{children:"Keep Personal separate from every Team you join."})]}),i.jsx("div",{className:"account-workspace-list",children:Z.map(ie=>i.jsxs("button",{className:ie.id===me?"active":"",onClick:()=>{ie.id!==me&&_?.(ie.id)},disabled:x||ie.id!==me&&!_,"aria-pressed":ie.id===me,type:"button",children:[i.jsx("span",{children:ie.kind==="team"?i.jsx(As,{size:15,"aria-hidden":"true"}):i.jsx(Qh,{size:15,"aria-hidden":"true"})}),i.jsxs("span",{children:[i.jsx("strong",{children:ie.name}),i.jsx("small",{children:ie.kind==="team"?ie.role==="operator"?"Operator · Wall and Control":ie.memberCount===void 0?"Owner · Team Space":`Owner · ${ie.memberCount} people`:"Personal workspace"})]}),i.jsx("em",{children:ll[ie.plan].shortName})]},ie.id))})]}),i.jsxs("section",{className:`account-current-plan plan-${p}`,"aria-label":h?"Current VuvoDesk plan":"VuvoDesk plan policy",children:[i.jsxs("div",{className:"account-current-plan-copy",children:[i.jsx("span",{className:"account-current-plan-icon",children:ih(p)}),i.jsxs("span",{children:[i.jsx("small",{children:h?"Current plan":"Plan policy"}),i.jsx("strong",{children:h?Mt.name:"Plan is managed at the Hub"}),i.jsx("span",{children:M})]})]}),i.jsxs("div",{className:"account-device-usage",children:[i.jsxs("span",{children:[i.jsx(Ra,{size:15,"aria-hidden":"true"})," ",h?"Computer usage":"This Client computer"]}),i.jsxs("strong",{children:[f," ",h&&i.jsxs("small",{children:["/ ",oh(k)]})]}),h&&Number.isFinite(k)&&i.jsx("span",{className:"account-device-meter","aria-label":`${f} of ${oh(k)} computers used`,children:i.jsx("i",{style:{width:`${oe}%`}})})]}),i.jsxs("dl",{className:"account-runtime-facts",children:[i.jsxs("div",{children:[i.jsx("dt",{children:"Hub"}),i.jsx("dd",{children:b})]}),i.jsxs("div",{children:[i.jsx("dt",{children:"Remote access"}),i.jsx("dd",{children:T})]})]})]}),i.jsxs("section",{className:"account-plan-section","aria-labelledby":"account-plan-section-title",children:[i.jsxs("div",{className:"account-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"License and features"}),i.jsx("h2",{id:"account-plan-section-title",children:"One account, the right way to manage your computers"})]}),i.jsx("small",{children:"Team members never share a Google login."})]}),i.jsx("div",{className:"account-plan-grid",children:Object.keys(ll).map(ie=>{const Pe=ll[ie],He=h&&p===ie,vt=h&&rh[ie]<rh[p],Je=ne&&!He&&!vt&&ie!=="free";return i.jsxs("article",{className:`account-plan-card plan-${ie} ${He?"current":""}`,children:[i.jsxs("div",{className:"account-plan-card-title",children:[i.jsxs("span",{children:[ih(ie)," ",Pe.name]}),He&&i.jsxs("em",{children:[i.jsx(hl,{size:13,"aria-hidden":"true"})," Current"]})]}),i.jsx("p",{children:Pe.audience}),i.jsx("span",{className:"account-plan-price",children:Pe.price}),Pe.ltdPrice&&i.jsxs("span",{className:"account-plan-ltd-price",children:[Pe.ltdPrice," · one-time"]}),i.jsx("strong",{children:Pe.deviceText}),i.jsx("ul",{children:Pe.features.map(At=>i.jsxs("li",{children:[i.jsx(hl,{size:14,"aria-hidden":"true"})," ",At]},At))}),He||vt||ie==="free"||!ne?i.jsx("span",{className:"account-plan-state",children:He?"Your current plan":vt?"Included in your plan":!ne&&ie!=="free"?ae:"Free plan"}):ie==="plus"||ie==="business"?i.jsxs("div",{className:"account-plan-actions",children:[i.jsxs("button",{className:"account-plan-action secondary",onClick:()=>{L(ie==="plus"?"plus_monthly":"pro_monthly")},disabled:!Je||!Q||I||x||E,type:"button",children:[i.jsx(xa,{size:15,"aria-hidden":"true"}),ne?Q?`Choose ${Pe.billingName} · ${Pe.price}`:"Monthly · Coming soon":ae]}),i.jsxs("button",{className:"account-plan-action",onClick:()=>{L(ie==="plus"?"plus_ltd":"pro_ltd")},disabled:!Je||!H||I||x||E,type:"button",children:[i.jsx(xa,{size:15,"aria-hidden":"true"}),ne?H?`Buy ${Pe.billingName} · ${Pe.ltdPrice}`:"LTD · Coming soon":ae]})]}):i.jsxs("button",{className:"account-plan-action",onClick:()=>{L("team_monthly")},disabled:!Je||!G||I||x||E,type:"button",children:[i.jsx(As,{size:15,"aria-hidden":"true"}),ne?G?`Choose Team · ${Pe.price}`:"Team · Coming soon":ae]})]},ie)})})]}),(p==="team"||le)&&i.jsxs("section",{className:"account-team-panel","aria-labelledby":"account-team-title",children:[i.jsxs("div",{className:"account-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Team Space"}),i.jsx("h2",{id:"account-team-title",children:le?.name||"Your shared computer workspace"})]}),le&&le.currentUserRole==="owner"&&i.jsxs("small",{children:[le.memberCount??le.members.length,"/",le.memberLimit," members"]})]}),le?i.jsxs(i.Fragment,{children:[le.currentUserRole==="owner"&&F&&i.jsxs("div",{className:"account-team-rename",children:[i.jsx("label",{htmlFor:"account-team-name",children:"Team Space name"}),i.jsxs("span",{children:[i.jsx("input",{id:"account-team-name",value:Be,onChange:ie=>K(ie.target.value),maxLength:80,disabled:x||!!ve}),i.jsx("button",{onClick:()=>{V()},disabled:x||!!ve||!Be.trim()||Be.trim()===le.name,type:"button",children:ve==="rename"?"Saving…":"Save name"})]})]}),le.currentUserRole==="owner"&&i.jsx("ul",{className:"account-team-members",children:le.members.map(ie=>i.jsxs("li",{children:[i.jsx("span",{className:"account-member-avatar",children:(ie.displayName||ie.email).slice(0,1).toUpperCase()}),i.jsxs("span",{children:[i.jsx("strong",{children:ie.displayName||ie.email}),i.jsx("small",{children:ie.email})]}),i.jsx("em",{children:ie.role==="owner"?"Owner":"Operator"}),i.jsx("span",{className:`account-member-status status-${ie.status}`,children:ie.status}),le.currentUserRole==="owner"&&ie.role!=="owner"&&(ie.status==="invited"&&P||ie.status==="active"&&ue)&&i.jsx("button",{onClick:()=>{St(ie)},disabled:x||!!ve,type:"button","aria-label":`${ie.status==="invited"?"Cancel invitation for":"Remove"} ${ie.email}`,children:ie.status==="invited"?"Cancel":"Remove"})]},ie.id))}),le.currentUserRole==="owner"&&i.jsxs("div",{className:"account-team-invite",children:[i.jsx("label",{children:"Invite an Operator"}),z?i.jsxs("span",{className:"account-team-invite-result",children:[i.jsx("input",{"aria-label":"Team invite link",value:z.url,readOnly:!0,onFocus:ie=>ie.currentTarget.select()}),i.jsxs("button",{onClick:()=>{A()},type:"button",children:[je?i.jsx(hl,{size:16,"aria-hidden":"true"}):i.jsx(sy,{size:16,"aria-hidden":"true"}),je?"Copied":"Copy link"]}),z.expiresAt&&i.jsxs("small",{children:["Expires ",z.expiresAt]})]}):i.jsxs("span",{className:"account-team-invite-compose",children:[i.jsx("input",{type:"email",value:kt,onChange:ie=>Te(ie.target.value),placeholder:"operator@example.com","aria-label":"Operator Google account email",autoComplete:"email",disabled:x||!le.invitationsEnabled||le.currentUserRole!=="owner"||we}),i.jsxs("button",{className:"account-create-invite",onClick:()=>{ye()},type:"button",disabled:x||!q||!kt.trim()||!le.invitationsEnabled||le.currentUserRole!=="owner"||we,children:[i.jsx(cy,{size:16,"aria-hidden":"true"}),we?"Creating…":"Create invite link"]})]}),i.jsx("p",{children:"Share this one-time link yourself. VuvoDesk does not email the invite."})]}),le.currentUserRole==="operator"&&i.jsx("p",{className:"account-team-operator-note",children:"Operator · Wall and Control. The owner manages settings, billing, members, files, and Agents."}),Oe&&i.jsx("small",{className:"account-team-error",role:"alert",children:Oe}),le.currentUserRole==="operator"&&ee&&i.jsx("button",{className:"account-team-leave",onClick:()=>{Ge()},disabled:x||!!ve,type:"button",children:ve==="leave"?"Leaving…":"Leave this Team Space"})]}):i.jsx("p",{className:"account-team-empty",children:"Team member management will appear here as soon as this account is connected to a Team Space."})]})]}),i.jsxs("footer",{className:"account-dialog-footer",children:[i.jsxs("span",{children:[i.jsx(ly,{size:16,"aria-hidden":"true"})," Licenses belong to this VuvoDesk account, not to one computer."]}),t?i.jsxs("button",{className:"account-auth-action",onClick:()=>{W()},disabled:I,type:"button",children:[i.jsx(uy,{size:16,"aria-hidden":"true"}),"Sign out"]}):i.jsxs("button",{className:"account-auth-action primary",onClick:()=>{se()},disabled:I,type:"button",children:[i.jsx(Sl,{size:16,"aria-hidden":"true"}),"Sign in with Google"]})]})]})})}const sh=Object.freeze({plus_monthly:"ltd",plus_ltd:"ltd",pro_monthly:"pro",pro_ltd:"pro",team_monthly:"team"}),P0=new Set(["plus_monthly","pro_monthly","team_monthly"]);function E0(e){return Object.prototype.hasOwnProperty.call(sh,e)?sh[e]:null}function ch(e){return P0.has(e)}function od(e){return e==="team_monthly"}function N0(e){let t=Promise.resolve();return a=>{const r=t.then(()=>e(a),()=>e(a));return t=r.then(()=>{},()=>{}),r}}const F0=1e3;function D0({now:e=()=>Date.now(),minimumForegroundIntervalMs:t=F0}={}){let a="",r=0,c=null,u=null,p=Number.NEGATIVE_INFINITY;const h=M=>{const b=String(M||"");b!==a&&(a=b,r+=1,c=null,u=null,p=Number.NEGATIVE_INFINITY)},f=(M,b,T)=>{const I=Promise.resolve().then(()=>a===M&&r===b?T():null);return c=I,I.finally(()=>{if(c!==I||a!==M||r!==b)return;c=null;const x=u;u=null,x&&f(M,b,x).catch(()=>{})}).catch(()=>{}),I};return Object.freeze({recover:(M,b,T)=>{const I=String(M||"");if(!I||typeof T!="function"||I!==a)return Promise.resolve(null);if(c)return b==="auth"&&(u=T),c;if(b==="foreground"){const x=Number(e());if(x-p<t)return Promise.resolve(null);p=x}return f(I,r,T)},switchOwner:h,snapshot:()=>Object.freeze({ownerKey:a,inFlight:!!c,queuedAuthRecovery:!!u,lastForegroundRecoveryAt:p})})}const Il="team_invite",id="vuvodesk.pending-team-invite",Ps=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Jd=/^[0-9a-f]{64}$/i,sd=[],cd=[],ld=[];function Co(e){return Array.isArray(e)?e[0]||null:e||null}function wi(e,t){return new Error(String(e?.reason||t).replaceAll("-"," "))}function L0(e){if(e==null)return Number.POSITIVE_INFINITY;const t=Number(e);return Number.isFinite(t)&&t>=0?t:Number.POSITIVE_INFINITY}function lh(e,t){const a=String(e.workspace_id||"").trim(),r=String(e.workspace_kind||"").trim().toLowerCase(),c=String(e.role||"").trim().toLowerCase(),u=String(e.plan||"free").trim().toLowerCase(),p=Number(e.membership_revision||0);return!Ps.test(a)||!["personal","team"].includes(r)||!["owner","operator"].includes(c)||!["free","ltd","pro","team"].includes(u)||!Number.isSafeInteger(p)||p<1?null:{id:a,name:String(e.workspace_name||(r==="personal"?"Personal":"Team")).trim().slice(0,80),kind:r,role:c,membershipRevision:p,plan:u,entitlementStatus:String(e.entitlement_status||"free").trim().toLowerCase(),deviceLimit:L0(e.device_limit),memberLimit:Math.max(1,Number(e.member_limit||1)),commercialUse:e.commercial_use===!0,isActive:t&&e.is_active===!0}}function O0(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has(Il)&&(e.searchParams.delete(Il),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`))}function _0(){if(typeof window>"u")return"";const e=String(new URL(window.location.href).searchParams.get(Il)||"").trim().toLowerCase();return Jd.test(e)?e:""}function j0(e,t=0){const a=e?.user?.id||"",r=a,[c,u]=Xt(r,sd),[p,h]=Xt(r,null),[f,k]=Xt(r,!!a),[M,b]=Xt(r,""),[T,I]=Xt(r,""),x=s.useRef(0),E=s.useRef(0),H=s.useRef(null),Q=s.useRef(""),G=s.useRef(new Set),ne=s.useRef(a);ne.current=a;const ae=s.useRef(null);ae.current||(ae.current=D0());const O=s.useRef(null);O.current||(O.current=N0(async W=>{if(!W.userId||ne.current!==W.userId)throw new Error("workspace selection owner changed");const{data:re,error:L}=await Ct.rpc("set_livedesk_active_workspace",{p_workspace_id:W.workspaceId});if(L)throw L;const _=Co(re);if(!_?.ok)throw wi(_,"workspace selection failed");return _}));const te=s.useCallback(W=>O.current({userId:a,workspaceId:W}),[a]),Z=s.useCallback(async(W="",re=!1)=>{const L=x.current+1;x.current=L;const _=()=>x.current===L&&ne.current===a,q=re?E.current+1:0;if(re&&(E.current=q,H.current={token:q,workspaceId:W},Q.current=""),!a)return Q.current="",re&&H.current?.token===q&&(H.current=null),u(r,sd),h(r,null),k(r,!1),b(r,""),null;k(r,!0),re&&h(r,null);try{if(!_())return null;const{error:ue}=await Ct.rpc("ensure_livedesk_personal_workspace");if(ue)throw ue;if(!_()||(re&&await te(W),!_()))return null;const{data:P,error:F}=await Ct.rpc("list_livedesk_workspaces");if(F)throw F;if(!_())return null;const ee=(Array.isArray(P)?P:[]).map(Oe=>lh(Oe,!0)).filter(Oe=>!!Oe),Se=W?ee.find(Oe=>Oe.id===W):null,de=ee.find(Oe=>Oe.isActive),Fe=ee.find(Oe=>Oe.kind==="personal"&&Oe.id===a),j=Se||de||Fe||ee[0]||null;if(!j)throw new Error("VuvoDesk did not return an accessible workspace.");if(!j.isActive&&!re&&await te(j.id),!_())return null;const{data:R,error:Ce}=await Ct.rpc("get_livedesk_workspace_access",{p_workspace_id:j.id});if(Ce)throw Ce;const we=Co(R);if(!we||we.ok!==!0)throw new Error(String(we?.reason||"workspace access denied").replaceAll("-"," "));const Ve=lh(we,!1);if(!Ve)throw new Error("VuvoDesk returned an invalid workspace access record.");return _()?(Q.current=Ve.id,u(r,ee.map(Oe=>({...Oe,isActive:Oe.id===Ve.id}))),h(r,Ve),b(r,""),k(r,!1),Ve):null}catch(ue){return _()&&(b(r,ue instanceof Error?ue.message:String(ue)),k(r,!1)),null}finally{re&&H.current?.token===q&&(H.current=null)}},[te,h,b,k,u,r,a]),me=s.useCallback(()=>H.current?Promise.resolve(null):Z(),[Z]),le=s.useCallback(W=>{if(!a||W!=="initial"&&document.visibilityState==="hidden"||H.current||Q.current)return Promise.resolve(null);const re=r;return ae.current.recover(re,W,()=>ne.current!==a||H.current||Q.current?null:Z())},[Z,r,a]),pe=s.useCallback(W=>!!W&&ne.current===a&&H.current===null&&Q.current===W,[a]);s.useEffect(()=>{if(ae.current.switchOwner(r),x.current+=1,u(r,sd),h(r,null),b(r,""),I(r,""),Q.current="",H.current=null,!a){k(r,!1);return}return le("initial"),()=>{x.current+=1,ae.current?.switchOwner("")}},[h,b,I,k,u,le,r,a]),s.useEffect(()=>{!a||t<1||le("auth")},[le,t,a]),s.useEffect(()=>{if(!a)return;const W=()=>{document.visibilityState!=="hidden"&&le("foreground")},re=()=>W();return window.addEventListener("pageshow",W),window.addEventListener("online",W),window.addEventListener("focus",W),document.addEventListener("visibilitychange",re),()=>{window.removeEventListener("pageshow",W),window.removeEventListener("online",W),window.removeEventListener("focus",W),document.removeEventListener("visibilitychange",re)}},[le,a]),s.useEffect(()=>{const W=_0();if(W)try{window.sessionStorage.setItem(id,W)}catch{}if(!a)return;let re=W;if(!re)try{re=String(window.sessionStorage.getItem(id)||"").trim().toLowerCase()}catch{}if(!Jd.test(re))return;const L=`${a}:${re}`;if(G.current.has(L))return;G.current.add(L),O0();try{window.sessionStorage.removeItem(id)}catch{}let _=!1;return(async()=>{const{data:q,error:ue}=await Ct.rpc("accept_livedesk_workspace_invite",{p_invite_token:re});if(_)return;if(ue){I(r,ue.message);return}const P=Co(q),F=String(P?.workspace_id||"").trim();if(!P?.ok||!Ps.test(F)){I(r,wi(P,"team invite could not be accepted").message);return}const ee=await Z(F,!0);!_&&ee&&I(r,`Joined ${ee.name}.`)})(),()=>{_=!0}},[Z,I,r,a]),s.useEffect(()=>{if(!a||!p?.id)return;const W=p.id,re=`${a}-${W}`.replace(/[^a-zA-Z0-9]/g,"");let L=null;const _=()=>{L===null&&(L=window.setTimeout(()=>{L=null,pe(W)&&me()},80))},q=Ct.channel(`livedesk-workspace-session-${re}`).on("postgres_changes",{event:"*",schema:"public",table:"livedesk_workspaces",filter:`id=eq.${W}`},_).on("postgres_changes",{event:"*",schema:"public",table:"livedesk_workspace_members",filter:`workspace_id=eq.${W}`},_).subscribe();return()=>{L!==null&&window.clearTimeout(L),Ct.removeChannel(q)}},[p?.id,pe,me,a]);const se=s.useCallback(W=>Ps.test(String(W||"").trim())?Z(W,!0):Promise.reject(new Error("Choose a valid VuvoDesk workspace.")),[Z]);return{workspaces:c,activeWorkspace:p,loading:f,error:M,inviteNotice:T,refresh:me,selectWorkspace:se,isWorkspaceActionCurrent:pe}}function B0(e,t,a,r,c){const u=e?.user?.id||"",p=t?.kind==="team"?t.id:"",h=t?.membershipRevision||0,f=`${u}
|
|
173
|
+
${a}`,[f,k]=Xt(h,null),M=r!=="free"?{workspace_id:t,plan:r,status:c==="active"?"active":["refunded","cancelled"].includes(c)?c:"inactive"}:null;s.useLayoutEffect(()=>{k(h,M)},[c,h,k,t,r]);const b=s.useCallback(async()=>{await u?.()},[u]),T=s.useMemo(()=>!(!f||f.status!=="active"),[f]);return{entitlement:f,licensed:T,loading:!1,error:"",refresh:b}}const ks={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},JS=2500,ZS=3e4,eC=750,tC=2e3,nC=8*1024,rC=32*1024,aC=6,Hg=new Map;function oC(e){return Hg.get(e)}const td={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function iC(e,t,a){const r=Number(t);if(!Number.isFinite(r)||r<=0)return 0;const c=a-r,u=e.minimumHubClockOffsetMs;if(!Number.isFinite(u)||c<Number(u))return e.minimumHubClockOffsetMs=c,0;const p=Math.max(0,c-Number(u));return p>ZS?(e.minimumHubClockOffsetMs=c,0):p}function Ae(e){if(e==null||e==="")return;const t=Number(e);return Number.isFinite(t)?t:void 0}const sC=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function cC(e){return Number(e.nativeCaptureTelemetryVersion)>=5&&sC.every(t=>Ae(e[t])!==void 0)&&typeof e.nativeOutputQueueAwaitingKeyFrame=="boolean"&&e.nativeCopyTelemetryAvailable===!0}function lC(e,t,a){if(!e||typeof e!="object")return null;const r=e,c=String(r.deviceId||t||"").trim(),u=String(r.sessionId||"").trim(),p=String(r.streamId||"").trim(),h=r.streamPurpose==="control"?"control":r.streamPurpose==="wall"?"wall":null,f=String(r.commandId||"").trim(),k=Number(r.captureGeneration||0),M=Number(r.monitorIndex??-1),b=r.readOnlyControlBorrow===!0,T=r.presentationPurpose==="wall"?"wall":void 0;return!c||c!==t||!h||!(h===a||a==="wall"&&h==="control"&&b&&T==="wall")||!u||!p||!f||!Number.isSafeInteger(k)||k<=0||!Number.isSafeInteger(M)||M<0?null:{deviceId:c,sessionId:u,streamId:p,streamPurpose:h,commandId:f,captureGeneration:k,monitorIndex:M,readOnlyControlBorrow:b,presentationPurpose:T,effectiveProfile:r.effectiveProfile&&typeof r.effectiveProfile=="object"?r.effectiveProfile:null}}function Ef(e,t,a=In,r={},c=""){const[u,p]=Xt(c,Pf),[h,f]=s.useState("idle"),[k,M]=s.useState(""),[b,T]=s.useState(ks),A=s.useRef(new Map),x=s.useRef(new Map),E=s.useRef(new Map),B=s.useRef(null);B.current===null&&(B.current=Ly());const q=s.useRef(0),G=s.useRef(new Map),ne=s.useRef(new Map),re=s.useRef({enabled:!1,token:"",reason:""}),O=s.useRef(new Map),ie=s.useRef(null),J=s.useRef(new Map),[de,se]=s.useState(0),pe=s.useRef(r.onFrame),ce=s.useRef(r.onStreamBound),W=s.useRef(r.onStreamReady),ee=s.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),L=s.useMemo(()=>[...e].sort().join(","),[e]),_=t&&L.length>0,K=s.useRef(!1),ue=s.useRef(L),P=s.useRef(c);ue.current=L,P.current=c,s.useLayoutEffect(()=>(K.current=_,()=>{K.current=!1}),[_]);const N=Number.isFinite(r.fps)?Number(r.fps):2,te=Number.isFinite(r.maxWidth)?Number(r.maxWidth):640,we=Number.isFinite(r.maxHeight)?Number(r.maxHeight):360,me=Number.isFinite(r.quality)?Number(r.quality):45,Fe=Number.isFinite(r.configurationRefreshMs)?Math.max(0,Math.round(Number(r.configurationRefreshMs))):0,H=String(r.frameMode||r.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",R=r.streamPurpose==="control"?"control":"wall",Se=r.allowReadOnlyControlBorrow===!0,Ce=r.forceRestart===!0,Ve=String(r.forceRestartToken||"").trim(),qe=String(r.restartReason||"").trim();re.current={enabled:Ce,token:Ve,reason:qe};const Oe=s.useMemo(()=>{const ae=Object.entries(r.monitorSelections||{}).filter(([$])=>!!$).sort(([$],[ye])=>$.localeCompare(ye));return JSON.stringify(Object.fromEntries(ae))},[r.monitorSelections]),z=s.useMemo(()=>{const ae=Object.entries(r.connectionSessionIds||{}).filter(([$])=>!!$).map(([$,ye])=>[$,String(ye||"").trim()]).sort(([$],[ye])=>$.localeCompare(ye));return JSON.stringify(Object.fromEntries(ae))},[r.connectionSessionIds]);s.useEffect(()=>{pe.current=r.onFrame},[r.onFrame]),s.useEffect(()=>{ce.current=r.onStreamBound},[r.onStreamBound]),s.useEffect(()=>{W.current=r.onStreamReady},[r.onStreamReady]);const Me=s.useCallback((ae,$="livedesk-frame-socket-release")=>{Oy(ae,$,B.current)},[]),je=s.useCallback(ae=>{const $=O.current.get(ae);$!==void 0&&(window.clearTimeout($),O.current.delete(ae))},[]),Ge=s.useCallback((ae,$)=>{const ye=String(ae||"").trim();if(!ye||O.current.has(ye))return!1;const V=window.setTimeout(()=>{O.current.get(ye)===V&&(O.current.delete(ye),!(!K.current||P.current!==$||!ue.current.split(",").includes(ye)||Wu(E.current.get(ye),$))&&se(Ke=>Ke+1))},eC);return O.current.set(ye,V),!0},[]),kt=s.useCallback(()=>{if(!_)return[];const ae=L.split(",").filter(Boolean),$=_y(ae,E.current,O.current,c);for(const ye of $)Ge(ye,c);return $.length===ae.length&&$.length>0&&f("connecting"),$},[L,Ge,_,c]),Te=s.useCallback(ae=>{const $=J.current.get(ae);$!==void 0&&(window.clearTimeout($),J.current.delete(ae))},[]),Be=s.useCallback((ae,$=!0)=>{for(const ye of O.current.values())window.clearTimeout(ye);O.current.clear();for(const ye of J.current.values())window.clearTimeout(ye);J.current.clear();for(const ye of E.current.values())ye.expectedBinding=void 0,Me(ye,ae);E.current.clear(),G.current.clear(),ne.current.clear(),A.current=new Map,x.current.clear(),ee.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},$&&(p(c,Pf),M(""),T(ks),f("idle"))},[Me,p,c]),Y=s.useCallback(()=>{const ae=[...E.current.values()].map($=>$.socket);if(ae.length===0){f("idle");return}if(ae.some($=>$.readyState===WebSocket.OPEN)){f("open");return}if(ae.some($=>$.readyState===WebSocket.CONNECTING)){f("connecting");return}f("closed")},[]),ve=s.useCallback((ae,$,ye,V)=>{if($.disposed||$.socket.readyState!==WebSocket.OPEN)return!1;try{return $.socket.send(JSON.stringify({...$.payload,type:"restart-live",deviceIds:[ae],forceRestart:!0,restartReason:ye,restartToken:V})),$.restartMayHaveApplied=!0,$.expectedBinding=void 0,Cf($.sparseTelemetry),!0}catch{return!1}},[]),st=s.useCallback((ae,$)=>{if($.disposed||E.current.get(ae)!==$||$.socket.readyState!==WebSocket.OPEN)return!1;try{return $.socket.send(JSON.stringify({...$.payload,type:"refresh-live",deviceIds:[ae],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{$.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),it=s.useCallback((ae,$)=>{if(!K.current||$.workspaceOwnerKey!==P.current||$.disposed||!ae||ae.byteLength<5)return;const ye=Date.now(),Ke=new DataView(ae).getUint32(0,!1);if(Ke<=0||Ke+4>ae.byteLength)return;const St=new Uint8Array(ae,4,Ke),I=JSON.parse(Yd.decode(St));uS(I,$.sparseTelemetry,$.expectedBinding);const oe=Ae(I.hubPacketEpochMs),Pe=oe!==void 0&&oe>0?oe:void 0,He=iC($,Pe,ye);if(He>JS)return;const vt=new Uint8Array(ae,4+Ke),Ze=Ae(I.nativeCaptureTelemetryVersion),At=Ae(I.nativeCaptureTelemetryAgeMs),_t=Ae(I.hubClientDropped),Jt=Ae(I.hubClientQueueDepth),xt=Ae(I.hubClientQueueLimit),Vt=Ae(I.hubClientBufferedBytes),g=_t!==void 0&&Jt!==void 0&&xt!==void 0&&Vt!==void 0,U={deviceId:String(I.deviceId||""),kind:I.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(I.frameSeq||0),streamFrameSeq:Number(I.streamFrameSeq||0)||void 0,streamId:String(I.streamId||""),commandId:I.commandId?String(I.commandId):void 0,sessionId:I.sessionId?String(I.sessionId):void 0,captureGeneration:Number(I.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:I.streamPurpose?String(I.streamPurpose):void 0,width:Number(I.width||0),height:Number(I.height||0),sourceWidth:Number(I.sourceWidth||0)||void 0,sourceHeight:Number(I.sourceHeight||0)||void 0,mimeType:String(I.mimeType||"image/jpeg"),mode:I.mode?String(I.mode):void 0,frameMode:I.frameMode?String(I.frameMode):void 0,frameProfile:I.frameProfile?String(I.frameProfile):void 0,encoding:I.encoding?String(I.encoding):void 0,codec:I.codec?String(I.codec):void 0,compression:I.compression?String(I.compression):void 0,pixelFormat:I.pixelFormat?String(I.pixelFormat):void 0,bytesPerPixel:Number(I.bytesPerPixel||0)||0,uncompressedByteLength:Number(I.uncompressedByteLength||0)||0,h264Format:I.h264Format?String(I.h264Format):void 0,isKeyFrame:I.isKeyFrame===!0,chunkType:I.chunkType?String(I.chunkType):void 0,timestampUs:Number(I.timestampUs||0)||0,durationUs:Number(I.durationUs||0)||0,sourceGapMs:Number(I.sourceGapMs||0)||0,agentSendGapMs:Number(I.agentSendGapMs||0)||0,agentSendDurationMs:Number(I.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(I.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(I.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(I.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(I.agentFrameAgeMs||0)||0,inputFeedbackEventId:I.inputFeedbackEventId?String(I.inputFeedbackEventId):void 0,inputFeedbackInputSeq:Ae(I.inputFeedbackInputSeq),inputFeedbackInputType:I.inputFeedbackInputType?String(I.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:Ae(I.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:Ae(I.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:Ae(I.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:Ae(I.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:Ae(I.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:Ae(I.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:Ae(I.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof I.inputFeedbackCaptureTimestampAvailable=="boolean"?I.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof I.nativeCaptureTelemetryAvailable=="boolean"?I.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:Ze===void 0?void 0:Math.max(0,Ze),nativeCaptureTelemetryAgeMs:At===void 0?void 0:Math.max(0,At),nativeEncoderHardwareAccelerationKnown:typeof I.nativeEncoderHardwareAccelerationKnown=="boolean"?I.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof I.nativeEncoderHardwareAccelerated=="boolean"?I.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:I.nativeEncoderHardwareQueryStatus?String(I.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:Ae(I.nativeCaptureDisplayId),nativeCaptureFps:Ae(I.nativeCaptureFps),nativeCompressionFps:Ae(I.nativeCompressionFps),nativeEncodedFps:Ae(I.nativeEncodedFps),nativeCaptureSampleCount:Ae(I.nativeCaptureSampleCount),nativeEncodableFrameCount:Ae(I.nativeEncodableFrameCount),nativeSkippedFrameCount:Ae(I.nativeSkippedFrameCount),nativeCompressionOutputCount:Ae(I.nativeCompressionOutputCount),nativeEncodedFrameCount:Ae(I.nativeEncodedFrameCount),nativeEncodeFramesInFlight:Ae(I.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:Ae(I.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:Ae(I.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:Ae(I.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:Ae(I.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:Ae(I.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:Ae(I.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:Ae(I.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:Ae(I.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:Ae(I.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:Ae(I.nativeOutputQueueDepth),nativeOutputQueueBytes:Ae(I.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:Ae(I.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:Ae(I.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:Ae(I.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof I.nativeOutputQueueAwaitingKeyFrame=="boolean"?I.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof I.nativeCopyTelemetryAvailable=="boolean"?I.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:Ae(I.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:Ae(I.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:Ae(I.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:Ae(I.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:Ae(I.pipePayloadAllocationCount),pipePayloadCopyCount:Ae(I.pipePayloadCopyCount),pipePayloadCopiedBytes:Ae(I.pipePayloadCopiedBytes),handoffDroppedFrameCount:Ae(I.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:Ae(I.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:Ae(I.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:I.nativeCaptureResourceTelemetryAvailable===!0?cC(I):I.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:I.nativeCaptureTelemetryAt?String(I.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(I.droppedByAgent||0)||0,hubIngressDropped:Number(I.hubIngressDropped||0)||0,hubClientDropped:_t,transport:I.transport?String(I.transport):void 0,videoTransport:I.videoTransport?String(I.videoTransport):void 0,frameTransportActive:I.frameTransportActive?String(I.frameTransportActive):void 0,frameTransportProtocol:I.frameTransportProtocol?String(I.frameTransportProtocol):void 0,frameTransportState:I.frameTransportState?String(I.frameTransportState):void 0,frameTransportReason:I.frameTransportReason?String(I.frameTransportReason):void 0,frameTransportChangedAt:I.frameTransportChangedAt?String(I.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(I.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(I.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:I.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:g,hubClientQueueDepth:Jt,hubClientQueueLimit:xt,hubClientBufferedBytes:Vt,udpIncompleteFrames:Number(I.udpIncompleteFrames||0)||0,hardwareEncoder:I.hardwareEncoder?String(I.hardwareEncoder):void 0,platformProfile:I.platformProfile?String(I.platformProfile):void 0,monitorIndex:Number.isFinite(Number(I.monitorIndex))?Number(I.monitorIndex):void 0,monitorCount:Number.isFinite(Number(I.monitorCount))?Number(I.monitorCount):void 0,requestedFps:Number(I.requestedFps||0)||0,effectiveFps:Number(I.effectiveFps||0)||0,captureTimingAvailable:I.captureTimingAvailable===!0,captureAverageMs:Ae(I.captureAverageMs),captureP95Ms:Ae(I.captureP95Ms),slowFrameCount:Number(I.slowFrameCount||0)||0,captureHelperRestarts:Number(I.captureHelperRestarts||0)||0,capturedAt:String(I.capturedAt||""),receivedAt:String(I.receivedAt||""),hubPacketAt:I.hubPacketAt?String(I.hubPacketAt):void 0,hubPacketEpochMs:Pe,browserReceivedEpochMs:ye,hubPacketTransitAgeMs:Pe!==void 0?He:void 0,byteLength:Number(I.byteLength||vt.byteLength),contentHash:I.contentHash?String(I.contentHash):void 0,captureMs:Ae(I.captureMs),captureStageMs:Ae(I.captureStageMs),convertMs:Number(I.convertMs||0)||0,compressMs:Number(I.compressMs||0)||0,captureSourceSerial:Number(I.captureSourceSerial||0)||0,captureSourceSkipped:Number(I.captureSourceSkipped||0)||0,deltaTileSize:Number(I.deltaTileSize||0)||0,deltaTileCount:Number(I.deltaTileCount||0)||0,deltaVisualTileCount:Number(I.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(I.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(I.deltaTotalTiles||0)||0,payload:vt};if(!U.deviceId)return;const F=$.expectedBinding;if(!F)return;const he=U.deviceId===F.deviceId&&String(U.sessionId||"")===F.sessionId&&U.streamId===F.streamId&&String(U.commandId||"")===F.commandId&&Number(U.captureGeneration||0)===F.captureGeneration&&Number(U.monitorIndex??-1)===F.monitorIndex&&String(U.streamPurpose||"")===F.streamPurpose;if(!he)return;U.currentGenerationVerified=he;const Q=Number($.payload.monitorSelections?.[U.deviceId]);if(Number.isFinite(Q)&&Number.isFinite(Number(U.monitorIndex))&&Number(U.monitorIndex)!==Q)return;const Ie={streamId:$.lastFrameStreamId,commandId:$.lastFrameCommandId,order:$.lastFrameOrder},be=Number(U.streamFrameSeq||U.frameSeq||0),Ye=!!Ie.commandId&&!!U.commandId,ut=Ie.streamId===U.streamId&&(!Ye||Ie.commandId===U.commandId),xe=Ie.order;if(ut&&xe>=be&&(xe===be||Ye))return;$.lastFrameStreamId=U.streamId,$.lastFrameCommandId=U.commandId||"",$.lastFrameOrder=be;const Qe=ee.current;Qe.totalFrames+=1,Qe.totalBytes+=vt.byteLength,Qe.sampleFrames+=1,Qe.sampleBytes+=vt.byteLength;const _e=!A.current.has(U.deviceId)&&!x.current.has(U.deviceId),Wt=aS(x.current,U);_e&&(A.current.set(U.deviceId,Wt),x.current.delete(U.deviceId),p($.workspaceOwnerKey,new Map(A.current))),pe.current?.(U)},[p]);s.useEffect(()=>{if(!t||!L)return;ee.current.sampleStartedAt=performance.now();const ae=window.setInterval(()=>{if(!K.current||P.current!==c)return;kt();const $=performance.now(),ye=ee.current,V=Math.max(1,$-ye.sampleStartedAt);T({totalFrames:ye.totalFrames,totalBytes:ye.totalBytes,framesPerSecond:ye.sampleFrames*1e3/V,bytesPerSecond:ye.sampleBytes*1e3/V,sampleMs:V,lastUpdatedAt:Date.now()}),p(c,oS(A.current,x.current)),ye.sampleFrames=0,ye.sampleBytes=0,ye.sampleStartedAt=$},tC);return ie.current=ae,()=>{window.clearInterval(ae),ie.current===ae&&(ie.current=null)}},[t,L,p,kt,c]),s.useEffect(()=>{const ae=()=>{const $=new Set,ye=[...E.current.values()];for(;ye.length>0;){const I=ye.pop();!I||$.has(I)||($.add(I),I.handoffFrom&&ye.push(I.handoffFrom))}const V=[...A.current.values(),...x.current.values()],Ke=[...$],St=B.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:L,active:K.current,socketCount:Ke.length+St.closingSocketCount,openSocketCount:Ke.filter(I=>I.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:Ke.filter(I=>I.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:St.closingSocketCount,closingSocketTimerCount:St.closingSocketTimerCount,closingSocketTimeoutCount:St.closingSocketTimeoutCount,expectedBindingCount:Ke.filter(I=>!!I.expectedBinding).length,reconnectTimerCount:O.current.size,statsTimerCount:ie.current===null?0:1,configurationRefreshTimerCount:J.current.size,handoffDeadlineTimerCount:Ke.filter(I=>I.handoffDeadlineTimer!==void 0).length,restartTokenCount:ne.current.size,retainedFrameCount:V.length,retainedPayloadBytes:V.reduce((I,oe)=>I+Math.max(0,Number(oe.payload?.byteLength||0)),0)}};return Nd.add(ae),()=>{Nd.delete(ae)}},[L]),s.useEffect(()=>{const ae=L?L.split(",").filter(Boolean):[];if(!_){Be(t?"livedesk-no-devices":"livedesk-stream-inactive");return}const $=new Set(ae),ye=performance.now();for(const V of O.current.keys())$.has(V)||je(V);for(const V of J.current.keys())$.has(V)||Te(V);for(const[V,Ke]of E.current.entries())$.has(V)||(je(V),Me(Ke,"livedesk-device-unsubscribed"),E.current.delete(V),G.current.delete(V),ne.current.delete(V),A.current.delete(V),x.current.delete(V));ee.current.sampleStartedAt<=0&&(ee.current.sampleStartedAt=ye,T({...ks,lastUpdatedAt:Date.now()}));for(const V of ae){je(V);const Ke=Number(r.monitorSelections?.[V]),St=Number.isInteger(Ke)&&Ke>=0?Ke:0,I={[V]:St},oe={type:"subscribe",deviceIds:[V],autoStartLive:t,fps:N,maxWidth:te,maxHeight:we,quality:me,mode:H,frameMode:H,streamPurpose:R,allowReadOnlyControlBorrow:Se,monitorSelections:I},Pe=String(r.connectionSessionIds?.[V]||"").trim(),He=G.current.get(V)||0,vt=JSON.stringify({subscribePayload:oe,connectionSessionId:Pe}),Ze=E.current.get(V),At=Number(Ze?.payload.monitorSelections?.[V]),_t=Number(I[V]),Jt=!!Ze&&Number.isFinite(At)&&Number.isFinite(_t)&&At!==_t,xt=!!Ze&&Ze?.connectionSessionId!==Pe;if(Ze&&Ze.payloadKey===vt&&Ze.reconnectRevision===He&&Wu(Ze,c))continue;Te(V);const Vt=Ze&&(Ze.socket.readyState===WebSocket.CONNECTING||Ze.socket.readyState===WebSocket.OPEN)&&!Ze.disposed?Ze.handoffFrom&&!Ze.handoffCompleted?Ze.handoffFrom:Ze:void 0,g=Ze&&Ze!==Vt?Ze:void 0,U=`/api/remote/frames/ws?devices=${encodeURIComponent(V)}`,F=xs(Rs(U,a),U,"frame");F.binaryType="arraybuffer";const he=lS();let Q;Q={socket:F,workspaceOwnerKey:c,payload:oe,payloadKey:vt,reconnectRevision:He,connectionSessionId:Pe,restartMayHaveApplied:g?.restartMayHaveApplied===!0,generation:q.current+1,monitorRestartToken:Jt?`monitor-${V}-${_t}-${q.current+1}`:"",disposed:!1,handoffFrom:Vt,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:he,releaseOwnedState:()=>{Q.handoffDeadlineTimer!==void 0&&(window.clearTimeout(Q.handoffDeadlineTimer),Q.handoffDeadlineTimer=void 0),Cf(he)}},q.current=Q.generation,(Jt||xt)&&(A.current.delete(V),x.current.delete(V),p(c,new Map(A.current))),E.current.set(V,Q),g&&(g.handoffFrom=void 0,$u(g,V,ne.current),Me(g,"livedesk-subscription-superseded"));const Ie=()=>{Q.handoffDeadlineTimer!==void 0&&(window.clearTimeout(Q.handoffDeadlineTimer),Q.handoffDeadlineTimer=void 0)},be=()=>{Ie();const _e=Vu(Q);Q.handoffCompleted=!0,Q.sentForceRestartToken=void 0,_e&&!_e.disposed&&Me(_e,"livedesk-subscription-replaced")},Ye=()=>{if(!K.current||Q.workspaceOwnerKey!==P.current||Q.disposed||E.current.get(V)!==Q){Me(Q,"livedesk-stale-frame-socket");return}je(V),M("");const _e=re.current,Wt=_e.enabled&&(!_e.token||ne.current.get(V)!==_e.token),lt=Wt||Q.monitorRestartToken!=="",ct=Wt?_e.token:Q.monitorRestartToken,ht=Wt?_e.reason:Q.monitorRestartToken?"monitor-selection-change":"";if(F.send(JSON.stringify({...Q.payload,forceRestart:lt,restartReason:lt?ht:"",restartToken:lt?ct:""})),lt&&(Q.restartMayHaveApplied=!0),Fe>0){const rt=window.setTimeout(()=>{J.current.get(V)===rt&&J.current.delete(V),!(!K.current||Q.workspaceOwnerKey!==P.current)&&st(V,Q)},Math.max(1e3,Fe));J.current.set(V,rt)}if(Wt&&_e.token&&(Q.sentForceRestartToken=_e.token,ne.current.set(V,_e.token)),Q.handoffFrom){const rt=window.setTimeout(()=>{if(Q.handoffDeadlineTimer!==rt||Q.disposed||E.current.get(V)!==Q||!Q.handoffFrom)return;Ie();const Pt=Vu(Q),zt=sf(Q,Pt,c);Te(V),$u(Q,V,ne.current),zt?E.current.set(V,Pt):(E.current.delete(V),Pt&&Me(Pt,"livedesk-handoff-owner-changed"),A.current.delete(V),x.current.delete(V),p(c,new Map(A.current)),Ge(V,c)),Me(Q,"livedesk-handoff-timeout"),Y()},5e3);Q.handoffDeadlineTimer=rt}else Q.handoffCompleted=!0;Y()},ut=_e=>{if(!K.current||Q.workspaceOwnerKey!==P.current||Q.disposed||E.current.get(V)!==Q)return;if(typeof _e.data=="string"){try{const lt=JSON.parse(_e.data),ct=(ht,rt=!0)=>{const Pt=Q.payload.streamPurpose==="control"?"control":"wall",zt=lC(ht,V,Pt),xi=Number(Q.payload.monitorSelections?.[V]);return!zt||!jy(zt,{deviceId:V,connectionSessionId:Q.connectionSessionId,monitorIndex:xi,streamPurpose:Pt,allowReadOnlyControlBorrow:Q.payload.allowReadOnlyControlBorrow===!0})?!1:(Q.expectedBinding=zt,ce.current?.(zt),rt&&W.current?.(zt),!0)};if(lt?.type==="RemoteFrameSubscriptionError"){const ht=String(lt.error||"control-stream-start-failed");cf(ht,lt.retryScheduled===!0)?(M(""),Y()):M(ht)}else if(lt?.type==="RemoteFrameLiveAutoStart"){const rt=(Array.isArray(lt.skipped)?lt.skipped:[]).find(Pt=>Pt?.deviceId===V);if(rt)cf(rt.reason,rt.retryScheduled===!0)?(M(""),Y()):M(String(rt.reason||"control-stream-start-failed"));else if(Array.isArray(lt.started)){const Pt=lt.started.find(zt=>zt?.deviceId===V);Pt&&(M(""),ct(Pt,Pt.ready===!0)&&be())}}else lt?.type==="RemoteFrameStreamReady"&<.deviceId===V&&ct(lt)&&(M(""),be())}catch{}return}const Wt=_e.data instanceof ArrayBuffer?_e.data:null;Wt&&(M(""),it(Wt,Q))},xe=()=>{!K.current||Q.workspaceOwnerKey!==P.current||Q.disposed||E.current.get(V)!==Q||f("connecting")},Qe=()=>{Ie();const _e=!Q.disposed;Q.disposed=!0,Q.handoffCompleted=!0;const Wt=Q.detachListeners;Q.detachListeners=void 0,Wt?.();const lt=E.current.get(V);lt===Q&&Te(V);let ct=!1;if(lt===Q){const ht=Vu(Q);sf(Q,ht,c)?(E.current.set(V,ht),ct=!0):(E.current.delete(V),ht&&(Me(ht,"livedesk-handoff-owner-changed"),A.current.delete(V),x.current.delete(V),p(c,new Map(A.current))))}_e&<===Q&&$u(Q,V,ne.current),Y(),_e&&K.current&&Q.workspaceOwnerKey===P.current&<===Q&&!ct&&(je(V),Ge(V,Q.workspaceOwnerKey))};Q.detachListeners=()=>{F.removeEventListener("open",Ye),F.removeEventListener("message",ut),F.removeEventListener("error",xe),F.removeEventListener("close",Qe)},F.addEventListener("open",Ye),F.addEventListener("message",ut),F.addEventListener("error",xe),F.addEventListener("close",Qe)}Y()},[Se,t,Te,je,Me,Fe,z,L,N,H,it,a,we,te,Oe,r.monitorSelections,p,me,de,Be,Ge,st,R,_,Y,c]),s.useEffect(()=>{if(!_)return;const ae=()=>{document.visibilityState==="visible"&&kt()};return ae(),document.addEventListener("visibilitychange",ae),window.addEventListener("pageshow",ae),window.addEventListener("focus",ae),()=>{document.removeEventListener("visibilitychange",ae),window.removeEventListener("pageshow",ae),window.removeEventListener("focus",ae)}},[kt,_]),s.useEffect(()=>{if(!_||!Ce||!Ve)return;const ae=L?L.split(",").filter(Boolean):[];for(const $ of ae){if(ne.current.get($)===Ve)continue;const ye=E.current.get($);!ye||!ve($,ye,qe,Ve)||(ye.sentForceRestartToken=Ve,ne.current.set($,Ve))}},[L,Ce,Ve,qe,ve,_]),s.useEffect(()=>()=>{Be("livedesk-hook-unmount",!1)},[Be]);const bt=s.useCallback((ae,$="browser-stale")=>{if(!_)return!1;const ye=Array.isArray(ae)&&ae.length>0?ae:L.split(",").filter(Boolean);if(ye.length===0)return!1;let V=!1;for(const Ke of ye){const St=E.current.get(Ke);!St||St.socket.readyState!==WebSocket.OPEN||(V=ve(Ke,St,$,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||V)}return V},[L,ve,_]),Mt=s.useCallback((ae,$="browser-reconnect")=>{if(!_)return!1;const ye=Array.isArray(ae)&&ae.length>0?ae:L.split(",").filter(Boolean);if(ye.length===0)return!1;for(const V of ye){const Ke=E.current.get(V);je(V),Ke&&!Wu(Ke,c)&&(Me(Ke,`livedesk-${$}`),E.current.delete(V)),G.current.set(V,(G.current.get(V)||0)+1),A.current.delete(V),x.current.delete(V)}return p(c,new Map(A.current)),se(V=>V+1),Y(),!0},[je,Me,L,p,_,Y,c]);return{frames:u,state:h,error:k,stats:b,restartLive:bt,reconnectLive:Mt}}function uC(e,t,a=In,r={},c=""){const[u,p]=Xt(c,null),[h,f]=Xt(c,null),[k,M]=Xt(c,"idle"),[b,T]=Xt(c,ks),A=s.useRef(null),x=s.useRef(""),E=s.useRef(c);E.current=c;const B=s.useRef(r.onFrame),q=s.useRef(null),G=s.useRef(0),ne=s.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),re=s.useMemo(()=>[...new Set(e.filter(Boolean))].join(","),[e]),O=s.useMemo(()=>[...new Set((r.captureDeviceIds||e).filter(Boolean))].join(","),[e,r.captureDeviceIds]),ie=s.useMemo(()=>JSON.stringify(r.monitorSelections||{}),[r.monitorSelections]),J=s.useMemo(()=>{const L=Object.entries(r.connectionSessionIds||{}).filter(([_])=>!!_).map(([_,K])=>[_,String(K||"").trim()]).sort(([_],[K])=>_.localeCompare(K));return JSON.stringify(Object.fromEntries(L))},[r.connectionSessionIds]),de=s.useMemo(()=>({deviceIds:re.split(",").filter(Boolean),captureDeviceIds:O.split(",").filter(Boolean),fps:Number(r.fps||20),inputFps:Number(r.inputFps||8),width:Number(r.width||1920),height:Number(r.height||1080),tileWidth:Number(r.tileWidth||320),tileHeight:Number(r.tileHeight||180),monitorSelections:r.monitorSelections||{}}),[O,re,ie,r.fps,r.height,r.inputFps,r.monitorSelections,r.tileHeight,r.tileWidth,r.width]),se=s.useMemo(()=>JSON.stringify({atlasConfiguration:de,connectionSessionKey:J}),[de,J]),pe=s.useRef(de);pe.current=de;const ce=t&&de.deviceIds.length>0,W=s.useCallback(L=>L.readyState!==WebSocket.OPEN?!1:(L.send(JSON.stringify({type:"configure",...pe.current})),!0),[]);s.useEffect(()=>{B.current=r.onFrame},[r.onFrame]),s.useEffect(()=>{if(!ce)return;const L=c;ne.current.sampleStartedAt=performance.now();const _=window.setInterval(()=>{if(E.current!==L)return;const K=ne.current,ue=performance.now(),P=Math.max(1,ue-K.sampleStartedAt);T(L,{totalFrames:K.totalFrames,totalBytes:K.totalBytes,framesPerSecond:K.sampleFrames*1e3/P,bytesPerSecond:K.sampleBytes*1e3/P,sampleMs:P,lastUpdatedAt:Date.now()});const N=q.current;N&&N.frameSeq!==G.current&&(G.current=N.frameSeq,p(L,N)),K.sampleFrames=0,K.sampleBytes=0,K.sampleStartedAt=ue},1e3);return()=>window.clearInterval(_)},[ce,p,T,c]),s.useEffect(()=>{const L=c;if(!ce){A.current?.close(),A.current=null,x.current="",p(L,null),q.current=null,G.current=0,f(L,null),M(L,"idle"),T(L,ks);return}p(L,null),f(L,null),q.current=null,G.current=0,ne.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:performance.now()};let _=!1,K=0;const ue=()=>{if(_||E.current!==L)return;const P=xs(Rs("/api/remote/atlas/ws",a),"/api/remote/atlas/ws","atlas");P.binaryType="arraybuffer",A.current=P,x.current=L,M(L,"connecting"),P.addEventListener("open",()=>{_||A.current!==P||E.current!==L||(ne.current.sampleStartedAt=performance.now(),M(L,"open"),W(P))}),P.addEventListener("message",N=>{if(_||A.current!==P||E.current!==L)return;if(typeof N.data=="string"){try{const we=JSON.parse(N.data);we?.type==="Mode4AtlasLayout"&&f(L,{layoutVersion:Number(we.layoutVersion||0),width:Number(we.width||1920),height:Number(we.height||1080),columns:Number(we.columns||1),rows:Number(we.rows||1),tiles:Array.isArray(we.tiles)?we.tiles:[]})}catch{}return}const te=N.data instanceof ArrayBuffer?N.data:null;if(!(!te||te.byteLength<5))try{const we=Date.now(),Fe=new DataView(te).getUint32(0,!1);if(Fe<=0||Fe+4>te.byteLength)return;const H=JSON.parse(Yd.decode(new Uint8Array(te,4,Fe))),R=new Uint8Array(te,4+Fe),Se=Ae(H.hubClientDropped),Ce=Ae(H.hubClientQueueDepth),Ve=Ae(H.hubClientQueueLimit),qe=Ae(H.hubClientBufferedBytes),Oe={deviceId:String(H.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(H.frameSeq||0),streamFrameSeq:Number(H.streamFrameSeq||0)||void 0,streamId:String(H.streamId||"mode4-atlas"),commandId:H.commandId?String(H.commandId):void 0,width:Number(H.width||1920),height:Number(H.height||1080),sourceWidth:Number(H.sourceWidth||H.width||1920),sourceHeight:Number(H.sourceHeight||H.height||1080),mimeType:String(H.mimeType||"video/h264"),mode:String(H.mode||"mode4-h264-atlas"),frameMode:String(H.frameMode||"mode4-h264-atlas"),frameProfile:String(H.frameProfile||"mode4-h264-atlas-v1"),encoding:String(H.encoding||"video-atlas"),codec:String(H.codec||"h264"),compression:String(H.compression||"video/h264"),h264Format:String(H.h264Format||"annexb"),isKeyFrame:H.isKeyFrame===!0,chunkType:String(H.chunkType||""),timestampUs:Number(H.timestampUs||0),durationUs:Number(H.durationUs||0),transport:H.transport?String(H.transport):void 0,videoTransport:H.videoTransport?String(H.videoTransport):void 0,frameTransportActive:H.frameTransportActive?String(H.frameTransportActive):void 0,frameTransportProtocol:H.frameTransportProtocol?String(H.frameTransportProtocol):void 0,frameTransportState:H.frameTransportState?String(H.frameTransportState):void 0,frameTransportReason:H.frameTransportReason?String(H.frameTransportReason):void 0,frameTransportChangedAt:H.frameTransportChangedAt?String(H.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(H.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(H.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:H.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:Se!==void 0&&Ce!==void 0&&Ve!==void 0&&qe!==void 0,hubClientDropped:Se,hubClientQueueDepth:Ce,hubClientQueueLimit:Ve,hubClientBufferedBytes:qe,udpIncompleteFrames:Number(H.udpIncompleteFrames||0)||0,hardwareEncoder:H.hardwareEncoder?String(H.hardwareEncoder):void 0,platformProfile:H.platformProfile?String(H.platformProfile):void 0,capturedAt:String(H.capturedAt||""),receivedAt:String(H.receivedAt||""),hubPacketAt:H.hubPacketAt?String(H.hubPacketAt):void 0,hubPacketEpochMs:Number(H.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:we,byteLength:R.byteLength,layoutVersion:Number(H.layoutVersion||0),atlasComposeMs:Number(H.atlasComposeMs||0),atlasPoolStarved:Number(H.atlasPoolStarved||0),atlasReadyTiles:Number(H.atlasReadyTiles||0),atlasTileCount:Number(H.atlasTileCount||0),atlasInputRevision:Number(H.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(H.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(H.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(H.atlasSourceMaxAgeMs||0),payload:R},z=ne.current;z.totalFrames+=1,z.totalBytes+=R.byteLength,z.sampleFrames+=1,z.sampleBytes+=R.byteLength,q.current=Oe,G.current===0&&(G.current=Oe.frameSeq,p(L,Oe)),B.current?.(Oe)}catch{}}),P.addEventListener("error",()=>{_||A.current!==P||E.current!==L||M(L,"error")}),P.addEventListener("close",()=>{A.current===P&&(A.current=null),x.current===L&&(x.current=""),!(_||E.current!==L)&&(M(L,"closed"),K=window.setTimeout(ue,1200))})};return ue(),()=>{_=!0,window.clearTimeout(K),x.current===L&&(A.current?.close(),A.current=null,x.current="")}},[ce,a,p,f,M,T,W,c]),s.useEffect(()=>{if(!ce)return;const L=A.current;L&&x.current===c&&W(L)},[se,ce,W,c]);const ee=s.useCallback(()=>{const L=A.current;return L&&x.current===E.current?W(L):!1},[W]);return{frame:u,layout:h,state:k,stats:b,refreshInputs:ee}}function dC(e,t=In,a="",r=""){const c=String(a||"").trim(),u=s.useRef(null),p=s.useRef(null),h=s.useRef(0),f=s.useRef(0),k=s.useRef(c),M=s.useRef(!1),b=s.useRef(new Map),T=s.useRef(""),A=s.useRef(new Map),x=s.useRef(r),E=s.useRef("");x.current=r;const[B,q]=s.useState(r),[G,ne]=s.useState("idle"),[re,O]=s.useState(""),[ie,J]=s.useState(""),[de,se]=s.useState(!1),[pe,ce]=s.useState(td),[W,ee]=s.useState(null),L=s.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});k.current!==c&&(k.current=c,M.current=!1),s.useEffect(()=>{const ue=r;if(E.current=ue,q(ue),!e){u.current?.close(),u.current=null,p.current=null,f.current=0,M.current=!1,T.current="",A.current.clear(),b.current.clear(),ne("idle"),O(""),J(""),se(!1),ce(td),ee(null);return}let P=!1,N=0,te=0,we=0;const me=()=>!P&&E.current===ue&&x.current===ue,Fe=()=>{window.clearTimeout(te),te=0},H=Ce=>{me()&&(we+=1,we>=If&&O(ed(Ce,navigator.language)))},R=Ce=>{me()&&(window.clearTimeout(N),N=window.setTimeout(Ce,jS(we)))},Se=()=>{if(!me())return;let Ce;try{Ce=xs(Rs("/api/remote/input/ws",t),"/api/remote/input/ws","input")}catch{H("remote-input-transport-error"),ne("error"),R(Se);return}let Ve=!1,qe=!1;const Oe=z=>{qe||(qe=!0,H(z))};u.current=Ce,p.current=null,M.current=!1,J(""),se(!1),L.current.sampleStartedAt=performance.now(),ne("connecting"),te=window.setTimeout(()=>{if(!(!me()||u.current!==Ce||Ve)){Oe("remote-input-ready-timeout"),ne("error");try{Ce.close(4e3,"remote-input-ready-timeout")}catch{u.current===Ce&&(u.current=null,R(Se))}}},LS),Ce.addEventListener("open",()=>{!me()||u.current!==Ce||ne("connecting")}),Ce.addEventListener("message",z=>{if(!(!me()||u.current!==Ce||typeof z.data!="string"))try{const Me=JSON.parse(z.data);if(Me?.type==="RemoteInputSocketReady"){const Y=String(Me.clientId||"").trim();if(!Y){Oe("remote-input-ready-timeout"),Ce.close(4e3,"remote-input-ready-missing-owner");return}Ve=!0,we=0,Fe(),p.current=Ce,J(Y),O(""),ne("open");const ve=k.current;if(ve)try{Ce.send(JSON.stringify({type:"watch",deviceId:ve}))}catch{Ce.close(4002,"input-watch-send-failed")}return}if(Me?.type==="RemoteInputRouteState"){const Y=String(Me.deviceId||"").trim();if(!Y||Y!==k.current)return;const ve=Me.ready===!0;M.current=ve,se(ve),ve||ee(null),!ve&&we>=If?O(ed("INPUT_CHANNEL_RECONNECTING",navigator.language)):ve&&O("");return}const je=Number(Me.inputSeq||Me.result?.inputSeq||0),Ge=String(Me.deviceId||Me.result?.deviceId||""),kt=String(Me.inputEventId||Me.result?.inputEventId||""),Te=b.current.get(je);if(Ge&&(Te&&Te.deviceId!==Ge||!Te&&T.current&&T.current!==Ge)||Te?.inputEventId&&kt&&Te.inputEventId!==kt)return;if(Me?.type==="RemoteInputError"){je>0&&b.current.delete(je);const Y=String(Me.error||Me.result?.error||"remote-input-failed"),ve=String(Me.errorKind||Me.result?.errorKind||"").trim().toLowerCase(),st=WS(Y),it=ve==="native-apply";if(st&&(M.current=!1,se(!1)),it){const bt=Ge||k.current,Mt=`${bt}
|
|
174
|
+
${Y}`,ae=performance.now(),$=A.current;for(const[V,Ke]of $)ae-Ke>=Af&&$.delete(V);const ye=$.get(Mt);(ye===void 0||ae-ye>=Af)&&($.set(Mt,ae),console.warn("[VuvoDesk remote input] native apply rejected",{deviceId:bt,inputSeq:je,error:Y}))}O(ed(Y,navigator.language,ve)),p.current===Ce&&ne("open");return}if(Me?.type!=="RemoteInputApplied")return;Te&&(L.current.lastRoundTripMs=Math.max(0,performance.now()-Te.sentAt),b.current.delete(je)),L.current.lastInputSeq=je,L.current.lastAgentApplyMs=Math.max(0,Number(Me.agentApplyMs||0));const Be=String(Me.nativeInputBackend||Me.result?.nativeInputBackend||"").trim();if(Te&&Be&&Te.normalizedX!==null&&Te.normalizedY!==null)if(Be==="win32-window-message"){const Y={deviceId:Te.deviceId,monitorIndex:Te.monitorIndex,normalizedX:Te.normalizedX,normalizedY:Te.normalizedY,inputSeq:je,inputType:Te.inputType,nativeInputBackend:Be,controlSessionId:Te.controlSessionId,controlCommandId:Te.controlCommandId,captureGeneration:Te.captureGeneration};ee(ve=>ve&&ve.deviceId===Y.deviceId&&ve.inputSeq>je?ve:Y)}else ee(null);O(""),ne("open")}catch{}}),Ce.addEventListener("close",z=>{!me()||u.current!==Ce||(Fe(),Ve||Oe(z.reason||"remote-input-socket-closed"),u.current=null,p.current===Ce&&(p.current=null),f.current=0,M.current=!1,T.current="",A.current.clear(),b.current.clear(),J(""),se(!1),ee(null),ne("closed"),R(Se))}),Ce.addEventListener("error",()=>{me()&&u.current===Ce&&ne("error")})};return Se(),()=>{P=!0,window.clearTimeout(N),Fe();const Ce=u.current;u.current=null,p.current=null,f.current=0,M.current=!1,A.current.clear(),J(""),se(!1),ee(null),Ce?.close(),b.current.clear(),E.current===ue&&(E.current="")}},[e,t,r]),s.useEffect(()=>{if(E.current!==x.current||(M.current=!1,se(!1),ee(null),!e||!c))return;const ue=p.current;if(!(!ue||ue.readyState!==WebSocket.OPEN))try{ue.send(JSON.stringify({type:"watch",deviceId:c}))}catch{ue.close(4002,"input-watch-send-failed")}},[e,c,r]),s.useEffect(()=>{if(!e)return;const ue=window.setInterval(()=>{if(E.current!==x.current)return;const P=performance.now(),N=L.current,te=Math.max(1,P-N.sampleStartedAt);ce({totalSent:N.totalSent,totalDropped:N.totalDropped,sentPerSecond:N.sampleSent*1e3/te,droppedPerSecond:N.sampleDropped*1e3/te,bufferedAmount:u.current?.bufferedAmount||0,lastInputType:N.lastInputType,lastInputSeq:N.lastInputSeq,lastRoundTripMs:N.lastRoundTripMs,lastAgentApplyMs:N.lastAgentApplyMs,lastUpdatedAt:Date.now()}),N.sampleSent=0,N.sampleDropped=0,N.sampleStartedAt=P},1e3);return()=>window.clearInterval(ue)},[e,r]);const _=s.useCallback((ue,P)=>{const N=u.current;if(!N||E.current!==x.current||p.current!==N||N.readyState!==WebSocket.OPEN||M.current!==!0||k.current!==ue||!ue)return!1;const te=String(P.type||"").toLowerCase(),Fe=te==="pointermove"||te==="wheel",H=L.current,R=performance.now();if(Fe&&N.bufferedAmount>nC)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${te}-coalescible-drop`,!1;if(!Fe&&N.bufferedAmount>rC){H.lastInputType=`${te||"input"}-fail-closed`,O("Remote input channel was reset because ordered input could not drain.");try{N.close(4001,"ordered-input-backpressure")}catch{}return!1}const Se=h.current+1;h.current=Se;const Ce=`${Se}-${crypto.randomUUID()}`,Ve=Date.now(),qe=Number(P.normalizedX),Oe=Number(P.normalizedY),z=Number.isFinite(qe)?Math.max(0,Math.min(1,qe)):null,Me=Number.isFinite(Oe)?Math.max(0,Math.min(1,Oe)):null,je=!Fe||Se-f.current>=aC;for(je&&b.current.set(Se,{sentAt:R,deviceId:ue,inputEventId:Ce,inputType:te,monitorIndex:Math.max(0,Math.trunc(Number(P.monitorIndex)||0)),normalizedX:z,normalizedY:Me,controlSessionId:String(P.controlSessionId||""),controlCommandId:String(P.controlCommandId||""),captureGeneration:Math.max(0,Math.trunc(Number(P.captureGeneration)||0))}),T.current=ue,Hg.set(ue,{inputSeq:Se,inputType:te||"input",sentAt:performance.now()});b.current.size>256;){const Ge=b.current.keys().next().value;if(Ge===void 0)break;b.current.delete(Ge)}try{N.send(JSON.stringify({type:"input",requestId:Fe?"":crypto.randomUUID(),fireAndForget:Fe,deviceId:ue,input:{...P,inputEventId:Ce,inputSeq:Se,requestAck:je,issuedAtEpochMs:Ve,issuedAt:new Date(Ve).toISOString()}}))}catch{b.current.delete(Se),O("Remote input channel closed before the ordered input was queued.");try{N.close(4002,"input-send-failed")}catch{}return!1}return Fe&&je&&(f.current=Se),H.totalSent+=1,H.sampleSent+=1,H.lastInputType=te||"input",!0},[]),K=B===r;return{state:K?G:"idle",connectionId:K?ie:"",routeReady:K?de:!1,sendInput:_,stats:K?pe:td,error:K?re:"",remotePointerFeedback:K?W:null}}const go={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},mC=.25,Nf=300,Ff=2,rl=1500,nd=5e3,pC=2e3,Df=1e4,ms=[0,1e3,3e3];function Lf(e){const t=Date.parse(String(e||""));return Number.isFinite(t)?Math.max(0,Date.now()-t):0}function fC(e,t,a=In,r=0,c=!1,u="",p,h,f=""){const k=s.useRef(null),M=s.useRef(""),b=s.useRef(f);b.current=f;const[T,A]=s.useState(f),[x,E]=s.useState("idle"),[B,q]=s.useState(null),[G,ne]=s.useState(go),[re,O]=s.useState(""),ie=s.useRef(c);ie.current=c,s.useLayoutEffect(()=>{const de=f;return()=>{const se=k.current;!se||M.current!==de||(k.current=null,M.current="",se.close().catch(()=>{}))}},[f]),s.useEffect(()=>{c||(q(de=>de===null?de:null),ne(de=>de===go?de:go))},[c]),s.useEffect(()=>{const de=f;if(A(de),!t||!e){E("idle"),q(null),ne(go),O("");return}E("connecting"),q(null),ne(go),O("");const se=window.AudioContext||window.webkitAudioContext;if(!se){E("unsupported"),ne(go),O("Audio playback is not supported in this browser.");return}let pe=!1;const ce=()=>!pe&&b.current===de;let W=null;const ee=wS.acquire(({release:L})=>{if(!ce()){L();return}const _=new se({latencyHint:"interactive"});k.current=_,M.current=de;let K=String(u||"").trim();const ue="/api/remote/audio/ws?devices="+encodeURIComponent(e)+(K?"&streamId="+encodeURIComponent(K):"");let P=xs(Rs(ue,a),ue,"audio");P.binaryType="arraybuffer";const N=Ot.createOwner({deviceId:e,socket:P,audioContext:_,statsTimer:null});let te=!1;const we=()=>{const F=Ot.releaseIfDrained(N);return(F||!Ot.hasOwner(N))&&!te&&(te=!0,L()),F},me=Kd({sampleRate:192e3,channels:8}).capacityBytes,Fe=IS({maxPendingPackets:Pd,maxPendingBytes:me}),H=pS(),R={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(_.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let Se=!1,Ce=!1,Ve=null,qe=0,Oe=0,z="",Me=!1,je=()=>{},Ge="connecting",kt="",Te=()=>{};const Be=F=>{Se||!ce()||F===Ge||(Ge=F,E(F))},Y=F=>{Se||!ce()||F===kt||(kt=F,O(F))},ve=vS({schedule:(F,he)=>window.setTimeout(F,he),cancel:F=>window.clearTimeout(F),onTimerChange:F=>{Ot.setReconnectTimer(N,F),we()},onReconnect:()=>{try{const F=xs(Rs(ue,a),ue,"audio");if(F.binaryType="arraybuffer",!ve.replaceSocket(F)){F.close();return}P=F,Ot.setSocket(N,F),Be("connecting"),Te(F)}catch(F){throw Be("error"),Y(F instanceof Error?`Remote audio reconnect failed: ${F.message}`:"Remote audio reconnect failed."),F}}});ve.replaceSocket(P);let st=0,it=!1,bt=0,Mt=0,ae=0,$=!1;const ye=()=>{Ot.setPendingWorkletPackets(N,Fe.getPendingPacketCount(),Fe.getPendingPacketBytes(),Fe.getPendingPacketHighWater(),Fe.getPendingByteHighWater())},V=F=>{R.workletRingCapacityBytes=Math.max(0,Math.min(me,Number(F.ringCapacityBytes||0)||0)),R.workletRingBufferedBytes=Math.max(0,Math.min(R.workletRingCapacityBytes,Number(F.ringBufferedBytes||0)||0)),R.workletRingBufferedMs=Math.max(0,Math.min(mC*1e3,Number(F.ringBufferedMs||0)||0)),R.workletRingDroppedFrames=Math.max(R.workletRingDroppedFrames,Number(F.ringDroppedFrames||0)||0),R.workletRingUnderflowCount=Math.max(R.workletRingUnderflowCount,Number(F.ringUnderflowCount||0)||0),Ot.setPcmRing(N,R.workletRingCapacityBytes,R.workletRingBufferedBytes)},Ke=()=>{const F=Ve;if(Ve=null,Me=!1,F){F.onprocessorerror=null,F.port.onmessage=null;try{F.disconnect()}catch{}try{F.port.close()}catch{}}Fe.terminate(),ye(),R.workletRingCapacityBytes=0,R.workletRingBufferedBytes=0,R.workletRingBufferedMs=0,Ot.setPcmRing(N,0,0),Ot.setWorkletNode(N,0,0,qe),we()},St=F=>{const he=F.data||{},Q=String(he.type||"");if((Q==="packet-terminal"||Q==="processor-error")&&(Fe.acknowledge(typeof he.packetId=="number"?he.packetId:String(he.packetId||"")),ye()),Q==="packet-terminal"){const Ie=Math.max(0,Number(he.droppedFrames||0)||0);Ie>0&&(R.workletRingDroppedFrames+=Ie,R.resyncs+=1)}if(Q==="ring-configured"||Q==="ring-state"||Q==="disposed"){const Ie=R.workletRingDroppedFrames;V(he),R.workletRingDroppedFrames>Ie&&(R.resyncs+=1)}Q==="disposed"?Ke():Q==="processor-error"&&je(String(he.error||"Remote audio worklet processing failed."))},I=()=>{if(!(!Ve||!Me))try{Ve.port.postMessage({type:"flush"})}catch{je("Remote audio worklet could not be flushed.")}},oe=()=>{P.readyState===WebSocket.OPEN&&P.send(JSON.stringify({type:"subscribe",deviceIds:[e],streamIdsByDeviceId:K?{[e]:K}:{}}))},Pe=()=>{R.audioContextState=String(_.state),!Se&&(R.audioContextState==="suspended"||R.audioContextState==="interrupted"?Be("suspended"):R.audioContextState==="closed"&&(Be("error"),Y("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},He=async()=>{if(Se||String(_.state)==="closed")return!1;try{if(String(_.state)!=="running"&&await _.resume(),R.audioContextState=String(_.state),!Se&&!it&&R.audioContextState==="running"){const F=R.lastAcceptedAt>0&&performance.now()-R.lastAcceptedAt<=rl,he=R.lastCaptureStatusAt>0&&performance.now()-R.lastCaptureStatusAt<=nd&&R.captureHealthy;Be(F?"playing":he?"silent":"open")}return R.audioContextState==="running"}catch(F){return Se||(Be("suspended"),Y(F instanceof Error?"Audio playback is suspended: "+F.message:"Audio playback is suspended.")),!1}},vt=async()=>{if(!_.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const F=new Blob([FS],{type:"text/javascript"});z=URL.createObjectURL(F);try{await _.audioWorklet.addModule(z)}finally{URL.revokeObjectURL(z),z=""}if(Se||String(_.state)==="closed")return;const he=new AudioWorkletNode(_,jg,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[Ff],channelCount:Ff,channelCountMode:"explicit"});qe+=1,Ve=he,he.port.onmessage=St,he.onprocessorerror=()=>{je("Remote audio worklet stopped unexpectedly.")},he.connect(_.destination),Me=!0,Ot.setWorkletNode(N,1,1,qe)},Ze=(F,he,Q,Ie)=>{const be=Ve;if(Se||!Me||!be||he.byteLength<=0)return!1;const Ye=Gd({sampleRate:F.sampleRate,channels:F.channels,mimeType:F.mimeType}),ut=++Oe;if(!Fe.claim(ut,he.byteLength))return ye(),!1;ye();try{return be.port.postMessage({type:"pcm",packetId:ut,buffer:he,byteOffset:Q,byteLength:Ie,sampleRate:Ye.sampleRate,channels:Ye.channels,mimeType:F.mimeType,sampleFormat:Ye.sampleFormat},[he]),!0}catch{return Fe.acknowledge(ut),ye(),!1}},At=async()=>{if(Se||it||P.readyState!==WebSocket.OPEN)return;if(bt>=ms.length){Be("error"),Y("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const F=bt;bt+=1,it=!0,R.stalledCount+=1,R.automaticRestarts+=1,Be("reconnecting");try{if(!p)throw new Error("Remote audio restart owner is unavailable.");const he=await p(e);if(Se||!he)return;K=he,oe();const Q=performance.now();st=Q,R.lastPacketAt=Q,R.lastAcceptedAt=0,R.lastCaptureStatusAt=0,R.lastPcmAtEpochMs=0,R.captureAlive=null,R.helperAlive=null,R.helperReady=!1,R.captureHealthy=!1,R.captureStatusFailed=!1,R.captureAwaitingCurrentPcm=!1,R.captureAwaitingSinceAt=0,R.capturePhase="",R.backendKind="",R.helperRequired=!1,R.helperPid=0,R.nativeCallbackDiagnosticsAvailable=!1,R.nativeRejectedCallbackCount=0,R.nativeCurrentnessDropCount=0,R.nativeLastDropReason="",R.silentForMs=0,R.activeStreamId=K,R.lastFrameSeq=0,R.maximumAcceptedGapMs=0,I(),Mt=Q+(ms[F+1]??3e3),Y(""),Se||Be("open")}catch(he){Se||(Mt=performance.now()+(ms[F+1]??3e3),Be("error"),Y(he instanceof Error?"Remote audio restart failed: "+he.message:"Remote audio restart failed."))}finally{it=!1}},_t=()=>{R.drops+=1},Jt=window.setInterval(()=>{if(Se||!ce())return;const F=performance.now(),he=R.lastPacketAt>0?Math.max(0,F-R.lastPacketAt):st>0?Math.max(0,F-st):0,Q=R.lastAcceptedAt>0?Math.max(0,F-R.lastAcceptedAt):0,Ie=R.lastCaptureStatusAt>0?Math.max(0,F-R.lastCaptureStatusAt):0,be=P.readyState===WebSocket.OPEN,Ye=R.lastCaptureStatusAt>0,ut=Ye&&Ie<=nd&&R.captureHealthy,xe=Ye&&R.captureStatusFailed&&Ie>pC,Qe=Ye&&Ie>nd,_e=!Ye&&st>0&&F-st>Df,Wt=R.captureAwaitingCurrentPcm&&R.captureAwaitingSinceAt>0&&F-R.captureAwaitingSinceAt>Df,lt=st>0&&(R.lastAcceptedAt<=0?F-st>rl:Q>rl);if(be&&st>0&&(xe||Qe||_e||Wt)?bt>=ms.length&&!it?(Be("error"),Y("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!it&&F>=Mt?At():it||Be("stalled"):be&<&&!it&&R.audioContextState!=="suspended"&&R.audioContextState!=="interrupted"&&Be(ut?"silent":"open"),SS({enabled:ie.current,now:F,lastPublishedAt:ae})){ae=F,ne({queuedMs:R.workletRingBufferedMs,browserAgeMs:R.browserAgeMs,captureAgeMs:R.captureAgeMs,captureStatusAgeMs:Ie,silentForMs:R.silentForMs,captureAlive:R.captureAlive,helperAlive:R.helperAlive,helperReady:R.helperReady,captureHealthy:R.captureHealthy,captureAwaitingCurrentPcm:R.captureAwaitingCurrentPcm,capturePhase:R.capturePhase,backendKind:R.backendKind,helperRequired:R.helperRequired,helperPid:R.helperPid,captureRestartCount:R.captureRestartCount,nativeCallbackDiagnosticsAvailable:R.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:R.nativeRejectedCallbackCount,nativeCurrentnessDropCount:R.nativeCurrentnessDropCount,nativeLastDropReason:R.nativeLastDropReason,localProcessingAgeMs:R.localProcessingAgeMs,lastPacketAgeMs:he,lastAcceptedAgeMs:Q,framesReceived:R.framesReceived,drops:R.drops,resyncs:R.resyncs,pendingDecodes:R.pendingDecodes,lastFrameSeq:R.lastFrameSeq,audioContextState:R.audioContextState,stalledCount:R.stalledCount,automaticRestarts:R.automaticRestarts,maximumAcceptedGapMs:R.maximumAcceptedGapMs,workletRingCapacityBytes:R.workletRingCapacityBytes,workletRingBufferedBytes:R.workletRingBufferedBytes,workletRingDroppedFrames:R.workletRingDroppedFrames,workletRingUnderflowCount:R.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const ct=H.publish();ct&&($=!0,Ot.setRetainedFrame(N,1,ct.payload.byteLength),q(ct))}else!ie.current&&$&&($=!1,H.clear(),Ot.setRetainedFrame(N,0,0))},250);Ot.setStatsTimer(N,Jt);const xt=()=>{Pe(),(String(_.state)==="suspended"||String(_.state)==="interrupted")&&He()},Vt=()=>{document.visibilityState==="visible"&&He()},g=()=>{He()};_.addEventListener("statechange",xt),document.addEventListener("visibilitychange",Vt),window.addEventListener("pageshow",g),window.addEventListener("pointerdown",g),window.addEventListener("keydown",g),Be("connecting"),Y(""),Pe();const U=(F,he,Q,Ie,be)=>{if(R.localProcessingAgeMs=Math.max(0,performance.now()-be),Se||!ce()||R.localProcessingAgeMs>Nf||!Ed(F,{deviceId:e,streamId:K}))return _t(),!1;R.activeStreamId!==K&&(R.activeStreamId=K,R.lastFrameSeq=0,R.maximumAcceptedGapMs=0,I());const Ye=xS(F,{deviceId:e,streamId:K,lastFrameSeq:R.lastFrameSeq});if(!Ye.accepted||!Ze(F,he,Q,Ie))return _t(),!1;R.browserAgeMs=Lf(F.receivedAt),R.captureAgeMs=Lf(F.capturedAt);const ut=performance.now();R.lastAcceptedAt>0&&(R.maximumAcceptedGapMs=Math.max(R.maximumAcceptedGapMs,ut-R.lastAcceptedAt)),R.lastAcceptedAt=ut,R.framesReceived+=1,R.lastFrameSeq=Ye.nextFrameSeq,bt=0,Mt=0,ie.current&&(H.accept(F),$=!0,Ot.setRetainedFrame(N,1,0)),String(_.state)!=="running"&&He();const xe=String(_.state)==="running";return xe&&Y(""),Be(xe?"playing":"suspended"),!0};je=(F="")=>{if(!Ce){if(Ce=!0,F&&(Ot.recordTerminalFailure(N,F,F.includes("setup failed")?"setup":"processor"),Be(F.includes("AudioWorklet is unavailable")?"unsupported":"error"),Y(F),h?.(e,K,"browser-audio-playback-failed").catch(()=>{})),Se=!0,ve.stop(),Ot.deactivate(N),window.clearInterval(Jt),Ot.setStatsTimer(N,null),_.removeEventListener("statechange",xt),document.removeEventListener("visibilitychange",Vt),window.removeEventListener("pageshow",g),window.removeEventListener("pointerdown",g),window.removeEventListener("keydown",g),H.clear(),Ot.setRetainedFrame(N,0,0),Ve)try{Ve.port.postMessage({type:"dispose"})}catch{}try{P.close()}catch{}P.readyState===WebSocket.CLOSED&&xf({reconnectOwner:ve,lifecycleLedger:Ot,lifecycleOwner:N,socket:P}),_.close().catch(()=>{}).finally(()=>{Ke(),String(_.state)==="closed"&&Ot.setAudioContext(N,null),we()}),k.current===_&&(k.current=null,M.current=""),we()}},vt().catch(F=>{je(F instanceof Error?`Remote audio worklet setup failed: ${F.message}`:"Remote audio worklet setup failed.")}),Te=F=>{let he=!1;F.addEventListener("open",()=>{he||Se||!ce()||!ve.isCurrent(F)||(oe(),st=performance.now(),R.lastPacketAt=st,R.lastAcceptedAt=0,R.lastCaptureStatusAt=0,R.lastPcmAtEpochMs=0,R.captureAlive=null,R.helperAlive=null,R.helperReady=!1,R.captureHealthy=!1,R.captureStatusFailed=!1,R.captureAwaitingCurrentPcm=!1,R.captureAwaitingSinceAt=0,R.capturePhase="",R.backendKind="",R.helperRequired=!1,R.helperPid=0,R.maximumAcceptedGapMs=0,R.silentForMs=0,Be("open"),Y(""),He())}),F.addEventListener("message",Q=>{if(he||Se||!ce()||!ve.isCurrent(F)||typeof Q.data=="string")return;const Ie=Q.data instanceof ArrayBuffer?Q.data:null;if(!Ie||Ie.byteLength<5)return;const be=performance.now();R.lastPacketAt=be;try{const ut=new DataView(Ie).getUint32(0,!1);if(ut<=0||ut+4>Ie.byteLength){_t();return}const xe=new Uint8Array(Ie,4,ut),Qe=JSON.parse(Yd.decode(xe)),_e=new Uint8Array(Ie,4+ut),Wt=String(Qe.deviceId||""),lt=String(Qe.streamId||"");if(!Ed({deviceId:Wt,streamId:lt},{deviceId:e,streamId:K})){_t();return}const ct=String(Qe.frameKind||Qe.kind||"").toLowerCase();if(Qe.type==="remote.audio.status"||ct==="audio-status"){ve.markHealthy(F),R.lastCaptureStatusAt=be;const rt=RS(Qe);if(R.captureAlive=rt.captureAlive,R.helperAlive=rt.helperAlive,R.helperReady=rt.helperReady,R.captureHealthy=rt.healthy,R.captureStatusFailed=rt.failed,R.captureAwaitingCurrentPcm=rt.awaitingCurrentPcm,rt.awaitingCurrentPcm?R.captureAwaitingSinceAt||=be:R.captureAwaitingSinceAt=0,R.capturePhase=rt.capturePhase,R.backendKind=rt.backendKind,R.helperRequired=rt.helperRequired===!0,R.helperPid=rt.helperPid,R.captureRestartCount=Math.max(0,Number(Qe.restartCount||0)||0),R.nativeCallbackDiagnosticsAvailable=Qe.callbackDiagnosticsAvailable===!0,R.nativeRejectedCallbackCount=R.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Qe.rejectedCallbackCount||0)||0):0,R.nativeCurrentnessDropCount=R.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Qe.currentnessDropCount||0)||0):0,R.nativeLastDropReason=R.nativeCallbackDiagnosticsAvailable?String(Qe.lastDropReason||""):"",R.lastPcmAtEpochMs=Math.max(0,Number(Qe.lastPcmAtEpochMs||0)||0),R.silentForMs=Math.max(0,Number(Qe.silentForMs||0)||0),R.captureAgeMs=R.lastPcmAtEpochMs>0?Math.max(0,Date.now()-R.lastPcmAtEpochMs):R.silentForMs,R.captureHealthy){if(bt=0,Mt=0,!it){Y("");const Pt=String(_.state)==="running",zt=R.lastAcceptedAt>0&&performance.now()-R.lastAcceptedAt<=rl;Be(Pt?zt?"playing":"silent":"suspended")}}else R.captureAwaitingCurrentPcm&&!it?Be("open"):R.captureStatusFailed&&!it&&Be("stalled");return}const ht={deviceId:Wt,frameSeq:Number(Qe.frameSeq||0),streamId:lt,mimeType:String(Qe.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Qe.sampleRate||48e3),channels:Number(Qe.channels||2),capturedAt:String(Qe.capturedAt||""),receivedAt:String(Qe.receivedAt||""),byteLength:Number(Qe.byteLength||_e.byteLength),payload:_g};if(!ht.deviceId||Se)return;if(performance.now()-be>Nf){_t();return}if(MS(ht.mimeType)){U(ht,Ie,_e.byteOffset,_e.byteLength,be)&&ve.markHealthy(F);return}_t(),Be("error"),Y(`Unsupported remote audio format "${ht.mimeType}". Requesting a bounded PCM restart.`),!it&&bt<ms.length&&(Mt=0,At());return}catch(Ye){Se||(Be("error"),Y(Ye instanceof Error?Ye.message:String(Ye)))}}),F.addEventListener("error",()=>{!he&&!Se&&ce()&&ve.isCurrent(F)&&(Be("error"),Y("Remote audio WebSocket error."))}),F.addEventListener("close",()=>{if(he)return;const Q=xf({reconnectOwner:ve,lifecycleLedger:Ot,lifecycleOwner:N,socket:F});Q!=="stale"&&(he=!0,we(),!Se&&ce()&&Q==="current"&&(I(),Be("closed"),ve.scheduleReconnect(F)))})},Te(P),W=()=>{je()}});return ee.ready.catch(L=>{ce()&&(E("error"),O(L instanceof Error?`Remote audio owner setup failed: ${L.message}`:"Remote audio owner setup failed."))}),()=>{pe=!0,W?W():ee.cancel()}},[e,t,a,r,p,h,f]);const J=T===f;return{state:J?x:"idle",lastFrame:J?B:null,stats:J?G:go,error:J?re:""}}function hC({workspaceReady:e,desktopShell:t,publicConsole:a,authenticated:r,managerNeedsLocalAccess:c,localHubAccessEnabled:u}){return e?t?!0:a?r:!c||u:!1}const vl=384e3,gC=1024*1024,bC=24*1024*1024,vC=256*1024*1024,yC=24;function wC(e,t){if(!e||e.repeat||e.altKey||e.shiftKey)return"";const a=String(e.key||"").toLowerCase();return a!=="c"&&a!=="v"||!(t?e.metaKey===!0&&e.ctrlKey!==!0:e.ctrlKey===!0&&e.metaKey!==!0)?"":a==="c"?"copy":"paste"}function SC(e){return`clipboard-${e==="copy"?"copy":"paste"}-${Date.now()}-${crypto.randomUUID()}`}function Fd(e,t=""){const a=e&&typeof e=="object"?e:{},r=String(a.operationId||""),c=String(a.contentKind||"").toLowerCase(),u=Array.isArray(a.items)?a.items:[];if(!r||t&&r!==t||!["text","image","files"].includes(c)||u.length<1||u.length>yC)throw new Error("clipboard-manifest-invalid");let p=0;const h=u.map((f,k)=>{const M=Number(f?.itemIndex),b=Number(f?.size),T=String(f?.kind||"").toLowerCase();if(M!==k||!Number.isSafeInteger(b)||b<0||T!=="file"&&b===0||!["text","image","file"].includes(T)||T!==(c==="files"?"file":c))throw new Error("clipboard-item-invalid");p+=b;const A=String(f?.sha256||"").toLowerCase(),x=String(f?.storageName||`item-${k}.bin`);if(!/^[a-f0-9]{64}$/.test(A)||x!==`item-${k}.bin`||String(f?.name||"").includes("\0"))throw new Error("clipboard-item-metadata-invalid");return{itemIndex:M,kind:T,name:String(f?.name||"").slice(0,240),mimeType:String(f?.mimeType||"").slice(0,160),size:b,lastModified:Math.max(0,Number(f?.lastModified||0)||0),sha256:A,storageName:x}});if(p!==Number(a.totalBytes)||p>vC||c==="text"&&p>gC||c==="image"&&p>bC)throw new Error("clipboard-size-limit");return{operationId:r,contentKind:c,totalBytes:p,items:h}}function rd(e,t=vl){if(!Number.isSafeInteger(e)||e<0||!Number.isSafeInteger(t)||t<1)throw new Error("clipboard-chunk-plan-invalid");if(e===0)return[{offset:0,byteLength:0,final:!0}];const a=[];for(let r=0;r<e;r+=t){const c=Math.min(t,e-r);a.push({offset:r,byteLength:c,final:r+c===e})}return a}const CC=80,Of=new Set(["down","move","up","leave"]);function ps(e,t=0){const a=Number(e);return Number.isFinite(a)?a:t}function _f(e){return{at:ps(e?.timeStamp),clientX:ps(e?.clientX),clientY:ps(e?.clientY),button:ps(e?.button),buttons:ps(e?.buttons)}}function kC(e,t,a){const r=a.at-t.at;return r>=0&&r<=CC&&Math.abs(a.clientX-t.clientX)<=1&&Math.abs(a.clientY-t.clientY)<=1&&a.buttons===t.buttons&&(e==="move"||e==="leave"||a.button===t.button)}function MC(){const e=new Map;return{observePointerEvent(t,a){Of.has(t)&&e.set(t,_f(a))},shouldHandleMouseEvent(t,a){if(!Of.has(t))return!1;const r=e.get(t);return e.delete(t),!r||!kC(t,r,_f(a))},reset(){e.clear()}}}const xC=3;function jf(e,t,a){const r=Math.max(1,Number(a)||1),c=Math.max(0,Math.min(r,Number(e)-Number(t))),u=Math.min(r/2,xC);return c<=u?0:c>=r-u?1:c/r}function RC(e,t,a){return{normalizedX:jf(e,a.left,a.width),normalizedY:jf(t,a.top,a.height)}}const Bf=8,Dd=320,Hf=28,Ts=1,Wg=4;function AC(){let e=!1;return{claimNativeTouchEvents(){e=!0},shouldHandlePointerEvent(){return!e}}}function ot(e,t=0){const a=Number(e);return Number.isFinite(a)?a:t}function Qd(e,t){const a=ot(e?.clientX)-ot(t?.clientX),r=ot(e?.clientY)-ot(t?.clientY);return a*a+r*r}function yl(e,t,a){return Math.min(a,Math.max(t,e))}function $g(e,t){return{clientX:(ot(e?.clientX)+ot(t?.clientX))/2,clientY:(ot(e?.clientY)+ot(t?.clientY))/2}}function Vg(e,t){return Math.sqrt(Qd(e,t))}function xl(){return{scale:Ts,translateX:0,translateY:0}}function IC(e,t,a,r){const c=a||xl(),u=yl(ot(c.scale,Ts),Ts,Wg),p={left:ot(r?.left),top:ot(r?.top),width:Math.max(1,ot(r?.width,1)),height:Math.max(1,ot(r?.height,1))},h=$g(e,t);return{startDistance:Math.max(1,Vg(e,t)),startScale:u,anchorX:(h.clientX-p.left-ot(c.translateX))/u,anchorY:(h.clientY-p.top-ot(c.translateY))/u,bounds:p}}function TC(e,t,a){if(!e)return xl();const r=$g(t,a),c=yl(ot(e.startScale,Ts)*Vg(t,a)/Math.max(1,ot(e.startDistance,1)),Ts,Wg),u=Math.max(1,ot(e.bounds?.width,1)),p=Math.max(1,ot(e.bounds?.height,1)),h=yl(r.clientX-ot(e.bounds?.left)-ot(e.anchorX)*c,u*(1-c),0),f=yl(r.clientY-ot(e.bounds?.top)-ot(e.anchorY)*c,p*(1-c),0);return{scale:c,translateX:h,translateY:f}}function PC(e,t,a){return{pointerId:ot(e,-1),startClientX:ot(t),startClientY:ot(a),clientX:ot(t),clientY:ot(a),dragged:!1}}function zg(e,t,a,r){if(!e||e.pointerId!==ot(t,-1))return e;const c={...e,clientX:ot(a,e.clientX),clientY:ot(r,e.clientY)},u=Bf*Bf;return{...c,dragged:e.dragged||Qd({clientX:e.startClientX,clientY:e.startClientY},c)>=u}}function EC(e,t,a,r,c){if(!e||e.pointerId!==ot(t,-1))return{kind:"ignore",gesture:e,tap:null};const u=zg(e,t,a,r);return{kind:u.dragged?"drag":"tap",gesture:u,tap:u.dragged?null:{clientX:u.clientX,clientY:u.clientY,at:ot(c)}}}function Wf(e,t){if(!e||!t)return!1;const a=ot(t.at)-ot(e.at);if(a<0||a>Dd)return!1;const r=Hf*Hf;return Qd(e,t)<=r}const Rl=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),NC=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),$f=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),Ld=64,FC=256,Vf=Object.freeze({Backspace:Object.freeze({key:"Backspace",code:"Backspace",keyCode:8,location:0}),Tab:Object.freeze({key:"Tab",code:"Tab",keyCode:9,location:0}),Enter:Object.freeze({key:"Enter",code:"Enter",keyCode:13,location:0}),Escape:Object.freeze({key:"Escape",code:"Escape",keyCode:27,location:0}),PageUp:Object.freeze({key:"PageUp",code:"PageUp",keyCode:33,location:0}),PageDown:Object.freeze({key:"PageDown",code:"PageDown",keyCode:34,location:0}),End:Object.freeze({key:"End",code:"End",keyCode:35,location:0}),Home:Object.freeze({key:"Home",code:"Home",keyCode:36,location:0}),ArrowLeft:Object.freeze({key:"ArrowLeft",code:"ArrowLeft",keyCode:37,location:0}),ArrowUp:Object.freeze({key:"ArrowUp",code:"ArrowUp",keyCode:38,location:0}),ArrowRight:Object.freeze({key:"ArrowRight",code:"ArrowRight",keyCode:39,location:0}),ArrowDown:Object.freeze({key:"ArrowDown",code:"ArrowDown",keyCode:40,location:0}),Delete:Object.freeze({key:"Delete",code:"Delete",keyCode:46,location:0})}),zf=Object.freeze({deleteContentBackward:"Backspace",deleteWordBackward:"Backspace",deleteSoftLineBackward:"Backspace",deleteHardLineBackward:"Backspace",deleteContentForward:"Delete",deleteWordForward:"Delete",deleteSoftLineForward:"Delete",deleteHardLineForward:"Delete",insertLineBreak:"Enter",insertParagraph:"Enter"});function Xd(e,t=80){return String(e||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,t)}function Ug(e){const t=String(e??"");return t===" "?" ":Xd(t)}function Od(e){const t=Xd(e);return Object.prototype.hasOwnProperty.call($f,t)?$f[t]:t}function ad(e={}){const t=Ug(e.key),a=Number(e.keyCode??e.which);if(t===" "||t==="Spacebar"||a===32)return"Space";const r=Number.isFinite(Number(e.location))?Math.max(0,Math.min(3,Math.trunc(Number(e.location)))):0,c=r===2?"Right":"Left";return t==="Shift"?`Shift${c}`:t==="Control"?`Control${c}`:t==="Alt"||t==="AltGraph"?`Alt${c}`:t==="Meta"||t==="OS"?`Meta${c}`:t?`Key:${r}:${t}`.slice(0,80):""}function _d(e={}){const t=Od(e.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(t)?ad({...e,key:t}):t==="Unidentified"?ad(e):t||ad(e)}function wl(e){for(const[t,a]of Object.entries(Rl))if(a.includes(e))return t;return""}function Aa(e,t){return Rl[t].some(a=>e.has(a))}function al(e,t,a={},r="",c=""){for(const u of Object.keys(Rl)){const p=a[u]===!0,h=Rl[u];if(u===r){if(c==="keyup"&&!p)for(const f of h)t.has(f)||e.delete(f);continue}if(p){!Aa(e,u)&&e.size<Ld&&e.add(NC[u]);continue}for(const f of h)t.has(f)||e.delete(f)}}function DC(e,t){if(e.length!==t.size)return!1;let a=0;for(const r of t){if(e[a]!==r)return!1;a+=1}return!0}function Uf(e){for(const t of[...e])wl(t)||e.delete(t)}function jd(e){return{shiftKey:Aa(e,"shiftKey"),ctrlKey:Aa(e,"ctrlKey"),altKey:Aa(e,"altKey"),metaKey:Aa(e,"metaKey")}}function LC(e={},t={}){return{shiftKey:e.shiftKey===!0||t.shiftKey===!0,ctrlKey:e.ctrlKey===!0||t.ctrlKey===!0,altKey:e.altKey===!0||t.altKey===!0,metaKey:e.metaKey===!0||t.metaKey===!0}}function ol(e){const t=String(e||""),a=Object.prototype.hasOwnProperty.call(zf,t)?zf[t]:t;return Object.prototype.hasOwnProperty.call(Vf,a)?{...Vf[a],repeat:!1}:null}function OC(e){const t=String(e??"").replace(/\0/g,"");if(!t)return[];const a=[];let r=t;for(;r.length>0;){let c=Math.min(FC,r.length);c<r.length&&/[\uD800-\uDBFF]/.test(r[c-1])&&/[\uDC00-\uDFFF]/.test(r[c])&&(c-=1),a.push(r.slice(0,c)),r=r.slice(c)}return a}function _C(e,t,a){const r=_d(e),c=Ug(e.key),u=Number(e.keyCode??e.which),p=Number(e.location);return{type:t,key:c,code:r,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(p)?Math.max(0,Math.min(255,Math.trunc(p))):0,text:c.length===1?c:"",repeat:t==="keydown"&&e.repeat===!0,pressedCodes:[...a],...jd(a)}}function jC(){const e=new Set,t=new Set,a=()=>({pressedCodes:[...e]});return{event(r={},c=""){if(c!=="keydown"&&c!=="keyup")return null;const u=_d(r);if(!u)return null;const p=wl(u),h=e.has(u),f=[...e];return p?c==="keydown"?(al(e,t,r,p,c),e.size<Ld&&e.add(u)):(t.has(u)||e.delete(u),al(e,t,r,p,c)):(al(e,t,r),c==="keydown"?e.size<Ld&&e.add(u):e.delete(u)),c==="keyup"&&p==="metaKey"&&!Aa(e,"metaKey")&&Uf(e),c==="keydown"&&h&&r.repeat!==!0&&DC(f,e)?null:_C(r,c,e)},modifier(r,c){const u=Od(r),p=wl(u);if(!p)return null;const h=t.has(u);return c===h?null:(c?(t.add(u),e.add(u)):(t.delete(u),e.delete(u),p==="metaKey"&&!Aa(e,"metaKey")&&Uf(e)),{type:c?"keydown":"keyup",key:p==="metaKey"?"Meta":p==="ctrlKey"?"Control":p==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...a(),...jd(e)})},reset(r="keyboard-owner-reset",c=!1){const u=e.size>0;return e.clear(),t.clear(),!u&&!c?null:{type:"keyboard.reset",reason:Xd(r,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(r={}){const c=typeof r=="string"?Od(r):_d(r);if(e.has(c))return!0;const u=wl(c);return!!u&&Aa(e,u)},snapshot(){return{...a(),latchedCodes:[...t],...jd(e)}}}}const qg=64,BC=2;function Gg(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(1,Math.min(qg,t)):1}function Jd(e){const t=Math.floor(Number(e));return Number.isFinite(t)?Math.max(0,Math.min(qg-1,t)):0}function Kg(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"||t==="linux"||t.startsWith("linux ")}function HC(e,t,a){const r=String(t||"").trim();if(!r)return e||null;const c=String(a||"").trim();return e&&e.fingerprint===r&&(c?e.sampleId===c:e.sampleId==="")?e:{fingerprint:r,sampleId:c,consecutiveSamples:e?.fingerprint===r?e.consecutiveSamples+1:1}}function Yg({platform:e,topologyFingerprint:t,consecutiveTopologySamples:a}){return Kg(e)?!!String(t||"").trim()&&Number(a)>=BC:!0}function WC({requestedIndex:e,monitorCount:t,platform:a,topologyFingerprint:r,consecutiveTopologySamples:c}){const u=Jd(e),p=Gg(t);return u<p||!Yg({platform:a,topologyFingerprint:r,consecutiveTopologySamples:c})?u:p-1}function $C(e,t,a){const r=Jd(e),c=Gg(t);return r<c||Kg(a)?r:c-1}const VC=820,zC=500,qf=`(max-width: ${VC}px), (orientation: landscape) and (max-height: ${zC}px) and (pointer: coarse)`,UC="1200px 0px 1800px 0px",qC=960,GC=540,KC=68,Gf=6,YC=30,Kf=24,QC=16;function XC(e,t,a,r){return/iPad|iPhone|iPod/i.test(String(e||""))||t==="MacIntel"&&Number(a)>1||typeof r=="boolean"}function JC(e,t,a=""){const r=[...new Set((Array.isArray(e)?e:[]).map(u=>String(u||"").trim()).filter(Boolean))];if(!t)return r;const c=String(a||"").trim();return!c||!r.includes(c)?r.slice(0,Gf):[c,...r.filter(u=>u!==c)].slice(0,Gf)}function ZC(e,t){const a=Math.max(1,Math.floor(Number(e)||1));return t?Math.min(a,YC):a}function e0(e,t,a=1){const r=e&&typeof e=="object"?e:{},c={fps:Math.max(1,Math.floor(Number(r.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(r.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(r.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(r.quality)||1)))};return t?{...c,maxWidth:Math.min(c.maxWidth,qC),maxHeight:Math.min(c.maxHeight,GC),quality:Math.min(c.quality,KC)}:c}function t0(e,t){return!t||!e||typeof e.closest!="function"?null:e.closest(".desk-stage")}function Yf(e,t,a){return!!(e||t&&a)}function n0({isIos:e,standalone:t,safeAreaTop:a,screenHeight:r,layoutViewportHeight:c}){if(!e||!t)return 0;const u=Number(r),p=Number(c);if((Number.isFinite(u)&&u>0&&Number.isFinite(p)&&p>0?Math.max(0,u-p):0)>=QC)return 0;const f=Number(a);return Number.isFinite(f)&&f>0?Math.max(Kf,Math.round(f)-20):Kf}function r0(e,t,a,r=!1,c=r){const u=Number(e?.height),p=Number(t),h=Number(e?.offsetTop),f=r&&Number.isFinite(p)&&p>0,k=f?0:Number.isFinite(h)?Math.max(0,Math.round(h)):0,M=f?p:Number.isFinite(u)&&u>0?u:Number.isFinite(p)&&p>0?p:1,b=Number(e?.width),T=Number(a),A=c&&Number.isFinite(T)&&T>0,x=A?T:Number.isFinite(b)&&b>0?b:Number.isFinite(T)&&T>0?T:1,E=Number(e?.offsetLeft);return{height:Math.max(1,Math.round(M)),width:Math.max(1,Math.round(x)),offsetTop:k,offsetLeft:A?0:Number.isFinite(E)?Math.max(0,Math.round(E)):0}}const Bd=3e4;function Qg(e={},t={}){const a=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=t?.cadence==="slow"?"slow":"fast",c=Number.isFinite(Number(t?.viewScale))?Math.max(0,Math.min(100,Math.round(Number(t.viewScale)))):100;return{cadence:a.cadence==="slow"||a.cadence==="fast"?a.cadence:r,viewScale:Number.isFinite(Number(a.viewScale))?Math.max(0,Math.min(100,Math.round(Number(a.viewScale)))):c}}function a0(e){return Number(e)<=0?"list":"large"}function o0(e,t){return!e||typeof e!="object"||Array.isArray(e)||!t||typeof t!="object"||Array.isArray(t)?!1:e.cadence===t.cadence&&Number.isFinite(Number(e.viewScale))&&Math.round(Number(e.viewScale))===t.viewScale}function i0({error:e,publicConsole:t,workspaceKind:a,workspaceRole:r,workspaceId:c,userId:u}){const p=String(e instanceof Error?e.message:e||"").trim().toLowerCase(),h=String(c||"").trim().toLowerCase(),f=String(u||"").trim().toLowerCase();return t===!0&&String(a||"").trim().toLowerCase()==="personal"&&String(r||"").trim().toLowerCase()==="owner"&&!!h&&h===f&&p==="502 console-route-not-allowed"}function od(e=!1){return e?"/api/settings":"/api/remote/wall-preferences"}function s0({legacy:e=!1,revision:t,preferences:a}){const r=Qg(a);return e?{revision:t,wall:r}:{revision:t,cadence:r.cadence,viewScale:r.viewScale}}function c0(e,t=!1){if(!(!e||typeof e!="object"||Array.isArray(e)))return t?e.settings?.wall:e.wallPreferences}function l0({wallSize:e,elapsedMs:t}){return e==="list"&&Number.isFinite(Number(t))&&Number(t)>=Bd}function Qf(e){const t=Number(e);return Number.isSafeInteger(t)&&t>=0?t:0}function u0(e=""){let t=String(e||""),a,r=0;const c=h=>{const f=String(h||"");return f===t?!1:(t=f,a=void 0,r+=1,!0)},u=h=>String(h||"")!==t||!t?null:(r+=1,Object.freeze({ownerKey:t,generation:r})),p=h=>!!h&&h.ownerKey===t&&h.generation===r;return{switchOwner:c,beginWrite:u,ownsWrite:p,readRevision(h){return String(h||"")===t?a:void 0},acceptSnapshot(h,f){if(String(h||"")!==t)return!1;const k=Qf(f);return a!==void 0&&k<a?!1:(a=k,!0)},commitWriteRevision(h,f){return p(h)?(a=Qf(f),!0):!1},inspect(){return{ownerKey:t,revision:a,writeGeneration:r}}}}function d0(e,t){const a=Promise.resolve(e).catch(()=>{}).then(t);return{result:a,tail:a.then(()=>{},()=>{})}}function m0(){let e=Promise.resolve(),t=Promise.resolve();const a=r=>{const c=d0(e,r);return e=c.tail,c.result};return{enqueue:a,enqueueStop(r){const c=a(r);return t=c.then(()=>{}),t.catch(()=>{}),c},enqueueStart(r){const c=t;return a(async()=>(await c,r()))}}}function p0(e={}){return Number(e.generation)===Number(e.currentGeneration)&&e.enabled===!0&&String(e.deviceId||"")!==""&&String(e.deviceId||"")===String(e.currentDeviceId||"")&&e.documentVisible===!0&&e.presentationVisible===!0&&String(e.streamId||"")!==""&&String(e.streamId||"")===String(e.currentStreamId||"")}function f0(e={}){const t=e.ok!==!1,a=t&&e.staleOwner===!0;return{confirmed:t&&(a||e.captureStopConfirmed===!0||e.alreadyStopped===!0),staleOwner:a,preserveNewerOwner:a&&(e.retainedNewerOwner===!0||String(e.activeStreamId||"")!=="")}}const wt=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:30,slowWallFps:5,fastWallFps:30,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,intentionalIdleTelemetryFreshMs:3e3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:30,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function Ms(e){return e==="slow"?wt.slowWallFps:wt.fastWallFps}function Xf(e,t){const a=e&&typeof e=="object"?e:{};return Object.entries(t&&typeof t=="object"?t:{}).some(([c,u])=>{const p=String(u||"").trim();return p.length>0&&String(a[c]||"").trim()!==p})}function Jf({paintStale:e,lastRecoveryAt:t,now:a,recoveryCooldownMs:r,transportRecoveryAfterMs:c}){if(e!==!0)return"none";const u=Math.max(0,Number(a)||0),p=Math.max(0,Number(t)||0),h=p>0?u-p:Number.POSITIVE_INFINITY;return p>0&&h>=Math.max(1,Number(c)||1)?"recover-transport":p<=0||h>=Math.max(1,Number(r)||1)?"reset-decoder":"wait"}function Zf({lastReceivedAt:e,lastPaintedAt:t,now:a,staleAfterMs:r}){const c=Math.max(0,Number(e)||0);if(c<=0)return!1;const u=Math.max(0,Number(t)||0),p=u>0?u:c;return Math.max(0,Number(a)||0)-p>Math.max(1,Number(r)||1)}function h0(e,t){const a=e&&typeof e=="object"?e:{},r=t&&typeof t=="object"?t:{},c=Object.keys(a),u=Object.keys(r);return c.length!==u.length?r:u.every(p=>Object.prototype.hasOwnProperty.call(a,p)&&String(a[p]||"").trim()===String(r[p]||"").trim())?a:r}function eh({presentationOwnerActive:e,desiredDeviceCount:t}){return e===!0&&Math.max(0,Math.floor(Number(t)||0))>0}function g0(e){return e==="share-files"||e==="agents"}function b0({captureOwnershipActive:e,localFeatureAccess:t,controlSessionDeviceId:a,planAllowed:r,sessionState:c,controlFocusVisible:u,presentationCanvasMounted:p,wallPresentationVisible:h,wallPresentationCanvasMounted:f,decoderOwnerExists:k}){const M=c==="connecting"||c==="active"||c==="warm";return e!==!0||t!==!0||!String(a||"").trim()||r!==!0||!M?!1:k===!0||u===!0&&p===!0||h===!0&&f===!0}function v0({decodeWidth:e,decodeHeight:t,presentationCssWidth:a,presentationCssHeight:r,devicePixelRatio:c,sourceWidth:u,sourceHeight:p}){const h=Math.max(0,Number(e)||0),f=Math.max(0,Number(t)||0),k=Math.max(0,Number(a)||0),M=Math.max(0,Number(r)||0),b=Math.max(1,Math.min(2,Number(c)||1)),T=Math.max(0,Number(u)||0),A=Math.max(0,Number(p)||0);if(h<=0||f<=0||k<=0||M<=0||T<=0||A<=0)return!1;const x=k*b,E=M*b,B=Math.min(1,x/T,E/A),q=Math.max(1,Math.round(T*B)),G=Math.max(1,Math.round(A*B));return h<q*.9||f<G*.9}function y0({cadenceCredit:e,targetFps:t,sourceFps:a,elapsedSincePaintMs:r=0,nowMs:c=0,scheduledPaintAtMs:u=0,force:p=!1}){const h=Math.max(1,Number(t)||1),f=Math.max(1,Number(a)||1);if(h>=f)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const k=Math.max(0,Number(c)||0),M=Math.max(0,Number(u)||0),b=k>0&&M>0,T=1e3/h,A=Math.min(T/3,1e3/f*.5),x=Number.isFinite(Number(e))?Math.max(0,Math.min(f-Number.EPSILON,Number(e))):0;if(p)return{shouldPaint:!0,nextCadenceCredit:x,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:b?M:k>0?k+T:0};const E=x+h,B=E>=f,q=1e3/h*wt.controlWallReuseStarvationFactor,G=!B&&Number(r)>=q,ne=b&&k+A>=M,re=b?ne||G:B||G;let O=M;return re&&k>0&&(!b||G?O=k+T:(O=M+T,O<=k-T&&(O=k+T))),{shouldPaint:re,nextCadenceCredit:G?0:B&&re?E-f:Math.min(f-Number.EPSILON,E),sourceCadencePassthrough:!1,deadlineForced:G,scheduleSelected:ne,nextScheduledPaintAtMs:O}}function w0(e,t){const a=Number.isFinite(Number(t))?Math.max(0,Math.floor(Number(t))):Number.POSITIVE_INFINITY;if(a<=0)return[];const r=(Array.isArray(e)?e:[]).filter(p=>p&&String(p.deviceId||"").trim()).slice().sort((p,h)=>{const f=Number.isFinite(Number(p.slotNumber))?Number(p.slotNumber):Number.MAX_SAFE_INTEGER,k=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return f!==k?f-k:String(p.deviceId).localeCompare(String(h.deviceId))}),c=[],u=new Set;for(const p of r){const h=String(p.deviceId).trim();if(!u.has(h)&&(u.add(h),c.push(h),c.length>=a))break}return c}function S0(e,t){const a=Math.max(0,Math.floor(Number(t)||0));return e===!0&&a>0}function fs({mode4Enabled:e,directMode4WallEnabled:t,isMac:a}){return"direct"}function C0({mode4Enabled:e,directMode4WallEnabled:t,adaptiveFps:a,directDeviceCount:r,adaptive:c=!0}){return Math.max(1,Math.floor(Number(a)||1))}function k0({directDeviceCount:e,requestedFps:t,measuredFramesPerSecond:a,measuredPaintFramesPerSecond:r,measuredBytesPerSecond:c,maxBytesPerSecond:u,worstReceiveGapMs:p,worstPaintP95Ms:h,maxFrameGapMs:f}){const k=Math.max(1,Math.floor(Number(e)||1)),M=Math.max(1,Number(t)||1),b=Math.max(0,Number(a)||0),T=Math.max(0,Number(r)||0),A=Math.max(0,Number(c)||0),x=Math.max(1,Number(u)||1),E=Math.max(0,Number(p)||0),B=Math.max(0,Number(h)||0),q=Math.max(1,Number(f)||1),G=k*M,ne=G>8&&b<G*wt.missingDeliveryRatio,re=G>8&&T<G*wt.missingDeliveryRatio,O=A>x||E>q||ne||re,ie=b>=G*wt.recoveryDeliveryRatio&&T>=G*wt.recoveryDeliveryRatio&&A<x*wt.recoveryByteRatio&&E<q*wt.recoveryGapRatio&&B<q*wt.recoveryGapRatio;return{expectedFramesPerSecond:G,estimatedMissingFrames:ne,estimatedMissingPaints:re,overloaded:O,healthyForRecovery:ie}}function M0({receiveSampleMs:e,paintSampleMs:t,currentGenerationVerified:a,frameRequestedFps:r,adaptiveFps:c}){const u=Number(e),p=Number(t),h=Number(r),f=Number(c);return a===!0&&Number.isFinite(u)&&u>=wt.adaptiveMinimumCurrentSampleMs&&Number.isFinite(p)&&p>=wt.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===f}function x0(e,t=Date.now()){const a=e&&typeof e=="object"?e:{},r=Number(t),c=Number(a.browserReceivedEpochMs),u=Number(a.nativeCaptureTelemetryAgeMs),p=a.nativeCaptureTelemetryAvailable===!0&&a.nativeCaptureResourceTelemetryAvailable===!0&&Number(a.nativeCaptureTelemetryVersion)>=5&&Number.isFinite(r)&&Number.isFinite(c)&&c>0&&r>=c&&Number.isFinite(u)&&u>=0&&u+(r-c)<=wt.intentionalIdleTelemetryFreshMs,h=Math.max(0,Number(a.requestedFps||a.effectiveFps||0)),f=Math.max(0,Number(a.nativeCaptureFps||0)),k=Math.max(0,Number(a.nativeEncodedFps||0)),M=Math.max(0,Number(a.nativeCaptureSampleCount||0)),b=Math.max(0,Number(a.nativeIdleSkippedFrameCount||0)),T=Math.max(0,Number(a.nativeBackpressureSkippedFrameCount||0)),A=h>0&&f>=h*wt.missingDeliveryRatio,x=k>=1&&k<h*wt.missingDeliveryRatio;return p&&M>0&&A&&x&&b>=Math.max(1,f*.6)&&T===0}function R0({deviceCount:e,targetFps:t,adaptive:a=!0}){const r=Math.max(1,Math.floor(Number(e)||1)),c=Math.max(1,Math.min(wt.scalableAtlasMaxInputFps,Math.floor(Number(t)||wt.scalableAtlasMaxInputFps)));if(!a)return c;const u=Math.max(wt.scalableAtlasMinInputFps,Math.min(wt.scalableAtlasMaxInputFps,Math.floor(wt.scalableAtlasAggregateInputFps/r)));return Math.min(c,u)}function A0(e,t){return{acceleration:wt.directDecodeAcceleration,latencyMode:wt.directLatencyMode}}const Al=0,ea=100,I0=25,T0=50,th=300,P0=560;function Mi(e){return Number.isFinite(e)?Math.min(ea,Math.max(Al,Math.round(e))):ea}function E0(e){const t=Mi(e);return t===Al?"list":t<T0?"medium":"large"}function N0(e){const a=(Math.max(1,Mi(e))-1)/(ea-1);return Math.round(th+a*(P0-th))}function il(e){if(!e)return"";const t=Math.max(0,Math.floor((Date.now()-e)/1e3)),a=Math.floor(t/3600),r=Math.floor(t%3600/60),c=t%60;return a>0?`${String(a).padStart(2,"0")}:${String(r).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(r).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function nh({controller:e,compact:t=!1,onFirstRollingUse:a,onError:r}){const{state:c,settings:u,videoSupported:p}=e,h=async b=>{try{await b()}catch(T){r?.(T instanceof Error?T.message:String(T))}},f=async()=>{if(u.rollingEnabled){e.setRollingEnabled(!1);return}(a?await a():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
175
|
+
Nothing is saved until you press Save Last 30s.`))&&e.setRollingEnabled(!0)},k=c.recording?`Stop recording · ${il(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,M=c.timelapse?`Stop timelapse · ${il(c.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return i.jsxs("div",{className:`capture-toolbar ${t?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[i.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{h(e.takeScreenshot)},type:"button",children:i.jsx(iy,{size:17})}),i.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":k,title:k,disabled:!p||c.busy||c.timelapse,onClick:()=>{h(c.recording?e.stopRecording:e.startRecording)},type:"button",children:c.recording?i.jsxs(i.Fragment,{children:[i.jsx(tf,{size:14,fill:"currentColor"}),i.jsx("span",{children:il(c.recordingStartedAt)})]}):i.jsx(sy,{size:18})}),i.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:!p||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void h(e.saveLast30Seconds):void f(),type:"button",children:[i.jsx(cy,{size:17}),i.jsx("small",{children:"30s"})]}),i.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":M,title:M,disabled:!p||c.busy||c.recording,onClick:()=>{h(c.timelapse?e.stopTimelapse:e.startTimelapse)},type:"button",children:c.timelapse?i.jsxs(i.Fragment,{children:[i.jsx(tf,{size:14,fill:"currentColor"}),i.jsx("span",{children:il(c.timelapseStartedAt)})]}):i.jsx(ly,{size:17})})]})}function sl(e){return Number.isFinite(e)?`Up to ${e} computers`:"Unlimited computers"}function cl(e){return`${e} ${e===1?"person":"people"}`}const ll={free:{name:$e.free.name,shortName:$e.free.name,price:`${$e.free.price} forever`,audience:$e.free.audience,deviceText:sl($e.free.limit),features:["Live Wall and Control",cl($e.free.people),"Standard banner"]},plus:{name:$e.ltd.name,shortName:$e.ltd.name,price:`${$e.ltd.price} / month`,ltdPrice:$e.ltd.ltd,billingName:"Plus",audience:$e.ltd.audience,deviceText:sl($e.ltd.limit),features:["Everything in Free",`${cl($e.ltd.people)} · no banner`,"Personal and creator use"]},business:{name:$e.pro.name,shortName:"Business",price:`${$e.pro.price} / month`,ltdPrice:$e.pro.ltd,billingName:"Pro",audience:$e.pro.audience,deviceText:sl($e.pro.limit),features:["Everything in Plus",cl($e.pro.people),"Commercial, school, and academy use"]},team:{name:$e.team.name,shortName:$e.team.name,price:`${$e.team.price} / month`,billingName:"Team",audience:$e.team.audience,deviceText:`${sl($e.team.limit)} · one shared workspace`,features:[`${cl($e.team.people)} with their own accounts`,"Commercial use","Owner and Operator roles","One controller per computer"]}},rh={free:0,plus:1,business:2,team:3};function ah(e){const t=String(e||"").trim().toLowerCase();return t==="team"?"team":t==="pro"||t==="business"?"business":t==="ltd"||t==="plus"?"plus":"free"}function oh(e){return Number.isFinite(e)?String(Math.max(0,e)):"Unlimited"}function ih(e){return e==="team"?i.jsx(As,{size:17,"aria-hidden":"true"}):e==="business"?i.jsx(wo,{size:17,"aria-hidden":"true"}):e==="plus"?i.jsx(Xh,{size:17,"aria-hidden":"true"}):i.jsx(Qh,{size:17,"aria-hidden":"true"})}function F0({open:e,signedIn:t,accountName:a,accountEmail:r,accountInitial:c,avatarUrl:u,currentPlan:p,currentPlanKnown:h=!0,deviceCount:f,deviceLimit:k,licenseLabel:M,networkLabel:b,accessLabel:T,authBusy:A,workspaceBusy:x=!1,checkoutBusy:E,ltdCheckoutEnabled:B,monthlyCheckoutEnabled:q,teamCheckoutEnabled:G,planChangesEnabled:ne,planManagementLabel:re="Managed by Team owner",showWorkspaceSwitcher:O=!0,sessionRevocationError:ie="",workspaces:J,activeWorkspaceId:de,teamWorkspace:se,onClose:pe,onSignIn:ce,onSignOut:W,onRetrySessionRevocation:ee,onSelectPlan:L,onSelectWorkspace:_,onCreateTeamInvite:K,onRemoveTeamMember:ue,onRevokeTeamInvite:P,onRenameTeamWorkspace:N,onLeaveTeamWorkspace:te}){const we=s.useRef(null),me=s.useRef(null),Fe=s.useRef(null),H=s.useRef(()=>{}),R=e?`${de}
|
|
176
|
+
${se?.id||""}
|
|
177
|
+
${se?.currentUserRole||""}`:"",Se=s.useRef({key:R,generation:0});Se.current.key!==R&&(Se.current={key:R,generation:Se.current.generation+1});const[Ce,Ve]=s.useState(!1),[qe,Oe]=s.useState(""),[z,Me]=s.useState(null),[je,Ge]=s.useState(!1),[kt,Te]=s.useState(""),[Be,Y]=s.useState(se?.name||""),[ve,st]=s.useState(""),it=()=>({...Se.current}),bt=oe=>Se.current.generation===oe.generation&&Se.current.key===oe.key&&oe.key===R,Mt=ll[p],ae=s.useMemo(()=>!Number.isFinite(k)||k<=0?0:Math.min(100,Math.round(f/k*100)),[f,k]),$=()=>{Se.current={key:"",generation:Se.current.generation+1},pe()};if(H.current=$,s.useEffect(()=>{if(!e)return;Fe.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const oe=window.requestAnimationFrame(()=>me.current?.focus()),Pe=He=>{if(He.key==="Escape"){He.preventDefault(),H.current();return}if(He.key!=="Tab"||!we.current)return;const vt=Array.from(we.current.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'));if(vt.length===0){He.preventDefault(),we.current.focus();return}const Ze=vt[0],At=vt[vt.length-1];He.shiftKey&&document.activeElement===Ze?(He.preventDefault(),At.focus()):!He.shiftKey&&document.activeElement===At&&(He.preventDefault(),Ze.focus())};return window.addEventListener("keydown",Pe),()=>{window.cancelAnimationFrame(oe),window.removeEventListener("keydown",Pe),Fe.current?.focus(),Fe.current=null}},[e]),s.useEffect(()=>{Me(null),Oe(""),Ge(!1),Te(""),Ve(!1),st(""),Y(se?.name||"")},[R,se?.name]),s.useEffect(()=>{ve||Y(se?.name||"")},[ve,se?.name]),!e)return null;const ye=async()=>{if(!K||Ce||x||!R)return;const oe=it(),Pe=()=>bt(oe);Ve(!0),Oe(""),Ge(!1);try{const He=await K(kt);if(!Pe())return;if(!He?.url)throw new Error("The invite link was not returned.");Me(He),Te("")}catch(He){if(!Pe())return;Oe(He instanceof Error?He.message:"The invite link could not be created.")}finally{Pe()&&Ve(!1)}},V=async()=>{if(!N||ve)return;const oe=it(),Pe=Be.trim();if(!Pe){Oe("Enter a Team Space name.");return}st("rename"),Oe("");try{if(await N(Pe),!bt(oe))return}catch(He){if(!bt(oe))return;Oe(He instanceof Error?He.message:"The Team Space could not be renamed.")}finally{bt(oe)&&st("")}},Ke=async()=>{if(!te||ve)return;const oe=it();st("leave"),Oe("");try{if(await te(),!bt(oe))return;$()}catch(Pe){if(!bt(oe))return;Oe(Pe instanceof Error?Pe.message:"The Team Space could not be left.")}finally{bt(oe)&&st("")}},St=async oe=>{if(ve)return;const Pe=it(),He=oe.status==="invited"?P:ue;if(He){st(`member:${oe.id}`),Oe("");try{if(await He(oe.id),!bt(Pe))return}catch(vt){if(!bt(Pe))return;Oe(vt instanceof Error?vt.message:"The Team member could not be changed.")}finally{bt(Pe)&&st("")}}},I=async()=>{if(z?.url)try{await navigator.clipboard.writeText(z.url),Ge(!0),window.setTimeout(()=>Ge(!1),1800)}catch{Oe("Copy failed. Select and copy the invite link manually.")}};return i.jsx("div",{className:"account-dialog-backdrop",role:"presentation",onPointerDown:oe=>{oe.currentTarget===oe.target&&$()},children:i.jsxs("section",{id:"vuvodesk-account-dialog",ref:we,className:"account-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"account-dialog-title",tabIndex:-1,onPointerDown:oe=>oe.stopPropagation(),children:[i.jsxs("header",{className:"account-dialog-header",children:[i.jsxs("div",{className:"account-dialog-identity",children:[i.jsx("span",{className:"account-dialog-avatar",children:t&&u?i.jsx("img",{src:u,alt:"",referrerPolicy:"no-referrer"}):t?i.jsx("span",{children:c}):i.jsx(Sl,{size:21,"aria-hidden":"true"})}),i.jsxs("span",{children:[i.jsx("small",{children:"VuvoDesk account"}),i.jsx("strong",{id:"account-dialog-title",children:t?a:"Sign in to manage VuvoDesk"}),i.jsx("span",{children:r||"Your computers and plan stay with your account."})]})]}),i.jsx("button",{ref:me,className:"account-dialog-close",onClick:$,type:"button","aria-label":"Close account",children:i.jsx(Ma,{size:20,"aria-hidden":"true"})})]}),i.jsxs("div",{className:"account-dialog-body",children:[ie&&i.jsxs("div",{className:"account-session-revocation-error",role:"alert",children:[i.jsx("strong",{children:"Hub sign-out is not confirmed"}),i.jsx("span",{children:"Wall and Control stay blocked. Retry when the Hub is reachable so its browser permission is removed."}),ee&&i.jsx("button",{onClick:()=>{ee()},disabled:A,type:"button",children:A?"Retrying…":"Retry Hub sign-out"})]}),O&&i.jsxs("section",{className:"account-workspace-switcher","aria-labelledby":"account-workspace-title","aria-busy":x,children:[i.jsxs("div",{children:[i.jsx("span",{id:"account-workspace-title",children:"Workspaces"}),i.jsx("small",{children:"Keep Personal separate from every Team you join."})]}),i.jsx("div",{className:"account-workspace-list",children:J.map(oe=>i.jsxs("button",{className:oe.id===de?"active":"",onClick:()=>{oe.id!==de&&_?.(oe.id)},disabled:x||oe.id!==de&&!_,"aria-pressed":oe.id===de,type:"button",children:[i.jsx("span",{children:oe.kind==="team"?i.jsx(As,{size:15,"aria-hidden":"true"}):i.jsx(Qh,{size:15,"aria-hidden":"true"})}),i.jsxs("span",{children:[i.jsx("strong",{children:oe.name}),i.jsx("small",{children:oe.kind==="team"?oe.role==="operator"?"Operator · Wall and Control":oe.memberCount===void 0?"Owner · Team Space":`Owner · ${oe.memberCount} people`:"Personal workspace"})]}),i.jsx("em",{children:ll[oe.plan].shortName})]},oe.id))})]}),i.jsxs("section",{className:`account-current-plan plan-${p}`,"aria-label":h?"Current VuvoDesk plan":"VuvoDesk plan policy",children:[i.jsxs("div",{className:"account-current-plan-copy",children:[i.jsx("span",{className:"account-current-plan-icon",children:ih(p)}),i.jsxs("span",{children:[i.jsx("small",{children:h?"Current plan":"Plan policy"}),i.jsx("strong",{children:h?Mt.name:"Plan is managed at the Hub"}),i.jsx("span",{children:M})]})]}),i.jsxs("div",{className:"account-device-usage",children:[i.jsxs("span",{children:[i.jsx(Ra,{size:15,"aria-hidden":"true"})," ",h?"Computer usage":"This Client computer"]}),i.jsxs("strong",{children:[f," ",h&&i.jsxs("small",{children:["/ ",oh(k)]})]}),h&&Number.isFinite(k)&&i.jsx("span",{className:"account-device-meter","aria-label":`${f} of ${oh(k)} computers used`,children:i.jsx("i",{style:{width:`${ae}%`}})})]}),i.jsxs("dl",{className:"account-runtime-facts",children:[i.jsxs("div",{children:[i.jsx("dt",{children:"Hub"}),i.jsx("dd",{children:b})]}),i.jsxs("div",{children:[i.jsx("dt",{children:"Remote access"}),i.jsx("dd",{children:T})]})]})]}),i.jsxs("section",{className:"account-plan-section","aria-labelledby":"account-plan-section-title",children:[i.jsxs("div",{className:"account-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"License and features"}),i.jsx("h2",{id:"account-plan-section-title",children:"One account, the right way to manage your computers"})]}),i.jsx("small",{children:"Team members never share a Google login."})]}),i.jsx("div",{className:"account-plan-grid",children:Object.keys(ll).map(oe=>{const Pe=ll[oe],He=h&&p===oe,vt=h&&rh[oe]<rh[p],Ze=ne&&!He&&!vt&&oe!=="free";return i.jsxs("article",{className:`account-plan-card plan-${oe} ${He?"current":""}`,children:[i.jsxs("div",{className:"account-plan-card-title",children:[i.jsxs("span",{children:[ih(oe)," ",Pe.name]}),He&&i.jsxs("em",{children:[i.jsx(hl,{size:13,"aria-hidden":"true"})," Current"]})]}),i.jsx("p",{children:Pe.audience}),i.jsx("span",{className:"account-plan-price",children:Pe.price}),Pe.ltdPrice&&i.jsxs("span",{className:"account-plan-ltd-price",children:[Pe.ltdPrice," · one-time"]}),i.jsx("strong",{children:Pe.deviceText}),i.jsx("ul",{children:Pe.features.map(At=>i.jsxs("li",{children:[i.jsx(hl,{size:14,"aria-hidden":"true"})," ",At]},At))}),He||vt||oe==="free"||!ne?i.jsx("span",{className:"account-plan-state",children:He?"Your current plan":vt?"Included in your plan":!ne&&oe!=="free"?re:"Free plan"}):oe==="plus"||oe==="business"?i.jsxs("div",{className:"account-plan-actions",children:[i.jsxs("button",{className:"account-plan-action secondary",onClick:()=>{L(oe==="plus"?"plus_monthly":"pro_monthly")},disabled:!Ze||!q||A||x||E,type:"button",children:[i.jsx(xa,{size:15,"aria-hidden":"true"}),ne?q?`Choose ${Pe.billingName} · ${Pe.price}`:"Monthly · Coming soon":re]}),i.jsxs("button",{className:"account-plan-action",onClick:()=>{L(oe==="plus"?"plus_ltd":"pro_ltd")},disabled:!Ze||!B||A||x||E,type:"button",children:[i.jsx(xa,{size:15,"aria-hidden":"true"}),ne?B?`Buy ${Pe.billingName} · ${Pe.ltdPrice}`:"LTD · Coming soon":re]})]}):i.jsxs("button",{className:"account-plan-action",onClick:()=>{L("team_monthly")},disabled:!Ze||!G||A||x||E,type:"button",children:[i.jsx(As,{size:15,"aria-hidden":"true"}),ne?G?`Choose Team · ${Pe.price}`:"Team · Coming soon":re]})]},oe)})})]}),(p==="team"||se)&&i.jsxs("section",{className:"account-team-panel","aria-labelledby":"account-team-title",children:[i.jsxs("div",{className:"account-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Team Space"}),i.jsx("h2",{id:"account-team-title",children:se?.name||"Your shared computer workspace"})]}),se&&se.currentUserRole==="owner"&&i.jsxs("small",{children:[se.memberCount??se.members.length,"/",se.memberLimit," members"]})]}),se?i.jsxs(i.Fragment,{children:[se.currentUserRole==="owner"&&N&&i.jsxs("div",{className:"account-team-rename",children:[i.jsx("label",{htmlFor:"account-team-name",children:"Team Space name"}),i.jsxs("span",{children:[i.jsx("input",{id:"account-team-name",value:Be,onChange:oe=>Y(oe.target.value),maxLength:80,disabled:x||!!ve}),i.jsx("button",{onClick:()=>{V()},disabled:x||!!ve||!Be.trim()||Be.trim()===se.name,type:"button",children:ve==="rename"?"Saving…":"Save name"})]})]}),se.currentUserRole==="owner"&&i.jsx("ul",{className:"account-team-members",children:se.members.map(oe=>i.jsxs("li",{children:[i.jsx("span",{className:"account-member-avatar",children:(oe.displayName||oe.email).slice(0,1).toUpperCase()}),i.jsxs("span",{children:[i.jsx("strong",{children:oe.displayName||oe.email}),i.jsx("small",{children:oe.email})]}),i.jsx("em",{children:oe.role==="owner"?"Owner":"Operator"}),i.jsx("span",{className:`account-member-status status-${oe.status}`,children:oe.status}),se.currentUserRole==="owner"&&oe.role!=="owner"&&(oe.status==="invited"&&P||oe.status==="active"&&ue)&&i.jsx("button",{onClick:()=>{St(oe)},disabled:x||!!ve,type:"button","aria-label":`${oe.status==="invited"?"Cancel invitation for":"Remove"} ${oe.email}`,children:oe.status==="invited"?"Cancel":"Remove"})]},oe.id))}),se.currentUserRole==="owner"&&i.jsxs("div",{className:"account-team-invite",children:[i.jsx("label",{children:"Invite an Operator"}),z?i.jsxs("span",{className:"account-team-invite-result",children:[i.jsx("input",{"aria-label":"Team invite link",value:z.url,readOnly:!0,onFocus:oe=>oe.currentTarget.select()}),i.jsxs("button",{onClick:()=>{I()},type:"button",children:[je?i.jsx(hl,{size:16,"aria-hidden":"true"}):i.jsx(uy,{size:16,"aria-hidden":"true"}),je?"Copied":"Copy link"]}),z.expiresAt&&i.jsxs("small",{children:["Expires ",z.expiresAt]})]}):i.jsxs("span",{className:"account-team-invite-compose",children:[i.jsx("input",{type:"email",value:kt,onChange:oe=>Te(oe.target.value),placeholder:"operator@example.com","aria-label":"Operator Google account email",autoComplete:"email",disabled:x||!se.invitationsEnabled||se.currentUserRole!=="owner"||Ce}),i.jsxs("button",{className:"account-create-invite",onClick:()=>{ye()},type:"button",disabled:x||!K||!kt.trim()||!se.invitationsEnabled||se.currentUserRole!=="owner"||Ce,children:[i.jsx(dy,{size:16,"aria-hidden":"true"}),Ce?"Creating…":"Create invite link"]})]}),i.jsx("p",{children:"Share this one-time link yourself. VuvoDesk does not email the invite."})]}),se.currentUserRole==="operator"&&i.jsx("p",{className:"account-team-operator-note",children:"Operator · Wall and Control. The owner manages settings, billing, members, files, and Agents."}),qe&&i.jsx("small",{className:"account-team-error",role:"alert",children:qe}),se.currentUserRole==="operator"&&te&&i.jsx("button",{className:"account-team-leave",onClick:()=>{Ke()},disabled:x||!!ve,type:"button",children:ve==="leave"?"Leaving…":"Leave this Team Space"})]}):i.jsx("p",{className:"account-team-empty",children:"Team member management will appear here as soon as this account is connected to a Team Space."})]})]}),i.jsxs("footer",{className:"account-dialog-footer",children:[i.jsxs("span",{children:[i.jsx(my,{size:16,"aria-hidden":"true"})," Licenses belong to this VuvoDesk account, not to one computer."]}),t?i.jsxs("button",{className:"account-auth-action",onClick:()=>{W()},disabled:A,type:"button",children:[i.jsx(py,{size:16,"aria-hidden":"true"}),"Sign out"]}):i.jsxs("button",{className:"account-auth-action primary",onClick:()=>{ce()},disabled:A,type:"button",children:[i.jsx(Sl,{size:16,"aria-hidden":"true"}),"Sign in with Google"]})]})]})})}const sh=Object.freeze({plus_monthly:"ltd",plus_ltd:"ltd",pro_monthly:"pro",pro_ltd:"pro",team_monthly:"team"}),D0=new Set(["plus_monthly","pro_monthly","team_monthly"]);function L0(e){return Object.prototype.hasOwnProperty.call(sh,e)?sh[e]:null}function ch(e){return D0.has(e)}function id(e){return e==="team_monthly"}function O0(e){let t=Promise.resolve();return a=>{const r=t.then(()=>e(a),()=>e(a));return t=r.then(()=>{},()=>{}),r}}const _0=1e3;function j0({now:e=()=>Date.now(),minimumForegroundIntervalMs:t=_0}={}){let a="",r=0,c=null,u=null,p=Number.NEGATIVE_INFINITY;const h=M=>{const b=String(M||"");b!==a&&(a=b,r+=1,c=null,u=null,p=Number.NEGATIVE_INFINITY)},f=(M,b,T)=>{const A=Promise.resolve().then(()=>a===M&&r===b?T():null);return c=A,A.finally(()=>{if(c!==A||a!==M||r!==b)return;c=null;const x=u;u=null,x&&f(M,b,x).catch(()=>{})}).catch(()=>{}),A};return Object.freeze({recover:(M,b,T)=>{const A=String(M||"");if(!A||typeof T!="function"||A!==a)return Promise.resolve(null);if(c)return b==="auth"&&(u=T),c;if(b==="foreground"){const x=Number(e());if(x-p<t)return Promise.resolve(null);p=x}return f(A,r,T)},switchOwner:h,snapshot:()=>Object.freeze({ownerKey:a,inFlight:!!c,queuedAuthRecovery:!!u,lastForegroundRecoveryAt:p})})}const Il="team_invite",sd="vuvodesk.pending-team-invite",Ps=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,Zd=/^[0-9a-f]{64}$/i,cd=[],ld=[],ud=[];function Co(e){return Array.isArray(e)?e[0]||null:e||null}function wi(e,t){return new Error(String(e?.reason||t).replaceAll("-"," "))}function B0(e){if(e==null)return Number.POSITIVE_INFINITY;const t=Number(e);return Number.isFinite(t)&&t>=0?t:Number.POSITIVE_INFINITY}function lh(e,t){const a=String(e.workspace_id||"").trim(),r=String(e.workspace_kind||"").trim().toLowerCase(),c=String(e.role||"").trim().toLowerCase(),u=String(e.plan||"free").trim().toLowerCase(),p=Number(e.membership_revision||0);return!Ps.test(a)||!["personal","team"].includes(r)||!["owner","operator"].includes(c)||!["free","ltd","pro","team"].includes(u)||!Number.isSafeInteger(p)||p<1?null:{id:a,name:String(e.workspace_name||(r==="personal"?"Personal":"Team")).trim().slice(0,80),kind:r,role:c,membershipRevision:p,plan:u,entitlementStatus:String(e.entitlement_status||"free").trim().toLowerCase(),deviceLimit:B0(e.device_limit),memberLimit:Math.max(1,Number(e.member_limit||1)),commercialUse:e.commercial_use===!0,isActive:t&&e.is_active===!0}}function H0(){if(typeof window>"u")return;const e=new URL(window.location.href);e.searchParams.has(Il)&&(e.searchParams.delete(Il),window.history.replaceState(window.history.state,"",`${e.pathname}${e.search}${e.hash}`))}function W0(){if(typeof window>"u")return"";const e=String(new URL(window.location.href).searchParams.get(Il)||"").trim().toLowerCase();return Zd.test(e)?e:""}function $0(e,t=0){const a=e?.user?.id||"",r=a,[c,u]=Xt(r,cd),[p,h]=Xt(r,null),[f,k]=Xt(r,!!a),[M,b]=Xt(r,""),[T,A]=Xt(r,""),x=s.useRef(0),E=s.useRef(0),B=s.useRef(null),q=s.useRef(""),G=s.useRef(new Set),ne=s.useRef(a);ne.current=a;const re=s.useRef(null);re.current||(re.current=j0());const O=s.useRef(null);O.current||(O.current=O0(async W=>{if(!W.userId||ne.current!==W.userId)throw new Error("workspace selection owner changed");const{data:ee,error:L}=await Ct.rpc("set_livedesk_active_workspace",{p_workspace_id:W.workspaceId});if(L)throw L;const _=Co(ee);if(!_?.ok)throw wi(_,"workspace selection failed");return _}));const ie=s.useCallback(W=>O.current({userId:a,workspaceId:W}),[a]),J=s.useCallback(async(W="",ee=!1)=>{const L=x.current+1;x.current=L;const _=()=>x.current===L&&ne.current===a,K=ee?E.current+1:0;if(ee&&(E.current=K,B.current={token:K,workspaceId:W},q.current=""),!a)return q.current="",ee&&B.current?.token===K&&(B.current=null),u(r,cd),h(r,null),k(r,!1),b(r,""),null;k(r,!0),ee&&h(r,null);const ue=Bg({timeoutMs:8e3,code:"workspace-restore-timeout"});try{if(!_())return null;const{error:P}=await ue.waitFor(()=>Ct.rpc("ensure_livedesk_personal_workspace"));if(P)throw P;if(!_()||(ee&&await ue.waitFor(()=>ie(W)),!_()))return null;const{data:N,error:te}=await ue.waitFor(()=>Ct.rpc("list_livedesk_workspaces"));if(te)throw te;if(!_())return null;const we=(Array.isArray(N)?N:[]).map(Oe=>lh(Oe,!0)).filter(Oe=>!!Oe),me=W?we.find(Oe=>Oe.id===W):null,Fe=we.find(Oe=>Oe.isActive),H=we.find(Oe=>Oe.kind==="personal"&&Oe.id===a),R=me||Fe||H||we[0]||null;if(!R)throw new Error("VuvoDesk did not return an accessible workspace.");if(!R.isActive&&!ee&&await ue.waitFor(()=>ie(R.id)),!_())return null;const{data:Se,error:Ce}=await ue.waitFor(()=>Ct.rpc("get_livedesk_workspace_access",{p_workspace_id:R.id}));if(Ce)throw Ce;const Ve=Co(Se);if(!Ve||Ve.ok!==!0)throw new Error(String(Ve?.reason||"workspace access denied").replaceAll("-"," "));const qe=lh(Ve,!1);if(!qe)throw new Error("VuvoDesk returned an invalid workspace access record.");return _()?(q.current=qe.id,u(r,we.map(Oe=>({...Oe,isActive:Oe.id===qe.id}))),h(r,qe),b(r,""),k(r,!1),qe):null}catch(P){return _()&&(b(r,P instanceof Error?P.message:String(P)),k(r,!1)),null}finally{ue.dispose(),ee&&B.current?.token===K&&(B.current=null)}},[ie,h,b,k,u,r,a]),de=s.useCallback(()=>B.current?Promise.resolve(null):J(),[J]),se=s.useCallback(W=>{if(!a||W!=="initial"&&document.visibilityState==="hidden"||B.current||q.current)return Promise.resolve(null);const ee=r;return re.current.recover(ee,W,()=>ne.current!==a||B.current||q.current?null:J())},[J,r,a]),pe=s.useCallback(W=>!!W&&ne.current===a&&B.current===null&&q.current===W,[a]);s.useEffect(()=>{if(re.current.switchOwner(r),x.current+=1,u(r,cd),h(r,null),b(r,""),A(r,""),q.current="",B.current=null,!a){k(r,!1);return}return se("initial"),()=>{x.current+=1,re.current?.switchOwner("")}},[h,b,A,k,u,se,r,a]),s.useEffect(()=>{!a||t<1||se("auth")},[se,t,a]),s.useEffect(()=>{if(!a)return;const W=()=>{document.visibilityState!=="hidden"&&se("foreground")},ee=()=>W();return window.addEventListener("pageshow",W),window.addEventListener("online",W),window.addEventListener("focus",W),document.addEventListener("visibilitychange",ee),()=>{window.removeEventListener("pageshow",W),window.removeEventListener("online",W),window.removeEventListener("focus",W),document.removeEventListener("visibilitychange",ee)}},[se,a]),s.useEffect(()=>{const W=W0();if(W)try{window.sessionStorage.setItem(sd,W)}catch{}if(!a)return;let ee=W;if(!ee)try{ee=String(window.sessionStorage.getItem(sd)||"").trim().toLowerCase()}catch{}if(!Zd.test(ee))return;const L=`${a}:${ee}`;if(G.current.has(L))return;G.current.add(L),H0();try{window.sessionStorage.removeItem(sd)}catch{}let _=!1;return(async()=>{const{data:K,error:ue}=await Ct.rpc("accept_livedesk_workspace_invite",{p_invite_token:ee});if(_)return;if(ue){A(r,ue.message);return}const P=Co(K),N=String(P?.workspace_id||"").trim();if(!P?.ok||!Ps.test(N)){A(r,wi(P,"team invite could not be accepted").message);return}const te=await J(N,!0);!_&&te&&A(r,`Joined ${te.name}.`)})(),()=>{_=!0}},[J,A,r,a]),s.useEffect(()=>{if(!a||!p?.id)return;const W=p.id,ee=`${a}-${W}`.replace(/[^a-zA-Z0-9]/g,"");let L=null;const _=()=>{L===null&&(L=window.setTimeout(()=>{L=null,pe(W)&&de()},80))},K=Ct.channel(`livedesk-workspace-session-${ee}`).on("postgres_changes",{event:"*",schema:"public",table:"livedesk_workspaces",filter:`id=eq.${W}`},_).on("postgres_changes",{event:"*",schema:"public",table:"livedesk_workspace_members",filter:`workspace_id=eq.${W}`},_).subscribe();return()=>{L!==null&&window.clearTimeout(L),Ct.removeChannel(K)}},[p?.id,pe,de,a]);const ce=s.useCallback(W=>Ps.test(String(W||"").trim())?J(W,!0):Promise.reject(new Error("Choose a valid VuvoDesk workspace.")),[J]);return{workspaces:c,activeWorkspace:p,loading:f,error:M,inviteNotice:T,refresh:de,selectWorkspace:ce,isWorkspaceActionCurrent:pe}}function V0(e,t,a,r,c){const u=e?.user?.id||"",p=t?.kind==="team"?t.id:"",h=t?.membershipRevision||0,f=`${u}
|
|
178
178
|
${p}
|
|
179
|
-
${h}`,[k,M]=Xt(f,
|
|
180
|
-
${p}`,ne=s.useRef(G);ne.current=G;const ae=s.useCallback((pe,se)=>{if(ne.current!==pe||!c(se))throw new Error("The active VuvoDesk workspace changed. Please try again in the current workspace.")},[c]),O=s.useCallback(async()=>{const pe=Q.current+1;Q.current=pe;const se=()=>Q.current===pe;if(!u||!p){M(f,cd),T(f,ld),x(f,!1),H(f,"");return}x(f,!0);try{const W=t?.role==="owner"?Ct.rpc("list_livedesk_workspace_members",{p_workspace_id:p}):Promise.resolve({data:[],error:null}),re=t?.role==="owner"?Ct.rpc("list_livedesk_workspace_invites",{p_workspace_id:p}):Promise.resolve({data:[],error:null}),[L,_]=await Promise.all([W,re]);if(!se())return;if(L.error)throw L.error;if(_.error)throw _.error;M(f,(Array.isArray(L.data)?L.data:[]).map(q=>({id:String(q.user_id||""),email:String(q.email||""),displayName:String(q.display_name||""),role:String(q.role||"")==="owner"?"owner":"operator",joinedAt:String(q.joined_at||"")})).filter(q=>Ps.test(q.id))),T(f,(Array.isArray(_.data)?_.data:[]).map(q=>({id:String(q.invite_id||""),email:String(q.email||""),role:"operator",createdAt:String(q.created_at||""),expiresAt:String(q.expires_at||"")})).filter(q=>Ps.test(q.id))),H(f,""),x(f,!1)}catch(W){if(!se())return;H(f,W instanceof Error?W.message:String(W)),x(f,!1)}},[t?.role,f,H,T,x,M,u,p]);s.useEffect(()=>(Q.current+=1,M(f,cd),T(f,ld),H(f,""),O(),()=>{Q.current+=1}),[f,H,T,M,O,h]);const te=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can create invitations.");const se=G,W=String(pe||"").trim().toLowerCase();if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(W))throw new Error("Enter the Google account email to invite.");const{data:re,error:L}=await Ct.rpc("invite_livedesk_workspace_member",{p_workspace_id:p,p_email:W,p_role:"operator"});if(ae(se,p),L)throw L;const _=Co(re),q=String(_?.invite_token||"").trim().toLowerCase();if(!_?.ok||!Jd.test(q))throw wi(_,"team invite creation failed");const ue=new URL("/app",window.location.origin);return ue.searchParams.set(Il,q),ae(se,p),await Promise.all([O(),r()]),{url:ue.toString(),expiresAt:_.expires_at}},[t?.role,ae,O,r,p,G]),Z=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can remove members.");const se=G,{data:W,error:re}=await Ct.rpc("remove_livedesk_workspace_member",{p_workspace_id:p,p_user_id:pe});if(ae(se,p),re)throw re;const L=Co(W);if(!L?.ok)throw wi(L,"team member removal failed");let _=!0;try{await ze(`/api/remote/workspace/members/${encodeURIComponent(pe)}/revoke`,{method:"POST",body:JSON.stringify({workspaceId:p})},a)}catch{_=!1}return ae(se,p),await Promise.all([O(),r()]),{revokedImmediately:_}},[t?.role,ae,a,O,r,p,G]),me=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can revoke invitations.");const se=G,{data:W,error:re}=await Ct.rpc("revoke_livedesk_workspace_invite",{p_workspace_id:p,p_invite_id:pe});if(ae(se,p),re)throw re;const L=Co(W);if(!L?.ok)throw wi(L,"team invite revocation failed");await Promise.all([O(),r()])},[t?.role,ae,O,r,p,G]),le=s.useCallback(async()=>{if(!p||t?.role!=="operator")throw new Error("Only an Operator can leave this Team Space.");const pe=G,{data:se,error:W}=await Ct.rpc("leave_livedesk_workspace",{p_workspace_id:p});if(ae(pe,p),W)throw W;const re=Co(se);if(!re?.ok)throw wi(re,"leaving team workspace failed")},[t?.role,ae,p,G]);return s.useMemo(()=>({members:k,invites:b,loading:I,error:E,refresh:O,createInvite:te,removeMember:Z,revokeInvite:me,leaveWorkspace:le}),[te,E,b,le,I,k,O,Z,me])}function Qg({state:e}){return e==="ok"?i.jsx(Cn,{size:15,"aria-hidden":"true"}):i.jsx(py,{size:15,"aria-hidden":"true"})}function uh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button ${e?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(dy,{size:18,"aria-hidden":"true"})})}function dh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button debug-status-button ${e?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(my,{size:18,"aria-hidden":"true"})})}function mh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button hub-status-button ${e?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Si,{size:18,"aria-hidden":"true"})})}function Xg({items:e,mode:t="remote"}){return i.jsx("span",{className:`remote-status-lines mode-${t}`,role:"status","aria-label":t==="debug"?"Debug status":"Remote status",onPointerDown:t==="debug"?a=>a.stopPropagation():void 0,onClick:t==="debug"?a=>a.stopPropagation():void 0,onDoubleClick:t==="debug"?a=>a.stopPropagation():void 0,children:e.map(a=>i.jsxs("span",{className:`remote-status-line state-${a.state}`,title:a.detail,children:[i.jsx(Qg,{state:a.state}),i.jsxs("span",{children:[i.jsx("strong",{children:a.label}),i.jsx("small",{children:a.detail})]})]},a.id))})}function H0({items:e,collectedAt:t,onClose:a}){return i.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[i.jsxs("header",{children:[i.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:i.jsx(Si,{size:19})}),i.jsxs("span",{children:[i.jsx("small",{children:"Hub measurements"}),i.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),i.jsx("button",{type:"button",onClick:a,title:"Close Hub status","aria-label":"Close Hub status",children:i.jsx(Ma,{size:17})})]}),i.jsx("p",{children:"VuvoDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),i.jsx("div",{className:"remote-status-dialog-list",children:e.map(r=>i.jsxs("article",{className:`remote-status-dialog-row state-${r.state}`,children:[i.jsx(Qg,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))}),i.jsxs("footer",{children:["Checked ",new Date(t).toLocaleTimeString()]})]})}async function W0(e,t={}){const a=e.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),r=Math.max(320,t.maxWidth||1920),c=Math.max(180,t.maxHeight||1080),u=a.length<=1?1:a.length<=4?2:a.length<=9?3:4,p=Math.max(1,Math.ceil(Math.max(1,a.length)/u)),h=Math.floor(r/u),f=Math.floor(c/p),k=document.createElement("canvas");k.width=Math.max(320,h*u),k.height=Math.max(180,f*p);const M=k.getContext("2d",{alpha:!1});if(!M)return k;M.fillStyle="#0b1220",M.fillRect(0,0,k.width,k.height),M.font="600 14px system-ui, sans-serif",M.textBaseline="bottom";for(let b=0;b<a.length;b+=1){const T=a[b],I=b%u,x=Math.floor(b/u),E=I*h,H=x*f,Q=T.canvas,G=Math.min(h/Q.width,f/Q.height),ne=Math.max(1,Math.floor(Q.width*G)),ae=Math.max(1,Math.floor(Q.height*G)),O=E+Math.floor((h-ne)/2),te=H+Math.floor((f-ae)/2);M.drawImage(Q,O,te,ne,ae),t.includeLabels!==!1&&(M.fillStyle="rgba(4, 10, 20, .74)",M.fillRect(E,H+f-28,h,28),M.fillStyle="#f8fafc",M.fillText(T.label,E+9,H+f-9))}return k}function $0(e){return e?.signature||"none"}function V0(e){return e?.label||"No capture target"}function ph(e){return{...e,deviceIds:[...e.deviceIds],sourceCanvas:e.sourceCanvas||null}}function Jg(e){return{type:e.type,deviceIds:e.deviceIds,monitorIndex:e.monitorIndex,label:e.label}}async function Zg(e){try{return(await e.json()).error||`${e.status} ${e.statusText}`}catch{return`${e.status} ${e.statusText}`}}async function eb(e,t,a){const r=encodeURIComponent(JSON.stringify({kind:t.kind,fileName:t.fileName,mimeType:e.type||"application/octet-stream",durationMs:t.durationMs,target:Jg(t.target)})),c=await Yh(`/api/captures?metadata=${r}`,{method:"POST",headers:{"Content-Type":e.type||"application/octet-stream"},body:e},a);if(!c.ok)throw new Error(await Zg(c));return await c.json()}async function z0(e,t){return await ze("/api/capture-sessions",{method:"POST",body:JSON.stringify({...e,target:Jg(e.target)})},t)}async function U0(e,t,a,r){const c=await Yh(`/api/capture-sessions/${encodeURIComponent(e)}/chunks/${t}`,{method:"PUT",headers:{"Content-Type":a.type||"application/octet-stream"},body:a},r);if(!c.ok)throw new Error(await Zg(c));return await c.json()}async function q0(e,t,a){return await ze(`/api/capture-sessions/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:t})},a)}async function fh(e,t){await ze(`/api/capture-sessions/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function ox(e){return await ze("/api/captures",void 0,e)}function ix(e,t){return`${Kh(t)}/api/captures/${encodeURIComponent(e)}/content`}async function sx(e,t){return await ze(`/api/captures/${encodeURIComponent(e)}`,{method:"DELETE"},t)}function G0(){const e=new Date,t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}_${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function K0(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function Y0(e){return`VuvoDesk_${e.type==="wall"||e.type==="selection"?"Wall":`${K0(e.label)}_Monitor-${Number(e.monitorIndex||0)+1}`}_${G0()}.png`}async function Q0(e,t,a){const r=await new Promise((u,p)=>e.toBlob(h=>h?u(h):p(new Error("Screenshot could not be encoded.")),"image/png")),c=await eb(r,{kind:"screenshot",fileName:Y0(t),target:t},a);try{await navigator.clipboard.write([new ClipboardItem({"image/png":r})])}catch{}return c.capture}function tb(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(t=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(t))||""}function X0(e,t){const a=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),r=t.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return e==="timelapse"?`VuvoDesk_Timelapse_${r}_${a}.webm`:`VuvoDesk_Recording_${r}_${a}.webm`}async function nb(e){if(typeof MediaRecorder>"u"||typeof e.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const t=tb();if(!t)throw new Error("This browser does not support WebM recording.");const a=e.kind||"recording",r=await z0({kind:a,fileName:X0(a,e.target),mimeType:t,target:e.target},e.hubUrl),c=e.canvas.captureStream(e.frameRequests?0:e.fps),u=new MediaRecorder(c,{mimeType:t,videoBitsPerSecond:a==="timelapse"?2e6:4e6}),p=performance.now();let h=0,f=!1,k=null,M=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const T=h++;M=M.then(()=>U0(r.sessionId,T,b.data,e.hubUrl).then(()=>{})).catch(I=>{k=k||(I instanceof Error?I:new Error(String(I))),e.onError?.(k)})},u.onerror=()=>{k=new Error("Video recording stopped unexpectedly."),e.onError?.(k)},u.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!f){if(f=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),c.getTracks().forEach(b=>b.stop()),await M,k)throw await fh(r.sessionId,e.hubUrl).catch(()=>{}),k;await q0(r.sessionId,Math.max(0,performance.now()-p),e.hubUrl)}},cancel:async()=>{f||(f=!0,u.stop(),c.getTracks().forEach(b=>b.stop()),await fh(r.sessionId,e.hubUrl).catch(()=>{}))}}}class J0{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(t,a){if(this.recorder&&this.targetSignature===a.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof t.captureStream!="function")throw new Error("This browser does not support Last 30s.");const r=tb();if(!r)throw new Error("This browser does not support WebM recording.");this.targetSignature=a.signature,this.stream=t.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:r,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const u=performance.now();for(this.segments.push({blob:c.data,at:u}),this.totalBytes+=c.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const p=this.segments.shift();this.totalBytes-=p.blob.size}},this.recorder.start(1e3)}stop(){const t=this.recorder;this.recorder=null,t&&t.state!=="inactive"&&(t.ondataavailable=null,t.stop()),this.stream?.getTracks().forEach(a=>a.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(t,a){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const r=new Blob(this.segments.map(p=>p.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`VuvoDesk_Last30s_${t.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 eb(r,{kind:"last-30s",fileName:u,target:t,durationMs:Math.min(3e4,this.segments.length*1e3)},a)}}async function Z0(e,t,a,r,c){const u=await nb({canvas:e,target:t,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:r,onError:c});u.requestFrame?.();const p=window.setInterval(()=>u.requestFrame?.(),Math.max(5,a)*1e3);return{stop:async()=>{window.clearInterval(p),await u.stop()},cancel:async()=>{window.clearInterval(p),await u.cancel()}}}const rb="livedesk.captureSettings";function ek(){const e={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const t=JSON.parse(localStorage.getItem(rb)||"null");return{...e,...t&&typeof t=="object"?t:{}}}catch{return e}}function tk(e){const[t,a]=s.useState(ek),[r,c]=s.useState(0),[u,p]=s.useState(0),[h,f]=s.useState(0),[k,M]=s.useState(!1),b=s.useRef(void 0),T=s.useRef(!1),I=s.useRef(""),x=s.useRef(null),E=s.useRef(null),H=s.useRef(null),Q=s.useRef(null),G=s.useRef(new J0),ne=e.sourceRegistry.resolveCurrentTarget(),ae=$0(ne),O=V0(ne),te=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;s.useEffect(()=>{if(localStorage.setItem(rb,JSON.stringify(t)),!e.remoteSettingsEnabled||!e.hubUrl||!T.current)return;const P=JSON.stringify(t);P!==I.current&&(I.current=P,ze("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:t.rollingEnabled,recordingQuality:t.recordingQuality,timelapseIntervalSeconds:t.timelapseIntervalSeconds,includeRemoteCursor:t.includeRemoteCursor}})},e.hubUrl).then(F=>{b.current=Number(F.revision||b.current||0)}).catch(()=>{}))},[e.hubUrl,e.remoteSettingsEnabled,t]),s.useEffect(()=>{if(!e.remoteSettingsEnabled||!e.hubUrl){T.current=!1;return}let P=!0;return ze("/api/settings",void 0,e.hubUrl).then(F=>{if(!P)return;const ee=F.settings?.filesAudio||{},Se=typeof ee.rollingBufferEnabled=="boolean"?ee.rollingBufferEnabled:t.rollingEnabled,de=ee.recordingQuality==="high"?"high":"standard",Fe=[5,10,30,60].includes(Number(ee.timelapseIntervalSeconds))?Number(ee.timelapseIntervalSeconds):t.timelapseIntervalSeconds,j=typeof ee.includeRemoteCursor=="boolean"?ee.includeRemoteCursor:t.includeRemoteCursor,R={rollingEnabled:Se,recordingQuality:de,timelapseIntervalSeconds:Fe,includeRemoteCursor:j};b.current=Number(F.revision||0),I.current=JSON.stringify(R),T.current=!0,a(R)}).catch(()=>{T.current=!0}),()=>{P=!1}},[e.hubUrl,e.remoteSettingsEnabled]);const Z=s.useCallback(async P=>{if(P.sourceCanvas&&P.sourceCanvas.width>0&&P.sourceCanvas.height>0)return{target:ph(P),canvas:P.sourceCanvas,cleanup:()=>{}};const F=await e.sourceRegistry.composeWall(P.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let ee=!1;const Se=window.setInterval(async()=>{if(ee)return;const de=await e.sourceRegistry.composeWall(P.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!de||ee||((F.width!==de.width||F.height!==de.height)&&(F.width=de.width,F.height=de.height),F.getContext("2d")?.drawImage(de,0,0))},100);return{target:ph(P),canvas:F,cleanup:()=>{ee=!0,window.clearInterval(Se)}}},[e.sourceRegistry]);s.useEffect(()=>{const P=G.current;if(!t.rollingEnabled||!ne||!te){P.stop(),f(0);return}let F=!1,ee=null;return(async()=>{try{if(ee=await Z(ne),F)return;await P.start(ee.canvas,ee.target);const de=window.setInterval(()=>f(Math.round(P.seconds)),500),Fe=()=>{window.clearInterval(de),ee?.cleanup()};P.__cleanup=Fe}catch(de){F||e.onToast(de instanceof Error?de.message:String(de))}})(),()=>{F=!0,P.stop(),P.__cleanup?.(),P.__cleanup=void 0,f(0)}},[Z,e.onToast,t.rollingEnabled,ae,te]);const me=s.useCallback(P=>a(F=>({...F,rollingEnabled:P})),[]),le=s.useCallback(P=>a(F=>({...F,recordingQuality:P})),[]),pe=s.useCallback(P=>a(F=>({...F,timelapseIntervalSeconds:P})),[]),se=s.useCallback(async()=>{const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");M(!0);let F=null;try{F=await Z(P),await Q0(F.canvas,F.target,e.hubUrl),e.onToast("Screenshot saved")}finally{F?.cleanup(),M(!1)}},[Z,e.hubUrl,e.onToast,e.sourceRegistry]),W=s.useCallback(async()=>{if(H.current)throw new Error("Stop the timelapse before recording.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");const F=await Z(P),ee=await nb({canvas:F.canvas,target:F.target,fps:P.type==="control"?30:15,hubUrl:e.hubUrl,onError:Se=>e.onToast(Se.message)});E.current=F.cleanup,x.current=ee,c(Date.now()),e.onToast("Recording started")},[Z,e.hubUrl,e.onToast,e.sourceRegistry]),re=s.useCallback(async()=>{const P=x.current;if(P){M(!0);try{await P.stop(),e.onToast("Recording saved")}finally{x.current=null,E.current?.(),E.current=null,c(0),M(!1)}}},[e.onToast]),L=s.useCallback(async()=>{if(x.current||H.current)throw new Error("Last 30s is unavailable during a recording.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");M(!0);try{await G.current.save(P,e.hubUrl),e.onToast("Last 30 seconds saved")}finally{M(!1)}},[e.hubUrl,e.onToast,e.sourceRegistry]),_=s.useCallback(async()=>{if(x.current)throw new Error("Stop the recording before starting a timelapse.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");const F=await Z(P),ee=await Z0(F.canvas,F.target,t.timelapseIntervalSeconds,e.hubUrl,Se=>e.onToast(Se.message));Q.current=F.cleanup,H.current=ee,p(Date.now()),e.onToast("Timelapse started")},[Z,e.hubUrl,e.onToast,e.sourceRegistry,t.timelapseIntervalSeconds]),q=s.useCallback(async()=>{const P=H.current;if(P){M(!0);try{await P.stop(),e.onToast("Timelapse saved")}finally{H.current=null,Q.current?.(),Q.current=null,p(0),M(!1)}}},[e.onToast]);return s.useEffect(()=>{const P=F=>{!x.current&&!H.current||(F.preventDefault(),F.returnValue="")};return window.addEventListener("beforeunload",P),()=>window.removeEventListener("beforeunload",P)},[]),s.useEffect(()=>()=>{G.current.stop(),x.current?.cancel(),H.current?.cancel(),E.current?.(),Q.current?.()},[]),{state:s.useMemo(()=>({recording:!!x.current,recordingStartedAt:r,timelapse:!!H.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:t.rollingEnabled,busy:k,targetLabel:O}),[h,k,r,t.rollingEnabled,O,u]),settings:t,videoSupported:te,targetKey:ae,setRollingEnabled:me,setRecordingQuality:le,setTimelapseInterval:pe,takeScreenshot:se,startRecording:W,stopRecording:re,saveLast30Seconds:L,startTimelapse:_,stopTimelapse:q}}function nk(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const e=window.navigator.userAgent,t=window.navigator.standalone,a=GC(e,window.navigator.platform,window.navigator.maxTouchPoints,t),r=/Android/i.test(e),c=a&&/CriOS/i.test(e),u=a&&/Safari/i.test(e)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(e);return{isIos:a,isAndroid:r,isSafari:u,browserName:c?"Chrome":u?"Safari":"browser"}}const hh=s.lazy(()=>mr(()=>import("./AgentsPage-AoFB_KD4.js"),__vite__mapDeps([0,1,2,3,4,5])).then(e=>({default:e.AgentsPage}))),rk=s.lazy(()=>mr(()=>import("./ShareFilesPage-rESjZP8s.js"),__vite__mapDeps([6,1,2,3,4,7])).then(e=>({default:e.ShareFilesPage}))),An="".trim().toLowerCase()==="true",Sa="".trim().toLowerCase()==="true",Jr="".trim().toLowerCase()==="true",ak=s.lazy(()=>mr(()=>import("./SupportPage-B90rx4D0.js"),__vite__mapDeps([8,1,2,3,4,9,10,11])).then(e=>({default:e.SupportPage}))),ok=s.lazy(()=>mr(()=>import("./SettingsPage-DLhQYnES.js"),__vite__mapDeps([12,1,2,3,4])).then(e=>({default:e.SettingsPage}))),ik=s.lazy(()=>mr(()=>import("./SettingsTabs-C1ovcXzw.js"),__vite__mapDeps([13,1,2,3,4])).then(e=>({default:e.PinSettingsTab}))),sk=s.lazy(()=>mr(()=>import("./AgentSettingsTab-SlFWbGlY.js"),__vite__mapDeps([14,1,2,3,4])).then(e=>({default:e.AgentSettingsTab}))),ck=s.lazy(()=>mr(()=>import("./DesktopUpdatePanel-BDIHhw5J.js"),__vite__mapDeps([15,1,2,3,4])).then(e=>({default:e.DesktopUpdatePanel}))),lk=s.lazy(()=>mr(()=>import("./CaptureGallery-bgLFx77c.js"),__vite__mapDeps([16,1,2,3,4,9,10])).then(e=>({default:e.CaptureGallery})));function hs({children:e}){return i.jsx(s.Suspense,{fallback:i.jsx("div",{className:"deferred-feature-loading",role:"status",children:"Loading…"}),children:e})}const uk=120,dk=999,ab="livedesk.remoteDirectory",Bd="livedesk.localHubAccessEnabled",mk="livedesk.streamSettings",pk=18,fk="livedesk.controlStreamSettings",hk=10,ob="livedesk.wallCadence",ib="livedesk.wallViewScale",sb="livedesk.mobileWallStatsVisible",gk=1e3,cb="livedesk.wallMonitorSelections",lb=2,ud=512*1024,bk=250,vk=15e3,yk=!1;function wk(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(`${navigator.platform} ${navigator.userAgent}`)}function Sk(e){let t="";for(let a=0;a<e.length;a+=32*1024)t+=String.fromCharCode(...e.subarray(a,Math.min(e.length,a+32*1024)));return window.btoa(t)}function gh(e){const t=window.atob(String(e||"")),a=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)a[r]=t.charCodeAt(r);return a}async function ub(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),a=>a.toString(16).padStart(2,"0")).join("")}async function Ck(e){const t=navigator.clipboard;let a="text",r="clipboard.txt",c="text/plain",u=null;if(typeof t?.read=="function"){const h=await t.read(),f=h.find(k=>k.types.includes("image/png"));if(f){const k=await f.getType("image/png");a="image",r="clipboard.png",c="image/png",u=new Uint8Array(await k.arrayBuffer())}else{const k=h.find(M=>M.types.includes("text/plain"));if(k){const M=await k.getType("text/plain");u=new TextEncoder().encode(await M.text())}}}if(!u&&typeof t?.readText=="function"&&(u=new TextEncoder().encode(await t.readText())),!u)throw new Error("The browser did not provide text or a PNG image from the clipboard.");return{manifest:Nd({operationId:e,contentKind:a,totalBytes:u.byteLength,items:[{itemIndex:0,kind:a,name:r,mimeType:c,size:u.byteLength,lastModified:Date.now(),sha256:await ub(u),storageName:"item-0.bin"}]},e),payloads:[u]}}async function kk(e){const{manifest:t,payloads:a}=e,r=a[0];if(!r||t.items.length!==1)throw new Error("clipboard-browser-snapshot-invalid");if(t.contentKind==="text"){await navigator.clipboard.writeText(new TextDecoder().decode(r));return}if(t.contentKind==="image"&&typeof ClipboardItem<"u"){await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([r],{type:"image/png"})})]);return}throw new Error("Multiple files require the VuvoDesk desktop app.")}"".trim();"".trim();const Mk=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),xk=1e3/60,dd=1500,Rk=650,Ak=1800,Ik=650,Tk=2500,md=1500,bh=15e3,vh=120,Pk=.72,db=6,Ek=640*360,Nk=8;function Fk(e){let t=2166136261;for(let a=0;a<e.length;a+=1)t=Math.imul(t^e.charCodeAt(a),16777619);return(t>>>0)%db}const yh=100,wh=20,Dk=6e4,Lk=6e4,Sh=240,Ok=1024,_k=640,jk=360,Ch="Connected VuvoDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",ul="VuvoDesk is replacing the Hub and verifying the requested version.",dl=5*6e4,Bk=5e3,kh=2e3,Hk=8e3;function Mh(e,t){return`${e}:${t.deviceId}:${t.completedAt||t.candidateSessionId||t.commandId||"completed"}`}function bo({label:e,tooltip:t,disabled:a=!1,active:r=!1,danger:c=!1,pressed:u,onClick:p,children:h}){return i.jsx("span",{className:`manual-action-tooltip ${a?"disabled":""}`.trim(),"data-tooltip":t,children:i.jsx("button",{className:`manual-action ${r?"active":""} ${c?"danger":""}`.trim(),onClick:p,disabled:a,"aria-label":e,"aria-pressed":u,type:"button",children:h})})}function Wk(e,t){if(t.deviceId!==e.deviceId)return!1;const a=Number(t.browserReceivedEpochMs);if(!Number.isFinite(a)||a<e.startedAtEpochMs)return!1;const r=Number(t.monitorIndex);if(Number.isFinite(r)&&Math.floor(r)!==e.monitorIndex)return!1;const c=String(t.frameMode||t.mode||"").trim().toLowerCase();return!c||c===e.frameMode}const $k={"mode3-h264-hw":30};function xh(e,t){const a=p=>{const f=String(p||"").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(!f)return null;const k=f[4]?f[4].split(".").map(M=>/^\d+$/.test(M)?M.length>1&&M.startsWith("0")?Number.NaN:Number(M):M):[];return k.some(M=>typeof M=="number"&&!Number.isFinite(M))?null:{core:[Number(f[1]),Number(f[2]),Number(f[3])],prerelease:k}},r=a(e),c=a(t);if(!r||!c)return!1;for(let p=0;p<3;p+=1){if(r.core[p]>c.core[p])return!0;if(r.core[p]<c.core[p])return!1}if(r.prerelease.length===0||c.prerelease.length===0)return r.prerelease.length===0;const u=Math.max(r.prerelease.length,c.prerelease.length);for(let p=0;p<u;p+=1){const h=r.prerelease[p],f=c.prerelease[p];if(h===void 0||f===void 0)return f===void 0;if(h!==f){if(typeof h=="number"&&typeof f=="number")return h>f;if(typeof h=="number")return!1;if(typeof f=="number"||h>f)return!0;if(h<f)return!1}}return!0}const Vk=1024;function ft(e,t){return`${e}:${t}`}function er(e){return[e.deviceId,e.sessionId||"",e.streamId||"",e.commandId||"",Number(e.captureGeneration||0),Number(e.monitorIndex??-1),e.streamPurpose||""].join("|")}const zk={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:$k["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},Uk={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Rh={maxWidth:3840,maxHeight:2160};function gs(e,t){if(e.length===0)return 0;const a=[...e].sort((c,u)=>c-u),r=Math.max(0,Math.min(a.length-1,Math.ceil(a.length*t)-1));return a[r]}function mb(e,t){e.push(t),e.length>Sh&&e.splice(0,e.length-Sh)}function ml(e,t){e.sampleFrames=0,e.sampleStartedAt=t,e.intervalCount=0,e.intervalSumMs=0,e.minIntervalMs=Number.POSITIVE_INFINITY,e.maxIntervalMs=0,e.intervalSamplesMs.length=0,e.seqGapCount=0,e.maxSeqGap=0}function Ah(e,t,a){if(e.lastAt!==void 0){const r=Math.max(0,t-e.lastAt);e.intervalCount+=1,e.intervalSumMs+=r,e.minIntervalMs=Math.min(e.minIntervalMs,r),e.maxIntervalMs=Math.max(e.maxIntervalMs,r),mb(e.intervalSamplesMs,r)}if(e.lastFrameSeq!==void 0){const r=a-e.lastFrameSeq;r!==1&&(e.seqGapCount+=1,e.maxSeqGap=Math.max(e.maxSeqGap,Math.abs(r)))}e.lastAt=t,e.lastFrameSeq=a}function Ih(e){return!e||e.intervalCount<=0?"waiting":`${Math.round(e.averageIntervalMs)}ms avg / p95 ${Math.round(e.p95IntervalMs)}ms / max ${Math.round(e.maxIntervalMs)}ms`}function Th(e){return!e||e.seqGapCount<=0?"none":`${e.seqGapCount} gaps / max ${e.maxSeqGap}`}function qk(e){return Number.isFinite(e)?String(e):"Unlimited"}const pb=[1,2,5,8,12,20,30],Ph={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},ur={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:wt.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:wt.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},pd=2200,Gk=2500,Kk=8e3,Yk=3500,Eh=7e3,Qk=2,Xk=2500,Nh=7e3,Fh=2600,Jk=4200,Zk=750,eM=2,Dh=2500,Lh=4200,Oh=2200;function _h(e,t){return Math.min(3e4,e*2**Math.min(3,Math.max(0,t)))}function vi(e,t){const a=e.capabilities?.[t];return typeof a=="boolean"?a:/^(1|true|yes|on)$/i.test(String(a||"").trim())}function Qt(e){return e.deviceName||e.hostname||e.deviceId}function tM(){return"npx -y --prefer-online livedesk@latest client"}function nM(){return"npx -y --prefer-online livedesk@latest"}function rM(){try{return localStorage.getItem(ab)||""}catch{return""}}function aM(){try{return localStorage.getItem(Bd)==="1"}catch{return!1}}function hi(e){try{e?localStorage.setItem(Bd,"1"):localStorage.removeItem(Bd)}catch{}}function dr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ka(e){const t=dr(e.status),a=dr(t.screens),r=dr(e.capabilities),c=dr(e.latestLiveFrame),u=dr(e.activeLiveStream),h=[t.monitorCount,t.screenCount,a.count,r.monitorCount,r.screenCount,c.monitorCount,u.monitorCount,Array.isArray(a.displays)?a.displays.length:0,Array.isArray(t.displays)?t.displays.length:0,Array.isArray(t.monitors)?t.monitors.length:0].map(Number).filter(f=>Number.isFinite(f)&&f>0).map(f=>Math.max(1,Math.min(64,Math.floor(f))));return h.length>0?Math.max(...h):1}function Ia(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.floor(t):0}function fb(e){const t=dr(e.status),r=[dr(t.screens).displays,t.displays,t.monitors];for(const c of r)if(!(!Array.isArray(c)||c.length===0))return c.map(u=>dr(u));return[]}function Zd(e,t){const a=fb(e),r=a.find(f=>Number(f.index)===t)||a[t]||a[0]||{},c=Ia(r.width),u=Ia(r.height),p=[r.name,r.displayName,r.deviceName,r.id].find(f=>typeof f=="string"&&f.trim()),h=typeof p=="string"?p.trim():`Display ${t+1}`;return{index:t,name:h,width:c,height:u,primary:r.primary===!0||r.isPrimary===!0}}function oM(e){const t=ka(e);return Array.from({length:t},(a,r)=>Zd(e,r))}function iM(e){const t=fb(e);if(t.length===0)return"";const a=t.map((r,c)=>{const u=Number(r.index),p=[r.name,r.displayName,r.deviceName,r.id].find(f=>typeof f=="string"&&f.trim()),h=f=>{const k=Number(f);return Number.isFinite(k)?k:null};return[Number.isFinite(u)?Math.floor(u):c,typeof p=="string"?p.trim().toLowerCase():"",h(r.left),h(r.top),h(r.width),h(r.height),r.primary===!0||r.isPrimary===!0]}).sort((r,c)=>r[0]-c[0]);return JSON.stringify(a)}function sM(e){const t=[e.name||`Display ${e.index+1}`];return e.width>0&&e.height>0&&t.push(`${e.width}x${e.height}`),e.primary&&t.push("Primary"),t.join(" - ")}function hb(e,t){const a=Zd(e,t);if(a.width>0&&a.height>0)return{width:a.width,height:a.height};const r=dr(e.status),c=Ia(r.screenWidth||r.width),u=Ia(r.screenHeight||r.height);return c>0&&u>0?{width:c,height:u}:null}function gb(e){if(!e)return null;const t=Ia(e.sourceWidth)||Ia(e.width),a=Ia(e.sourceHeight)||Ia(e.height);return t>0&&a>0?{width:t,height:a}:null}function cM(e,t,a){const u=((typeof t?.monitorIndex=="number"?ys(t.monitorIndex,Math.max(1,t.monitorCount||1)):a)===a?gb(t):null)||hb(e,a);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const pl=16/9;function ys(e,t){const a=Math.max(1,Math.min(64,Math.floor(Number(t)||1))),r=Math.floor(Number(e));return Number.isFinite(r)?Math.max(0,Math.min(a-1,r)):0}function _n(e,t){return jC(t,ka(e),e.platform)}function lM(){try{const e=localStorage.getItem(cb);if(!e)return{selections:{},topologyFingerprints:{}};const t=JSON.parse(e),a=t&&typeof t=="object"&&!Array.isArray(t)?t.selections:void 0;if(Number(t?.version)!==lb||!a||typeof a!="object"||Array.isArray(a))return{selections:{},topologyFingerprints:{}};const r={},c={};for(const[u,p]of Object.entries(a)){const h=u.trim(),f=dr(p),k=f.monitorIndex,M=Math.floor(Number(k));if(!h||!Number.isFinite(M))continue;r[h]=Math.max(0,Math.min(63,M));const b=typeof f.topologyFingerprint=="string"?f.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:r,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function uM(e,t){try{const a=Object.fromEntries(Object.entries(e).map(([r,c])=>[r,{monitorIndex:c,topologyFingerprint:t[r]||""}]));localStorage.setItem(cb,JSON.stringify({version:lb,selections:a}))}catch{}}function dM(){return{...zk}}function mM(e){try{localStorage.setItem(mk,JSON.stringify({...e,version:pk}))}catch{}}function pM(){return{...Uk}}function fM(e){try{localStorage.setItem(fk,JSON.stringify({...e,version:hk}))}catch{}}function hM(){try{return localStorage.getItem(ob)==="slow"?"slow":"fast"}catch{return"fast"}}function gM(e){try{localStorage.setItem(ob,e)}catch{}}function bM(){try{return localStorage.getItem(sb)==="true"}catch{return!1}}function vM(e){try{localStorage.setItem(sb,String(e))}catch{}}function yM(){try{const e=localStorage.getItem(ib);return e===null?ea:Mi(Number(e))}catch{return ea}}function wM(e){try{localStorage.setItem(ib,String(Mi(e)))}catch{}}function fd(e,t){return e.length!==t.length?!1:e.every((a,r)=>a===t[r])}function hd(e){return[...new Set(e.filter(Boolean))].sort()}function SM(e){return ur.fallbackVisibleCounts[e]||ur.fallbackVisibleCounts.large}function jh(e,t,a){if(e.frameMode==="mode4-h264-atlas")return e.atlasTileSizeMode==="auto"?t==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:e.atlasTileWidth,maxHeight:e.atlasTileHeight};if(!e.adaptiveSizeByWall)return{maxWidth:e.maxWidth,maxHeight:e.maxHeight};const r=Ph[t]||Ph.large;return{maxWidth:Math.min(e.maxWidth,r.maxWidth),maxHeight:Math.min(e.maxHeight,r.maxHeight)}}function CM(e,t=ur.minFps){const a=[...pb].sort((c,u)=>c-u),r=Math.max(t,Math.floor(e/2));return[...a].reverse().find(c=>c<e&&c>=t)||r}function kM(e,t){return[...pb].sort((r,c)=>r-c).find(r=>r>e&&r<=t)||t}function ws(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let a=e,r=0;for(;a>=1024&&r<t.length-1;)a/=1024,r+=1;const c=r===0||a>=100?0:1;return`${a.toFixed(c)} ${t[r]}`}function Bh(e){if(!Number.isFinite(e)||!e||e<=0)return"0GB";const t=1024**4,a=1024**3;return e>=t?`${Math.max(1,Math.round(e/t))}TB`:`${Math.max(1,Math.round(e/a))}GB`}function gd(e,t){if(!Number.isFinite(e)||!e||e<=0)return"not reported";const a=Math.max(0,e-Math.max(0,Number(t||0)));return`${Bh(a)} / ${Bh(e)}`}function MM(e){const t=new Uint8Array(e),a=32768;let r="";for(let c=0;c<t.length;c+=a){const u=t.subarray(c,c+a);r+=String.fromCharCode(...u)}return btoa(r)}function Hh(e){return Array.from(e).filter(t=>t.size>=0).map(t=>{const a=t.webkitRelativePath||t.name;return{file:t,relativePath:a,fingerprint:`${t.size}:${t.lastModified}`}})}function bs(e){return e===1?"middle":e===2?"right":"left"}function Wh(e,...t){for(const a of t){const r=e?.[a];if(typeof r=="string"&&r.trim())return r.trim()}return""}function $h(e){const t=Number(e);return Number.isInteger(t)&&t>=1&&t<=dk?t:0}const xM={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function RM(e,t,a){if(e==="online")return"Online";if(e==="busy")return"Busy";if(e==="stale")return"Stale";if(e==="offline")return"Offline";if(a==="failed")return"Task failed";const r=e==="critical"?"critical":"warn",c=t.find(p=>p.state===r)||t.find(p=>p.state==="critical"||p.state==="warn");if(!c)return e==="critical"?"Issue":"Check";const u=xM[c.id]||c.label;return c.value&&c.value!=="-"?`${u} ${c.value}`:u}function bb(e,t){const a=t.split(".");let r=e;for(const c of a){if(r==null)return;if(Array.isArray(r)){const u=Number(c);r=Number.isInteger(u)?r[u]:void 0;continue}if(typeof r=="object"){r=r[c];continue}return}return r}function Lt(e,...t){for(const a of t){const r=bb(e,a),c=Number(r);if(Number.isFinite(c))return c}}function Er(e,...t){for(const a of t){const r=bb(e,a);if(typeof r=="string"&&r.trim())return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}return""}function Zr(e){const t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(1,t>1?t/100:t))}function bd(e,t){if(!(typeof e!="number"||typeof t!="number"||!Number.isFinite(e)||!Number.isFinite(t)||e<=0))return Zr((e-Math.max(0,t))/e)}function gi(e){return e===void 0?"-":`${Math.round(e*100)}%`}function vd(e){return e===void 0||!Number.isFinite(e)?"":e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}Gb/s`:`${Math.round(e)}Mb/s`}function vo(e,t=.92,a=.78){return e===void 0?"unknown":e>=t?"critical":e>=a?"warn":"good"}function AM(e){return!Number.isFinite(e)||!e||e<=0?"-":e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h`:`${Math.round(e/86400)}d`}function vb(e){const t=e.status||{},a=Lt(t,"cpu.cores","cpuCores","processorCount"),r=Lt(t,"loadavg.0","cpu.load1"),c=Zr(Lt(t,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(a&&r!==void 0?r/Math.max(1,a):void 0)),u=Lt(t,"memory.totalBytes","totalMem"),p=Lt(t,"memory.freeBytes","freeMem"),h=Zr(Lt(t,"memory.usedRatio","memory.usedPct","usedMemRatio"))??bd(u,p),f=Lt(t,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),k=Lt(t,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),M=Zr(Lt(t,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??bd(f,k),b=Lt(t,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),T=Zr(Lt(t,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),I=Er(t,"gpu.name","gpu.model","accelerators.gpu.name"),x=Lt(t,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),E=Lt(t,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),H=Zr(Lt(t,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??bd(x,E),Q=Lt(t,"gpu.temperatureC","thermal.gpuC"),G=Zr(Lt(t,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),ne=Er(t,"npu.name","npu.model","accelerators.npu.name"),ae=Lt(t,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=Lt(t,"network.rxMbps","network.receiveMbps","network.downMbps"),te=Lt(t,"network.txMbps","network.transmitMbps","network.upMbps"),Z=Lt(t,"network.latencyMs","network.rttMs"),me=Zr(Lt(t,"network.usedRatio","network.usageRatio","network.saturationRatio")),le=Er(t,"network.link","network.interface","network.name"),pe=Math.max(b??Number.NEGATIVE_INFINITY,Q??Number.NEGATIVE_INFINITY),se=Number.isFinite(pe)?pe:void 0,W=se===void 0?void 0:Zr((se-35)/60),re=b!==void 0&&Q!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(Q)}°`:b!==void 0?`CPU ${Math.round(b)}°`:Q!==void 0?`GPU ${Math.round(Q)}°`:"-",L=Er(t,"workload.role","role","lane")||(vi(e,"taskDispatch")?"Command-ready Client":"Local machine"),_=Er(e.latestTask,"status")||Er(t,"workload.status")||"idle",q=Er(e.latestTask,"title","instructionPreview")||Er(t,"workload.title"),ue=Er(e.latestTask,"resultSummary","error","instructionPreview")||Er(t,"workload.summary"),P=Date.parse(e.lastSeenAt||e.connectedAt||""),F=Number.isFinite(P)?Date.now()-P:0;let ee="online";e.connected?F>5*6e4?ee="stale":(b??0)>=86||(Q??0)>=88||(c??0)>=.94||(T??0)>=.96||(H??0)>=.96||(G??0)>=.96||(h??0)>=.94||(M??0)>=.94||(Z??0)>=200||_==="failed"?ee="critical":(b??0)>=78||(Q??0)>=80||(c??0)>=.82||(T??0)>=.86||(H??0)>=.88||(G??0)>=.86||(h??0)>=.82||(M??0)>=.86||(Z??0)>=80?ee="warn":["queued","running","targeted"].includes(_)&&(ee="busy"):ee="offline";const Se=[{id:"cpu",label:"CPU",value:gi(c),detail:a?`${a} cores`:r!==void 0?`load ${r.toFixed(1)}`:"not reported",ratio:c,state:vo(c,.92,.78)},{id:"memory",label:"RAM",value:gi(h),detail:gd(u,p),ratio:h,state:vo(h,.92,.78)},{id:"disk",label:"DISK",value:gi(M),detail:gd(f,k),ratio:M,state:vo(M,.92,.82)},{id:"gpu",label:"GPU",value:gi(T),detail:I||(x&&E!==void 0?`${ws(E)} VRAM free`:Q!==void 0?`${Math.round(Q)}C`:"not reported"),ratio:T,state:Q!==void 0&&Q>=88?"critical":Q!==void 0&&Q>=80?"warn":vo(T,.96,.86)},{id:"vram",label:"VRAM",value:gi(H),detail:gd(x,E),ratio:H,state:vo(H,.96,.88)},{id:"npu",label:"NPU",value:G!==void 0?gi(G):ae!==void 0?`${Math.round(ae)} TOPS`:"-",detail:ne||(ae!==void 0?"neural engine":"not reported"),ratio:G,state:vo(G,.96,.86)},{id:"temp",label:"TEMP",value:re,detail:`uptime ${AM(Lt(t,"uptimeSec"))}`,ratio:W,state:se===void 0?"unknown":se>=86?"critical":se>=78?"warn":"good"},{id:"network",label:"NET",value:vd(O)||(Z!==void 0?`${Math.round(Z)}ms`:le||"-"),detail:vd(te)?`${vd(te)} up`:le||"not reported",ratio:me,state:Z!==void 0&&Z>=200?"critical":Z!==void 0&&Z>=80?"warn":vo(me,.9,.75)}];return{state:ee,label:RM(ee,Se,_),role:L,taskLabel:q||(_==="idle"?"idle":_),taskStatus:_,taskSummary:ue,metrics:Se}}const Vh=[{id:"slow",label:"Slow",fps:Ms("slow")},{id:"fast",label:"Fast",fps:Ms("fast")}],IM=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],TM=[{id:"list",label:"List"},{id:"large",label:"Wall"}],zh=[{id:"sync-server",label:"Hub",icon:Si,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Jh,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Cs,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Zh,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:gl,accent:"violet",tooltip:"agents"}],Uh=[{id:"doc",label:"Doc",icon:wd,accent:"amber"},{id:"support",label:"Support",icon:fy,accent:"violet"},{id:"pricing",label:"Pricing",icon:xa,accent:"green"}];function PM(e){return e.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 Tt(e){return PM(e).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 yo(e){return e.map(t=>Tt(t))}function pn(e){return{languageName:e.languageName,languageLabel:e.languageLabel,eyebrow:e.eyebrow,title:Tt(e.title),intro:Tt(e.intro),sections:[{title:Tt(e.managerTitle),body:Tt(e.managerBody),points:yo(e.managerPoints)},{title:Tt(e.clientTitle),body:Tt(e.clientBody),points:yo(e.clientPoints)},{title:Tt(e.syncTitle),body:Tt(e.syncBody),points:yo(e.syncPoints)},...e.agentTitle&&e.agentBody&&e.agentPoints?[{title:Tt(e.agentTitle),body:Tt(e.agentBody),points:yo(e.agentPoints)}]:[],{title:Tt(e.platformTitle),body:Tt(e.platformBody),points:yo(e.platformPoints)}],sync:{title:Tt(e.syncTitle),body:Tt(e.syncBody),points:yo(e.syncPoints)},firewall:{title:Tt(e.firewallTitle),body:Tt(e.firewallBody),points:yo(e.firewallPoints)},commands:{title:Tt(e.commandsTitle),body:Tt(e.commandsBody),manager:Tt(e.managerCommandLabel),primary:Tt(e.clientCommandLabel),slot:Tt(e.slotCommandLabel),manual:Tt(e.manualCommandLabel)}}}const Ci={ko:pn({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"VuvoDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"VuvoDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 VuvoDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 VuvoDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --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를 누릅니다.","이제 vuvodesk.com의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 VuvoDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"VuvoDesk는 인증된 Direct TCP와 암호화된 UDP/WebRTC P2P로 화면과 제어를 직접 연결합니다. rendezvous 서비스는 상대 찾기와 P2P 연결 정보 교환만 하며 화면·입력 데이터는 중계하지 않습니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 상대 찾기와 P2P signaling을 위해 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","영상과 입력 데이터는 Direct TCP 또는 암호화된 UDP/WebRTC P2P로 장치끼리 직접 전송합니다.","외부망 Direct TCP에는 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다. P2P가 막히면 VuvoDesk가 직접 연결을 다시 시도합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 VuvoDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:pn({languageName:"English",languageLabel:"Document language",eyebrow:"VuvoDesk Manual",title:"Open a local Screen Wall with one command",intro:"VuvoDesk is an npm-first remote work deck for monitoring Clients, mini PCs, Mac minis, and development machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run VuvoDesk 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 VuvoDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",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 vuvodesk.com is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability 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.","The Hub-hosted Codex Agent turns instructions into approved VuvoDesk tool calls and shows progress and results for each computer."],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:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client 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, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"VuvoDesk connects screen and control payloads directly through authenticated Direct TCP and encrypted UDP/WebRTC P2P. The rendezvous service only finds peers and exchanges P2P connection details; it never carries screen or input payloads.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server for peer discovery and P2P signaling.","Screen and input payloads travel device-to-device through Direct TCP or encrypted UDP/WebRTC P2P.","For Direct TCP across networks, forward TCP 5197 or configure VPN/IP allowlists. When P2P is blocked, VuvoDesk keeps retrying a direct connection.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:pn({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"VuvoDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"VuvoDesk は、複数の作業 PC、mini PC、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで VuvoDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い VuvoDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",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 を押します。","vuvodesk.com の 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、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"VuvoDesk は認証済み Direct TCP と暗号化 UDP/WebRTC P2P で画面と操作を直接接続します。rendezvous サービスは相手の発見と P2P 接続情報の交換だけを行い、画面や入力データを中継しません。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は相手の発見と P2P signaling のため、設定済み rendezvous server へ outbound 接続できる必要があります。","画面と入力データは Direct TCP または暗号化 UDP/WebRTC P2P で端末間を直接移動します。","ネットワーク越しの Direct TCP には TCP 5197 の転送または VPN/IP allowlist を設定します。P2P が遮断された場合は直接接続を再試行します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":pn({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"VuvoDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"VuvoDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 VuvoDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 VuvoDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",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。","vuvodesk.com 的 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 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"VuvoDesk 通过经过认证的 Direct TCP 和加密 UDP/WebRTC P2P 直接传送画面与控制。rendezvous 服务只负责发现对端和交换 P2P 连接信息,不会转发画面或输入数据。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接,用于发现对端和 P2P signaling。","画面和输入数据通过 Direct TCP 或加密 UDP/WebRTC P2P 在设备之间直接传送。","跨网络使用 Direct TCP 时请转发 TCP 5197 或配置 VPN/IP 白名单。P2P 被阻断时会继续重试直连。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":pn({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"VuvoDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"VuvoDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 VuvoDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 VuvoDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",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。","vuvodesk.com 的 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、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"VuvoDesk 透過已驗證的 Direct TCP 與加密 UDP/WebRTC P2P 直接傳送畫面和控制。rendezvous 服務只負責尋找對端與交換 P2P 連線資訊,不會轉送畫面或輸入資料。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線,以尋找對端並進行 P2P signaling。","畫面與輸入資料透過 Direct TCP 或加密 UDP/WebRTC P2P 在裝置間直接傳送。","跨網路使用 Direct TCP 時請轉送 TCP 5197 或設定 VPN/IP allowlist。P2P 受阻時會持續重試直連。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:pn({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"VuvoDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"VuvoDesk es una consola npm-first para vigilar equipos de trabajo, mini PC, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta VuvoDesk 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 Client",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 vuvodesk.com 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: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"VuvoDesk conecta pantalla y control directamente mediante Direct TCP autenticado y UDP/WebRTC P2P cifrado. El servicio rendezvous solo localiza pares e intercambia datos de conexión P2P; no reenvía pantallas ni entradas.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado para descubrir pares y hacer signaling P2P.","Pantalla e input viajan entre dispositivos por Direct TCP o UDP/WebRTC P2P cifrado.","Para Direct TCP entre redes, reenvía TCP 5197 o configura VPN/allowlist de IP. Si P2P está bloqueado, VuvoDesk sigue intentando una conexión directa.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],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 Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:pn({languageName:"Français",languageLabel:"Langue du document",eyebrow:"VuvoDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"VuvoDesk est un deck npm-first pour surveiller plusieurs postes, mini PC, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez VuvoDesk 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 Client",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 vuvodesk.com 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, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"VuvoDesk relie directement l’écran et le contrôle par Direct TCP authentifié et UDP/WebRTC P2P chiffré. Le service rendezvous sert uniquement à trouver les pairs et à échanger les informations P2P ; il ne transmet ni écran ni saisie.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent accéder au serveur rendezvous configuré pour la découverte et le signaling P2P.","Écran et saisie passent directement entre appareils par Direct TCP ou UDP/WebRTC P2P chiffré.","Pour Direct TCP entre réseaux, redirigez TCP 5197 ou configurez VPN/allowlist IP. Si le P2P est bloqué, VuvoDesk retente une connexion directe.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],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 Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:pn({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"VuvoDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"VuvoDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte VuvoDesk 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 VuvoDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client 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 vuvodesk.com 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, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"VuvoDesk verbindet Bildschirm und Steuerung direkt über authentifiziertes Direct TCP und verschlüsseltes UDP/WebRTC P2P. Der Rendezvous-Dienst findet nur Peers und tauscht P2P-Verbindungsdaten aus; Bildschirm- und Eingabedaten werden nicht weitergeleitet.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server für Peer-Erkennung und P2P-Signaling.","Bildschirm- und Eingabedaten laufen direkt zwischen Geräten über Direct TCP oder verschlüsseltes UDP/WebRTC P2P.","Für Direct TCP zwischen Netzwerken TCP 5197 weiterleiten oder VPN/IP-Allowlist einrichten. Wenn P2P blockiert ist, versucht VuvoDesk die direkte Verbindung erneut.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":pn({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"VuvoDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"VuvoDesk é um deck npm-first para monitorar várias estações, mini PCs, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"VuvoDesk conecta tela e controle diretamente por Direct TCP autenticado e UDP/WebRTC P2P criptografado. O serviço rendezvous apenas encontra os pares e troca dados de conexão P2P; ele não encaminha tela nem entrada.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado para descoberta e signaling P2P.","Tela e entrada trafegam diretamente entre dispositivos por Direct TCP ou UDP/WebRTC P2P criptografado.","Para Direct TCP entre redes, encaminhe TCP 5197 ou configure VPN/allowlist IP. Se o P2P estiver bloqueado, VuvoDesk continua tentando conexão direta.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],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 Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:pn({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"VuvoDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"VuvoDesk è un deck npm-first per monitorare Client, mini PC, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"VuvoDesk collega schermo e controllo direttamente con Direct TCP autenticato e UDP/WebRTC P2P cifrato. Il servizio rendezvous trova solo i peer e scambia le informazioni P2P; non inoltra schermo o input.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono accedere al server rendezvous configurato per discovery e signaling P2P.","Schermo e input viaggiano direttamente tra dispositivi tramite Direct TCP o UDP/WebRTC P2P cifrato.","Per Direct TCP tra reti, inoltra TCP 5197 o configura VPN/allowlist IP. Se il P2P è bloccato, VuvoDesk ritenta la connessione diretta.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:pn({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"VuvoDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"VuvoDesk adalah deck npm-first untuk memantau banyak Client, mini PC, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"VuvoDesk menghubungkan layar dan kontrol secara langsung melalui Direct TCP terautentikasi dan UDP/WebRTC P2P terenkripsi. Layanan rendezvous hanya menemukan peer dan menukar informasi koneksi P2P; tidak meneruskan layar atau input.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous untuk discovery dan signaling P2P.","Layar dan input bergerak langsung antardevice melalui Direct TCP atau UDP/WebRTC P2P terenkripsi.","Untuk Direct TCP antarjaringan, forward TCP 5197 atau atur VPN/IP allowlist. Jika P2P diblokir, VuvoDesk terus mencoba koneksi langsung.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:pn({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"VuvoDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"VuvoDesk là deck npm-first để giám sát nhiều Client, mini PC, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"VuvoDesk kết nối trực tiếp màn hình và control bằng Direct TCP đã xác thực và UDP/WebRTC P2P mã hóa. Dịch vụ rendezvous chỉ tìm peer và trao đổi thông tin kết nối P2P; không chuyển tiếp màn hình hoặc input.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server để discovery và signaling P2P.","Màn hình và input đi trực tiếp giữa các thiết bị qua Direct TCP hoặc UDP/WebRTC P2P mã hóa.","Để dùng Direct TCP giữa các mạng, hãy forward TCP 5197 hoặc cấu hình VPN/IP allowlist. Khi P2P bị chặn, VuvoDesk tiếp tục thử kết nối trực tiếp.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],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 Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:pn({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"VuvoDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"VuvoDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน VuvoDesk บนเครื่องที่ใช้ดูหน้าจอ 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. เชื่อม Client",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 บน vuvodesk.com ไม่ใช่ 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 และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"VuvoDesk เชื่อมหน้าจอและ control โดยตรงด้วย Direct TCP ที่ยืนยันตัวตนและ UDP/WebRTC P2P ที่เข้ารหัส บริการ rendezvous ใช้เพียงค้นหา peer และแลกข้อมูลการเชื่อมต่อ P2P โดยไม่ส่งต่อหน้าจอหรือ input",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server เพื่อ discovery และ P2P signaling","หน้าจอและ input ส่งตรงระหว่าง device ผ่าน Direct TCP หรือ UDP/WebRTC P2P ที่เข้ารหัส","หากต้องใช้ Direct TCP ข้าม network ให้ forward TCP 5197 หรือตั้ง VPN/IP allowlist เมื่อ P2P ถูกบล็อก VuvoDesk จะลองเชื่อมตรงอีกครั้ง","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:pn({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"VuvoDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"VuvoDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर VuvoDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने VuvoDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",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 दबाएं।","vuvodesk.com का 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, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"VuvoDesk authenticated Direct TCP और encrypted UDP/WebRTC P2P से screen और control को सीधे जोड़ता है। rendezvous service केवल peers खोजती और P2P connection info बदलती है; screen या input data आगे नहीं भेजती।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Peer discovery और P2P signaling के लिए Clients और manager को configured rendezvous server तक outbound access चाहिए।","Screen और input data Direct TCP या encrypted UDP/WebRTC P2P से device-to-device सीधे जाते हैं।","Networks के बीच Direct TCP के लिए TCP 5197 forward या VPN/IP allowlist सेट करें। P2P block होने पर VuvoDesk direct connection फिर आज़माता है।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:pn({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"VuvoDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"VuvoDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل VuvoDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية VuvoDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",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 على vuvodesk.com لم يعد مسار التشغيل الافتراضي. تطبيق 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 وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يربط VuvoDesk الشاشة والتحكم مباشرة عبر Direct TCP موثق وUDP/WebRTC P2P مشفر. تقتصر خدمة rendezvous على اكتشاف الأطراف وتبادل معلومات اتصال P2P، ولا تمرر الشاشة أو بيانات الإدخال.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous للاكتشاف وP2P signaling.","تنتقل الشاشة وبيانات الإدخال مباشرة بين الأجهزة عبر Direct TCP أو UDP/WebRTC P2P المشفر.","لاستخدام Direct TCP بين الشبكات وجه TCP 5197 أو اضبط VPN/IP allowlist. عند حظر P2P يعيد VuvoDesk محاولة الاتصال المباشر.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:pn({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"VuvoDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"VuvoDesk, tek bir manager PC üzerinden birçok Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda VuvoDesk 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 VuvoDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client 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.","vuvodesk.com ü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 X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"VuvoDesk ekranı ve kontrolü doğrulanmış Direct TCP ve şifreli UDP/WebRTC P2P ile doğrudan bağlar. Rendezvous hizmeti yalnızca eşleri bulur ve P2P bağlantı bilgilerini değiştirir; ekran veya girdi verisini taşımaz.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager, eş keşfi ve P2P signaling için yapılandırılmış rendezvous servera outbound erişebilmelidir.","Ekran ve girdi verileri Direct TCP veya şifreli UDP/WebRTC P2P ile cihazdan cihaza doğrudan gider.","Ağlar arasında Direct TCP için TCP 5197 yönlendirme veya VPN/IP allowlist yapılandırın. P2P engellenirse VuvoDesk doğrudan bağlantıyı yeniden dener.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose 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:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},EM=Object.entries(Ci).map(([e,t])=>({id:e,label:t.languageName}));function NM(){if(typeof navigator>"u")return"en";const e=navigator.languages?.length?navigator.languages:[navigator.language];for(const t of e){const a=t.toLowerCase();if(Ci[t])return t;if(a.startsWith("zh-tw")||a.startsWith("zh-hk"))return"zh-TW";if(a.startsWith("pt"))return"pt-BR";const r=a.split("-")[0];if(Ci[r])return r}return"en"}function qh({index:e}){const t=e+1;return i.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${t}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"empty-screen",children:[i.jsx(Ra,{size:24}),i.jsxs("strong",{children:["Slot ",String(t).padStart(3,"0")]})]})]})})}const FM=["cpu","gpu","memory","vram","network","disk","temp"];function DM({device:e,slotNumber:t,selected:a,updateIndicator:r,remoteDiagnostics:c,diagnosticsMode:u="remote",onSelect:p,onOpenControl:h}){const f=vb(e),k=new Map(f.metrics.map(b=>[b.id,b])),M=r?.label||f.label;return i.jsxs("div",{className:`wall-device-list-row state-${f.state} ${a?"selected":""}`,role:"row","aria-selected":a,tabIndex:0,onClick:p,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())},children:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ra,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:Qt(e)}),i.jsxs("small",{children:["Slot ",String(t).padStart(3,"0"),e.platform?` · ${e.platform}`:"",e.arch?` · ${e.arch}`:""]})]}),a&&i.jsx(hl,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),i.jsxs("span",{className:`wall-device-list-status state-${f.state} ${r?`update-${r.state}`:""}`,role:"gridcell",title:r?.error||M,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:M})]}),FM.map(b=>{const T=k.get(b);return i.jsxs("span",{className:`wall-device-list-metric state-${T?.state||"unknown"}`,role:"gridcell",title:T?`${T.label}: ${T.value} · ${T.detail}`:"Not reported",children:[i.jsx("strong",{children:T?.value||"-"}),i.jsx("small",{children:T?.detail||"not reported"}),T?.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(T.ratio*100)}%`},"aria-hidden":"true"})]},b)}),c&&i.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:i.jsx(Xg,{items:c,mode:u})})]})}function LM(e){if(!e)return!1;const t=String(e.platform||"").trim().toLowerCase();return Nr(t)&&e.capabilities?.screenRecordingPermission===!1}function Nr(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"}function OM(e){const t=String(e||"").trim().toLowerCase();return t==="linux"||t.startsWith("linux ")}function Gh(e){const t=String(e||"").trim().toLowerCase();return["win32","windows","win32nt"].includes(t)?"mode5-lzo-delta":Nr(t)?"mode1-jpeg":""}function yd({device:e,frame:t,selected:a,controlEnabled:r,showStatus:c,showDeviceTitle:u=!0,monitorIndex:p,monitorCount:h,onSelect:f,onFocusDevice:k,onOpenControl:M,onCycleMonitor:b,onCanvasReady:T,sendInput:I,remotePointerFeedback:x,remoteModifierState:E,updateIndicator:H,presentationReady:Q,showPresentationSpinner:G=!1,remoteDiagnostics:ne,diagnosticsMode:ae="remote"}){const O=s.useRef(null),te=s.useRef(null),Z=s.useRef(null),me=s.useRef(0),le=s.useRef(null),pe=s.useRef(null),se=s.useRef(new Map),W=s.useRef(null),re=s.useRef(kC()),L=s.useRef(wC()),_=s.useRef(!1),q=s.useRef([]),ue=s.useRef(xl()),P=s.useRef(null),F=s.useRef(null),ee=vb(e),Se=["cpu","gpu","memory","vram"].map(g=>ee.metrics.find(U=>U.id===g)).filter(g=>!!g),de=Xd(p),Fe=h>1,j=Q??!!t,R=LM(e)&&!j,Ce=G&&e.connected&&!j&&!R,we=cM(e,t,de),Ve=we>=pl?100:we/pl*100,Oe=we>=pl?pl/we*100:100,it={"--screen-aspect":we.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Ve)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,Oe)).toFixed(3)}%`},z=r?{transformOrigin:"0 0",transform:`translate3d(${ue.current.translateX.toFixed(2)}px, ${ue.current.translateY.toFixed(2)}px, 0) scale(${ue.current.scale.toFixed(4)})`}:void 0,Me=!!(r&&j&&x?.nativeInputBackend==="win32-window-message"&&x.deviceId===e.deviceId&&x.monitorIndex===de),je=Me?{left:`${Math.max(0,Math.min(1,x.normalizedX))*100}%`,top:`${Math.max(0,Math.min(1,x.normalizedY))*100}%`}:void 0,qe=s.useCallback(g=>{ue.current=g;const U=O.current;U&&(U.style.transformOrigin="0 0",U.style.transform=`translate3d(${g.translateX.toFixed(2)}px, ${g.translateY.toFixed(2)}px, 0) scale(${g.scale.toFixed(4)})`,U.dataset.touchZoom=g.scale.toFixed(2))},[]),kt=s.useCallback(g=>{if(O.current=g,g&&r){const U=ue.current;g.style.transformOrigin="0 0",g.style.transform=`translate3d(${U.translateX.toFixed(2)}px, ${U.translateY.toFixed(2)}px, 0) scale(${U.scale.toFixed(4)})`,g.dataset.touchZoom=U.scale.toFixed(2)}T(e.deviceId,g)},[r,e.deviceId,T]),Te=(g,U,N)=>CC(g,U,N.getBoundingClientRect()),Be=g=>Te(g.clientX,g.clientY,g.currentTarget),K=g=>EC(g,E),ve=s.useCallback(()=>{le.current!==null&&(window.cancelAnimationFrame(le.current),le.current=null)},[]),st=s.useCallback(()=>{const g=P.current;g&&(window.clearTimeout(g.timerId),P.current=null);const U=F.current;U&&window.clearTimeout(U.timerId),F.current=null},[]),ot=s.useCallback(()=>{const g=Z.current;if(!g)return;Z.current=null;const U=Number(g.input.normalizedX),N=Number(g.input.normalizedY);if(!Number.isFinite(U)||!Number.isFinite(N))return;I(e.deviceId,{...g.input,normalizedX:U,normalizedY:N})&&(me.current=performance.now())},[e.deviceId,I]),bt=s.useCallback(()=>{le.current===null&&(le.current=window.requestAnimationFrame(()=>{le.current=null,ot()}))},[ot]);s.useEffect(()=>{L.current.reset(),_.current=!1,q.current=[];const g=xl();return qe(g),()=>{ve(),st(),Z.current=null,pe.current=null,se.current.clear(),W.current=null,L.current.reset(),_.current=!1,q.current=[]}},[de,qe,st,ve,r,e.deviceId]);const Mt=(g,U)=>{if(!r)return;const N={...g,type:U};if(U==="pointermove"){const he=performance.now();Z.current={input:N},he-me.current>=xk&&(ve(),ot()),bt();return}Z.current&&(ve(),ot()),I(e.deviceId,N)},oe=(g,U,N=bs(g.button),he="")=>{Mt({monitorIndex:de,...Be(g),button:N,...he?{inputSource:he}:{},...K(g)},U)},$=(g,U)=>{I(e.deviceId,{...g,type:"pointerdown",button:U}),I(e.deviceId,{...g,type:"pointerup",button:U})},ye=(g,U,N)=>({monitorIndex:de,...Te(g,U,N),shiftKey:!!E?.shiftKey,ctrlKey:!!E?.ctrlKey,altKey:!!E?.altKey,metaKey:!!E?.metaKey}),V=(g,U)=>{const N=P.current;N&&(window.clearTimeout(N.timerId),P.current=null,$(N.input,"left"));const he={tap:g,input:U,timerId:0};he.timerId=window.setTimeout(()=>{P.current===he&&(P.current=null,$(U,"left"))},Fd),P.current=he},Ge=(g,U,N)=>{if(se.current.set(g,{clientX:U,clientY:N}),W.current)return;const he=pe.current;if(he&&he.pointerId!==g){const Ke=se.current.get(he.pointerId),ut=se.current.get(g),xe=te.current?.getBoundingClientRect();Ke&&ut&&xe&&(ve(),Z.current=null,st(),pe.current=null,W.current={gesture:MC(Ke,ut,ue.current,xe),pointerIds:[he.pointerId,g]});return}const Y=performance.now(),Ie=P.current,be={clientX:U,clientY:N,at:Y};if(Ie&&Wf(Ie.tap,be)){window.clearTimeout(Ie.timerId),P.current=null;const Ke={...Ie,timerId:0};Ke.timerId=window.setTimeout(()=>{F.current===Ke&&(F.current=null,$(Ke.input,"left"))},Math.max(0,Ie.tap.at+Fd-Y)),F.current=Ke}else F.current=null,Ie&&(window.clearTimeout(Ie.timerId),P.current=null,$(Ie.input,"left"));pe.current=RC(g,U,N),k()},St=(g,U,N,he)=>{se.current.set(g,{clientX:U,clientY:N});const Y=W.current;if(Y){const Ke=se.current.get(Y.pointerIds[0]),ut=se.current.get(Y.pointerIds[1]);Ke&&ut&&qe(xC(Y.gesture,Ke,ut));return}const Ie=pe.current;if(!Ie||Ie.pointerId!==g)return;const be=Vg(Ie,g,U,N);if(pe.current=be,be?.dragged&&F.current){const Ke=F.current;window.clearTimeout(Ke.timerId),F.current=null,$(Ke.input,"left")}be?.dragged&&Mt(ye(U,N,he),"pointermove")},A=(g,U,N,he)=>{if(se.current.set(g,{clientX:U,clientY:N}),W.current){se.current.delete(g),se.current.size===0&&(W.current=null);return}const Y=AC(pe.current,g,U,N,performance.now());if(se.current.delete(g),Y.kind==="ignore")return;Y.kind==="drag"&&(Mt(ye(U,N,he),"pointermove"),ve(),ot()),pe.current=null;const Ie=F.current;if(Ie&&window.clearTimeout(Ie.timerId),F.current=null,Y.kind==="tap"&&Y.tap){const be=ye(U,N,he);Ie&&Wf(Ie.tap,Y.tap)?$(be,"right"):(Ie&&$(Ie.input,"left"),V(Y.tap,be))}else Ie&&$(Ie.input,"left")},ie=g=>{if(se.current.delete(g),W.current){se.current.size===0&&(W.current=null);return}if(pe.current?.pointerId===g){ve(),Z.current=null,pe.current=null;const U=F.current;U&&(window.clearTimeout(U.timerId),$(U.input,"left")),F.current=null}},Pe=g=>{if(g.pointerType!=="touch")return!1;if(g.preventDefault(),g.stopPropagation(),re.current.shouldHandlePointerEvent()){Ge(g.pointerId,g.clientX,g.clientY);try{g.currentTarget.setPointerCapture(g.pointerId)}catch{}}return!0},He=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),re.current.shouldHandlePointerEvent()&&St(g.pointerId,g.clientX,g.clientY,g.currentTarget),!0),vt=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),g.stopPropagation(),re.current.shouldHandlePointerEvent()&&A(g.pointerId,g.clientX,g.clientY,g.currentTarget),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),!0),Je=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),g.stopPropagation(),re.current.shouldHandlePointerEvent()&&ie(g.pointerId),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),!0),At=g=>{if(r){g.preventDefault(),g.stopPropagation(),re.current.shouldHandlePointerEvent()&&(re.current.claimNativeTouchEvents(),pe.current=null,se.current.clear(),W.current=null);for(const U of Array.from(g.changedTouches))Ge(U.identifier,U.clientX,U.clientY)}},_t=g=>{if(!r)return;g.preventDefault(),g.stopPropagation();for(const he of Array.from(g.touches))se.current.set(he.identifier,{clientX:he.clientX,clientY:he.clientY});const U=pe.current?.pointerId,N=Array.from(g.touches).find(he=>he.identifier===U)||g.touches.item(0);N&&St(N.identifier,N.clientX,N.clientY,g.currentTarget)},Jt=g=>{if(r){g.preventDefault(),g.stopPropagation();for(const U of Array.from(g.changedTouches))A(U.identifier,U.clientX,U.clientY,g.currentTarget)}},xt=g=>{if(r){g.preventDefault(),g.stopPropagation();for(const U of Array.from(g.changedTouches))ie(U.identifier)}},Vt=s.useCallback(g=>{const U=document.activeElement;U instanceof HTMLElement&&g.contains(U)&&U.classList.contains("monitor-cycle-button")&&U.blur()},[]);return i.jsx("article",{className:`device-tile ${a?"selected":""} ${e.connected?"online":"offline"}`,"data-live-device-id":e.deviceId,style:it,children:i.jsxs("div",{className:`tile-screen ${j?"has-frame":"is-empty"}`,role:"button",tabIndex:r?-1:0,"aria-pressed":a,onClick:g=>{g.target instanceof Element&&g.target.closest(".monitor-cycle")||r||f()},onKeyDown:g=>{g.target instanceof Element&&g.target.closest(".monitor-cycle")||r||(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),f())},onDoubleClick:g=>{if(!(g.target instanceof Element&&g.target.closest(".monitor-cycle"))){if(g.preventDefault(),r){g.stopPropagation();return}M()}},onPointerLeave:g=>Vt(g.currentTarget),children:[i.jsxs("span",{ref:te,className:`screen-content ${j?"has-frame":"is-empty"}`,children:[i.jsx("canvas",{ref:kt,className:`remote-canvas ${j?"has-frame":"is-empty"} ${r?"control-input-enabled":""}`,"data-monitor-index":de,"data-touch-zoom":ue.current.scale.toFixed(2),style:z,tabIndex:r?0:-1,onPointerDown:g=>{if(r&&!Pe(g)){_.current=!1,L.current.observePointerEvent("down",g),g.preventDefault(),g.stopPropagation(),k(),g.currentTarget.focus(),oe(g,"pointerdown");try{g.currentTarget.setPointerCapture(g.pointerId)}catch{}}},onPointerMove:g=>{r&&g.preventDefault(),!He(g)&&(r&&(_.current=!1,L.current.observePointerEvent("move",g)),oe(g,"pointermove"))},onPointerLeave:g=>{r&&g.pointerType!=="touch"&&(_.current=!1,L.current.observePointerEvent("leave",g),oe(g,"pointermove"),ve(),ot())},onPointerUp:g=>{r&&(vt(g)||(_.current=!1,L.current.observePointerEvent("up",g),g.preventDefault(),g.stopPropagation(),oe(g,"pointerup"),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId)))},onPointerCancel:g=>{Je(g)||(r&&(g.preventDefault(),g.stopPropagation(),oe(g,"pointerup")),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId))},onMouseDown:g=>{if(!r||!L.current.shouldHandleMouseEvent("down",g))return;g.preventDefault(),g.stopPropagation(),_.current=!0,k(),g.currentTarget.focus();const U=bs(g.button);q.current.includes(U)||q.current.push(U),oe(g,"pointerdown",U,"legacy-mouse")},onMouseMove:g=>{!r||!L.current.shouldHandleMouseEvent("move",g)||(g.preventDefault(),_.current=!0,oe(g,"pointermove",bs(g.button),"legacy-mouse"))},onMouseLeave:g=>{if(!r||!L.current.shouldHandleMouseEvent("leave",g))return;_.current=!0,oe(g,"pointermove",bs(g.button),"legacy-mouse"),ve(),ot();const U=q.current.splice(0).reverse();for(const N of U)oe(g,"pointerup",N,"legacy-mouse")},onMouseUp:g=>{if(!r||!L.current.shouldHandleMouseEvent("up",g))return;g.preventDefault(),g.stopPropagation(),_.current=!0;const U=bs(g.button);oe(g,"pointerup",U,"legacy-mouse"),q.current=q.current.filter(N=>N!==U)},onTouchStart:At,onTouchMove:_t,onTouchEnd:Jt,onTouchCancel:xt,onWheel:g=>{r&&(g.preventDefault(),I(e.deviceId,{type:"wheel",monitorIndex:de,...Be(g),deltaX:g.deltaX,deltaY:g.deltaY,..._.current?{inputSource:"legacy-mouse"}:{},...K(g)}))},onContextMenu:g=>r&&g.preventDefault(),onDoubleClick:g=>{r&&(g.preventDefault(),g.stopPropagation())}},`${e.deviceId}:monitor:${de}`),Me&&i.jsx("span",{className:"remote-pointer-feedback","data-input-seq":x.inputSeq,"data-native-input-backend":x.nativeInputBackend,style:je,"aria-hidden":"true",children:i.jsx(Cs,{size:22,strokeWidth:2.2})})]}),!j&&i.jsx("span",{className:"empty-screen",children:i.jsx(Ra,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:Qt(e),children:Qt(e)}),Ce&&i.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Preparing video"})]}),R&&i.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[i.jsx(wo,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"Screen Recording permission required"}),i.jsx("small",{children:"Allow the terminal app on this Mac, then restart VuvoDesk."})]}),H&&i.jsxs("span",{className:`wall-update-status state-${H.state}`,role:"status","aria-live":"polite",title:H.error||H.label,children:[H.state==="updated"?i.jsx(Cn,{size:20,"aria-hidden":"true"}):H.state==="failed"?i.jsx(Ma,{size:22,"aria-hidden":"true"}):H.state==="offline"?i.jsx(eg,{size:22,"aria-hidden":"true"}):i.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),i.jsx("strong",{children:H.label}),H.error?i.jsx("small",{children:H.error}):null]}),c&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`tile-health-pill state-${ee.state}`,children:ee.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${Qt(e)} status`,children:Se.map(g=>i.jsxs("span",{className:`tile-metric state-${g.state}`,children:[i.jsx("b",{children:g.label}),i.jsx("em",{children:g.value}),g.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(g.ratio*100)}%`}})]},g.id))})]}),ne&&i.jsx(Xg,{items:ne,mode:ae}),Fe&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${Qt(e)} display ${de+1} of ${h}`,onPointerDown:g=>g.stopPropagation(),onClick:g=>g.stopPropagation(),onDoubleClick:g=>g.stopPropagation(),children:[i.jsx("button",{className:"monitor-cycle-button previous",onClick:g=>{g.preventDefault(),g.stopPropagation(),b(-1),g.currentTarget.blur()},title:"Previous display",type:"button",children:i.jsx(tg,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",de+1,"/",h]}),i.jsx("button",{className:"monitor-cycle-button next",onClick:g=>{g.preventDefault(),g.stopPropagation(),b(1),g.currentTarget.blur()},title:"Next display",type:"button",children:i.jsx(ng,{size:18})})]})]})})}function _M({visible:e}){const t=yk;return s.useEffect(()=>{},[t]),null}function cx({runtimeBaseUrl:e=""}){const t=typeof window<"u"&&!!window.liveDesk,a=t,{session:r,sessionHydrationRevision:c,loading:u,hubSessionRevoking:p,hubSessionBlocked:h,hubSessionRevocationError:f,revokeHubSession:k}=zS(),{workspaces:M,activeWorkspace:b,loading:T,error:I,inviteNotice:x,refresh:E,selectWorkspace:H,isWorkspaceActionCurrent:Q}=j0(r,c),G=b?.id||"",ne=b?.membershipRevision||0,ae=b?.kind==="team"&&b.role==="operator",O=b?`${r?.user.id||""}:${b.id}:${b.role}`:"",te=s.useRef(O);te.current=O,Zv(r&&b&&!h&&!p?{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:r.expires_at,user:{id:r.user.id,email:r.user.email},workspaceId:b.id,workspaceKind:b.kind,workspaceRole:b.role,membershipRevision:b.membershipRevision}:null);const{target:Z,error:me,refresh:le}=qS(r,G,ne),pe=s.useMemo(()=>{if(!Z?.active)return null;const n=Z.expires_at?Date.parse(Z.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(n)&&n<=Date.now()?null:Z},[Z]),se=s.useMemo(()=>Xp(pe),[pe]),W=yi(),re=e.trim().replace(/\/+$/,""),L=s.useMemo(()=>[...new Set((W?se:[re,...se,In]).filter(Boolean))],[W,se,re]),[_,q]=s.useState(null),[ue]=s.useState(nk),[P,F]=s.useState(!1),[ee,Se]=s.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[de,Fe]=s.useState(()=>typeof window<"u"&&Yf(window.matchMedia(qf).matches,ee,window.matchMedia("(pointer: coarse)").matches)),j=W&&de;s.useEffect(()=>{if(!W){q(null);return}const n=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),o=()=>Se(n.matches||!!window.navigator.standalone),l=d=>{d.preventDefault(),q(d)},m=()=>{q(null),Se(!0)};return o(),n.addEventListener("change",o),window.addEventListener("beforeinstallprompt",l),window.addEventListener("appinstalled",m),()=>{n.removeEventListener("change",o),window.removeEventListener("beforeinstallprompt",l),window.removeEventListener("appinstalled",m)}},[W]);const R=s.useCallback(async()=>{const n=_;if(!n){ue.isIos&&F(!0);return}q(null);try{await n.prompt(),(await n.userChoice).outcome==="accepted"&&Se(!0)}catch(o){q(n),console.warn("[VuvoDesk] PWA install prompt failed.",o)}},[ue.isIos,_]);s.useEffect(()=>{const n=window.matchMedia(qf),o=window.matchMedia("(pointer: coarse)"),l=()=>Fe(Yf(n.matches,ee,o.matches));return l(),n.addEventListener("change",l),o.addEventListener("change",l),()=>{n.removeEventListener("change",l),o.removeEventListener("change",l)}},[ee]),s.useLayoutEffect(()=>{const n=document.documentElement,o=()=>{n.classList.remove("livedesk-mobile-console-active"),n.style.removeProperty("--livedesk-mobile-viewport-height"),n.style.removeProperty("--livedesk-mobile-viewport-top"),n.style.removeProperty("--livedesk-mobile-viewport-width"),n.style.removeProperty("--livedesk-mobile-viewport-left"),n.style.removeProperty("--livedesk-mobile-ios-top-guard")};if(!de){o();return}n.classList.add("livedesk-mobile-console-active");const l=window.visualViewport,m=document.createElement("div");m.setAttribute("aria-hidden","true"),m.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);",document.body.appendChild(m);let d=0;const C=()=>{d=0;const S=Math.max(window.innerHeight,document.documentElement.clientHeight),y=ZC(l,S,window.innerWidth,ee||ue.isIos,ee||ue.isIos||ue.isAndroid),w=Number.parseFloat(window.getComputedStyle(m).paddingTop),J=JC({isIos:ue.isIos,standalone:ee,safeAreaTop:w,screenHeight:window.screen.height,layoutViewportHeight:S});n.style.setProperty("--livedesk-mobile-viewport-height",`${y.height}px`),n.style.setProperty("--livedesk-mobile-viewport-top",`${y.offsetTop}px`),n.style.setProperty("--livedesk-mobile-viewport-width",`${y.width}px`),n.style.setProperty("--livedesk-mobile-viewport-left",`${y.offsetLeft}px`),n.style.setProperty("--livedesk-mobile-ios-top-guard",`${J}px`)},v=()=>{d||(d=window.requestAnimationFrame(C))};return C(),l?.addEventListener("resize",v),l?.addEventListener("scroll",v),window.addEventListener("resize",v),window.addEventListener("orientationchange",v),window.addEventListener("pageshow",v),()=>{d&&window.cancelAnimationFrame(d),l?.removeEventListener("resize",v),l?.removeEventListener("scroll",v),window.removeEventListener("resize",v),window.removeEventListener("orientationchange",v),window.removeEventListener("pageshow",v),m.remove(),o()}},[ue.isAndroid,ue.isIos,de,ee]);const[Ce,we]=s.useState(aM),Ve=s.useMemo(()=>L.some(n=>!!fl(n)),[L]),Oe=!!(r&&b&&!h&&!p&&!f),it=dC({workspaceReady:Oe,desktopShell:t,publicConsole:W,authenticated:!!r,managerNeedsLocalAccess:Ve,localHubAccessEnabled:Ce}),{status:z,devices:Me,error:je,connectionState:qe,failure:kt,refresh:Te,retry:Be,hubBaseUrl:K}=US(L,it,r?.access_token||"",O,G,b?.kind||""),ve=s.useRef(null),st=s.useRef(0),[ot,bt]=s.useState(0),Mt=s.useCallback(n=>{const o=l=>{ve.current===n&&n.record({type:"hub.request.failed",component:"pwa-diagnostic-control",state:"failed",reason:l instanceof Error?l.message:String(l),details:{transport:"authenticated-hub-http"}})};n.flushWithOneFollowUp(o)},[]),oe=s.useCallback(n=>{const o=ve.current;if(!o)return!1;let l=!1;for(const m of n)l=o.record(m).accepted||l;return l&&Mt(o),l},[Mt]),$=s.useCallback(n=>oe([n]),[oe]);s.useEffect(()=>{const n=String(r?.user?.id||"").trim(),o=String(K||"").trim();if(t||!Oe||!n||!o){ve.current=null;return}const l=st.current+1;st.current=l;let m=!1,d=null;return mr(async()=>{const{createPwaRuntimeDiagnosticLane:C}=await import("./pwa-runtime-diagnostic-lane-CXJ3zl5c.js");return{createPwaRuntimeDiagnosticLane:C}},[]).then(({createPwaRuntimeDiagnosticLane:C})=>{m||l!==st.current||(d=C({owner:{clientId:n,sessionId:"unknown"},sendBatch:(v,{signal:S})=>ze("/api/remote/pwa-diagnostics",{method:"POST",signal:S,timeoutMs:15e3,body:JSON.stringify(v)},o)}),ve.current=d,d.record({type:"client.started",component:"pwa-runtime",state:"active",reason:"diagnostic-owner-created",details:{ownerGeneration:l,workspaceId:G||"unknown",workspaceRole:b?.role||"unknown",managerHubUrl:o}}),d.record({type:"visibility.changed",component:"document",state:document.visibilityState==="visible"?"visible":"hidden",reason:"initial-current-visibility",details:{source:"current-document-state"}}),Mt(d),bt(v=>v+1))}).catch(()=>{m||console.warn("[VuvoDesk] PWA lifecycle diagnostics are unavailable.")}),()=>{m=!0,ve.current===d&&(ve.current=null),d?.dispose()}},[b?.role,G,t,Mt,K,r?.user?.id,O,Oe]),s.useEffect(()=>{if(!ve.current)return;const n=Jp();oe([{type:"session.changed",component:"authenticated-workspace",state:Oe?"ready":"unknown",reason:`workspace:${G||"unknown"}:revision:${ne}:role:${b?.role||"unknown"}`,details:{clientId:r?.user?.id||"unknown",workspaceId:G||"unknown",workspaceRevision:ne,workspaceRole:b?.role||"unknown"}},{type:"session.changed",component:"hub-manager",state:String(qe||(z?.started?"ready":"unknown")),reason:je?`error:${je}:manager:${z?.deviceId||"unknown"}`:`manager:${z?.deviceId||"unknown"}:version:${z?.managerVersion||"unknown"}:role:${z?.runtimeRole||"unknown"}`,details:{managerHubUrl:K||"unknown",managerDeviceId:z?.deviceId||"unknown",managerPackage:z?.managerPackage||"unknown",managerVersion:z?.managerVersion||"unknown",runtimeRole:z?.runtimeRole||"unknown",hubError:je||"unknown",directStage:n.stage||"unknown",directReady:n.directReady===!0}}])},[b?.role,G,ne,qe,je,K,ot,oe,r?.user?.id,z?.deviceId,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started,Oe]);const ye=s.useCallback(()=>E(),[E]),V=B0(r,b,K,ye,Q),[Ge,St]=s.useState(!1);s.useEffect(()=>{if(!z?.started){St(!1);return}const n=new AbortController;return ze("/api/remote/wall-preferences",{signal:n.signal},K).then(o=>{St(o.wallPreferences?.showThisComputer===!0)}).catch(o=>{n.signal.aborted||(St(!1),console.warn("[VuvoDesk] Computer visibility setting could not be loaded.",o))}),()=>n.abort()},[K,z?.started]);const{entitlement:A,licensed:ie,loading:Pe,error:He,refresh:vt}=GS(r,G,ne,b?.plan,b?.entitlementStatus,ye),[Je,At]=s.useState([]),[_t,Jt]=s.useState(""),[xt,Vt]=s.useState(""),[g,U]=s.useState(""),[N,he]=s.useState(""),[Y,Ie]=s.useState(""),[be,Ke]=s.useState("idle"),ut=s.useRef("idle"),xe=s.useCallback(n=>{const o=typeof n=="function"?n(ut.current):n;ut.current=o,Ke(o)},[]),[Ye,_e]=s.useState(!1),[Wt,lt]=s.useState(""),[ct,ht]=s.useState(null),nt=s.useRef(null),[Pt,zt]=s.useState(""),xi=s.useRef("");xi.current=N;const[kn,jn]=s.useState(!1);s.useLayoutEffect(()=>{St(!1),At([]),Jt(""),Vt(""),U(""),he(""),xe("idle"),_e(!1),ht(null),jn(!1)},[O]);const[Ri,Fs]=s.useState([]),Dl=s.useRef(null),Ai=s.useRef(null),em=s.useRef(null),Ds=s.useRef(!1),tm=s.useRef({key:"",source:"",at:0}),[nm,rm]=s.useState(!1),[Zt,Fr]=s.useState(!1),Na=s.useRef(""),dt=s.useRef(new Map),Ro=s.useRef(0),Ls=s.useRef(!1),Os=s.useRef(""),am=s.useRef(O),Ll=s.useRef(O);Ll.current=O;const _s=s.useRef(null);_s.current||(_s.current=c0());const Ol=s.useRef(document.visibilityState==="visible"),[na,om]=s.useState({}),rt=s.useRef({}),Ii=s.useRef(new Set),ra=s.useRef(new Map),Fa=s.useRef(new Map),[Ao,im]=s.useState({}),Ti=s.useMemo(()=>new Set(Object.keys(na)),[na]),js=s.useCallback((n,o)=>{if(!n)return;const l={...rt.current};o?l[n]=o:delete l[n],rt.current=l,om(l)},[]),Io=s.useCallback((n,o)=>{n&&im(l=>{if(!!l[n]===o)return l;const m={...l};return o?m[n]=!0:delete m[n],m})},[]),sm=s.useCallback((n,o)=>{n&&Fa.current.set(n,{paused:o,expiresAt:Date.now()+Hk})},[]),[et,Mn]=s.useState(""),[an,To]=s.useState(""),[Po,_l]=s.useState(!1),cm=s.useRef(null),lm=s.useRef(null);s.useEffect(()=>{et==="auth"&&r?.access_token&&Mn("")},[et,r?.access_token]);const[jl,um]=s.useState(""),[Da,Bs]=s.useState(null),tr=s.useRef(null),yb=s.useRef(0),Hs=s.useRef(0),Ws=s.useCallback((n,o,l)=>{const m=String(n||"").trim();if(um(m),tr.current!==null&&(window.clearTimeout(tr.current),tr.current=null),!m)return Hs.current=0,Bs(null),0;const d=++yb.current;if(Hs.current=d,Bs({id:d,message:m,tone:o}),!l)return d;const C=window.setTimeout(()=>{Bs(v=>v?.id===d?null:v),tr.current===C&&(tr.current=null)},5e3);return tr.current=C,d},[]),B=s.useCallback((n,o="info")=>Ws(n,o,!0),[Ws]);s.useEffect(()=>{I&&B(I,"error")},[B,I]),s.useEffect(()=>{x&&B(x,/joined/i.test(x)?"success":"error")},[x,B]),s.useEffect(()=>{V.error&&B(V.error,"error")},[B,V.error]),s.useEffect(()=>{f&&B("Hub sign-out could not be confirmed. Wall and Control remain blocked; open Account and retry when the Hub is reachable.","error")},[f,B]);const dm=s.useCallback((n,o)=>{const l=String(o||"").trim();!l||n<=0||Hs.current!==n||(Hs.current=0,tr.current!==null&&(window.clearTimeout(tr.current),tr.current=null),um(m=>m===l?"":m),Bs(m=>m?.id===n&&m.message===l?null:m))},[]),Bn=s.useCallback(n=>{Ws(n,"progress",!1)},[Ws]);s.useEffect(()=>()=>{tr.current!==null&&window.clearTimeout(tr.current)},[]);const[It,La]=s.useState(()=>typeof window>"u"?"wall":window.location.pathname.startsWith("/support")?"support":new URLSearchParams(window.location.search).get("view")==="pricing"?"pricing":"wall");s.useEffect(()=>{const n=()=>{La(window.location.pathname.startsWith("/support")?"support":o=>o==="support"?"wall":o)};return window.addEventListener("popstate",n),()=>window.removeEventListener("popstate",n)},[]);const[Eo,mm]=s.useState(yM),[Oa,pm]=s.useState(hM),_a=s.useRef(Eo),aa=s.useRef(Oa);_a.current=Eo,aa.current=Oa;const Hn=Ms(Oa),[Pn,No]=s.useState(Hn),Bl=s.useRef(null);Bl.current||(Bl.current=i0(O));const En=Bl.current;En.switchOwner(O);const Dr=s.useRef(null),Wn=s.useRef(null);s.useLayoutEffect(()=>{Wn.current!==null&&(window.clearTimeout(Wn.current),Wn.current=null),Dr.current=null,aa.current="fast",_a.current=ea,pm("fast"),No(Ms("fast")),mm(ea)},[O]);const oa=s.useCallback(n=>{const o=Yg(n,{cadence:aa.current,viewScale:_a.current});return aa.current!==o.cadence&&(aa.current=o.cadence,pm(o.cadence),No(Ms(o.cadence)),gM(o.cadence)),_a.current!==o.viewScale&&(_a.current=o.viewScale,mm(o.viewScale),wM(o.viewScale)),o},[]);s.useEffect(()=>{const n=z?.wallPreferences;if(!n)return;const o=Math.max(0,Number(n.revision)||0);if(!En.acceptSnapshot(O,o))return;const l=Dr.current;l&&(l.cadence!==n.cadence||l.viewScale!==Mi(n.viewScale))||(l&&(Dr.current=null),oa(n))},[oa,z?.wallPreferences,En,O]);const $s=s.useCallback(async(n,o)=>{const l=()=>En.ownsWrite(o)&&te.current===O;if(!l())return;let m=!1;const d=S=>m||!n0({error:S,publicConsole:yi(),workspaceKind:b?.kind,workspaceRole:b?.role,workspaceId:G,userId:r?.user.id})?!1:(m=!0,!0);let C=En.readRevision(O);if(C===void 0)try{for(;;)try{const S=await ze(ad(m),void 0,K);if(!l()||(C=Math.max(0,Number(S.revision)||0),!En.commitWriteRevision(o,C)))return;break}catch(S){if(!l())return;if(d(S))continue;throw S}}catch{if(!l())return;Dr.current=null,Te(),B("Wall view changed here, but Hub synchronization failed.","error");return}let v=!1;for(let S=0;S<3;S+=1)try{const y=await ze(ad(m),{method:"PATCH",body:JSON.stringify(r0({legacy:m,revision:C,preferences:n}))},K);if(!l()||!En.commitWriteRevision(o,y.revision))return;const w=a0(y,m);if(!t0(w,n)){Dr.current=null,Te(),B("Update the Hub to synchronize Wall controls.","error");return}Dr.current=null,oa(w),Te();return}catch(y){if(!l())return;if(d(y))continue;if(/^409\s/.test(y instanceof Error?y.message:String(y))&&!v)try{const J=await ze(ad(m),void 0,K);if(!l()||(C=Math.max(0,Number(J.revision)||0),!En.commitWriteRevision(o,C)))return;v=!0;continue}catch{}Dr.current=null,Te(),B("Wall view changed here, but Hub synchronization failed.","error");return}},[b?.kind,b?.role,G,oa,K,Te,r?.user.id,B,En,O]),Vs=s.useCallback((n,o)=>{Wn.current!==null&&(window.clearTimeout(Wn.current),Wn.current=null);const l=oa({cadence:n,viewScale:o}),m=En.beginWrite(O);m&&(Dr.current=l,$s(l,m))},[oa,$s,En,O]),wb=s.useCallback(n=>{const o=oa({cadence:aa.current,viewScale:Mi(n)}),l=En.beginWrite(O);return l&&(Dr.current=o,Wn.current!==null&&window.clearTimeout(Wn.current),Wn.current=window.setTimeout(()=>{Wn.current=null,$s({cadence:aa.current,viewScale:_a.current},l)},250)),o},[oa,$s,En,O]);s.useEffect(()=>()=>{Wn.current!==null&&window.clearTimeout(Wn.current)},[]);const Bt=A0(Eo),fm=e0(Eo),hm=s.useCallback(n=>{Vs(aa.current,n==="list"?Al:n==="medium"?M0:ea)},[Vs]),gm=s.useCallback(n=>{Vs(n,_a.current)},[Vs]),[Sb,bm]=s.useState(!1);s.useEffect(()=>{if(bm(!1),Bt!=="list")return;const n=window.setTimeout(()=>{bm(!0)},jd);return()=>window.clearTimeout(n)},[Bt]);const Pi=o0({wallSize:Bt,elapsedMs:Sb?jd:0});s.useLayoutEffect(()=>{!ae||It==="wall"||It==="control"||It==="doc"||It==="support"||(La("wall"),jn(!1))},[It,ae]);const Hl=I0(Eo),vm=s.useMemo(()=>({"--wall-tile-min-width":`${Hl}px`}),[Hl]),Cb=Bt==="list"?"List view":`${Bt==="medium"?"Small":"Large"} tiles, ${Hl} pixel minimum width`,[Ei,kb]=s.useState(bM),[fn,zs]=s.useState(!1),[Ut,Us]=s.useState(!1),[pr,qs]=s.useState(!1),[Ni,Mb]=s.useState(null),[$n,Fo]=s.useState(null),[Do,Lo]=s.useState(!1),[xb,Gs]=s.useState(Date.now),Lr=s.useRef(null),ym=s.useRef(null),Wl=s.useRef(null),ia=s.useRef(0);s.useEffect(()=>()=>{ia.current+=1,Lr.current!==null&&window.clearTimeout(Lr.current)},[]);const[ja,Rb]=s.useState(NM),[Ba,wm]=s.useState(!1),[sa,Or]=s.useState(!1),Ks=s.useRef(sa);s.useLayoutEffect(()=>{Ks.current=sa},[sa]);const[jM,BM]=s.useState(!1),[Oo,Sm]=s.useState(rM),[De]=s.useState(dM),Cm=de?Ei:De.showScreenStatus,[on]=s.useState(pM),[$l]=s.useState(lM),[gt,Vl]=s.useState($l.selections),km=s.useRef({...$l.topologyFingerprints}),Fi=s.useRef({}),Mm=s.useRef({...$l.selections}),[Ze,fr]=s.useState(null),[Ys,zl]=s.useState({}),Ul=s.useRef(new Set),[ql,Qs]=s.useState([]),[Di,Ab]=s.useState(""),[Ib,Tb]=s.useState(0),[Pb,xm]=s.useState(0),[Eb,Nb]=s.useState(0),[Gl,Li]=s.useState(()=>new Set),mt=s.useRef(new Map),hn=s.useRef(new Map),_r=s.useRef(new Map),Et=s.useRef(new Map),Ha=s.useRef(null),Wa=s.useRef(new Map),jr=s.useRef(new Set),ca=s.useRef(new Map),_o=s.useRef(new Map),$a=s.useRef(new Map),Vn=s.useRef(new Map),Xs=s.useRef(new WeakMap),Js=s.useRef(new WeakMap),la=s.useRef(""),xn=s.useRef(null),Rm=s.useRef(Promise.resolve()),Zs=s.useRef(0),jo=s.useRef(null),Nn=s.useRef(null),Oi=s.useRef(""),en=s.useRef(new Map),Bo=s.useRef(null),_i=s.useRef(0),ua=s.useRef(new Map),ec=s.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),tc=s.useRef(new Map),Kl=s.useRef([]),Am=s.useRef(0),[nc,Yl]=s.useState({}),Va=s.useRef(new Map),[rc,ac]=s.useState({}),oc=s.useRef(null),[Ql,gn]=s.useState(!1),ic=s.useRef(null),Fb=s.useRef(0),Br=s.useRef(null),Im=s.useRef(new Map),nr=s.useRef(null),zn=s.useRef(null),yt=s.useRef(null),ji=s.useRef(!1),Tm=s.useRef(0),Ht=s.useRef(0),sn=s.useRef(""),Pm=s.useRef(Promise.resolve()),Ho=s.useRef(""),ke=s.useRef(null),Un=s.useRef(""),za=s.useRef(null),Wo=s.useRef(0),Bi=s.useRef(""),Hr=s.useRef(new Map),hr=s.useRef(new Map),sc=s.useRef(performance.now()),da=s.useRef(new Map),Fn=s.useRef(new Map),ma=s.useRef(new Map),Wr=s.useRef(new Map),$r=s.useRef(new Map),gr=s.useRef(new Map),qn=s.useRef(document.visibilityState==="visible"),rr=s.useRef(1),Xl=s.useRef([]),[qt,Db]=s.useState(document.visibilityState==="visible"),[Lb,Ob]=s.useState(0),Hi=s.useRef(0),cc=s.useRef(0),lc=s.useRef(0),uc=s.useRef(0),Jl=s.useRef(0),Zl=s.useRef(new Map),Wi=s.useRef([]),Em=s.useRef(new Map),Nm=s.useRef(new Map),Nt=s.useRef(new Map),Vr=s.useRef(new Map),$i=s.useRef(new Map),eu=s.useRef({}),dc=s.useRef(new Set),Ft=s.useCallback((n,o,l,m,d)=>{const C=ft(n,o),v=performance.now(),S=Hr.current.get(C)||0,y=hr.current.get(C)||0,w=n==="control"?ke.current:null,J=w?.deviceId===o?er({...w,streamPurpose:"control"}):Vn.current.get(o)||"",ge={scope:n,deviceId:o,stage:l,reason:m,at:Date.now(),attempts:Math.max(0,Math.floor(Number(d)||0)),receiveAgeMs:S>0?Math.max(0,v-S):-1,paintAgeMs:y>0?Math.max(0,v-y):-1,bindingKey:J};$i.current.set(C,ge),console.info("[VuvoDesk frame recovery]",ge);const D=ve.current;if(!D)return;const fe={type:"frame.recovery.changed",component:`frame-recovery:${n}:${o}`,state:l,reason:m,details:{scope:n,deviceId:o,attempts:ge.attempts,receiveAgeMs:ge.receiveAgeMs>=0?ge.receiveAgeMs:"unknown",paintAgeMs:ge.paintAgeMs>=0?ge.paintAgeMs:"unknown",bindingKey:J||"unknown"}};if(l==="stable"){queueMicrotask(()=>{ve.current===D&&D.record(fe).accepted&&Mt(D)});return}$(fe)},[Mt,$]),$o=s.useCallback(n=>Qw(Xs.current,n),[]),Vo=s.useCallback(n=>Ud(Js.current,n),[]),Ua=s.useCallback((n,o)=>wf(Js.current,n,o),[]),$t=s.useCallback(n=>{const o=yf(Xs.current,n);return yf(Js.current,n),o},[]),zo=s.useCallback((n,o)=>wf(Xs.current,n,o),[]),Fm=s.useCallback(n=>Nn.current===n||Ha.current===n?!0:[mt.current,hn.current,_r.current,Et.current,en.current].some(l=>Array.from(l.values()).some(m=>m===n)),[]),bn=s.useCallback(n=>{n&&($t(n),dc.current.add(n),Zw(n,{isCurrent:Fm,dispose:pi,schedule:o=>queueMicrotask(()=>{try{o()}finally{dc.current.delete(n)}})}))},[Fm,$t]),vn=s.useCallback(n=>($t(n),Nl(n,pi)),[$t]),Dm=s.useCallback(()=>{const n=Nn.current,o=Ha.current,l=[...dc.current];Nn.current=null,Ha.current=null,dc.current.clear(),Xs.current=new WeakMap,Js.current=new WeakMap,Vn.current.clear(),Oi.current="",Jw([mt.current,hn.current,_r.current,Et.current,en.current],[n,o,...l],pi),Bo.current=null,_i.current=0,Wa.current.clear(),jr.current.clear(),ca.current.clear(),_o.current.clear(),$a.current.clear(),ua.current.clear(),tc.current.clear(),Kl.current.length=0,Va.current.clear(),Hr.current.clear(),hr.current.clear(),da.current.clear(),Fn.current.clear(),ma.current.clear(),Wr.current.clear(),$r.current.clear(),gr.current.clear(),Nt.current.clear(),Vr.current.clear(),$i.current.clear(),Ii.current.clear()},[]);s.useEffect(()=>()=>{Dm()},[Dm]);const zr=s.useCallback((n,o,l={})=>{const m=ft(n,o);Hr.current.delete(m),hr.current.delete(m),da.current.delete(m),Fn.current.delete(m),gr.current.delete(m),Nt.current.delete(m),Vr.current.delete(m),l.preserveLatestDiagnostic!==!0&&$i.current.delete(m),Va.current.delete(m),ua.current.delete(m),ma.current.delete(m),Wr.current.delete(m),$r.current.delete(m),ac(d=>{if(!Object.prototype.hasOwnProperty.call(d,m))return d;const C={...d};return delete C[m],C}),Yl(d=>{if(!Object.prototype.hasOwnProperty.call(d,m))return d;const C={...d};return delete C[m],C})},[]),Dt=s.useCallback((n,o,l={})=>{const m=ft(n,o),d=performance.now();zr(n,o,l),n==="control"?Wr.current.set(m,d):$r.current.set(m,d)},[zr]),[qa,pa]=s.useState(null),[_b,tu]=s.useState(!1),[HM,jb]=s.useState([]),[Uo,Bb]=s.useState("all"),[qo,nu]=s.useState([]),[WM,$M]=s.useState(!1),[VM,Hb]=s.useState(!0),Lm=s.useRef(null),Om=s.useRef(null),Wb=s.useRef(null),$b=s.useRef(null),Vb=s.useRef(!1),ru=s.useRef(!1),Vi=s.useRef(0),br=s.useRef(0),vr=s.useRef(0),ar=s.useRef(0),zi=s.useRef(0),Ui=s.useRef(""),au=s.useRef({}),qi=It==="settings"&&!ae,_m=!ae&&It==="pricing",jm=It==="doc",Bm=It==="support",Ga=!ae&&It==="share-files",mc=!ae&&It==="agents",Ur=!qi&&!_m&&!jm&&!Bm&&!Ga&&!mc,Re=It==="control",Hm=m0(It),or=qt&&It==="wall"&&!Pi,Wm=s.useRef(or);Wm.current=or;const zb=!j&&Hm&&Wi.current.length>0,yr=qt&&(It==="wall"&&!Pi||!j&&Re||zb),Go=s.useRef(yr);Go.current=yr;const pc=qt&&(Re||or),Ko=qt&&(pc||Hm&&(be==="connecting"||be==="active")),ou=s.useRef({active:yr,epoch:rr.current});ou.current.active!==yr&&(rr.current+=1,ou.current={active:yr,epoch:rr.current}),s.useEffect(()=>{Ur||(zs(!1),Us(!1),qs(!1))},[Ur]);const tt=De.frameMode==="mode4-h264-atlas",Gn=Y||on.frameMode,Ub=Gn!=="mode3-h264-hw"?Math.min(30,on.fps):on.fps,Gi=YC(Ub,j),Yo=Me.find(n=>n.deviceId===xt),qb=Yo?.platform,Gb=Yo?_n(Yo,gt[Yo.deviceId]):0,fc=Yo?Zd(Yo,Gb):null,$m=OM(qb)?{maxWidth:1280,maxHeight:720}:Rh,Vm=Gn!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Rh,hc={maxWidth:Math.min(Vm.maxWidth,$m.maxWidth,on.maxWidth),maxHeight:Math.min(Vm.maxHeight,$m.maxHeight,on.maxHeight)},wr={maxWidth:fc?.width?Math.min(hc.maxWidth,fc.width):hc.maxWidth,maxHeight:fc?.height?Math.min(hc.maxHeight,fc.height):hc.maxHeight};s.useEffect(()=>{if(b?.kind!=="team"&&z?.started){if(!r?.access_token){ze("/api/remote/license",{method:"DELETE"},K).catch(()=>{});return}ze("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`},body:JSON.stringify({workspaceId:G})},K).catch(n=>{console.warn("[VuvoDesk] Hub license sync failed",n)})}},[b?.entitlementStatus,b?.kind,G,ne,K,r?.access_token,z?.started]),s.useEffect(()=>{!r?.access_token||b?.kind!=="personal"||b.role!=="owner"||!z?.started||z.runtimeRole!=="hub"||!z.deviceId||(async()=>{try{const{data:n,error:o}=await Ct.rpc("register_livedesk_device",{p_device_id:z.deviceId,p_device_name:z.deviceName||z.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:z.managerVersion||z.managerPackage||""}),l=Array.isArray(n)?n[0]:n;(o||l?.ok===!1)&&console.warn("[VuvoDesk] Hub device role registration failed",o||l?.reason||"unknown-error")}catch(n){console.warn("[VuvoDesk] Hub device role registration failed",n)}})()},[b?.kind,b?.role,r?.access_token,z?.deviceId,z?.deviceName,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started]);const qr=z?.runtimeRole==="hub"?String(z.deviceId||"").trim():"",Le=s.useMemo(()=>Me.filter(n=>n.connected&&(de||Ge||!qr||n.deviceId!==qr)),[Me,qr,de,Ge]),Ka=s.useMemo(()=>Le.filter(n=>!qr||n.deviceId!==qr),[Le,qr]);s.useEffect(()=>{const n={...rt.current},o=Date.now();let l=!1;im(m=>{const d={...m};let C=!1;for(const v of Me){const S=String(v.liveCapturePause?.token||"").trim(),y=Fa.current.get(v.deviceId);if(y)if((y.paused?!!S:!S)||y.expiresAt<=o)Fa.current.delete(v.deviceId);else continue;const w=!!S&&(v.liveCapturePause?.captureStopConfirmed!==!0||v.liveCapturePause?.phase==="stop-unconfirmed");!!d[v.deviceId]!==w&&(C=!0,w?d[v.deviceId]=!0:delete d[v.deviceId])}return C?d:m});for(const m of Me){const d=String(m.liveCapturePause?.token||"").trim(),C=String(n[m.deviceId]||""),v=Fa.current.get(m.deviceId);if(v)if((v.paused?!!d:!d)||v.expiresAt<=o)Fa.current.delete(m.deviceId);else continue;d&&d!==C?(n[m.deviceId]=d,l=!0):!d&&C&&(delete n[m.deviceId],ra.current.delete(m.deviceId),l=!0)}l&&(rt.current=n,om(n))},[Me]);const zm=Uo==="all"?Le.length:qo.filter(n=>Le.some(o=>o.deviceId===n)).length,Kb=s.useMemo(()=>Le.reduce((n,o)=>Math.max(n,$h(o.slotNumber)),0),[Le]),gc=Math.max(uk,Le.length,Kb),fa=s.useMemo(()=>{const n=Array(gc).fill(null),o=[];for(const l of Le){const m=$h(l.slotNumber);m>0&&m<=gc&&!n[m-1]?n[m-1]=l:o.push(l)}for(const l of o){const m=n.findIndex(d=>!d);m<0?n.push(l):n[m]=l}return n},[Le,gc]),Um=s.useMemo(()=>de?fa.filter(n=>!!n):fa,[de,fa]),qm=s.useMemo(()=>fa.flatMap((n,o)=>n?[{device:n,slotNumber:o+1}]:[]),[fa]),bc=s.useMemo(()=>Le.map(n=>n.deviceId),[Le]),Ya=s.useMemo(()=>new Set(Je),[Je]),cn=s.useMemo(()=>Le.filter(n=>Ya.has(n.deviceId)),[Le,Ya]),ha=s.useMemo(()=>Me.find(n=>n.deviceId===_t)||cn[0]||null,[Me,_t,cn]),tn=s.useMemo(()=>Me.find(n=>n.deviceId===xt)||null,[xt,Me]),ir=tn?_n(tn,gt[tn.deviceId]):0,X=Re?tn:ha,Gm=s.useMemo(()=>new Set(qo),[qo]),Yb=s.useMemo(()=>Uo==="all"?Le.map(n=>n.deviceId):Le.filter(n=>Gm.has(n.deviceId)).map(n=>n.deviceId),[Le,Gm,Uo]),Qb=X?vi(X,"control"):!1,iu=Nr(X?.platform)&&(X?.capabilities?.controlPermission===!1||X?.capabilities?.accessibilityPermission===!1),sr=X?vi(X,"audio")||vi(X,"remoteAudio"):!1,Qo=(Array.isArray(X?.capabilities?.agentTools)?X.capabilities.agentTools.map(String):[]).includes("system.power"),su=b?.entitlementStatus==="active"&&b.plan!=="free"?b.plan:ie?A?.plan:null,Qe=su==="team"?"team":su==="pro"?"pro":su==="ltd"?"ltd":"free",Km=$e[Qe],vc=b?.deviceLimit??Km.limit,Sr=s.useMemo(()=>{const n=new Set(g0(Ka,vc));return qr&&n.add(qr),n},[vc,qr,Ka]),pt=!X||Sr.has(X.deviceId),Xo=Qe==="ltd"?`Plus includes up to ${us} Clients. Upgrade to Pro for schools, academies, commercial use, and larger walls.`:Qe==="pro"?`Pro includes up to ${Lu} Clients for schools, academies, and commercial use.`:Qe==="team"?"Team includes every connected Client in this shared commercial workspace.":`Free includes up to ${Ou} Clients. Upgrade to Plus for ${us} devices and no ads.`,Xb=Qe==="free",Cr=pt&&!!X&&Qb,Ym=pt&&!!X&&sr,Ki=s.useMemo(()=>Re?X?[X]:[]:cn.length>0?cn:X?[X]:[],[X,cn,Re]),Dn=s.useMemo(()=>Ki.filter(n=>Sr.has(n.deviceId)),[Sr,Ki]),yc=Dn.some(n=>String(na[n.deviceId]||"").startsWith("pending:")||Ao[n.deviceId]===!0),Yi=!(Dn.length>0&&Dn.every(n=>{const o=String(na[n.deviceId]||"");return!!o&&!o.startsWith("pending:")&&Ao[n.deviceId]!==!0}))||yc,wc=s.useMemo(()=>fa.filter(n=>!!n?.connected).slice(0,SM(Bt)).map(n=>n.deviceId),[fa,Bt]),Sc=s.useMemo(()=>yr?or?tt||Bt==="list"?bc:De.visibleOnlyLive?ql.length>0?ql:wc:bc:Wi.current.length>0?Wi.current:bc:[],[wc,tt,ql,De.visibleOnlyLive,bc,yr,or,Bt]),Kn=s.useMemo(()=>{const n=hd(Sc.filter(o=>Sr.has(o)));return KC(n,j,ha?.deviceId||"")},[j,Sr,Sc,ha?.deviceId]);Wi.current=Kn;const kr=s.useMemo(()=>Kn.filter(n=>n!==Di&&!Ti.has(n)),[Ti,Kn,Di]),Cc=s.useMemo(()=>new Map(Le.map(n=>[n.deviceId,n.platform])),[Le]),yn=s.useMemo(()=>{const n=Object.fromEntries(Le.map(o=>[o.deviceId,String(o.sessionId||"").trim()]));return d0(eu.current,n)},[Le]);s.useLayoutEffect(()=>{eu.current=yn},[yn]);const Jb=Xf(au.current,yn)?Hn:Pn;s.useLayoutEffect(()=>{const n=au.current,o=Xf(n,yn);au.current={...yn};const l=new Set([...Object.keys(n),...Object.keys(yn)]),m=ve.current?[]:null;for(const d of l){const C=String(n[d]||"").trim(),v=String(yn[d]||"").trim();C!==v&&(console.info("[VuvoDesk frame session]",{deviceId:d,previousSessionId:C,currentSessionId:v,action:v?"fresh-recovery-owner":"owner-released"}),m?.push({type:"session.changed",component:`remote-device:${d}`,state:v?"connected":"disconnected",reason:`session:${v||C||"unknown"}`,details:{deviceId:d,previousSessionId:C||"unknown",currentSessionId:v||"unknown",action:v?"fresh-recovery-owner":"owner-released"}}),v?(Dt("wall",d),Dt("control",d)):(zr("wall",d),zr("control",d)))}m&&m.length>0&&oe(m),o&&(No(Hn),Vi.current=Date.now(),br.current=0,vr.current=0,ar.current=0,zi.current=0,Ui.current="")},[zr,yn,oe,Dt,Hn]),s.useEffect(()=>{if(!ve.current)return;const n=Object.entries(yn).filter(([,o])=>!!o).map(([o,l])=>({type:"session.changed",component:`remote-device:${o}`,state:"connected",reason:`session:${l}`,details:{deviceId:o,currentSessionId:l,action:"current-connected-owner"}}));n.length>0&&oe(n)},[yn,ot,oe]);const Mr=b0(tt,Kn.length),nn=s.useMemo(()=>tt?kr.filter(n=>fs({mode4Enabled:tt,directMode4WallEnabled:Mr,isMac:Nr(Cc.get(n))})==="atlas"):[],[Mr,tt,Cc,kr]),Gt=s.useMemo(()=>kr.filter(n=>fs({mode4Enabled:tt,directMode4WallEnabled:Mr,isMac:Nr(Cc.get(n))})==="direct"),[Mr,tt,Cc,kr]),Qm=s.useMemo(()=>{const n=De.autoStartLive?kr.map(o=>ft("wall",o)):[];return Ko&&pt&&g&&Sr.has(g)&&(be==="connecting"||be==="active"||be==="warm")&&n.push(ft("control",g)),[...new Set(n)].sort()},[Ko,g,be,pt,Sr,De.autoStartLive,kr]);s.useEffect(()=>{const n=new Set(Kn);Li(o=>{let l=!1;const m=new Set;for(const d of o)n.has(d)?m.add(d):l=!0;return l?m:o})},[Kn]);const Zb=s.useMemo(()=>{const n=d=>Le.find(C=>C.deviceId===d)||null,o=d=>{const C=n(d);return C?_n(C,gt[d]):0},l=(d,C=o(d))=>d===g&&(be==="connecting"||be==="active"||be==="warm")?Et.current.get(d)||hn.current.get(d)||null:tt?en.current.get(d)||mt.current.get(d)||null:mt.current.get(d)||null,m=(d,C=o(d))=>{const v=n(d);return`${v?Qt(v):d} · Monitor ${C+1}`};return{resolveCurrentTarget(){if(Re&&tn){const y=ir;return{type:"control",deviceIds:[tn.deviceId],monitorIndex:y,label:`${Qt(tn)} · Monitor ${y+1}`,sourceCanvas:l(tn.deviceId,y),signature:`control:${tn.deviceId}:${y}:${on.frameMode}`}}const d=cn.map(y=>y.deviceId).filter(y=>kr.includes(y)),C=ha&&kr.includes(ha.deviceId)?ha.deviceId:"",v=d.length>0?d:C?[C]:kr,S=d.length===0&&!C;if(v.length===0)return null;if(v.length===1){const y=v[0],w=o(y);return{type:S?"wall":d.length>1?"selection":"device",deviceIds:v,monitorIndex:w,label:S?"Wall":m(y,w),sourceCanvas:S?null:l(y,w),signature:`${S?"wall":"device"}:${y}:${w}:${tt?"atlas":"direct"}`}}return{type:d.length>1?"selection":"wall",deviceIds:v,label:d.length>1?`${v.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${d.length>1?"selection":"wall"}:${v.join(",")}:${Bt}`}},getDeviceCanvas:l,composeWall(d,C={}){return W0(d.map(v=>{const S=o(v);return{deviceId:v,label:m(v,S),canvas:l(v,S)}}),C)}}},[Le,tn,g,be,on.frameMode,mt,tt,gt,ir,cn,Re,kr,ha,Bt]),Xm=tk({hubUrl:K,remoteSettingsEnabled:!!(z?.started&&K),sourceRegistry:Zb,onToast:B}),Gr=s.useMemo(()=>p0({captureOwnershipActive:Ko,localFeatureAccess:pt,controlSessionDeviceId:g,planAllowed:Sr.has(g),sessionState:be,controlFocusVisible:Re,presentationCanvasMounted:Wt===g,wallPresentationVisible:or,wallPresentationCanvasMounted:mt.current.has(g)||en.current.has(g),decoderOwnerExists:Et.current.has(g)})?[g]:[],[Ko,g,be,pt,Wt,Sr,Re,or]),cu=s.useMemo(()=>hd([...Kn,...Gr]),[Gr,Kn]),kc=s.useMemo(()=>jh(De,Bt),[De,Bt]),Jo=s.useMemo(()=>jh(De,"large"),[De]),Mc=v0({mode4Enabled:tt,directMode4WallEnabled:Mr,adaptiveFps:Jb,directDeviceCount:Gt.length,adaptive:De.adaptiveLoadShedding}),ln=QC({fps:Mc,maxWidth:Jo.maxWidth,maxHeight:Jo.maxHeight,quality:De.quality},j,Gt.length),lu=C0({deviceCount:nn.length,targetFps:Pn,adaptive:De.adaptiveLoadShedding});tt&&nn.length>0;const Kr=s.useCallback((n,o,l,m=1)=>{if(n.width<=0||n.height<=0)return!1;if(n===o)return!0;const d=l?Math.min(1,l.maxWidth/n.width,l.maxHeight/n.height):1,C=Math.max(1,Math.round(n.width*d)),v=Math.max(1,Math.round(n.height*d)),S=o.width!==C||o.height!==v;S&&(o.width=C,o.height=v);const y=o.getContext("2d",{alpha:!1});if(!y)return!1;y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="low";const w=y.globalAlpha;y.globalAlpha=S?1:Math.max(.05,Math.min(1,m));try{y.drawImage(n,0,0,n.width,n.height,0,0,o.width,o.height)}finally{y.globalAlpha=w}return!0},[]),xc=s.useCallback((n,o)=>{const l=Math.max(0,Number(o.clientWidth||0)),m=Math.max(0,Number(o.clientHeight||0)),d=Math.max(1,Number(window.devicePixelRatio||1)),C=l>0&&m>0?{maxWidth:Math.ceil(l*d),maxHeight:Math.ceil(m*d)}:void 0;return Kr(n,o,C)},[Kr]),Rc=s.useCallback((n,o,l)=>{const m=Math.max(0,Math.floor(Number(n?.frameSeq||0))),d=o||(n?mt.current.get(n.deviceId):null),C=l||d,v=Math.max(0,Number(C?.width||0))*Math.max(0,Number(C?.height||0)),S=Math.max(mt.current.size,en.current.size);return a&&m>0&&(m+Fk(n?.deviceId||""))%db===0&&S<=Nk&&ew(d)&&v>0&&v<=Ek?Pk:1},[a]),Zo=s.useCallback((n,o,l)=>{if(!ec.current)return;const m=`${n}:${o.deviceId}`,d=tc.current.get(m)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};d.bindingKey=er(o),d.totalPaints+=1,d.lastPaintAt=performance.now(),d.lastFrameSeq=Number(o.frameSeq||0),tc.current.set(m,d);const C=++Am.current,v={sequence:C,scope:n,deviceId:o.deviceId,bindingKey:d.bindingKey,frameSeq:d.lastFrameSeq,paintedAt:d.lastPaintAt,sourceGapMs:Number(o.sourceGapMs||0),agentSendGapMs:Number(o.agentSendGapMs||0),agentSendDurationMs:Number(o.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(o.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(o.agentFrameAgeMs||0),timestampUs:Number(o.timestampUs||0),queuedForMs:Number(l?.queuedForMs||0),decodedForMs:Number(l?.decodedForMs||0),scheduledForMs:Number(l?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(l?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(l?.interactiveBurstTailHoldCount||0)};Kl.current[(C-1)%Vk]=v},[]),xr=s.useCallback(n=>{n&&Li(o=>{if(o.has(n))return o;const l=new Set(o);return l.add(n),l})},[]),Rr=s.useCallback(n=>{n&&Li(o=>{if(!o.has(n))return o;const l=new Set(o);return l.delete(n),l})},[]),Qa=s.useCallback((n,o)=>{if(!o||o.width<=0||o.height<=0)return!1;const l=document.createElement("canvas");if(l.width=o.width,l.height=o.height,!Kr(o,l))return bn(l),!1;const m=_r.current.get(n);return _r.current.set(n,l),m&&m!==l&&vn(m),xr(n),!0},[xr,Kr,vn,bn]),Kt=s.useCallback(n=>{Xw(_r.current,n,pi)},[]),Ac=s.useCallback((n,o)=>{const l=_r.current.get(n),m=mt.current.get(n)===o||en.current.get(n)===o;return rt.current[n]?(Kt(n),!1):!l||!m||l.width<=0||l.height<=0?!1:Kr(l,o)?!0:(Kt(n),!1)},[Kr,Kt]),Yr=s.useCallback((n,o=!1,l)=>{if(rt.current[n]||!jr.current.has(n))return!1;const m=Math.max(1,Math.min(Hn,wt.controlWallReuseMaxFps,Gi)),d=performance.now(),C=_o.current.get(n)||0,v=Et.current.get(n)||hn.current.get(n),S=mt.current.get(n)||en.current.get(n);if(!v||!S||!S.isConnected)return!1;const y=h0({cadenceCredit:ca.current.get(n)||0,targetFps:m,sourceFps:Gi,elapsedSincePaintMs:C>0?d-C:0,nowMs:d,scheduledPaintAtMs:$a.current.get(n)||0,force:o});if(!y.shouldPaint)return ca.current.set(n,y.nextCadenceCredit),!1;const w=Math.max(0,Number(S.clientWidth||0)),J=Math.max(0,Number(S.clientHeight||0)),ge=Math.max(1,Number(window.devicePixelRatio||1)),D=w>0&&J>0?{maxWidth:Math.min(kc.maxWidth,Math.ceil(w*ge)),maxHeight:Math.min(kc.maxHeight,Math.ceil(J*ge))}:kc;return Kr(v,S,D,l?Rc(l,v,S):1)?(ca.current.set(n,y.nextCadenceCredit),y.nextScheduledPaintAtMs>0&&$a.current.set(n,y.nextScheduledPaintAtMs),_o.current.set(n,performance.now()),y.sourceCadencePassthrough&&(ca.current.delete(n),$a.current.delete(n)),l&&Zo("wall-reuse-visible",l),xr(n),Kt(n),!0):!1},[Gi,kc,xr,Kr,Zo,Kt,Rc,Hn]);s.useEffect(()=>{la.current=Di},[Di]);const Ic=s.useCallback((n,o)=>{const l=Br.current;if(!l||l.deviceId!==n)return;const m=Date.now();Im.current.set(n,{...l,source:o,completedAtEpochMs:m,durationMs:Math.max(0,performance.now()-l.startedAt)}),Br.current=null},[]),Jm=s.useCallback((n,o)=>{const l=mt.current.get(n);if(o&&l&&l!==o&&Qa(n,l),o){if(mt.current.set(n,o),l&&l!==o&&bn(l),rt.current[n]){Kt(n),vn(o),Rr(n);return}_r.current.get(n)&&Ac(n,o)&&xr(n),Yr(n,!0);return}if(l&&Go.current&&Wi.current.includes(n)){Qa(n,l),mt.current.delete(n),bn(l);return}mt.current.delete(n),Kt(n),bn(l),Rr(n)},[Rr,xr,Yr,Ac,Qa,vn,Kt,bn]),ev=s.useCallback((n,o)=>{const l=hn.current.get(n);if(o){hn.current.set(n,o),lt(n),l&&l!==o&&bn(l);const m=g===n&&Ye?Et.current.get(n):null;m&&xc(m,o)&&n===xt&&(Ic(n,"warm-reuse"),gn(!0)),m&&m!==o&&f0({decodeWidth:m.width,decodeHeight:m.height,presentationCssWidth:o.getBoundingClientRect().width,presentationCssHeight:o.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:wr.maxWidth,sourceHeight:wr.maxHeight})&&(Et.current.set(n,o),bn(m));return}hn.current.delete(n),lt(m=>m===n?"":m),bn(l)},[Ic,xt,g,Ye,wr.maxHeight,wr.maxWidth,xc,bn]),Tc=s.useCallback((n,o,l)=>{const m=performance.now(),d=ft(n,l.deviceId);let C=l;if(n==="control"&&l.visualChanged){const J=String(o.inputFeedbackEventId||""),ge=Number(o.inputFeedbackInputSeq||0),D=Number(o.inputFeedbackIssuedAtEpochMs||0),fe=Number(o.browserReceivedEpochMs||0),Ne=Em.current.get(l.deviceId)||"",We=D>0?Math.max(0,Date.now()-D):Number.POSITIVE_INFINITY;if(J.length>0&&ge>0&&J!==Ne&&We<=md){const Ue=Nm.current.get(l.deviceId)||[];Ue.push(We),Ue.length>vh&&Ue.splice(0,Ue.length-vh),Nm.current.set(l.deviceId,Ue),C={...l,inputFeedbackSeq:ge,inputFeedbackMs:We,inputFeedbackAt:m,inputFeedbackExact:!0,inputFeedbackEventId:J,inputFeedbackInputType:o.inputFeedbackInputType,inputFeedbackInputToFrameMs:fe>0?Math.max(0,fe-D):void 0,inputFeedbackFrameToPaintMs:fe>0?Math.max(0,Date.now()-fe):void 0,inputFeedbackAgentApplyMs:o.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:o.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Ue.length,inputFeedbackP50Ms:gs(Ue,.5),inputFeedbackP95Ms:gs(Ue,.95)},Em.current.set(l.deviceId,J),Zl.current.set(l.deviceId,ge)}else if(!J){const Ue=tC(l.deviceId),Yt=Zl.current.get(l.deviceId)||0,Xr=Ue?m-Ue.sentAt:Number.POSITIVE_INFINITY;Ue&&Ue.inputSeq>Yt&&Xr<=md&&(C={...l,inputFeedbackSeq:Ue.inputSeq,inputFeedbackMs:Math.max(0,Xr),inputFeedbackAt:m,inputFeedbackExact:!1},Zl.current.set(l.deviceId,Ue.inputSeq))}}const v=Nt.current.get(d)||0,S=v>0&&hr.current.get(d)||0;if(hr.current.set(d,m),Fn.current.delete(d),n==="control"&&ma.current.delete(d),gr.current.delete(d),v>0){const J=Oy({restartAttempts:v,healthySinceAt:Vr.current.get(d)||0,previousPaintAt:S,paintedAt:m,maximumHealthyGapMs:n==="control"?pd:Fh,stableForMs:n==="control"?Eh:Nh});J.resetAttempts?(Nt.current.delete(d),Vr.current.delete(d),Ft(n,o.deviceId,"stable","stable-paint-window",v)):J.healthySinceAt>0&&Vr.current.set(d,J.healthySinceAt)}const y=ua.current.get(d)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:m,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},w=er(o);y.bindingKey!==w&&(y.bindingKey=w,y.lastAt=void 0,y.lastFrameSeq=void 0,y.sampleChangedFrames=0,y.sampleDecoderInputBase=Number(l.decoderInputCount||0),y.sampleDecoderOutputBase=Number(l.decoderOutputCount||0),ml(y,m)),n==="control"&&C.inputFeedbackMs===void 0&&y.lastInfo?.inputFeedbackMs!==void 0&&y.lastInfo.inputFeedbackAt!==void 0&&m-y.lastInfo.inputFeedbackAt<=md&&(C={...C,inputFeedbackSeq:y.lastInfo.inputFeedbackSeq,inputFeedbackMs:y.lastInfo.inputFeedbackMs,inputFeedbackAt:y.lastInfo.inputFeedbackAt,inputFeedbackExact:y.lastInfo.inputFeedbackExact,inputFeedbackEventId:y.lastInfo.inputFeedbackEventId,inputFeedbackInputType:y.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:y.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:y.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:y.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:y.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:y.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:y.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:y.lastInfo.inputFeedbackP95Ms}),y.totalFrames+=1,y.sampleFrames+=1,Ah(y,m,C.frameSeq),C.visualChanged&&(y.totalChangedFrames+=1,y.sampleChangedFrames+=1),y.lastInfo=C,ua.current.set(d,y)},[Ft]),Pc=s.useCallback((n,o)=>{if(rt.current[n.deviceId]||la.current===n.deviceId||n.currentGenerationVerified!==!0||Vn.current.get(n.deviceId)!==er(n))return;Tc("wall",n,o);const l=Ye&&g===n.deviceId,m=mt.current.get(n.deviceId)||en.current.get(n.deviceId);ec.current&&!Re&&!l&&m?.isConnected&&Zo("wall-visible",n,o),n.kind==="live"&&(xr(n.deviceId),Kt(n.deviceId)),la.current!==n.deviceId&&!l&&(jr.current.delete(n.deviceId),ca.current.delete(n.deviceId),_o.current.delete(n.deviceId),$a.current.delete(n.deviceId))},[g,Ye,xr,Tc,Zo,Kt,Re]),Zm=s.useCallback((n,o)=>{if(rt.current[n.deviceId]||On(yt.current,ke.current)||ya(yt.current,ke.current)||yt.current&&ke.current&&dn(yt.current,ke.current)&&ho(yt.current,ke.current.deviceId,ke.current.sessionId)&&yt.current.monitorIndex===ke.current.monitorIndex||!Vu(n,ke.current))return;Tc("control",n,o),zt(v=>v&&"");const l=Et.current.get(n.deviceId),m=hn.current.get(n.deviceId);let d=!1;l&&l.width>0&&l.height>0&&(m&&Re&&n.deviceId===xt&&(d=xc(l,m),d&&Zo("control-visible",n,o)),Wa.current.set(n.deviceId,So(n)),jr.current.add(n.deviceId),n.deviceId===g&&(_e(!0),xe(v=>v==="connecting"?"active":v)),Yr(n.deviceId,!1,n));const C=ic.current;!C||!Wk(C,n)||!d||(Ic(n.deviceId,"fresh-frame"),gn(!0))},[Ic,xt,g,Yr,xc,Tc,Zo,Re]),Xa=s.useCallback((n,o)=>{const l=performance.now(),m=ft(n,o.deviceId);Hr.current.set(m,l),n!=="control"&&$r.current.delete(m);const d=Va.current.get(m)||{totalFrames:0,sampleFrames:0,sampleStartedAt:l,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},C=er(o);if(d.bindingKey!==C&&(d.bindingKey=C,d.lastAt=void 0,d.lastFrameSeq=void 0,d.lastContentHash=void 0,d.sampleBytes=0,d.sampleH264Frames=0,d.sampleTinyFrames=0,d.sampleRepeatedFrames=0,d.sourceSendIntervalsMs.length=0,ml(d,l)),d.totalFrames+=1,d.sampleFrames+=1,d.sampleBytes+=Math.max(0,Number(o.byteLength||0)),String(o.frameMode||o.mode||o.codec||o.mimeType||"").toLowerCase().includes("h264")){d.sampleH264Frames+=1,Number(o.byteLength||0)<=Ok&&(d.sampleTinyFrames+=1);const w=String(o.contentHash||"");w&&d.lastContentHash===w&&(d.sampleRepeatedFrames+=1),d.lastContentHash=w}const y=Number(o.agentSendGapMs||0);y>0&&y<1e3&&mb(d.sourceSendIntervalsMs,y),d.lastFrame=So(o),Ah(d,l,o.frameSeq),Va.current.set(m,d)},[]);s.useEffect(()=>{const n=new Set(Qm),o=new Set([...Hr.current.keys(),...hr.current.keys(),...da.current.keys(),...Fn.current.keys(),...gr.current.keys(),...Nt.current.keys(),...Vr.current.keys(),...$i.current.keys(),...ma.current.keys(),...Wr.current.keys(),...$r.current.keys(),...ua.current.keys(),...Va.current.keys()]);for(const d of o){if(n.has(d))continue;const C=d.indexOf(":"),v=d.slice(0,C),S=d.slice(C+1);(v==="wall"||v==="control")&&S&&zr(v,S)}const l=d=>{const C=Object.entries(d).filter(([v])=>n.has(v));return C.length===Object.keys(d).length?d:Object.fromEntries(C)};if(Yl(l),ac(l),n.size===0)return;const m=window.setInterval(()=>{const d=performance.now(),C={},v={};for(const S of n){const y=ua.current.get(S);if(y){const D=Math.max(1,d-y.sampleStartedAt);C[S]={bindingKey:y.bindingKey||"",totalFrames:y.totalFrames,totalChangedFrames:y.totalChangedFrames,framesPerSecond:y.sampleFrames*1e3/D,changedFramesPerSecond:y.sampleChangedFrames*1e3/D,averageIntervalMs:y.intervalCount>0?y.intervalSumMs/y.intervalCount:0,minIntervalMs:Number.isFinite(y.minIntervalMs)?y.minIntervalMs:0,maxIntervalMs:y.maxIntervalMs,p95IntervalMs:gs(y.intervalSamplesMs,.95),intervalCount:y.intervalCount,seqGapCount:y.seqGapCount,maxSeqGap:y.maxSeqGap,decoderInputFps:Math.max(0,(Number(y.lastInfo?.decoderInputCount||0)-y.sampleDecoderInputBase)*1e3/D),decoderOutputFps:Math.max(0,(Number(y.lastInfo?.decoderOutputCount||0)-y.sampleDecoderOutputBase)*1e3/D),sampleMs:D,lastInfo:y.lastInfo},y.sampleDecoderInputBase=Number(y.lastInfo?.decoderInputCount||0),y.sampleDecoderOutputBase=Number(y.lastInfo?.decoderOutputCount||0),y.sampleChangedFrames=0,ml(y,d)}const w=Va.current.get(S);if(!w)continue;const J=Math.max(1,d-w.sampleStartedAt),ge=w.lastFrame?So(w.lastFrame):void 0;w.lastFrame=ge,v[S]={totalFrames:w.totalFrames,framesPerSecond:w.sampleFrames*1e3/J,averageIntervalMs:w.intervalCount>0?w.intervalSumMs/w.intervalCount:0,minIntervalMs:Number.isFinite(w.minIntervalMs)?w.minIntervalMs:0,maxIntervalMs:w.maxIntervalMs,p95IntervalMs:gs(w.intervalSamplesMs,.95),intervalCount:w.intervalCount,seqGapCount:w.seqGapCount,maxSeqGap:w.maxSeqGap,averageFrameBytes:w.sampleFrames>0?w.sampleBytes/w.sampleFrames:0,tinyFrameRatio:w.sampleH264Frames>0?w.sampleTinyFrames/w.sampleH264Frames:0,repeatedFrameRatio:w.sampleH264Frames>0?w.sampleRepeatedFrames/w.sampleH264Frames:0,sourceSendAverageMs:w.sourceSendIntervalsMs.length>0?w.sourceSendIntervalsMs.reduce((D,fe)=>D+fe,0)/w.sourceSendIntervalsMs.length:0,sourceSendP95Ms:gs(w.sourceSendIntervalsMs,.95),sourceSendSampleCount:w.sourceSendIntervalsMs.length,sampleMs:J,lastFrame:ge},w.sampleBytes=0,w.sampleH264Frames=0,w.sampleTinyFrames=0,w.sampleRepeatedFrames=0,w.sourceSendIntervalsMs.length=0,ml(w,d)}Yl(C),ac(v)},1e3);return oc.current=m,()=>{window.clearInterval(m),oc.current===m&&(oc.current=null)}},[Qm,zr]);const ep=s.useCallback(n=>{const o=O;if(te.current!==o)return;const l=n.deviceId,m=er(n);if(rt.current[l]||la.current===l||n.currentGenerationVerified!==!0||Vn.current.get(l)!==m)return;Xa("wall",n);const d=mt.current.get(l);if(!d)return;const C=$o(d),v=Vo(d),S=()=>mt.current.get(l)!==d||!zo(d,C)||te.current!==o||!!rt.current[l]||la.current===l||Vn.current.get(l)!==m,y=()=>S()||!Ua(d,v),w=k0(tt,De.h264DecodeAcceleration);Xu(d,n,y,Pc,w.acceleration,w.latencyMode,S,Rc).catch(()=>{})},[$o,Ua,zo,Vo,Pc,tt,Xa,Rc,De.h264DecodeAcceleration,O]),tp=s.useCallback(n=>{const o=O;if(te.current!==o)return;const l=n.deviceId;if(rt.current[l]||On(yt.current,ke.current)||ya(yt.current,ke.current)||yt.current&&ke.current&&dn(yt.current,ke.current)&&ho(yt.current,ke.current.deviceId,ke.current.sessionId)&&yt.current.monitorIndex===ke.current.monitorIndex||!Vu(n,ke.current))return;let m=Et.current.get(l);if(!m){const fe=hn.current.get(l),Ne=Ha.current;m=fe||Ne||document.createElement("canvas"),fe&&Ne&&Ne!==fe&&vn(Ne),Ha.current=null,m!==fe&&m.setAttribute("aria-hidden","true"),Et.current.set(l,m)}const d=m,C=n,v=$o(d),S=Vo(d),y=()=>Et.current.get(l)!==d||!zo(d,v)||te.current!==o||!!rt.current[l]||!Vu(C,ke.current),w=()=>y()||!Ua(d,S),J=xi.current,ge=String(n.frameMode||n.mode||n.codec||n.mimeType||"").toLowerCase().includes("h264");ge||Xa("control",n);const D=Xu(d,n,w,Zm,on.h264DecodeAcceleration,"interactive",y);ge&&Xa("control",n),D.catch(fe=>{xi.current!==J||Et.current.get(l)!==d||!Ua(d,S)||y()||g!==l||zt(fe instanceof Error?fe.message:String(fe||"Control H.264 decode failed"))})},[$o,Ua,zo,Vo,g,on.h264DecodeAcceleration,Zm,Xa,vn,O]),tv=s.useCallback(n=>{const o=Nn.current;Nn.current=n,o&&o!==n&&bn(o),Hi.current=0,cc.current=0,lc.current=0,uc.current=0,Jl.current=0,_i.current=0},[bn]),ei=s.useCallback(()=>{const n=new Set,o=O;if(te.current!==o)return n;const l=Nn.current,m=Bo.current;if(!l||!m||l.width<=0||l.height<=0||_i.current!==m.layoutVersion)return n;for(const d of m.tiles){if(rt.current[d.deviceId])continue;const C=en.current.get(d.deviceId);if(!C||d.width<=0||d.height<=0)continue;const v=Math.max(1,Math.round(d.width)),S=Math.max(1,Math.round(d.height)),y=_k,w=jk;(C.width!==y||C.height!==w)&&(C.width=y,C.height=w);const J=C.getContext("2d",{alpha:!1});if(J){J.imageSmoothingEnabled=!0,J.imageSmoothingQuality="high";try{J.drawImage(l,Math.round(d.x),Math.round(d.y),v,S,0,0,y,w),n.add(d.deviceId)}catch{}}}return n},[O]),nv=s.useCallback((n,o)=>{const l=en.current.get(n);if(o&&l&&l!==o&&Qa(n,l),o){if(en.current.set(n,o),l&&l!==o&&bn(l),rt.current[n]){Kt(n),vn(o),Rr(n);return}_r.current.get(n)&&Ac(n,o)&&xr(n),window.requestAnimationFrame(()=>{ei().has(n)&&Kt(n)}),window.requestAnimationFrame(()=>Yr(n,!0));return}en.current.delete(n),Kt(n),bn(l),Rr(n)},[Rr,xr,ei,Yr,Ac,Qa,vn,Kt,bn]),np=s.useCallback((n,o)=>{if(te.current!==O)return;lc.current=performance.now(),_i.current=Number(n.layoutVersion||0),ei();const l=Bo.current?.tiles||[],m=l.length>0?Math.round(n.byteLength/l.length):n.byteLength;for(const d of l){if(rt.current[d.deviceId])continue;const C={...n,deviceId:d.deviceId,width:d.width,height:d.height,sourceWidth:d.width,sourceHeight:d.height,byteLength:m};Pc(C,{...o,deviceId:d.deviceId,width:d.width,height:d.height,byteLength:m}),la.current===d.deviceId&&Yr(d.deviceId,!0)}},[Pc,ei,Yr,O]),rv=s.useCallback(n=>{const o=O;if(te.current!==o)return;const l=performance.now();Hi.current<=0&&(Hi.current=l),cc.current=l;const m=Nn.current;if(!m)return;const d=er(n);Oi.current!==d&&(Oi.current=d,$t(m));const C=$o(m),v=Vo(m),S=()=>Nn.current!==m||Oi.current!==d||te.current!==o||!zo(m,C),y=()=>S()||!Ua(m,v),w=Bo.current?.tiles||[],J=w.length>0?Math.round(n.byteLength/w.length):n.byteLength;for(const ge of w)rt.current[ge.deviceId]||Xa("wall",{...n,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:J});Xu(m,n,y,np,void 0,"smooth",S).catch(()=>{})},[$o,Ua,zo,Vo,np,Xa,$t,O]),rp=s.useCallback(n=>{const o=j&&n.streamPurpose==="control"&&n.readOnlyControlBorrow===!0&&n.presentationPurpose==="wall";if(n.streamPurpose!=="wall"&&!o||rt.current[n.deviceId])return;const l=er(n);Vn.current.get(n.deviceId)!==l&&(Vn.current.set(n.deviceId,l),$t(mt.current.get(n.deviceId)),ve.current&&$({type:"frame.owner.changed",component:`wall-owner:${n.deviceId}`,state:"bound",reason:`owner:${n.sessionId||"unknown"}:${n.captureGeneration||"unknown"}:${n.monitorIndex}`,details:{deviceId:n.deviceId,sessionId:n.sessionId||"unknown",streamId:n.streamId||"unknown",commandId:n.commandId||"unknown",captureGeneration:n.captureGeneration||"unknown",monitorIndex:n.monitorIndex,streamPurpose:n.streamPurpose||"unknown",presentationPurpose:n.presentationPurpose||"unknown"}}))},[j,$,$t]),uu=s.useMemo(()=>({fps:ln.fps,maxWidth:ln.maxWidth,maxHeight:ln.maxHeight,quality:ln.quality,mode:tt?"mode3-h264-hw":De.frameMode,frameMode:tt?"mode3-h264-hw":De.frameMode,streamPurpose:"wall",allowReadOnlyControlBorrow:j,configurationRefreshMs:gk,connectionSessionIds:yn,monitorSelections:gt,onFrame:ep,onStreamReady:rp}),[yn,ep,rp,j,tt,gt,De.frameMode,ln.fps,ln.maxHeight,ln.maxWidth,ln.quality]),Ec=s.useCallback(n=>{const o=ut.current;if(o!=="connecting"&&o!=="active"&&o!=="warm"&&o!=="stopping")return Ft("control",n.deviceId,"stop-deferred",`stream-binding-ignored-during-${o}`,Nt.current.get(ft("control",n.deviceId))||0),null;const l=ke.current;if(rt.current[n.deviceId]||!l||l.deviceId!==n.deviceId||n.deviceId!==g||n.streamPurpose!=="control"||n.monitorIndex!==ir)return null;const m=eu.current[n.deviceId]||"";if(!m||m!==n.sessionId)return null;const d=zu(l.deviceId,l.transitionGeneration,n),C=dn(l,d)&&ho(l,d.deviceId,d.sessionId)&&l.monitorIndex===d.monitorIndex;return!Uu(l,d)&&!ya(l,d)&&!C?(Ft("control",n.deviceId,"owner-replaced","stale-stream-binding-ignored",Nt.current.get(ft("control",n.deviceId))||0),null):(Uu(l,d)||(ke.current=d,ve.current&&$({type:"frame.owner.changed",component:`control-owner:${n.deviceId}`,state:"bound",reason:`owner:${n.sessionId||"unknown"}:${n.captureGeneration||"unknown"}:${n.monitorIndex}`,details:{deviceId:n.deviceId,sessionId:n.sessionId||"unknown",streamId:n.streamId||"unknown",commandId:n.commandId||"unknown",captureGeneration:n.captureGeneration||"unknown",monitorIndex:n.monitorIndex,streamPurpose:n.streamPurpose}}),Ft("control",n.deviceId,"owner-bound","hub-start-descriptor",Nt.current.get(ft("control",n.deviceId))||0)),d)},[g,Ft,$,ir]),ap=s.useCallback(n=>{const o=Ec(n);if(!o)return;const l=yt.current;if(On(l,o)||ya(l,o)||!!l&&dn(l,o)&&ho(l,o.deviceId,o.sessionId)&&l.monitorIndex===o.monitorIndex)return;yt.current&&(yt.current=null,Ft("control",n.deviceId,"owner-replaced","stream-ready-superseded-stale-downshift",Nt.current.get(ft("control",n.deviceId))||0));const d=ut.current;if(d!=="connecting"&&d!=="active"&&d!=="warm"){Ft("control",n.deviceId,"stop-deferred",`stream-ready-ignored-during-${d}`,Nt.current.get(ft("control",n.deviceId))||0);return}const C=nt.current;(!C||er(C)!==er(n))&&$t(Et.current.get(n.deviceId)),nt.current=n,ht(n),xe(_y)},[Ec,Ft,$t]);s.useEffect(()=>{$t(Et.current.get(g)),nt.current=null,ht(null)},[g,N,Gn,$t,ir]);const Nc=N?`${N}-monitor-${ir}`:"",du=s.useMemo(()=>({fps:Gi,maxWidth:wr.maxWidth,maxHeight:wr.maxHeight,quality:on.quality,mode:Gn,frameMode:Gn,streamPurpose:"control",forceRestart:Nc!=="",forceRestartToken:Nc,restartReason:Nc?"control-session-or-monitor-change":"",connectionSessionIds:yn,monitorSelections:gt,onFrame:tp,onStreamBound:Ec,onStreamReady:ap}),[yn,Nc,on.quality,tp,Gi,Gn,wr.maxHeight,wr.maxWidth,Ec,ap,gt]),{frames:op,state:Qi,error:Fc,stats:Ja,restartLive:ip,reconnectLive:mu}=Ef(Gt,De.autoStartLive&&Gt.length>0,K,uu,O);s.useEffect(()=>{const n=new Set(Gt),o=ve.current?[]:null;for(const l of Vn.current.keys())n.has(l)||(Vn.current.delete(l),$t(mt.current.get(l)),o?.push({type:"frame.owner.changed",component:`wall-owner:${l}`,state:"unbound",reason:"device-no-longer-requested",details:{deviceId:l}}));o&&o.length>0&&oe(o)},[Gt,oe,$t]);const{frame:ti,layout:Za,state:Xi,stats:av,refreshInputs:sp}=iC(nn,tt&&De.autoStartLive&&nn.length>0,K,{fps:wt.atlasOutputFps,inputFps:lu,width:1920,height:1080,tileWidth:Jo.maxWidth,tileHeight:Jo.maxHeight,captureDeviceIds:nn,connectionSessionIds:yn,monitorSelections:gt,onFrame:rv},O);s.useEffect(()=>{Bo.current=Za,Za&&window.requestAnimationFrame(ei)},[Za,ei]),s.useEffect(()=>{if(!tt||Xi!=="open"){Hi.current=0,cc.current=0,lc.current=0;return}const n=window.setInterval(()=>{const o=Nn.current,l=performance.now();if(!o||document.visibilityState!=="visible"||l-sc.current<dd)return;const m=cc.current,d=Hi.current;if(m<=0||d<=0||l-m>500)return;const C=lc.current||d,v=l-C;if(v>=Ak&&l-Jl.current>=Tk){fi(o)&&(Jl.current=l,uc.current=l);return}v>=Rk&&l-uc.current>=Ik&&zw(o)&&(uc.current=l)},250);return()=>window.clearInterval(n)},[Xi,tt]);const{frames:Ji,state:Dc,error:eo,stats:ov,restartLive:Lc,reconnectLive:Zi}=Ef(Gr,Gr.length>0,K,du,O);s.useEffect(()=>{ve.current&&oe([{type:"frame.transport.changed",component:"wall-frame-socket",state:Qi||"unknown",reason:Fc||`desired-owners:${Gt.length}`,details:{desiredOwnerCount:Gt.length,frameMode:uu.frameMode,managerHubUrl:K||"unknown"}},{type:"frame.transport.changed",component:"control-frame-socket",state:Dc||"unknown",reason:eo||`desired-owners:${Gr.length}`,details:{desiredOwnerCount:Gr.length,frameMode:du.frameMode,managerHubUrl:K||"unknown"}},{type:"frame.transport.changed",component:"atlas-frame-socket",state:Xi||"unknown",reason:`desired-owners:${nn.length}`,details:{desiredOwnerCount:nn.length,enabled:tt,managerHubUrl:K||"unknown"}},{type:"stream.state.changed",component:"wall-subscription",state:yr&&De.autoStartLive?"requested":"idle",reason:qt?`tool:${It}:desired-owners:${Gt.length}`:"document-hidden",details:{documentVisible:qt,captureOwnershipActive:yr,autoStartLive:De.autoStartLive,activeTool:It,desiredOwnerCount:Gt.length}},{type:"stream.state.changed",component:`control-session:${g||"unknown"}`,state:be,reason:`frame-transport:${Dc||"unknown"}`,details:{deviceId:g||"unknown",bindingSessionId:ct?.sessionId||"unknown",bindingStreamId:ct?.streamId||"unknown",bindingCaptureGeneration:ct?.captureGeneration||"unknown",bindingMonitorIndex:ct?.monitorIndex??"unknown"}}])},[It,Xi,Gr.length,eo,Dc,du.frameMode,g,be,ct,Gt.length,qt,K,nn.length,tt,ot,oe,De.autoStartLive,yr,Fc,Qi,uu.frameMode]),s.useEffect(()=>{const n=Mm.current,o=new Set([...Object.keys(n),...Object.keys(gt)]);for(const l of o){const m=Math.max(0,Math.floor(Number(n[l])||0)),d=Math.max(0,Math.floor(Number(gt[l])||0));m!==d&&(Vn.current.delete(l),$t(mt.current.get(l)),$t(Et.current.get(l)),$t(en.current.get(l)),Dt("wall",l),Dt("control",l),fi(mt.current.get(l)||null),fi(Et.current.get(l)||null))}o.size>0&&($t(Nn.current),fi(Nn.current)),Mm.current={...gt}},[gt,Dt,$t]);const ni=s.useMemo(()=>{const n=(l,m)=>{const d=Le.find(v=>v.deviceId===l),C=d?_n(d,gt[l]):0;return!Number.isFinite(Number(m.monitorIndex))||Number(m.monitorIndex)===C},o=new Map;for(const[l,m]of op.entries())n(l,m)&&o.set(l,m);if(tt&&ti&&nn.length>0){const l=new Map((Za?.tiles||[]).map(d=>[d.deviceId,d])),m=Math.max(1,l.size);for(const d of nn){const C=l.get(d);C&&o.set(d,{...ti,deviceId:d,width:C.width,height:C.height,sourceWidth:C.width,sourceHeight:C.height,byteLength:Math.round(ti.byteLength/m)})}}for(const[l,m]of Ji.entries())n(l,m)&&o.set(l,m);for(const l of Sc){if(!jr.current.has(l)||o.has(l))continue;const m=Wa.current.get(l);m&&n(l,m)&&o.set(l,m)}return o},[ti,Za,Le,Ji,nn,tt,gt,op,Sc,Eb]),pu=Re&&Gr.length>0?Dc:nn.length>0?Xi:Qi,Oc=Re&&Gr.length>0?ov:nn.length>0?av:Ja;s.useCallback((n,o="browser-stale")=>{const l=ip(n,o),m=Lc(n,o);return l||m},[Lc,ip]),s.useEffect(()=>{tt&&nn.length>0&&!Re&&sp()},[nn.length,tt,sp,Re]);const ri=s.useCallback((n,o,l)=>{const m=o==="control"?Et.current.get(n)||null:mt.current.get(n)||null;if(!m)return!1;fi(m);const d=performance.now();return gr.current.set(ft(o,n),d),!0},[]),es=s.useCallback(n=>{if(Gn!=="mode3-h264-hw"||!g||Y)return!1;const o=Le.find(S=>S.deviceId===g)||tn,l=Gh(o?.platform);if(!l)return!1;const m=ft("control",g),d=Nt.current.get(m)||0;Ft("control",g,"fallback",n,d),Dt("control",g,{preserveLatestDiagnostic:!0}),fi(Et.current.get(g)||null),Zi([g],"control-decode-fallback"),Ie(l),he(`control-${l}-fallback-${g}-${Date.now()}`),_e(!1),gn(!1);const C=n==="no first frame"||n==="control-first-frame-timeout",v=l==="mode1-jpeg"?"Mode 1 JPEG":"Mode 5";return zt(S=>S||(C?`Control frame transport timeout; retrying Control with ${v} (${n})`:`H.264 decode failed; retrying Control with ${v} (${n})`)),xe("connecting"),!0},[Le,tn,g,Y,Gn,Zi,Ft,Dt]);s.useEffect(()=>{const n=Re?tn:null;if(n){ic.current={deviceId:n.deviceId,monitorIndex:ir,frameMode:Gn,startedAtEpochMs:Date.now()},gn(g===n.deviceId&&Ye);return}ic.current=null,gn(!1)},[tn?.sessionId,xt,g,Ye,Gn,ir,Re]);const cp=s.useCallback(async(n,o)=>{const l=String(o.streamId||"").trim(),m=String(o.streamPurpose||"").trim(),d=String(o.sessionId||"").trim(),C=String(o.commandId||"").trim(),v=Number(o.captureGeneration||0),S=Number(o.monitorIndex??-1);if(!l||!["wall","atlas"].includes(m)||!d||!C||!Number.isSafeInteger(v)||v<=0||!Number.isSafeInteger(S)||S<0)throw new Error("wall-start-owner-incomplete");const y=performance.now()+3e3;for(;;){const w=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:l,streamPurpose:m,expectedSessionId:d,expectedCommandId:C,expectedCaptureGeneration:v,expectedMonitorIndex:S,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},K);if(w?.ok===!1)throw new Error(w.error||"revoked-wall-start-stop-failed");if(w?.captureStopConfirmed===!0||w?.alreadyStopped===!0||w?.staleOwner===!0)return w;if(w?.presentationOwnerActive===!0||w?.retainedForPresentation===!0){if(qn.current&&Go.current)return w;if(performance.now()<y){await new Promise(J=>window.setTimeout(J,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[K]),to=s.useCallback(async n=>{if(rt.current[n])throw new Error("LIVE_CAPTURE_PAUSED");if(!qn.current||!Go.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const o=rr.current,l=Me.find(v=>v.deviceId===n);fs({mode4Enabled:tt,directMode4WallEnabled:Mr,isMac:Nr(l?.platform)});const m=l?_n(l,gt[n]):0,d={fps:ln.fps,maxWidth:ln.maxWidth,maxHeight:ln.maxHeight,quality:ln.quality,mode:tt?"mode3-h264-hw":De.frameMode,frameMode:tt?"mode3-h264-hw":De.frameMode,streamPurpose:"wall",monitorIndex:m},C=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/start`,{method:"POST",body:JSON.stringify(d)},K);if(C?.ok===!1)throw new Error(C.error||"wall-stream-start-failed");return o!==rr.current||!qn.current||!Go.current?(await cp(n,C),{...C,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):C},[lu,Me,Mr,K,tt,gt,cp,De.frameMode,Jo.maxHeight,Jo.maxWidth,ln.fps,ln.maxHeight,ln.maxWidth,ln.quality]),lp=s.useCallback(async n=>{const o=Me.find(m=>m.deviceId===n);fs({mode4Enabled:tt,directMode4WallEnabled:Mr,isMac:Nr(o?.platform)});const l=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},K);if(l?.ok===!1)throw new Error(l.error||"wall-stream-stop-failed");return l},[Me,Mr,K,tt]),up=s.useCallback(async(n,o="control-session-stop")=>{if(!Xc(n))return Ft("control",n.deviceId,"stop-deferred",`${o}:unbound-stop-deferred-to-frame-owner`,Nt.current.get(ft("control",n.deviceId))||0),{ok:!0,pendingOwner:!0,deferredToFrameOwner:!0};const m=await ze(`/api/remote/devices/${encodeURIComponent(n.deviceId)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:n.streamId,expectedSessionId:n.sessionId,expectedCommandId:n.commandId,expectedCaptureGeneration:n.captureGeneration,expectedMonitorIndex:n.monitorIndex,streamPurpose:"control",reason:o})},K);if(m?.ok===!1)throw new Error(m.error||"control-stream-stop-failed");return(m?.staleOwner===!0||m?.retainedNewerOwner===!0)&&Ft("control",n.deviceId,"owner-replaced",`${o}:hub-retained-newer-owner`,Nt.current.get(ft("control",n.deviceId))||0),m},[K,Ft]),Rn=s.useCallback((n,o={})=>{yt.current?.deviceId===n&&(yt.current=null);const l=Et.current.get(n);if(l){const d=_r.current.has(n)||mt.current.has(n)||en.current.has(n);o.preservePresentation!==!1&&!d&&Qa(n,l),Et.current.delete(n),vn(l),!(hn.current.get(n)||mt.current.get(n)||en.current.get(n))&&!Ha.current&&(Ha.current=l)}const m=hn.current.get(n);m&&pi(m),Wa.current.delete(n),jr.current.delete(n),ca.current.delete(n),_o.current.delete(n),$a.current.delete(n),zr("control",n)},[zr,Qa,vn]),_c=s.useCallback(n=>{const o=[ft("wall",n),ft("control",n)];for(const l of o){const m=Va.current.get(l);m?.lastFrame&&(m.lastFrame=So(m.lastFrame))}ac(l=>{let m=!1;const d={...l};for(const C of o){const v=l[C];!v?.lastFrame||v.lastFrame.payload.byteLength===0||(d[C]={...v,lastFrame:So(v.lastFrame)},m=!0)}return m?d:l})},[]),fu=s.useCallback(n=>{Vn.current.delete(n),Kt(n),Rn(n,{preservePresentation:!1});const o=new Set;for(const l of[hn.current.get(n),mt.current.get(n),en.current.get(n)])l&&o.add(l);for(const l of o)vn(l);Rr(n),g===n&&(ic.current=null,gn(!1),_e(!1)),Ii.current.add(n),_c(n)},[Rr,g,vn,Rn,_c,Kt]);s.useEffect(()=>{const n=new Set(Object.keys(na));for(const o of n)Ii.current.has(o)||fu(o);for(const o of Ii.current)n.has(o)||Ii.current.delete(o)},[fu,na]);const ai=s.useCallback(n=>{const o=lf(Rm.current,n);return Rm.current=o.tail,o.result},[]),Yn=s.useCallback(n=>{const o=lf(Pm.current,n);return Pm.current=o.tail,o.result},[]),Qn=s.useCallback(n=>{xn.current=n,Zs.current=0;const o=n?.deviceId||"";la.current=o,Ab(o),o&&jr.current.add(o)},[]),oi=s.useCallback(n=>ai(async()=>{if(rt.current[n.deviceId])return!1;const o=xn.current;return!dn(o,n)||!Jc(n.deviceId,n,ke.current)?!1:(await to(n.deviceId),dn(xn.current,n)&&Qn(null),!0)}),[Qn,ai,to]),dp=s.useCallback((n,o,l)=>ai(async()=>{const m=xn.current;if(dn(m,n))return l.stoppedWallDeviceId=n.deviceId,!0;if(m)if(rt.current[m.deviceId])dn(xn.current,m)&&Qn(null);else{if(!Jc(m.deviceId,m,ke.current))return!1;await to(m.deviceId),dn(xn.current,m)&&Qn(null)}if(!o())return!1;if(await lp(n.deviceId),l.stoppedWallDeviceId=n.deviceId,!o()){if(Jc(l.stoppedWallDeviceId,n,ke.current))try{await to(l.stoppedWallDeviceId)}catch(d){throw Qn(n),d}finally{l.stoppedWallDeviceId=""}return!1}return pi(mt.current.get(n.deviceId)||null),Qn(n),!0}),[Qn,ai,to,lp]),jc=s.useCallback(async(n,o)=>{if(o.stoppedWallDeviceId){if(dn(xn.current,n)){try{await oi(n)}catch(l){B(l instanceof Error?l.message:String(l))}finally{o.stoppedWallDeviceId=""}return}await ai(async()=>{if(!o.stoppedWallDeviceId||!Jc(o.stoppedWallDeviceId,n,ke.current))return;const l=o.stoppedWallDeviceId;try{await to(l)}catch(m){Qn(n),B(m instanceof Error?m.message:String(m))}finally{o.stoppedWallDeviceId=""}})}},[Qn,ai,oi,B,to]),Xn=s.useCallback(async(n,o,l={})=>{const m=l.allowStopFailure===!0,d=l.resumeWall!==!1,C=S=>{const y=ke.current;if(!y)return S;const w=Xc(y)&&dn(y,S)&&ho(S,y.deviceId,y.sessionId)&&S.monitorIndex===y.monitorIndex;return On(y,S)||ya(S,y)||w?y:S};let v=C(n);for(let S=0;S<2;S+=1){try{await up(v,o)}catch(w){if(!m)throw w}const y=C(v);if(On(y,v)||Uu(y,v)||!Xc(y)||!dn(y,v))break;v=y}if(!On(ke.current,v))return!1;if(ke.current=null,nt.current=null,ht(null),Rn(v.deviceId),_e(!1),he(""),Ie(""),zt(""),U(S=>S===v.deviceId?"":S),!d)return dn(xn.current,v)&&Qn(null),!0;try{await oi(v)}catch(S){B(S instanceof Error?S.message:String(S))}return!0},[Qn,Rn,oi,B,up]),mp=(qt&&Re&&pt&&xt&&!Ti.has(xt)&&Le.find(n=>n.deviceId===xt)||null)?.deviceId||"";s.useEffect(()=>{Ho.current=mp},[mp]),s.useEffect(()=>{const n=xt&&Le.find(C=>C.deviceId===xt)||null;if(!qt||!Re||!pt||!n){sn.current&&(++Ht.current,sn.current="");return}if(rt.current[n.deviceId]){sn.current&&(++Ht.current,sn.current=""),g===n.deviceId&&xe("paused");return}if(Un.current){if(Un.current===n.deviceId)return;Un.current=""}if(g===n.deviceId&&ho(ke.current,n.deviceId,n.sessionId||"")&&(be==="active"||be==="warm"||be==="connecting")){xe(C=>C==="warm"?"active":C);return}if(sn.current===n.deviceId)return;const o=++Ht.current,l=zu(n.deviceId,o,{sessionId:n.sessionId,monitorIndex:ir});sn.current=n.deviceId;const m={stoppedWallDeviceId:""},d=()=>o===Ht.current&&Ho.current===l.deviceId;Yn(async()=>{if(!d())return;const C=ke.current;if(C){xe("stopping");try{await Xn(C,"control-session-switch")}catch(y){d()&&(xe("error"),B(y instanceof Error?y.message:String(y)));return}if(!d()){ke.current||xe("idle");return}}try{if(!await dp(l,d,m)||!d()){await jc(l,m),ke.current||xe("idle");return}}catch(y){await jc(l,m),d()&&(xe("error"),B(y instanceof Error?y.message:String(y)));return}if(!d()){await jc(l,m);return}ke.current=l,yt.current=null,Un.current="",za.current=null,Wo.current=0,Bi.current="",m.stoppedWallDeviceId="";const v=ft("control",l.deviceId),S=`control-session-${o}-${l.deviceId}`;Wr.current.set(v,performance.now()),Hr.current.delete(v),hr.current.delete(v),da.current.delete(v),Fn.current.delete(v),gr.current.delete(v),Nt.current.delete(v),Vr.current.delete(v),ma.current.delete(v),Ie(""),zt(""),he(S),U(l.deviceId),_e(!1),xe("connecting")}).catch(C=>{d()&&(xe("error"),B(C instanceof Error?C.message:String(C)))}).finally(()=>{Ht.current===o&&sn.current===l.deviceId&&(sn.current="")})},[Le,xt,g,be,qt,Yn,pt,dp,jc,ir,B,Re,Xn,na]),s.useEffect(()=>{if(!g||Le.some(l=>l.deviceId===g))return;const n=g;++Ht.current,sn.current="";const o=ke.current;xe("stopping"),Yn(async()=>{o&&o.deviceId===n?await Xn(o,"control-device-disconnected",{allowStopFailure:!0}):(Rn(n),U(l=>l===n?"":l)),ke.current||xe("idle")})},[Le,g,Yn,Rn,Xn]),s.useEffect(()=>{if(zn.current!==null&&(window.clearTimeout(zn.current),zn.current=null),!or||Re||!g||rt.current[g]||be!=="connecting"&&be!=="active"&&be!=="warm")return;const n=g,o=ke.current;if(!o||o.deviceId!==n)return;const l=window.setTimeout(()=>{zn.current===l&&(zn.current=null);const m=ke.current,d=S=>On(S,o)||ya(o,S)||!!S&&dn(S,o)&&ho(o,S.deviceId,S.sessionId)&&o.monitorIndex===S.monitorIndex;if(Ho.current||rt.current[n]||!d(m))return;const C=m||o;yt.current=C;const v=++Ht.current;sn.current="",xe("stopping"),Yn(async()=>{if(v!==Ht.current||Ho.current||!d(ke.current)){(On(yt.current,C)||ya(yt.current,C))&&(yt.current=null);const S=ke.current;Ho.current&&Xc(S)&&S?.deviceId===n&&xe("active");return}try{await Xn(C,"control-session-wall-downshift")}catch(S){(On(yt.current,C)||ya(yt.current,C))&&(yt.current=null),v===Ht.current&&!Ho.current&&d(ke.current)&&(xe("active"),B(S instanceof Error?S.message:String(S)));return}yt.current=null,v===Ht.current&&!ke.current&&xe("idle")})},Lk);return zn.current=l,()=>{zn.current===l&&(window.clearTimeout(l),zn.current=null)}},[g,be,Yn,B,Re,Xn,na,or]);const Bc=s.useCallback(n=>{if(Tm.current===n)return;Tm.current=n;const o=ke.current,l=o?.deviceId||g,m=++Ht.current;sn.current="",nt.current=null,ji.current=!0,ht(null),_e(!1),gn(!1),l&&(Dt("control",l),Rn(l,{preservePresentation:!1}),xe("stopping"),Yn(async()=>{if(o&&o.deviceId===l)try{await Xn(o,"control-session-document-hidden",{resumeWall:!1})}catch(d){!qn.current&&rr.current===n&&(xe("error"),B(d instanceof Error?d.message:String(d)));return}else Rn(l,{preservePresentation:!1}),U(d=>d===l?"":d);!ke.current&&Ht.current===m&&xe("idle")}))},[g,Yn,Rn,Dt,B,Xn]);s.useEffect(()=>{if(nr.current!==null&&(window.clearTimeout(nr.current),nr.current=null),!g||be==="idle"||be==="paused"||be==="error")return;if(!qt){Bc(rr.current);return}if(be==="stopping"||Ko){g&&pc&&be==="connecting"&&(ji.current=!1),g&&pc&&ji.current&&(be==="warm"||be==="active")&&(ji.current=!1,nt.current=null,ht(null),_e(!1),gn(!1),Dt("control",g),he(`control-presentation-resume-${Date.now()}-${g}`),xe("connecting"));return}nt.current=null,ji.current=!0,ht(null),_e(!1),gn(!1),xe(o=>o==="idle"||o==="stopping"?o:"warm");const n=g;return Rn(n,{preservePresentation:!1}),nr.current=window.setTimeout(()=>{nr.current=null,++Ht.current,sn.current="";const o=ke.current;xe("stopping"),Yn(async()=>{if(o&&o.deviceId===n)try{await Xn(o,"control-session-warm-timeout")}catch(l){xe("error"),B(l instanceof Error?l.message:String(l));return}else Rn(n),U(l=>l===n?"":l);ke.current||xe("idle")})},Dk),()=>{nr.current!==null&&(window.clearTimeout(nr.current),nr.current=null)}},[Ko,pc,g,be,qt,Yn,Rn,Bc,Dt,B,Xn]),s.useEffect(()=>()=>{nr.current!==null&&window.clearTimeout(nr.current),zn.current!==null&&(window.clearTimeout(zn.current),zn.current=null),yt.current=null},[]);const Hc=s.useCallback(()=>{const n=new Set(Xl.current),o=ke.current?.deviceId||"";g&&n.add(g),o&&n.add(o),Xl.current=[];for(const m of n){Vn.current.delete(m),Kt(m),Rn(m,{preservePresentation:!1});for(const d of[mt.current.get(m),hn.current.get(m),en.current.get(m)])d&&vn(d);Rr(m),Dt("wall",m),Dt("control",m),_c(m)}const l=Nn.current;l&&vn(l),Oi.current="",Bo.current=null,_i.current=0},[Rr,g,vn,Rn,_c,Kt,Dt]);s.useEffect(()=>{if(qt){Xl.current=[...cu];return}Hc()},[qt,cu,Hc]),s.useEffect(()=>{const n=xn.current,o=ke.current;if(!or||!n||rt.current[n.deviceId]||o&&o.deviceId===n.deviceId){Zs.current=0;return}const l=Zs.current,m=Math.min(5e3,500*2**Math.min(l,4)),d=window.setTimeout(()=>{jo.current===d&&(jo.current=null);const C=xn.current;!Wm.current||!C||rt.current[C.deviceId]||!dn(C,n)||(Zs.current=l+1,oi(C).catch(v=>{B(v instanceof Error?v.message:String(v)),dn(xn.current,C)&&!ke.current&&Tb(S=>S+1)}))},m);return jo.current=d,()=>{window.clearTimeout(d),jo.current===d&&(jo.current=null)}},[be,oi,B,or,Ib,Di]);const ga=g&&Le.find(n=>n.deviceId===g)||null,ba=ga?.deviceId||"",iv=!!(qt&&Re&&kn&&Cr),ts=!!(Re&&kn&&be==="active"&&ga?.sessionId&&ct?.deviceId===ga.deviceId&&ct.sessionId===ga.sessionId&&ct.streamPurpose==="control"&&ct.commandId&&ct.captureGeneration>0&&ct.monitorIndex===ir),pp=ga?.capabilities?.clipboardProtocol==="livedesk.clipboard.v1",fp=pp&&vi(ga,"clipboardCopy"),hp=pp&&vi(ga,"clipboardPaste"),{state:ns,connectionId:no,routeReady:Wc,sendInput:gp,stats:Ar,error:bp,remotePointerFeedback:ro}=sC(iv,K,ba,O),ao=ga?.sessionId||"",oo=ct?.commandId||"",io=Number(ct?.captureGeneration||0),ii=Number(ct?.monitorIndex||0),sv=ro&&ro.deviceId===ba&&ro.monitorIndex===ii&&ro.controlSessionId===ao&&ro.controlCommandId===oo&&ro.captureGeneration===io?ro:null,rs=s.useCallback((n,o)=>{const l=String(o.type||"").trim().toLowerCase();return Ks.current&&l!=="keyboard.reset"||!qn.current||!ts||!ba||!ao||!oo||io<=0||n!==ba?!1:gp(n,{...o,monitorIndex:ii,controlSessionId:ao,controlCommandId:oo,captureGeneration:io})},[ts,io,oo,ba,ii,ao,gp]),$c=[ba,ao,oo,io,ii,no].join("|"),hu=s.useRef($c);hu.current=$c;const Vc=s.useRef(null),wn=s.useCallback(async(n,o,l,m,d=15e3)=>{if(!no||hu.current!==m)throw new Error("Remote Control changed before the clipboard transfer completed.");const C=await ze(`/api/remote/devices/${encodeURIComponent(ba)}/clipboard`,{method:"POST",timeoutMs:d,body:JSON.stringify({action:n,hubConnectionId:no,operationId:o,binding:{sessionId:ao,commandId:oo,captureGeneration:io,monitorIndex:ii},payload:l})},K);if(hu.current!==m)throw new Error("Remote Control changed before the clipboard transfer completed.");if(C?.ok===!1)throw new Error(C.error||"Remote clipboard transfer failed.");return C},[io,oo,ba,ii,ao,no,K]),vp=s.useCallback(async(n,o)=>{const l=window.liveDesk?.clipboard;let m=!1,d=!1;try{await wn("clipboard.prepare",n,{clipboardDirection:"copy"},o),await wn("clipboard.copy",n,{clipboardDirection:"copy"},o),d=!0;const C=await wn("clipboard.copy.begin",n,{},o),v=Nd(C.manifest,n);if(l?.beginWrite&&l.writeChunk&&l.commitWrite){await l.beginWrite(v),m=!0;for(const S of v.items)for(const y of nd(S.size)){const w=await wn("clipboard.copy.chunk",n,{itemIndex:S.itemIndex,offset:y.offset,maxBytes:vl},o),J=gh(String(w.dataBase64||""));if(Number(w.itemIndex)!==S.itemIndex||Number(w.offset)!==y.offset||Number(w.bytes)!==y.byteLength||J.byteLength!==y.byteLength||w.final===!0!==y.final)throw new Error("Remote clipboard chunk did not match the requested file range.");await l.writeChunk({operationId:n,itemIndex:S.itemIndex,offset:y.offset,dataBase64:String(w.dataBase64||""),final:y.final})}await l.commitWrite(n),m=!1}else{if(v.contentKind==="files")throw new Error("Multiple files require the VuvoDesk desktop app.");const S=[];for(const y of v.items){const w=new Uint8Array(y.size);for(const J of nd(y.size)){const ge=await wn("clipboard.copy.chunk",n,{itemIndex:y.itemIndex,offset:J.offset,maxBytes:vl},o),D=gh(String(ge.dataBase64||""));if(D.byteLength!==J.byteLength)throw new Error("Remote clipboard chunk was incomplete.");w.set(D,J.offset)}if(await ub(w)!==y.sha256)throw new Error("Remote clipboard content check failed.");S.push(w)}await kk({manifest:v,payloads:S})}await wn("clipboard.copy.end",n,{},o),d=!1,B(v.contentKind==="files"?`${v.items.length} remote file${v.items.length===1?"":"s"} copied.`:v.contentKind==="image"?"Remote image copied.":"Remote text copied.","success")}catch(C){throw m&&await l?.cancelWrite?.(n).catch(()=>{}),d&&await wn("clipboard.copy.end",n,{},o).catch(()=>{}),C}},[wn,B]),yp=s.useCallback(async(n,o)=>{const l=window.liveDesk?.clipboard;let m=null,d,C=!1;try{l?.readSnapshot&&l.readChunk?d=Nd(await l.readSnapshot(n),n):(m=await Ck(n),d=m.manifest),await wn("clipboard.prepare",n,{clipboardDirection:"paste",manifest:d},o),C=!0,await wn("clipboard.paste.begin",n,{manifest:d},o);for(const y of d.items)for(const w of nd(y.size)){const J=l?.readChunk?await l.readChunk({operationId:n,itemIndex:y.itemIndex,offset:w.offset,maxBytes:w.byteLength||vl}):{operationId:n,itemIndex:y.itemIndex,offset:w.offset,byteLength:w.byteLength,dataBase64:Sk(m.payloads[y.itemIndex].subarray(w.offset,w.offset+w.byteLength)),final:w.final};if(J.offset!==w.offset||J.byteLength!==w.byteLength||J.final!==w.final)throw new Error("Local clipboard changed during transfer.");const ge=await wn("clipboard.paste.chunk",n,{itemIndex:y.itemIndex,offset:w.offset,dataBase64:J.dataBase64,final:w.final},o);if(Number(ge.itemIndex)!==y.itemIndex||Number(ge.offset)!==w.offset||Number(ge.bytes)!==w.byteLength||ge.final===!0!==w.final)throw new Error("Remote clipboard did not confirm the requested file range.")}await wn("clipboard.paste",n,{clipboardDirection:"paste"},o);const v=Date.now()+vk;let S=!1;for(;Date.now()<v;){const y=await wn("clipboard.operation.status",n,{},o,Math.max(250,v-Date.now())),w=String(y.status||"").toLowerCase();if(["completed","complete","applied","pasted"].includes(w)){S=!0;break}if(["failed","cancelled","expired"].includes(w))throw new Error(`Remote clipboard paste ${w}.`);await new Promise(J=>window.setTimeout(J,bk))}if(!S)throw new Error("Remote clipboard paste confirmation timed out.");C=!1,B(d.contentKind==="files"?`${d.items.length} file${d.items.length===1?"":"s"} pasted on the remote computer.`:d.contentKind==="image"?"Image pasted on the remote computer.":"Text pasted on the remote computer.","success")}catch(v){throw C&&await wn("clipboard.paste.cancel",n,{},o).catch(()=>{}),v}finally{await l?.releaseRead?.(n).catch(()=>{})}},[wn,B]),wp=s.useCallback(async n=>{if(!ts||!Wc||ns!=="open"||!no){B("Remote input is not ready for clipboard transfer.","error");return}if(Vc.current){B("Another clipboard transfer is still running.");return}const o=bC(n),l=$c;Vc.current={operationId:o,direction:n,bindingKey:l};try{Bn(n==="copy"?"Copying from the remote computer…":"Pasting on the remote computer…"),n==="copy"?await vp(o,l):await yp(o,l)}catch(m){B(m instanceof Error?m.message:String(m),"error")}finally{Vc.current?.operationId===o&&(Vc.current=null)}},[$c,ts,vp,no,Wc,ns,yp,B,Bn]),Ir=qt&&qn.current&&ts&&ns==="open"&&Wc&&!!no,gu={shiftKey:Ri.includes("ShiftLeft"),ctrlKey:Ri.includes("ControlLeft"),altKey:Ri.includes("AltLeft"),metaKey:Ri.includes("MetaLeft")},cr=s.useCallback(n=>_s.current.enqueueStop(n),[]),so=s.useCallback(n=>_s.current.enqueueStart(n),[]),un=s.useCallback((n,o=Os.current)=>(Ls.current=n,Os.current=n?String(o||""):"",am.current=Ll.current,Ro.current+=1,Ro.current),[]),lr=s.useCallback((n,o,l)=>am.current===Ll.current&&l0({generation:n,currentGeneration:Ro.current,enabled:Ls.current,deviceId:o,currentDeviceId:Os.current,documentVisible:qn.current,presentationVisible:Ol.current,streamId:l,currentStreamId:dt.current.get(o)||""}),[]),Jn=s.useCallback(async(n,o,l)=>{if(!o)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const d=await(v=>ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/stop`,{method:"POST",body:JSON.stringify({...v?{streamId:v}:{},reason:l})},K))(o),C=u0(d);if(C.staleOwner)return d;if(!C.confirmed)throw new Error(d?.error||"Remote audio capture stop was not confirmed.");return d},[K]),bu=s.useCallback(async(n,o)=>{const l=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:o})},K);if(l?.ok===!1||l?.captureStopConfirmed!==!0&&l?.alreadyStopped!==!0)throw new Error(l?.error||"Remote audio stop-all was not confirmed.");return l},[K]),cv=s.useCallback(n=>{const o=Ro.current,l=dt.current.get(n)||"";return cr(()=>Jn(n,l,"remote-audio-automatic-restart")).then(()=>so(async()=>{if(o!==Ro.current||!Ls.current||Os.current!==n||!qn.current||!Ol.current||!pt||!sr||(Na.current||X?.deviceId||"")!==n)return"";const m=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(dt.current.set(n,m),!lr(o,n,m))return dt.current.delete(n),"";const d=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},K);if(d?.ok===!1)throw dt.current.get(n)===m&&dt.current.delete(n),new Error(d.error||"Remote audio restart failed.");return lr(o,n,m)?m:(await Jn(n,m,"remote-audio-stale-restart-compensation"),dt.current.get(n)===m&&dt.current.delete(n),"")}))},[so,cr,pt,K,lr,sr,X?.deviceId,Jn]),Sp=X?.deviceId&&dt.current.get(X.deviceId)||"",lv=s.useCallback(async(n,o,l)=>{un(!1),Fr(!1),await cr(()=>Jn(n,o,l)),dt.current.get(n)===o&&dt.current.delete(n)},[cr,un,Jn]),{state:vu,lastFrame:yu,stats:Rt,error:wu}=uC(X?.deviceId||"",qt&&Ym&&Zt,K,Lb,fn||Ut||ec.current,Sp,cv,lv,O),co=s.useRef(new Map);s.useEffect(()=>{const n=[["hub",je],["registry",me],["license",He],["wall-stream",Fc],["control-stream",eo],["control-decode",Pt],["remote-input",bp],["remote-audio",wu]];for(const[o,l]of n){const m=String(l||"").trim(),d=ke.current;if(o==="wall-stream"&&m==="CONTROL_CAPTURE_OWNS_DEVICE"&&!!d&&la.current===d.deviceId){co.current.delete(o);continue}if(o==="hub"&&Ze?.requiresHubRestart&&Ze.stage==="updating"){co.current.delete(o);continue}if(o==="hub"&&W&&(kt?.kind==="signal-service-unavailable"||kt?.kind==="p2p-unavailable")){co.current.delete(o);continue}if(!m){const S=co.current.get(o);co.current.delete(o),o==="remote-input"&&S&&dm(S.noticeId,S.message);continue}if(co.current.get(o)?.message===m)continue;const v=B(m);co.current.set(o,{message:m,noticeId:v})}},[wu,dm,Pt,eo,je,kt?.kind,bp,He,W,me,B,Fc,Ze]);const zc=X?.deviceId||"",Cp=X?_n(X,gt[zc]):0;s.useEffect(()=>{if(sa||!kn||!Cr||!Ir||!zc)return;const n=DC(),o=zc,l=Cp,m=D=>{if(!D)return!1;const fe=rs(o,{...D,monitorIndex:l});return!fe&&D.type!=="keyboard.reset"&&(n.reset("browser-input-send-rejected"),Fs([])),fe},d=(D,fe)=>{if(Ks.current)return;const Ne=D.target,We=Ne?.tagName?.toLowerCase(),Xe=Ne?.isContentEditable||We==="input"||We==="textarea"||We==="select",Ue=n.isPressed(D);if(Xe&&(fe==="keydown"||!Ue))return;const Yt=fe==="keydown"?gC(D,wk()):"";if(Yt&&(Yt==="copy"?fp:Yt==="paste"?hp:!1)){D.preventDefault(),D.stopPropagation();const ls=n.reset("remote-clipboard-shortcut",!0);ls&&m(ls),Fs([]),wp(Yt);return}const fo=n.event(D,fe);fo&&(D.preventDefault(),D.stopPropagation(),m(fo))},C=D=>d(D,"keydown"),v=D=>d(D,"keyup"),S=(D,fe=!1)=>{const Ne=n.reset(D,fe);Ne&&(m(Ne),Fs([]))};Dl.current=D=>{const fe=n.snapshot().latchedCodes.includes(D),Ne=n.modifier(D,!fe);Ne&&(m(Ne),Fs(We=>fe?We.filter(Xe=>Xe!==D):[...We.filter(Xe=>Xe!==D),D]))};const y=D=>{const fe=ol(D);if(!fe)return!1;const Ne=n.snapshot(),We={...fe,shiftKey:Ne.shiftKey,ctrlKey:Ne.ctrlKey,altKey:Ne.altKey,metaKey:Ne.metaKey},Xe=n.event(We,"keydown");if(!Xe||!m(Xe))return!1;const Ue=n.event(We,"keyup");return!!Ue&&m(Ue)};Ai.current={sendKey:y,sendText:D=>{let fe=!1;const Ne=String(D??"").split(/(\r\n|\r|\n)/);for(const We of Ne)if(We){if(We==="\r"||We===`
|
|
179
|
+
${h}`,[k,M]=Xt(f,ld),[b,T]=Xt(f,ud),[A,x]=Xt(f,!1),[E,B]=Xt(f,""),q=s.useRef(0),G=`${u}
|
|
180
|
+
${p}`,ne=s.useRef(G);ne.current=G;const re=s.useCallback((pe,ce)=>{if(ne.current!==pe||!c(ce))throw new Error("The active VuvoDesk workspace changed. Please try again in the current workspace.")},[c]),O=s.useCallback(async()=>{const pe=q.current+1;q.current=pe;const ce=()=>q.current===pe;if(!u||!p){M(f,ld),T(f,ud),x(f,!1),B(f,"");return}x(f,!0);try{const W=t?.role==="owner"?Ct.rpc("list_livedesk_workspace_members",{p_workspace_id:p}):Promise.resolve({data:[],error:null}),ee=t?.role==="owner"?Ct.rpc("list_livedesk_workspace_invites",{p_workspace_id:p}):Promise.resolve({data:[],error:null}),[L,_]=await Promise.all([W,ee]);if(!ce())return;if(L.error)throw L.error;if(_.error)throw _.error;M(f,(Array.isArray(L.data)?L.data:[]).map(K=>({id:String(K.user_id||""),email:String(K.email||""),displayName:String(K.display_name||""),role:String(K.role||"")==="owner"?"owner":"operator",joinedAt:String(K.joined_at||"")})).filter(K=>Ps.test(K.id))),T(f,(Array.isArray(_.data)?_.data:[]).map(K=>({id:String(K.invite_id||""),email:String(K.email||""),role:"operator",createdAt:String(K.created_at||""),expiresAt:String(K.expires_at||"")})).filter(K=>Ps.test(K.id))),B(f,""),x(f,!1)}catch(W){if(!ce())return;B(f,W instanceof Error?W.message:String(W)),x(f,!1)}},[t?.role,f,B,T,x,M,u,p]);s.useEffect(()=>(q.current+=1,M(f,ld),T(f,ud),B(f,""),O(),()=>{q.current+=1}),[f,B,T,M,O,h]);const ie=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can create invitations.");const ce=G,W=String(pe||"").trim().toLowerCase();if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(W))throw new Error("Enter the Google account email to invite.");const{data:ee,error:L}=await Ct.rpc("invite_livedesk_workspace_member",{p_workspace_id:p,p_email:W,p_role:"operator"});if(re(ce,p),L)throw L;const _=Co(ee),K=String(_?.invite_token||"").trim().toLowerCase();if(!_?.ok||!Zd.test(K))throw wi(_,"team invite creation failed");const ue=new URL("/app",window.location.origin);return ue.searchParams.set(Il,K),re(ce,p),await Promise.all([O(),r()]),{url:ue.toString(),expiresAt:_.expires_at}},[t?.role,re,O,r,p,G]),J=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can remove members.");const ce=G,{data:W,error:ee}=await Ct.rpc("remove_livedesk_workspace_member",{p_workspace_id:p,p_user_id:pe});if(re(ce,p),ee)throw ee;const L=Co(W);if(!L?.ok)throw wi(L,"team member removal failed");let _=!0;try{await ze(`/api/remote/workspace/members/${encodeURIComponent(pe)}/revoke`,{method:"POST",body:JSON.stringify({workspaceId:p})},a)}catch{_=!1}return re(ce,p),await Promise.all([O(),r()]),{revokedImmediately:_}},[t?.role,re,a,O,r,p,G]),de=s.useCallback(async pe=>{if(!p||t?.role!=="owner")throw new Error("Only the Team owner can revoke invitations.");const ce=G,{data:W,error:ee}=await Ct.rpc("revoke_livedesk_workspace_invite",{p_workspace_id:p,p_invite_id:pe});if(re(ce,p),ee)throw ee;const L=Co(W);if(!L?.ok)throw wi(L,"team invite revocation failed");await Promise.all([O(),r()])},[t?.role,re,O,r,p,G]),se=s.useCallback(async()=>{if(!p||t?.role!=="operator")throw new Error("Only an Operator can leave this Team Space.");const pe=G,{data:ce,error:W}=await Ct.rpc("leave_livedesk_workspace",{p_workspace_id:p});if(re(pe,p),W)throw W;const ee=Co(ce);if(!ee?.ok)throw wi(ee,"leaving team workspace failed")},[t?.role,re,p,G]);return s.useMemo(()=>({members:k,invites:b,loading:A,error:E,refresh:O,createInvite:ie,removeMember:J,revokeInvite:de,leaveWorkspace:se}),[ie,E,b,se,A,k,O,J,de])}function Xg({state:e}){return e==="ok"?i.jsx(Cn,{size:15,"aria-hidden":"true"}):i.jsx(gy,{size:15,"aria-hidden":"true"})}function uh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button ${e?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(fy,{size:18,"aria-hidden":"true"})})}function dh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button debug-status-button ${e?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(hy,{size:18,"aria-hidden":"true"})})}function mh({active:e,refreshing:t,onClick:a}){return i.jsx("button",{className:`remote-status-button hub-status-button ${e?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":e,"aria-busy":t,onClick:a,children:t?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Si,{size:18,"aria-hidden":"true"})})}function Jg({items:e,mode:t="remote"}){return i.jsx("span",{className:`remote-status-lines mode-${t}`,role:"status","aria-label":t==="debug"?"Debug status":"Remote status",onPointerDown:t==="debug"?a=>a.stopPropagation():void 0,onClick:t==="debug"?a=>a.stopPropagation():void 0,onDoubleClick:t==="debug"?a=>a.stopPropagation():void 0,children:e.map(a=>i.jsxs("span",{className:`remote-status-line state-${a.state}`,title:a.detail,children:[i.jsx(Xg,{state:a.state}),i.jsxs("span",{children:[i.jsx("strong",{children:a.label}),i.jsx("small",{children:a.detail})]})]},a.id))})}function z0({items:e,collectedAt:t,onClose:a}){return i.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[i.jsxs("header",{children:[i.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:i.jsx(Si,{size:19})}),i.jsxs("span",{children:[i.jsx("small",{children:"Hub measurements"}),i.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),i.jsx("button",{type:"button",onClick:a,title:"Close Hub status","aria-label":"Close Hub status",children:i.jsx(Ma,{size:17})})]}),i.jsx("p",{children:"VuvoDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),i.jsx("div",{className:"remote-status-dialog-list",children:e.map(r=>i.jsxs("article",{className:`remote-status-dialog-row state-${r.state}`,children:[i.jsx(Xg,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))}),i.jsxs("footer",{children:["Checked ",new Date(t).toLocaleTimeString()]})]})}async function U0(e,t={}){const a=e.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),r=Math.max(320,t.maxWidth||1920),c=Math.max(180,t.maxHeight||1080),u=a.length<=1?1:a.length<=4?2:a.length<=9?3:4,p=Math.max(1,Math.ceil(Math.max(1,a.length)/u)),h=Math.floor(r/u),f=Math.floor(c/p),k=document.createElement("canvas");k.width=Math.max(320,h*u),k.height=Math.max(180,f*p);const M=k.getContext("2d",{alpha:!1});if(!M)return k;M.fillStyle="#0b1220",M.fillRect(0,0,k.width,k.height),M.font="600 14px system-ui, sans-serif",M.textBaseline="bottom";for(let b=0;b<a.length;b+=1){const T=a[b],A=b%u,x=Math.floor(b/u),E=A*h,B=x*f,q=T.canvas,G=Math.min(h/q.width,f/q.height),ne=Math.max(1,Math.floor(q.width*G)),re=Math.max(1,Math.floor(q.height*G)),O=E+Math.floor((h-ne)/2),ie=B+Math.floor((f-re)/2);M.drawImage(q,O,ie,ne,re),t.includeLabels!==!1&&(M.fillStyle="rgba(4, 10, 20, .74)",M.fillRect(E,B+f-28,h,28),M.fillStyle="#f8fafc",M.fillText(T.label,E+9,B+f-9))}return k}function q0(e){return e?.signature||"none"}function G0(e){return e?.label||"No capture target"}function ph(e){return{...e,deviceIds:[...e.deviceIds],sourceCanvas:e.sourceCanvas||null}}function Zg(e){return{type:e.type,deviceIds:e.deviceIds,monitorIndex:e.monitorIndex,label:e.label}}async function eb(e){try{return(await e.json()).error||`${e.status} ${e.statusText}`}catch{return`${e.status} ${e.statusText}`}}async function tb(e,t,a){const r=encodeURIComponent(JSON.stringify({kind:t.kind,fileName:t.fileName,mimeType:e.type||"application/octet-stream",durationMs:t.durationMs,target:Zg(t.target)})),c=await Yh(`/api/captures?metadata=${r}`,{method:"POST",headers:{"Content-Type":e.type||"application/octet-stream"},body:e},a);if(!c.ok)throw new Error(await eb(c));return await c.json()}async function K0(e,t){return await ze("/api/capture-sessions",{method:"POST",body:JSON.stringify({...e,target:Zg(e.target)})},t)}async function Y0(e,t,a,r){const c=await Yh(`/api/capture-sessions/${encodeURIComponent(e)}/chunks/${t}`,{method:"PUT",headers:{"Content-Type":a.type||"application/octet-stream"},body:a},r);if(!c.ok)throw new Error(await eb(c));return await c.json()}async function Q0(e,t,a){return await ze(`/api/capture-sessions/${encodeURIComponent(e)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:t})},a)}async function fh(e,t){await ze(`/api/capture-sessions/${encodeURIComponent(e)}`,{method:"DELETE"},t)}async function lx(e){return await ze("/api/captures",void 0,e)}function ux(e,t){return`${Kh(t)}/api/captures/${encodeURIComponent(e)}/content`}async function dx(e,t){return await ze(`/api/captures/${encodeURIComponent(e)}`,{method:"DELETE"},t)}function X0(){const e=new Date,t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}${t(e.getMonth()+1)}${t(e.getDate())}_${t(e.getHours())}${t(e.getMinutes())}${t(e.getSeconds())}`}function J0(e){return e.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function Z0(e){return`VuvoDesk_${e.type==="wall"||e.type==="selection"?"Wall":`${J0(e.label)}_Monitor-${Number(e.monitorIndex||0)+1}`}_${X0()}.png`}async function ek(e,t,a){const r=await new Promise((u,p)=>e.toBlob(h=>h?u(h):p(new Error("Screenshot could not be encoded.")),"image/png")),c=await tb(r,{kind:"screenshot",fileName:Z0(t),target:t},a);try{await navigator.clipboard.write([new ClipboardItem({"image/png":r})])}catch{}return c.capture}function nb(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(t=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(t))||""}function tk(e,t){const a=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),r=t.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return e==="timelapse"?`VuvoDesk_Timelapse_${r}_${a}.webm`:`VuvoDesk_Recording_${r}_${a}.webm`}async function rb(e){if(typeof MediaRecorder>"u"||typeof e.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const t=nb();if(!t)throw new Error("This browser does not support WebM recording.");const a=e.kind||"recording",r=await K0({kind:a,fileName:tk(a,e.target),mimeType:t,target:e.target},e.hubUrl),c=e.canvas.captureStream(e.frameRequests?0:e.fps),u=new MediaRecorder(c,{mimeType:t,videoBitsPerSecond:a==="timelapse"?2e6:4e6}),p=performance.now();let h=0,f=!1,k=null,M=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const T=h++;M=M.then(()=>Y0(r.sessionId,T,b.data,e.hubUrl).then(()=>{})).catch(A=>{k=k||(A instanceof Error?A:new Error(String(A))),e.onError?.(k)})},u.onerror=()=>{k=new Error("Video recording stopped unexpectedly."),e.onError?.(k)},u.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!f){if(f=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),c.getTracks().forEach(b=>b.stop()),await M,k)throw await fh(r.sessionId,e.hubUrl).catch(()=>{}),k;await Q0(r.sessionId,Math.max(0,performance.now()-p),e.hubUrl)}},cancel:async()=>{f||(f=!0,u.stop(),c.getTracks().forEach(b=>b.stop()),await fh(r.sessionId,e.hubUrl).catch(()=>{}))}}}class nk{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(t,a){if(this.recorder&&this.targetSignature===a.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof t.captureStream!="function")throw new Error("This browser does not support Last 30s.");const r=nb();if(!r)throw new Error("This browser does not support WebM recording.");this.targetSignature=a.signature,this.stream=t.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:r,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const u=performance.now();for(this.segments.push({blob:c.data,at:u}),this.totalBytes+=c.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const p=this.segments.shift();this.totalBytes-=p.blob.size}},this.recorder.start(1e3)}stop(){const t=this.recorder;this.recorder=null,t&&t.state!=="inactive"&&(t.ondataavailable=null,t.stop()),this.stream?.getTracks().forEach(a=>a.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(t,a){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const r=new Blob(this.segments.map(p=>p.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`VuvoDesk_Last30s_${t.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 tb(r,{kind:"last-30s",fileName:u,target:t,durationMs:Math.min(3e4,this.segments.length*1e3)},a)}}async function rk(e,t,a,r,c){const u=await rb({canvas:e,target:t,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:r,onError:c});u.requestFrame?.();const p=window.setInterval(()=>u.requestFrame?.(),Math.max(5,a)*1e3);return{stop:async()=>{window.clearInterval(p),await u.stop()},cancel:async()=>{window.clearInterval(p),await u.cancel()}}}const ab="livedesk.captureSettings";function ak(){const e={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const t=JSON.parse(localStorage.getItem(ab)||"null");return{...e,...t&&typeof t=="object"?t:{}}}catch{return e}}function ok(e){const[t,a]=s.useState(ak),[r,c]=s.useState(0),[u,p]=s.useState(0),[h,f]=s.useState(0),[k,M]=s.useState(!1),b=s.useRef(void 0),T=s.useRef(!1),A=s.useRef(""),x=s.useRef(null),E=s.useRef(null),B=s.useRef(null),q=s.useRef(null),G=s.useRef(new nk),ne=e.sourceRegistry.resolveCurrentTarget(),re=q0(ne),O=G0(ne),ie=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;s.useEffect(()=>{if(localStorage.setItem(ab,JSON.stringify(t)),!e.remoteSettingsEnabled||!e.hubUrl||!T.current)return;const P=JSON.stringify(t);P!==A.current&&(A.current=P,ze("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:t.rollingEnabled,recordingQuality:t.recordingQuality,timelapseIntervalSeconds:t.timelapseIntervalSeconds,includeRemoteCursor:t.includeRemoteCursor}})},e.hubUrl).then(N=>{b.current=Number(N.revision||b.current||0)}).catch(()=>{}))},[e.hubUrl,e.remoteSettingsEnabled,t]),s.useEffect(()=>{if(!e.remoteSettingsEnabled||!e.hubUrl){T.current=!1;return}let P=!0;return ze("/api/settings",void 0,e.hubUrl).then(N=>{if(!P)return;const te=N.settings?.filesAudio||{},we=typeof te.rollingBufferEnabled=="boolean"?te.rollingBufferEnabled:t.rollingEnabled,me=te.recordingQuality==="high"?"high":"standard",Fe=[5,10,30,60].includes(Number(te.timelapseIntervalSeconds))?Number(te.timelapseIntervalSeconds):t.timelapseIntervalSeconds,H=typeof te.includeRemoteCursor=="boolean"?te.includeRemoteCursor:t.includeRemoteCursor,R={rollingEnabled:we,recordingQuality:me,timelapseIntervalSeconds:Fe,includeRemoteCursor:H};b.current=Number(N.revision||0),A.current=JSON.stringify(R),T.current=!0,a(R)}).catch(()=>{T.current=!0}),()=>{P=!1}},[e.hubUrl,e.remoteSettingsEnabled]);const J=s.useCallback(async P=>{if(P.sourceCanvas&&P.sourceCanvas.width>0&&P.sourceCanvas.height>0)return{target:ph(P),canvas:P.sourceCanvas,cleanup:()=>{}};const N=await e.sourceRegistry.composeWall(P.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let te=!1;const we=window.setInterval(async()=>{if(te)return;const me=await e.sourceRegistry.composeWall(P.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!me||te||((N.width!==me.width||N.height!==me.height)&&(N.width=me.width,N.height=me.height),N.getContext("2d")?.drawImage(me,0,0))},100);return{target:ph(P),canvas:N,cleanup:()=>{te=!0,window.clearInterval(we)}}},[e.sourceRegistry]);s.useEffect(()=>{const P=G.current;if(!t.rollingEnabled||!ne||!ie){P.stop(),f(0);return}let N=!1,te=null;return(async()=>{try{if(te=await J(ne),N)return;await P.start(te.canvas,te.target);const me=window.setInterval(()=>f(Math.round(P.seconds)),500),Fe=()=>{window.clearInterval(me),te?.cleanup()};P.__cleanup=Fe}catch(me){N||e.onToast(me instanceof Error?me.message:String(me))}})(),()=>{N=!0,P.stop(),P.__cleanup?.(),P.__cleanup=void 0,f(0)}},[J,e.onToast,t.rollingEnabled,re,ie]);const de=s.useCallback(P=>a(N=>({...N,rollingEnabled:P})),[]),se=s.useCallback(P=>a(N=>({...N,recordingQuality:P})),[]),pe=s.useCallback(P=>a(N=>({...N,timelapseIntervalSeconds:P})),[]),ce=s.useCallback(async()=>{const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");M(!0);let N=null;try{N=await J(P),await ek(N.canvas,N.target,e.hubUrl),e.onToast("Screenshot saved")}finally{N?.cleanup(),M(!1)}},[J,e.hubUrl,e.onToast,e.sourceRegistry]),W=s.useCallback(async()=>{if(B.current)throw new Error("Stop the timelapse before recording.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");const N=await J(P),te=await rb({canvas:N.canvas,target:N.target,fps:P.type==="control"?30:15,hubUrl:e.hubUrl,onError:we=>e.onToast(we.message)});E.current=N.cleanup,x.current=te,c(Date.now()),e.onToast("Recording started")},[J,e.hubUrl,e.onToast,e.sourceRegistry]),ee=s.useCallback(async()=>{const P=x.current;if(P){M(!0);try{await P.stop(),e.onToast("Recording saved")}finally{x.current=null,E.current?.(),E.current=null,c(0),M(!1)}}},[e.onToast]),L=s.useCallback(async()=>{if(x.current||B.current)throw new Error("Last 30s is unavailable during a recording.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");M(!0);try{await G.current.save(P,e.hubUrl),e.onToast("Last 30 seconds saved")}finally{M(!1)}},[e.hubUrl,e.onToast,e.sourceRegistry]),_=s.useCallback(async()=>{if(x.current)throw new Error("Stop the recording before starting a timelapse.");const P=e.sourceRegistry.resolveCurrentTarget();if(!P)throw new Error("화면이 준비된 후 다시 시도하세요.");const N=await J(P),te=await rk(N.canvas,N.target,t.timelapseIntervalSeconds,e.hubUrl,we=>e.onToast(we.message));q.current=N.cleanup,B.current=te,p(Date.now()),e.onToast("Timelapse started")},[J,e.hubUrl,e.onToast,e.sourceRegistry,t.timelapseIntervalSeconds]),K=s.useCallback(async()=>{const P=B.current;if(P){M(!0);try{await P.stop(),e.onToast("Timelapse saved")}finally{B.current=null,q.current?.(),q.current=null,p(0),M(!1)}}},[e.onToast]);return s.useEffect(()=>{const P=N=>{!x.current&&!B.current||(N.preventDefault(),N.returnValue="")};return window.addEventListener("beforeunload",P),()=>window.removeEventListener("beforeunload",P)},[]),s.useEffect(()=>()=>{G.current.stop(),x.current?.cancel(),B.current?.cancel(),E.current?.(),q.current?.()},[]),{state:s.useMemo(()=>({recording:!!x.current,recordingStartedAt:r,timelapse:!!B.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:t.rollingEnabled,busy:k,targetLabel:O}),[h,k,r,t.rollingEnabled,O,u]),settings:t,videoSupported:ie,targetKey:re,setRollingEnabled:de,setRecordingQuality:se,setTimelapseInterval:pe,takeScreenshot:ce,startRecording:W,stopRecording:ee,saveLast30Seconds:L,startTimelapse:_,stopTimelapse:K}}function ik(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const e=window.navigator.userAgent,t=window.navigator.standalone,a=XC(e,window.navigator.platform,window.navigator.maxTouchPoints,t),r=/Android/i.test(e),c=a&&/CriOS/i.test(e),u=a&&/Safari/i.test(e)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(e);return{isIos:a,isAndroid:r,isSafari:u,browserName:c?"Chrome":u?"Safari":"browser"}}const hh=s.lazy(()=>mr(()=>import("./AgentsPage-DUMU7WPH.js"),__vite__mapDeps([0,1,2,3,4,5])).then(e=>({default:e.AgentsPage}))),sk=s.lazy(()=>mr(()=>import("./ShareFilesPage-Bp5Dh9tQ.js"),__vite__mapDeps([6,1,2,3,4,7])).then(e=>({default:e.ShareFilesPage}))),An="".trim().toLowerCase()==="true",Sa="".trim().toLowerCase()==="true",Jr="".trim().toLowerCase()==="true",ck=s.lazy(()=>mr(()=>import("./SupportPage-BwS_toBH.js"),__vite__mapDeps([8,1,2,3,4,9,10,11])).then(e=>({default:e.SupportPage}))),lk=s.lazy(()=>mr(()=>import("./SettingsPage-JYlSHnWI.js"),__vite__mapDeps([12,1,2,3,4])).then(e=>({default:e.SettingsPage}))),uk=s.lazy(()=>mr(()=>import("./SettingsTabs-D75pwHMD.js"),__vite__mapDeps([13,1,2,3,4])).then(e=>({default:e.PinSettingsTab}))),dk=s.lazy(()=>mr(()=>import("./AgentSettingsTab-BBNQK3m_.js"),__vite__mapDeps([14,1,2,3,4])).then(e=>({default:e.AgentSettingsTab}))),mk=s.lazy(()=>mr(()=>import("./DesktopUpdatePanel-BPD9IaXS.js"),__vite__mapDeps([15,1,2,3,4])).then(e=>({default:e.DesktopUpdatePanel}))),pk=s.lazy(()=>mr(()=>import("./CaptureGallery-Dgucz-9s.js"),__vite__mapDeps([16,1,2,3,4,9,10])).then(e=>({default:e.CaptureGallery})));function hs({children:e}){return i.jsx(s.Suspense,{fallback:i.jsx("div",{className:"deferred-feature-loading",role:"status",children:"Loading…"}),children:e})}const fk=120,hk=999,ob="livedesk.remoteDirectory",Hd="livedesk.localHubAccessEnabled",gk="livedesk.streamSettings",bk=18,vk="livedesk.controlStreamSettings",yk=10,ib="livedesk.wallCadence",sb="livedesk.wallViewScale",cb="livedesk.mobileWallStatsVisible",wk=1e3,lb="livedesk.wallMonitorSelections",ub=2,dd=512*1024,Sk=250,Ck=15e3,kk=!1;function Mk(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(`${navigator.platform} ${navigator.userAgent}`)}function xk(e){let t="";for(let a=0;a<e.length;a+=32*1024)t+=String.fromCharCode(...e.subarray(a,Math.min(e.length,a+32*1024)));return window.btoa(t)}function gh(e){const t=window.atob(String(e||"")),a=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)a[r]=t.charCodeAt(r);return a}async function db(e){const t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),a=>a.toString(16).padStart(2,"0")).join("")}async function Rk(e){const t=navigator.clipboard;let a="text",r="clipboard.txt",c="text/plain",u=null;if(typeof t?.read=="function"){const h=await t.read(),f=h.find(k=>k.types.includes("image/png"));if(f){const k=await f.getType("image/png");a="image",r="clipboard.png",c="image/png",u=new Uint8Array(await k.arrayBuffer())}else{const k=h.find(M=>M.types.includes("text/plain"));if(k){const M=await k.getType("text/plain");u=new TextEncoder().encode(await M.text())}}}if(!u&&typeof t?.readText=="function"&&(u=new TextEncoder().encode(await t.readText())),!u)throw new Error("The browser did not provide text or a PNG image from the clipboard.");return{manifest:Fd({operationId:e,contentKind:a,totalBytes:u.byteLength,items:[{itemIndex:0,kind:a,name:r,mimeType:c,size:u.byteLength,lastModified:Date.now(),sha256:await db(u),storageName:"item-0.bin"}]},e),payloads:[u]}}async function Ak(e){const{manifest:t,payloads:a}=e,r=a[0];if(!r||t.items.length!==1)throw new Error("clipboard-browser-snapshot-invalid");if(t.contentKind==="text"){await navigator.clipboard.writeText(new TextDecoder().decode(r));return}if(t.contentKind==="image"&&typeof ClipboardItem<"u"){await navigator.clipboard.write([new ClipboardItem({"image/png":new Blob([r],{type:"image/png"})})]);return}throw new Error("Multiple files require the VuvoDesk desktop app.")}"".trim();"".trim();const Ik=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),Tk=1e3/60,md=1500,Pk=650,Ek=1800,Nk=650,Fk=2500,pd=1500,bh=15e3,vh=120,Dk=.72,mb=6,Lk=640*360,Ok=8;function _k(e){let t=2166136261;for(let a=0;a<e.length;a+=1)t=Math.imul(t^e.charCodeAt(a),16777619);return(t>>>0)%mb}const yh=100,wh=20,jk=6e4,Bk=6e4,Sh=240,Hk=1024,Wk=640,$k=360,Ch="Connected VuvoDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",ul="VuvoDesk is replacing the Hub and verifying the requested version.",dl=5*6e4,Vk=5e3,kh=2e3,zk=8e3;function Mh(e,t){return`${e}:${t.deviceId}:${t.completedAt||t.candidateSessionId||t.commandId||"completed"}`}function bo({label:e,tooltip:t,disabled:a=!1,active:r=!1,danger:c=!1,pressed:u,onClick:p,children:h}){return i.jsx("span",{className:`manual-action-tooltip ${a?"disabled":""}`.trim(),"data-tooltip":t,children:i.jsx("button",{className:`manual-action ${r?"active":""} ${c?"danger":""}`.trim(),onClick:p,disabled:a,"aria-label":e,"aria-pressed":u,type:"button",children:h})})}function Uk(e,t){if(t.deviceId!==e.deviceId)return!1;const a=Number(t.browserReceivedEpochMs);if(!Number.isFinite(a)||a<e.startedAtEpochMs)return!1;const r=Number(t.monitorIndex);if(Number.isFinite(r)&&Math.floor(r)!==e.monitorIndex)return!1;const c=String(t.frameMode||t.mode||"").trim().toLowerCase();return!c||c===e.frameMode}const qk={"mode3-h264-hw":30};function xh(e,t){const a=p=>{const f=String(p||"").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(!f)return null;const k=f[4]?f[4].split(".").map(M=>/^\d+$/.test(M)?M.length>1&&M.startsWith("0")?Number.NaN:Number(M):M):[];return k.some(M=>typeof M=="number"&&!Number.isFinite(M))?null:{core:[Number(f[1]),Number(f[2]),Number(f[3])],prerelease:k}},r=a(e),c=a(t);if(!r||!c)return!1;for(let p=0;p<3;p+=1){if(r.core[p]>c.core[p])return!0;if(r.core[p]<c.core[p])return!1}if(r.prerelease.length===0||c.prerelease.length===0)return r.prerelease.length===0;const u=Math.max(r.prerelease.length,c.prerelease.length);for(let p=0;p<u;p+=1){const h=r.prerelease[p],f=c.prerelease[p];if(h===void 0||f===void 0)return f===void 0;if(h!==f){if(typeof h=="number"&&typeof f=="number")return h>f;if(typeof h=="number")return!1;if(typeof f=="number"||h>f)return!0;if(h<f)return!1}}return!0}const Gk=1024;function ft(e,t){return`${e}:${t}`}function er(e){return[e.deviceId,e.sessionId||"",e.streamId||"",e.commandId||"",Number(e.captureGeneration||0),Number(e.monitorIndex??-1),e.streamPurpose||""].join("|")}const Kk={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:qk["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},Yk={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Rh={maxWidth:3840,maxHeight:2160};function gs(e,t){if(e.length===0)return 0;const a=[...e].sort((c,u)=>c-u),r=Math.max(0,Math.min(a.length-1,Math.ceil(a.length*t)-1));return a[r]}function pb(e,t){e.push(t),e.length>Sh&&e.splice(0,e.length-Sh)}function ml(e,t){e.sampleFrames=0,e.sampleStartedAt=t,e.intervalCount=0,e.intervalSumMs=0,e.minIntervalMs=Number.POSITIVE_INFINITY,e.maxIntervalMs=0,e.intervalSamplesMs.length=0,e.seqGapCount=0,e.maxSeqGap=0}function Ah(e,t,a){if(e.lastAt!==void 0){const r=Math.max(0,t-e.lastAt);e.intervalCount+=1,e.intervalSumMs+=r,e.minIntervalMs=Math.min(e.minIntervalMs,r),e.maxIntervalMs=Math.max(e.maxIntervalMs,r),pb(e.intervalSamplesMs,r)}if(e.lastFrameSeq!==void 0){const r=a-e.lastFrameSeq;r!==1&&(e.seqGapCount+=1,e.maxSeqGap=Math.max(e.maxSeqGap,Math.abs(r)))}e.lastAt=t,e.lastFrameSeq=a}function Ih(e){return!e||e.intervalCount<=0?"waiting":`${Math.round(e.averageIntervalMs)}ms avg / p95 ${Math.round(e.p95IntervalMs)}ms / max ${Math.round(e.maxIntervalMs)}ms`}function Th(e){return!e||e.seqGapCount<=0?"none":`${e.seqGapCount} gaps / max ${e.maxSeqGap}`}function Qk(e){return Number.isFinite(e)?String(e):"Unlimited"}const fb=[1,2,5,8,12,20,30],Ph={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},ur={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:wt.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:wt.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},fd=2200,Xk=2500,Jk=8e3,Zk=3500,Eh=7e3,eM=2,tM=2500,Nh=7e3,Fh=2600,nM=4200,rM=750,aM=2,Dh=2500,Lh=4200,Oh=2200;function _h(e,t){return Math.min(3e4,e*2**Math.min(3,Math.max(0,t)))}function vi(e,t){const a=e.capabilities?.[t];return typeof a=="boolean"?a:/^(1|true|yes|on)$/i.test(String(a||"").trim())}function Qt(e){return e.deviceName||e.hostname||e.deviceId}function oM(){return"npx -y --prefer-online livedesk@latest client"}function iM(){return"npx -y --prefer-online livedesk@latest"}function sM(){try{return localStorage.getItem(ob)||""}catch{return""}}function cM(){try{return localStorage.getItem(Hd)==="1"}catch{return!1}}function hi(e){try{e?localStorage.setItem(Hd,"1"):localStorage.removeItem(Hd)}catch{}}function dr(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ka(e){const t=dr(e.status),a=dr(t.screens),r=dr(e.capabilities),c=dr(e.latestLiveFrame),u=dr(e.activeLiveStream),h=[t.monitorCount,t.screenCount,a.count,r.monitorCount,r.screenCount,c.monitorCount,u.monitorCount,Array.isArray(a.displays)?a.displays.length:0,Array.isArray(t.displays)?t.displays.length:0,Array.isArray(t.monitors)?t.monitors.length:0].map(Number).filter(f=>Number.isFinite(f)&&f>0).map(f=>Math.max(1,Math.min(64,Math.floor(f))));return h.length>0?Math.max(...h):1}function Ia(e){const t=Number(e);return Number.isFinite(t)&&t>0?Math.floor(t):0}function hb(e){const t=dr(e.status),r=[dr(t.screens).displays,t.displays,t.monitors];for(const c of r)if(!(!Array.isArray(c)||c.length===0))return c.map(u=>dr(u));return[]}function em(e,t){const a=hb(e),r=a.find(f=>Number(f.index)===t)||a[t]||a[0]||{},c=Ia(r.width),u=Ia(r.height),p=[r.name,r.displayName,r.deviceName,r.id].find(f=>typeof f=="string"&&f.trim()),h=typeof p=="string"?p.trim():`Display ${t+1}`;return{index:t,name:h,width:c,height:u,primary:r.primary===!0||r.isPrimary===!0}}function lM(e){const t=ka(e);return Array.from({length:t},(a,r)=>em(e,r))}function uM(e){const t=hb(e);if(t.length===0)return"";const a=t.map((r,c)=>{const u=Number(r.index),p=[r.name,r.displayName,r.deviceName,r.id].find(f=>typeof f=="string"&&f.trim()),h=f=>{const k=Number(f);return Number.isFinite(k)?k:null};return[Number.isFinite(u)?Math.floor(u):c,typeof p=="string"?p.trim().toLowerCase():"",h(r.left),h(r.top),h(r.width),h(r.height),r.primary===!0||r.isPrimary===!0]}).sort((r,c)=>r[0]-c[0]);return JSON.stringify(a)}function dM(e){const t=[e.name||`Display ${e.index+1}`];return e.width>0&&e.height>0&&t.push(`${e.width}x${e.height}`),e.primary&&t.push("Primary"),t.join(" - ")}function gb(e,t){const a=em(e,t);if(a.width>0&&a.height>0)return{width:a.width,height:a.height};const r=dr(e.status),c=Ia(r.screenWidth||r.width),u=Ia(r.screenHeight||r.height);return c>0&&u>0?{width:c,height:u}:null}function bb(e){if(!e)return null;const t=Ia(e.sourceWidth)||Ia(e.width),a=Ia(e.sourceHeight)||Ia(e.height);return t>0&&a>0?{width:t,height:a}:null}function mM(e,t,a){const u=((typeof t?.monitorIndex=="number"?ys(t.monitorIndex,Math.max(1,t.monitorCount||1)):a)===a?bb(t):null)||gb(e,a);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const pl=16/9;function ys(e,t){const a=Math.max(1,Math.min(64,Math.floor(Number(t)||1))),r=Math.floor(Number(e));return Number.isFinite(r)?Math.max(0,Math.min(a-1,r)):0}function _n(e,t){return $C(t,ka(e),e.platform)}function pM(){try{const e=localStorage.getItem(lb);if(!e)return{selections:{},topologyFingerprints:{}};const t=JSON.parse(e),a=t&&typeof t=="object"&&!Array.isArray(t)?t.selections:void 0;if(Number(t?.version)!==ub||!a||typeof a!="object"||Array.isArray(a))return{selections:{},topologyFingerprints:{}};const r={},c={};for(const[u,p]of Object.entries(a)){const h=u.trim(),f=dr(p),k=f.monitorIndex,M=Math.floor(Number(k));if(!h||!Number.isFinite(M))continue;r[h]=Math.max(0,Math.min(63,M));const b=typeof f.topologyFingerprint=="string"?f.topologyFingerprint.trim():"";b&&(c[h]=b)}return{selections:r,topologyFingerprints:c}}catch{return{selections:{},topologyFingerprints:{}}}}function fM(e,t){try{const a=Object.fromEntries(Object.entries(e).map(([r,c])=>[r,{monitorIndex:c,topologyFingerprint:t[r]||""}]));localStorage.setItem(lb,JSON.stringify({version:ub,selections:a}))}catch{}}function hM(){return{...Kk}}function gM(e){try{localStorage.setItem(gk,JSON.stringify({...e,version:bk}))}catch{}}function bM(){return{...Yk}}function vM(e){try{localStorage.setItem(vk,JSON.stringify({...e,version:yk}))}catch{}}function yM(){try{return localStorage.getItem(ib)==="slow"?"slow":"fast"}catch{return"fast"}}function wM(e){try{localStorage.setItem(ib,e)}catch{}}function SM(){try{return localStorage.getItem(cb)==="true"}catch{return!1}}function CM(e){try{localStorage.setItem(cb,String(e))}catch{}}function kM(){try{const e=localStorage.getItem(sb);return e===null?ea:Mi(Number(e))}catch{return ea}}function MM(e){try{localStorage.setItem(sb,String(Mi(e)))}catch{}}function hd(e,t){return e.length!==t.length?!1:e.every((a,r)=>a===t[r])}function gd(e){return[...new Set(e.filter(Boolean))].sort()}function xM(e){return ur.fallbackVisibleCounts[e]||ur.fallbackVisibleCounts.large}function jh(e,t,a){if(e.frameMode==="mode4-h264-atlas")return e.atlasTileSizeMode==="auto"?t==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:e.atlasTileWidth,maxHeight:e.atlasTileHeight};if(!e.adaptiveSizeByWall)return{maxWidth:e.maxWidth,maxHeight:e.maxHeight};const r=Ph[t]||Ph.large;return{maxWidth:Math.min(e.maxWidth,r.maxWidth),maxHeight:Math.min(e.maxHeight,r.maxHeight)}}function RM(e,t=ur.minFps){const a=[...fb].sort((c,u)=>c-u),r=Math.max(t,Math.floor(e/2));return[...a].reverse().find(c=>c<e&&c>=t)||r}function AM(e,t){return[...fb].sort((r,c)=>r-c).find(r=>r>e&&r<=t)||t}function ws(e){if(!Number.isFinite(e)||e<=0)return"0 B";const t=["B","KB","MB","GB","TB"];let a=e,r=0;for(;a>=1024&&r<t.length-1;)a/=1024,r+=1;const c=r===0||a>=100?0:1;return`${a.toFixed(c)} ${t[r]}`}function Bh(e){if(!Number.isFinite(e)||!e||e<=0)return"0GB";const t=1024**4,a=1024**3;return e>=t?`${Math.max(1,Math.round(e/t))}TB`:`${Math.max(1,Math.round(e/a))}GB`}function bd(e,t){if(!Number.isFinite(e)||!e||e<=0)return"not reported";const a=Math.max(0,e-Math.max(0,Number(t||0)));return`${Bh(a)} / ${Bh(e)}`}function IM(e){const t=new Uint8Array(e),a=32768;let r="";for(let c=0;c<t.length;c+=a){const u=t.subarray(c,c+a);r+=String.fromCharCode(...u)}return btoa(r)}function Hh(e){return Array.from(e).filter(t=>t.size>=0).map(t=>{const a=t.webkitRelativePath||t.name;return{file:t,relativePath:a,fingerprint:`${t.size}:${t.lastModified}`}})}function bs(e){return e===1?"middle":e===2?"right":"left"}function Wh(e,...t){for(const a of t){const r=e?.[a];if(typeof r=="string"&&r.trim())return r.trim()}return""}function $h(e){const t=Number(e);return Number.isInteger(t)&&t>=1&&t<=hk?t:0}const TM={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function PM(e,t,a){if(e==="online")return"Online";if(e==="busy")return"Busy";if(e==="stale")return"Stale";if(e==="offline")return"Offline";if(a==="failed")return"Task failed";const r=e==="critical"?"critical":"warn",c=t.find(p=>p.state===r)||t.find(p=>p.state==="critical"||p.state==="warn");if(!c)return e==="critical"?"Issue":"Check";const u=TM[c.id]||c.label;return c.value&&c.value!=="-"?`${u} ${c.value}`:u}function vb(e,t){const a=t.split(".");let r=e;for(const c of a){if(r==null)return;if(Array.isArray(r)){const u=Number(c);r=Number.isInteger(u)?r[u]:void 0;continue}if(typeof r=="object"){r=r[c];continue}return}return r}function Lt(e,...t){for(const a of t){const r=vb(e,a),c=Number(r);if(Number.isFinite(c))return c}}function Er(e,...t){for(const a of t){const r=vb(e,a);if(typeof r=="string"&&r.trim())return r.trim();if(typeof r=="number"&&Number.isFinite(r))return String(r)}return""}function Zr(e){const t=Number(e);if(Number.isFinite(t))return Math.max(0,Math.min(1,t>1?t/100:t))}function vd(e,t){if(!(typeof e!="number"||typeof t!="number"||!Number.isFinite(e)||!Number.isFinite(t)||e<=0))return Zr((e-Math.max(0,t))/e)}function gi(e){return e===void 0?"-":`${Math.round(e*100)}%`}function yd(e){return e===void 0||!Number.isFinite(e)?"":e>=1e3?`${(e/1e3).toFixed(e>=1e4?0:1)}Gb/s`:`${Math.round(e)}Mb/s`}function vo(e,t=.92,a=.78){return e===void 0?"unknown":e>=t?"critical":e>=a?"warn":"good"}function EM(e){return!Number.isFinite(e)||!e||e<=0?"-":e<3600?`${Math.round(e/60)}m`:e<86400?`${Math.round(e/3600)}h`:`${Math.round(e/86400)}d`}function yb(e){const t=e.status||{},a=Lt(t,"cpu.cores","cpuCores","processorCount"),r=Lt(t,"loadavg.0","cpu.load1"),c=Zr(Lt(t,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(a&&r!==void 0?r/Math.max(1,a):void 0)),u=Lt(t,"memory.totalBytes","totalMem"),p=Lt(t,"memory.freeBytes","freeMem"),h=Zr(Lt(t,"memory.usedRatio","memory.usedPct","usedMemRatio"))??vd(u,p),f=Lt(t,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),k=Lt(t,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),M=Zr(Lt(t,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??vd(f,k),b=Lt(t,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),T=Zr(Lt(t,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),A=Er(t,"gpu.name","gpu.model","accelerators.gpu.name"),x=Lt(t,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),E=Lt(t,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),B=Zr(Lt(t,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??vd(x,E),q=Lt(t,"gpu.temperatureC","thermal.gpuC"),G=Zr(Lt(t,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),ne=Er(t,"npu.name","npu.model","accelerators.npu.name"),re=Lt(t,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=Lt(t,"network.rxMbps","network.receiveMbps","network.downMbps"),ie=Lt(t,"network.txMbps","network.transmitMbps","network.upMbps"),J=Lt(t,"network.latencyMs","network.rttMs"),de=Zr(Lt(t,"network.usedRatio","network.usageRatio","network.saturationRatio")),se=Er(t,"network.link","network.interface","network.name"),pe=Math.max(b??Number.NEGATIVE_INFINITY,q??Number.NEGATIVE_INFINITY),ce=Number.isFinite(pe)?pe:void 0,W=ce===void 0?void 0:Zr((ce-35)/60),ee=b!==void 0&&q!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(q)}°`:b!==void 0?`CPU ${Math.round(b)}°`:q!==void 0?`GPU ${Math.round(q)}°`:"-",L=Er(t,"workload.role","role","lane")||(vi(e,"taskDispatch")?"Command-ready Client":"Local machine"),_=Er(e.latestTask,"status")||Er(t,"workload.status")||"idle",K=Er(e.latestTask,"title","instructionPreview")||Er(t,"workload.title"),ue=Er(e.latestTask,"resultSummary","error","instructionPreview")||Er(t,"workload.summary"),P=Date.parse(e.lastSeenAt||e.connectedAt||""),N=Number.isFinite(P)?Date.now()-P:0;let te="online";e.connected?N>5*6e4?te="stale":(b??0)>=86||(q??0)>=88||(c??0)>=.94||(T??0)>=.96||(B??0)>=.96||(G??0)>=.96||(h??0)>=.94||(M??0)>=.94||(J??0)>=200||_==="failed"?te="critical":(b??0)>=78||(q??0)>=80||(c??0)>=.82||(T??0)>=.86||(B??0)>=.88||(G??0)>=.86||(h??0)>=.82||(M??0)>=.86||(J??0)>=80?te="warn":["queued","running","targeted"].includes(_)&&(te="busy"):te="offline";const we=[{id:"cpu",label:"CPU",value:gi(c),detail:a?`${a} cores`:r!==void 0?`load ${r.toFixed(1)}`:"not reported",ratio:c,state:vo(c,.92,.78)},{id:"memory",label:"RAM",value:gi(h),detail:bd(u,p),ratio:h,state:vo(h,.92,.78)},{id:"disk",label:"DISK",value:gi(M),detail:bd(f,k),ratio:M,state:vo(M,.92,.82)},{id:"gpu",label:"GPU",value:gi(T),detail:A||(x&&E!==void 0?`${ws(E)} VRAM free`:q!==void 0?`${Math.round(q)}C`:"not reported"),ratio:T,state:q!==void 0&&q>=88?"critical":q!==void 0&&q>=80?"warn":vo(T,.96,.86)},{id:"vram",label:"VRAM",value:gi(B),detail:bd(x,E),ratio:B,state:vo(B,.96,.88)},{id:"npu",label:"NPU",value:G!==void 0?gi(G):re!==void 0?`${Math.round(re)} TOPS`:"-",detail:ne||(re!==void 0?"neural engine":"not reported"),ratio:G,state:vo(G,.96,.86)},{id:"temp",label:"TEMP",value:ee,detail:`uptime ${EM(Lt(t,"uptimeSec"))}`,ratio:W,state:ce===void 0?"unknown":ce>=86?"critical":ce>=78?"warn":"good"},{id:"network",label:"NET",value:yd(O)||(J!==void 0?`${Math.round(J)}ms`:se||"-"),detail:yd(ie)?`${yd(ie)} up`:se||"not reported",ratio:de,state:J!==void 0&&J>=200?"critical":J!==void 0&&J>=80?"warn":vo(de,.9,.75)}];return{state:te,label:PM(te,we,_),role:L,taskLabel:K||(_==="idle"?"idle":_),taskStatus:_,taskSummary:ue,metrics:we}}const Vh=[{id:"slow",label:"Slow",fps:Ms("slow")},{id:"fast",label:"Fast",fps:Ms("fast")}],NM=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],FM=[{id:"list",label:"List"},{id:"large",label:"Wall"}],zh=[{id:"sync-server",label:"Hub",icon:Si,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Jh,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Cs,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Zh,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:gl,accent:"violet",tooltip:"agents"}],Uh=[{id:"doc",label:"Doc",icon:Sd,accent:"amber"},{id:"support",label:"Support",icon:by,accent:"violet"},{id:"pricing",label:"Pricing",icon:xa,accent:"green"}];function DM(e){return e.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 Tt(e){return DM(e).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 yo(e){return e.map(t=>Tt(t))}function pn(e){return{languageName:e.languageName,languageLabel:e.languageLabel,eyebrow:e.eyebrow,title:Tt(e.title),intro:Tt(e.intro),sections:[{title:Tt(e.managerTitle),body:Tt(e.managerBody),points:yo(e.managerPoints)},{title:Tt(e.clientTitle),body:Tt(e.clientBody),points:yo(e.clientPoints)},{title:Tt(e.syncTitle),body:Tt(e.syncBody),points:yo(e.syncPoints)},...e.agentTitle&&e.agentBody&&e.agentPoints?[{title:Tt(e.agentTitle),body:Tt(e.agentBody),points:yo(e.agentPoints)}]:[],{title:Tt(e.platformTitle),body:Tt(e.platformBody),points:yo(e.platformPoints)}],sync:{title:Tt(e.syncTitle),body:Tt(e.syncBody),points:yo(e.syncPoints)},firewall:{title:Tt(e.firewallTitle),body:Tt(e.firewallBody),points:yo(e.firewallPoints)},commands:{title:Tt(e.commandsTitle),body:Tt(e.commandsBody),manager:Tt(e.managerCommandLabel),primary:Tt(e.clientCommandLabel),slot:Tt(e.slotCommandLabel),manual:Tt(e.manualCommandLabel)}}}const Ci={ko:pn({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"VuvoDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"VuvoDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 VuvoDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 VuvoDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --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를 누릅니다.","이제 vuvodesk.com의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 VuvoDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"VuvoDesk는 인증된 Direct TCP와 암호화된 UDP/WebRTC P2P로 화면과 제어를 직접 연결합니다. rendezvous 서비스는 상대 찾기와 P2P 연결 정보 교환만 하며 화면·입력 데이터는 중계하지 않습니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 상대 찾기와 P2P signaling을 위해 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","영상과 입력 데이터는 Direct TCP 또는 암호화된 UDP/WebRTC P2P로 장치끼리 직접 전송합니다.","외부망 Direct TCP에는 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다. P2P가 막히면 VuvoDesk가 직접 연결을 다시 시도합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 VuvoDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:pn({languageName:"English",languageLabel:"Document language",eyebrow:"VuvoDesk Manual",title:"Open a local Screen Wall with one command",intro:"VuvoDesk is an npm-first remote work deck for monitoring Clients, mini PCs, Mac minis, and development machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run VuvoDesk 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 VuvoDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a Client",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 vuvodesk.com is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability 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.","The Hub-hosted Codex Agent turns instructions into approved VuvoDesk tool calls and shows progress and results for each computer."],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:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client 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, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"VuvoDesk connects screen and control payloads directly through authenticated Direct TCP and encrypted UDP/WebRTC P2P. The rendezvous service only finds peers and exchanges P2P connection details; it never carries screen or input payloads.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server for peer discovery and P2P signaling.","Screen and input payloads travel device-to-device through Direct TCP or encrypted UDP/WebRTC P2P.","For Direct TCP across networks, forward TCP 5197 or configure VPN/IP allowlists. When P2P is blocked, VuvoDesk keeps retrying a direct connection.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],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 Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:pn({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"VuvoDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"VuvoDesk は、複数の作業 PC、mini PC、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで VuvoDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い VuvoDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. Client を接続",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 を押します。","vuvodesk.com の 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、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"VuvoDesk は認証済み Direct TCP と暗号化 UDP/WebRTC P2P で画面と操作を直接接続します。rendezvous サービスは相手の発見と P2P 接続情報の交換だけを行い、画面や入力データを中継しません。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は相手の発見と P2P signaling のため、設定済み rendezvous server へ outbound 接続できる必要があります。","画面と入力データは Direct TCP または暗号化 UDP/WebRTC P2P で端末間を直接移動します。","ネットワーク越しの Direct TCP には TCP 5197 の転送または VPN/IP allowlist を設定します。P2P が遮断された場合は直接接続を再試行します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":pn({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"VuvoDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"VuvoDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 VuvoDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 VuvoDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 Client",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。","vuvodesk.com 的 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 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"VuvoDesk 通过经过认证的 Direct TCP 和加密 UDP/WebRTC P2P 直接传送画面与控制。rendezvous 服务只负责发现对端和交换 P2P 连接信息,不会转发画面或输入数据。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接,用于发现对端和 P2P signaling。","画面和输入数据通过 Direct TCP 或加密 UDP/WebRTC P2P 在设备之间直接传送。","跨网络使用 Direct TCP 时请转发 TCP 5197 或配置 VPN/IP 白名单。P2P 被阻断时会继续重试直连。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":pn({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"VuvoDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"VuvoDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 VuvoDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 VuvoDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 Client",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。","vuvodesk.com 的 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、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"VuvoDesk 透過已驗證的 Direct TCP 與加密 UDP/WebRTC P2P 直接傳送畫面和控制。rendezvous 服務只負責尋找對端與交換 P2P 連線資訊,不會轉送畫面或輸入資料。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線,以尋找對端並進行 P2P signaling。","畫面與輸入資料透過 Direct TCP 或加密 UDP/WebRTC P2P 在裝置間直接傳送。","跨網路使用 Direct TCP 時請轉送 TCP 5197 或設定 VPN/IP allowlist。P2P 受阻時會持續重試直連。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:pn({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"VuvoDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"VuvoDesk es una consola npm-first para vigilar equipos de trabajo, mini PC, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta VuvoDesk 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 Client",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 vuvodesk.com 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: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"VuvoDesk conecta pantalla y control directamente mediante Direct TCP autenticado y UDP/WebRTC P2P cifrado. El servicio rendezvous solo localiza pares e intercambia datos de conexión P2P; no reenvía pantallas ni entradas.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado para descubrir pares y hacer signaling P2P.","Pantalla e input viajan entre dispositivos por Direct TCP o UDP/WebRTC P2P cifrado.","Para Direct TCP entre redes, reenvía TCP 5197 o configura VPN/allowlist de IP. Si P2P está bloqueado, VuvoDesk sigue intentando una conexión directa.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],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 Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:pn({languageName:"Français",languageLabel:"Langue du document",eyebrow:"VuvoDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"VuvoDesk est un deck npm-first pour surveiller plusieurs postes, mini PC, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez VuvoDesk 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 Client",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 vuvodesk.com 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, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"VuvoDesk relie directement l’écran et le contrôle par Direct TCP authentifié et UDP/WebRTC P2P chiffré. Le service rendezvous sert uniquement à trouver les pairs et à échanger les informations P2P ; il ne transmet ni écran ni saisie.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent accéder au serveur rendezvous configuré pour la découverte et le signaling P2P.","Écran et saisie passent directement entre appareils par Direct TCP ou UDP/WebRTC P2P chiffré.","Pour Direct TCP entre réseaux, redirigez TCP 5197 ou configurez VPN/allowlist IP. Si le P2P est bloqué, VuvoDesk retente une connexion directe.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],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 Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:pn({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"VuvoDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"VuvoDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte VuvoDesk 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 VuvoDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Client 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 vuvodesk.com 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, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"VuvoDesk verbindet Bildschirm und Steuerung direkt über authentifiziertes Direct TCP und verschlüsseltes UDP/WebRTC P2P. Der Rendezvous-Dienst findet nur Peers und tauscht P2P-Verbindungsdaten aus; Bildschirm- und Eingabedaten werden nicht weitergeleitet.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server für Peer-Erkennung und P2P-Signaling.","Bildschirm- und Eingabedaten laufen direkt zwischen Geräten über Direct TCP oder verschlüsseltes UDP/WebRTC P2P.","Für Direct TCP zwischen Netzwerken TCP 5197 weiterleiten oder VPN/IP-Allowlist einrichten. Wenn P2P blockiert ist, versucht VuvoDesk die direkte Verbindung erneut.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":pn({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"VuvoDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"VuvoDesk é um deck npm-first para monitorar várias estações, mini PCs, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"VuvoDesk conecta tela e controle diretamente por Direct TCP autenticado e UDP/WebRTC P2P criptografado. O serviço rendezvous apenas encontra os pares e troca dados de conexão P2P; ele não encaminha tela nem entrada.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado para descoberta e signaling P2P.","Tela e entrada trafegam diretamente entre dispositivos por Direct TCP ou UDP/WebRTC P2P criptografado.","Para Direct TCP entre redes, encaminhe TCP 5197 ou configure VPN/allowlist IP. Se o P2P estiver bloqueado, VuvoDesk continua tentando conexão direta.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],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 Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:pn({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"VuvoDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"VuvoDesk è un deck npm-first per monitorare Client, mini PC, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"VuvoDesk collega schermo e controllo direttamente con Direct TCP autenticato e UDP/WebRTC P2P cifrato. Il servizio rendezvous trova solo i peer e scambia le informazioni P2P; non inoltra schermo o input.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono accedere al server rendezvous configurato per discovery e signaling P2P.","Schermo e input viaggiano direttamente tra dispositivi tramite Direct TCP o UDP/WebRTC P2P cifrato.","Per Direct TCP tra reti, inoltra TCP 5197 o configura VPN/allowlist IP. Se il P2P è bloccato, VuvoDesk ritenta la connessione diretta.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:pn({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"VuvoDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"VuvoDesk adalah deck npm-first untuk memantau banyak Client, mini PC, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"VuvoDesk menghubungkan layar dan kontrol secara langsung melalui Direct TCP terautentikasi dan UDP/WebRTC P2P terenkripsi. Layanan rendezvous hanya menemukan peer dan menukar informasi koneksi P2P; tidak meneruskan layar atau input.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous untuk discovery dan signaling P2P.","Layar dan input bergerak langsung antardevice melalui Direct TCP atau UDP/WebRTC P2P terenkripsi.","Untuk Direct TCP antarjaringan, forward TCP 5197 atau atur VPN/IP allowlist. Jika P2P diblokir, VuvoDesk terus mencoba koneksi langsung.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:pn({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"VuvoDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"VuvoDesk là deck npm-first để giám sát nhiều Client, mini PC, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy VuvoDesk 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 Client",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 vuvodesk.com 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 X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"VuvoDesk kết nối trực tiếp màn hình và control bằng Direct TCP đã xác thực và UDP/WebRTC P2P mã hóa. Dịch vụ rendezvous chỉ tìm peer và trao đổi thông tin kết nối P2P; không chuyển tiếp màn hình hoặc input.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server để discovery và signaling P2P.","Màn hình và input đi trực tiếp giữa các thiết bị qua Direct TCP hoặc UDP/WebRTC P2P mã hóa.","Để dùng Direct TCP giữa các mạng, hãy forward TCP 5197 hoặc cấu hình VPN/IP allowlist. Khi P2P bị chặn, VuvoDesk tiếp tục thử kết nối trực tiếp.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],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 Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:pn({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"VuvoDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"VuvoDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน VuvoDesk บนเครื่องที่ใช้ดูหน้าจอ 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. เชื่อม Client",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 บน vuvodesk.com ไม่ใช่ 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 และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"VuvoDesk เชื่อมหน้าจอและ control โดยตรงด้วย Direct TCP ที่ยืนยันตัวตนและ UDP/WebRTC P2P ที่เข้ารหัส บริการ rendezvous ใช้เพียงค้นหา peer และแลกข้อมูลการเชื่อมต่อ P2P โดยไม่ส่งต่อหน้าจอหรือ input",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server เพื่อ discovery และ P2P signaling","หน้าจอและ input ส่งตรงระหว่าง device ผ่าน Direct TCP หรือ UDP/WebRTC P2P ที่เข้ารหัส","หากต้องใช้ Direct TCP ข้าม network ให้ forward TCP 5197 หรือตั้ง VPN/IP allowlist เมื่อ P2P ถูกบล็อก VuvoDesk จะลองเชื่อมตรงอีกครั้ง","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:pn({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"VuvoDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"VuvoDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर VuvoDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने VuvoDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. Client जोड़ें",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 दबाएं।","vuvodesk.com का 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, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"VuvoDesk authenticated Direct TCP और encrypted UDP/WebRTC P2P से screen और control को सीधे जोड़ता है। rendezvous service केवल peers खोजती और P2P connection info बदलती है; screen या input data आगे नहीं भेजती।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Peer discovery और P2P signaling के लिए Clients और manager को configured rendezvous server तक outbound access चाहिए।","Screen और input data Direct TCP या encrypted UDP/WebRTC P2P से device-to-device सीधे जाते हैं।","Networks के बीच Direct TCP के लिए TCP 5197 forward या VPN/IP allowlist सेट करें। P2P block होने पर VuvoDesk direct connection फिर आज़माता है।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:pn({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"VuvoDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"VuvoDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل VuvoDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية VuvoDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل Client",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 على vuvodesk.com لم يعد مسار التشغيل الافتراضي. تطبيق 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 وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يربط VuvoDesk الشاشة والتحكم مباشرة عبر Direct TCP موثق وUDP/WebRTC P2P مشفر. تقتصر خدمة rendezvous على اكتشاف الأطراف وتبادل معلومات اتصال P2P، ولا تمرر الشاشة أو بيانات الإدخال.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous للاكتشاف وP2P signaling.","تنتقل الشاشة وبيانات الإدخال مباشرة بين الأجهزة عبر Direct TCP أو UDP/WebRTC P2P المشفر.","لاستخدام Direct TCP بين الشبكات وجه TCP 5197 أو اضبط VPN/IP allowlist. عند حظر P2P يعيد VuvoDesk محاولة الاتصال المباشر.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:pn({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"VuvoDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"VuvoDesk, tek bir manager PC üzerinden birçok Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda VuvoDesk 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 VuvoDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Client 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.","vuvodesk.com ü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 X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"VuvoDesk ekranı ve kontrolü doğrulanmış Direct TCP ve şifreli UDP/WebRTC P2P ile doğrudan bağlar. Rendezvous hizmeti yalnızca eşleri bulur ve P2P bağlantı bilgilerini değiştirir; ekran veya girdi verisini taşımaz.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager, eş keşfi ve P2P signaling için yapılandırılmış rendezvous servera outbound erişebilmelidir.","Ekran ve girdi verileri Direct TCP veya şifreli UDP/WebRTC P2P ile cihazdan cihaza doğrudan gider.","Ağlar arasında Direct TCP için TCP 5197 yönlendirme veya VPN/IP allowlist yapılandırın. P2P engellenirse VuvoDesk doğrudan bağlantıyı yeniden dener.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose 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:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},LM=Object.entries(Ci).map(([e,t])=>({id:e,label:t.languageName}));function OM(){if(typeof navigator>"u")return"en";const e=navigator.languages?.length?navigator.languages:[navigator.language];for(const t of e){const a=t.toLowerCase();if(Ci[t])return t;if(a.startsWith("zh-tw")||a.startsWith("zh-hk"))return"zh-TW";if(a.startsWith("pt"))return"pt-BR";const r=a.split("-")[0];if(Ci[r])return r}return"en"}function qh({index:e}){const t=e+1;return i.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${t}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"empty-screen",children:[i.jsx(Ra,{size:24}),i.jsxs("strong",{children:["Slot ",String(t).padStart(3,"0")]})]})]})})}const _M=["cpu","gpu","memory","vram","network","disk","temp"];function jM({device:e,slotNumber:t,selected:a,updateIndicator:r,remoteDiagnostics:c,diagnosticsMode:u="remote",onSelect:p,onOpenControl:h}){const f=yb(e),k=new Map(f.metrics.map(b=>[b.id,b])),M=r?.label||f.label;return i.jsxs("div",{className:`wall-device-list-row state-${f.state} ${a?"selected":""}`,role:"row","aria-selected":a,tabIndex:0,onClick:p,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),p())},children:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ra,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:Qt(e)}),i.jsxs("small",{children:["Slot ",String(t).padStart(3,"0"),e.platform?` · ${e.platform}`:"",e.arch?` · ${e.arch}`:""]})]}),a&&i.jsx(hl,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),i.jsxs("span",{className:`wall-device-list-status state-${f.state} ${r?`update-${r.state}`:""}`,role:"gridcell",title:r?.error||M,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:M})]}),_M.map(b=>{const T=k.get(b);return i.jsxs("span",{className:`wall-device-list-metric state-${T?.state||"unknown"}`,role:"gridcell",title:T?`${T.label}: ${T.value} · ${T.detail}`:"Not reported",children:[i.jsx("strong",{children:T?.value||"-"}),i.jsx("small",{children:T?.detail||"not reported"}),T?.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(T.ratio*100)}%`},"aria-hidden":"true"})]},b)}),c&&i.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:i.jsx(Jg,{items:c,mode:u})})]})}function BM(e){if(!e)return!1;const t=String(e.platform||"").trim().toLowerCase();return Nr(t)&&e.capabilities?.screenRecordingPermission===!1}function Nr(e){const t=String(e||"").trim().toLowerCase();return t==="macos"||t==="darwin"||t==="mac"||t==="macosx"}function HM(e){const t=String(e||"").trim().toLowerCase();return t==="linux"||t.startsWith("linux ")}function Gh(e){const t=String(e||"").trim().toLowerCase();return["win32","windows","win32nt"].includes(t)?"mode5-lzo-delta":Nr(t)?"mode1-jpeg":""}function wd({device:e,frame:t,selected:a,controlEnabled:r,showStatus:c,showDeviceTitle:u=!0,monitorIndex:p,monitorCount:h,onSelect:f,onFocusDevice:k,onOpenControl:M,onCycleMonitor:b,onCanvasReady:T,sendInput:A,remotePointerFeedback:x,remoteModifierState:E,updateIndicator:B,presentationReady:q,showPresentationSpinner:G=!1,remoteDiagnostics:ne,diagnosticsMode:re="remote"}){const O=s.useRef(null),ie=s.useRef(null),J=s.useRef(null),de=s.useRef(0),se=s.useRef(null),pe=s.useRef(null),ce=s.useRef(new Map),W=s.useRef(null),ee=s.useRef(AC()),L=s.useRef(MC()),_=s.useRef(!1),K=s.useRef([]),ue=s.useRef(xl()),P=s.useRef(null),N=s.useRef(null),te=yb(e),we=["cpu","gpu","memory","vram"].map(g=>te.metrics.find(U=>U.id===g)).filter(g=>!!g),me=Jd(p),Fe=h>1,H=q??!!t,R=BM(e)&&!H,Se=G&&e.connected&&!H&&!R,Ce=mM(e,t,me),Ve=Ce>=pl?100:Ce/pl*100,qe=Ce>=pl?pl/Ce*100:100,Oe={"--screen-aspect":Ce.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,Ve)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,qe)).toFixed(3)}%`},z=r?{transformOrigin:"0 0",transform:`translate3d(${ue.current.translateX.toFixed(2)}px, ${ue.current.translateY.toFixed(2)}px, 0) scale(${ue.current.scale.toFixed(4)})`}:void 0,Me=!!(r&&H&&x?.nativeInputBackend==="win32-window-message"&&x.deviceId===e.deviceId&&x.monitorIndex===me),je=Me?{left:`${Math.max(0,Math.min(1,x.normalizedX))*100}%`,top:`${Math.max(0,Math.min(1,x.normalizedY))*100}%`}:void 0,Ge=s.useCallback(g=>{ue.current=g;const U=O.current;U&&(U.style.transformOrigin="0 0",U.style.transform=`translate3d(${g.translateX.toFixed(2)}px, ${g.translateY.toFixed(2)}px, 0) scale(${g.scale.toFixed(4)})`,U.dataset.touchZoom=g.scale.toFixed(2))},[]),kt=s.useCallback(g=>{if(O.current=g,g&&r){const U=ue.current;g.style.transformOrigin="0 0",g.style.transform=`translate3d(${U.translateX.toFixed(2)}px, ${U.translateY.toFixed(2)}px, 0) scale(${U.scale.toFixed(4)})`,g.dataset.touchZoom=U.scale.toFixed(2)}T(e.deviceId,g)},[r,e.deviceId,T]),Te=(g,U,F)=>RC(g,U,F.getBoundingClientRect()),Be=g=>Te(g.clientX,g.clientY,g.currentTarget),Y=g=>LC(g,E),ve=s.useCallback(()=>{se.current!==null&&(window.cancelAnimationFrame(se.current),se.current=null)},[]),st=s.useCallback(()=>{const g=P.current;g&&(window.clearTimeout(g.timerId),P.current=null);const U=N.current;U&&window.clearTimeout(U.timerId),N.current=null},[]),it=s.useCallback(()=>{const g=J.current;if(!g)return;J.current=null;const U=Number(g.input.normalizedX),F=Number(g.input.normalizedY);if(!Number.isFinite(U)||!Number.isFinite(F))return;A(e.deviceId,{...g.input,normalizedX:U,normalizedY:F})&&(de.current=performance.now())},[e.deviceId,A]),bt=s.useCallback(()=>{se.current===null&&(se.current=window.requestAnimationFrame(()=>{se.current=null,it()}))},[it]);s.useEffect(()=>{L.current.reset(),_.current=!1,K.current=[];const g=xl();return Ge(g),()=>{ve(),st(),J.current=null,pe.current=null,ce.current.clear(),W.current=null,L.current.reset(),_.current=!1,K.current=[]}},[me,Ge,st,ve,r,e.deviceId]);const Mt=(g,U)=>{if(!r)return;const F={...g,type:U};if(U==="pointermove"){const he=performance.now();J.current={input:F},he-de.current>=Tk&&(ve(),it()),bt();return}J.current&&(ve(),it()),A(e.deviceId,F)},ae=(g,U,F=bs(g.button),he="")=>{Mt({monitorIndex:me,...Be(g),button:F,...he?{inputSource:he}:{},...Y(g)},U)},$=(g,U)=>{A(e.deviceId,{...g,type:"pointerdown",button:U}),A(e.deviceId,{...g,type:"pointerup",button:U})},ye=(g,U,F)=>({monitorIndex:me,...Te(g,U,F),shiftKey:!!E?.shiftKey,ctrlKey:!!E?.ctrlKey,altKey:!!E?.altKey,metaKey:!!E?.metaKey}),V=(g,U)=>{const F=P.current;F&&(window.clearTimeout(F.timerId),P.current=null,$(F.input,"left"));const he={tap:g,input:U,timerId:0};he.timerId=window.setTimeout(()=>{P.current===he&&(P.current=null,$(U,"left"))},Dd),P.current=he},Ke=(g,U,F)=>{if(ce.current.set(g,{clientX:U,clientY:F}),W.current)return;const he=pe.current;if(he&&he.pointerId!==g){const Ye=ce.current.get(he.pointerId),ut=ce.current.get(g),xe=ie.current?.getBoundingClientRect();Ye&&ut&&xe&&(ve(),J.current=null,st(),pe.current=null,W.current={gesture:IC(Ye,ut,ue.current,xe),pointerIds:[he.pointerId,g]});return}const Q=performance.now(),Ie=P.current,be={clientX:U,clientY:F,at:Q};if(Ie&&Wf(Ie.tap,be)){window.clearTimeout(Ie.timerId),P.current=null;const Ye={...Ie,timerId:0};Ye.timerId=window.setTimeout(()=>{N.current===Ye&&(N.current=null,$(Ye.input,"left"))},Math.max(0,Ie.tap.at+Dd-Q)),N.current=Ye}else N.current=null,Ie&&(window.clearTimeout(Ie.timerId),P.current=null,$(Ie.input,"left"));pe.current=PC(g,U,F),k()},St=(g,U,F,he)=>{ce.current.set(g,{clientX:U,clientY:F});const Q=W.current;if(Q){const Ye=ce.current.get(Q.pointerIds[0]),ut=ce.current.get(Q.pointerIds[1]);Ye&&ut&&Ge(TC(Q.gesture,Ye,ut));return}const Ie=pe.current;if(!Ie||Ie.pointerId!==g)return;const be=zg(Ie,g,U,F);if(pe.current=be,be?.dragged&&N.current){const Ye=N.current;window.clearTimeout(Ye.timerId),N.current=null,$(Ye.input,"left")}be?.dragged&&Mt(ye(U,F,he),"pointermove")},I=(g,U,F,he)=>{if(ce.current.set(g,{clientX:U,clientY:F}),W.current){ce.current.delete(g),ce.current.size===0&&(W.current=null);return}const Q=EC(pe.current,g,U,F,performance.now());if(ce.current.delete(g),Q.kind==="ignore")return;Q.kind==="drag"&&(Mt(ye(U,F,he),"pointermove"),ve(),it()),pe.current=null;const Ie=N.current;if(Ie&&window.clearTimeout(Ie.timerId),N.current=null,Q.kind==="tap"&&Q.tap){const be=ye(U,F,he);Ie&&Wf(Ie.tap,Q.tap)?$(be,"right"):(Ie&&$(Ie.input,"left"),V(Q.tap,be))}else Ie&&$(Ie.input,"left")},oe=g=>{if(ce.current.delete(g),W.current){ce.current.size===0&&(W.current=null);return}if(pe.current?.pointerId===g){ve(),J.current=null,pe.current=null;const U=N.current;U&&(window.clearTimeout(U.timerId),$(U.input,"left")),N.current=null}},Pe=g=>{if(g.pointerType!=="touch")return!1;if(g.preventDefault(),g.stopPropagation(),ee.current.shouldHandlePointerEvent()){Ke(g.pointerId,g.clientX,g.clientY);try{g.currentTarget.setPointerCapture(g.pointerId)}catch{}}return!0},He=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),ee.current.shouldHandlePointerEvent()&&St(g.pointerId,g.clientX,g.clientY,g.currentTarget),!0),vt=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),g.stopPropagation(),ee.current.shouldHandlePointerEvent()&&I(g.pointerId,g.clientX,g.clientY,g.currentTarget),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),!0),Ze=g=>g.pointerType!=="touch"?!1:(g.preventDefault(),g.stopPropagation(),ee.current.shouldHandlePointerEvent()&&oe(g.pointerId),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId),!0),At=g=>{if(r){g.preventDefault(),g.stopPropagation(),ee.current.shouldHandlePointerEvent()&&(ee.current.claimNativeTouchEvents(),pe.current=null,ce.current.clear(),W.current=null);for(const U of Array.from(g.changedTouches))Ke(U.identifier,U.clientX,U.clientY)}},_t=g=>{if(!r)return;g.preventDefault(),g.stopPropagation();for(const he of Array.from(g.touches))ce.current.set(he.identifier,{clientX:he.clientX,clientY:he.clientY});const U=pe.current?.pointerId,F=Array.from(g.touches).find(he=>he.identifier===U)||g.touches.item(0);F&&St(F.identifier,F.clientX,F.clientY,g.currentTarget)},Jt=g=>{if(r){g.preventDefault(),g.stopPropagation();for(const U of Array.from(g.changedTouches))I(U.identifier,U.clientX,U.clientY,g.currentTarget)}},xt=g=>{if(r){g.preventDefault(),g.stopPropagation();for(const U of Array.from(g.changedTouches))oe(U.identifier)}},Vt=s.useCallback(g=>{const U=document.activeElement;U instanceof HTMLElement&&g.contains(U)&&U.classList.contains("monitor-cycle-button")&&U.blur()},[]);return i.jsx("article",{className:`device-tile ${a?"selected":""} ${e.connected?"online":"offline"}`,"data-live-device-id":e.deviceId,style:Oe,children:i.jsxs("div",{className:`tile-screen ${H?"has-frame":"is-empty"}`,role:"button",tabIndex:r?-1:0,"aria-pressed":a,onClick:g=>{g.target instanceof Element&&g.target.closest(".monitor-cycle")||r||f()},onKeyDown:g=>{g.target instanceof Element&&g.target.closest(".monitor-cycle")||r||(g.key==="Enter"||g.key===" ")&&(g.preventDefault(),f())},onDoubleClick:g=>{if(!(g.target instanceof Element&&g.target.closest(".monitor-cycle"))){if(g.preventDefault(),r){g.stopPropagation();return}M()}},onPointerLeave:g=>Vt(g.currentTarget),children:[i.jsxs("span",{ref:ie,className:`screen-content ${H?"has-frame":"is-empty"}`,children:[i.jsx("canvas",{ref:kt,className:`remote-canvas ${H?"has-frame":"is-empty"} ${r?"control-input-enabled":""}`,"data-monitor-index":me,"data-touch-zoom":ue.current.scale.toFixed(2),style:z,tabIndex:r?0:-1,onPointerDown:g=>{if(r&&!Pe(g)){_.current=!1,L.current.observePointerEvent("down",g),g.preventDefault(),g.stopPropagation(),k(),g.currentTarget.focus(),ae(g,"pointerdown");try{g.currentTarget.setPointerCapture(g.pointerId)}catch{}}},onPointerMove:g=>{r&&g.preventDefault(),!He(g)&&(r&&(_.current=!1,L.current.observePointerEvent("move",g)),ae(g,"pointermove"))},onPointerLeave:g=>{r&&g.pointerType!=="touch"&&(_.current=!1,L.current.observePointerEvent("leave",g),ae(g,"pointermove"),ve(),it())},onPointerUp:g=>{r&&(vt(g)||(_.current=!1,L.current.observePointerEvent("up",g),g.preventDefault(),g.stopPropagation(),ae(g,"pointerup"),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId)))},onPointerCancel:g=>{Ze(g)||(r&&(g.preventDefault(),g.stopPropagation(),ae(g,"pointerup")),g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId))},onMouseDown:g=>{if(!r||!L.current.shouldHandleMouseEvent("down",g))return;g.preventDefault(),g.stopPropagation(),_.current=!0,k(),g.currentTarget.focus();const U=bs(g.button);K.current.includes(U)||K.current.push(U),ae(g,"pointerdown",U,"legacy-mouse")},onMouseMove:g=>{!r||!L.current.shouldHandleMouseEvent("move",g)||(g.preventDefault(),_.current=!0,ae(g,"pointermove",bs(g.button),"legacy-mouse"))},onMouseLeave:g=>{if(!r||!L.current.shouldHandleMouseEvent("leave",g))return;_.current=!0,ae(g,"pointermove",bs(g.button),"legacy-mouse"),ve(),it();const U=K.current.splice(0).reverse();for(const F of U)ae(g,"pointerup",F,"legacy-mouse")},onMouseUp:g=>{if(!r||!L.current.shouldHandleMouseEvent("up",g))return;g.preventDefault(),g.stopPropagation(),_.current=!0;const U=bs(g.button);ae(g,"pointerup",U,"legacy-mouse"),K.current=K.current.filter(F=>F!==U)},onTouchStart:At,onTouchMove:_t,onTouchEnd:Jt,onTouchCancel:xt,onWheel:g=>{r&&(g.preventDefault(),A(e.deviceId,{type:"wheel",monitorIndex:me,...Be(g),deltaX:g.deltaX,deltaY:g.deltaY,..._.current?{inputSource:"legacy-mouse"}:{},...Y(g)}))},onContextMenu:g=>r&&g.preventDefault(),onDoubleClick:g=>{r&&(g.preventDefault(),g.stopPropagation())}},`${e.deviceId}:monitor:${me}`),Me&&i.jsx("span",{className:"remote-pointer-feedback","data-input-seq":x.inputSeq,"data-native-input-backend":x.nativeInputBackend,style:je,"aria-hidden":"true",children:i.jsx(Cs,{size:22,strokeWidth:2.2})})]}),!H&&i.jsx("span",{className:"empty-screen",children:i.jsx(Ra,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:Qt(e),children:Qt(e)}),Se&&i.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Preparing video"})]}),R&&i.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[i.jsx(wo,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"Screen Recording permission required"}),i.jsx("small",{children:"Allow the terminal app on this Mac, then restart VuvoDesk."})]}),B&&i.jsxs("span",{className:`wall-update-status state-${B.state}`,role:"status","aria-live":"polite",title:B.error||B.label,children:[B.state==="updated"?i.jsx(Cn,{size:20,"aria-hidden":"true"}):B.state==="failed"?i.jsx(Ma,{size:22,"aria-hidden":"true"}):B.state==="offline"?i.jsx(eg,{size:22,"aria-hidden":"true"}):i.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),i.jsx("strong",{children:B.label}),B.error?i.jsx("small",{children:B.error}):null]}),c&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`tile-health-pill state-${te.state}`,children:te.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${Qt(e)} status`,children:we.map(g=>i.jsxs("span",{className:`tile-metric state-${g.state}`,children:[i.jsx("b",{children:g.label}),i.jsx("em",{children:g.value}),g.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(g.ratio*100)}%`}})]},g.id))})]}),ne&&i.jsx(Jg,{items:ne,mode:re}),Fe&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${Qt(e)} display ${me+1} of ${h}`,onPointerDown:g=>g.stopPropagation(),onClick:g=>g.stopPropagation(),onDoubleClick:g=>g.stopPropagation(),children:[i.jsx("button",{className:"monitor-cycle-button previous",onClick:g=>{g.preventDefault(),g.stopPropagation(),b(-1),g.currentTarget.blur()},title:"Previous display",type:"button",children:i.jsx(tg,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",me+1,"/",h]}),i.jsx("button",{className:"monitor-cycle-button next",onClick:g=>{g.preventDefault(),g.stopPropagation(),b(1),g.currentTarget.blur()},title:"Next display",type:"button",children:i.jsx(ng,{size:18})})]})]})})}function WM({visible:e}){const t=kk;return s.useEffect(()=>{},[t]),null}function mx({runtimeBaseUrl:e=""}){const t=typeof window<"u"&&!!window.liveDesk,a=t,{session:r,sessionHydrationRevision:c,loading:u,hubSessionRevoking:p,hubSessionBlocked:h,hubSessionRevocationError:f,revokeHubSession:k}=KS(),{workspaces:M,activeWorkspace:b,loading:T,error:A,inviteNotice:x,refresh:E,selectWorkspace:B,isWorkspaceActionCurrent:q}=$0(r,c),G=b?.id||"",ne=b?.membershipRevision||0,re=b?.kind==="team"&&b.role==="operator",O=b?`${r?.user.id||""}:${b.id}:${b.role}`:"",ie=s.useRef(O);ie.current=O,ny(r&&b&&!h&&!p?{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:r.expires_at,user:{id:r.user.id,email:r.user.email},workspaceId:b.id,workspaceKind:b.kind,workspaceRole:b.role,membershipRevision:b.membershipRevision}:null);const{target:J,error:de,refresh:se}=QS(r,G,ne),pe=s.useMemo(()=>{if(!J?.active)return null;const n=J.expires_at?Date.parse(J.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(n)&&n<=Date.now()?null:J},[J]),ce=s.useMemo(()=>Xp(pe),[pe]),W=yi(),ee=e.trim().replace(/\/+$/,""),L=s.useMemo(()=>[...new Set((W?ce:[ee,...ce,In]).filter(Boolean))],[W,ce,ee]),[_,K]=s.useState(null),[ue]=s.useState(ik),[P,N]=s.useState(!1),[te,we]=s.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[me,Fe]=s.useState(()=>typeof window<"u"&&Yf(window.matchMedia(qf).matches,te,window.matchMedia("(pointer: coarse)").matches)),H=W&&me;s.useEffect(()=>{if(!W){K(null);return}const n=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),o=()=>we(n.matches||!!window.navigator.standalone),l=d=>{d.preventDefault(),K(d)},m=()=>{K(null),we(!0)};return o(),n.addEventListener("change",o),window.addEventListener("beforeinstallprompt",l),window.addEventListener("appinstalled",m),()=>{n.removeEventListener("change",o),window.removeEventListener("beforeinstallprompt",l),window.removeEventListener("appinstalled",m)}},[W]);const R=s.useCallback(async()=>{const n=_;if(!n){ue.isIos&&N(!0);return}K(null);try{await n.prompt(),(await n.userChoice).outcome==="accepted"&&we(!0)}catch(o){K(n),console.warn("[VuvoDesk] PWA install prompt failed.",o)}},[ue.isIos,_]);s.useEffect(()=>{const n=window.matchMedia(qf),o=window.matchMedia("(pointer: coarse)"),l=()=>Fe(Yf(n.matches,te,o.matches));return l(),n.addEventListener("change",l),o.addEventListener("change",l),()=>{n.removeEventListener("change",l),o.removeEventListener("change",l)}},[te]),s.useLayoutEffect(()=>{const n=document.documentElement,o=()=>{n.classList.remove("livedesk-mobile-console-active"),n.style.removeProperty("--livedesk-mobile-viewport-height"),n.style.removeProperty("--livedesk-mobile-viewport-top"),n.style.removeProperty("--livedesk-mobile-viewport-width"),n.style.removeProperty("--livedesk-mobile-viewport-left"),n.style.removeProperty("--livedesk-mobile-ios-top-guard")};if(!me){o();return}n.classList.add("livedesk-mobile-console-active");const l=window.visualViewport,m=document.createElement("div");m.setAttribute("aria-hidden","true"),m.style.cssText="position:fixed;visibility:hidden;pointer-events:none;padding-top:env(safe-area-inset-top);",document.body.appendChild(m);let d=0;const C=()=>{d=0;const S=Math.max(window.innerHeight,document.documentElement.clientHeight),y=r0(l,S,window.innerWidth,te||ue.isIos,te||ue.isIos||ue.isAndroid),w=Number.parseFloat(window.getComputedStyle(m).paddingTop),Z=n0({isIos:ue.isIos,standalone:te,safeAreaTop:w,screenHeight:window.screen.height,layoutViewportHeight:S});n.style.setProperty("--livedesk-mobile-viewport-height",`${y.height}px`),n.style.setProperty("--livedesk-mobile-viewport-top",`${y.offsetTop}px`),n.style.setProperty("--livedesk-mobile-viewport-width",`${y.width}px`),n.style.setProperty("--livedesk-mobile-viewport-left",`${y.offsetLeft}px`),n.style.setProperty("--livedesk-mobile-ios-top-guard",`${Z}px`)},v=()=>{d||(d=window.requestAnimationFrame(C))};return C(),l?.addEventListener("resize",v),l?.addEventListener("scroll",v),window.addEventListener("resize",v),window.addEventListener("orientationchange",v),window.addEventListener("pageshow",v),()=>{d&&window.cancelAnimationFrame(d),l?.removeEventListener("resize",v),l?.removeEventListener("scroll",v),window.removeEventListener("resize",v),window.removeEventListener("orientationchange",v),window.removeEventListener("pageshow",v),m.remove(),o()}},[ue.isAndroid,ue.isIos,me,te]);const[Se,Ce]=s.useState(cM),Ve=s.useMemo(()=>L.some(n=>!!fl(n)),[L]),qe=!!(r&&b&&!h&&!p&&!f),Oe=hC({workspaceReady:qe,desktopShell:t,publicConsole:W,authenticated:!!r,managerNeedsLocalAccess:Ve,localHubAccessEnabled:Se}),{status:z,devices:Me,error:je,connectionState:Ge,failure:kt,refresh:Te,retry:Be,hubBaseUrl:Y}=YS(L,Oe,r?.access_token||"",O,G,b?.kind||""),ve=s.useRef(null),st=s.useRef(0),[it,bt]=s.useState(0),Mt=s.useCallback(n=>{const o=l=>{ve.current===n&&n.record({type:"hub.request.failed",component:"pwa-diagnostic-control",state:"failed",reason:l instanceof Error?l.message:String(l),details:{transport:"authenticated-hub-http"}})};n.flushWithOneFollowUp(o)},[]),ae=s.useCallback(n=>{const o=ve.current;if(!o)return!1;let l=!1;for(const m of n)l=o.record(m).accepted||l;return l&&Mt(o),l},[Mt]),$=s.useCallback(n=>ae([n]),[ae]);s.useEffect(()=>{const n=String(r?.user?.id||"").trim(),o=String(Y||"").trim();if(t||!qe||!n||!o){ve.current=null;return}const l=st.current+1;st.current=l;let m=!1,d=null;return mr(async()=>{const{createPwaRuntimeDiagnosticLane:C}=await import("./pwa-runtime-diagnostic-lane-CXJ3zl5c.js");return{createPwaRuntimeDiagnosticLane:C}},[]).then(({createPwaRuntimeDiagnosticLane:C})=>{m||l!==st.current||(d=C({owner:{clientId:n,sessionId:"unknown"},sendBatch:(v,{signal:S})=>ze("/api/remote/pwa-diagnostics",{method:"POST",signal:S,timeoutMs:15e3,body:JSON.stringify(v)},o)}),ve.current=d,d.record({type:"client.started",component:"pwa-runtime",state:"active",reason:"diagnostic-owner-created",details:{ownerGeneration:l,workspaceId:G||"unknown",workspaceRole:b?.role||"unknown",managerHubUrl:o}}),d.record({type:"visibility.changed",component:"document",state:document.visibilityState==="visible"?"visible":"hidden",reason:"initial-current-visibility",details:{source:"current-document-state"}}),Mt(d),bt(v=>v+1))}).catch(()=>{m||console.warn("[VuvoDesk] PWA lifecycle diagnostics are unavailable.")}),()=>{m=!0,ve.current===d&&(ve.current=null),d?.dispose()}},[b?.role,G,t,Mt,Y,r?.user?.id,O,qe]),s.useEffect(()=>{if(!ve.current)return;const n=Jp();ae([{type:"session.changed",component:"authenticated-workspace",state:qe?"ready":"unknown",reason:`workspace:${G||"unknown"}:revision:${ne}:role:${b?.role||"unknown"}`,details:{clientId:r?.user?.id||"unknown",workspaceId:G||"unknown",workspaceRevision:ne,workspaceRole:b?.role||"unknown"}},{type:"session.changed",component:"hub-manager",state:String(Ge||(z?.started?"ready":"unknown")),reason:je?`error:${je}:manager:${z?.deviceId||"unknown"}`:`manager:${z?.deviceId||"unknown"}:version:${z?.managerVersion||"unknown"}:role:${z?.runtimeRole||"unknown"}`,details:{managerHubUrl:Y||"unknown",managerDeviceId:z?.deviceId||"unknown",managerPackage:z?.managerPackage||"unknown",managerVersion:z?.managerVersion||"unknown",runtimeRole:z?.runtimeRole||"unknown",hubError:je||"unknown",directStage:n.stage||"unknown",directReady:n.directReady===!0}}])},[b?.role,G,ne,Ge,je,Y,it,ae,r?.user?.id,z?.deviceId,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started,qe]);const ye=s.useCallback(()=>E(),[E]),V=V0(r,b,Y,ye,q),[Ke,St]=s.useState(!1);s.useEffect(()=>{if(!z?.started){St(!1);return}const n=new AbortController;return ze("/api/remote/wall-preferences",{signal:n.signal},Y).then(o=>{St(o.wallPreferences?.showThisComputer===!0)}).catch(o=>{n.signal.aborted||(St(!1),console.warn("[VuvoDesk] Computer visibility setting could not be loaded.",o))}),()=>n.abort()},[Y,z?.started]);const{entitlement:I,licensed:oe,loading:Pe,error:He,refresh:vt}=XS(r,G,ne,b?.plan,b?.entitlementStatus,ye),[Ze,At]=s.useState([]),[_t,Jt]=s.useState(""),[xt,Vt]=s.useState(""),[g,U]=s.useState(""),[F,he]=s.useState(""),[Q,Ie]=s.useState(""),[be,Ye]=s.useState("idle"),ut=s.useRef("idle"),xe=s.useCallback(n=>{const o=typeof n=="function"?n(ut.current):n;ut.current=o,Ye(o)},[]),[Qe,_e]=s.useState(!1),[Wt,lt]=s.useState(""),[ct,ht]=s.useState(null),rt=s.useRef(null),[Pt,zt]=s.useState(""),xi=s.useRef("");xi.current=F;const[kn,jn]=s.useState(!1);s.useLayoutEffect(()=>{St(!1),At([]),Jt(""),Vt(""),U(""),he(""),xe("idle"),_e(!1),ht(null),jn(!1)},[O]);const[Ri,Fs]=s.useState([]),Dl=s.useRef(null),Ai=s.useRef(null),tm=s.useRef(null),Ds=s.useRef(!1),nm=s.useRef({key:"",source:"",at:0}),[rm,am]=s.useState(!1),[Zt,Fr]=s.useState(!1),Na=s.useRef(""),dt=s.useRef(new Map),Ro=s.useRef(0),Ls=s.useRef(!1),Os=s.useRef(""),om=s.useRef(O),Ll=s.useRef(O);Ll.current=O;const _s=s.useRef(null);_s.current||(_s.current=m0());const Ol=s.useRef(document.visibilityState==="visible"),[na,im]=s.useState({}),at=s.useRef({}),Ii=s.useRef(new Set),ra=s.useRef(new Map),Fa=s.useRef(new Map),[Ao,sm]=s.useState({}),Ti=s.useMemo(()=>new Set(Object.keys(na)),[na]),js=s.useCallback((n,o)=>{if(!n)return;const l={...at.current};o?l[n]=o:delete l[n],at.current=l,im(l)},[]),Io=s.useCallback((n,o)=>{n&&sm(l=>{if(!!l[n]===o)return l;const m={...l};return o?m[n]=!0:delete m[n],m})},[]),cm=s.useCallback((n,o)=>{n&&Fa.current.set(n,{paused:o,expiresAt:Date.now()+zk})},[]),[tt,Mn]=s.useState(""),[an,To]=s.useState(""),[Po,_l]=s.useState(!1),lm=s.useRef(null),um=s.useRef(null);s.useEffect(()=>{tt==="auth"&&r?.access_token&&Mn("")},[tt,r?.access_token]);const[jl,dm]=s.useState(""),[Da,Bs]=s.useState(null),tr=s.useRef(null),wb=s.useRef(0),Hs=s.useRef(0),Ws=s.useCallback((n,o,l)=>{const m=String(n||"").trim();if(dm(m),tr.current!==null&&(window.clearTimeout(tr.current),tr.current=null),!m)return Hs.current=0,Bs(null),0;const d=++wb.current;if(Hs.current=d,Bs({id:d,message:m,tone:o}),!l)return d;const C=window.setTimeout(()=>{Bs(v=>v?.id===d?null:v),tr.current===C&&(tr.current=null)},5e3);return tr.current=C,d},[]),j=s.useCallback((n,o="info")=>Ws(n,o,!0),[Ws]);s.useEffect(()=>{A&&j(A,"error")},[j,A]),s.useEffect(()=>{x&&j(x,/joined/i.test(x)?"success":"error")},[x,j]),s.useEffect(()=>{V.error&&j(V.error,"error")},[j,V.error]),s.useEffect(()=>{f&&j("Hub sign-out could not be confirmed. Wall and Control remain blocked; open Account and retry when the Hub is reachable.","error")},[f,j]);const mm=s.useCallback((n,o)=>{const l=String(o||"").trim();!l||n<=0||Hs.current!==n||(Hs.current=0,tr.current!==null&&(window.clearTimeout(tr.current),tr.current=null),dm(m=>m===l?"":m),Bs(m=>m?.id===n&&m.message===l?null:m))},[]),Bn=s.useCallback(n=>{Ws(n,"progress",!1)},[Ws]);s.useEffect(()=>()=>{tr.current!==null&&window.clearTimeout(tr.current)},[]);const[It,La]=s.useState(()=>typeof window>"u"?"wall":window.location.pathname.startsWith("/support")?"support":new URLSearchParams(window.location.search).get("view")==="pricing"?"pricing":"wall");s.useEffect(()=>{const n=()=>{La(window.location.pathname.startsWith("/support")?"support":o=>o==="support"?"wall":o)};return window.addEventListener("popstate",n),()=>window.removeEventListener("popstate",n)},[]);const[Eo,pm]=s.useState(kM),[Oa,fm]=s.useState(yM),_a=s.useRef(Eo),aa=s.useRef(Oa);_a.current=Eo,aa.current=Oa;const Hn=Ms(Oa),[Pn,No]=s.useState(Hn),Bl=s.useRef(null);Bl.current||(Bl.current=u0(O));const En=Bl.current;En.switchOwner(O);const Dr=s.useRef(null),Wn=s.useRef(null);s.useLayoutEffect(()=>{Wn.current!==null&&(window.clearTimeout(Wn.current),Wn.current=null),Dr.current=null,aa.current="fast",_a.current=ea,fm("fast"),No(Ms("fast")),pm(ea)},[O]);const oa=s.useCallback(n=>{const o=Qg(n,{cadence:aa.current,viewScale:_a.current});return aa.current!==o.cadence&&(aa.current=o.cadence,fm(o.cadence),No(Ms(o.cadence)),wM(o.cadence)),_a.current!==o.viewScale&&(_a.current=o.viewScale,pm(o.viewScale),MM(o.viewScale)),o},[]);s.useEffect(()=>{const n=z?.wallPreferences;if(!n)return;const o=Math.max(0,Number(n.revision)||0);if(!En.acceptSnapshot(O,o))return;const l=Dr.current;l&&(l.cadence!==n.cadence||l.viewScale!==Mi(n.viewScale))||(l&&(Dr.current=null),oa(n))},[oa,z?.wallPreferences,En,O]);const $s=s.useCallback(async(n,o)=>{const l=()=>En.ownsWrite(o)&&ie.current===O;if(!l())return;let m=!1;const d=S=>m||!i0({error:S,publicConsole:yi(),workspaceKind:b?.kind,workspaceRole:b?.role,workspaceId:G,userId:r?.user.id})?!1:(m=!0,!0);let C=En.readRevision(O);if(C===void 0)try{for(;;)try{const S=await ze(od(m),void 0,Y);if(!l()||(C=Math.max(0,Number(S.revision)||0),!En.commitWriteRevision(o,C)))return;break}catch(S){if(!l())return;if(d(S))continue;throw S}}catch{if(!l())return;Dr.current=null,Te(),j("Wall view changed here, but Hub synchronization failed.","error");return}let v=!1;for(let S=0;S<3;S+=1)try{const y=await ze(od(m),{method:"PATCH",body:JSON.stringify(s0({legacy:m,revision:C,preferences:n}))},Y);if(!l()||!En.commitWriteRevision(o,y.revision))return;const w=c0(y,m);if(!o0(w,n)){Dr.current=null,Te(),j("Update the Hub to synchronize Wall controls.","error");return}Dr.current=null,oa(w),Te();return}catch(y){if(!l())return;if(d(y))continue;if(/^409\s/.test(y instanceof Error?y.message:String(y))&&!v)try{const Z=await ze(od(m),void 0,Y);if(!l()||(C=Math.max(0,Number(Z.revision)||0),!En.commitWriteRevision(o,C)))return;v=!0;continue}catch{}Dr.current=null,Te(),j("Wall view changed here, but Hub synchronization failed.","error");return}},[b?.kind,b?.role,G,oa,Y,Te,r?.user.id,j,En,O]),Vs=s.useCallback((n,o)=>{Wn.current!==null&&(window.clearTimeout(Wn.current),Wn.current=null);const l=oa({cadence:n,viewScale:o}),m=En.beginWrite(O);m&&(Dr.current=l,$s(l,m))},[oa,$s,En,O]),Sb=s.useCallback(n=>{const o=oa({cadence:aa.current,viewScale:Mi(n)}),l=En.beginWrite(O);return l&&(Dr.current=o,Wn.current!==null&&window.clearTimeout(Wn.current),Wn.current=window.setTimeout(()=>{Wn.current=null,$s({cadence:aa.current,viewScale:_a.current},l)},250)),o},[oa,$s,En,O]);s.useEffect(()=>()=>{Wn.current!==null&&window.clearTimeout(Wn.current)},[]);const Bt=E0(Eo),hm=a0(Eo),gm=s.useCallback(n=>{Vs(aa.current,n==="list"?Al:n==="medium"?I0:ea)},[Vs]),bm=s.useCallback(n=>{Vs(n,_a.current)},[Vs]),[Cb,vm]=s.useState(!1);s.useEffect(()=>{if(vm(!1),Bt!=="list")return;const n=window.setTimeout(()=>{vm(!0)},Bd);return()=>window.clearTimeout(n)},[Bt]);const Pi=l0({wallSize:Bt,elapsedMs:Cb?Bd:0});s.useLayoutEffect(()=>{!re||It==="wall"||It==="control"||It==="doc"||It==="support"||(La("wall"),jn(!1))},[It,re]);const Hl=N0(Eo),ym=s.useMemo(()=>({"--wall-tile-min-width":`${Hl}px`}),[Hl]),kb=Bt==="list"?"List view":`${Bt==="medium"?"Small":"Large"} tiles, ${Hl} pixel minimum width`,[Ei,Mb]=s.useState(SM),[fn,zs]=s.useState(!1),[Ut,Us]=s.useState(!1),[pr,qs]=s.useState(!1),[Ni,xb]=s.useState(null),[$n,Fo]=s.useState(null),[Do,Lo]=s.useState(!1),[Rb,Gs]=s.useState(Date.now),Lr=s.useRef(null),wm=s.useRef(null),Wl=s.useRef(null),ia=s.useRef(0);s.useEffect(()=>()=>{ia.current+=1,Lr.current!==null&&window.clearTimeout(Lr.current)},[]);const[ja,Ab]=s.useState(OM),[Ba,Sm]=s.useState(!1),[sa,Or]=s.useState(!1),Ks=s.useRef(sa);s.useLayoutEffect(()=>{Ks.current=sa},[sa]);const[$M,VM]=s.useState(!1),[Oo,Cm]=s.useState(sM),[De]=s.useState(hM),km=me?Ei:De.showScreenStatus,[on]=s.useState(bM),[$l]=s.useState(pM),[gt,Vl]=s.useState($l.selections),Mm=s.useRef({...$l.topologyFingerprints}),Fi=s.useRef({}),xm=s.useRef({...$l.selections}),[et,fr]=s.useState(null),[Ys,zl]=s.useState({}),Ul=s.useRef(new Set),[ql,Qs]=s.useState([]),[Di,Ib]=s.useState(""),[Tb,Pb]=s.useState(0),[Eb,Rm]=s.useState(0),[Nb,Fb]=s.useState(0),[Gl,Li]=s.useState(()=>new Set),mt=s.useRef(new Map),hn=s.useRef(new Map),_r=s.useRef(new Map),Et=s.useRef(new Map),Ha=s.useRef(null),Wa=s.useRef(new Map),jr=s.useRef(new Set),ca=s.useRef(new Map),_o=s.useRef(new Map),$a=s.useRef(new Map),Vn=s.useRef(new Map),Xs=s.useRef(new WeakMap),Js=s.useRef(new WeakMap),la=s.useRef(""),xn=s.useRef(null),Am=s.useRef(Promise.resolve()),Zs=s.useRef(0),jo=s.useRef(null),Nn=s.useRef(null),Oi=s.useRef(""),en=s.useRef(new Map),Bo=s.useRef(null),_i=s.useRef(0),ua=s.useRef(new Map),ec=s.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),tc=s.useRef(new Map),Kl=s.useRef([]),Im=s.useRef(0),[nc,Yl]=s.useState({}),Va=s.useRef(new Map),[rc,ac]=s.useState({}),oc=s.useRef(null),[Ql,gn]=s.useState(!1),ic=s.useRef(null),Db=s.useRef(0),Br=s.useRef(null),Tm=s.useRef(new Map),nr=s.useRef(null),zn=s.useRef(null),yt=s.useRef(null),ji=s.useRef(!1),Pm=s.useRef(0),Ht=s.useRef(0),sn=s.useRef(""),Em=s.useRef(Promise.resolve()),Ho=s.useRef(""),ke=s.useRef(null),Un=s.useRef(""),za=s.useRef(null),Wo=s.useRef(0),Bi=s.useRef(""),Hr=s.useRef(new Map),hr=s.useRef(new Map),sc=s.useRef(performance.now()),da=s.useRef(new Map),Fn=s.useRef(new Map),ma=s.useRef(new Map),Wr=s.useRef(new Map),$r=s.useRef(new Map),gr=s.useRef(new Map),qn=s.useRef(document.visibilityState==="visible"),rr=s.useRef(1),Xl=s.useRef([]),[qt,Lb]=s.useState(document.visibilityState==="visible"),[Ob,_b]=s.useState(0),Hi=s.useRef(0),cc=s.useRef(0),lc=s.useRef(0),uc=s.useRef(0),Jl=s.useRef(0),Zl=s.useRef(new Map),Wi=s.useRef([]),Nm=s.useRef(new Map),Fm=s.useRef(new Map),Nt=s.useRef(new Map),Vr=s.useRef(new Map),$i=s.useRef(new Map),eu=s.useRef({}),dc=s.useRef(new Set),Ft=s.useCallback((n,o,l,m,d)=>{const C=ft(n,o),v=performance.now(),S=Hr.current.get(C)||0,y=hr.current.get(C)||0,w=n==="control"?ke.current:null,Z=w?.deviceId===o?er({...w,streamPurpose:"control"}):Vn.current.get(o)||"",ge={scope:n,deviceId:o,stage:l,reason:m,at:Date.now(),attempts:Math.max(0,Math.floor(Number(d)||0)),receiveAgeMs:S>0?Math.max(0,v-S):-1,paintAgeMs:y>0?Math.max(0,v-y):-1,bindingKey:Z};$i.current.set(C,ge),console.info("[VuvoDesk frame recovery]",ge);const D=ve.current;if(!D)return;const fe={type:"frame.recovery.changed",component:`frame-recovery:${n}:${o}`,state:l,reason:m,details:{scope:n,deviceId:o,attempts:ge.attempts,receiveAgeMs:ge.receiveAgeMs>=0?ge.receiveAgeMs:"unknown",paintAgeMs:ge.paintAgeMs>=0?ge.paintAgeMs:"unknown",bindingKey:Z||"unknown"}};if(l==="stable"){queueMicrotask(()=>{ve.current===D&&D.record(fe).accepted&&Mt(D)});return}$(fe)},[Mt,$]),$o=s.useCallback(n=>Zw(Xs.current,n),[]),Vo=s.useCallback(n=>qd(Js.current,n),[]),Ua=s.useCallback((n,o)=>wf(Js.current,n,o),[]),$t=s.useCallback(n=>{const o=yf(Xs.current,n);return yf(Js.current,n),o},[]),zo=s.useCallback((n,o)=>wf(Xs.current,n,o),[]),Dm=s.useCallback(n=>Nn.current===n||Ha.current===n?!0:[mt.current,hn.current,_r.current,Et.current,en.current].some(l=>Array.from(l.values()).some(m=>m===n)),[]),bn=s.useCallback(n=>{n&&($t(n),dc.current.add(n),nS(n,{isCurrent:Dm,dispose:pi,schedule:o=>queueMicrotask(()=>{try{o()}finally{dc.current.delete(n)}})}))},[Dm,$t]),vn=s.useCallback(n=>($t(n),Nl(n,pi)),[$t]),Lm=s.useCallback(()=>{const n=Nn.current,o=Ha.current,l=[...dc.current];Nn.current=null,Ha.current=null,dc.current.clear(),Xs.current=new WeakMap,Js.current=new WeakMap,Vn.current.clear(),Oi.current="",tS([mt.current,hn.current,_r.current,Et.current,en.current],[n,o,...l],pi),Bo.current=null,_i.current=0,Wa.current.clear(),jr.current.clear(),ca.current.clear(),_o.current.clear(),$a.current.clear(),ua.current.clear(),tc.current.clear(),Kl.current.length=0,Va.current.clear(),Hr.current.clear(),hr.current.clear(),da.current.clear(),Fn.current.clear(),ma.current.clear(),Wr.current.clear(),$r.current.clear(),gr.current.clear(),Nt.current.clear(),Vr.current.clear(),$i.current.clear(),Ii.current.clear()},[]);s.useEffect(()=>()=>{Lm()},[Lm]);const zr=s.useCallback((n,o,l={})=>{const m=ft(n,o);Hr.current.delete(m),hr.current.delete(m),da.current.delete(m),Fn.current.delete(m),gr.current.delete(m),Nt.current.delete(m),Vr.current.delete(m),l.preserveLatestDiagnostic!==!0&&$i.current.delete(m),Va.current.delete(m),ua.current.delete(m),ma.current.delete(m),Wr.current.delete(m),$r.current.delete(m),ac(d=>{if(!Object.prototype.hasOwnProperty.call(d,m))return d;const C={...d};return delete C[m],C}),Yl(d=>{if(!Object.prototype.hasOwnProperty.call(d,m))return d;const C={...d};return delete C[m],C})},[]),Dt=s.useCallback((n,o,l={})=>{const m=ft(n,o),d=performance.now();zr(n,o,l),n==="control"?Wr.current.set(m,d):$r.current.set(m,d)},[zr]),[qa,pa]=s.useState(null),[jb,tu]=s.useState(!1),[zM,Bb]=s.useState([]),[Uo,Hb]=s.useState("all"),[qo,nu]=s.useState([]),[UM,qM]=s.useState(!1),[GM,Wb]=s.useState(!0),Om=s.useRef(null),_m=s.useRef(null),$b=s.useRef(null),Vb=s.useRef(null),zb=s.useRef(!1),ru=s.useRef(!1),Vi=s.useRef(0),br=s.useRef(0),vr=s.useRef(0),ar=s.useRef(0),zi=s.useRef(0),Ui=s.useRef(""),au=s.useRef({}),qi=It==="settings"&&!re,jm=!re&&It==="pricing",Bm=It==="doc",Hm=It==="support",Ga=!re&&It==="share-files",mc=!re&&It==="agents",Ur=!qi&&!jm&&!Bm&&!Hm&&!Ga&&!mc,Re=It==="control",Wm=g0(It),or=qt&&It==="wall"&&!Pi,$m=s.useRef(or);$m.current=or;const Ub=!H&&Wm&&Wi.current.length>0,yr=qt&&(It==="wall"&&!Pi||!H&&Re||Ub),Go=s.useRef(yr);Go.current=yr;const pc=qt&&(Re||or),Ko=qt&&(pc||Wm&&(be==="connecting"||be==="active")),ou=s.useRef({active:yr,epoch:rr.current});ou.current.active!==yr&&(rr.current+=1,ou.current={active:yr,epoch:rr.current}),s.useEffect(()=>{Ur||(zs(!1),Us(!1),qs(!1))},[Ur]);const nt=De.frameMode==="mode4-h264-atlas",Gn=Q||on.frameMode,qb=Gn!=="mode3-h264-hw"?Math.min(30,on.fps):on.fps,Gi=ZC(qb,H),Yo=Me.find(n=>n.deviceId===xt),Gb=Yo?.platform,Kb=Yo?_n(Yo,gt[Yo.deviceId]):0,fc=Yo?em(Yo,Kb):null,Vm=HM(Gb)?{maxWidth:1280,maxHeight:720}:Rh,zm=Gn!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Rh,hc={maxWidth:Math.min(zm.maxWidth,Vm.maxWidth,on.maxWidth),maxHeight:Math.min(zm.maxHeight,Vm.maxHeight,on.maxHeight)},wr={maxWidth:fc?.width?Math.min(hc.maxWidth,fc.width):hc.maxWidth,maxHeight:fc?.height?Math.min(hc.maxHeight,fc.height):hc.maxHeight};s.useEffect(()=>{if(b?.kind!=="team"&&z?.started){if(!r?.access_token){ze("/api/remote/license",{method:"DELETE"},Y).catch(()=>{});return}ze("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${r.access_token}`},body:JSON.stringify({workspaceId:G})},Y).catch(n=>{console.warn("[VuvoDesk] Hub license sync failed",n)})}},[b?.entitlementStatus,b?.kind,G,ne,Y,r?.access_token,z?.started]),s.useEffect(()=>{!r?.access_token||b?.kind!=="personal"||b.role!=="owner"||!z?.started||z.runtimeRole!=="hub"||!z.deviceId||(async()=>{try{const{data:n,error:o}=await Ct.rpc("register_livedesk_device",{p_device_id:z.deviceId,p_device_name:z.deviceName||z.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:z.managerVersion||z.managerPackage||""}),l=Array.isArray(n)?n[0]:n;(o||l?.ok===!1)&&console.warn("[VuvoDesk] Hub device role registration failed",o||l?.reason||"unknown-error")}catch(n){console.warn("[VuvoDesk] Hub device role registration failed",n)}})()},[b?.kind,b?.role,r?.access_token,z?.deviceId,z?.deviceName,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started]);const qr=z?.runtimeRole==="hub"?String(z.deviceId||"").trim():"",Le=s.useMemo(()=>Me.filter(n=>n.connected&&(me||Ke||!qr||n.deviceId!==qr)),[Me,qr,me,Ke]),Ka=s.useMemo(()=>Le.filter(n=>!qr||n.deviceId!==qr),[Le,qr]);s.useEffect(()=>{const n={...at.current},o=Date.now();let l=!1;sm(m=>{const d={...m};let C=!1;for(const v of Me){const S=String(v.liveCapturePause?.token||"").trim(),y=Fa.current.get(v.deviceId);if(y)if((y.paused?!!S:!S)||y.expiresAt<=o)Fa.current.delete(v.deviceId);else continue;const w=!!S&&(v.liveCapturePause?.captureStopConfirmed!==!0||v.liveCapturePause?.phase==="stop-unconfirmed");!!d[v.deviceId]!==w&&(C=!0,w?d[v.deviceId]=!0:delete d[v.deviceId])}return C?d:m});for(const m of Me){const d=String(m.liveCapturePause?.token||"").trim(),C=String(n[m.deviceId]||""),v=Fa.current.get(m.deviceId);if(v)if((v.paused?!!d:!d)||v.expiresAt<=o)Fa.current.delete(m.deviceId);else continue;d&&d!==C?(n[m.deviceId]=d,l=!0):!d&&C&&(delete n[m.deviceId],ra.current.delete(m.deviceId),l=!0)}l&&(at.current=n,im(n))},[Me]);const Um=Uo==="all"?Le.length:qo.filter(n=>Le.some(o=>o.deviceId===n)).length,Yb=s.useMemo(()=>Le.reduce((n,o)=>Math.max(n,$h(o.slotNumber)),0),[Le]),gc=Math.max(fk,Le.length,Yb),fa=s.useMemo(()=>{const n=Array(gc).fill(null),o=[];for(const l of Le){const m=$h(l.slotNumber);m>0&&m<=gc&&!n[m-1]?n[m-1]=l:o.push(l)}for(const l of o){const m=n.findIndex(d=>!d);m<0?n.push(l):n[m]=l}return n},[Le,gc]),qm=s.useMemo(()=>me?fa.filter(n=>!!n):fa,[me,fa]),Gm=s.useMemo(()=>fa.flatMap((n,o)=>n?[{device:n,slotNumber:o+1}]:[]),[fa]),bc=s.useMemo(()=>Le.map(n=>n.deviceId),[Le]),Ya=s.useMemo(()=>new Set(Ze),[Ze]),cn=s.useMemo(()=>Le.filter(n=>Ya.has(n.deviceId)),[Le,Ya]),ha=s.useMemo(()=>Me.find(n=>n.deviceId===_t)||cn[0]||null,[Me,_t,cn]),tn=s.useMemo(()=>Me.find(n=>n.deviceId===xt)||null,[xt,Me]),ir=tn?_n(tn,gt[tn.deviceId]):0,X=Re?tn:ha,Km=s.useMemo(()=>new Set(qo),[qo]),Qb=s.useMemo(()=>Uo==="all"?Le.map(n=>n.deviceId):Le.filter(n=>Km.has(n.deviceId)).map(n=>n.deviceId),[Le,Km,Uo]),Xb=X?vi(X,"control"):!1,iu=Nr(X?.platform)&&(X?.capabilities?.controlPermission===!1||X?.capabilities?.accessibilityPermission===!1),sr=X?vi(X,"audio")||vi(X,"remoteAudio"):!1,Qo=(Array.isArray(X?.capabilities?.agentTools)?X.capabilities.agentTools.map(String):[]).includes("system.power"),su=b?.entitlementStatus==="active"&&b.plan!=="free"?b.plan:oe?I?.plan:null,Xe=su==="team"?"team":su==="pro"?"pro":su==="ltd"?"ltd":"free",Ym=$e[Xe],vc=b?.deviceLimit??Ym.limit,Sr=s.useMemo(()=>{const n=new Set(w0(Ka,vc));return qr&&n.add(qr),n},[vc,qr,Ka]),pt=!X||Sr.has(X.deviceId),Xo=Xe==="ltd"?`Plus includes up to ${us} Clients. Upgrade to Pro for schools, academies, commercial use, and larger walls.`:Xe==="pro"?`Pro includes up to ${Ou} Clients for schools, academies, and commercial use.`:Xe==="team"?"Team includes every connected Client in this shared commercial workspace.":`Free includes up to ${_u} Clients. Upgrade to Plus for ${us} devices and no ads.`,Jb=Xe==="free",Cr=pt&&!!X&&Xb,Qm=pt&&!!X&&sr,Ki=s.useMemo(()=>Re?X?[X]:[]:cn.length>0?cn:X?[X]:[],[X,cn,Re]),Dn=s.useMemo(()=>Ki.filter(n=>Sr.has(n.deviceId)),[Sr,Ki]),yc=Dn.some(n=>String(na[n.deviceId]||"").startsWith("pending:")||Ao[n.deviceId]===!0),Yi=!(Dn.length>0&&Dn.every(n=>{const o=String(na[n.deviceId]||"");return!!o&&!o.startsWith("pending:")&&Ao[n.deviceId]!==!0}))||yc,wc=s.useMemo(()=>fa.filter(n=>!!n?.connected).slice(0,xM(Bt)).map(n=>n.deviceId),[fa,Bt]),Sc=s.useMemo(()=>yr?or?nt||Bt==="list"?bc:De.visibleOnlyLive?ql.length>0?ql:wc:bc:Wi.current.length>0?Wi.current:bc:[],[wc,nt,ql,De.visibleOnlyLive,bc,yr,or,Bt]),Kn=s.useMemo(()=>{const n=gd(Sc.filter(o=>Sr.has(o)));return JC(n,H,ha?.deviceId||"")},[H,Sr,Sc,ha?.deviceId]);Wi.current=Kn;const kr=s.useMemo(()=>Kn.filter(n=>n!==Di&&!Ti.has(n)),[Ti,Kn,Di]),Cc=s.useMemo(()=>new Map(Le.map(n=>[n.deviceId,n.platform])),[Le]),yn=s.useMemo(()=>{const n=Object.fromEntries(Le.map(o=>[o.deviceId,String(o.sessionId||"").trim()]));return h0(eu.current,n)},[Le]);s.useLayoutEffect(()=>{eu.current=yn},[yn]);const Zb=Xf(au.current,yn)?Hn:Pn;s.useLayoutEffect(()=>{const n=au.current,o=Xf(n,yn);au.current={...yn};const l=new Set([...Object.keys(n),...Object.keys(yn)]),m=ve.current?[]:null;for(const d of l){const C=String(n[d]||"").trim(),v=String(yn[d]||"").trim();C!==v&&(console.info("[VuvoDesk frame session]",{deviceId:d,previousSessionId:C,currentSessionId:v,action:v?"fresh-recovery-owner":"owner-released"}),m?.push({type:"session.changed",component:`remote-device:${d}`,state:v?"connected":"disconnected",reason:`session:${v||C||"unknown"}`,details:{deviceId:d,previousSessionId:C||"unknown",currentSessionId:v||"unknown",action:v?"fresh-recovery-owner":"owner-released"}}),v?(Dt("wall",d),Dt("control",d)):(zr("wall",d),zr("control",d)))}m&&m.length>0&&ae(m),o&&(No(Hn),Vi.current=Date.now(),br.current=0,vr.current=0,ar.current=0,zi.current=0,Ui.current="")},[zr,yn,ae,Dt,Hn]),s.useEffect(()=>{if(!ve.current)return;const n=Object.entries(yn).filter(([,o])=>!!o).map(([o,l])=>({type:"session.changed",component:`remote-device:${o}`,state:"connected",reason:`session:${l}`,details:{deviceId:o,currentSessionId:l,action:"current-connected-owner"}}));n.length>0&&ae(n)},[yn,it,ae]);const Mr=S0(nt,Kn.length),nn=s.useMemo(()=>nt?kr.filter(n=>fs({mode4Enabled:nt,directMode4WallEnabled:Mr,isMac:Nr(Cc.get(n))})==="atlas"):[],[Mr,nt,Cc,kr]),Gt=s.useMemo(()=>kr.filter(n=>fs({mode4Enabled:nt,directMode4WallEnabled:Mr,isMac:Nr(Cc.get(n))})==="direct"),[Mr,nt,Cc,kr]),Xm=s.useMemo(()=>{const n=De.autoStartLive?kr.map(o=>ft("wall",o)):[];return Ko&&pt&&g&&Sr.has(g)&&(be==="connecting"||be==="active"||be==="warm")&&n.push(ft("control",g)),[...new Set(n)].sort()},[Ko,g,be,pt,Sr,De.autoStartLive,kr]);s.useEffect(()=>{const n=new Set(Kn);Li(o=>{let l=!1;const m=new Set;for(const d of o)n.has(d)?m.add(d):l=!0;return l?m:o})},[Kn]);const ev=s.useMemo(()=>{const n=d=>Le.find(C=>C.deviceId===d)||null,o=d=>{const C=n(d);return C?_n(C,gt[d]):0},l=(d,C=o(d))=>d===g&&(be==="connecting"||be==="active"||be==="warm")?Et.current.get(d)||hn.current.get(d)||null:nt?en.current.get(d)||mt.current.get(d)||null:mt.current.get(d)||null,m=(d,C=o(d))=>{const v=n(d);return`${v?Qt(v):d} · Monitor ${C+1}`};return{resolveCurrentTarget(){if(Re&&tn){const y=ir;return{type:"control",deviceIds:[tn.deviceId],monitorIndex:y,label:`${Qt(tn)} · Monitor ${y+1}`,sourceCanvas:l(tn.deviceId,y),signature:`control:${tn.deviceId}:${y}:${on.frameMode}`}}const d=cn.map(y=>y.deviceId).filter(y=>kr.includes(y)),C=ha&&kr.includes(ha.deviceId)?ha.deviceId:"",v=d.length>0?d:C?[C]:kr,S=d.length===0&&!C;if(v.length===0)return null;if(v.length===1){const y=v[0],w=o(y);return{type:S?"wall":d.length>1?"selection":"device",deviceIds:v,monitorIndex:w,label:S?"Wall":m(y,w),sourceCanvas:S?null:l(y,w),signature:`${S?"wall":"device"}:${y}:${w}:${nt?"atlas":"direct"}`}}return{type:d.length>1?"selection":"wall",deviceIds:v,label:d.length>1?`${v.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${d.length>1?"selection":"wall"}:${v.join(",")}:${Bt}`}},getDeviceCanvas:l,composeWall(d,C={}){return U0(d.map(v=>{const S=o(v);return{deviceId:v,label:m(v,S),canvas:l(v,S)}}),C)}}},[Le,tn,g,be,on.frameMode,mt,nt,gt,ir,cn,Re,kr,ha,Bt]),Jm=ok({hubUrl:Y,remoteSettingsEnabled:!!(z?.started&&Y),sourceRegistry:ev,onToast:j}),Gr=s.useMemo(()=>b0({captureOwnershipActive:Ko,localFeatureAccess:pt,controlSessionDeviceId:g,planAllowed:Sr.has(g),sessionState:be,controlFocusVisible:Re,presentationCanvasMounted:Wt===g,wallPresentationVisible:or,wallPresentationCanvasMounted:mt.current.has(g)||en.current.has(g),decoderOwnerExists:Et.current.has(g)})?[g]:[],[Ko,g,be,pt,Wt,Sr,Re,or]),cu=s.useMemo(()=>gd([...Kn,...Gr]),[Gr,Kn]),kc=s.useMemo(()=>jh(De,Bt),[De,Bt]),Jo=s.useMemo(()=>jh(De,"large"),[De]),Mc=C0({mode4Enabled:nt,directMode4WallEnabled:Mr,adaptiveFps:Zb,directDeviceCount:Gt.length,adaptive:De.adaptiveLoadShedding}),ln=e0({fps:Mc,maxWidth:Jo.maxWidth,maxHeight:Jo.maxHeight,quality:De.quality},H,Gt.length),lu=R0({deviceCount:nn.length,targetFps:Pn,adaptive:De.adaptiveLoadShedding});nt&&nn.length>0;const Kr=s.useCallback((n,o,l,m=1)=>{if(n.width<=0||n.height<=0)return!1;if(n===o)return!0;const d=l?Math.min(1,l.maxWidth/n.width,l.maxHeight/n.height):1,C=Math.max(1,Math.round(n.width*d)),v=Math.max(1,Math.round(n.height*d)),S=o.width!==C||o.height!==v;S&&(o.width=C,o.height=v);const y=o.getContext("2d",{alpha:!1});if(!y)return!1;y.imageSmoothingEnabled=!0,y.imageSmoothingQuality="low";const w=y.globalAlpha;y.globalAlpha=S?1:Math.max(.05,Math.min(1,m));try{y.drawImage(n,0,0,n.width,n.height,0,0,o.width,o.height)}finally{y.globalAlpha=w}return!0},[]),xc=s.useCallback((n,o)=>{const l=Math.max(0,Number(o.clientWidth||0)),m=Math.max(0,Number(o.clientHeight||0)),d=Math.max(1,Number(window.devicePixelRatio||1)),C=l>0&&m>0?{maxWidth:Math.ceil(l*d),maxHeight:Math.ceil(m*d)}:void 0;return Kr(n,o,C)},[Kr]),Rc=s.useCallback((n,o,l)=>{const m=Math.max(0,Math.floor(Number(n?.frameSeq||0))),d=o||(n?mt.current.get(n.deviceId):null),C=l||d,v=Math.max(0,Number(C?.width||0))*Math.max(0,Number(C?.height||0)),S=Math.max(mt.current.size,en.current.size);return a&&m>0&&(m+_k(n?.deviceId||""))%mb===0&&S<=Ok&&rw(d)&&v>0&&v<=Lk?Dk:1},[a]),Zo=s.useCallback((n,o,l)=>{if(!ec.current)return;const m=`${n}:${o.deviceId}`,d=tc.current.get(m)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};d.bindingKey=er(o),d.totalPaints+=1,d.lastPaintAt=performance.now(),d.lastFrameSeq=Number(o.frameSeq||0),tc.current.set(m,d);const C=++Im.current,v={sequence:C,scope:n,deviceId:o.deviceId,bindingKey:d.bindingKey,frameSeq:d.lastFrameSeq,paintedAt:d.lastPaintAt,sourceGapMs:Number(o.sourceGapMs||0),agentSendGapMs:Number(o.agentSendGapMs||0),agentSendDurationMs:Number(o.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(o.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(o.agentFrameAgeMs||0),timestampUs:Number(o.timestampUs||0),queuedForMs:Number(l?.queuedForMs||0),decodedForMs:Number(l?.decodedForMs||0),scheduledForMs:Number(l?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(l?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(l?.interactiveBurstTailHoldCount||0)};Kl.current[(C-1)%Gk]=v},[]),xr=s.useCallback(n=>{n&&Li(o=>{if(o.has(n))return o;const l=new Set(o);return l.add(n),l})},[]),Rr=s.useCallback(n=>{n&&Li(o=>{if(!o.has(n))return o;const l=new Set(o);return l.delete(n),l})},[]),Qa=s.useCallback((n,o)=>{if(!o||o.width<=0||o.height<=0)return!1;const l=document.createElement("canvas");if(l.width=o.width,l.height=o.height,!Kr(o,l))return bn(l),!1;const m=_r.current.get(n);return _r.current.set(n,l),m&&m!==l&&vn(m),xr(n),!0},[xr,Kr,vn,bn]),Kt=s.useCallback(n=>{eS(_r.current,n,pi)},[]),Ac=s.useCallback((n,o)=>{const l=_r.current.get(n),m=mt.current.get(n)===o||en.current.get(n)===o;return at.current[n]?(Kt(n),!1):!l||!m||l.width<=0||l.height<=0?!1:Kr(l,o)?!0:(Kt(n),!1)},[Kr,Kt]),Yr=s.useCallback((n,o=!1,l)=>{if(at.current[n]||!jr.current.has(n))return!1;const m=Math.max(1,Math.min(Hn,wt.controlWallReuseMaxFps,Gi)),d=performance.now(),C=_o.current.get(n)||0,v=Et.current.get(n)||hn.current.get(n),S=mt.current.get(n)||en.current.get(n);if(!v||!S||!S.isConnected)return!1;const y=y0({cadenceCredit:ca.current.get(n)||0,targetFps:m,sourceFps:Gi,elapsedSincePaintMs:C>0?d-C:0,nowMs:d,scheduledPaintAtMs:$a.current.get(n)||0,force:o});if(!y.shouldPaint)return ca.current.set(n,y.nextCadenceCredit),!1;const w=Math.max(0,Number(S.clientWidth||0)),Z=Math.max(0,Number(S.clientHeight||0)),ge=Math.max(1,Number(window.devicePixelRatio||1)),D=w>0&&Z>0?{maxWidth:Math.min(kc.maxWidth,Math.ceil(w*ge)),maxHeight:Math.min(kc.maxHeight,Math.ceil(Z*ge))}:kc;return Kr(v,S,D,l?Rc(l,v,S):1)?(ca.current.set(n,y.nextCadenceCredit),y.nextScheduledPaintAtMs>0&&$a.current.set(n,y.nextScheduledPaintAtMs),_o.current.set(n,performance.now()),y.sourceCadencePassthrough&&(ca.current.delete(n),$a.current.delete(n)),l&&Zo("wall-reuse-visible",l),xr(n),Kt(n),!0):!1},[Gi,kc,xr,Kr,Zo,Kt,Rc,Hn]);s.useEffect(()=>{la.current=Di},[Di]);const Ic=s.useCallback((n,o)=>{const l=Br.current;if(!l||l.deviceId!==n)return;const m=Date.now();Tm.current.set(n,{...l,source:o,completedAtEpochMs:m,durationMs:Math.max(0,performance.now()-l.startedAt)}),Br.current=null},[]),Zm=s.useCallback((n,o)=>{const l=mt.current.get(n);if(o&&l&&l!==o&&Qa(n,l),o){if(mt.current.set(n,o),l&&l!==o&&bn(l),at.current[n]){Kt(n),vn(o),Rr(n);return}_r.current.get(n)&&Ac(n,o)&&xr(n),Yr(n,!0);return}if(l&&Go.current&&Wi.current.includes(n)){Qa(n,l),mt.current.delete(n),bn(l);return}mt.current.delete(n),Kt(n),bn(l),Rr(n)},[Rr,xr,Yr,Ac,Qa,vn,Kt,bn]),tv=s.useCallback((n,o)=>{const l=hn.current.get(n);if(o){hn.current.set(n,o),lt(n),l&&l!==o&&bn(l);const m=g===n&&Qe?Et.current.get(n):null;m&&xc(m,o)&&n===xt&&(Ic(n,"warm-reuse"),gn(!0)),m&&m!==o&&v0({decodeWidth:m.width,decodeHeight:m.height,presentationCssWidth:o.getBoundingClientRect().width,presentationCssHeight:o.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:wr.maxWidth,sourceHeight:wr.maxHeight})&&(Et.current.set(n,o),bn(m));return}hn.current.delete(n),lt(m=>m===n?"":m),bn(l)},[Ic,xt,g,Qe,wr.maxHeight,wr.maxWidth,xc,bn]),Tc=s.useCallback((n,o,l)=>{const m=performance.now(),d=ft(n,l.deviceId);let C=l;if(n==="control"&&l.visualChanged){const Z=String(o.inputFeedbackEventId||""),ge=Number(o.inputFeedbackInputSeq||0),D=Number(o.inputFeedbackIssuedAtEpochMs||0),fe=Number(o.browserReceivedEpochMs||0),Ne=Nm.current.get(l.deviceId)||"",We=D>0?Math.max(0,Date.now()-D):Number.POSITIVE_INFINITY;if(Z.length>0&&ge>0&&Z!==Ne&&We<=pd){const Ue=Fm.current.get(l.deviceId)||[];Ue.push(We),Ue.length>vh&&Ue.splice(0,Ue.length-vh),Fm.current.set(l.deviceId,Ue),C={...l,inputFeedbackSeq:ge,inputFeedbackMs:We,inputFeedbackAt:m,inputFeedbackExact:!0,inputFeedbackEventId:Z,inputFeedbackInputType:o.inputFeedbackInputType,inputFeedbackInputToFrameMs:fe>0?Math.max(0,fe-D):void 0,inputFeedbackFrameToPaintMs:fe>0?Math.max(0,Date.now()-fe):void 0,inputFeedbackAgentApplyMs:o.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:o.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Ue.length,inputFeedbackP50Ms:gs(Ue,.5),inputFeedbackP95Ms:gs(Ue,.95)},Nm.current.set(l.deviceId,Z),Zl.current.set(l.deviceId,ge)}else if(!Z){const Ue=oC(l.deviceId),Yt=Zl.current.get(l.deviceId)||0,Xr=Ue?m-Ue.sentAt:Number.POSITIVE_INFINITY;Ue&&Ue.inputSeq>Yt&&Xr<=pd&&(C={...l,inputFeedbackSeq:Ue.inputSeq,inputFeedbackMs:Math.max(0,Xr),inputFeedbackAt:m,inputFeedbackExact:!1},Zl.current.set(l.deviceId,Ue.inputSeq))}}const v=Nt.current.get(d)||0,S=v>0&&hr.current.get(d)||0;if(hr.current.set(d,m),Fn.current.delete(d),n==="control"&&ma.current.delete(d),gr.current.delete(d),v>0){const Z=By({restartAttempts:v,healthySinceAt:Vr.current.get(d)||0,previousPaintAt:S,paintedAt:m,maximumHealthyGapMs:n==="control"?fd:Fh,stableForMs:n==="control"?Eh:Nh});Z.resetAttempts?(Nt.current.delete(d),Vr.current.delete(d),Ft(n,o.deviceId,"stable","stable-paint-window",v)):Z.healthySinceAt>0&&Vr.current.set(d,Z.healthySinceAt)}const y=ua.current.get(d)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:m,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},w=er(o);y.bindingKey!==w&&(y.bindingKey=w,y.lastAt=void 0,y.lastFrameSeq=void 0,y.sampleChangedFrames=0,y.sampleDecoderInputBase=Number(l.decoderInputCount||0),y.sampleDecoderOutputBase=Number(l.decoderOutputCount||0),ml(y,m)),n==="control"&&C.inputFeedbackMs===void 0&&y.lastInfo?.inputFeedbackMs!==void 0&&y.lastInfo.inputFeedbackAt!==void 0&&m-y.lastInfo.inputFeedbackAt<=pd&&(C={...C,inputFeedbackSeq:y.lastInfo.inputFeedbackSeq,inputFeedbackMs:y.lastInfo.inputFeedbackMs,inputFeedbackAt:y.lastInfo.inputFeedbackAt,inputFeedbackExact:y.lastInfo.inputFeedbackExact,inputFeedbackEventId:y.lastInfo.inputFeedbackEventId,inputFeedbackInputType:y.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:y.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:y.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:y.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:y.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:y.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:y.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:y.lastInfo.inputFeedbackP95Ms}),y.totalFrames+=1,y.sampleFrames+=1,Ah(y,m,C.frameSeq),C.visualChanged&&(y.totalChangedFrames+=1,y.sampleChangedFrames+=1),y.lastInfo=C,ua.current.set(d,y)},[Ft]),Pc=s.useCallback((n,o)=>{if(at.current[n.deviceId]||la.current===n.deviceId||n.currentGenerationVerified!==!0||Vn.current.get(n.deviceId)!==er(n))return;Tc("wall",n,o);const l=Qe&&g===n.deviceId,m=mt.current.get(n.deviceId)||en.current.get(n.deviceId);ec.current&&!Re&&!l&&m?.isConnected&&Zo("wall-visible",n,o),n.kind==="live"&&(xr(n.deviceId),Kt(n.deviceId)),la.current!==n.deviceId&&!l&&(jr.current.delete(n.deviceId),ca.current.delete(n.deviceId),_o.current.delete(n.deviceId),$a.current.delete(n.deviceId))},[g,Qe,xr,Tc,Zo,Kt,Re]),ep=s.useCallback((n,o)=>{if(at.current[n.deviceId]||On(yt.current,ke.current)||ya(yt.current,ke.current)||yt.current&&ke.current&&dn(yt.current,ke.current)&&ho(yt.current,ke.current.deviceId,ke.current.sessionId)&&yt.current.monitorIndex===ke.current.monitorIndex||!zu(n,ke.current))return;Tc("control",n,o),zt(v=>v&&"");const l=Et.current.get(n.deviceId),m=hn.current.get(n.deviceId);let d=!1;l&&l.width>0&&l.height>0&&(m&&Re&&n.deviceId===xt&&(d=xc(l,m),d&&Zo("control-visible",n,o)),Wa.current.set(n.deviceId,So(n)),jr.current.add(n.deviceId),n.deviceId===g&&(_e(!0),xe(v=>v==="connecting"?"active":v)),Yr(n.deviceId,!1,n));const C=ic.current;!C||!Uk(C,n)||!d||(Ic(n.deviceId,"fresh-frame"),gn(!0))},[Ic,xt,g,Yr,xc,Tc,Zo,Re]),Xa=s.useCallback((n,o)=>{const l=performance.now(),m=ft(n,o.deviceId);Hr.current.set(m,l),n!=="control"&&$r.current.delete(m);const d=Va.current.get(m)||{totalFrames:0,sampleFrames:0,sampleStartedAt:l,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},C=er(o);if(d.bindingKey!==C&&(d.bindingKey=C,d.lastAt=void 0,d.lastFrameSeq=void 0,d.lastContentHash=void 0,d.sampleBytes=0,d.sampleH264Frames=0,d.sampleTinyFrames=0,d.sampleRepeatedFrames=0,d.sourceSendIntervalsMs.length=0,ml(d,l)),d.totalFrames+=1,d.sampleFrames+=1,d.sampleBytes+=Math.max(0,Number(o.byteLength||0)),String(o.frameMode||o.mode||o.codec||o.mimeType||"").toLowerCase().includes("h264")){d.sampleH264Frames+=1,Number(o.byteLength||0)<=Hk&&(d.sampleTinyFrames+=1);const w=String(o.contentHash||"");w&&d.lastContentHash===w&&(d.sampleRepeatedFrames+=1),d.lastContentHash=w}const y=Number(o.agentSendGapMs||0);y>0&&y<1e3&&pb(d.sourceSendIntervalsMs,y),d.lastFrame=So(o),Ah(d,l,o.frameSeq),Va.current.set(m,d)},[]);s.useEffect(()=>{const n=new Set(Xm),o=new Set([...Hr.current.keys(),...hr.current.keys(),...da.current.keys(),...Fn.current.keys(),...gr.current.keys(),...Nt.current.keys(),...Vr.current.keys(),...$i.current.keys(),...ma.current.keys(),...Wr.current.keys(),...$r.current.keys(),...ua.current.keys(),...Va.current.keys()]);for(const d of o){if(n.has(d))continue;const C=d.indexOf(":"),v=d.slice(0,C),S=d.slice(C+1);(v==="wall"||v==="control")&&S&&zr(v,S)}const l=d=>{const C=Object.entries(d).filter(([v])=>n.has(v));return C.length===Object.keys(d).length?d:Object.fromEntries(C)};if(Yl(l),ac(l),n.size===0)return;const m=window.setInterval(()=>{const d=performance.now(),C={},v={};for(const S of n){const y=ua.current.get(S);if(y){const D=Math.max(1,d-y.sampleStartedAt);C[S]={bindingKey:y.bindingKey||"",totalFrames:y.totalFrames,totalChangedFrames:y.totalChangedFrames,framesPerSecond:y.sampleFrames*1e3/D,changedFramesPerSecond:y.sampleChangedFrames*1e3/D,averageIntervalMs:y.intervalCount>0?y.intervalSumMs/y.intervalCount:0,minIntervalMs:Number.isFinite(y.minIntervalMs)?y.minIntervalMs:0,maxIntervalMs:y.maxIntervalMs,p95IntervalMs:gs(y.intervalSamplesMs,.95),intervalCount:y.intervalCount,seqGapCount:y.seqGapCount,maxSeqGap:y.maxSeqGap,decoderInputFps:Math.max(0,(Number(y.lastInfo?.decoderInputCount||0)-y.sampleDecoderInputBase)*1e3/D),decoderOutputFps:Math.max(0,(Number(y.lastInfo?.decoderOutputCount||0)-y.sampleDecoderOutputBase)*1e3/D),sampleMs:D,lastInfo:y.lastInfo},y.sampleDecoderInputBase=Number(y.lastInfo?.decoderInputCount||0),y.sampleDecoderOutputBase=Number(y.lastInfo?.decoderOutputCount||0),y.sampleChangedFrames=0,ml(y,d)}const w=Va.current.get(S);if(!w)continue;const Z=Math.max(1,d-w.sampleStartedAt),ge=w.lastFrame?So(w.lastFrame):void 0;w.lastFrame=ge,v[S]={totalFrames:w.totalFrames,framesPerSecond:w.sampleFrames*1e3/Z,averageIntervalMs:w.intervalCount>0?w.intervalSumMs/w.intervalCount:0,minIntervalMs:Number.isFinite(w.minIntervalMs)?w.minIntervalMs:0,maxIntervalMs:w.maxIntervalMs,p95IntervalMs:gs(w.intervalSamplesMs,.95),intervalCount:w.intervalCount,seqGapCount:w.seqGapCount,maxSeqGap:w.maxSeqGap,averageFrameBytes:w.sampleFrames>0?w.sampleBytes/w.sampleFrames:0,tinyFrameRatio:w.sampleH264Frames>0?w.sampleTinyFrames/w.sampleH264Frames:0,repeatedFrameRatio:w.sampleH264Frames>0?w.sampleRepeatedFrames/w.sampleH264Frames:0,sourceSendAverageMs:w.sourceSendIntervalsMs.length>0?w.sourceSendIntervalsMs.reduce((D,fe)=>D+fe,0)/w.sourceSendIntervalsMs.length:0,sourceSendP95Ms:gs(w.sourceSendIntervalsMs,.95),sourceSendSampleCount:w.sourceSendIntervalsMs.length,sampleMs:Z,lastFrame:ge},w.sampleBytes=0,w.sampleH264Frames=0,w.sampleTinyFrames=0,w.sampleRepeatedFrames=0,w.sourceSendIntervalsMs.length=0,ml(w,d)}Yl(C),ac(v)},1e3);return oc.current=m,()=>{window.clearInterval(m),oc.current===m&&(oc.current=null)}},[Xm,zr]);const tp=s.useCallback(n=>{const o=O;if(ie.current!==o)return;const l=n.deviceId,m=er(n);if(at.current[l]||la.current===l||n.currentGenerationVerified!==!0||Vn.current.get(l)!==m)return;Xa("wall",n);const d=mt.current.get(l);if(!d)return;const C=$o(d),v=Vo(d),S=()=>mt.current.get(l)!==d||!zo(d,C)||ie.current!==o||!!at.current[l]||la.current===l||Vn.current.get(l)!==m,y=()=>S()||!Ua(d,v),w=A0(nt,De.h264DecodeAcceleration);Ju(d,n,y,Pc,w.acceleration,w.latencyMode,S,Rc).catch(()=>{})},[$o,Ua,zo,Vo,Pc,nt,Xa,Rc,De.h264DecodeAcceleration,O]),np=s.useCallback(n=>{const o=O;if(ie.current!==o)return;const l=n.deviceId;if(at.current[l]||On(yt.current,ke.current)||ya(yt.current,ke.current)||yt.current&&ke.current&&dn(yt.current,ke.current)&&ho(yt.current,ke.current.deviceId,ke.current.sessionId)&&yt.current.monitorIndex===ke.current.monitorIndex||!zu(n,ke.current))return;let m=Et.current.get(l);if(!m){const fe=hn.current.get(l),Ne=Ha.current;m=fe||Ne||document.createElement("canvas"),fe&&Ne&&Ne!==fe&&vn(Ne),Ha.current=null,m!==fe&&m.setAttribute("aria-hidden","true"),Et.current.set(l,m)}const d=m,C=n,v=$o(d),S=Vo(d),y=()=>Et.current.get(l)!==d||!zo(d,v)||ie.current!==o||!!at.current[l]||!zu(C,ke.current),w=()=>y()||!Ua(d,S),Z=xi.current,ge=String(n.frameMode||n.mode||n.codec||n.mimeType||"").toLowerCase().includes("h264");ge||Xa("control",n);const D=Ju(d,n,w,ep,on.h264DecodeAcceleration,"interactive",y);ge&&Xa("control",n),D.catch(fe=>{xi.current!==Z||Et.current.get(l)!==d||!Ua(d,S)||y()||g!==l||zt(fe instanceof Error?fe.message:String(fe||"Control H.264 decode failed"))})},[$o,Ua,zo,Vo,g,on.h264DecodeAcceleration,ep,Xa,vn,O]),nv=s.useCallback(n=>{const o=Nn.current;Nn.current=n,o&&o!==n&&bn(o),Hi.current=0,cc.current=0,lc.current=0,uc.current=0,Jl.current=0,_i.current=0},[bn]),ei=s.useCallback(()=>{const n=new Set,o=O;if(ie.current!==o)return n;const l=Nn.current,m=Bo.current;if(!l||!m||l.width<=0||l.height<=0||_i.current!==m.layoutVersion)return n;for(const d of m.tiles){if(at.current[d.deviceId])continue;const C=en.current.get(d.deviceId);if(!C||d.width<=0||d.height<=0)continue;const v=Math.max(1,Math.round(d.width)),S=Math.max(1,Math.round(d.height)),y=Wk,w=$k;(C.width!==y||C.height!==w)&&(C.width=y,C.height=w);const Z=C.getContext("2d",{alpha:!1});if(Z){Z.imageSmoothingEnabled=!0,Z.imageSmoothingQuality="high";try{Z.drawImage(l,Math.round(d.x),Math.round(d.y),v,S,0,0,y,w),n.add(d.deviceId)}catch{}}}return n},[O]),rv=s.useCallback((n,o)=>{const l=en.current.get(n);if(o&&l&&l!==o&&Qa(n,l),o){if(en.current.set(n,o),l&&l!==o&&bn(l),at.current[n]){Kt(n),vn(o),Rr(n);return}_r.current.get(n)&&Ac(n,o)&&xr(n),window.requestAnimationFrame(()=>{ei().has(n)&&Kt(n)}),window.requestAnimationFrame(()=>Yr(n,!0));return}en.current.delete(n),Kt(n),bn(l),Rr(n)},[Rr,xr,ei,Yr,Ac,Qa,vn,Kt,bn]),rp=s.useCallback((n,o)=>{if(ie.current!==O)return;lc.current=performance.now(),_i.current=Number(n.layoutVersion||0),ei();const l=Bo.current?.tiles||[],m=l.length>0?Math.round(n.byteLength/l.length):n.byteLength;for(const d of l){if(at.current[d.deviceId])continue;const C={...n,deviceId:d.deviceId,width:d.width,height:d.height,sourceWidth:d.width,sourceHeight:d.height,byteLength:m};Pc(C,{...o,deviceId:d.deviceId,width:d.width,height:d.height,byteLength:m}),la.current===d.deviceId&&Yr(d.deviceId,!0)}},[Pc,ei,Yr,O]),av=s.useCallback(n=>{const o=O;if(ie.current!==o)return;const l=performance.now();Hi.current<=0&&(Hi.current=l),cc.current=l;const m=Nn.current;if(!m)return;const d=er(n);Oi.current!==d&&(Oi.current=d,$t(m));const C=$o(m),v=Vo(m),S=()=>Nn.current!==m||Oi.current!==d||ie.current!==o||!zo(m,C),y=()=>S()||!Ua(m,v),w=Bo.current?.tiles||[],Z=w.length>0?Math.round(n.byteLength/w.length):n.byteLength;for(const ge of w)at.current[ge.deviceId]||Xa("wall",{...n,deviceId:ge.deviceId,width:ge.width,height:ge.height,sourceWidth:ge.width,sourceHeight:ge.height,byteLength:Z});Ju(m,n,y,rp,void 0,"smooth",S).catch(()=>{})},[$o,Ua,zo,Vo,rp,Xa,$t,O]),ap=s.useCallback(n=>{const o=H&&n.streamPurpose==="control"&&n.readOnlyControlBorrow===!0&&n.presentationPurpose==="wall";if(n.streamPurpose!=="wall"&&!o||at.current[n.deviceId])return;const l=er(n);Vn.current.get(n.deviceId)!==l&&(Vn.current.set(n.deviceId,l),$t(mt.current.get(n.deviceId)),ve.current&&$({type:"frame.owner.changed",component:`wall-owner:${n.deviceId}`,state:"bound",reason:`owner:${n.sessionId||"unknown"}:${n.captureGeneration||"unknown"}:${n.monitorIndex}`,details:{deviceId:n.deviceId,sessionId:n.sessionId||"unknown",streamId:n.streamId||"unknown",commandId:n.commandId||"unknown",captureGeneration:n.captureGeneration||"unknown",monitorIndex:n.monitorIndex,streamPurpose:n.streamPurpose||"unknown",presentationPurpose:n.presentationPurpose||"unknown"}}))},[H,$,$t]),uu=s.useMemo(()=>({fps:ln.fps,maxWidth:ln.maxWidth,maxHeight:ln.maxHeight,quality:ln.quality,mode:nt?"mode3-h264-hw":De.frameMode,frameMode:nt?"mode3-h264-hw":De.frameMode,streamPurpose:"wall",allowReadOnlyControlBorrow:H,configurationRefreshMs:wk,connectionSessionIds:yn,monitorSelections:gt,onFrame:tp,onStreamReady:ap}),[yn,tp,ap,H,nt,gt,De.frameMode,ln.fps,ln.maxHeight,ln.maxWidth,ln.quality]),Ec=s.useCallback(n=>{const o=ut.current;if(o!=="connecting"&&o!=="active"&&o!=="warm"&&o!=="stopping")return Ft("control",n.deviceId,"stop-deferred",`stream-binding-ignored-during-${o}`,Nt.current.get(ft("control",n.deviceId))||0),null;const l=ke.current;if(at.current[n.deviceId]||!l||l.deviceId!==n.deviceId||n.deviceId!==g||n.streamPurpose!=="control"||n.monitorIndex!==ir)return null;const m=eu.current[n.deviceId]||"";if(!m||m!==n.sessionId)return null;const d=Uu(l.deviceId,l.transitionGeneration,n),C=dn(l,d)&&ho(l,d.deviceId,d.sessionId)&&l.monitorIndex===d.monitorIndex;return!qu(l,d)&&!ya(l,d)&&!C?(Ft("control",n.deviceId,"owner-replaced","stale-stream-binding-ignored",Nt.current.get(ft("control",n.deviceId))||0),null):(qu(l,d)||(ke.current=d,ve.current&&$({type:"frame.owner.changed",component:`control-owner:${n.deviceId}`,state:"bound",reason:`owner:${n.sessionId||"unknown"}:${n.captureGeneration||"unknown"}:${n.monitorIndex}`,details:{deviceId:n.deviceId,sessionId:n.sessionId||"unknown",streamId:n.streamId||"unknown",commandId:n.commandId||"unknown",captureGeneration:n.captureGeneration||"unknown",monitorIndex:n.monitorIndex,streamPurpose:n.streamPurpose}}),Ft("control",n.deviceId,"owner-bound","hub-start-descriptor",Nt.current.get(ft("control",n.deviceId))||0)),d)},[g,Ft,$,ir]),op=s.useCallback(n=>{const o=Ec(n);if(!o)return;const l=yt.current;if(On(l,o)||ya(l,o)||!!l&&dn(l,o)&&ho(l,o.deviceId,o.sessionId)&&l.monitorIndex===o.monitorIndex)return;yt.current&&(yt.current=null,Ft("control",n.deviceId,"owner-replaced","stream-ready-superseded-stale-downshift",Nt.current.get(ft("control",n.deviceId))||0));const d=ut.current;if(d!=="connecting"&&d!=="active"&&d!=="warm"){Ft("control",n.deviceId,"stop-deferred",`stream-ready-ignored-during-${d}`,Nt.current.get(ft("control",n.deviceId))||0);return}const C=rt.current;(!C||er(C)!==er(n))&&$t(Et.current.get(n.deviceId)),rt.current=n,ht(n),xe(Hy)},[Ec,Ft,$t]);s.useEffect(()=>{$t(Et.current.get(g)),rt.current=null,ht(null)},[g,F,Gn,$t,ir]);const Nc=F?`${F}-monitor-${ir}`:"",du=s.useMemo(()=>({fps:Gi,maxWidth:wr.maxWidth,maxHeight:wr.maxHeight,quality:on.quality,mode:Gn,frameMode:Gn,streamPurpose:"control",forceRestart:Nc!=="",forceRestartToken:Nc,restartReason:Nc?"control-session-or-monitor-change":"",connectionSessionIds:yn,monitorSelections:gt,onFrame:np,onStreamBound:Ec,onStreamReady:op}),[yn,Nc,on.quality,np,Gi,Gn,wr.maxHeight,wr.maxWidth,Ec,op,gt]),{frames:ip,state:Qi,error:Fc,stats:Ja,restartLive:sp,reconnectLive:mu}=Ef(Gt,De.autoStartLive&&Gt.length>0,Y,uu,O);s.useEffect(()=>{const n=new Set(Gt),o=ve.current?[]:null;for(const l of Vn.current.keys())n.has(l)||(Vn.current.delete(l),$t(mt.current.get(l)),o?.push({type:"frame.owner.changed",component:`wall-owner:${l}`,state:"unbound",reason:"device-no-longer-requested",details:{deviceId:l}}));o&&o.length>0&&ae(o)},[Gt,ae,$t]);const{frame:ti,layout:Za,state:Xi,stats:ov,refreshInputs:cp}=uC(nn,nt&&De.autoStartLive&&nn.length>0,Y,{fps:wt.atlasOutputFps,inputFps:lu,width:1920,height:1080,tileWidth:Jo.maxWidth,tileHeight:Jo.maxHeight,captureDeviceIds:nn,connectionSessionIds:yn,monitorSelections:gt,onFrame:av},O);s.useEffect(()=>{Bo.current=Za,Za&&window.requestAnimationFrame(ei)},[Za,ei]),s.useEffect(()=>{if(!nt||Xi!=="open"){Hi.current=0,cc.current=0,lc.current=0;return}const n=window.setInterval(()=>{const o=Nn.current,l=performance.now();if(!o||document.visibilityState!=="visible"||l-sc.current<md)return;const m=cc.current,d=Hi.current;if(m<=0||d<=0||l-m>500)return;const C=lc.current||d,v=l-C;if(v>=Ek&&l-Jl.current>=Fk){fi(o)&&(Jl.current=l,uc.current=l);return}v>=Pk&&l-uc.current>=Nk&&Gw(o)&&(uc.current=l)},250);return()=>window.clearInterval(n)},[Xi,nt]);const{frames:Ji,state:Dc,error:eo,stats:iv,restartLive:Lc,reconnectLive:Zi}=Ef(Gr,Gr.length>0,Y,du,O);s.useEffect(()=>{ve.current&&ae([{type:"frame.transport.changed",component:"wall-frame-socket",state:Qi||"unknown",reason:Fc||`desired-owners:${Gt.length}`,details:{desiredOwnerCount:Gt.length,frameMode:uu.frameMode,managerHubUrl:Y||"unknown"}},{type:"frame.transport.changed",component:"control-frame-socket",state:Dc||"unknown",reason:eo||`desired-owners:${Gr.length}`,details:{desiredOwnerCount:Gr.length,frameMode:du.frameMode,managerHubUrl:Y||"unknown"}},{type:"frame.transport.changed",component:"atlas-frame-socket",state:Xi||"unknown",reason:`desired-owners:${nn.length}`,details:{desiredOwnerCount:nn.length,enabled:nt,managerHubUrl:Y||"unknown"}},{type:"stream.state.changed",component:"wall-subscription",state:yr&&De.autoStartLive?"requested":"idle",reason:qt?`tool:${It}:desired-owners:${Gt.length}`:"document-hidden",details:{documentVisible:qt,captureOwnershipActive:yr,autoStartLive:De.autoStartLive,activeTool:It,desiredOwnerCount:Gt.length}},{type:"stream.state.changed",component:`control-session:${g||"unknown"}`,state:be,reason:`frame-transport:${Dc||"unknown"}`,details:{deviceId:g||"unknown",bindingSessionId:ct?.sessionId||"unknown",bindingStreamId:ct?.streamId||"unknown",bindingCaptureGeneration:ct?.captureGeneration||"unknown",bindingMonitorIndex:ct?.monitorIndex??"unknown"}}])},[It,Xi,Gr.length,eo,Dc,du.frameMode,g,be,ct,Gt.length,qt,Y,nn.length,nt,it,ae,De.autoStartLive,yr,Fc,Qi,uu.frameMode]),s.useEffect(()=>{const n=xm.current,o=new Set([...Object.keys(n),...Object.keys(gt)]);for(const l of o){const m=Math.max(0,Math.floor(Number(n[l])||0)),d=Math.max(0,Math.floor(Number(gt[l])||0));m!==d&&(Vn.current.delete(l),$t(mt.current.get(l)),$t(Et.current.get(l)),$t(en.current.get(l)),Dt("wall",l),Dt("control",l),fi(mt.current.get(l)||null),fi(Et.current.get(l)||null))}o.size>0&&($t(Nn.current),fi(Nn.current)),xm.current={...gt}},[gt,Dt,$t]);const ni=s.useMemo(()=>{const n=(l,m)=>{const d=Le.find(v=>v.deviceId===l),C=d?_n(d,gt[l]):0;return!Number.isFinite(Number(m.monitorIndex))||Number(m.monitorIndex)===C},o=new Map;for(const[l,m]of ip.entries())n(l,m)&&o.set(l,m);if(nt&&ti&&nn.length>0){const l=new Map((Za?.tiles||[]).map(d=>[d.deviceId,d])),m=Math.max(1,l.size);for(const d of nn){const C=l.get(d);C&&o.set(d,{...ti,deviceId:d,width:C.width,height:C.height,sourceWidth:C.width,sourceHeight:C.height,byteLength:Math.round(ti.byteLength/m)})}}for(const[l,m]of Ji.entries())n(l,m)&&o.set(l,m);for(const l of Sc){if(!jr.current.has(l)||o.has(l))continue;const m=Wa.current.get(l);m&&n(l,m)&&o.set(l,m)}return o},[ti,Za,Le,Ji,nn,nt,gt,ip,Sc,Nb]),pu=Re&&Gr.length>0?Dc:nn.length>0?Xi:Qi,Oc=Re&&Gr.length>0?iv:nn.length>0?ov:Ja;s.useCallback((n,o="browser-stale")=>{const l=sp(n,o),m=Lc(n,o);return l||m},[Lc,sp]),s.useEffect(()=>{nt&&nn.length>0&&!Re&&cp()},[nn.length,nt,cp,Re]);const ri=s.useCallback((n,o,l)=>{const m=o==="control"?Et.current.get(n)||null:mt.current.get(n)||null;if(!m)return!1;fi(m);const d=performance.now();return gr.current.set(ft(o,n),d),!0},[]),es=s.useCallback(n=>{if(Gn!=="mode3-h264-hw"||!g||Q)return!1;const o=Le.find(S=>S.deviceId===g)||tn,l=Gh(o?.platform);if(!l)return!1;const m=ft("control",g),d=Nt.current.get(m)||0;Ft("control",g,"fallback",n,d),Dt("control",g,{preserveLatestDiagnostic:!0}),fi(Et.current.get(g)||null),Zi([g],"control-decode-fallback"),Ie(l),he(`control-${l}-fallback-${g}-${Date.now()}`),_e(!1),gn(!1);const C=n==="no first frame"||n==="control-first-frame-timeout",v=l==="mode1-jpeg"?"Mode 1 JPEG":"Mode 5";return zt(S=>S||(C?`Control frame transport timeout; retrying Control with ${v} (${n})`:`H.264 decode failed; retrying Control with ${v} (${n})`)),xe("connecting"),!0},[Le,tn,g,Q,Gn,Zi,Ft,Dt]);s.useEffect(()=>{const n=Re?tn:null;if(n){ic.current={deviceId:n.deviceId,monitorIndex:ir,frameMode:Gn,startedAtEpochMs:Date.now()},gn(g===n.deviceId&&Qe);return}ic.current=null,gn(!1)},[tn?.sessionId,xt,g,Qe,Gn,ir,Re]);const lp=s.useCallback(async(n,o)=>{const l=String(o.streamId||"").trim(),m=String(o.streamPurpose||"").trim(),d=String(o.sessionId||"").trim(),C=String(o.commandId||"").trim(),v=Number(o.captureGeneration||0),S=Number(o.monitorIndex??-1);if(!l||!["wall","atlas"].includes(m)||!d||!C||!Number.isSafeInteger(v)||v<=0||!Number.isSafeInteger(S)||S<0)throw new Error("wall-start-owner-incomplete");const y=performance.now()+3e3;for(;;){const w=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:l,streamPurpose:m,expectedSessionId:d,expectedCommandId:C,expectedCaptureGeneration:v,expectedMonitorIndex:S,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},Y);if(w?.ok===!1)throw new Error(w.error||"revoked-wall-start-stop-failed");if(w?.captureStopConfirmed===!0||w?.alreadyStopped===!0||w?.staleOwner===!0)return w;if(w?.presentationOwnerActive===!0||w?.retainedForPresentation===!0){if(qn.current&&Go.current)return w;if(performance.now()<y){await new Promise(Z=>window.setTimeout(Z,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[Y]),to=s.useCallback(async n=>{if(at.current[n])throw new Error("LIVE_CAPTURE_PAUSED");if(!qn.current||!Go.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const o=rr.current,l=Me.find(v=>v.deviceId===n);fs({mode4Enabled:nt,directMode4WallEnabled:Mr,isMac:Nr(l?.platform)});const m=l?_n(l,gt[n]):0,d={fps:ln.fps,maxWidth:ln.maxWidth,maxHeight:ln.maxHeight,quality:ln.quality,mode:nt?"mode3-h264-hw":De.frameMode,frameMode:nt?"mode3-h264-hw":De.frameMode,streamPurpose:"wall",monitorIndex:m},C=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/start`,{method:"POST",body:JSON.stringify(d)},Y);if(C?.ok===!1)throw new Error(C.error||"wall-stream-start-failed");return o!==rr.current||!qn.current||!Go.current?(await lp(n,C),{...C,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):C},[lu,Me,Mr,Y,nt,gt,lp,De.frameMode,Jo.maxHeight,Jo.maxWidth,ln.fps,ln.maxHeight,ln.maxWidth,ln.quality]),up=s.useCallback(async n=>{const o=Me.find(m=>m.deviceId===n);fs({mode4Enabled:nt,directMode4WallEnabled:Mr,isMac:Nr(o?.platform)});const l=await ze(`/api/remote/devices/${encodeURIComponent(n)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},Y);if(l?.ok===!1)throw new Error(l.error||"wall-stream-stop-failed");return l},[Me,Mr,Y,nt]),dp=s.useCallback(async(n,o="control-session-stop")=>{if(!Xc(n))return Ft("control",n.deviceId,"stop-deferred",`${o}:unbound-stop-deferred-to-frame-owner`,Nt.current.get(ft("control",n.deviceId))||0),{ok:!0,pendingOwner:!0,deferredToFrameOwner:!0};const m=await ze(`/api/remote/devices/${encodeURIComponent(n.deviceId)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:n.streamId,expectedSessionId:n.sessionId,expectedCommandId:n.commandId,expectedCaptureGeneration:n.captureGeneration,expectedMonitorIndex:n.monitorIndex,streamPurpose:"control",reason:o})},Y);if(m?.ok===!1)throw new Error(m.error||"control-stream-stop-failed");return(m?.staleOwner===!0||m?.retainedNewerOwner===!0)&&Ft("control",n.deviceId,"owner-replaced",`${o}:hub-retained-newer-owner`,Nt.current.get(ft("control",n.deviceId))||0),m},[Y,Ft]),Rn=s.useCallback((n,o={})=>{yt.current?.deviceId===n&&(yt.current=null);const l=Et.current.get(n);if(l){const d=_r.current.has(n)||mt.current.has(n)||en.current.has(n);o.preservePresentation!==!1&&!d&&Qa(n,l),Et.current.delete(n),vn(l),!(hn.current.get(n)||mt.current.get(n)||en.current.get(n))&&!Ha.current&&(Ha.current=l)}const m=hn.current.get(n);m&&pi(m),Wa.current.delete(n),jr.current.delete(n),ca.current.delete(n),_o.current.delete(n),$a.current.delete(n),zr("control",n)},[zr,Qa,vn]),_c=s.useCallback(n=>{const o=[ft("wall",n),ft("control",n)];for(const l of o){const m=Va.current.get(l);m?.lastFrame&&(m.lastFrame=So(m.lastFrame))}ac(l=>{let m=!1;const d={...l};for(const C of o){const v=l[C];!v?.lastFrame||v.lastFrame.payload.byteLength===0||(d[C]={...v,lastFrame:So(v.lastFrame)},m=!0)}return m?d:l})},[]),fu=s.useCallback(n=>{Vn.current.delete(n),Kt(n),Rn(n,{preservePresentation:!1});const o=new Set;for(const l of[hn.current.get(n),mt.current.get(n),en.current.get(n)])l&&o.add(l);for(const l of o)vn(l);Rr(n),g===n&&(ic.current=null,gn(!1),_e(!1)),Ii.current.add(n),_c(n)},[Rr,g,vn,Rn,_c,Kt]);s.useEffect(()=>{const n=new Set(Object.keys(na));for(const o of n)Ii.current.has(o)||fu(o);for(const o of Ii.current)n.has(o)||Ii.current.delete(o)},[fu,na]);const ai=s.useCallback(n=>{const o=lf(Am.current,n);return Am.current=o.tail,o.result},[]),Yn=s.useCallback(n=>{const o=lf(Em.current,n);return Em.current=o.tail,o.result},[]),Qn=s.useCallback(n=>{xn.current=n,Zs.current=0;const o=n?.deviceId||"";la.current=o,Ib(o),o&&jr.current.add(o)},[]),oi=s.useCallback(n=>ai(async()=>{if(at.current[n.deviceId])return!1;const o=xn.current;return!dn(o,n)||!Jc(n.deviceId,n,ke.current)?!1:(await to(n.deviceId),dn(xn.current,n)&&Qn(null),!0)}),[Qn,ai,to]),mp=s.useCallback((n,o,l)=>ai(async()=>{const m=xn.current;if(dn(m,n))return l.stoppedWallDeviceId=n.deviceId,!0;if(m)if(at.current[m.deviceId])dn(xn.current,m)&&Qn(null);else{if(!Jc(m.deviceId,m,ke.current))return!1;await to(m.deviceId),dn(xn.current,m)&&Qn(null)}if(!o())return!1;if(await up(n.deviceId),l.stoppedWallDeviceId=n.deviceId,!o()){if(Jc(l.stoppedWallDeviceId,n,ke.current))try{await to(l.stoppedWallDeviceId)}catch(d){throw Qn(n),d}finally{l.stoppedWallDeviceId=""}return!1}return pi(mt.current.get(n.deviceId)||null),Qn(n),!0}),[Qn,ai,to,up]),jc=s.useCallback(async(n,o)=>{if(o.stoppedWallDeviceId){if(dn(xn.current,n)){try{await oi(n)}catch(l){j(l instanceof Error?l.message:String(l))}finally{o.stoppedWallDeviceId=""}return}await ai(async()=>{if(!o.stoppedWallDeviceId||!Jc(o.stoppedWallDeviceId,n,ke.current))return;const l=o.stoppedWallDeviceId;try{await to(l)}catch(m){Qn(n),j(m instanceof Error?m.message:String(m))}finally{o.stoppedWallDeviceId=""}})}},[Qn,ai,oi,j,to]),Xn=s.useCallback(async(n,o,l={})=>{const m=l.allowStopFailure===!0,d=l.resumeWall!==!1,C=S=>{const y=ke.current;if(!y)return S;const w=Xc(y)&&dn(y,S)&&ho(S,y.deviceId,y.sessionId)&&S.monitorIndex===y.monitorIndex;return On(y,S)||ya(S,y)||w?y:S};let v=C(n);for(let S=0;S<2;S+=1){try{await dp(v,o)}catch(w){if(!m)throw w}const y=C(v);if(On(y,v)||qu(y,v)||!Xc(y)||!dn(y,v))break;v=y}if(!On(ke.current,v))return!1;if(ke.current=null,rt.current=null,ht(null),Rn(v.deviceId),_e(!1),he(""),Ie(""),zt(""),U(S=>S===v.deviceId?"":S),!d)return dn(xn.current,v)&&Qn(null),!0;try{await oi(v)}catch(S){j(S instanceof Error?S.message:String(S))}return!0},[Qn,Rn,oi,j,dp]),pp=(qt&&Re&&pt&&xt&&!Ti.has(xt)&&Le.find(n=>n.deviceId===xt)||null)?.deviceId||"";s.useEffect(()=>{Ho.current=pp},[pp]),s.useEffect(()=>{const n=xt&&Le.find(C=>C.deviceId===xt)||null;if(!qt||!Re||!pt||!n){sn.current&&(++Ht.current,sn.current="");return}if(at.current[n.deviceId]){sn.current&&(++Ht.current,sn.current=""),g===n.deviceId&&xe("paused");return}if(Un.current){if(Un.current===n.deviceId)return;Un.current=""}if(g===n.deviceId&&ho(ke.current,n.deviceId,n.sessionId||"")&&(be==="active"||be==="warm"||be==="connecting")){xe(C=>C==="warm"?"active":C);return}if(sn.current===n.deviceId)return;const o=++Ht.current,l=Uu(n.deviceId,o,{sessionId:n.sessionId,monitorIndex:ir});sn.current=n.deviceId;const m={stoppedWallDeviceId:""},d=()=>o===Ht.current&&Ho.current===l.deviceId;Yn(async()=>{if(!d())return;const C=ke.current;if(C){xe("stopping");try{await Xn(C,"control-session-switch")}catch(y){d()&&(xe("error"),j(y instanceof Error?y.message:String(y)));return}if(!d()){ke.current||xe("idle");return}}try{if(!await mp(l,d,m)||!d()){await jc(l,m),ke.current||xe("idle");return}}catch(y){await jc(l,m),d()&&(xe("error"),j(y instanceof Error?y.message:String(y)));return}if(!d()){await jc(l,m);return}ke.current=l,yt.current=null,Un.current="",za.current=null,Wo.current=0,Bi.current="",m.stoppedWallDeviceId="";const v=ft("control",l.deviceId),S=`control-session-${o}-${l.deviceId}`;Wr.current.set(v,performance.now()),Hr.current.delete(v),hr.current.delete(v),da.current.delete(v),Fn.current.delete(v),gr.current.delete(v),Nt.current.delete(v),Vr.current.delete(v),ma.current.delete(v),Ie(""),zt(""),he(S),U(l.deviceId),_e(!1),xe("connecting")}).catch(C=>{d()&&(xe("error"),j(C instanceof Error?C.message:String(C)))}).finally(()=>{Ht.current===o&&sn.current===l.deviceId&&(sn.current="")})},[Le,xt,g,be,qt,Yn,pt,mp,jc,ir,j,Re,Xn,na]),s.useEffect(()=>{if(!g||Le.some(l=>l.deviceId===g))return;const n=g;++Ht.current,sn.current="";const o=ke.current;xe("stopping"),Yn(async()=>{o&&o.deviceId===n?await Xn(o,"control-device-disconnected",{allowStopFailure:!0}):(Rn(n),U(l=>l===n?"":l)),ke.current||xe("idle")})},[Le,g,Yn,Rn,Xn]),s.useEffect(()=>{if(zn.current!==null&&(window.clearTimeout(zn.current),zn.current=null),!or||Re||!g||at.current[g]||be!=="connecting"&&be!=="active"&&be!=="warm")return;const n=g,o=ke.current;if(!o||o.deviceId!==n)return;const l=window.setTimeout(()=>{zn.current===l&&(zn.current=null);const m=ke.current,d=S=>On(S,o)||ya(o,S)||!!S&&dn(S,o)&&ho(o,S.deviceId,S.sessionId)&&o.monitorIndex===S.monitorIndex;if(Ho.current||at.current[n]||!d(m))return;const C=m||o;yt.current=C;const v=++Ht.current;sn.current="",xe("stopping"),Yn(async()=>{if(v!==Ht.current||Ho.current||!d(ke.current)){(On(yt.current,C)||ya(yt.current,C))&&(yt.current=null);const S=ke.current;Ho.current&&Xc(S)&&S?.deviceId===n&&xe("active");return}try{await Xn(C,"control-session-wall-downshift")}catch(S){(On(yt.current,C)||ya(yt.current,C))&&(yt.current=null),v===Ht.current&&!Ho.current&&d(ke.current)&&(xe("active"),j(S instanceof Error?S.message:String(S)));return}yt.current=null,v===Ht.current&&!ke.current&&xe("idle")})},Bk);return zn.current=l,()=>{zn.current===l&&(window.clearTimeout(l),zn.current=null)}},[g,be,Yn,j,Re,Xn,na,or]);const Bc=s.useCallback(n=>{if(Pm.current===n)return;Pm.current=n;const o=ke.current,l=o?.deviceId||g,m=++Ht.current;sn.current="",rt.current=null,ji.current=!0,ht(null),_e(!1),gn(!1),l&&(Dt("control",l),Rn(l,{preservePresentation:!1}),xe("stopping"),Yn(async()=>{if(o&&o.deviceId===l)try{await Xn(o,"control-session-document-hidden",{resumeWall:!1})}catch(d){!qn.current&&rr.current===n&&(xe("error"),j(d instanceof Error?d.message:String(d)));return}else Rn(l,{preservePresentation:!1}),U(d=>d===l?"":d);!ke.current&&Ht.current===m&&xe("idle")}))},[g,Yn,Rn,Dt,j,Xn]);s.useEffect(()=>{if(nr.current!==null&&(window.clearTimeout(nr.current),nr.current=null),!g||be==="idle"||be==="paused"||be==="error")return;if(!qt){Bc(rr.current);return}if(be==="stopping"||Ko){g&&pc&&be==="connecting"&&(ji.current=!1),g&&pc&&ji.current&&(be==="warm"||be==="active")&&(ji.current=!1,rt.current=null,ht(null),_e(!1),gn(!1),Dt("control",g),he(`control-presentation-resume-${Date.now()}-${g}`),xe("connecting"));return}rt.current=null,ji.current=!0,ht(null),_e(!1),gn(!1),xe(o=>o==="idle"||o==="stopping"?o:"warm");const n=g;return Rn(n,{preservePresentation:!1}),nr.current=window.setTimeout(()=>{nr.current=null,++Ht.current,sn.current="";const o=ke.current;xe("stopping"),Yn(async()=>{if(o&&o.deviceId===n)try{await Xn(o,"control-session-warm-timeout")}catch(l){xe("error"),j(l instanceof Error?l.message:String(l));return}else Rn(n),U(l=>l===n?"":l);ke.current||xe("idle")})},jk),()=>{nr.current!==null&&(window.clearTimeout(nr.current),nr.current=null)}},[Ko,pc,g,be,qt,Yn,Rn,Bc,Dt,j,Xn]),s.useEffect(()=>()=>{nr.current!==null&&window.clearTimeout(nr.current),zn.current!==null&&(window.clearTimeout(zn.current),zn.current=null),yt.current=null},[]);const Hc=s.useCallback(()=>{const n=new Set(Xl.current),o=ke.current?.deviceId||"";g&&n.add(g),o&&n.add(o),Xl.current=[];for(const m of n){Vn.current.delete(m),Kt(m),Rn(m,{preservePresentation:!1});for(const d of[mt.current.get(m),hn.current.get(m),en.current.get(m)])d&&vn(d);Rr(m),Dt("wall",m),Dt("control",m),_c(m)}const l=Nn.current;l&&vn(l),Oi.current="",Bo.current=null,_i.current=0},[Rr,g,vn,Rn,_c,Kt,Dt]);s.useEffect(()=>{if(qt){Xl.current=[...cu];return}Hc()},[qt,cu,Hc]),s.useEffect(()=>{const n=xn.current,o=ke.current;if(!or||!n||at.current[n.deviceId]||o&&o.deviceId===n.deviceId){Zs.current=0;return}const l=Zs.current,m=Math.min(5e3,500*2**Math.min(l,4)),d=window.setTimeout(()=>{jo.current===d&&(jo.current=null);const C=xn.current;!$m.current||!C||at.current[C.deviceId]||!dn(C,n)||(Zs.current=l+1,oi(C).catch(v=>{j(v instanceof Error?v.message:String(v)),dn(xn.current,C)&&!ke.current&&Pb(S=>S+1)}))},m);return jo.current=d,()=>{window.clearTimeout(d),jo.current===d&&(jo.current=null)}},[be,oi,j,or,Tb,Di]);const ga=g&&Le.find(n=>n.deviceId===g)||null,ba=ga?.deviceId||"",sv=!!(qt&&Re&&kn&&Cr),ts=!!(Re&&kn&&be==="active"&&ga?.sessionId&&ct?.deviceId===ga.deviceId&&ct.sessionId===ga.sessionId&&ct.streamPurpose==="control"&&ct.commandId&&ct.captureGeneration>0&&ct.monitorIndex===ir),fp=ga?.capabilities?.clipboardProtocol==="livedesk.clipboard.v1",hp=fp&&vi(ga,"clipboardCopy"),gp=fp&&vi(ga,"clipboardPaste"),{state:ns,connectionId:no,routeReady:Wc,sendInput:bp,stats:Ar,error:vp,remotePointerFeedback:ro}=dC(sv,Y,ba,O),ao=ga?.sessionId||"",oo=ct?.commandId||"",io=Number(ct?.captureGeneration||0),ii=Number(ct?.monitorIndex||0),cv=ro&&ro.deviceId===ba&&ro.monitorIndex===ii&&ro.controlSessionId===ao&&ro.controlCommandId===oo&&ro.captureGeneration===io?ro:null,rs=s.useCallback((n,o)=>{const l=String(o.type||"").trim().toLowerCase();return Ks.current&&l!=="keyboard.reset"||!qn.current||!ts||!ba||!ao||!oo||io<=0||n!==ba?!1:bp(n,{...o,monitorIndex:ii,controlSessionId:ao,controlCommandId:oo,captureGeneration:io})},[ts,io,oo,ba,ii,ao,bp]),$c=[ba,ao,oo,io,ii,no].join("|"),hu=s.useRef($c);hu.current=$c;const Vc=s.useRef(null),wn=s.useCallback(async(n,o,l,m,d=15e3)=>{if(!no||hu.current!==m)throw new Error("Remote Control changed before the clipboard transfer completed.");const C=await ze(`/api/remote/devices/${encodeURIComponent(ba)}/clipboard`,{method:"POST",timeoutMs:d,body:JSON.stringify({action:n,hubConnectionId:no,operationId:o,binding:{sessionId:ao,commandId:oo,captureGeneration:io,monitorIndex:ii},payload:l})},Y);if(hu.current!==m)throw new Error("Remote Control changed before the clipboard transfer completed.");if(C?.ok===!1)throw new Error(C.error||"Remote clipboard transfer failed.");return C},[io,oo,ba,ii,ao,no,Y]),yp=s.useCallback(async(n,o)=>{const l=window.liveDesk?.clipboard;let m=!1,d=!1;try{await wn("clipboard.prepare",n,{clipboardDirection:"copy"},o),await wn("clipboard.copy",n,{clipboardDirection:"copy"},o),d=!0;const C=await wn("clipboard.copy.begin",n,{},o),v=Fd(C.manifest,n);if(l?.beginWrite&&l.writeChunk&&l.commitWrite){await l.beginWrite(v),m=!0;for(const S of v.items)for(const y of rd(S.size)){const w=await wn("clipboard.copy.chunk",n,{itemIndex:S.itemIndex,offset:y.offset,maxBytes:vl},o),Z=gh(String(w.dataBase64||""));if(Number(w.itemIndex)!==S.itemIndex||Number(w.offset)!==y.offset||Number(w.bytes)!==y.byteLength||Z.byteLength!==y.byteLength||w.final===!0!==y.final)throw new Error("Remote clipboard chunk did not match the requested file range.");await l.writeChunk({operationId:n,itemIndex:S.itemIndex,offset:y.offset,dataBase64:String(w.dataBase64||""),final:y.final})}await l.commitWrite(n),m=!1}else{if(v.contentKind==="files")throw new Error("Multiple files require the VuvoDesk desktop app.");const S=[];for(const y of v.items){const w=new Uint8Array(y.size);for(const Z of rd(y.size)){const ge=await wn("clipboard.copy.chunk",n,{itemIndex:y.itemIndex,offset:Z.offset,maxBytes:vl},o),D=gh(String(ge.dataBase64||""));if(D.byteLength!==Z.byteLength)throw new Error("Remote clipboard chunk was incomplete.");w.set(D,Z.offset)}if(await db(w)!==y.sha256)throw new Error("Remote clipboard content check failed.");S.push(w)}await Ak({manifest:v,payloads:S})}await wn("clipboard.copy.end",n,{},o),d=!1,j(v.contentKind==="files"?`${v.items.length} remote file${v.items.length===1?"":"s"} copied.`:v.contentKind==="image"?"Remote image copied.":"Remote text copied.","success")}catch(C){throw m&&await l?.cancelWrite?.(n).catch(()=>{}),d&&await wn("clipboard.copy.end",n,{},o).catch(()=>{}),C}},[wn,j]),wp=s.useCallback(async(n,o)=>{const l=window.liveDesk?.clipboard;let m=null,d,C=!1;try{l?.readSnapshot&&l.readChunk?d=Fd(await l.readSnapshot(n),n):(m=await Rk(n),d=m.manifest),await wn("clipboard.prepare",n,{clipboardDirection:"paste",manifest:d},o),C=!0,await wn("clipboard.paste.begin",n,{manifest:d},o);for(const y of d.items)for(const w of rd(y.size)){const Z=l?.readChunk?await l.readChunk({operationId:n,itemIndex:y.itemIndex,offset:w.offset,maxBytes:w.byteLength||vl}):{operationId:n,itemIndex:y.itemIndex,offset:w.offset,byteLength:w.byteLength,dataBase64:xk(m.payloads[y.itemIndex].subarray(w.offset,w.offset+w.byteLength)),final:w.final};if(Z.offset!==w.offset||Z.byteLength!==w.byteLength||Z.final!==w.final)throw new Error("Local clipboard changed during transfer.");const ge=await wn("clipboard.paste.chunk",n,{itemIndex:y.itemIndex,offset:w.offset,dataBase64:Z.dataBase64,final:w.final},o);if(Number(ge.itemIndex)!==y.itemIndex||Number(ge.offset)!==w.offset||Number(ge.bytes)!==w.byteLength||ge.final===!0!==w.final)throw new Error("Remote clipboard did not confirm the requested file range.")}await wn("clipboard.paste",n,{clipboardDirection:"paste"},o);const v=Date.now()+Ck;let S=!1;for(;Date.now()<v;){const y=await wn("clipboard.operation.status",n,{},o,Math.max(250,v-Date.now())),w=String(y.status||"").toLowerCase();if(["completed","complete","applied","pasted"].includes(w)){S=!0;break}if(["failed","cancelled","expired"].includes(w))throw new Error(`Remote clipboard paste ${w}.`);await new Promise(Z=>window.setTimeout(Z,Sk))}if(!S)throw new Error("Remote clipboard paste confirmation timed out.");C=!1,j(d.contentKind==="files"?`${d.items.length} file${d.items.length===1?"":"s"} pasted on the remote computer.`:d.contentKind==="image"?"Image pasted on the remote computer.":"Text pasted on the remote computer.","success")}catch(v){throw C&&await wn("clipboard.paste.cancel",n,{},o).catch(()=>{}),v}finally{await l?.releaseRead?.(n).catch(()=>{})}},[wn,j]),Sp=s.useCallback(async n=>{if(!ts||!Wc||ns!=="open"||!no){j("Remote input is not ready for clipboard transfer.","error");return}if(Vc.current){j("Another clipboard transfer is still running.");return}const o=SC(n),l=$c;Vc.current={operationId:o,direction:n,bindingKey:l};try{Bn(n==="copy"?"Copying from the remote computer…":"Pasting on the remote computer…"),n==="copy"?await yp(o,l):await wp(o,l)}catch(m){j(m instanceof Error?m.message:String(m),"error")}finally{Vc.current?.operationId===o&&(Vc.current=null)}},[$c,ts,yp,no,Wc,ns,wp,j,Bn]),Ir=qt&&qn.current&&ts&&ns==="open"&&Wc&&!!no,gu={shiftKey:Ri.includes("ShiftLeft"),ctrlKey:Ri.includes("ControlLeft"),altKey:Ri.includes("AltLeft"),metaKey:Ri.includes("MetaLeft")},cr=s.useCallback(n=>_s.current.enqueueStop(n),[]),so=s.useCallback(n=>_s.current.enqueueStart(n),[]),un=s.useCallback((n,o=Os.current)=>(Ls.current=n,Os.current=n?String(o||""):"",om.current=Ll.current,Ro.current+=1,Ro.current),[]),lr=s.useCallback((n,o,l)=>om.current===Ll.current&&p0({generation:n,currentGeneration:Ro.current,enabled:Ls.current,deviceId:o,currentDeviceId:Os.current,documentVisible:qn.current,presentationVisible:Ol.current,streamId:l,currentStreamId:dt.current.get(o)||""}),[]),Jn=s.useCallback(async(n,o,l)=>{if(!o)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const d=await(v=>ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/stop`,{method:"POST",body:JSON.stringify({...v?{streamId:v}:{},reason:l})},Y))(o),C=f0(d);if(C.staleOwner)return d;if(!C.confirmed)throw new Error(d?.error||"Remote audio capture stop was not confirmed.");return d},[Y]),bu=s.useCallback(async(n,o)=>{const l=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:o})},Y);if(l?.ok===!1||l?.captureStopConfirmed!==!0&&l?.alreadyStopped!==!0)throw new Error(l?.error||"Remote audio stop-all was not confirmed.");return l},[Y]),lv=s.useCallback(n=>{const o=Ro.current,l=dt.current.get(n)||"";return cr(()=>Jn(n,l,"remote-audio-automatic-restart")).then(()=>so(async()=>{if(o!==Ro.current||!Ls.current||Os.current!==n||!qn.current||!Ol.current||!pt||!sr||(Na.current||X?.deviceId||"")!==n)return"";const m=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(dt.current.set(n,m),!lr(o,n,m))return dt.current.delete(n),"";const d=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},Y);if(d?.ok===!1)throw dt.current.get(n)===m&&dt.current.delete(n),new Error(d.error||"Remote audio restart failed.");return lr(o,n,m)?m:(await Jn(n,m,"remote-audio-stale-restart-compensation"),dt.current.get(n)===m&&dt.current.delete(n),"")}))},[so,cr,pt,Y,lr,sr,X?.deviceId,Jn]),Cp=X?.deviceId&&dt.current.get(X.deviceId)||"",uv=s.useCallback(async(n,o,l)=>{un(!1),Fr(!1),await cr(()=>Jn(n,o,l)),dt.current.get(n)===o&&dt.current.delete(n)},[cr,un,Jn]),{state:vu,lastFrame:yu,stats:Rt,error:wu}=fC(X?.deviceId||"",qt&&Qm&&Zt,Y,Ob,fn||Ut||ec.current,Cp,lv,uv,O),co=s.useRef(new Map);s.useEffect(()=>{const n=[["hub",je],["registry",de],["license",He],["wall-stream",Fc],["control-stream",eo],["control-decode",Pt],["remote-input",vp],["remote-audio",wu]];for(const[o,l]of n){const m=String(l||"").trim(),d=ke.current;if(o==="wall-stream"&&m==="CONTROL_CAPTURE_OWNS_DEVICE"&&!!d&&la.current===d.deviceId){co.current.delete(o);continue}if(o==="hub"&&et?.requiresHubRestart&&et.stage==="updating"){co.current.delete(o);continue}if(o==="hub"&&W&&(kt?.kind==="signal-service-unavailable"||kt?.kind==="p2p-unavailable")){co.current.delete(o);continue}if(!m){const S=co.current.get(o);co.current.delete(o),o==="remote-input"&&S&&mm(S.noticeId,S.message);continue}if(co.current.get(o)?.message===m)continue;const v=j(m);co.current.set(o,{message:m,noticeId:v})}},[wu,mm,Pt,eo,je,kt?.kind,vp,He,W,de,j,Fc,et]);const zc=X?.deviceId||"",kp=X?_n(X,gt[zc]):0;s.useEffect(()=>{if(sa||!kn||!Cr||!Ir||!zc)return;const n=jC(),o=zc,l=kp,m=D=>{if(!D)return!1;const fe=rs(o,{...D,monitorIndex:l});return!fe&&D.type!=="keyboard.reset"&&(n.reset("browser-input-send-rejected"),Fs([])),fe},d=(D,fe)=>{if(Ks.current)return;const Ne=D.target,We=Ne?.tagName?.toLowerCase(),Je=Ne?.isContentEditable||We==="input"||We==="textarea"||We==="select",Ue=n.isPressed(D);if(Je&&(fe==="keydown"||!Ue))return;const Yt=fe==="keydown"?wC(D,Mk()):"";if(Yt&&(Yt==="copy"?hp:Yt==="paste"?gp:!1)){D.preventDefault(),D.stopPropagation();const ls=n.reset("remote-clipboard-shortcut",!0);ls&&m(ls),Fs([]),Sp(Yt);return}const fo=n.event(D,fe);fo&&(D.preventDefault(),D.stopPropagation(),m(fo))},C=D=>d(D,"keydown"),v=D=>d(D,"keyup"),S=(D,fe=!1)=>{const Ne=n.reset(D,fe);Ne&&(m(Ne),Fs([]))};Dl.current=D=>{const fe=n.snapshot().latchedCodes.includes(D),Ne=n.modifier(D,!fe);Ne&&(m(Ne),Fs(We=>fe?We.filter(Je=>Je!==D):[...We.filter(Je=>Je!==D),D]))};const y=D=>{const fe=ol(D);if(!fe)return!1;const Ne=n.snapshot(),We={...fe,shiftKey:Ne.shiftKey,ctrlKey:Ne.ctrlKey,altKey:Ne.altKey,metaKey:Ne.metaKey},Je=n.event(We,"keydown");if(!Je||!m(Je))return!1;const Ue=n.event(We,"keyup");return!!Ue&&m(Ue)};Ai.current={sendKey:y,sendText:D=>{let fe=!1;const Ne=String(D??"").split(/(\r\n|\r|\n)/);for(const We of Ne)if(We){if(We==="\r"||We===`
|
|
181
181
|
`||We===`\r
|
|
182
|
-
`){if(!y("Enter"))return!1;fe=!0;continue}for(const Xe of NC(We)){const Ue=n.snapshot();if(!m({type:"text",text:Xe,repeat:!1,pressedCodes:Ue.pressedCodes,shiftKey:Ue.shiftKey,ctrlKey:Ue.ctrlKey,altKey:Ue.altKey,metaKey:Ue.metaKey}))return!1;fe=!0}}return fe}};const w=()=>S("browser-window-blur"),J=()=>S("browser-page-hidden"),ge=()=>{document.visibilityState==="hidden"&&S("browser-document-hidden")};return window.addEventListener("keydown",C,!0),window.addEventListener("keyup",v,!0),window.addEventListener("blur",w),window.addEventListener("pagehide",J),document.addEventListener("visibilitychange",ge),()=>{window.removeEventListener("keydown",C,!0),window.removeEventListener("keyup",v,!0),window.removeEventListener("blur",w),window.removeEventListener("pagehide",J),document.removeEventListener("visibilitychange",ge),Dl.current=null,Ai.current=null,S("control-keyboard-owner-changed",!0)}},[sa,Cr,Ir,zc,Cp,kn,fp,hp,wp,rs]);const kp=(n,o)=>{const l=ol(n);if(!l)return!1;const m=performance.now(),d=tm.current;return d.key===l.key&&d.source!==o&&m-d.at<80?!0:(tm.current={key:l.key,source:o,at:m},Ai.current?.sendKey(l.key)??!1)},Mp=s.useCallback(n=>{Ol.current=n;const o=Na.current||X?.deviceId||"";if(!Zt||!o)return;const l=un(Ls.current,o);if(!n){const d=dt.current.get(o)||"";cr(async()=>{await Jn(o,d,"remote-audio-document-hidden")}).catch(C=>{(Na.current||X?.deviceId||"")===o&&(un(!1),dt.current.delete(o),Fr(!1),B(C instanceof Error?C.message:String(C)))});return}const m=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;dt.current.set(o,m),so(async()=>{if(!lr(l,o,m)||!pt||!sr||(Na.current||X?.deviceId||"")!==o)return;const d=await ze(`/api/remote/devices/${encodeURIComponent(o)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},K);if(d?.ok===!1)throw new Error(d.error||"Remote audio presentation resume failed.");lr(l,o,m)||(await Jn(o,m,"remote-audio-stale-presentation-compensation"),dt.current.get(o)===m&&dt.current.delete(o))}).catch(d=>{qn.current&&l===Ro.current&&(un(!1),dt.current.delete(o),Fr(!1),B(d instanceof Error?d.message:String(d)))})},[Zt,so,cr,un,pt,K,lr,sr,X?.deviceId,B,Jn]);s.useEffect(()=>{const n=v=>{const S=qn.current;v!==S&&(qn.current=v,rr.current+=1,ou.current={active:v&&Go.current,epoch:rr.current},v||(Hc(),Bc(rr.current)),Mp(v),Db(v),ve.current&&$({type:"visibility.changed",component:"document",state:v?"visible":"hidden",reason:"presentation-visibility-commit",details:{previous:S?"visible":"hidden",presentationOwnershipEpoch:rr.current}}),v&&!S&&(Ob(y=>y+1),sc.current=performance.now()))},o=Yy({readVisible:()=>document.visibilityState==="visible",initialCommittedVisible:qn.current,commitVisibility:n,schedule:(v,S)=>window.setTimeout(v,S),cancel:v=>window.clearTimeout(v)}),l=()=>o.handleVisibilityChange(),m=()=>o.handlePageHide(),d=()=>o.handleForegroundHint(),C=()=>o.handleForegroundHint();return document.addEventListener("visibilitychange",l),window.addEventListener("pagehide",m),window.addEventListener("pageshow",d),window.addEventListener("focus",C),o.handleForegroundHint(),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("pagehide",m),window.removeEventListener("pageshow",d),window.removeEventListener("focus",C),o.dispose()}},[$,Hc,Bc,Mp]),s.useEffect(()=>{if(!eh({presentationOwnerActive:!!g&&(be==="connecting"||be==="active"||be==="warm"),desiredDeviceCount:g?1:0}))return;const n=g,o=ft("control",n),l=window.setInterval(()=>{const m=performance.now();if(document.visibilityState!=="visible"||m-sc.current<dd)return;const d=Hr.current.get(o)||0,C=hr.current.get(o)||0,v=da.current.get(o)||0,S=Wr.current.get(o)||m;Wr.current.has(o)||Wr.current.set(o,S);const y=d<=0,w=y?m-S>Kk:m-d>pd,J=Zf({lastReceivedAt:d,lastPaintedAt:C,now:m,staleAfterMs:pd}),ge=Jf({paintStale:J,lastRecoveryAt:gr.current.get(o)||0,now:m,recoveryCooldownMs:Lh,transportRecoveryAfterMs:Oh});if(!w&&ge==="reset-decoder"&&ri(n,"control","decoder-paint-stale")||!w&&ge==="wait")return;if(!(w||ge==="recover-transport")){J&&ri(n,"control","decoder-paint-stale"),y&&m-S>Gk&&!Fn.current.has(o)&&Zi([n],"control-frame-socket-recovery")&&(Fn.current.set(o,m),Ft("control",n,"socket-reconnect","control-first-frame-socket-recovery",Nt.current.get(o)||0));return}const fe=Fn.current.get(o)||0;if(fe<=0){Zi([n],"control-frame-socket-recovery")&&(Fn.current.set(o,m),Ft("control",n,"socket-reconnect",w?"control-receive-stale":"control-paint-stale",Nt.current.get(o)||0));return}if(m-fe<Dh)return;const Ne=ma.current.get(o)||0;if(Ne>0){if(m-Ne<Eh)return;ma.current.delete(o)}const We=Nt.current.get(o)||0,Xe=Le.find(Xr=>Xr.deviceId===n)||tn,Ue=Gh(Xe?.platform);if(!w&&ge==="recover-transport"&&Ue==="mode1-jpeg"&&es("mac-control-paint-timeout"))return;if(We>=Qk){if(es(y?"no first frame":"stale stream"))return;_e(!1),gn(!1),Un.current=n,Ft("control",n,"terminal",y?"control-first-frame-restart-limit":"control-stream-restart-limit",We),xe("error");return}if(m-v<_h(Yk,We))return;const Yt=y?"control-first-frame-timeout":ge==="recover-transport"?"control-paint-timeout":"control-receive-stale";Lc([n],Yt)&&(Fn.current.delete(o),gr.current.delete(o),da.current.set(o,m),ma.current.set(o,m),Wr.current.set(o,m),Nt.current.set(o,We+1),Vr.current.delete(o),Ft("control",n,"native-restart",Yt,We+1))},650);return()=>window.clearInterval(l)},[Le,tn,g,be,es,Zi,Ft,ri,Lc]),s.useEffect(()=>{!Pt||g&&rt.current[g]||Gn!=="mode3-h264-hw"||es(Pt)||(_e(!1),gn(!1),Un.current=ke.current?.deviceId||"",xe("error"))},[Pt,g,Gn,es]),s.useEffect(()=>{!Re||!g||rt.current[g]||!eo||(Un.current=g,xe(n=>n==="error"?n:"error"))},[eo,g,Re]),s.useEffect(()=>{if(be!=="error")return;const n=ke.current;if(!n)return;Un.current=n.deviceId,On(za.current,n)||(za.current=n,Wo.current=0);const o=Wo.current,l=o===0?0:Math.min(5e3,500*2**Math.min(o-1,4)),m=window.setTimeout(()=>{On(ke.current,n)&&(++Ht.current,sn.current="",xe("stopping"),Yn(async()=>{if(On(ke.current,n))try{if(!await Xn(n,"control-session-terminal-error"))return;za.current=null,Wo.current=0,Bi.current===n.deviceId?(Bi.current="",Un.current="",xe("idle")):xe("error")}catch(d){if(!On(ke.current,n))return;Wo.current+=1,B(d instanceof Error?d.message:String(d)),xe("error"),xm(C=>C+1)}}))},l);return()=>window.clearTimeout(m)},[be,Pb,Yn,B,Xn]);const as=s.useCallback(n=>{if(!n||Un.current!==n)return!1;const o=ke.current;return++Ht.current,sn.current="",Wo.current=0,o&&o.deviceId===n?(Bi.current=n,za.current=null,xe("error"),xm(l=>l+1),!0):(Bi.current="",Un.current="",za.current=null,xe("idle"),!0)},[]);s.useEffect(()=>{if(!eh({presentationOwnerActive:De.autoStartLive,desiredDeviceCount:Gt.length}))return;const n=window.setInterval(()=>{const o=performance.now();if(document.visibilityState!=="visible"||o-sc.current<dd)return;const l=1e3/Math.max(1,Mc||Hn||1),m=Math.max(Fh,Math.ceil(l*4)),d=[],C=[];for(const v of Gt){if(C.length+d.length>=eM)break;const S=ft("wall",v),y=Hr.current.get(S)||0,w=y<=0,J=$r.current.get(S)||o;$r.current.has(S)||$r.current.set(S,J);const ge=da.current.get(S)||0,D=hr.current.get(S)||0,fe=w||o-y>m,Ne=Zf({lastReceivedAt:y,lastPaintedAt:D,now:o,staleAfterMs:m}),We=Jf({paintStale:Ne,lastRecoveryAt:gr.current.get(S)||0,now:o,recoveryCooldownMs:Lh,transportRecoveryAfterMs:Oh});if(!fe&&We==="reset-decoder"&&ri(v,"wall","decoder-paint-stale")||!fe&&We==="wait")continue;if(!(fe||We==="recover-transport")){Ne&&ri(v,"wall","decoder-paint-stale");continue}const Ue=Fn.current.get(S)||0;if(Ue<=0&&(!w||o-J>Xk)){d.push(v);continue}if(w&&o-J<=Nh||Ue>0&&o-Ue<Dh)continue;const Yt=Nt.current.get(S)||0;o-ge>=_h(Jk,Yt)&&C.push(v)}if(d.length>0&&mu(d,"wall-frame-socket-recovery"))for(const v of d){const S=ft("wall",v);Fn.current.set(S,o),Ft("wall",v,"socket-reconnect","wall-frame-socket-recovery",Nt.current.get(S)||0)}if(C.length>0&&mu(C,"wall-frame-lane-retry"))for(const v of C){const S=ft("wall",v),y=(Nt.current.get(S)||0)+1;Ft("wall",v,"lane-retry","wall-frame-lane-retry",y),Fn.current.set(S,o),gr.current.delete(S),da.current.set(S,o),$r.current.set(S,o),Hr.current.delete(S),hr.current.delete(S),Nt.current.set(S,y),Vr.current.delete(S)}},Zk);return()=>window.clearInterval(n)},[Mc,Gt,mu,Ft,ri,De.autoStartLive,Hn]),s.useEffect(()=>{No(Hn),Vi.current=Date.now(),br.current=0,vr.current=0,ar.current=0,zi.current=0,Ui.current=""},[Hn,De.frameMode,De.adaptiveLoadShedding]),s.useEffect(()=>{Rw({h264DecodeAcceleration:De.h264DecodeAcceleration})},[De.h264DecodeAcceleration]),s.useEffect(()=>{if(!pt||Re||Bt==="list"||!De.visibleOnlyLive){Qs([]);return}const n=Lm.current;if(!n||typeof IntersectionObserver>"u"){Qs(wc);return}const o=Array.from(n.querySelectorAll("[data-live-device-id]"));if(o.length===0){Qs([]);return}const l=new Map,m=XC(n,de),d=()=>{const v=hd(o.map(S=>String(S.dataset.liveDeviceId||"")).filter(S=>(l.get(S)||0)>0));Qs(S=>fd(S,v)?S:v)},C=new IntersectionObserver(v=>{for(const S of v){const y=String(S.target.dataset.liveDeviceId||"");y&&l.set(y,S.isIntersecting?S.intersectionRatio||.01:0)}d()},{root:m,rootMargin:de?WC:ur.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return o.forEach(v=>C.observe(v)),d(),()=>C.disconnect()},[wc,pt,de,Re,fa,De.visibleOnlyLive,Bt]),s.useEffect(()=>{if(!De.adaptiveLoadShedding||!De.autoStartLive||Gt.length===0){vr.current=0,ar.current=0,zi.current=0,Ui.current="";return}const n=Hn;if(Qi!=="open"||Ja.sampleMs<500||Ja.lastUpdatedAt<=0||zi.current===Ja.lastUpdatedAt)return;zi.current=Ja.lastUpdatedAt;const o=Date.now(),l=Gt.map(D=>{const fe=rc[ft("wall",D)];return{deviceId:D,receive:fe,paint:nc[ft("wall",D)],intentionalIdle:S0(fe?.lastFrame,o)}});if(!l.every(({receive:D,paint:fe})=>{const Ne=D?.lastFrame,We=Math.max(0,Number(Ne?.requestedFps||0)),Xe=Ne?er(Ne):"";return w0({receiveSampleMs:Number(D?.sampleMs||0),paintSampleMs:Number(fe?.sampleMs||0),currentGenerationVerified:Ne?.currentGenerationVerified===!0,frameRequestedFps:We,adaptiveFps:Pn})&&fe?.bindingKey===Xe})){vr.current=0,ar.current=0,br.current=0;return}const d=[Pn,...l.map(({deviceId:D,receive:fe,intentionalIdle:Ne})=>`${D}:${er(fe.lastFrame)}:${Ne?"idle":"active"}`).sort()].join("|");if(Ui.current!==d){Ui.current=d,vr.current=o,ar.current=0,br.current=0;return}if(!vr.current){vr.current=o,ar.current=0;return}if(o-vr.current<ur.downshiftStableSampleMs)return;const C=l.filter(D=>!D.intentionalIdle),v=C.reduce((D,{receive:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0)),0),S=C.reduce((D,{receive:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0))*Math.max(0,Number(fe?.averageFrameBytes||0)),0),y=C.reduce((D,{paint:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0)),0),w=Math.max(0,...C.map(({receive:D})=>Number(D?.maxIntervalMs||0))),J=Math.max(0,...C.map(({paint:D})=>Number(D?.p95IntervalMs||0))),ge=C.length===0?{overloaded:!1,healthyForRecovery:!0}:y0({directDeviceCount:C.length,requestedFps:Pn,measuredFramesPerSecond:v,measuredPaintFramesPerSecond:y,measuredBytesPerSecond:S,maxBytesPerSecond:ur.maxWallBytesPerSecond,worstReceiveGapMs:w,worstPaintP95Ms:J,maxFrameGapMs:ur.maxFrameGapMs});if(ge.overloaded){if(br.current=0,ar.current+=1,ar.current<ur.downshiftConsecutiveSamples)return;const D=ur.minFps;if(o-Vi.current>=ur.downshiftCooldownMs&&Pn>D){const fe=Math.max(D,CM(Pn,D));fe<Pn&&(No(fe),Vi.current=o,vr.current=0,ar.current=0)}return}if(ar.current=0,!ge.healthyForRecovery||Pn>=n){ge.healthyForRecovery||(br.current=0);return}if(!br.current){br.current=o;return}if(o-br.current>=ur.recoveryCooldownMs){const D=Math.min(n,kM(Pn,n));D>Pn&&(No(D),Vi.current=o,br.current=0,vr.current=0,ar.current=0)}},[Pn,Gt.length,Gt,nc,rc,Qi,Ja.lastUpdatedAt,Ja.sampleMs,De.adaptiveLoadShedding,De.autoStartLive,De.frameMode,Hn]),s.useEffect(()=>{const n=new URLSearchParams(window.location.search).get("checkout");if(n==="success"){B("Checkout returned. Waiting for Dodo confirmation."),vt();const o=window.setInterval(()=>{vt()},4e3),l=window.setTimeout(()=>{window.clearInterval(o)},45e3);return()=>{window.clearInterval(o),window.clearTimeout(l)}}n==="cancelled"&&B("Checkout cancelled.")},[vt]),s.useEffect(()=>{!pt&&kn&&jn(!1),!pt&&Zt&&(un(!1),Fr(!1))},[Zt,kn,un,pt]),s.useEffect(()=>{Zt&&(!X||!sr)&&(un(!1),Fr(!1))},[Zt,un,sr,X]),s.useEffect(()=>{const n=X?.deviceId||"",o=Na.current;if(Na.current=n,!o||o===n)return;const l=un(Zt,n),m=n?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";n&&Zt&&dt.current.set(n,m);let d=!0;const C=dt.current.get(o)||"";return(async()=>{try{await cr(async()=>{await Jn(o,C,"remote-audio-device-switch"),dt.current.delete(o)}),await so(async()=>{if(!d||!lr(l,n,m)||!n||!pt||!sr)return;const v=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},K);if(v.ok===!1)throw new Error(v.error||"Remote audio start failed.");lr(l,n,m)||(await Jn(n,m,"remote-audio-stale-device-switch-compensation"),dt.current.get(n)===m&&dt.current.delete(n))})}catch(v){d&&(un(!1),dt.current.delete(n),Fr(!1),B(v instanceof Error?v.message:String(v)))}})(),()=>{d=!1}},[Zt,so,cr,un,pt,K,lr,sr,X?.deviceId,Jn]),s.useEffect(()=>{const n=Le.map(d=>d.deviceId),o=new Set(n),l=new Map(Le.map(d=>[d.deviceId,d])),m=new Map;for(const d of Le){const C=iM(d);if(!C)continue;const v=dr(d.status),S=[d.lastStatusAt,v.capturedAt,v.collectedAt,v.timestamp,v.updatedAt].find(w=>typeof w=="string"&&w.trim()),y=OC(Fi.current[d.deviceId],C,S);y&&(Fi.current[d.deviceId]=y,m.set(d.deviceId,y),Kg({platform:d.platform,topologyFingerprint:C,consecutiveTopologySamples:y.consecutiveSamples})&&(km.current[d.deviceId]=C))}for(const d of Object.keys(Fi.current))o.has(d)||delete Fi.current[d];At(d=>{const C=d.filter(v=>o.has(v));return fd(d,C)?d:C}),Jt(d=>d&&o.has(d)?d:""),Vt(d=>d&&o.has(d)?d:""),Vl(d=>{let C=!1;const v={};for(const[S,y]of Object.entries(d)){const w=l.get(S);if(!w){v[S]=y;continue}const J=m.get(S)||Fi.current[S],ge=_C({requestedIndex:y,monitorCount:ka(w),platform:w.platform,topologyFingerprint:J?.fingerprint||"",consecutiveTopologySamples:J?.consecutiveSamples||0});v[S]=ge,ge!==y&&(C=!0)}return C?v:d}),nu(d=>{const C=d.filter(v=>o.has(v));return fd(d,C)?d:C})},[Le,gc]),s.useEffect(()=>{jb([]),Hb(!1)},[Yr]),s.useEffect(()=>{!Ga||Uo!=="selected"||qo.length>0||cn.length===0||nu(cn.map(n=>n.deviceId))},[cn,qo.length,Uo,Ga]),s.useEffect(()=>{try{localStorage.setItem(ab,Oo)}catch{}},[Oo]),s.useEffect(()=>{mM(De)},[De]),s.useEffect(()=>{fM(on)},[on]),s.useEffect(()=>{uM(gt,km.current)},[Le,gt]);const Uc=s.useCallback(async()=>{const n=new Set(L);n.add(In);try{const C=await ze("/api/remote/status",void 0,In);Xp({endpoint:C.agentEndpoint,endpoint_candidates:[...C.agentEndpointCandidates||[],...C.hostTargetEndpointCandidates||[]]}).forEach(v=>n.add(v))}catch{}const o=[...n].sort((C,v)=>{const S=y=>{const w=fl(y);return w==="local"?0:w==="loopback"?1:2};return S(C)-S(v)||C.localeCompare(v)});let l=!1,m="",d=!1;try{for(const C of o){const v=fl(C);try{if(await ze("/api/health",void 0,C),v==="local")return we(!0),hi(!0),C;v==="loopback"&&(l=!0,m=C)}catch{v==="local"&&(d=!0)}}return l?(d&&B("VuvoDesk Hub is reachable on this PC, but not through the LAN address yet. Restart VuvoDesk Hub to bind 5179 on the network."),we(!0),hi(!0),m||In):(we(!1),hi(!1),"")}catch{return we(!1),hi(!1),""}},[L]),Qr=async()=>{if(Mn("auth"),Or(!1),window.liveDesk?.auth?.signInWithGoogle){const m=window.liveDesk.auth.signInWithGoogle();Uc();const d=await m;d?.ok===!1&&(B(d.error||"VuvoDesk could not open the system browser for Google sign-in."),Mn(""));return}const n=Ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:ty(window.location.href,ny)}});Uc();const{data:o,error:l}=await n;l&&(B(l.message),Mn(""))},uv=async()=>{Mn("auth"),Or(!1);const n=!!window.liveDesk?.auth?.signOut;try{if(n)(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&B("Signed out locally. The VuvoDesk runtime could not be reached to clear its session.","error");else{await k();const{error:o}=await Ct.auth.signOut({scope:"local"});if(o)throw o}}catch(o){B(`Sign-out is not complete: ${o instanceof Error?o.message:String(o)}. Remote access stays blocked; open Account and retry.`,"error")}Mn("")},xp=s.useCallback(async(n={})=>{const o=n.silent===!0,l=n.takeover===!0,m=n.requestLocalAccess===!0;if(!r?.user){o||B("Sign in before publishing this host.","error");return}if(W){o||B("Open VuvoDesk on the Hub computer to sync or configure that Hub.","error");return}if(ae){o||B("Only the Team owner can sync or configure the Hub.","error");return}if(!G){o||B("Choose a workspace before syncing the Hub.","error");return}if(ru.current)return;const d=G,C=O,v=()=>te.current===C&&Q(d),S=()=>{if(!v())throw new Error("The active VuvoDesk workspace changed while Hub sync was running.")};ru.current=!0,o||(Mn("host"),Bn("Hub · 1/3 · Checking the local runtime…"));try{const y=m?await Uc():"";S();const w=y||K||In,J=z||await ze("/api/remote/status",void 0,w);if(S(),!J.started)throw new Error("Start VuvoDesk on this computer before syncing the server.");o||Bn("Hub · 2/3 · Publishing the current workspace endpoint…"),S();const ge=await ze("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:l})},w);if(S(),!ge.ok)throw new Error(ge.error||"host-target-failed");if(!o){Bn("Hub · 3/3 · Verifying the endpoint and lease renewal…");const D=await ze("/api/hub/status",void 0,w);if(S(),!D.hostTargetActive)throw new Error(D.hostTargetLease?.lastError||"host-target-not-active-after-sync");const fe=D.hostTargetEndpoint||D.agentEndpoint||"endpoint ready",Ne=Number(D.connectedDeviceCount||0),We=Ne>0?`${Ne} client${Ne===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";B(`Hub ready · ${fe} · lease auto-renewal active. ${We}`,"success"),(m||Ve)&&(we(!0),hi(!0)),Te()}S(),le()}catch(y){if(!o){if(!v()){B("Hub sync stopped because the active workspace changed.","info");return}const w=y instanceof Error?y.message:String(y);w.includes("local network access")&&(we(!1),hi(!1)),B(`Hub setup failed · ${w}`,"error")}}finally{ru.current=!1,o||Mn(y=>y==="host"?"":y)}},[G,Q,K,Ve,W,Te,le,Uc,r,B,Bn,z,ae,O]),os=s.useCallback((n=!0)=>{et!=="host"&&(_l(!1),n&&window.requestAnimationFrame(()=>lm.current?.focus()))},[et]),dv=s.useCallback(()=>{if(et!=="host"){if(ae){B("Only the Team owner can sync or configure the Hub.","error");return}lm.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Or(!1),_l(!0)}},[et,B,ae]),mv=s.useCallback(()=>{_l(!1),xp({takeover:!0,requestLocalAccess:!0})},[xp]);s.useEffect(()=>{if(!Po)return;const n=window.requestAnimationFrame(()=>cm.current?.focus()),o=m=>{m.target instanceof Element&&m.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||os(!1)},l=m=>{m.key==="Escape"&&os()};return window.addEventListener("pointerdown",o),window.addEventListener("keydown",l),()=>{window.cancelAnimationFrame(n),window.removeEventListener("pointerdown",o),window.removeEventListener("keydown",l)}},[os,Po]);const Rp=s.useCallback(async()=>{if(!(!z?.update?.canApply||et==="update")){Mn("update");try{const n=await ze("/api/update/apply",{method:"POST",body:JSON.stringify({})},K||In);if(!n.ok)throw new Error(n.error||"VuvoDesk update could not be started.");const o=[...new Set((n.targets||[]).map(d=>String(d.deviceId||"").trim()).filter(Boolean))],l=!!(n.managerUpdateAvailable||n.clientPackageUpdateAvailable),m=n.state==="hub-restart-requested"?Date.now():void 0;(o.length>0||l)&&fr({operationId:String(n.operationId||`wall-update-${Date.now()}`),targetIds:o,stage:n.state==="clients-updated"?"updated":"updating",requiresHubRestart:l,initialHostInstanceId:String(z.hostInstanceId||""),targetManagerVersion:String(n.latestVersion||z.update?.latestVersion||""),targetClientVersion:String(n.latestClientVersion||z.update?.latestClientVersion||""),restartRequestedAt:m,restartDeadlineAt:m?m+dl:void 0}),Bn(n.state==="hub-restart-requested"?ul:Ch),Te()}catch(n){B(n instanceof Error?n.message:String(n),"error")}finally{Mn("")}}},[et,K,Te,B,Bn,z]);s.useEffect(()=>{const n=Ze,o=z?.update;if(!n||n.stage!=="updating"||!o)return;const l=o.restartResult?.operationId===n.operationId?o.restartResult:null;if(l?.outcome==="restored"){const y=l.error||`The requested Hub ${l.targetVersion||n.targetManagerVersion||"version"} failed verification.`;fr(w=>w?.operationId===n.operationId?{...w,stage:"restored",error:y}:w),B(`VuvoDesk update did not complete. Hub ${l.fallbackVersion||l.appVersion||"the previous version"} was restored. ${y}`,"error");return}if(l?.outcome==="failed"){const y=l.error||"No verified VuvoDesk Hub replacement could be started.";fr(w=>w?.operationId===n.operationId?{...w,stage:"failed",error:y}:w),B(`VuvoDesk Hub update failed. ${y}`,"error");return}if(o.operationId===n.operationId&&o.state==="failed"){const y=o.error||"VuvoDesk update failed before the Hub replacement completed.";fr(w=>w?.operationId===n.operationId?{...w,stage:"failed",error:y}:w),B(y,"error");return}if(o.operationId===n.operationId){if(o.state==="hub-restart-requested"&&!n.restartDeadlineAt){const y=Date.now();fr(w=>w?.operationId===n.operationId?{...w,restartRequestedAt:y,restartDeadlineAt:y+dl}:w),Bn(ul)}!n.requiresHubRestart&&o.state==="clients-updated"&&(fr(y=>y?.operationId===n.operationId?{...y,stage:"updated"}:y),B("VuvoDesk clients updated and reconnected successfully.","success"));return}if(!n.requiresHubRestart)return;const m=z.started===!0&&(!n.initialHostInstanceId||z.hostInstanceId&&z.hostInstanceId!==n.initialHostInstanceId),d=!!o.checkedAt,C=xh(o.currentVersion,n.targetManagerVersion),v=!n.targetClientVersion||xh(o.currentClientVersion,n.targetClientVersion),S=d&&o.state==="idle"&&o.updateAvailable===!1&&C&&v;m&&S&&(fr(y=>y?.operationId===n.operationId?{...y,stage:"updated"}:y),B(`VuvoDesk Hub ${o.currentVersion||l?.appVersion||n.targetManagerVersion} restarted and passed version verification.`,"success"))},[B,Bn,z,Ze]),s.useEffect(()=>{const n=Ze;if(!n||n.stage!=="updating"||!n.requiresHubRestart||n.restartDeadlineAt)return;const o=()=>{const m=Date.now();fr(d=>d?.operationId===n.operationId&&d.stage==="updating"&&!d.restartDeadlineAt?{...d,restartRequestedAt:m,restartDeadlineAt:m+dl}:d),Bn(ul)};if(z?.update?.state==="hub-restart-requested"){o();return}if(!je)return;const l=window.setTimeout(o,Bk);return()=>window.clearTimeout(l)},[je,Bn,z?.update?.state,Ze]),s.useEffect(()=>{const n=Ze;if(!n||n.stage!=="updating"||!n.requiresHubRestart||!n.restartDeadlineAt)return;const o=Math.max(0,n.restartDeadlineAt-Date.now()),l=n.operationId,m=window.setTimeout(()=>{const d=`VuvoDesk Hub did not return and verify ${n.targetManagerVersion||"the requested version"} within ${Math.round(dl/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;fr(C=>C?.operationId===l&&C.stage==="updating"?{...C,stage:"failed",error:d}:C),B(d,"error")},o);return()=>window.clearTimeout(m)},[B,Ze]),s.useEffect(()=>{if(!Ze||Ze.stage!=="updated")return;const n=Ze.operationId,o=window.setTimeout(()=>{fr(l=>l?.operationId===n?null:l)},kh);return()=>window.clearTimeout(o)},[Ze]),s.useEffect(()=>{Ul.current.clear(),zl({})},[Ze?.operationId]),s.useEffect(()=>{if(!Ze||z?.update?.operationId!==Ze.operationId)return;const n=(z.update.targets||[]).filter(l=>l.state==="completed").map(l=>Mh(Ze.operationId,l)).filter(l=>!Ul.current.has(l));if(n.length===0)return;const o=Date.now()+kh;for(const l of n)Ul.current.add(l);zl(l=>({...l,...Object.fromEntries(n.map(m=>[m,o]))}))},[z?.update,Ze]),s.useEffect(()=>{const n=Math.min(...Object.values(Ys));if(!Number.isFinite(n))return;const o=window.setTimeout(()=>{const l=Date.now();zl(m=>Object.fromEntries(Object.entries(m).filter(([,d])=>d>l)))},Math.max(0,n-Date.now()));return()=>window.clearTimeout(o)},[Ys]),s.useEffect(()=>{if(jl!==Ch&&jl!==ul)return;const n=z?.update;if(String(n?.state||"")==="failed"){B(n?.error||"VuvoDesk update failed.","error");return}Ze?.stage==="updated"&&B("")},[jl,B,z?.update?.error,z?.update?.state,Ze?.stage]);const pv=s.useCallback(async()=>{if(!et){Mn("pin");try{const o=await ze("/api/remote/pairing-pin",{method:"POST"},K||In);if(!o.ok)throw new Error(o.error||"pin-rotation-failed");await Te(),B("New PIN published.")}catch(n){B(n instanceof Error?n.message:String(n))}finally{Mn("")}}},[et,K,Te]),Su=s.useCallback(n=>{n&&(Jt(n),At(o=>o.includes(n)?o:[...o,n]))},[]),Cu=s.useCallback(n=>{if(!n)return;const o=Ya.has(n);Jt(l=>o?l===n?"":l:n),At(l=>o?l.filter(m=>m!==n):l.includes(n)?l:[...l,n])},[Ya]),is=s.useCallback(()=>{At([]),Jt("")},[Kr]),Ap=s.useCallback(()=>{At(Le.map(n=>n.deviceId)),Jt("")},[Le]),ku=s.useCallback((n,o)=>{const l=Le.find(d=>d.deviceId===n);if(!l)return;const m=ka(l);if(!(m<=1)&&(Vl(d=>{const C=ys(d[n],m),v=(C+o+m)%m;return v===C?d:{...d,[n]:v}}),Dt("wall",n),Dt("control",n),Li(d=>{if(!d.has(n))return d;const C=new Set(d);return C.delete(n),C}),Wa.current.delete(n),jr.current.delete(n),Re)){const d=as(n);_e(!1),d||xe("connecting"),gn(!1),Vt(n)}},[Le,Dt,as,Re]);s.useEffect(()=>{const n=o=>{if(Ks.current||kn&&Cr&&Ir)return;const l=o.target,m=l?.tagName?.toLowerCase();l?.isContentEditable||m==="input"||m==="textarea"||m==="select"||((o.ctrlKey||o.metaKey)&&o.key.toLowerCase()==="a"&&(o.preventDefault(),Ap()),o.key==="Escape"&&is())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[Cr,is,Ir,kn,Ap]);const fv=(n,o)=>{const l=Le.find(v=>v.deviceId===n),m=l?ka(l):1,d=ys(gt[n],m),C=ys(o,m);if(d!==C&&(Vl(v=>({...v,[n]:C})),Li(v=>{if(!v.has(n))return v;const S=new Set(v);return S.delete(n),S}),Wa.current.delete(n),jr.current.delete(n),ca.current.delete(n),_o.current.delete(n),$a.current.delete(n),Dt("wall",n),Dt("control",n)),Re){const v=as(n);d!==C&&(_e(!1),v||xe("connecting")),gn(!1),Vt(n)}else Su(n)},hv=n=>{const o=Na.current||X?.deviceId||"",l=[...new Set([o,n].filter(Boolean))],m=Zt||l.some(d=>dt.current.has(d));un(!1),Fr(!1);for(const d of l)dt.current.delete(d);l.length!==0&&(async()=>{for(const d of l)await cr(()=>bu(d,"remote-audio-control-entry"))})().catch(d=>{m&&B("Remote audio was muted locally, but Client capture stop was not confirmed: "+(d instanceof Error?d.message:String(d)),"error")})},si=async n=>{const o={requestId:++Fb.current,deviceId:n,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(Br.current=o,!Sr.has(n)){Br.current?.requestId===o.requestId&&(Br.current=null),jn(!1),B(Xo);return}const l=Le.find(d=>d.deviceId===n);if(Nr(l?.platform)&&(l?.capabilities?.controlPermission===!1||l?.capabilities?.accessibilityPermission===!1)){Br.current?.requestId===o.requestId&&(Br.current=null),jn(!1),B("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts VuvoDesk, then restart the Mac client.","error");return}hv(n),as(n),gn(!1),Vt(n),La("control"),jn(!0),B(`Opening remote control${l?` for ${Qt(l)}`:""}.`,"success")},gv=async()=>{if(!X){B("Select a Client before playing audio.");return}if(!pt){B(Xo);return}if(!sr){B("Selected Client does not report remote audio support yet.");return}if(an)return;const n=!Zt,o=n?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:dt.current.get(X.deviceId),l=un(n,X.deviceId);n&&o?dt.current.set(X.deviceId,o):n||dt.current.delete(X.deviceId),To("audio"),Fr(n);try{n?(await cr(()=>bu(X.deviceId,"remote-audio-user-enable-reconcile")),await so(async()=>{if(!o||!lr(l,X.deviceId,o))return;const m=await ze(`/api/remote/devices/${encodeURIComponent(X.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:o,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},K);if(m?.ok===!1)throw new Error(m.error||"Remote audio start failed.");lr(l,X.deviceId,o)||await Jn(X.deviceId,o,"remote-audio-stale-user-start-compensation")})):await cr(()=>bu(X.deviceId,"remote-audio-user-disabled")),B(`${n?"Audio started":"Audio stopped"} for ${Qt(X)}.`,"success")}catch(m){un(!1),n&&dt.current.delete(X.deviceId),Fr(!1),B(m instanceof Error?m.message:String(m),"error")}finally{To("")}},bv=async(n,o)=>{const l=n.deviceId,m=Qt(n),d=String(rt.current[l]||""),C=!!d&&Ao[l]===!0;if(o&&d&&!C)return{ok:!0,skipped:!0,action:"pause",deviceId:l,title:m};if(!o&&!d)return{ok:!0,skipped:!0,action:"resume",deviceId:l,title:m};if(!o&&d.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:l,title:m,error:"Pause is still pending confirmation."};if(o){const J=d||`pending:${Date.now()}:${l}`,ge=ke.current?.deviceId===l?ke.current:null,D=!!ge||g===l,fe=D?++Ht.current:0,Ne=()=>uf({deviceId:l,requestTransitionGeneration:fe,currentTransitionGeneration:Ht.current,actualControlOwner:ke.current}),We=ra.current.get(l);ra.current.set(l,{deviceId:l,monitorIndex:_n(n,gt[l]??We?.monitorIndex),previousControlOwner:ge||We?.previousControlOwner||null}),sm(l,!0),Io(l,!1),js(l,J),fu(l),D&&(sn.current="",xe("paused"));try{const Xe=await ze(`/api/remote/devices/${encodeURIComponent(l)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},K);if(!Xe?.pauseToken)return Fa.current.delete(l),js(l,""),Io(l,!1),ra.current.delete(l),Ne()&&(nt.current=null,ht(null),_e(!1),he(`control-pause-rollback-${Date.now()}-${l}`),xe("connecting")),{ok:!1,action:"pause",deviceId:l,title:m,error:Xe?.error||"video-capture-pause-failed"};const Ue=String(rt.current[l]||"");if(Ue!==J&&Ue!==Xe.pauseToken)return{ok:!1,action:"pause",deviceId:l,title:m,error:"Pause ownership changed before confirmation."};const Yt=Ne(),Xr=Yt&&ke.current?.deviceId===l?ke.current:ge,fo=ra.current.get(l);return fo&&(fo.previousControlOwner=Xr),Yt&&ke.current?.deviceId===l&&(ke.current=null),Yt&&(nt.current=null,ht(null)),js(l,Xe.pauseToken),Yt&&xe("paused"),Xe.ok===!1||Xe.captureStopConfirmed!==!0?(Io(l,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:l,title:m,error:Xe.stopError||Xe.error||"Client capture shutdown was not confirmed."}):(Io(l,!1),{ok:!0,action:"pause",deviceId:l,title:m})}catch(Xe){return Io(l,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:l,title:m,error:Xe instanceof Error?Xe.message:String(Xe)}}}const v=ra.current.get(l),S=v?.previousControlOwner||null,y=g===l&&(S!==null||xn.current?.deviceId===l||be==="paused"),w=y?Ht.current:0;try{sm(l,!1);const J=await ze(`/api/remote/devices/${encodeURIComponent(l)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:d})},K);if(J?.ok===!1)throw new Error(J.error||"video-capture-resume-failed");if(String(rt.current[l]||"")!==d)return{ok:!1,action:"resume",deviceId:l,title:m,error:"Resume ownership changed before confirmation."};const ge=ra.current.get(l)||v,D=ge?.previousControlOwner||S,fe=y&&uf({deviceId:l,requestTransitionGeneration:w,currentTransitionGeneration:Ht.current,actualControlOwner:ke.current});if(js(l,""),Io(l,!1),ra.current.delete(l),fe){const Ne=++Ht.current;sn.current="";const We=zu(l,Ne,{sessionId:n.sessionId||D?.sessionId,monitorIndex:_n(n,gt[l]??ge?.monitorIndex)});ke.current=We,Qn(We),Un.current="",za.current=null,nt.current=null,ht(null),Ie(""),zt(""),_e(!1),Dt("control",l);const Xe=`control-video-resume-${Ne}-${l}`;he(Xe),U(l),xe("connecting")}else Dt("wall",l);return{ok:!0,action:"resume",deviceId:l,title:m}}catch(J){return Fa.current.delete(l),{ok:!1,action:"resume",deviceId:l,title:m,error:J instanceof Error?J.message:String(J)}}},vv=async()=>{if(Ki.length===0){B("Select one or more Clients before pausing video.");return}if(Dn.length===0){B(Xo);return}if(an)return;const n=Dn.some(l=>{const m=String(rt.current[l.deviceId]||"");return!m||m.startsWith("pending:")||Ao[l.deviceId]===!0}),o=Dn.filter(l=>{const m=String(rt.current[l.deviceId]||"");return n?!m||m.startsWith("pending:")||Ao[l.deviceId]===!0:!!m});if(o.length===0){B(n?"Selected Clients are already paused.":"Selected Clients are already playing.");return}To("video");try{const l=await Promise.all(o.map(w=>bv(w,n)));Te();const m=l.filter(w=>w.ok&&!w.skipped),d=l.filter(w=>!w.ok&&w.unconfirmed),C=l.filter(w=>!w.ok&&!w.unconfirmed),v=Dn.length-o.length+l.filter(w=>w.skipped).length,S=Ki.length-Dn.length,y=n?"pause":"resume";if(C.length>0||d.length>0){const w=C.slice(0,2).map(J=>`${J.title}: ${J.error||"unknown error"}`).join(" · ");B([`Video ${y} completed for ${m.length}/${o.length} Clients.`,d.length>0?`${d.length} Client capture stop${d.length===1?"":"s"} remain unconfirmed.`:"",w,S>0?`${S} selected Client${S===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}B([`Video ${n?"paused":"resumed"} for ${m.length} Client${m.length===1?"":"s"}.`,v>0?`${v} already ${n?"paused":"playing"}.`:"",S>0?`${S} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{To("")}},yv=n=>{const o=n instanceof Error?n.message:String(n);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(o)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(o)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(o)?"This Client needs a newer VuvoDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(o)?"The Client disconnected before the action could be sent.":o},Mu=async n=>{if(!X||an)return;const o=X,m={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[n];if(window.confirm(`${m} ${Qt(o)}? Unsaved work on that computer may be lost.`)){To(n),B(`Sending ${m.toLowerCase()} request to ${Qt(o)}...`);try{const d=await ze(`/api/remote/devices/${encodeURIComponent(o.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:n})},K);if(!d.ok)throw new Error(d.error||"The remote action could not be sent.");B(`${m} request sent to ${Qt(o)}.`,"success"),Te()}catch(d){B(yv(d),"error")}finally{To("")}}},Ip=async(n,o,l="files")=>{const m=n.filter(S=>S.file.size>=0);if(m.length===0)return{files:0,bytes:0};if(!pt)throw new Error(Xo);if(o.length===0)throw new Error("Select at least one connected Client.");const d=crypto.randomUUID(),C=m.reduce((S,y)=>S+y.file.size,0);let v=0;pa({id:d,status:"reading",progress:1,message:`Preparing ${m.length} ${l}`});try{for(let S=0;S<m.length;S+=1){const y=m[S],w=y.file,J=Math.max(1,Math.ceil(w.size/ud));for(let ge=0;ge<J;ge+=1){const D=ge*ud,fe=Math.min(w.size,D+ud),Ne=w.size===0?new ArrayBuffer(0):await w.slice(D,fe).arrayBuffer(),We=ge===J-1;pa({id:d,status:"sending",progress:Math.max(2,Math.min(98,Math.round(v/Math.max(1,C)*96))),message:`${S+1}/${m.length} ${y.relativePath}`});const Xe=await ze("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:d,deviceIds:o,remoteDirectory:Oo.trim(),name:w.name,relativePath:y.relativePath,size:w.size,type:w.type,lastModified:w.lastModified,offset:D,totalBytes:w.size,final:We,dataBase64:MM(Ne)})},K);if(!Xe.ok||Xe.queued!==o.length)throw new Error(Xe.error||`file-chunk-not-queued-${Xe.queued}/${o.length}`);v+=Ne.byteLength,await new Promise(Ue=>window.setTimeout(Ue,0))}}return pa({id:d,status:"queued",progress:100,message:`Sent ${m.length} file${m.length===1?"":"s"} to ${o.length} Client${o.length===1?"":"s"}`}),window.setTimeout(()=>{pa(S=>S?.id===d&&S.status==="queued"?null:S)},4500),{files:m.length,bytes:C}}catch(S){throw pa({id:d,status:"failed",progress:100,message:S instanceof Error?S.message:String(S)}),S}},Tp=async n=>{const o=cn.length>0?cn.map(l=>l.deviceId):X?[X.deviceId]:[];try{await Ip(Hh(n),o)}catch(l){B(l instanceof Error?l.message:String(l))}},Pp=async n=>{try{await Ip(Hh(n),Yb)}catch(o){B(o instanceof Error?o.message:String(o))}};s.useEffect(()=>{Vb.current=!1},[]);const wv=n=>{n.preventDefault(),n.stopPropagation(),tu(!1),Tp(n.dataTransfer.files)},lo=async(n="plus_ltd")=>{const o=E0(n);if(!o){B("This VuvoDesk checkout option is not recognized.");return}if(!r){B("Sign in with Google before checkout.");return}if(T||!b){B("Your VuvoDesk workspace is still loading. Try again in a moment.");return}if(ae){B("The Team owner manages billing and plan changes.");return}if(!ch(n)&&!An){B("VuvoDesk LTD checkout is not open yet.");return}if(ch(n)&&!od(n)&&!Sa){B("VuvoDesk Plus and Pro monthly checkout is not open yet.");return}if(od(n)&&!Jr){B("VuvoDesk Team checkout is not open yet. Contact support to join the Team launch group.");return}const l=b?.kind==="personal"&&b.id===r.user.id;if(o!=="team"&&l&&ie&&o===Qe){B("VuvoDesk license is already active.");return}if(o!=="team"&&l&&ie&&Qe==="pro"){B("VuvoDesk Pro is already active.");return}Mn("checkout");try{let m=r.user.id;if(od(n)){let v=M.find(S=>S.kind==="team"&&S.role==="owner")?.id||"";if(v)G!==v&&await H(v);else{const{data:S,error:y}=await Ct.rpc("create_livedesk_team_workspace",{p_name:`${uo||"My"} Team`});if(y)throw y;const w=Array.isArray(S)?S[0]:S,J=String(w?.workspace_id||"").trim();if(!w?.ok||!J)throw new Error(String(w?.reason||"Team Space could not be created."));await H(J),v=J}m=v}const{data:d,error:C}=await Ct.functions.invoke("dodo-checkout",{body:{plan:n,workspace_id:m}});if(C)throw C;if(!d?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(d.checkout_url)}catch(m){B(m instanceof Error?m.message:String(m)),Mn("")}},qc=tM(),Ep=nM(),xu=cu.filter(n=>ni.has(n)).length,Ru=pu==="open"&&Oc.sampleMs>0?`${Oc.framesPerSecond.toFixed(1)} fps`:pu,ce=X?Re?Ji.get(X.deviceId):ni.get(X.deviceId):void 0,Gc=X?_n(X,gt[X.deviceId]):0,Sv=X?oM(X):[],Cv=typeof ce?.monitorIndex=="number"?ys(ce.monitorIndex,Math.max(1,ce.monitorCount||1)):Gc,Au=(ce&&Cv===Gc?gb(ce):null)||(X?hb(X,Gc):null);Au&&`${Au.width}${Au.height}`;const Kc=X?ft(Re?"control":"wall",X.deviceId):"",rn=Kc?rc[Kc]:void 0,Ln=Kc?nc[Kc]:void 0,Ee=Ln?.lastInfo,kv=rn&&rn.sampleMs>0?`${rn.framesPerSecond.toFixed(1)} fps`:"waiting";rn&&`${rn.totalFrames}${kv}`,Ln&&Ln.sampleMs>0&&`${Ln.framesPerSecond.toFixed(1)}`,Ln&&Ln.sampleMs>0&&`${Ln.changedFramesPerSecond.toFixed(1)}`,Ee&&(`${Ee.frameSeq}${Ee.decoderLabel}${Ee.queueSize}${Ee.renderQueueSize}${Ee.droppedForLatency}${Ee.decoderFlushCount}${Ee.decoderTimestampFallbacks}${Ee.decoderInputCount}${Ee.decoderOutputCount}`,Ee.visualChanged),Ee&&`${Math.round(Ee.queuedForMs)}${Math.round(Ee.decodedForMs)}${Math.round(Ee.scheduledForMs)}${Ee.drawMs.toFixed(1)}`,Ee?.targetPaintIntervalMs&&`${Ee.targetPaintIntervalMs.toFixed(1)}${(1e3/Ee.targetPaintIntervalMs).toFixed(1)}`,Ln&&`${Ln.decoderInputFps.toFixed(1)}${Ln.decoderOutputFps.toFixed(1)}`,Ee?.canvasPresentation,Ee&&`${Ee.interactiveBufferWaitCount}${Math.round(Ee.interactiveBufferWaitMs)}${Ee.interactiveQueueDrainCount}`,rn&&(ce?.frameMode==="mode5-lzo-delta"?`${ws(rn.averageFrameBytes)}${ce.deltaVisualTileCount||0}${ce.deltaRefreshTileCount||0}${ce.deltaTotalTiles||0}`:`${ws(rn.averageFrameBytes)}${Math.round(rn.tinyFrameRatio*100)}${Math.round(rn.repeatedFrameRatio*100)}`),rn&&rn.sourceSendSampleCount>0&&`${rn.sourceSendAverageMs.toFixed(1)}${rn.sourceSendP95Ms.toFixed(1)}`,Ih(rn),Ih(Ln),rn&&Ln&&`${Th(rn)}${Th(Ln)}`,ce?ce.frameMode||ce.mode||ce.codec||ce.mimeType:Re?on.frameMode:De.frameMode,Re?on.frameMode:De.frameMode,ce?`${ce.width}${ce.height}${ws(ce.byteLength)}`:Re?`${wr.maxWidth}${wr.maxHeight}`:`${De.maxWidth}${De.maxHeight}`,ce&&`${ce.isKeyFrame?"key":String(ce.chunkType||"delta")}`,ce&&ce.monitorCount&&((ce.monitorIndex??0)+1,`${ce.monitorCount}`),ce&&[`src ${Math.round(ce.sourceGapMs||0)}ms`,`gap ${Math.round(ce.agentSendGapMs||0)}ms`,`tx ${Math.round(ce.agentSendDurationMs||0)}ms`,`pace ${Math.round(ce.agentPaceMs||0)}ms`,`queue ${Math.round(ce.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(ce.agentFrameAgeMs||0)}ms`,ce.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(ce.hubPacketTransitAgeMs))}ms`:"",ce.droppedByAgent?`drop ${ce.droppedByAgent}`:"",ce.hubIngressDropped?`ingress-drop ${ce.hubIngressDropped}`:"",ce.hubClientDropped?`ws-drop ${ce.hubClientDropped}`:"",ce.captureStageMs?`capture ${Math.round(ce.captureStageMs)}ms`:"",ce.requestedFps?`req ${Math.round(ce.requestedFps)}fps`:"",ce.effectiveFps?`eff ${Math.round(ce.effectiveFps)}fps`:"",ce.captureAverageMs?`avg ${Math.round(ce.captureAverageMs)}ms`:"",ce.captureP95Ms?`p95 ${Math.round(ce.captureP95Ms)}ms`:"",ce.slowFrameCount?`slow ${Math.round(ce.slowFrameCount)}`:"",ce.captureHelperRestarts?`helper ${Math.round(ce.captureHelperRestarts)}`:"",ce.convertMs?`rgb565 ${Math.round(ce.convertMs)}ms`:"",ce.compressMs?`lzo ${Math.round(ce.compressMs)}ms`:"",ce.captureSourceSerial?`cap #${ce.captureSourceSerial}`:"",ce.captureSourceSkipped?`cap skip ${ce.captureSourceSkipped}`:"",ce.frameMode==="mode5-lzo-delta"?`tiles ${ce.deltaVisualTileCount||0}+${ce.deltaRefreshTileCount||0}/${ce.deltaTotalTiles||0}@${ce.deltaTileSize||0}`:"",ce.platformProfile||ce.hardwareEncoder||"-",ce.atlasComposeMs?`atlas ${ce.atlasComposeMs.toFixed(1)}ms`:"",ce.atlasPoolStarved?`pool ${ce.atlasPoolStarved}`:"",ce.atlasTileCount?`tiles ${ce.atlasReadyTiles||0}/${ce.atlasTileCount}`:"",ce.atlasInputRevision?`input #${ce.atlasInputRevision}`:"",ce.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(ce.atlasSourceMaxAgeMs)}ms`:"",Ee?.inputFeedbackMs!==void 0&&Ee.inputFeedbackAt!==void 0&&performance.now()-Ee.inputFeedbackAt<=bh?`feedback ${Math.round(Ee.inputFeedbackMs)}ms`:"",ce.contentHash?`enc ${ce.contentHash.slice(0,6)}`:"",Ee?.visualHash?`pix ${Ee.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),ns==="open"&&Wc&&[`${Ar.sentPerSecond.toFixed(1)} hz`,Ar.lastInputSeq>0?`rtt ${Math.round(Ar.lastRoundTripMs)}ms`:"",Ar.lastInputSeq>0?`apply ${Ar.lastAgentApplyMs.toFixed(1)}ms`:"",Ar.droppedPerSecond>0?`drop ${Ar.droppedPerSecond.toFixed(1)}/s`:"",Ar.bufferedAmount>0?`buf ${ws(Ar.bufferedAmount)}`:"",Ar.lastInputType||"ready"].filter(Boolean).join(" / "),Ee?.inputFeedbackMs!==void 0&&Ee.inputFeedbackAt!==void 0&&performance.now()-Ee.inputFeedbackAt<=bh&&[Ee.inputFeedbackExact?"exact":"estimated",Ee.inputFeedbackInputType||"",`total ${Math.round(Ee.inputFeedbackMs)}ms`,Ee.inputFeedbackAgentApplyMs!==void 0?`apply ${Ee.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",Ee.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(Ee.inputFeedbackApplyToCaptureMs)}ms`:"",Ee.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(Ee.inputFeedbackInputToFrameMs)}ms`:"",Ee.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(Ee.inputFeedbackFrameToPaintMs)}ms`:"",Ee.inputFeedbackSampleCount?`p50 ${Math.round(Ee.inputFeedbackP50Ms||0)}ms`:"",Ee.inputFeedbackSampleCount?`p95 ${Math.round(Ee.inputFeedbackP95Ms||0)}ms`:"",Ee.inputFeedbackSampleCount?`n=${Ee.inputFeedbackSampleCount}`:"",`input #${Ee.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),ce&&`${ce.frameSeq}${ey(ce.receivedAt||ce.capturedAt)}`;const ci=Math.max(0,Oc.bytesPerSecond*8/1e6),Np={activeTool:It,audioError:wu,audioMode:Zt,audioState:vu,audioStats:Rt,lastAudioFrame:yu,selectedAudioCaptureStreamId:Sp,controlFrames:Ji,controlInputReady:Ir,controlMode:kn,controlPresentationReady:Ql,controlSessionDeviceId:g,controlSessionFrameReady:Ye,controlSessionState:be,controlStreamBinding:ct,devices:Me,documentPresentationVisible:qt,focusedDeviceId:_t,frames:ni,localFeatureAccess:pt,quickActionBusy:an,selectedDeviceId:X?.deviceId||"",selectedIds:Je,showControlFocus:Re,videoCaptureStopUnconfirmedByDeviceId:Ao,videoCapturePausedDeviceIds:Ti,wallPresentationReadyDeviceIds:Gl},Fp=s.useRef(Np);Fp.current=Np,s.useEffect(()=>{if(!ec.current)return;const n=window,o=S=>{if(!S)return null;const y=S.sourceGapMs,w=y==null||y===""?null:Number.isFinite(Number(y))?Number(y):null,J=S;return{deviceId:S.deviceId,sessionId:S.sessionId||"",streamId:S.streamId||"",commandId:S.commandId||"",captureGeneration:Number(S.captureGeneration||0),monitorIndex:Number(S.monitorIndex||0),streamPurpose:S.streamPurpose||"",frameSeq:Number(S.frameSeq||0),frameMode:S.frameMode||"",mimeType:S.mimeType||"",currentGenerationVerified:J.currentGenerationVerified===!0,receivedAt:J.receivedAt||"",capturedAt:J.capturedAt||"",sourceGapMs:w,inputFeedbackEventId:String(S.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(S.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(S.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(S.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(S.inputFeedbackApplyToCaptureMs||0)}},l=S=>{if(!S)return null;const y=window.getComputedStyle(S),w=S.getBoundingClientRect(),J=Math.max(0,Math.min(w.right,window.innerWidth)-Math.max(w.left,0)),ge=Math.max(0,Math.min(w.bottom,window.innerHeight)-Math.max(w.top,0)),D=Number(y.opacity),fe=S.isConnected&&y.display!=="none"&&y.visibility!=="hidden"&&y.visibility!=="collapse"&&Number.isFinite(D)&&D>0&&w.width>0&&w.height>0&&J>0&&ge>0;return{connected:S.isConnected,userVisible:fe,width:Math.max(0,Number(S.width||0)),height:Math.max(0,Number(S.height||0)),css:{display:y.display,visibility:y.visibility,opacity:Number.isFinite(D)?D:0},rect:{left:w.left,top:w.top,right:w.right,bottom:w.bottom,width:w.width,height:w.height,viewportIntersectionWidth:J,viewportIntersectionHeight:ge},codec:el(S)}},m=(S,y)=>{const w=ua.current.get(ft(S,y));return w?{bindingKey:w.bindingKey||"",totalFrames:w.totalFrames,totalChangedFrames:w.totalChangedFrames,lastFrameSeq:Number(w.lastFrameSeq||0),lastPaintAgeMs:w.lastAt===void 0?-1:Math.max(0,performance.now()-w.lastAt),lastInfo:w.lastInfo?{frameSeq:Number(w.lastInfo.frameSeq||0),decoderInputCount:Number(w.lastInfo.decoderInputCount||0),decoderOutputCount:Number(w.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(w.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(w.lastInfo.droppedForLatency||0),visualChanged:w.lastInfo.visualChanged===!0,inputFeedbackExact:w.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(w.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(w.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(w.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(w.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:yh,inputFeedbackTargetMinSamples:wh,inputFeedbackOnTarget:w.lastInfo.inputFeedbackExact===!0&&Number(w.lastInfo.inputFeedbackSampleCount||0)>=wh&&Number(w.lastInfo.inputFeedbackP95Ms)<yh}:null}:null},d=(S,y)=>{if(!S)return null;if(y==="wall-visible"){const J=ua.current.get(ft("wall",S));return J?{bindingKey:J.bindingKey||"",total:J.totalFrames,lastFrameSeq:Number(J.lastFrameSeq||0),lastPaintAgeMs:J.lastAt===void 0?-1:Math.max(0,performance.now()-J.lastAt)}:null}if(y!=="control-visible"&&y!=="wall-reuse-visible")return null;const w=tc.current.get(`${y}:${S}`);return w?{bindingKey:w.bindingKey,total:w.totalPaints,lastFrameSeq:w.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-w.lastPaintAt)}:null},C=(S,y)=>{const w=d(S,y);return w?{bindingKey:w.bindingKey,totalPaints:w.total,lastPaintAgeMs:w.lastPaintAgeMs,lastFrameSeq:w.lastFrameSeq}:null},v={readPresentationCounter(S,y){return d(String(S||""),y)},snapshot(S,y={}){const w=String(S||""),J=y.includeHistory===!0,ge=Math.max(0,Number(y.presentationAfterSequence||0)),D=Fp.current,fe=D.devices.find(Pr=>Pr.deviceId===w)?.liveCapturePause,Ne=String(rt.current[w]||""),We=mt.current.get(w)||null,Xe=Et.current.get(w)||null,Ue=hn.current.get(w)||null,Yt=WS(),Xr=Jp(),fo=$S(),ls={frameStats:oc.current===null?0:1,wallRecovery:jo.current===null?0:1,controlWarm:nr.current===null?0:1,controlWallDownshift:zn.current===null?0:1},Fu=Br.current?.deviceId===w?Br.current:null,Qp=Im.current.get(w)||null;return{capturedAt:Date.now(),deviceId:w,activeTool:D.activeTool,documentPresentationVisible:D.documentPresentationVisible,showControlFocus:D.showControlFocus,selectedDeviceId:D.selectedDeviceId,focusedDeviceId:D.focusedDeviceId,selectedDeviceIds:[...D.selectedIds],localFeatureAccess:D.localFeatureAccess,quickActionBusy:D.quickActionBusy,audioMode:D.audioMode,audioState:D.audioState,audioError:D.audioError,audioCaptureStreamId:D.selectedAudioCaptureStreamId,audioFrame:D.lastAudioFrame?{deviceId:D.lastAudioFrame.deviceId,streamId:D.lastAudioFrame.streamId,frameSeq:Number(D.lastAudioFrame.frameSeq||0),mimeType:D.lastAudioFrame.mimeType,sampleRate:Number(D.lastAudioFrame.sampleRate||0),channels:Number(D.lastAudioFrame.channels||0),byteLength:Number(D.lastAudioFrame.byteLength||0)}:null,audioStats:{...D.audioStats},videoCapturePausePhase:Ne?Ne.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:D.videoCaptureStopUnconfirmedByDeviceId[w]===!0,authoritativeLiveCapturePause:fe?{phase:fe.phase||"",captureStopConfirmed:fe.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(fe.stopAttemptCount||0)),stopError:fe.stopError||""}:null,controlMode:D.controlMode,controlSessionDeviceId:D.controlSessionDeviceId,controlSessionState:D.controlSessionState,controlSessionFrameReady:D.controlSessionFrameReady,controlPresentationReady:D.controlPresentationReady,controlInputReady:D.controlInputReady,controlConnection:Qp?{...Qp}:null,pendingControlConnection:Fu?{...Fu,elapsedMs:Math.max(0,performance.now()-Fu.startedAt)}:null,videoCapturePaused:D.videoCapturePausedDeviceIds.has(w),wallPresentationReady:D.wallPresentationReadyDeviceIds.has(w),controlBinding:D.controlStreamBinding?.deviceId===w?{...D.controlStreamBinding}:null,actualControlOwner:ke.current?.deviceId===w?{...ke.current}:null,wallCapturePauseOwner:xn.current?.deviceId===w?{...xn.current}:null,frameSubscriptions:Yt,mobileConsoleDirect:Xr,audioSubscriptions:fo,presentationTimers:{...ls,total:Object.values(ls).reduce((Pr,Du)=>Pr+Du,0)},wallFrame:o(D.frames.get(w)),controlFrame:o(Wa.current.get(w)||D.controlFrames.get(w)),wallPaint:m("wall",w),controlPaint:m("control",w),controlVisiblePaint:C(w,"control-visible"),wallReuseVisiblePaint:C(w,"wall-reuse-visible"),presentationPaintSequence:Am.current,presentationPaintEvents:J?Kl.current.filter(Pr=>Pr.deviceId===w&&Pr.sequence>ge).sort((Pr,Du)=>Pr.sequence-Du.sequence).map(Pr=>({...Pr})):[],wallCanvas:l(We),controlDecodeCanvas:l(Xe),controlPresentationCanvas:l(Ue),globalCodec:el(void 0,{includeLifecycleEvents:J})}}};return n.__liveDeskTransmissionProbe=v,()=>{n.__liveDeskTransmissionProbe===v&&delete n.__liveDeskTransmissionProbe}},[]);const Dp=s.useCallback(()=>{Lo(!0),Gs(Date.now()),Te(),Lr.current!==null&&window.clearTimeout(Lr.current),Lr.current=window.setTimeout(()=>{Lr.current=null,Gs(Date.now()),Lo(!1)},650)},[Te]),Lp=s.useCallback(()=>{const n=ym.current;if(n)return Promise.resolve(n);const o=Wl.current;if(o)return o;const l=mr(()=>import("./remote-status-Ci5cE6Rj.js"),[]).then(m=>(ym.current=m,m)).catch(m=>{throw Wl.current=null,m});return Wl.current=l,l},[]),li=s.useCallback(n=>{const o=ia.current+1;ia.current=o,Fo(n),n==="remote"?Us(!1):n==="debug"&&zs(!1),Lp().then(l=>{o===ia.current&&(Mb(l),Fo(null),n==="remote"?zs(!0):n==="debug"?Us(!0):qs(!0),Dp())}).catch(()=>{o===ia.current&&(Fo(null),Lo(!1),console.warn("[VuvoDesk] Status diagnostics are unavailable."))})},[Lp,Dp]),Op=s.useCallback(()=>{if(fn||$n==="remote"){ia.current+=1,Fo(null),zs(!1);return}li("remote")},[li,$n,fn]),_p=s.useCallback(()=>{if(Ut||$n==="debug"){ia.current+=1,Fo(null),Us(!1);return}li("debug")},[Ut,li,$n]),jp=s.useCallback(()=>{if(pr||$n==="hub"){ia.current+=1,Fo(null),qs(!1);return}li("hub")},[pr,li,$n]),Bp=fn||Ut,Hp=JSON.stringify(Le.filter(n=>n.connected).map(n=>n.deviceId).sort());s.useEffect(()=>{if(!Bp)return;const n=JSON.parse(Hp);if(n.length===0){Lo(!1);return}const o=new AbortController,l=[];let m=!1;return Lr.current!==null&&(window.clearTimeout(Lr.current),Lr.current=null),Lo(!0),Gs(Date.now()),Promise.allSettled(n.map(d=>ze(`/api/remote/devices/${encodeURIComponent(d)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:o.signal,timeoutMs:1500},K))).then(()=>{m||[500,1800,4500].forEach((d,C,v)=>{const S=window.setTimeout(()=>{m||(Te(),Gs(Date.now()),C===v.length-1&&Lo(!1))},d);l.push(S)})}),()=>{m=!0,o.abort();for(const d of l)window.clearTimeout(d)}},[K,Te,Hp,Bp]);const ui=new Map,ss=new Map;if(Ni&&(fn||Ut||pr))for(const n of Le){const o=n.deviceId,l=Re&&g===o,d=ft(l?"control":"wall",o),C=l?Ji.get(o):ni.get(o),v=l?Et.current.get(o)||hn.current.get(o)||null:mt.current.get(o)||(tt?Nn.current:null),S={device:n,frame:C,receiveStat:rc[d],paintStat:nc[d],codec:v?el(v):{},selectedMonitorIndex:_n(n,gt[o]),control:l,controlInputReady:l&&Ir,controlBinding:l&&ct?.deviceId===o?ct:void 0,recoveryDiagnostic:$i.current.get(d),hubRelay:z?.relay,capturePaused:Ti.has(o),capturePauseConfirmed:n.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:n.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(z?.heartbeatMs||5e3),now:Date.now()},y=["open","playing","silent"].includes(vu),w=Rt.nativeCallbackDiagnosticsAvailable&&(Rt.nativeRejectedCallbackCount>0||Rt.nativeCurrentnessDropCount>0),J=y&&!w,ge=o===X?.deviceId&&Zt?{id:"browser-remote-audio",state:J?"ok":"warning",label:J?"Remote audio is healthy":"Remote audio needs attention",detail:Rt.lastUpdatedAt>0?[vu,`context ${Rt.audioContextState}`,`queue ${Math.round(Rt.queuedMs)}ms`,`packet ${Math.round(Rt.lastPacketAgeMs)}ms`,`capture ${Rt.captureHealthy?"healthy":Rt.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Rt.backendKind?`backend ${Rt.backendKind}`:"backend unknown",Rt.helperRequired?`helper ${Rt.helperAlive&&Rt.helperPid>0?`pid ${Rt.helperPid}`:"missing"}`:"helper N/A",`drop ${Rt.drops}`,`restart ${Rt.automaticRestarts}`,Rt.nativeCallbackDiagnosticsAvailable?`native reject ${Rt.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Rt.nativeCallbackDiagnosticsAvailable?`native stale ${Rt.nativeCurrentnessDropCount}`:"",Rt.nativeLastDropReason?`native reason ${Rt.nativeLastDropReason}`:"",yu?`frame #${yu.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(fn||pr){const D=Ni.buildRemoteDeviceDiagnostics(S);fn&&ge&&D.push(ge),ui.set(o,D)}if(Ut){const D=Ni.buildRemoteDeviceDebugDiagnostics(S);ge&&D.push(ge),ss.set(o,D)}}const Mv=pr&&Ni?Ni.buildHubRemoteDiagnostics({status:z||{},deviceDiagnostics:[...ui.values()],codec:el(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Oc}):[],Wp=ti?.atlasReadyTiles??xu,Iu=ti?.atlasTileCount??xu,xv=Wp===Iu?`${Iu} tiles`:`${Wp}/${Iu} tiles`,Rv=nn.length>0;Re?`${Ru}${ci.toFixed(ci>=10?0:1)}`:Rv?`${xv}${Ru}${ci.toFixed(ci>=10?0:1)}`:`${xu}${Ru}${ci.toFixed(ci>=10?0:1)}`;const Tu=cn.length,Av=Re?X?Qt(X):"No Client":Tu===0?"No Client":Tu>1?`${Tu} selected`:X?Qt(X):"No Client",Iv=Re?[X?.deviceId].filter(n=>!!n):cn.map(n=>n.deviceId),Sn=Ci[ja]||Ci.en,Yc=Sn.sync||Ci.en.sync,Tv=u||T||Pe?"checking":Qe==="team"?ae?"Team · Operator access":`Team · ${V.members.length+V.invites.length}/${b?.memberLimit||Zp} people`:Qe==="pro"?`Pro ${Ka.length}/${Lu}`:Qe==="ltd"?`Plus ${Ka.length}/${us}`:`Free ${Ka.length}/${Ou}`,Pv=An?Qe!=="free"?Qe==="team"?"Team active":Qe==="pro"?"Business active":"Upgrade to Pro LTD":r?et==="checkout"?"Opening checkout":Qe==="ltd"?"Buy Pro LTD":"Buy Plus LTD":et==="auth"?"Opening Google":"Sign in to buy":"LTD · Coming soon",Ev=!An||Qe==="pro"||Qe==="team"||et==="checkout"||et==="auth"||u||T||Pe,$p=r?.user?.user_metadata,cs=Wh($p,"avatar_url","picture"),uo=Wh($p,"full_name","name")||r?.user?.email||"Google",Pu=uo.slice(0,1).toUpperCase(),Nv=z?.started?"Local app ready":"Start VuvoDesk",Fv=Z?.active?"Published":r?"Not published":"Sign in required",Dv=ah(Qe),Lv=M.map(n=>({id:n.id,kind:n.kind,name:n.kind==="personal"?"Personal":n.name,role:n.role,plan:ah(n.plan),memberCount:n.id===G&&n.kind==="team"?V.members.length+V.invites.length:void 0})),di=b?.kind==="team"?{id:b.id,name:b.name,currentUserRole:b.role,memberLimit:b.memberLimit,memberCount:b.role==="owner"?V.members.length+V.invites.length:void 0,invitationsEnabled:Qe==="team"&&b.role==="owner"&&V.members.length+V.invites.length<b.memberLimit,members:[...V.members.map(n=>({id:n.id,email:n.email,displayName:n.displayName,role:n.role,status:"active"})),...V.invites.map(n=>({id:n.id,email:n.email,role:n.role,status:"invited",expiresAt:n.expiresAt}))]}:null,Ov=ae?zh.filter(n=>n.id==="wall"||n.id==="control"):zh,_v=ae?Uh.filter(n=>n.id==="doc"||n.id==="support"):Uh,jv=async n=>{if(n===G)return;const o=await H(n);if(!o){B("The VuvoDesk workspace could not be opened.","error");return}B(`Switched to ${o.name}.`,"success")},Bv=async n=>{if(!G||b?.role!=="owner")throw new Error("Only the Team owner can rename this space.");const o=G,{data:l,error:m}=await Ct.rpc("rename_livedesk_workspace",{p_workspace_id:o,p_name:n});if(!Q(o))throw new Error("The active VuvoDesk workspace changed. Please try again in the current workspace.");if(m)throw m;const d=Array.isArray(l)?l[0]:l;if(!d?.ok)throw new Error(String(d?.reason||"Team Space rename failed."));await ye(),Q(o)&&B("Team Space name saved.","success")},Hv=async n=>{const o=G,l=await V.removeMember(n);Q(o)&&B(l.revokedImmediately?"Team member removed and active remote access closed.":"Team member removed. The Hub was offline, so its next access check will close any old connection.",l.revokedImmediately?"success":"error")},Wv=async n=>{const o=G;await V.revokeInvite(n),Q(o)&&B("Team invitation cancelled.","success")},$v=async()=>{if(!r)throw new Error("Sign in before leaving a Team Space.");if(await V.leaveWorkspace(),!await H(r.user.id))throw new Error("The Team was left, but Personal could not be reopened yet. Retry in a moment.");B("You left the Team Space.","success")},Vv=/^\d{6}$/.test(z?.pairingPin||"")?z?.pairingPin:"------",mo=n=>{if(n==="pricing"&&(u||T)){B("Your VuvoDesk workspace is still loading. Try again in a moment.");return}if(ae&&n!=="wall"&&n!=="control"&&n!=="doc"&&n!=="support"){B("Team Operators can use Wall and Control. Ask the Team owner to change settings, billing, files, or Agents."),La("wall"),jn(!1);return}if(typeof window<"u"&&(n==="support"?window.history.pushState({},"","/support"):It==="support"&&window.history.pushState({},"",W?"/app":"/")),n==="control"){const o=tn||ha;if(o&&(as(o.deviceId),gn(!1),Vt(o.deviceId)),La(n),!pt){jn(!1),B(Xo);return}jn(!0);return}n==="wall"&&Nb(o=>o+1),La(n),jn(!1)},Tr=et==="update"||Ze?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(z?.update?.state||""),Vp=!ae&&!!(z?.update?.updateAvailable&&z.update.canApply||Tr||Ze?.error||!z&&Ze),po=Wy(ja),Eu=s.useCallback(n=>{if(!Ze?.targetIds.includes(n))return;const o=z?.update?.operationId===Ze.operationId?z.update.targets?.find(l=>l.deviceId===n):void 0;switch(o?.state){case"completed":return Ys[Mh(Ze.operationId,o)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:o.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Ze.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Ze.stage==="updating"?o.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Ze.stage==="updated"?{state:"updated",label:"Updated"}:Ze.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[z?.update,Ys,Ze]),Nu=de&&!!r&&it&&qe==="connecting",va=de&&!!r&&it&&(qe==="reconnecting"||qe==="unavailable"),zp=W&&va&&kt?.kind==="signal-service-unavailable",Up=W&&va&&kt?.kind==="p2p-unavailable",qp=kt?.retryAt?Math.max(0,Math.ceil((kt.retryAt-Date.now())/1e3)):0,zv=u?"checking":qe==="online"&&z?.started?"online":Nu?"connecting":va?qe:"offline",Gp=r&&!Oe?"Restoring your workspace...":"Restoring direct connection...",Qc=qe==="reconnecting"?Gp:u?"Checking Hub":qe==="online"&&z?.started?`${Le.length} online`:Nu?"Connecting Hub":zp?"Signaling unavailable":Up?"Direct connection unavailable":r?"Hub offline":"Sign in required",mi=qe==="reconnecting"?"":qe==="online"&&z?.deviceName?z.deviceName:Nu?"Trying saved Hub routes…":zp?qp>0?`Next attempt in ${qp}s`:"Automatic retry pending":Up?"This network cannot establish a direct peer connection":va?"Automatic retry in background":je?"Desktop Hub unavailable":"Remote management",Kp=W&&Ur&&!Re,Yp=Gy({authLoading:u,phase:qe,recoveryOverlayEligible:Kp}),Uv=Yp.statusVisible,qv=Yp.recoveryVisible||Kp&&!!r&&!Oe,Gv=t&&Ur&&!!r&&(!Oe||!z);return i.jsxs("main",{className:`app-shell ${Ur||Re?"stream-surface-active":""} ${de?"mobile-console-shell":""} ${de&&Re?"mobile-console-control-active":""}`,"data-mobile-standalone":de&&ee?"true":void 0,"data-mobile-ios":de&&ue.isIos?"true":void 0,"data-mobile-android":de&&ue.isAndroid?"true":void 0,children:[i.jsxs("aside",{className:"tool-rail","aria-label":"VuvoDesk tools",children:[i.jsx("div",{className:"rail-brand",title:"VuvoDesk",children:i.jsx(ef,{size:25})}),i.jsx("nav",{className:"rail-tools",children:Ov.map(n=>{const o=n.icon,l=ag(n.tooltip,ja);return i.jsxs("button",{className:`rail-tool ${n.id==="sync-server"?"sync-server hub-sync-trigger":""} ${It===n.id?"active":""} accent-${n.accent}`,onClick:()=>n.id==="sync-server"?dv():mo(n.id),"data-tooltip":n.id==="sync-server"&&Po?void 0:jy(n.label,n.tooltip,ja),"aria-label":`${n.label}. ${l}`,type:"button",disabled:n.id==="sync-server"&&et==="host","aria-busy":n.id==="sync-server"&&et==="host","aria-expanded":n.id==="sync-server"?Po:void 0,"aria-haspopup":n.id==="sync-server"?"dialog":void 0,"aria-controls":n.id==="sync-server"&&Po?"hub-sync-popover":void 0,children:[n.id==="sync-server"&&et==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(o,{size:19}),i.jsx("span",{children:n.id==="sync-server"&&et==="host"?"Syncing…":n.label})]},n.id)})}),i.jsxs("div",{className:"rail-footer",children:[_v.map(n=>{const o=n.icon;return i.jsxs("button",{className:`rail-tool compact ${It===n.id?"active":""} accent-${n.accent}`,onClick:()=>mo(n.id),title:n.label,type:"button",children:[i.jsx(o,{size:18}),i.jsx("span",{children:n.label})]},n.id)}),!ae&&i.jsxs("button",{className:`rail-tool compact local-settings ${qi?"active":""}`,onClick:()=>{La("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Or(!1),jn(!1),wm(!1)},title:"Settings",type:"button",children:[i.jsx(nf,{size:18}),i.jsx("span",{children:"Settings"})]}),i.jsxs("button",{className:`rail-account ${r?"signed-in":""}`,onClick:()=>{Or(n=>!n)},disabled:u||p||et==="auth","aria-expanded":sa,"aria-haspopup":"dialog","aria-controls":"vuvodesk-account-dialog",title:r?`Account: ${r.user?.email||uo}`:"Sign in with Google",type:"button",children:[r?cs?i.jsx("img",{src:cs,alt:uo,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Pu}):i.jsx(Sl,{size:18}),i.jsx("span",{children:r?"Account":"Google"})]})]})]}),i.jsx(T0,{open:sa,signedIn:!!r,accountName:uo,accountEmail:r?.user?.email||"",accountInitial:Pu,avatarUrl:cs,currentPlan:Dv,currentPlanKnown:!T&&!Pe,deviceCount:Ka.length,deviceLimit:vc,licenseLabel:Tv,networkLabel:Nv,accessLabel:Fv,authBusy:u||p||et==="auth",workspaceBusy:T,checkoutBusy:et==="checkout"||Pe||V.loading,ltdCheckoutEnabled:An,monthlyCheckoutEnabled:Sa,teamCheckoutEnabled:Jr,planChangesEnabled:!ae,sessionRevocationError:f,workspaces:Lv,activeWorkspaceId:G,teamWorkspace:di,onClose:()=>Or(!1),onSignIn:Qr,onSignOut:uv,onRetrySessionRevocation:k,onSelectPlan:n=>{if(!r)return Or(!1),Qr();if(ae){B("The Team owner manages billing and plan changes.");return}if((n==="plus_ltd"||n==="pro_ltd")&&!An){B("VuvoDesk LTD checkout is not open yet.");return}if(n==="team_monthly"&&!Jr){B("VuvoDesk Team checkout is not open yet. Contact support to join the Team launch group.");return}return Or(!1),lo(n)},onSelectWorkspace:jv,onCreateTeamInvite:di?.currentUserRole==="owner"?V.createInvite:void 0,onRemoveTeamMember:di?.currentUserRole==="owner"?Hv:void 0,onRevokeTeamInvite:di?.currentUserRole==="owner"?Wv:void 0,onRenameTeamWorkspace:di?.currentUserRole==="owner"?Bv:void 0,onLeaveTeamWorkspace:di?.currentUserRole==="operator"?$v:void 0}),de&&P&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>F(!1),children:i.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:n=>n.stopPropagation(),children:[i.jsxs("header",{children:[i.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:i.jsx(hy,{size:20})}),i.jsxs("span",{children:[i.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install VuvoDesk on iPhone"}),i.jsx("small",{children:"Open without browser bars and tabs"})]}),i.jsx("button",{type:"button",onClick:()=>F(!1),"aria-label":"Close install guide",children:i.jsx(Ma,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",ue.browserName==="browser"?"the browser":ue.browserName,"'s ",i.jsx("strong",{children:"Share"})," button."]}),i.jsxs("li",{children:["Tap ",i.jsx("strong",{children:"Add to Home Screen"}),"."]}),i.jsx("li",{children:ue.isSafari?i.jsxs(i.Fragment,{children:["Turn on ",i.jsx("strong",{children:"Open as Web App"}),", then tap ",i.jsx("strong",{children:"Add"}),"."]}):i.jsxs(i.Fragment,{children:["Confirm the app name, then tap ",i.jsx("strong",{children:"Add"}),"."]})})]}),i.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>F(!1),children:"Got it"})]})}),Po&&i.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:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(Si,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:po.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>os(),"aria-label":po.closeLabel,children:i.jsx(Ma,{size:17})})]}),i.jsx("h2",{id:"hub-sync-title",children:po.title}),i.jsx("p",{id:"hub-sync-description",children:po.description}),i.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[i.jsx(wo,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:po.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>os(),children:po.cancel}),i.jsxs("button",{ref:cm,className:"primary",type:"button",onClick:mv,disabled:et==="host",children:[i.jsx(Si,{size:16}),po.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${Ur&&!Ba?"dock-open":""} ${Re?"control-stage":""} ${mc?"agents-stage":""} ${Ga?"file-share-stage":""}`,children:[de&&i.jsxs("header",{className:"mobile-console-header",children:[i.jsxs("span",{className:"mobile-console-brand","aria-label":"VuvoDesk mobile Console",children:[i.jsx("span",{className:"mobile-console-brand-mark",children:i.jsx(ef,{size:22})}),i.jsxs("span",{children:[i.jsx("strong",{children:"VuvoDesk"}),i.jsx("small",{children:"Mobile Console"})]})]}),Uv&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:`mobile-console-hub state-${zv}`,onClick:va?Be:void 0,disabled:!va,type:"button","aria-label":`${Qc}${mi?`. ${mi}`:""}${va?" Retry now.":""}`,title:va?"Retry remote connection now":Qc,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:Qc}),mi&&i.jsx("small",{children:mi})]})]}),i.jsxs("span",{className:"mobile-console-hub-live",role:"status","aria-live":"polite",children:[Qc,mi?`. ${mi}`:""]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[i.jsxs("button",{className:`mobile-console-account ${r?"signed-in":""}`,onClick:()=>Or(n=>!n),disabled:u||et==="auth","aria-expanded":sa,"aria-haspopup":"dialog","aria-controls":"vuvodesk-account-dialog",title:r?`Account: ${r.user?.email||uo}`:"Sign in with Google",type:"button",children:[r?cs?i.jsx("img",{src:cs,alt:uo,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Pu}):i.jsx(Sl,{size:16}),i.jsx("span",{children:r?"Account":"Google"})]}),W&&!ee&&(_||ue.isIos)&&i.jsx("button",{className:"mobile-console-install",onClick:()=>{R()},"aria-label":"Install VuvoDesk app",title:"Install VuvoDesk app",type:"button",children:i.jsx(gy,{size:19,"aria-hidden":"true"})}),Vp&&i.jsx("button",{className:"mobile-console-update",onClick:()=>{Rp()},disabled:Tr||!z?.update?.canApply,"aria-label":Tr?"VuvoDesk update in progress":"Update VuvoDesk","aria-busy":Tr,type:"button",children:Tr?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(rf,{size:18,"aria-hidden":"true"})})]})]}),de&&Ur&&!Re&&i.jsxs("div",{className:"mobile-wall-preferences","data-list-status-only":Pi?"true":void 0,"aria-label":Pi?"Wall display preferences. List is updating status only.":"Wall display preferences",children:[i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:Vh.map(n=>i.jsx("button",{className:Oa===n.id?"active":"",onClick:()=>gm(n.id),title:`${n.label} Wall streaming (${n.fps} fps)`,"aria-pressed":Oa===n.id,type:"button",children:n.label},n.id))}),i.jsx("div",{className:"segmented-control mobile-wall-view-control","aria-label":"Wall view",children:TM.map(n=>i.jsx("button",{className:fm===n.id?"active":"",onClick:()=>hm(n.id),title:n.id==="list"&&Pi?"List status only. Wall video is paused to save data.":n.label,"aria-pressed":fm===n.id,type:"button",children:n.label},n.id))})]}),i.jsxs("header",{className:"topbar",children:[i.jsx("div",{className:"topbar-leading",children:Vp?i.jsxs("button",{className:"topbar-update-button",onClick:()=>{Rp()},title:Ze?.error?`VuvoDesk Hub update failed: ${Ze.error}`:`Update VuvoDesk to ${z?.update?.latestVersion||Ze?.targetManagerVersion||"latest"}`,"aria-label":Ze?.error?`VuvoDesk Hub update failed: ${Ze.error}`:Tr?"VuvoDesk update in progress":`Update VuvoDesk to ${z?.update?.latestVersion||Ze?.targetManagerVersion||"latest"}`,type:"button",disabled:Tr||!z?.update?.canApply,"aria-busy":Tr,children:[Tr?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(rf,{size:19,"aria-hidden":"true"}),Tr&&z?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[z.update.completedCount||0,"/",z.update.targetCount]}):null]}):null}),i.jsxs("div",{className:"topbar-tray",children:[Ga&&!Re&&i.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[i.jsxs("div",{children:[i.jsx(by,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Source"}),i.jsx("strong",{children:"VuvoDesk Hub"})]})]}),i.jsx(vy,{size:15}),i.jsx(yy,{size:16}),i.jsxs("div",{children:[i.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),i.jsxs("span",{children:[i.jsx("small",{children:"Destination"}),i.jsxs("strong",{children:[zm," Client",zm===1?"":"s"]}),i.jsx("em",{children:Oo.trim()||"Desktop/VuvoDeskFiles"})]})]})]}),Ur&&!Re&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mh,{active:pr,refreshing:pr&&Do||$n==="hub",onClick:jp}),i.jsx(uh,{active:fn,refreshing:fn&&Do||$n==="remote",onClick:Op}),i.jsx(dh,{active:Ut,refreshing:Ut&&Do||$n==="debug",onClick:_p}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(nh,{controller:Xm,onError:B}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:Vh.map(n=>i.jsx("button",{className:Oa===n.id?"active":"",onClick:()=>gm(n.id),title:n.label+" Wall streaming ("+n.fps+" fps)","aria-pressed":Oa===n.id,type:"button",children:n.label},n.id))}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsxs("div",{className:"wall-view-control",children:[i.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:IM.map(n=>i.jsx("button",{className:Bt===n.id?"active":"",onClick:()=>hm(n.id),"aria-pressed":Bt===n.id,type:"button",children:n.label},n.id))}),i.jsx("label",{className:"wall-view-slider",htmlFor:"wall-view-scale",children:i.jsx("input",{id:"wall-view-scale",type:"range",min:Al,max:ea,step:1,value:Eo,onChange:n=>wb(Number(n.currentTarget.value)),"aria-label":"Wall tile size","aria-valuetext":Cb})})]})]}),Re&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mh,{active:pr,refreshing:pr&&Do||$n==="hub",onClick:jp}),i.jsx(uh,{active:fn,refreshing:fn&&Do||$n==="remote",onClick:Op}),i.jsx(dh,{active:Ut,refreshing:Ut&&Do||$n==="debug",onClick:_p}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(nh,{controller:Xm,onError:B})]})]})]}),pr&&Ur&&i.jsx(H0,{items:Mv,collectedAt:xb,onClose:()=>qs(!1)}),jm?i.jsxs("section",{className:"doc-page",lang:ja,dir:ja==="ar"?"rtl":"ltr",children:[i.jsxs("section",{className:"doc-hero",children:[i.jsxs("div",{className:"doc-hero-copy",children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(wd,{size:16}),Sn.eyebrow]}),i.jsx("h2",{children:Sn.title}),i.jsx("p",{children:Sn.intro})]}),i.jsxs("label",{className:"doc-language-picker",children:[i.jsxs("span",{children:[i.jsx(wy,{size:17}),Sn.languageLabel]}),i.jsx("select",{value:ja,onChange:n=>Rb(n.target.value),children:EM.map(n=>i.jsx("option",{value:n.id,children:n.label},n.id))})]})]}),i.jsx("section",{className:"doc-grid",children:Sn.sections.map((n,o)=>{const m=[Si,gl,af,wo,eg][o]||wd;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(m,{size:19})}),i.jsxs("div",{children:[i.jsx("h3",{children:n.title}),i.jsx("p",{children:n.body}),i.jsx("ul",{children:n.points.map(d=>i.jsx("li",{children:d},d))})]})]},n.title)})}),Yc&&i.jsxs("section",{className:"doc-sync",children:[i.jsxs("div",{className:"doc-sync-head",children:[i.jsx(af,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Yc.title}),i.jsx("p",{children:Yc.body})]})]}),i.jsx("ul",{children:Yc.points.map(n=>i.jsx("li",{children:n},n))})]}),i.jsxs("section",{className:"doc-firewall",children:[i.jsxs("div",{className:"doc-firewall-head",children:[i.jsx(wo,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Sn.firewall.title}),i.jsx("p",{children:Sn.firewall.body})]})]}),i.jsx("ul",{children:Sn.firewall.points.map(n=>i.jsx("li",{children:n},n))})]}),i.jsxs("section",{className:"doc-command-panel",children:[i.jsxs("div",{className:"doc-command-head",children:[i.jsx(gl,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Sn.commands.title}),i.jsx("p",{children:Sn.commands.body})]})]}),i.jsxs("div",{className:"doc-command-list",children:[Sn.commands.manager&&i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.manager}),i.jsx("code",{children:Ep}),i.jsx("button",{className:"icon-button",onClick:()=>_u(Ep),title:"Copy command",type:"button",children:i.jsx(ju,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.primary}),i.jsx("code",{children:qc}),i.jsx("button",{className:"icon-button",onClick:()=>_u(qc),title:"Copy command",type:"button",children:i.jsx(ju,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.slot}),i.jsx("code",{children:`${qc} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>_u(`${qc} 3`),title:"Copy command",type:"button",children:i.jsx(ju,{size:16})})]})]})]})]}):mc?i.jsx(hs,{children:i.jsx(hh,{hubUrl:K,devices:Me})}):Ga?i.jsx(hs,{children:i.jsx(rk,{hubUrl:K,devices:Le,localFeatureAccess:pt,upgradeNotice:Xo,remoteDirectory:Oo,onRemoteDirectoryChange:Sm,targetMode:Uo,selectedTargetIds:qo,onTargetModeChange:Bb,onTargetToggle:n=>nu(o=>o.includes(n)?o.filter(l=>l!==n):[...o,n]),filePickerRef:Wb,folderPickerRef:$b,onBrowserFileImport:n=>{Pp(n)},onBrowserFolderImport:n=>{Pp(n)},onNotice:B,onTransferChange:n=>{if(!n){pa(null);return}const o=n.state==="failed"||n.state==="partially-failed"||n.state==="cancelled"?"failed":n.state==="completed"?"queued":n.state==="sending"?"sending":"reading";pa({id:n.id,status:o,progress:n.progress,message:n.message}),["completed","partially-failed","failed","cancelled"].includes(n.state)&&window.setTimeout(()=>pa(l=>l?.id===n.id?null:l),4500)}})}):Bm?i.jsx(hs,{children:i.jsx(ak,{session:r,currentProductKey:"livedesk",appVersion:"",onSignIn:Qr})}):qi?i.jsx(hs,{children:i.jsx(ok,{hubUrl:K,mobileLayout:de,runtimeRole:z?.runtimeRole||"hub",runtimeDeviceId:z?.deviceId||"",sessionAccessToken:r?.access_token||"",showThisComputerSetting:!de&&z?.runtimeRole==="hub",onShowThisComputerChange:St,pin:i.jsxs(ik,{children:[i.jsx("div",{className:"settings-section-grid",children:i.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Pair a Client"}),i.jsx("h3",{children:"Connect another local PC"})]}),i.jsx(Ra,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Vv}),i.jsxs("button",{className:"text-button ghost compact",onClick:pv,disabled:!z?.started||et==="pin",type:"button",children:[i.jsx(Sy,{size:15}),et==="pin"?"Creating":"New PIN"]})]})]})}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"File transfer"}),i.jsx("h3",{children:"Client destination folder"})]}),i.jsx(Bu,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:Oo,onChange:n=>Sm(n.target.value),placeholder:"Desktop/VuvoDeskFiles"})]}),i.jsx("p",{className:"settings-help",children:"Blank uses Desktop/VuvoDeskFiles on each Client."})]})]}),desktopUpdate:i.jsx(ck,{}),agent:i.jsx(sk,{hubUrl:K,showToast:B}),captureGallery:i.jsx(lk,{hubUrl:K,onToast:B})})}):_m?i.jsxs("section",{className:"pricing-page",children:[i.jsxs("header",{className:"pricing-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Cy,{size:15})," VuvoDesk plans"]}),i.jsx("h2",{children:"Choose the plan that fits your wall"}),i.jsx("p",{children:"Use one account for Personal or Business, or let each operator use a separate Google account in one Team Space."})]}),i.jsx("button",{className:"pricing-close",onClick:()=>mo("wall"),title:"Close pricing",type:"button",children:i.jsx(Ma,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:Km.name}),i.jsxs("small",{children:[Ka.length,"/",qk(vc)," managed Clients"]})]}),i.jsxs("div",{className:"pricing-cards","aria-label":"VuvoDesk plans",children:[i.jsxs("article",{className:`pricing-plan-card ${Qe==="free"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),i.jsx("strong",{children:$e.free.price})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.free.audience}),i.jsx("h3",{children:"Free personal screen wall"}),i.jsx("p",{children:$e.free.note}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",Ou," devices"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Standard banner helps keep Free available"]})]}),i.jsx("span",{className:"pricing-current-label",children:Qe==="free"?"Current plan":"Included for everyone"})]}),i.jsxs("article",{className:`pricing-plan-card featured ${Qe==="ltd"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge plus",children:[i.jsx(Xh,{size:14})," Plus"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.ltd.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.ltd.audience}),i.jsx("h3",{children:"Ad-free personal wall"}),i.jsxs("p",{children:["Monitor up to ",us," personal computers without the standard banner."]}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",us," devices"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," No standard ad banner"]})]}),i.jsxs("div",{className:"pricing-ltd-offer",children:[i.jsx("span",{children:"Plus LTD"}),i.jsx("strong",{children:$e.ltd.ltd}),i.jsx("small",{children:An?"One-time · available now":"One-time · coming soon"})]}),i.jsxs("div",{className:"pricing-plan-actions",children:[i.jsxs("button",{className:"pricing-plan-button secondary",onClick:Sa?r?()=>lo("plus_monthly"):Qr:void 0,disabled:!Sa||Qe!=="free"||et==="checkout"||et==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Qe!=="free"?"Plus active":Sa?r?`Choose Plus · ${$e.ltd.price}/month`:"Sign in for Plus monthly":"Monthly · Coming soon"]}),i.jsxs("button",{className:"pricing-plan-button",onClick:An?r?()=>lo("plus_ltd"):Qr:void 0,disabled:!An||Qe!=="free"||et==="checkout"||et==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Qe!=="free"?"Plus active":An?r?`Buy Plus · ${$e.ltd.ltd}`:"Sign in for Plus LTD":"LTD · Coming soon"]})]})]}),i.jsxs("article",{className:`pricing-plan-card pro ${Qe==="pro"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge pro",children:[i.jsx(wo,{size:14})," Pro / Business"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.pro.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.pro.audience}),i.jsx("h3",{children:"School and commercial monitoring"}),i.jsx("p",{children:"For schools, academies, studios, offices, and other commercial use."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",Lu," connected Clients"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Ad-free school, academy, and commercial use"]})]}),i.jsxs("div",{className:"pricing-ltd-offer pro",children:[i.jsx("span",{children:"Pro LTD"}),i.jsx("strong",{children:$e.pro.ltd}),i.jsx("small",{children:An?"One-time · available now":"One-time · coming soon"})]}),i.jsxs("div",{className:"pricing-plan-actions",children:[i.jsxs("button",{className:"pricing-plan-button secondary",onClick:Sa?r?()=>lo("pro_monthly"):Qr:void 0,disabled:!Sa||Qe==="pro"||Qe==="team"||et==="checkout"||et==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Qe==="pro"?"Business active":Qe==="team"?"Included with Team":Sa?r?`Choose Pro · ${$e.pro.price}/month`:"Sign in for Pro monthly":"Monthly · Coming soon"]}),i.jsxs("button",{className:"pricing-plan-button",onClick:An?r?()=>lo("pro_ltd"):Qr:void 0,disabled:!An||Qe==="pro"||Qe==="team"||et==="checkout"||et==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Qe==="pro"?"Business active":Qe==="team"?"Included with Team":An?r?`Buy Pro · ${$e.pro.ltd}`:"Sign in for Pro LTD":"LTD · Coming soon"]})]})]}),i.jsxs("article",{className:`pricing-plan-card team ${Qe==="team"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge team",children:[i.jsx(As,{size:14})," Team"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.team.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.team.audience}),i.jsx("h3",{children:"One Team Space, separate logins"}),i.jsx("p",{children:"Share the same computers without sharing one Google account."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",Zp," people"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Commercial use"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Owner and Operator roles"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," One controller per computer"]})]}),i.jsxs("div",{className:"pricing-team-readiness",children:[i.jsx("span",{children:Jr?"Team subscription":"Team launch group"}),i.jsx("strong",{children:Jr?`${$e.team.price} monthly`:"Contact support"}),i.jsx("small",{children:Jr?"Separate member accounts":"Checkout stays closed until recurring billing is ready"})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:Jr?r?()=>lo("team_monthly"):Qr:void 0,disabled:!Jr||Qe==="team"||et==="checkout"||et==="auth"||u||T||Pe,type:"button",children:[i.jsx(As,{size:16}),Qe==="team"?"Team active":Jr?r?`Choose Team · ${$e.team.price}/month`:"Sign in for Team":"Team · Coming soon"]})]})]}),i.jsxs("section",{className:"pricing-includes",children:[i.jsxs("div",{children:[i.jsx(Ra,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ layout slots"})]}),i.jsxs("div",{children:[i.jsx(Cs,{size:17}),i.jsx("span",{children:"Focused control"}),i.jsx("strong",{children:"Local-first"})]}),i.jsxs("div",{children:[i.jsx(of,{size:17}),i.jsx("span",{children:"Remote audio"}),i.jsx("strong",{children:"Available"})]}),i.jsxs("div",{children:[i.jsx(Bu,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(Cn,{size:15})," Free and Plus are personal. Pro / Business covers one person in a school, academy, or other commercial organization. Team gives each operator a separate account in one shared space."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:An?r?()=>lo(Qe==="ltd"?"pro_ltd":"plus_ltd"):Qr:void 0,disabled:Ev,type:"button",children:[i.jsx(xa,{size:18}),Pv]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Ba?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:Lm,className:`screen-wall-panel ${_b?"drop-active":""}`,onClick:n=>{n.currentTarget===n.target&&is()},onDragEnter:n=>{n.preventDefault(),tu(!0)},onDragOver:n=>{n.preventDefault(),n.dataTransfer.dropEffect="copy"},onDragLeave:n=>{n.currentTarget===n.target&&tu(!1)},onDrop:wv,children:[Gv&&i.jsx("div",{className:"desktop-hub-recovery-overlay",children:i.jsxs("div",{className:"desktop-hub-recovery-message",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"desktop-hub-recovery-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Restoring VuvoDesk…"}),i.jsx("small",{children:"Connected computers and video will return automatically."})]})}),qv&&i.jsx("div",{className:"mobile-hub-recovery-overlay",children:i.jsxs("div",{className:"mobile-hub-recovery-message",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"mobile-hub-recovery-spinner","aria-hidden":"true"}),i.jsx("strong",{children:Gp})]})}),nn.length>0&&i.jsx("canvas",{ref:tv,className:"atlas-source-canvas",width:Za?.width||1920,height:Za?.height||1080,"aria-hidden":"true"}),Re?i.jsx("section",{className:"control-focus",children:i.jsxs("div",{className:"control-wall",children:[X&&i.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${Qt(X)}`,children:[i.jsx("strong",{className:"control-computer-name",title:Qt(X),children:Qt(X)}),Sv.map(n=>i.jsxs("button",{className:n.index===Gc?"active":"",onClick:()=>fv(X.deviceId,n.index),title:sM(n),type:"button",children:[i.jsx("span",{children:n.name||`Display ${n.index+1}`}),n.width>0&&n.height>0&&i.jsxs("small",{children:[n.width,"x",n.height]})]},n.index))]}),X&&Ir&&i.jsxs("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:[de&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:`remote-keyboard-button ${nm?"active":""}`,type:"button","aria-pressed":nm,"aria-label":"Open remote keyboard",title:"Open the phone keyboard for the remote computer",onClick:()=>{const n=em.current;n&&(n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length))},children:i.jsx(ky,{size:15,"aria-hidden":"true"})}),i.jsx("textarea",{ref:em,className:"remote-keyboard-input","aria-label":"Type on the remote computer",autoComplete:"off",autoCorrect:"off",autoCapitalize:"sentences",enterKeyHint:"enter",spellCheck:!1,rows:1,onFocus:()=>rm(!0),onBlur:()=>{Ds.current=!1,rm(!1)},onCompositionStart:()=>{Ds.current=!0},onCompositionEnd:n=>{Ds.current=!1;const o=n.currentTarget.value;n.currentTarget.value="",Ai.current?.sendText(o)},onInput:n=>{if(Ds.current)return;const o=n.currentTarget.value;n.currentTarget.value="",Ai.current?.sendText(o)},onKeyDown:n=>{n.nativeEvent.isComposing||!ol(n.key)||(n.preventDefault(),n.stopPropagation(),kp(n.key,"keydown"))},onBeforeInput:n=>{const o=n.nativeEvent.inputType||"";ol(o)&&(n.preventDefault(),n.stopPropagation(),kp(o,"beforeinput"))}})]}),Mk.map(n=>{const o=n.code==="MetaLeft"&&Nr(X.platform)?"Cmd":n.label,l=Ri.includes(n.code);return i.jsx("button",{className:l?"active":"",type:"button","aria-pressed":l,title:`Hold ${o} on the remote computer`,onClick:()=>Dl.current?.(n.code),children:o},n.code)})]}),X?i.jsx(yd,{device:X,frame:ce,selected:!1,controlEnabled:Cr&&kn&&Ir,showStatus:on.showScreenStatus,showDeviceTitle:!1,monitorIndex:_n(X,gt[X.deviceId]),monitorCount:ka(X),onSelect:()=>{},onFocusDevice:()=>Vt(X.deviceId),onOpenControl:()=>si(X.deviceId),onCycleMonitor:n=>ku(X.deviceId,n),onCanvasReady:ev,sendInput:rs,remotePointerFeedback:sv,remoteModifierState:gu,presentationReady:Ql,remoteDiagnostics:Ut?ss.get(X.deviceId):fn?ui.get(X.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},X.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(Ra,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),X&&iu&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(wo,{size:22,"aria-hidden":"true"}),i.jsx("strong",{children:"Accessibility permission required"}),i.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts VuvoDesk, then restart the Mac client."})]}),X&&!iu&&!Ql&&i.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[be!=="error"&&i.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),i.jsx("strong",{children:be==="error"?"Connection failed":"Connecting"}),i.jsx("small",{children:be==="error"?"See the notification for details. Reopen Control to retry.":eo||Pt?"Control stream is recovering. See the notification for details.":pu==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Bt==="list"?i.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[i.jsxs("div",{className:"wall-device-list-head",role:"row",children:[i.jsx("span",{role:"columnheader",children:"Computer"}),i.jsx("span",{role:"columnheader",children:"Status"}),i.jsx("span",{role:"columnheader",children:"CPU"}),i.jsx("span",{role:"columnheader",children:"GPU"}),i.jsx("span",{role:"columnheader",children:"RAM"}),i.jsx("span",{role:"columnheader",children:"VRAM"}),i.jsx("span",{role:"columnheader",children:"Network"}),i.jsx("span",{role:"columnheader",children:"HDD"}),i.jsx("span",{role:"columnheader",children:"Temp"})]}),qm.length>0?qm.map(({device:n,slotNumber:o})=>i.jsx(DM,{device:n,slotNumber:o,selected:Ya.has(n.deviceId),updateIndicator:Eu(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote",onSelect:()=>Cu(n.deviceId),onOpenControl:()=>si(n.deviceId)},n.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(Ra,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"No connected computers"})]})]}):tt?i.jsx("div",{className:`screen-wall atlas-slot-wall size-${Bt}`,style:vm,onClick:n=>{n.currentTarget===n.target&&is()},children:Um.map((n,o)=>n?i.jsx(yd,{device:n,frame:ni.get(n.deviceId),selected:Ya.has(n.deviceId),controlEnabled:!1,showStatus:Cm,monitorIndex:_n(n,gt[n.deviceId]),monitorCount:ka(n),onSelect:()=>Cu(n.deviceId),onFocusDevice:()=>Su(n.deviceId),onOpenControl:()=>si(n.deviceId),onCycleMonitor:l=>ku(n.deviceId,l),onCanvasReady:fs({mode4Enabled:tt,directMode4WallEnabled:Mr,isMac:Nr(n.platform)})==="direct"?Jm:nv,sendInput:rs,remoteModifierState:gu,updateIndicator:Eu(n.deviceId),presentationReady:De.autoStartLive&&Kn.includes(n.deviceId)?Gl.has(n.deviceId):void 0,showPresentationSpinner:De.autoStartLive&&Kn.includes(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},n.deviceId):i.jsx(qh,{index:o},`slot-${o}`))}):i.jsx("div",{className:`screen-wall size-${Bt}`,style:vm,onClick:n=>{n.currentTarget===n.target&&is()},children:Um.map((n,o)=>n?i.jsx(yd,{device:n,frame:ni.get(n.deviceId),selected:Ya.has(n.deviceId),controlEnabled:Cr&&kn&&Ir&&X?.deviceId===n.deviceId,showStatus:Cm,monitorIndex:_n(n,gt[n.deviceId]),monitorCount:ka(n),onSelect:()=>Cu(n.deviceId),onFocusDevice:()=>Su(n.deviceId),onOpenControl:()=>si(n.deviceId),onCycleMonitor:l=>ku(n.deviceId,l),onCanvasReady:Jm,sendInput:rs,remoteModifierState:gu,updateIndicator:Eu(n.deviceId),presentationReady:De.autoStartLive&&Kn.includes(n.deviceId)?Gl.has(n.deviceId):void 0,showPresentationSpinner:De.autoStartLive&&Kn.includes(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},n.deviceId):i.jsx(qh,{index:o},`slot-${o}`))}),i.jsx(_M,{visible:Xb&&!Re})]}),!qi&&!de&&i.jsxs("aside",{className:`right-dock actions-mode ${Ba?"collapsed":""}`,"aria-label":"VuvoDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>wm(n=>!n),"aria-label":Ba?"Show control panel":"Hide control panel",title:Ba?"Show control panel":"Hide control panel",type:"button",children:Ba?i.jsx(tg,{size:18}):i.jsx(ng,{size:18})}),!Ba&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:Om,className:"hidden-file-input",type:"file",multiple:!0,onChange:n=>{n.currentTarget.files&&Tp(n.currentTarget.files),n.currentTarget.value=""}}),i.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[i.jsx(bo,{label:"Control",tooltip:X?iu?"Allow Accessibility for the terminal app that starts VuvoDesk, then restart the Mac client.":Cr?Ir?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(X){if(Re&&kn){jn(!1),B("Remote control paused. Screen viewing stays on.");return}si(X.deviceId)}},disabled:!Cr||!!an,active:kn,pressed:Re&&kn,children:i.jsx(Cs,{size:17})}),i.jsx(bo,{label:"Audio",tooltip:X?sr?Zt?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{gv()},disabled:!Ym||!!an,active:Zt,pressed:Zt,children:an==="audio"?i.jsx(ds,{className:"spin",size:17}):i.jsx(of,{size:17})}),i.jsx(bo,{label:yc?"Retry pause":Yi?"Pause video":"Resume video",tooltip:Ki.length===0?"Select one or more Clients to pause video":yc?"Retry every selected Client whose capture shutdown is unconfirmed":Yi?`Pause video for ${Dn.length} selected Client${Dn.length===1?"":"s"}`:`Resume video for ${Dn.length} selected Client${Dn.length===1?"":"s"}`,onClick:()=>{vv()},disabled:Dn.length===0||!!an,active:!Yi,pressed:!Yi,children:an==="video"?i.jsx(ds,{className:"spin",size:17}):!Yi&&!yc?i.jsx(My,{size:17}):i.jsx(xy,{size:17})}),i.jsx(bo,{label:"Send files",tooltip:cn.length===0&&!Re?"Select one or more Clients to send files":X?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{B(`Choose files to send to ${Av}.`),Om.current?.click()},disabled:!!an||!pt||(Re?!X:cn.length===0),children:i.jsx(Bu,{size:17})}),i.jsx(bo,{label:"Restart",tooltip:X?Qo?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Mu("restart")},disabled:!X||!pt||!!an||!Qo,children:an==="restart"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Ry,{size:17})}),i.jsx(bo,{label:"Sleep",tooltip:X?Qo?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Mu("sleep")},disabled:!X||!pt||!!an||!Qo,children:an==="sleep"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Ay,{size:17})}),i.jsx(bo,{label:"Shut down",tooltip:X?Qo?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Mu("shutdown")},disabled:!X||!pt||!!an||!Qo,danger:!0,children:an==="shutdown"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Iy,{size:17})})]})]}),i.jsx(hs,{children:i.jsx(hh,{hubUrl:K,devices:Me,variant:"dock",selectedDeviceIds:Iv})})]})]})]})})]}),de&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Ei?"active":"",onClick:()=>kb(n=>{const o=!n;return vM(o),o}),type:"button","aria-label":Ei?"Hide computer stats":"Show computer stats","aria-pressed":Ei,title:Ei?"Hide CPU, GPU, RAM, and online status":"Show CPU, GPU, RAM, and online status",children:[i.jsx(Ty,{size:19}),i.jsx("span",{children:"Stats"})]}),i.jsxs("button",{className:It==="wall"?"active":"",onClick:()=>mo("wall"),type:"button",children:[i.jsx(Jh,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:Re?"active":"",onClick:()=>X&&void si(X.deviceId),disabled:!X||!Cr,type:"button",children:[i.jsx(Cs,{size:19}),i.jsx("span",{children:"Control"})]}),!ae&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:Ga?"active":"",onClick:()=>mo("share-files"),type:"button",children:[i.jsx(Zh,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:mc?"active":"",onClick:()=>mo("agents"),type:"button",children:[i.jsx(gl,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:qi?"active":"",onClick:()=>mo("settings"),type:"button",children:[i.jsx(nf,{size:19}),i.jsx("span",{children:"Settings"})]})]})]}),qa&&i.jsxs("aside",{className:`transfer-bar state-${qa.status}`,"aria-live":"polite",children:[i.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:qa.status==="queued"?i.jsx(Cn,{size:18}):qa.status==="failed"?i.jsx(Ma,{size:18}):i.jsx(Py,{size:18})}),i.jsxs("div",{className:"transfer-bar-copy",children:[i.jsx("p",{children:qa.message}),i.jsx("div",{className:"transfer-bar-track",children:i.jsx("span",{style:{width:`${Math.max(0,Math.min(100,qa.progress))}%`}})})]}),i.jsxs("strong",{children:[Math.max(0,Math.min(100,qa.progress)),"%"]})]}),Da&&i.jsxs("aside",{className:`livedesk-toast tone-${Da.tone}`,role:Da.tone==="error"?"alert":"status","aria-live":Da.tone==="error"?"assertive":"polite","aria-busy":Da.tone==="progress",children:[Da.tone==="progress"&&i.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),i.jsx("span",{children:Da.message}),i.jsx("button",{className:"livedesk-toast-close",onClick:()=>B(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(Ma,{size:15})})]})]})}export{T0 as A,cx as H,ag as a,rx as b,ix as c,sx as d,jy as f,ax as g,ox as l,Ju as n,Hd as r,Ct as s};
|
|
182
|
+
`){if(!y("Enter"))return!1;fe=!0;continue}for(const Je of OC(We)){const Ue=n.snapshot();if(!m({type:"text",text:Je,repeat:!1,pressedCodes:Ue.pressedCodes,shiftKey:Ue.shiftKey,ctrlKey:Ue.ctrlKey,altKey:Ue.altKey,metaKey:Ue.metaKey}))return!1;fe=!0}}return fe}};const w=()=>S("browser-window-blur"),Z=()=>S("browser-page-hidden"),ge=()=>{document.visibilityState==="hidden"&&S("browser-document-hidden")};return window.addEventListener("keydown",C,!0),window.addEventListener("keyup",v,!0),window.addEventListener("blur",w),window.addEventListener("pagehide",Z),document.addEventListener("visibilitychange",ge),()=>{window.removeEventListener("keydown",C,!0),window.removeEventListener("keyup",v,!0),window.removeEventListener("blur",w),window.removeEventListener("pagehide",Z),document.removeEventListener("visibilitychange",ge),Dl.current=null,Ai.current=null,S("control-keyboard-owner-changed",!0)}},[sa,Cr,Ir,zc,kp,kn,hp,gp,Sp,rs]);const Mp=(n,o)=>{const l=ol(n);if(!l)return!1;const m=performance.now(),d=nm.current;return d.key===l.key&&d.source!==o&&m-d.at<80?!0:(nm.current={key:l.key,source:o,at:m},Ai.current?.sendKey(l.key)??!1)},xp=s.useCallback(n=>{Ol.current=n;const o=Na.current||X?.deviceId||"";if(!Zt||!o)return;const l=un(Ls.current,o);if(!n){const d=dt.current.get(o)||"";cr(async()=>{await Jn(o,d,"remote-audio-document-hidden")}).catch(C=>{(Na.current||X?.deviceId||"")===o&&(un(!1),dt.current.delete(o),Fr(!1),j(C instanceof Error?C.message:String(C)))});return}const m=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;dt.current.set(o,m),so(async()=>{if(!lr(l,o,m)||!pt||!sr||(Na.current||X?.deviceId||"")!==o)return;const d=await ze(`/api/remote/devices/${encodeURIComponent(o)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},Y);if(d?.ok===!1)throw new Error(d.error||"Remote audio presentation resume failed.");lr(l,o,m)||(await Jn(o,m,"remote-audio-stale-presentation-compensation"),dt.current.get(o)===m&&dt.current.delete(o))}).catch(d=>{qn.current&&l===Ro.current&&(un(!1),dt.current.delete(o),Fr(!1),j(d instanceof Error?d.message:String(d)))})},[Zt,so,cr,un,pt,Y,lr,sr,X?.deviceId,j,Jn]);s.useEffect(()=>{const n=v=>{const S=qn.current;v!==S&&(qn.current=v,rr.current+=1,ou.current={active:v&&Go.current,epoch:rr.current},v||(Hc(),Bc(rr.current)),xp(v),Lb(v),ve.current&&$({type:"visibility.changed",component:"document",state:v?"visible":"hidden",reason:"presentation-visibility-commit",details:{previous:S?"visible":"hidden",presentationOwnershipEpoch:rr.current}}),v&&!S&&(_b(y=>y+1),sc.current=performance.now()))},o=Jy({readVisible:()=>document.visibilityState==="visible",initialCommittedVisible:qn.current,commitVisibility:n,schedule:(v,S)=>window.setTimeout(v,S),cancel:v=>window.clearTimeout(v)}),l=()=>o.handleVisibilityChange(),m=()=>o.handlePageHide(),d=()=>o.handleForegroundHint(),C=()=>o.handleForegroundHint();return document.addEventListener("visibilitychange",l),window.addEventListener("pagehide",m),window.addEventListener("pageshow",d),window.addEventListener("focus",C),o.handleForegroundHint(),()=>{document.removeEventListener("visibilitychange",l),window.removeEventListener("pagehide",m),window.removeEventListener("pageshow",d),window.removeEventListener("focus",C),o.dispose()}},[$,Hc,Bc,xp]),s.useEffect(()=>{if(!eh({presentationOwnerActive:!!g&&(be==="connecting"||be==="active"||be==="warm"),desiredDeviceCount:g?1:0}))return;const n=g,o=ft("control",n),l=window.setInterval(()=>{const m=performance.now();if(document.visibilityState!=="visible"||m-sc.current<md)return;const d=Hr.current.get(o)||0,C=hr.current.get(o)||0,v=da.current.get(o)||0,S=Wr.current.get(o)||m;Wr.current.has(o)||Wr.current.set(o,S);const y=d<=0,w=y?m-S>Jk:m-d>fd,Z=Zf({lastReceivedAt:d,lastPaintedAt:C,now:m,staleAfterMs:fd}),ge=Jf({paintStale:Z,lastRecoveryAt:gr.current.get(o)||0,now:m,recoveryCooldownMs:Lh,transportRecoveryAfterMs:Oh});if(!w&&ge==="reset-decoder"&&ri(n,"control","decoder-paint-stale")||!w&&ge==="wait")return;if(!(w||ge==="recover-transport")){Z&&ri(n,"control","decoder-paint-stale"),y&&m-S>Xk&&!Fn.current.has(o)&&Zi([n],"control-frame-socket-recovery")&&(Fn.current.set(o,m),Ft("control",n,"socket-reconnect","control-first-frame-socket-recovery",Nt.current.get(o)||0));return}const fe=Fn.current.get(o)||0;if(fe<=0){Zi([n],"control-frame-socket-recovery")&&(Fn.current.set(o,m),Ft("control",n,"socket-reconnect",w?"control-receive-stale":"control-paint-stale",Nt.current.get(o)||0));return}if(m-fe<Dh)return;const Ne=ma.current.get(o)||0;if(Ne>0){if(m-Ne<Eh)return;ma.current.delete(o)}const We=Nt.current.get(o)||0,Je=Le.find(Xr=>Xr.deviceId===n)||tn,Ue=Gh(Je?.platform);if(!w&&ge==="recover-transport"&&Ue==="mode1-jpeg"&&es("mac-control-paint-timeout"))return;if(We>=eM){if(es(y?"no first frame":"stale stream"))return;_e(!1),gn(!1),Un.current=n,Ft("control",n,"terminal",y?"control-first-frame-restart-limit":"control-stream-restart-limit",We),xe("error");return}if(m-v<_h(Zk,We))return;const Yt=y?"control-first-frame-timeout":ge==="recover-transport"?"control-paint-timeout":"control-receive-stale";Lc([n],Yt)&&(Fn.current.delete(o),gr.current.delete(o),da.current.set(o,m),ma.current.set(o,m),Wr.current.set(o,m),Nt.current.set(o,We+1),Vr.current.delete(o),Ft("control",n,"native-restart",Yt,We+1))},650);return()=>window.clearInterval(l)},[Le,tn,g,be,es,Zi,Ft,ri,Lc]),s.useEffect(()=>{!Pt||g&&at.current[g]||Gn!=="mode3-h264-hw"||es(Pt)||(_e(!1),gn(!1),Un.current=ke.current?.deviceId||"",xe("error"))},[Pt,g,Gn,es]),s.useEffect(()=>{!Re||!g||at.current[g]||!eo||(Un.current=g,xe(n=>n==="error"?n:"error"))},[eo,g,Re]),s.useEffect(()=>{if(be!=="error")return;const n=ke.current;if(!n)return;Un.current=n.deviceId,On(za.current,n)||(za.current=n,Wo.current=0);const o=Wo.current,l=o===0?0:Math.min(5e3,500*2**Math.min(o-1,4)),m=window.setTimeout(()=>{On(ke.current,n)&&(++Ht.current,sn.current="",xe("stopping"),Yn(async()=>{if(On(ke.current,n))try{if(!await Xn(n,"control-session-terminal-error"))return;za.current=null,Wo.current=0,Bi.current===n.deviceId?(Bi.current="",Un.current="",xe("idle")):xe("error")}catch(d){if(!On(ke.current,n))return;Wo.current+=1,j(d instanceof Error?d.message:String(d)),xe("error"),Rm(C=>C+1)}}))},l);return()=>window.clearTimeout(m)},[be,Eb,Yn,j,Xn]);const as=s.useCallback(n=>{if(!n||Un.current!==n)return!1;const o=ke.current;return++Ht.current,sn.current="",Wo.current=0,o&&o.deviceId===n?(Bi.current=n,za.current=null,xe("error"),Rm(l=>l+1),!0):(Bi.current="",Un.current="",za.current=null,xe("idle"),!0)},[]);s.useEffect(()=>{if(!eh({presentationOwnerActive:De.autoStartLive,desiredDeviceCount:Gt.length}))return;const n=window.setInterval(()=>{const o=performance.now();if(document.visibilityState!=="visible"||o-sc.current<md)return;const l=1e3/Math.max(1,Mc||Hn||1),m=Math.max(Fh,Math.ceil(l*4)),d=[],C=[];for(const v of Gt){if(C.length+d.length>=aM)break;const S=ft("wall",v),y=Hr.current.get(S)||0,w=y<=0,Z=$r.current.get(S)||o;$r.current.has(S)||$r.current.set(S,Z);const ge=da.current.get(S)||0,D=hr.current.get(S)||0,fe=w||o-y>m,Ne=Zf({lastReceivedAt:y,lastPaintedAt:D,now:o,staleAfterMs:m}),We=Jf({paintStale:Ne,lastRecoveryAt:gr.current.get(S)||0,now:o,recoveryCooldownMs:Lh,transportRecoveryAfterMs:Oh});if(!fe&&We==="reset-decoder"&&ri(v,"wall","decoder-paint-stale")||!fe&&We==="wait")continue;if(!(fe||We==="recover-transport")){Ne&&ri(v,"wall","decoder-paint-stale");continue}const Ue=Fn.current.get(S)||0;if(Ue<=0&&(!w||o-Z>tM)){d.push(v);continue}if(w&&o-Z<=Nh||Ue>0&&o-Ue<Dh)continue;const Yt=Nt.current.get(S)||0;o-ge>=_h(nM,Yt)&&C.push(v)}if(d.length>0&&mu(d,"wall-frame-socket-recovery"))for(const v of d){const S=ft("wall",v);Fn.current.set(S,o),Ft("wall",v,"socket-reconnect","wall-frame-socket-recovery",Nt.current.get(S)||0)}if(C.length>0&&mu(C,"wall-frame-lane-retry"))for(const v of C){const S=ft("wall",v),y=(Nt.current.get(S)||0)+1;Ft("wall",v,"lane-retry","wall-frame-lane-retry",y),Fn.current.set(S,o),gr.current.delete(S),da.current.set(S,o),$r.current.set(S,o),Hr.current.delete(S),hr.current.delete(S),Nt.current.set(S,y),Vr.current.delete(S)}},rM);return()=>window.clearInterval(n)},[Mc,Gt,mu,Ft,ri,De.autoStartLive,Hn]),s.useEffect(()=>{No(Hn),Vi.current=Date.now(),br.current=0,vr.current=0,ar.current=0,zi.current=0,Ui.current=""},[Hn,De.frameMode,De.adaptiveLoadShedding]),s.useEffect(()=>{Tw({h264DecodeAcceleration:De.h264DecodeAcceleration})},[De.h264DecodeAcceleration]),s.useEffect(()=>{if(!pt||Re||Bt==="list"||!De.visibleOnlyLive){Qs([]);return}const n=Om.current;if(!n||typeof IntersectionObserver>"u"){Qs(wc);return}const o=Array.from(n.querySelectorAll("[data-live-device-id]"));if(o.length===0){Qs([]);return}const l=new Map,m=t0(n,me),d=()=>{const v=gd(o.map(S=>String(S.dataset.liveDeviceId||"")).filter(S=>(l.get(S)||0)>0));Qs(S=>hd(S,v)?S:v)},C=new IntersectionObserver(v=>{for(const S of v){const y=String(S.target.dataset.liveDeviceId||"");y&&l.set(y,S.isIntersecting?S.intersectionRatio||.01:0)}d()},{root:m,rootMargin:me?UC:ur.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return o.forEach(v=>C.observe(v)),d(),()=>C.disconnect()},[wc,pt,me,Re,fa,De.visibleOnlyLive,Bt]),s.useEffect(()=>{if(!De.adaptiveLoadShedding||!De.autoStartLive||Gt.length===0){vr.current=0,ar.current=0,zi.current=0,Ui.current="";return}const n=Hn;if(Qi!=="open"||Ja.sampleMs<500||Ja.lastUpdatedAt<=0||zi.current===Ja.lastUpdatedAt)return;zi.current=Ja.lastUpdatedAt;const o=Date.now(),l=Gt.map(D=>{const fe=rc[ft("wall",D)];return{deviceId:D,receive:fe,paint:nc[ft("wall",D)],intentionalIdle:x0(fe?.lastFrame,o)}});if(!l.every(({receive:D,paint:fe})=>{const Ne=D?.lastFrame,We=Math.max(0,Number(Ne?.requestedFps||0)),Je=Ne?er(Ne):"";return M0({receiveSampleMs:Number(D?.sampleMs||0),paintSampleMs:Number(fe?.sampleMs||0),currentGenerationVerified:Ne?.currentGenerationVerified===!0,frameRequestedFps:We,adaptiveFps:Pn})&&fe?.bindingKey===Je})){vr.current=0,ar.current=0,br.current=0;return}const d=[Pn,...l.map(({deviceId:D,receive:fe,intentionalIdle:Ne})=>`${D}:${er(fe.lastFrame)}:${Ne?"idle":"active"}`).sort()].join("|");if(Ui.current!==d){Ui.current=d,vr.current=o,ar.current=0,br.current=0;return}if(!vr.current){vr.current=o,ar.current=0;return}if(o-vr.current<ur.downshiftStableSampleMs)return;const C=l.filter(D=>!D.intentionalIdle),v=C.reduce((D,{receive:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0)),0),S=C.reduce((D,{receive:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0))*Math.max(0,Number(fe?.averageFrameBytes||0)),0),y=C.reduce((D,{paint:fe})=>D+Math.max(0,Number(fe?.framesPerSecond||0)),0),w=Math.max(0,...C.map(({receive:D})=>Number(D?.maxIntervalMs||0))),Z=Math.max(0,...C.map(({paint:D})=>Number(D?.p95IntervalMs||0))),ge=C.length===0?{overloaded:!1,healthyForRecovery:!0}:k0({directDeviceCount:C.length,requestedFps:Pn,measuredFramesPerSecond:v,measuredPaintFramesPerSecond:y,measuredBytesPerSecond:S,maxBytesPerSecond:ur.maxWallBytesPerSecond,worstReceiveGapMs:w,worstPaintP95Ms:Z,maxFrameGapMs:ur.maxFrameGapMs});if(ge.overloaded){if(br.current=0,ar.current+=1,ar.current<ur.downshiftConsecutiveSamples)return;const D=ur.minFps;if(o-Vi.current>=ur.downshiftCooldownMs&&Pn>D){const fe=Math.max(D,RM(Pn,D));fe<Pn&&(No(fe),Vi.current=o,vr.current=0,ar.current=0)}return}if(ar.current=0,!ge.healthyForRecovery||Pn>=n){ge.healthyForRecovery||(br.current=0);return}if(!br.current){br.current=o;return}if(o-br.current>=ur.recoveryCooldownMs){const D=Math.min(n,AM(Pn,n));D>Pn&&(No(D),Vi.current=o,br.current=0,vr.current=0,ar.current=0)}},[Pn,Gt.length,Gt,nc,rc,Qi,Ja.lastUpdatedAt,Ja.sampleMs,De.adaptiveLoadShedding,De.autoStartLive,De.frameMode,Hn]),s.useEffect(()=>{const n=new URLSearchParams(window.location.search).get("checkout");if(n==="success"){j("Checkout returned. Waiting for Dodo confirmation."),vt();const o=window.setInterval(()=>{vt()},4e3),l=window.setTimeout(()=>{window.clearInterval(o)},45e3);return()=>{window.clearInterval(o),window.clearTimeout(l)}}n==="cancelled"&&j("Checkout cancelled.")},[vt]),s.useEffect(()=>{!pt&&kn&&jn(!1),!pt&&Zt&&(un(!1),Fr(!1))},[Zt,kn,un,pt]),s.useEffect(()=>{Zt&&(!X||!sr)&&(un(!1),Fr(!1))},[Zt,un,sr,X]),s.useEffect(()=>{const n=X?.deviceId||"",o=Na.current;if(Na.current=n,!o||o===n)return;const l=un(Zt,n),m=n?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";n&&Zt&&dt.current.set(n,m);let d=!0;const C=dt.current.get(o)||"";return(async()=>{try{await cr(async()=>{await Jn(o,C,"remote-audio-device-switch"),dt.current.delete(o)}),await so(async()=>{if(!d||!lr(l,n,m)||!n||!pt||!sr)return;const v=await ze(`/api/remote/devices/${encodeURIComponent(n)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:m,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},Y);if(v.ok===!1)throw new Error(v.error||"Remote audio start failed.");lr(l,n,m)||(await Jn(n,m,"remote-audio-stale-device-switch-compensation"),dt.current.get(n)===m&&dt.current.delete(n))})}catch(v){d&&(un(!1),dt.current.delete(n),Fr(!1),j(v instanceof Error?v.message:String(v)))}})(),()=>{d=!1}},[Zt,so,cr,un,pt,Y,lr,sr,X?.deviceId,Jn]),s.useEffect(()=>{const n=Le.map(d=>d.deviceId),o=new Set(n),l=new Map(Le.map(d=>[d.deviceId,d])),m=new Map;for(const d of Le){const C=uM(d);if(!C)continue;const v=dr(d.status),S=[d.lastStatusAt,v.capturedAt,v.collectedAt,v.timestamp,v.updatedAt].find(w=>typeof w=="string"&&w.trim()),y=HC(Fi.current[d.deviceId],C,S);y&&(Fi.current[d.deviceId]=y,m.set(d.deviceId,y),Yg({platform:d.platform,topologyFingerprint:C,consecutiveTopologySamples:y.consecutiveSamples})&&(Mm.current[d.deviceId]=C))}for(const d of Object.keys(Fi.current))o.has(d)||delete Fi.current[d];At(d=>{const C=d.filter(v=>o.has(v));return hd(d,C)?d:C}),Jt(d=>d&&o.has(d)?d:""),Vt(d=>d&&o.has(d)?d:""),Vl(d=>{let C=!1;const v={};for(const[S,y]of Object.entries(d)){const w=l.get(S);if(!w){v[S]=y;continue}const Z=m.get(S)||Fi.current[S],ge=WC({requestedIndex:y,monitorCount:ka(w),platform:w.platform,topologyFingerprint:Z?.fingerprint||"",consecutiveTopologySamples:Z?.consecutiveSamples||0});v[S]=ge,ge!==y&&(C=!0)}return C?v:d}),nu(d=>{const C=d.filter(v=>o.has(v));return hd(d,C)?d:C})},[Le,gc]),s.useEffect(()=>{Bb([]),Wb(!1)},[Yr]),s.useEffect(()=>{!Ga||Uo!=="selected"||qo.length>0||cn.length===0||nu(cn.map(n=>n.deviceId))},[cn,qo.length,Uo,Ga]),s.useEffect(()=>{try{localStorage.setItem(ob,Oo)}catch{}},[Oo]),s.useEffect(()=>{gM(De)},[De]),s.useEffect(()=>{vM(on)},[on]),s.useEffect(()=>{fM(gt,Mm.current)},[Le,gt]);const Uc=s.useCallback(async()=>{const n=new Set(L);n.add(In);try{const C=await ze("/api/remote/status",void 0,In);Xp({endpoint:C.agentEndpoint,endpoint_candidates:[...C.agentEndpointCandidates||[],...C.hostTargetEndpointCandidates||[]]}).forEach(v=>n.add(v))}catch{}const o=[...n].sort((C,v)=>{const S=y=>{const w=fl(y);return w==="local"?0:w==="loopback"?1:2};return S(C)-S(v)||C.localeCompare(v)});let l=!1,m="",d=!1;try{for(const C of o){const v=fl(C);try{if(await ze("/api/health",void 0,C),v==="local")return Ce(!0),hi(!0),C;v==="loopback"&&(l=!0,m=C)}catch{v==="local"&&(d=!0)}}return l?(d&&j("VuvoDesk Hub is reachable on this PC, but not through the LAN address yet. Restart VuvoDesk Hub to bind 5179 on the network."),Ce(!0),hi(!0),m||In):(Ce(!1),hi(!1),"")}catch{return Ce(!1),hi(!1),""}},[L]),Qr=async()=>{if(Mn("auth"),Or(!1),window.liveDesk?.auth?.signInWithGoogle){const m=window.liveDesk.auth.signInWithGoogle();Uc();const d=await m;d?.ok===!1&&(j(d.error||"VuvoDesk could not open the system browser for Google sign-in."),Mn(""));return}const n=Ct.auth.signInWithOAuth({provider:"google",options:{redirectTo:ay(window.location.href,oy)}});Uc();const{data:o,error:l}=await n;l&&(j(l.message),Mn(""))},dv=async()=>{Mn("auth"),Or(!1);const n=!!window.liveDesk?.auth?.signOut;try{if(n)(await window.liveDesk.auth.signOut())?.runtimeCleared===!1&&j("Signed out locally. The VuvoDesk runtime could not be reached to clear its session.","error");else{await k();const{error:o}=await Ct.auth.signOut({scope:"local"});if(o)throw o}}catch(o){j(`Sign-out is not complete: ${o instanceof Error?o.message:String(o)}. Remote access stays blocked; open Account and retry.`,"error")}Mn("")},Rp=s.useCallback(async(n={})=>{const o=n.silent===!0,l=n.takeover===!0,m=n.requestLocalAccess===!0;if(!r?.user){o||j("Sign in before publishing this host.","error");return}if(W){o||j("Open VuvoDesk on the Hub computer to sync or configure that Hub.","error");return}if(re){o||j("Only the Team owner can sync or configure the Hub.","error");return}if(!G){o||j("Choose a workspace before syncing the Hub.","error");return}if(ru.current)return;const d=G,C=O,v=()=>ie.current===C&&q(d),S=()=>{if(!v())throw new Error("The active VuvoDesk workspace changed while Hub sync was running.")};ru.current=!0,o||(Mn("host"),Bn("Hub · 1/3 · Checking the local runtime…"));try{const y=m?await Uc():"";S();const w=y||Y||In,Z=z||await ze("/api/remote/status",void 0,w);if(S(),!Z.started)throw new Error("Start VuvoDesk on this computer before syncing the server.");o||Bn("Hub · 2/3 · Publishing the current workspace endpoint…"),S();const ge=await ze("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:l})},w);if(S(),!ge.ok)throw new Error(ge.error||"host-target-failed");if(!o){Bn("Hub · 3/3 · Verifying the endpoint and lease renewal…");const D=await ze("/api/hub/status",void 0,w);if(S(),!D.hostTargetActive)throw new Error(D.hostTargetLease?.lastError||"host-target-not-active-after-sync");const fe=D.hostTargetEndpoint||D.agentEndpoint||"endpoint ready",Ne=Number(D.connectedDeviceCount||0),We=Ne>0?`${Ne} client${Ne===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";j(`Hub ready · ${fe} · lease auto-renewal active. ${We}`,"success"),(m||Ve)&&(Ce(!0),hi(!0)),Te()}S(),se()}catch(y){if(!o){if(!v()){j("Hub sync stopped because the active workspace changed.","info");return}const w=y instanceof Error?y.message:String(y);w.includes("local network access")&&(Ce(!1),hi(!1)),j(`Hub setup failed · ${w}`,"error")}}finally{ru.current=!1,o||Mn(y=>y==="host"?"":y)}},[G,q,Y,Ve,W,Te,se,Uc,r,j,Bn,z,re,O]),os=s.useCallback((n=!0)=>{tt!=="host"&&(_l(!1),n&&window.requestAnimationFrame(()=>um.current?.focus()))},[tt]),mv=s.useCallback(()=>{if(tt!=="host"){if(re){j("Only the Team owner can sync or configure the Hub.","error");return}um.current=document.activeElement instanceof HTMLElement?document.activeElement:null,Or(!1),_l(!0)}},[tt,j,re]),pv=s.useCallback(()=>{_l(!1),Rp({takeover:!0,requestLocalAccess:!0})},[Rp]);s.useEffect(()=>{if(!Po)return;const n=window.requestAnimationFrame(()=>lm.current?.focus()),o=m=>{m.target instanceof Element&&m.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||os(!1)},l=m=>{m.key==="Escape"&&os()};return window.addEventListener("pointerdown",o),window.addEventListener("keydown",l),()=>{window.cancelAnimationFrame(n),window.removeEventListener("pointerdown",o),window.removeEventListener("keydown",l)}},[os,Po]);const Ap=s.useCallback(async()=>{if(!(!z?.update?.canApply||tt==="update")){Mn("update");try{const n=await ze("/api/update/apply",{method:"POST",body:JSON.stringify({})},Y||In);if(!n.ok)throw new Error(n.error||"VuvoDesk update could not be started.");const o=[...new Set((n.targets||[]).map(d=>String(d.deviceId||"").trim()).filter(Boolean))],l=!!(n.managerUpdateAvailable||n.clientPackageUpdateAvailable),m=n.state==="hub-restart-requested"?Date.now():void 0;(o.length>0||l)&&fr({operationId:String(n.operationId||`wall-update-${Date.now()}`),targetIds:o,stage:n.state==="clients-updated"?"updated":"updating",requiresHubRestart:l,initialHostInstanceId:String(z.hostInstanceId||""),targetManagerVersion:String(n.latestVersion||z.update?.latestVersion||""),targetClientVersion:String(n.latestClientVersion||z.update?.latestClientVersion||""),restartRequestedAt:m,restartDeadlineAt:m?m+dl:void 0}),Bn(n.state==="hub-restart-requested"?ul:Ch),Te()}catch(n){j(n instanceof Error?n.message:String(n),"error")}finally{Mn("")}}},[tt,Y,Te,j,Bn,z]);s.useEffect(()=>{const n=et,o=z?.update;if(!n||n.stage!=="updating"||!o)return;const l=o.restartResult?.operationId===n.operationId?o.restartResult:null;if(l?.outcome==="restored"){const y=l.error||`The requested Hub ${l.targetVersion||n.targetManagerVersion||"version"} failed verification.`;fr(w=>w?.operationId===n.operationId?{...w,stage:"restored",error:y}:w),j(`VuvoDesk update did not complete. Hub ${l.fallbackVersion||l.appVersion||"the previous version"} was restored. ${y}`,"error");return}if(l?.outcome==="failed"){const y=l.error||"No verified VuvoDesk Hub replacement could be started.";fr(w=>w?.operationId===n.operationId?{...w,stage:"failed",error:y}:w),j(`VuvoDesk Hub update failed. ${y}`,"error");return}if(o.operationId===n.operationId&&o.state==="failed"){const y=o.error||"VuvoDesk update failed before the Hub replacement completed.";fr(w=>w?.operationId===n.operationId?{...w,stage:"failed",error:y}:w),j(y,"error");return}if(o.operationId===n.operationId){if(o.state==="hub-restart-requested"&&!n.restartDeadlineAt){const y=Date.now();fr(w=>w?.operationId===n.operationId?{...w,restartRequestedAt:y,restartDeadlineAt:y+dl}:w),Bn(ul)}!n.requiresHubRestart&&o.state==="clients-updated"&&(fr(y=>y?.operationId===n.operationId?{...y,stage:"updated"}:y),j("VuvoDesk clients updated and reconnected successfully.","success"));return}if(!n.requiresHubRestart)return;const m=z.started===!0&&(!n.initialHostInstanceId||z.hostInstanceId&&z.hostInstanceId!==n.initialHostInstanceId),d=!!o.checkedAt,C=xh(o.currentVersion,n.targetManagerVersion),v=!n.targetClientVersion||xh(o.currentClientVersion,n.targetClientVersion),S=d&&o.state==="idle"&&o.updateAvailable===!1&&C&&v;m&&S&&(fr(y=>y?.operationId===n.operationId?{...y,stage:"updated"}:y),j(`VuvoDesk Hub ${o.currentVersion||l?.appVersion||n.targetManagerVersion} restarted and passed version verification.`,"success"))},[j,Bn,z,et]),s.useEffect(()=>{const n=et;if(!n||n.stage!=="updating"||!n.requiresHubRestart||n.restartDeadlineAt)return;const o=()=>{const m=Date.now();fr(d=>d?.operationId===n.operationId&&d.stage==="updating"&&!d.restartDeadlineAt?{...d,restartRequestedAt:m,restartDeadlineAt:m+dl}:d),Bn(ul)};if(z?.update?.state==="hub-restart-requested"){o();return}if(!je)return;const l=window.setTimeout(o,Vk);return()=>window.clearTimeout(l)},[je,Bn,z?.update?.state,et]),s.useEffect(()=>{const n=et;if(!n||n.stage!=="updating"||!n.requiresHubRestart||!n.restartDeadlineAt)return;const o=Math.max(0,n.restartDeadlineAt-Date.now()),l=n.operationId,m=window.setTimeout(()=>{const d=`VuvoDesk Hub did not return and verify ${n.targetManagerVersion||"the requested version"} within ${Math.round(dl/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;fr(C=>C?.operationId===l&&C.stage==="updating"?{...C,stage:"failed",error:d}:C),j(d,"error")},o);return()=>window.clearTimeout(m)},[j,et]),s.useEffect(()=>{if(!et||et.stage!=="updated")return;const n=et.operationId,o=window.setTimeout(()=>{fr(l=>l?.operationId===n?null:l)},kh);return()=>window.clearTimeout(o)},[et]),s.useEffect(()=>{Ul.current.clear(),zl({})},[et?.operationId]),s.useEffect(()=>{if(!et||z?.update?.operationId!==et.operationId)return;const n=(z.update.targets||[]).filter(l=>l.state==="completed").map(l=>Mh(et.operationId,l)).filter(l=>!Ul.current.has(l));if(n.length===0)return;const o=Date.now()+kh;for(const l of n)Ul.current.add(l);zl(l=>({...l,...Object.fromEntries(n.map(m=>[m,o]))}))},[z?.update,et]),s.useEffect(()=>{const n=Math.min(...Object.values(Ys));if(!Number.isFinite(n))return;const o=window.setTimeout(()=>{const l=Date.now();zl(m=>Object.fromEntries(Object.entries(m).filter(([,d])=>d>l)))},Math.max(0,n-Date.now()));return()=>window.clearTimeout(o)},[Ys]),s.useEffect(()=>{if(jl!==Ch&&jl!==ul)return;const n=z?.update;if(String(n?.state||"")==="failed"){j(n?.error||"VuvoDesk update failed.","error");return}et?.stage==="updated"&&j("")},[jl,j,z?.update?.error,z?.update?.state,et?.stage]);const fv=s.useCallback(async()=>{if(!tt){Mn("pin");try{const o=await ze("/api/remote/pairing-pin",{method:"POST"},Y||In);if(!o.ok)throw new Error(o.error||"pin-rotation-failed");await Te(),j("New PIN published.")}catch(n){j(n instanceof Error?n.message:String(n))}finally{Mn("")}}},[tt,Y,Te]),Su=s.useCallback(n=>{n&&(Jt(n),At(o=>o.includes(n)?o:[...o,n]))},[]),Cu=s.useCallback(n=>{if(!n)return;const o=Ya.has(n);Jt(l=>o?l===n?"":l:n),At(l=>o?l.filter(m=>m!==n):l.includes(n)?l:[...l,n])},[Ya]),is=s.useCallback(()=>{At([]),Jt("")},[Kr]),Ip=s.useCallback(()=>{At(Le.map(n=>n.deviceId)),Jt("")},[Le]),ku=s.useCallback((n,o)=>{const l=Le.find(d=>d.deviceId===n);if(!l)return;const m=ka(l);if(!(m<=1)&&(Vl(d=>{const C=ys(d[n],m),v=(C+o+m)%m;return v===C?d:{...d,[n]:v}}),Dt("wall",n),Dt("control",n),Li(d=>{if(!d.has(n))return d;const C=new Set(d);return C.delete(n),C}),Wa.current.delete(n),jr.current.delete(n),Re)){const d=as(n);_e(!1),d||xe("connecting"),gn(!1),Vt(n)}},[Le,Dt,as,Re]);s.useEffect(()=>{const n=o=>{if(Ks.current||kn&&Cr&&Ir)return;const l=o.target,m=l?.tagName?.toLowerCase();l?.isContentEditable||m==="input"||m==="textarea"||m==="select"||((o.ctrlKey||o.metaKey)&&o.key.toLowerCase()==="a"&&(o.preventDefault(),Ip()),o.key==="Escape"&&is())};return window.addEventListener("keydown",n),()=>window.removeEventListener("keydown",n)},[Cr,is,Ir,kn,Ip]);const hv=(n,o)=>{const l=Le.find(v=>v.deviceId===n),m=l?ka(l):1,d=ys(gt[n],m),C=ys(o,m);if(d!==C&&(Vl(v=>({...v,[n]:C})),Li(v=>{if(!v.has(n))return v;const S=new Set(v);return S.delete(n),S}),Wa.current.delete(n),jr.current.delete(n),ca.current.delete(n),_o.current.delete(n),$a.current.delete(n),Dt("wall",n),Dt("control",n)),Re){const v=as(n);d!==C&&(_e(!1),v||xe("connecting")),gn(!1),Vt(n)}else Su(n)},gv=n=>{const o=Na.current||X?.deviceId||"",l=[...new Set([o,n].filter(Boolean))],m=Zt||l.some(d=>dt.current.has(d));un(!1),Fr(!1);for(const d of l)dt.current.delete(d);l.length!==0&&(async()=>{for(const d of l)await cr(()=>bu(d,"remote-audio-control-entry"))})().catch(d=>{m&&j("Remote audio was muted locally, but Client capture stop was not confirmed: "+(d instanceof Error?d.message:String(d)),"error")})},si=async n=>{const o={requestId:++Db.current,deviceId:n,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(Br.current=o,!Sr.has(n)){Br.current?.requestId===o.requestId&&(Br.current=null),jn(!1),j(Xo);return}const l=Le.find(d=>d.deviceId===n);if(Nr(l?.platform)&&(l?.capabilities?.controlPermission===!1||l?.capabilities?.accessibilityPermission===!1)){Br.current?.requestId===o.requestId&&(Br.current=null),jn(!1),j("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts VuvoDesk, then restart the Mac client.","error");return}gv(n),as(n),gn(!1),Vt(n),La("control"),jn(!0),j(`Opening remote control${l?` for ${Qt(l)}`:""}.`,"success")},bv=async()=>{if(!X){j("Select a Client before playing audio.");return}if(!pt){j(Xo);return}if(!sr){j("Selected Client does not report remote audio support yet.");return}if(an)return;const n=!Zt,o=n?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:dt.current.get(X.deviceId),l=un(n,X.deviceId);n&&o?dt.current.set(X.deviceId,o):n||dt.current.delete(X.deviceId),To("audio"),Fr(n);try{n?(await cr(()=>bu(X.deviceId,"remote-audio-user-enable-reconcile")),await so(async()=>{if(!o||!lr(l,X.deviceId,o))return;const m=await ze(`/api/remote/devices/${encodeURIComponent(X.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:o,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},Y);if(m?.ok===!1)throw new Error(m.error||"Remote audio start failed.");lr(l,X.deviceId,o)||await Jn(X.deviceId,o,"remote-audio-stale-user-start-compensation")})):await cr(()=>bu(X.deviceId,"remote-audio-user-disabled")),j(`${n?"Audio started":"Audio stopped"} for ${Qt(X)}.`,"success")}catch(m){un(!1),n&&dt.current.delete(X.deviceId),Fr(!1),j(m instanceof Error?m.message:String(m),"error")}finally{To("")}},vv=async(n,o)=>{const l=n.deviceId,m=Qt(n),d=String(at.current[l]||""),C=!!d&&Ao[l]===!0;if(o&&d&&!C)return{ok:!0,skipped:!0,action:"pause",deviceId:l,title:m};if(!o&&!d)return{ok:!0,skipped:!0,action:"resume",deviceId:l,title:m};if(!o&&d.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:l,title:m,error:"Pause is still pending confirmation."};if(o){const Z=d||`pending:${Date.now()}:${l}`,ge=ke.current?.deviceId===l?ke.current:null,D=!!ge||g===l,fe=D?++Ht.current:0,Ne=()=>uf({deviceId:l,requestTransitionGeneration:fe,currentTransitionGeneration:Ht.current,actualControlOwner:ke.current}),We=ra.current.get(l);ra.current.set(l,{deviceId:l,monitorIndex:_n(n,gt[l]??We?.monitorIndex),previousControlOwner:ge||We?.previousControlOwner||null}),cm(l,!0),Io(l,!1),js(l,Z),fu(l),D&&(sn.current="",xe("paused"));try{const Je=await ze(`/api/remote/devices/${encodeURIComponent(l)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},Y);if(!Je?.pauseToken)return Fa.current.delete(l),js(l,""),Io(l,!1),ra.current.delete(l),Ne()&&(rt.current=null,ht(null),_e(!1),he(`control-pause-rollback-${Date.now()}-${l}`),xe("connecting")),{ok:!1,action:"pause",deviceId:l,title:m,error:Je?.error||"video-capture-pause-failed"};const Ue=String(at.current[l]||"");if(Ue!==Z&&Ue!==Je.pauseToken)return{ok:!1,action:"pause",deviceId:l,title:m,error:"Pause ownership changed before confirmation."};const Yt=Ne(),Xr=Yt&&ke.current?.deviceId===l?ke.current:ge,fo=ra.current.get(l);return fo&&(fo.previousControlOwner=Xr),Yt&&ke.current?.deviceId===l&&(ke.current=null),Yt&&(rt.current=null,ht(null)),js(l,Je.pauseToken),Yt&&xe("paused"),Je.ok===!1||Je.captureStopConfirmed!==!0?(Io(l,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:l,title:m,error:Je.stopError||Je.error||"Client capture shutdown was not confirmed."}):(Io(l,!1),{ok:!0,action:"pause",deviceId:l,title:m})}catch(Je){return Io(l,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:l,title:m,error:Je instanceof Error?Je.message:String(Je)}}}const v=ra.current.get(l),S=v?.previousControlOwner||null,y=g===l&&(S!==null||xn.current?.deviceId===l||be==="paused"),w=y?Ht.current:0;try{cm(l,!1);const Z=await ze(`/api/remote/devices/${encodeURIComponent(l)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:d})},Y);if(Z?.ok===!1)throw new Error(Z.error||"video-capture-resume-failed");if(String(at.current[l]||"")!==d)return{ok:!1,action:"resume",deviceId:l,title:m,error:"Resume ownership changed before confirmation."};const ge=ra.current.get(l)||v,D=ge?.previousControlOwner||S,fe=y&&uf({deviceId:l,requestTransitionGeneration:w,currentTransitionGeneration:Ht.current,actualControlOwner:ke.current});if(js(l,""),Io(l,!1),ra.current.delete(l),fe){const Ne=++Ht.current;sn.current="";const We=Uu(l,Ne,{sessionId:n.sessionId||D?.sessionId,monitorIndex:_n(n,gt[l]??ge?.monitorIndex)});ke.current=We,Qn(We),Un.current="",za.current=null,rt.current=null,ht(null),Ie(""),zt(""),_e(!1),Dt("control",l);const Je=`control-video-resume-${Ne}-${l}`;he(Je),U(l),xe("connecting")}else Dt("wall",l);return{ok:!0,action:"resume",deviceId:l,title:m}}catch(Z){return Fa.current.delete(l),{ok:!1,action:"resume",deviceId:l,title:m,error:Z instanceof Error?Z.message:String(Z)}}},yv=async()=>{if(Ki.length===0){j("Select one or more Clients before pausing video.");return}if(Dn.length===0){j(Xo);return}if(an)return;const n=Dn.some(l=>{const m=String(at.current[l.deviceId]||"");return!m||m.startsWith("pending:")||Ao[l.deviceId]===!0}),o=Dn.filter(l=>{const m=String(at.current[l.deviceId]||"");return n?!m||m.startsWith("pending:")||Ao[l.deviceId]===!0:!!m});if(o.length===0){j(n?"Selected Clients are already paused.":"Selected Clients are already playing.");return}To("video");try{const l=await Promise.all(o.map(w=>vv(w,n)));Te();const m=l.filter(w=>w.ok&&!w.skipped),d=l.filter(w=>!w.ok&&w.unconfirmed),C=l.filter(w=>!w.ok&&!w.unconfirmed),v=Dn.length-o.length+l.filter(w=>w.skipped).length,S=Ki.length-Dn.length,y=n?"pause":"resume";if(C.length>0||d.length>0){const w=C.slice(0,2).map(Z=>`${Z.title}: ${Z.error||"unknown error"}`).join(" · ");j([`Video ${y} completed for ${m.length}/${o.length} Clients.`,d.length>0?`${d.length} Client capture stop${d.length===1?"":"s"} remain unconfirmed.`:"",w,S>0?`${S} selected Client${S===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}j([`Video ${n?"paused":"resumed"} for ${m.length} Client${m.length===1?"":"s"}.`,v>0?`${v} already ${n?"paused":"playing"}.`:"",S>0?`${S} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{To("")}},wv=n=>{const o=n instanceof Error?n.message:String(n);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(o)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(o)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(o)?"This Client needs a newer VuvoDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(o)?"The Client disconnected before the action could be sent.":o},Mu=async n=>{if(!X||an)return;const o=X,m={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[n];if(window.confirm(`${m} ${Qt(o)}? Unsaved work on that computer may be lost.`)){To(n),j(`Sending ${m.toLowerCase()} request to ${Qt(o)}...`);try{const d=await ze(`/api/remote/devices/${encodeURIComponent(o.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:n})},Y);if(!d.ok)throw new Error(d.error||"The remote action could not be sent.");j(`${m} request sent to ${Qt(o)}.`,"success"),Te()}catch(d){j(wv(d),"error")}finally{To("")}}},Tp=async(n,o,l="files")=>{const m=n.filter(S=>S.file.size>=0);if(m.length===0)return{files:0,bytes:0};if(!pt)throw new Error(Xo);if(o.length===0)throw new Error("Select at least one connected Client.");const d=crypto.randomUUID(),C=m.reduce((S,y)=>S+y.file.size,0);let v=0;pa({id:d,status:"reading",progress:1,message:`Preparing ${m.length} ${l}`});try{for(let S=0;S<m.length;S+=1){const y=m[S],w=y.file,Z=Math.max(1,Math.ceil(w.size/dd));for(let ge=0;ge<Z;ge+=1){const D=ge*dd,fe=Math.min(w.size,D+dd),Ne=w.size===0?new ArrayBuffer(0):await w.slice(D,fe).arrayBuffer(),We=ge===Z-1;pa({id:d,status:"sending",progress:Math.max(2,Math.min(98,Math.round(v/Math.max(1,C)*96))),message:`${S+1}/${m.length} ${y.relativePath}`});const Je=await ze("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:d,deviceIds:o,remoteDirectory:Oo.trim(),name:w.name,relativePath:y.relativePath,size:w.size,type:w.type,lastModified:w.lastModified,offset:D,totalBytes:w.size,final:We,dataBase64:IM(Ne)})},Y);if(!Je.ok||Je.queued!==o.length)throw new Error(Je.error||`file-chunk-not-queued-${Je.queued}/${o.length}`);v+=Ne.byteLength,await new Promise(Ue=>window.setTimeout(Ue,0))}}return pa({id:d,status:"queued",progress:100,message:`Sent ${m.length} file${m.length===1?"":"s"} to ${o.length} Client${o.length===1?"":"s"}`}),window.setTimeout(()=>{pa(S=>S?.id===d&&S.status==="queued"?null:S)},4500),{files:m.length,bytes:C}}catch(S){throw pa({id:d,status:"failed",progress:100,message:S instanceof Error?S.message:String(S)}),S}},Pp=async n=>{const o=cn.length>0?cn.map(l=>l.deviceId):X?[X.deviceId]:[];try{await Tp(Hh(n),o)}catch(l){j(l instanceof Error?l.message:String(l))}},Ep=async n=>{try{await Tp(Hh(n),Qb)}catch(o){j(o instanceof Error?o.message:String(o))}};s.useEffect(()=>{zb.current=!1},[]);const Sv=n=>{n.preventDefault(),n.stopPropagation(),tu(!1),Pp(n.dataTransfer.files)},lo=async(n="plus_ltd")=>{const o=L0(n);if(!o){j("This VuvoDesk checkout option is not recognized.");return}if(!r){j("Sign in with Google before checkout.");return}if(T||!b){j("Your VuvoDesk workspace is still loading. Try again in a moment.");return}if(re){j("The Team owner manages billing and plan changes.");return}if(!ch(n)&&!An){j("VuvoDesk LTD checkout is not open yet.");return}if(ch(n)&&!id(n)&&!Sa){j("VuvoDesk Plus and Pro monthly checkout is not open yet.");return}if(id(n)&&!Jr){j("VuvoDesk Team checkout is not open yet. Contact support to join the Team launch group.");return}const l=b?.kind==="personal"&&b.id===r.user.id;if(o!=="team"&&l&&oe&&o===Xe){j("VuvoDesk license is already active.");return}if(o!=="team"&&l&&oe&&Xe==="pro"){j("VuvoDesk Pro is already active.");return}Mn("checkout");try{let m=r.user.id;if(id(n)){let v=M.find(S=>S.kind==="team"&&S.role==="owner")?.id||"";if(v)G!==v&&await B(v);else{const{data:S,error:y}=await Ct.rpc("create_livedesk_team_workspace",{p_name:`${uo||"My"} Team`});if(y)throw y;const w=Array.isArray(S)?S[0]:S,Z=String(w?.workspace_id||"").trim();if(!w?.ok||!Z)throw new Error(String(w?.reason||"Team Space could not be created."));await B(Z),v=Z}m=v}const{data:d,error:C}=await Ct.functions.invoke("dodo-checkout",{body:{plan:n,workspace_id:m}});if(C)throw C;if(!d?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(d.checkout_url)}catch(m){j(m instanceof Error?m.message:String(m)),Mn("")}},qc=oM(),Np=iM(),xu=cu.filter(n=>ni.has(n)).length,Ru=pu==="open"&&Oc.sampleMs>0?`${Oc.framesPerSecond.toFixed(1)} fps`:pu,le=X?Re?Ji.get(X.deviceId):ni.get(X.deviceId):void 0,Gc=X?_n(X,gt[X.deviceId]):0,Cv=X?lM(X):[],kv=typeof le?.monitorIndex=="number"?ys(le.monitorIndex,Math.max(1,le.monitorCount||1)):Gc,Au=(le&&kv===Gc?bb(le):null)||(X?gb(X,Gc):null);Au&&`${Au.width}${Au.height}`;const Kc=X?ft(Re?"control":"wall",X.deviceId):"",rn=Kc?rc[Kc]:void 0,Ln=Kc?nc[Kc]:void 0,Ee=Ln?.lastInfo,Mv=rn&&rn.sampleMs>0?`${rn.framesPerSecond.toFixed(1)} fps`:"waiting";rn&&`${rn.totalFrames}${Mv}`,Ln&&Ln.sampleMs>0&&`${Ln.framesPerSecond.toFixed(1)}`,Ln&&Ln.sampleMs>0&&`${Ln.changedFramesPerSecond.toFixed(1)}`,Ee&&(`${Ee.frameSeq}${Ee.decoderLabel}${Ee.queueSize}${Ee.renderQueueSize}${Ee.droppedForLatency}${Ee.decoderFlushCount}${Ee.decoderTimestampFallbacks}${Ee.decoderInputCount}${Ee.decoderOutputCount}`,Ee.visualChanged),Ee&&`${Math.round(Ee.queuedForMs)}${Math.round(Ee.decodedForMs)}${Math.round(Ee.scheduledForMs)}${Ee.drawMs.toFixed(1)}`,Ee?.targetPaintIntervalMs&&`${Ee.targetPaintIntervalMs.toFixed(1)}${(1e3/Ee.targetPaintIntervalMs).toFixed(1)}`,Ln&&`${Ln.decoderInputFps.toFixed(1)}${Ln.decoderOutputFps.toFixed(1)}`,Ee?.canvasPresentation,Ee&&`${Ee.interactiveBufferWaitCount}${Math.round(Ee.interactiveBufferWaitMs)}${Ee.interactiveQueueDrainCount}`,rn&&(le?.frameMode==="mode5-lzo-delta"?`${ws(rn.averageFrameBytes)}${le.deltaVisualTileCount||0}${le.deltaRefreshTileCount||0}${le.deltaTotalTiles||0}`:`${ws(rn.averageFrameBytes)}${Math.round(rn.tinyFrameRatio*100)}${Math.round(rn.repeatedFrameRatio*100)}`),rn&&rn.sourceSendSampleCount>0&&`${rn.sourceSendAverageMs.toFixed(1)}${rn.sourceSendP95Ms.toFixed(1)}`,Ih(rn),Ih(Ln),rn&&Ln&&`${Th(rn)}${Th(Ln)}`,le?le.frameMode||le.mode||le.codec||le.mimeType:Re?on.frameMode:De.frameMode,Re?on.frameMode:De.frameMode,le?`${le.width}${le.height}${ws(le.byteLength)}`:Re?`${wr.maxWidth}${wr.maxHeight}`:`${De.maxWidth}${De.maxHeight}`,le&&`${le.isKeyFrame?"key":String(le.chunkType||"delta")}`,le&&le.monitorCount&&((le.monitorIndex??0)+1,`${le.monitorCount}`),le&&[`src ${Math.round(le.sourceGapMs||0)}ms`,`gap ${Math.round(le.agentSendGapMs||0)}ms`,`tx ${Math.round(le.agentSendDurationMs||0)}ms`,`pace ${Math.round(le.agentPaceMs||0)}ms`,`queue ${Math.round(le.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(le.agentFrameAgeMs||0)}ms`,le.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(le.hubPacketTransitAgeMs))}ms`:"",le.droppedByAgent?`drop ${le.droppedByAgent}`:"",le.hubIngressDropped?`ingress-drop ${le.hubIngressDropped}`:"",le.hubClientDropped?`ws-drop ${le.hubClientDropped}`:"",le.captureStageMs?`capture ${Math.round(le.captureStageMs)}ms`:"",le.requestedFps?`req ${Math.round(le.requestedFps)}fps`:"",le.effectiveFps?`eff ${Math.round(le.effectiveFps)}fps`:"",le.captureAverageMs?`avg ${Math.round(le.captureAverageMs)}ms`:"",le.captureP95Ms?`p95 ${Math.round(le.captureP95Ms)}ms`:"",le.slowFrameCount?`slow ${Math.round(le.slowFrameCount)}`:"",le.captureHelperRestarts?`helper ${Math.round(le.captureHelperRestarts)}`:"",le.convertMs?`rgb565 ${Math.round(le.convertMs)}ms`:"",le.compressMs?`lzo ${Math.round(le.compressMs)}ms`:"",le.captureSourceSerial?`cap #${le.captureSourceSerial}`:"",le.captureSourceSkipped?`cap skip ${le.captureSourceSkipped}`:"",le.frameMode==="mode5-lzo-delta"?`tiles ${le.deltaVisualTileCount||0}+${le.deltaRefreshTileCount||0}/${le.deltaTotalTiles||0}@${le.deltaTileSize||0}`:"",le.platformProfile||le.hardwareEncoder||"-",le.atlasComposeMs?`atlas ${le.atlasComposeMs.toFixed(1)}ms`:"",le.atlasPoolStarved?`pool ${le.atlasPoolStarved}`:"",le.atlasTileCount?`tiles ${le.atlasReadyTiles||0}/${le.atlasTileCount}`:"",le.atlasInputRevision?`input #${le.atlasInputRevision}`:"",le.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(le.atlasSourceMaxAgeMs)}ms`:"",Ee?.inputFeedbackMs!==void 0&&Ee.inputFeedbackAt!==void 0&&performance.now()-Ee.inputFeedbackAt<=bh?`feedback ${Math.round(Ee.inputFeedbackMs)}ms`:"",le.contentHash?`enc ${le.contentHash.slice(0,6)}`:"",Ee?.visualHash?`pix ${Ee.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),ns==="open"&&Wc&&[`${Ar.sentPerSecond.toFixed(1)} hz`,Ar.lastInputSeq>0?`rtt ${Math.round(Ar.lastRoundTripMs)}ms`:"",Ar.lastInputSeq>0?`apply ${Ar.lastAgentApplyMs.toFixed(1)}ms`:"",Ar.droppedPerSecond>0?`drop ${Ar.droppedPerSecond.toFixed(1)}/s`:"",Ar.bufferedAmount>0?`buf ${ws(Ar.bufferedAmount)}`:"",Ar.lastInputType||"ready"].filter(Boolean).join(" / "),Ee?.inputFeedbackMs!==void 0&&Ee.inputFeedbackAt!==void 0&&performance.now()-Ee.inputFeedbackAt<=bh&&[Ee.inputFeedbackExact?"exact":"estimated",Ee.inputFeedbackInputType||"",`total ${Math.round(Ee.inputFeedbackMs)}ms`,Ee.inputFeedbackAgentApplyMs!==void 0?`apply ${Ee.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",Ee.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(Ee.inputFeedbackApplyToCaptureMs)}ms`:"",Ee.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(Ee.inputFeedbackInputToFrameMs)}ms`:"",Ee.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(Ee.inputFeedbackFrameToPaintMs)}ms`:"",Ee.inputFeedbackSampleCount?`p50 ${Math.round(Ee.inputFeedbackP50Ms||0)}ms`:"",Ee.inputFeedbackSampleCount?`p95 ${Math.round(Ee.inputFeedbackP95Ms||0)}ms`:"",Ee.inputFeedbackSampleCount?`n=${Ee.inputFeedbackSampleCount}`:"",`input #${Ee.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),le&&`${le.frameSeq}${ry(le.receivedAt||le.capturedAt)}`;const ci=Math.max(0,Oc.bytesPerSecond*8/1e6),Fp={activeTool:It,audioError:wu,audioMode:Zt,audioState:vu,audioStats:Rt,lastAudioFrame:yu,selectedAudioCaptureStreamId:Cp,controlFrames:Ji,controlInputReady:Ir,controlMode:kn,controlPresentationReady:Ql,controlSessionDeviceId:g,controlSessionFrameReady:Qe,controlSessionState:be,controlStreamBinding:ct,devices:Me,documentPresentationVisible:qt,focusedDeviceId:_t,frames:ni,localFeatureAccess:pt,quickActionBusy:an,selectedDeviceId:X?.deviceId||"",selectedIds:Ze,showControlFocus:Re,videoCaptureStopUnconfirmedByDeviceId:Ao,videoCapturePausedDeviceIds:Ti,wallPresentationReadyDeviceIds:Gl},Dp=s.useRef(Fp);Dp.current=Fp,s.useEffect(()=>{if(!ec.current)return;const n=window,o=S=>{if(!S)return null;const y=S.sourceGapMs,w=y==null||y===""?null:Number.isFinite(Number(y))?Number(y):null,Z=S;return{deviceId:S.deviceId,sessionId:S.sessionId||"",streamId:S.streamId||"",commandId:S.commandId||"",captureGeneration:Number(S.captureGeneration||0),monitorIndex:Number(S.monitorIndex||0),streamPurpose:S.streamPurpose||"",frameSeq:Number(S.frameSeq||0),frameMode:S.frameMode||"",mimeType:S.mimeType||"",currentGenerationVerified:Z.currentGenerationVerified===!0,receivedAt:Z.receivedAt||"",capturedAt:Z.capturedAt||"",sourceGapMs:w,inputFeedbackEventId:String(S.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(S.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(S.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(S.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(S.inputFeedbackApplyToCaptureMs||0)}},l=S=>{if(!S)return null;const y=window.getComputedStyle(S),w=S.getBoundingClientRect(),Z=Math.max(0,Math.min(w.right,window.innerWidth)-Math.max(w.left,0)),ge=Math.max(0,Math.min(w.bottom,window.innerHeight)-Math.max(w.top,0)),D=Number(y.opacity),fe=S.isConnected&&y.display!=="none"&&y.visibility!=="hidden"&&y.visibility!=="collapse"&&Number.isFinite(D)&&D>0&&w.width>0&&w.height>0&&Z>0&&ge>0;return{connected:S.isConnected,userVisible:fe,width:Math.max(0,Number(S.width||0)),height:Math.max(0,Number(S.height||0)),css:{display:y.display,visibility:y.visibility,opacity:Number.isFinite(D)?D:0},rect:{left:w.left,top:w.top,right:w.right,bottom:w.bottom,width:w.width,height:w.height,viewportIntersectionWidth:Z,viewportIntersectionHeight:ge},codec:el(S)}},m=(S,y)=>{const w=ua.current.get(ft(S,y));return w?{bindingKey:w.bindingKey||"",totalFrames:w.totalFrames,totalChangedFrames:w.totalChangedFrames,lastFrameSeq:Number(w.lastFrameSeq||0),lastPaintAgeMs:w.lastAt===void 0?-1:Math.max(0,performance.now()-w.lastAt),lastInfo:w.lastInfo?{frameSeq:Number(w.lastInfo.frameSeq||0),decoderInputCount:Number(w.lastInfo.decoderInputCount||0),decoderOutputCount:Number(w.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(w.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(w.lastInfo.droppedForLatency||0),visualChanged:w.lastInfo.visualChanged===!0,inputFeedbackExact:w.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(w.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(w.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(w.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(w.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:yh,inputFeedbackTargetMinSamples:wh,inputFeedbackOnTarget:w.lastInfo.inputFeedbackExact===!0&&Number(w.lastInfo.inputFeedbackSampleCount||0)>=wh&&Number(w.lastInfo.inputFeedbackP95Ms)<yh}:null}:null},d=(S,y)=>{if(!S)return null;if(y==="wall-visible"){const Z=ua.current.get(ft("wall",S));return Z?{bindingKey:Z.bindingKey||"",total:Z.totalFrames,lastFrameSeq:Number(Z.lastFrameSeq||0),lastPaintAgeMs:Z.lastAt===void 0?-1:Math.max(0,performance.now()-Z.lastAt)}:null}if(y!=="control-visible"&&y!=="wall-reuse-visible")return null;const w=tc.current.get(`${y}:${S}`);return w?{bindingKey:w.bindingKey,total:w.totalPaints,lastFrameSeq:w.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-w.lastPaintAt)}:null},C=(S,y)=>{const w=d(S,y);return w?{bindingKey:w.bindingKey,totalPaints:w.total,lastPaintAgeMs:w.lastPaintAgeMs,lastFrameSeq:w.lastFrameSeq}:null},v={readPresentationCounter(S,y){return d(String(S||""),y)},snapshot(S,y={}){const w=String(S||""),Z=y.includeHistory===!0,ge=Math.max(0,Number(y.presentationAfterSequence||0)),D=Dp.current,fe=D.devices.find(Pr=>Pr.deviceId===w)?.liveCapturePause,Ne=String(at.current[w]||""),We=mt.current.get(w)||null,Je=Et.current.get(w)||null,Ue=hn.current.get(w)||null,Yt=US(),Xr=Jp(),fo=qS(),ls={frameStats:oc.current===null?0:1,wallRecovery:jo.current===null?0:1,controlWarm:nr.current===null?0:1,controlWallDownshift:zn.current===null?0:1},Du=Br.current?.deviceId===w?Br.current:null,Qp=Tm.current.get(w)||null;return{capturedAt:Date.now(),deviceId:w,activeTool:D.activeTool,documentPresentationVisible:D.documentPresentationVisible,showControlFocus:D.showControlFocus,selectedDeviceId:D.selectedDeviceId,focusedDeviceId:D.focusedDeviceId,selectedDeviceIds:[...D.selectedIds],localFeatureAccess:D.localFeatureAccess,quickActionBusy:D.quickActionBusy,audioMode:D.audioMode,audioState:D.audioState,audioError:D.audioError,audioCaptureStreamId:D.selectedAudioCaptureStreamId,audioFrame:D.lastAudioFrame?{deviceId:D.lastAudioFrame.deviceId,streamId:D.lastAudioFrame.streamId,frameSeq:Number(D.lastAudioFrame.frameSeq||0),mimeType:D.lastAudioFrame.mimeType,sampleRate:Number(D.lastAudioFrame.sampleRate||0),channels:Number(D.lastAudioFrame.channels||0),byteLength:Number(D.lastAudioFrame.byteLength||0)}:null,audioStats:{...D.audioStats},videoCapturePausePhase:Ne?Ne.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:D.videoCaptureStopUnconfirmedByDeviceId[w]===!0,authoritativeLiveCapturePause:fe?{phase:fe.phase||"",captureStopConfirmed:fe.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(fe.stopAttemptCount||0)),stopError:fe.stopError||""}:null,controlMode:D.controlMode,controlSessionDeviceId:D.controlSessionDeviceId,controlSessionState:D.controlSessionState,controlSessionFrameReady:D.controlSessionFrameReady,controlPresentationReady:D.controlPresentationReady,controlInputReady:D.controlInputReady,controlConnection:Qp?{...Qp}:null,pendingControlConnection:Du?{...Du,elapsedMs:Math.max(0,performance.now()-Du.startedAt)}:null,videoCapturePaused:D.videoCapturePausedDeviceIds.has(w),wallPresentationReady:D.wallPresentationReadyDeviceIds.has(w),controlBinding:D.controlStreamBinding?.deviceId===w?{...D.controlStreamBinding}:null,actualControlOwner:ke.current?.deviceId===w?{...ke.current}:null,wallCapturePauseOwner:xn.current?.deviceId===w?{...xn.current}:null,frameSubscriptions:Yt,mobileConsoleDirect:Xr,audioSubscriptions:fo,presentationTimers:{...ls,total:Object.values(ls).reduce((Pr,Lu)=>Pr+Lu,0)},wallFrame:o(D.frames.get(w)),controlFrame:o(Wa.current.get(w)||D.controlFrames.get(w)),wallPaint:m("wall",w),controlPaint:m("control",w),controlVisiblePaint:C(w,"control-visible"),wallReuseVisiblePaint:C(w,"wall-reuse-visible"),presentationPaintSequence:Im.current,presentationPaintEvents:Z?Kl.current.filter(Pr=>Pr.deviceId===w&&Pr.sequence>ge).sort((Pr,Lu)=>Pr.sequence-Lu.sequence).map(Pr=>({...Pr})):[],wallCanvas:l(We),controlDecodeCanvas:l(Je),controlPresentationCanvas:l(Ue),globalCodec:el(void 0,{includeLifecycleEvents:Z})}}};return n.__liveDeskTransmissionProbe=v,()=>{n.__liveDeskTransmissionProbe===v&&delete n.__liveDeskTransmissionProbe}},[]);const Lp=s.useCallback(()=>{Lo(!0),Gs(Date.now()),Te(),Lr.current!==null&&window.clearTimeout(Lr.current),Lr.current=window.setTimeout(()=>{Lr.current=null,Gs(Date.now()),Lo(!1)},650)},[Te]),Op=s.useCallback(()=>{const n=wm.current;if(n)return Promise.resolve(n);const o=Wl.current;if(o)return o;const l=mr(()=>import("./remote-status-Ci5cE6Rj.js"),[]).then(m=>(wm.current=m,m)).catch(m=>{throw Wl.current=null,m});return Wl.current=l,l},[]),li=s.useCallback(n=>{const o=ia.current+1;ia.current=o,Fo(n),n==="remote"?Us(!1):n==="debug"&&zs(!1),Op().then(l=>{o===ia.current&&(xb(l),Fo(null),n==="remote"?zs(!0):n==="debug"?Us(!0):qs(!0),Lp())}).catch(()=>{o===ia.current&&(Fo(null),Lo(!1),console.warn("[VuvoDesk] Status diagnostics are unavailable."))})},[Op,Lp]),_p=s.useCallback(()=>{if(fn||$n==="remote"){ia.current+=1,Fo(null),zs(!1);return}li("remote")},[li,$n,fn]),jp=s.useCallback(()=>{if(Ut||$n==="debug"){ia.current+=1,Fo(null),Us(!1);return}li("debug")},[Ut,li,$n]),Bp=s.useCallback(()=>{if(pr||$n==="hub"){ia.current+=1,Fo(null),qs(!1);return}li("hub")},[pr,li,$n]),Hp=fn||Ut,Wp=JSON.stringify(Le.filter(n=>n.connected).map(n=>n.deviceId).sort());s.useEffect(()=>{if(!Hp)return;const n=JSON.parse(Wp);if(n.length===0){Lo(!1);return}const o=new AbortController,l=[];let m=!1;return Lr.current!==null&&(window.clearTimeout(Lr.current),Lr.current=null),Lo(!0),Gs(Date.now()),Promise.allSettled(n.map(d=>ze(`/api/remote/devices/${encodeURIComponent(d)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:o.signal,timeoutMs:1500},Y))).then(()=>{m||[500,1800,4500].forEach((d,C,v)=>{const S=window.setTimeout(()=>{m||(Te(),Gs(Date.now()),C===v.length-1&&Lo(!1))},d);l.push(S)})}),()=>{m=!0,o.abort();for(const d of l)window.clearTimeout(d)}},[Y,Te,Wp,Hp]);const ui=new Map,ss=new Map;if(Ni&&(fn||Ut||pr))for(const n of Le){const o=n.deviceId,l=Re&&g===o,d=ft(l?"control":"wall",o),C=l?Ji.get(o):ni.get(o),v=l?Et.current.get(o)||hn.current.get(o)||null:mt.current.get(o)||(nt?Nn.current:null),S={device:n,frame:C,receiveStat:rc[d],paintStat:nc[d],codec:v?el(v):{},selectedMonitorIndex:_n(n,gt[o]),control:l,controlInputReady:l&&Ir,controlBinding:l&&ct?.deviceId===o?ct:void 0,recoveryDiagnostic:$i.current.get(d),hubRelay:z?.relay,capturePaused:Ti.has(o),capturePauseConfirmed:n.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:n.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(z?.heartbeatMs||5e3),now:Date.now()},y=["open","playing","silent"].includes(vu),w=Rt.nativeCallbackDiagnosticsAvailable&&(Rt.nativeRejectedCallbackCount>0||Rt.nativeCurrentnessDropCount>0),Z=y&&!w,ge=o===X?.deviceId&&Zt?{id:"browser-remote-audio",state:Z?"ok":"warning",label:Z?"Remote audio is healthy":"Remote audio needs attention",detail:Rt.lastUpdatedAt>0?[vu,`context ${Rt.audioContextState}`,`queue ${Math.round(Rt.queuedMs)}ms`,`packet ${Math.round(Rt.lastPacketAgeMs)}ms`,`capture ${Rt.captureHealthy?"healthy":Rt.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,Rt.backendKind?`backend ${Rt.backendKind}`:"backend unknown",Rt.helperRequired?`helper ${Rt.helperAlive&&Rt.helperPid>0?`pid ${Rt.helperPid}`:"missing"}`:"helper N/A",`drop ${Rt.drops}`,`restart ${Rt.automaticRestarts}`,Rt.nativeCallbackDiagnosticsAvailable?`native reject ${Rt.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",Rt.nativeCallbackDiagnosticsAvailable?`native stale ${Rt.nativeCurrentnessDropCount}`:"",Rt.nativeLastDropReason?`native reason ${Rt.nativeLastDropReason}`:"",yu?`frame #${yu.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(fn||pr){const D=Ni.buildRemoteDeviceDiagnostics(S);fn&&ge&&D.push(ge),ui.set(o,D)}if(Ut){const D=Ni.buildRemoteDeviceDebugDiagnostics(S);ge&&D.push(ge),ss.set(o,D)}}const xv=pr&&Ni?Ni.buildHubRemoteDiagnostics({status:z||{},deviceDiagnostics:[...ui.values()],codec:el(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Oc}):[],$p=ti?.atlasReadyTiles??xu,Iu=ti?.atlasTileCount??xu,Rv=$p===Iu?`${Iu} tiles`:`${$p}/${Iu} tiles`,Av=nn.length>0;Re?`${Ru}${ci.toFixed(ci>=10?0:1)}`:Av?`${Rv}${Ru}${ci.toFixed(ci>=10?0:1)}`:`${xu}${Ru}${ci.toFixed(ci>=10?0:1)}`;const Tu=cn.length,Iv=Re?X?Qt(X):"No Client":Tu===0?"No Client":Tu>1?`${Tu} selected`:X?Qt(X):"No Client",Tv=Re?[X?.deviceId].filter(n=>!!n):cn.map(n=>n.deviceId),Sn=Ci[ja]||Ci.en,Yc=Sn.sync||Ci.en.sync,Pv=u||T||Pe?"checking":Xe==="team"?re?"Team · Operator access":`Team · ${V.members.length+V.invites.length}/${b?.memberLimit||Zp} people`:Xe==="pro"?`Pro ${Ka.length}/${Ou}`:Xe==="ltd"?`Plus ${Ka.length}/${us}`:`Free ${Ka.length}/${_u}`,Ev=An?Xe!=="free"?Xe==="team"?"Team active":Xe==="pro"?"Business active":"Upgrade to Pro LTD":r?tt==="checkout"?"Opening checkout":Xe==="ltd"?"Buy Pro LTD":"Buy Plus LTD":tt==="auth"?"Opening Google":"Sign in to buy":"LTD · Coming soon",Nv=!An||Xe==="pro"||Xe==="team"||tt==="checkout"||tt==="auth"||u||T||Pe,Vp=r?.user?.user_metadata,cs=Wh(Vp,"avatar_url","picture"),uo=Wh(Vp,"full_name","name")||r?.user?.email||"Google",Pu=uo.slice(0,1).toUpperCase(),Fv=z?.started?"Local app ready":"Start VuvoDesk",Dv=J?.active?"Published":r?"Not published":"Sign in required",Lv=ah(Xe),Ov=M.map(n=>({id:n.id,kind:n.kind,name:n.kind==="personal"?"Personal":n.name,role:n.role,plan:ah(n.plan),memberCount:n.id===G&&n.kind==="team"?V.members.length+V.invites.length:void 0})),di=b?.kind==="team"?{id:b.id,name:b.name,currentUserRole:b.role,memberLimit:b.memberLimit,memberCount:b.role==="owner"?V.members.length+V.invites.length:void 0,invitationsEnabled:Xe==="team"&&b.role==="owner"&&V.members.length+V.invites.length<b.memberLimit,members:[...V.members.map(n=>({id:n.id,email:n.email,displayName:n.displayName,role:n.role,status:"active"})),...V.invites.map(n=>({id:n.id,email:n.email,role:n.role,status:"invited",expiresAt:n.expiresAt}))]}:null,_v=re?zh.filter(n=>n.id==="wall"||n.id==="control"):zh,jv=re?Uh.filter(n=>n.id==="doc"||n.id==="support"):Uh,Bv=async n=>{if(n===G)return;const o=await B(n);if(!o){j("The VuvoDesk workspace could not be opened.","error");return}j(`Switched to ${o.name}.`,"success")},Hv=async n=>{if(!G||b?.role!=="owner")throw new Error("Only the Team owner can rename this space.");const o=G,{data:l,error:m}=await Ct.rpc("rename_livedesk_workspace",{p_workspace_id:o,p_name:n});if(!q(o))throw new Error("The active VuvoDesk workspace changed. Please try again in the current workspace.");if(m)throw m;const d=Array.isArray(l)?l[0]:l;if(!d?.ok)throw new Error(String(d?.reason||"Team Space rename failed."));await ye(),q(o)&&j("Team Space name saved.","success")},Wv=async n=>{const o=G,l=await V.removeMember(n);q(o)&&j(l.revokedImmediately?"Team member removed and active remote access closed.":"Team member removed. The Hub was offline, so its next access check will close any old connection.",l.revokedImmediately?"success":"error")},$v=async n=>{const o=G;await V.revokeInvite(n),q(o)&&j("Team invitation cancelled.","success")},Vv=async()=>{if(!r)throw new Error("Sign in before leaving a Team Space.");if(await V.leaveWorkspace(),!await B(r.user.id))throw new Error("The Team was left, but Personal could not be reopened yet. Retry in a moment.");j("You left the Team Space.","success")},zv=/^\d{6}$/.test(z?.pairingPin||"")?z?.pairingPin:"------",mo=n=>{if(n==="pricing"&&(u||T)){j("Your VuvoDesk workspace is still loading. Try again in a moment.");return}if(re&&n!=="wall"&&n!=="control"&&n!=="doc"&&n!=="support"){j("Team Operators can use Wall and Control. Ask the Team owner to change settings, billing, files, or Agents."),La("wall"),jn(!1);return}if(typeof window<"u"&&(n==="support"?window.history.pushState({},"","/support"):It==="support"&&window.history.pushState({},"",W?"/app":"/")),n==="control"){const o=tn||ha;if(o&&(as(o.deviceId),gn(!1),Vt(o.deviceId)),La(n),!pt){jn(!1),j(Xo);return}jn(!0);return}n==="wall"&&Fb(o=>o+1),La(n),jn(!1)},Tr=tt==="update"||et?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(z?.update?.state||""),zp=!re&&!!(z?.update?.updateAvailable&&z.update.canApply||Tr||et?.error||!z&&et),po=zy(ja),Eu=s.useCallback(n=>{if(!et?.targetIds.includes(n))return;const o=z?.update?.operationId===et.operationId?z.update.targets?.find(l=>l.deviceId===n):void 0;switch(o?.state){case"completed":return Ys[Mh(et.operationId,o)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:o.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return et.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return et.stage==="updating"?o.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return et.stage==="updated"?{state:"updated",label:"Updated"}:et.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[z?.update,Ys,et]),Nu=me&&!!r&&Oe&&Ge==="connecting",va=me&&!!r&&Oe&&(Ge==="reconnecting"||Ge==="unavailable"),Up=W&&va&&kt?.kind==="signal-service-unavailable",qp=W&&va&&kt?.kind==="p2p-unavailable",Gp=kt?.retryAt?Math.max(0,Math.ceil((kt.retryAt-Date.now())/1e3)):0,Uv=u?"checking":Ge==="online"&&z?.started?"online":Nu?"connecting":va?Ge:"offline",Kp=r&&!qe?"Restoring your workspace...":"Restoring direct connection...",Qc=Ge==="reconnecting"?Kp:u?"Checking Hub":Ge==="online"&&z?.started?`${Le.length} online`:Nu?"Connecting Hub":Up?"Signaling unavailable":qp?"Direct connection unavailable":r?"Hub offline":"Sign in required",mi=Ge==="reconnecting"?"":Ge==="online"&&z?.deviceName?z.deviceName:Nu?"Trying saved Hub routes…":Up?Gp>0?`Next attempt in ${Gp}s`:"Automatic retry pending":qp?"This network cannot establish a direct peer connection":va?"Automatic retry in background":je?"Desktop Hub unavailable":"Remote management",Fu=W&&Ur&&!Re,Yp=Qy({authLoading:u,phase:Ge,recoveryOverlayEligible:Fu}),qv=Yp.statusVisible,Gv=Fu&&!!r&&T&&!qe,Kv=Fu&&!!r&&!T&&!qe&&!!A,Yv=Yp.recoveryVisible||Gv,Qv=t&&Ur&&!!r&&(T&&!qe||qe&&!z);return i.jsxs("main",{className:`app-shell ${Ur||Re?"stream-surface-active":""} ${me?"mobile-console-shell":""} ${me&&Re?"mobile-console-control-active":""}`,"data-mobile-standalone":me&&te?"true":void 0,"data-mobile-ios":me&&ue.isIos?"true":void 0,"data-mobile-android":me&&ue.isAndroid?"true":void 0,children:[i.jsxs("aside",{className:"tool-rail","aria-label":"VuvoDesk tools",children:[i.jsx("div",{className:"rail-brand",title:"VuvoDesk",children:i.jsx(ef,{size:25})}),i.jsx("nav",{className:"rail-tools",children:_v.map(n=>{const o=n.icon,l=ag(n.tooltip,ja);return i.jsxs("button",{className:`rail-tool ${n.id==="sync-server"?"sync-server hub-sync-trigger":""} ${It===n.id?"active":""} accent-${n.accent}`,onClick:()=>n.id==="sync-server"?mv():mo(n.id),"data-tooltip":n.id==="sync-server"&&Po?void 0:Wy(n.label,n.tooltip,ja),"aria-label":`${n.label}. ${l}`,type:"button",disabled:n.id==="sync-server"&&tt==="host","aria-busy":n.id==="sync-server"&&tt==="host","aria-expanded":n.id==="sync-server"?Po:void 0,"aria-haspopup":n.id==="sync-server"?"dialog":void 0,"aria-controls":n.id==="sync-server"&&Po?"hub-sync-popover":void 0,children:[n.id==="sync-server"&&tt==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(o,{size:19}),i.jsx("span",{children:n.id==="sync-server"&&tt==="host"?"Syncing…":n.label})]},n.id)})}),i.jsxs("div",{className:"rail-footer",children:[jv.map(n=>{const o=n.icon;return i.jsxs("button",{className:`rail-tool compact ${It===n.id?"active":""} accent-${n.accent}`,onClick:()=>mo(n.id),title:n.label,type:"button",children:[i.jsx(o,{size:18}),i.jsx("span",{children:n.label})]},n.id)}),!re&&i.jsxs("button",{className:`rail-tool compact local-settings ${qi?"active":""}`,onClick:()=>{La("settings"),typeof window<"u"&&window.history.pushState({},"","/"),Or(!1),jn(!1),Sm(!1)},title:"Settings",type:"button",children:[i.jsx(nf,{size:18}),i.jsx("span",{children:"Settings"})]}),i.jsxs("button",{className:`rail-account ${r?"signed-in":""}`,onClick:()=>{Or(n=>!n)},disabled:u||p||tt==="auth","aria-expanded":sa,"aria-haspopup":"dialog","aria-controls":"vuvodesk-account-dialog",title:r?`Account: ${r.user?.email||uo}`:"Sign in with Google",type:"button",children:[r?cs?i.jsx("img",{src:cs,alt:uo,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Pu}):i.jsx(Sl,{size:18}),i.jsx("span",{children:r?"Account":"Google"})]})]})]}),i.jsx(F0,{open:sa,signedIn:!!r,accountName:uo,accountEmail:r?.user?.email||"",accountInitial:Pu,avatarUrl:cs,currentPlan:Lv,currentPlanKnown:!T&&!Pe,deviceCount:Ka.length,deviceLimit:vc,licenseLabel:Pv,networkLabel:Fv,accessLabel:Dv,authBusy:u||p||tt==="auth",workspaceBusy:T,checkoutBusy:tt==="checkout"||Pe||V.loading,ltdCheckoutEnabled:An,monthlyCheckoutEnabled:Sa,teamCheckoutEnabled:Jr,planChangesEnabled:!re,sessionRevocationError:f,workspaces:Ov,activeWorkspaceId:G,teamWorkspace:di,onClose:()=>Or(!1),onSignIn:Qr,onSignOut:dv,onRetrySessionRevocation:k,onSelectPlan:n=>{if(!r)return Or(!1),Qr();if(re){j("The Team owner manages billing and plan changes.");return}if((n==="plus_ltd"||n==="pro_ltd")&&!An){j("VuvoDesk LTD checkout is not open yet.");return}if(n==="team_monthly"&&!Jr){j("VuvoDesk Team checkout is not open yet. Contact support to join the Team launch group.");return}return Or(!1),lo(n)},onSelectWorkspace:Bv,onCreateTeamInvite:di?.currentUserRole==="owner"?V.createInvite:void 0,onRemoveTeamMember:di?.currentUserRole==="owner"?Wv:void 0,onRevokeTeamInvite:di?.currentUserRole==="owner"?$v:void 0,onRenameTeamWorkspace:di?.currentUserRole==="owner"?Hv:void 0,onLeaveTeamWorkspace:di?.currentUserRole==="operator"?Vv:void 0}),me&&P&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>N(!1),children:i.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:n=>n.stopPropagation(),children:[i.jsxs("header",{children:[i.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:i.jsx(vy,{size:20})}),i.jsxs("span",{children:[i.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install VuvoDesk on iPhone"}),i.jsx("small",{children:"Open without browser bars and tabs"})]}),i.jsx("button",{type:"button",onClick:()=>N(!1),"aria-label":"Close install guide",children:i.jsx(Ma,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",ue.browserName==="browser"?"the browser":ue.browserName,"'s ",i.jsx("strong",{children:"Share"})," button."]}),i.jsxs("li",{children:["Tap ",i.jsx("strong",{children:"Add to Home Screen"}),"."]}),i.jsx("li",{children:ue.isSafari?i.jsxs(i.Fragment,{children:["Turn on ",i.jsx("strong",{children:"Open as Web App"}),", then tap ",i.jsx("strong",{children:"Add"}),"."]}):i.jsxs(i.Fragment,{children:["Confirm the app name, then tap ",i.jsx("strong",{children:"Add"}),"."]})})]}),i.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>N(!1),children:"Got it"})]})}),Po&&i.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:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(Si,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:po.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>os(),"aria-label":po.closeLabel,children:i.jsx(Ma,{size:17})})]}),i.jsx("h2",{id:"hub-sync-title",children:po.title}),i.jsx("p",{id:"hub-sync-description",children:po.description}),i.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[i.jsx(wo,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:po.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>os(),children:po.cancel}),i.jsxs("button",{ref:lm,className:"primary",type:"button",onClick:pv,disabled:tt==="host",children:[i.jsx(Si,{size:16}),po.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${Ur&&!Ba?"dock-open":""} ${Re?"control-stage":""} ${mc?"agents-stage":""} ${Ga?"file-share-stage":""}`,children:[me&&i.jsxs("header",{className:"mobile-console-header",children:[i.jsxs("span",{className:"mobile-console-brand","aria-label":"VuvoDesk mobile Console",children:[i.jsx("span",{className:"mobile-console-brand-mark",children:i.jsx(ef,{size:22})}),i.jsxs("span",{children:[i.jsx("strong",{children:"VuvoDesk"}),i.jsx("small",{children:"Mobile Console"})]})]}),qv&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:`mobile-console-hub state-${Uv}`,onClick:va?Be:void 0,disabled:!va,type:"button","aria-label":`${Qc}${mi?`. ${mi}`:""}${va?" Retry now.":""}`,title:va?"Retry remote connection now":Qc,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:Qc}),mi&&i.jsx("small",{children:mi})]})]}),i.jsxs("span",{className:"mobile-console-hub-live",role:"status","aria-live":"polite",children:[Qc,mi?`. ${mi}`:""]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[i.jsxs("button",{className:`mobile-console-account ${r?"signed-in":""}`,onClick:()=>Or(n=>!n),disabled:u||tt==="auth","aria-expanded":sa,"aria-haspopup":"dialog","aria-controls":"vuvodesk-account-dialog",title:r?`Account: ${r.user?.email||uo}`:"Sign in with Google",type:"button",children:[r?cs?i.jsx("img",{src:cs,alt:uo,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Pu}):i.jsx(Sl,{size:16}),i.jsx("span",{children:r?"Account":"Google"})]}),W&&!te&&(_||ue.isIos)&&i.jsx("button",{className:"mobile-console-install",onClick:()=>{R()},"aria-label":"Install VuvoDesk app",title:"Install VuvoDesk app",type:"button",children:i.jsx(yy,{size:19,"aria-hidden":"true"})}),zp&&i.jsx("button",{className:"mobile-console-update",onClick:()=>{Ap()},disabled:Tr||!z?.update?.canApply,"aria-label":Tr?"VuvoDesk update in progress":"Update VuvoDesk","aria-busy":Tr,type:"button",children:Tr?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(rf,{size:18,"aria-hidden":"true"})})]})]}),me&&Ur&&!Re&&i.jsxs("div",{className:"mobile-wall-preferences","data-list-status-only":Pi?"true":void 0,"aria-label":Pi?"Wall display preferences. List is updating status only.":"Wall display preferences",children:[i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:Vh.map(n=>i.jsx("button",{className:Oa===n.id?"active":"",onClick:()=>bm(n.id),title:`${n.label} Wall streaming (${n.fps} fps)`,"aria-pressed":Oa===n.id,type:"button",children:n.label},n.id))}),i.jsx("div",{className:"segmented-control mobile-wall-view-control","aria-label":"Wall view",children:FM.map(n=>i.jsx("button",{className:hm===n.id?"active":"",onClick:()=>gm(n.id),title:n.id==="list"&&Pi?"List status only. Wall video is paused to save data.":n.label,"aria-pressed":hm===n.id,type:"button",children:n.label},n.id))})]}),i.jsxs("header",{className:"topbar",children:[i.jsx("div",{className:"topbar-leading",children:zp?i.jsxs("button",{className:"topbar-update-button",onClick:()=>{Ap()},title:et?.error?`VuvoDesk Hub update failed: ${et.error}`:`Update VuvoDesk to ${z?.update?.latestVersion||et?.targetManagerVersion||"latest"}`,"aria-label":et?.error?`VuvoDesk Hub update failed: ${et.error}`:Tr?"VuvoDesk update in progress":`Update VuvoDesk to ${z?.update?.latestVersion||et?.targetManagerVersion||"latest"}`,type:"button",disabled:Tr||!z?.update?.canApply,"aria-busy":Tr,children:[Tr?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(rf,{size:19,"aria-hidden":"true"}),Tr&&z?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[z.update.completedCount||0,"/",z.update.targetCount]}):null]}):null}),i.jsxs("div",{className:"topbar-tray",children:[Ga&&!Re&&i.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[i.jsxs("div",{children:[i.jsx(wy,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Source"}),i.jsx("strong",{children:"VuvoDesk Hub"})]})]}),i.jsx(Sy,{size:15}),i.jsx(Cy,{size:16}),i.jsxs("div",{children:[i.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),i.jsxs("span",{children:[i.jsx("small",{children:"Destination"}),i.jsxs("strong",{children:[Um," Client",Um===1?"":"s"]}),i.jsx("em",{children:Oo.trim()||"Desktop/VuvoDeskFiles"})]})]})]}),Ur&&!Re&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mh,{active:pr,refreshing:pr&&Do||$n==="hub",onClick:Bp}),i.jsx(uh,{active:fn,refreshing:fn&&Do||$n==="remote",onClick:_p}),i.jsx(dh,{active:Ut,refreshing:Ut&&Do||$n==="debug",onClick:jp}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(nh,{controller:Jm,onError:j}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:Vh.map(n=>i.jsx("button",{className:Oa===n.id?"active":"",onClick:()=>bm(n.id),title:n.label+" Wall streaming ("+n.fps+" fps)","aria-pressed":Oa===n.id,type:"button",children:n.label},n.id))}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsxs("div",{className:"wall-view-control",children:[i.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:NM.map(n=>i.jsx("button",{className:Bt===n.id?"active":"",onClick:()=>gm(n.id),"aria-pressed":Bt===n.id,type:"button",children:n.label},n.id))}),i.jsx("label",{className:"wall-view-slider",htmlFor:"wall-view-scale",children:i.jsx("input",{id:"wall-view-scale",type:"range",min:Al,max:ea,step:1,value:Eo,onChange:n=>Sb(Number(n.currentTarget.value)),"aria-label":"Wall tile size","aria-valuetext":kb})})]})]}),Re&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mh,{active:pr,refreshing:pr&&Do||$n==="hub",onClick:Bp}),i.jsx(uh,{active:fn,refreshing:fn&&Do||$n==="remote",onClick:_p}),i.jsx(dh,{active:Ut,refreshing:Ut&&Do||$n==="debug",onClick:jp}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(nh,{controller:Jm,onError:j})]})]})]}),pr&&Ur&&i.jsx(z0,{items:xv,collectedAt:Rb,onClose:()=>qs(!1)}),Bm?i.jsxs("section",{className:"doc-page",lang:ja,dir:ja==="ar"?"rtl":"ltr",children:[i.jsxs("section",{className:"doc-hero",children:[i.jsxs("div",{className:"doc-hero-copy",children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Sd,{size:16}),Sn.eyebrow]}),i.jsx("h2",{children:Sn.title}),i.jsx("p",{children:Sn.intro})]}),i.jsxs("label",{className:"doc-language-picker",children:[i.jsxs("span",{children:[i.jsx(ky,{size:17}),Sn.languageLabel]}),i.jsx("select",{value:ja,onChange:n=>Ab(n.target.value),children:LM.map(n=>i.jsx("option",{value:n.id,children:n.label},n.id))})]})]}),i.jsx("section",{className:"doc-grid",children:Sn.sections.map((n,o)=>{const m=[Si,gl,af,wo,eg][o]||Sd;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(m,{size:19})}),i.jsxs("div",{children:[i.jsx("h3",{children:n.title}),i.jsx("p",{children:n.body}),i.jsx("ul",{children:n.points.map(d=>i.jsx("li",{children:d},d))})]})]},n.title)})}),Yc&&i.jsxs("section",{className:"doc-sync",children:[i.jsxs("div",{className:"doc-sync-head",children:[i.jsx(af,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Yc.title}),i.jsx("p",{children:Yc.body})]})]}),i.jsx("ul",{children:Yc.points.map(n=>i.jsx("li",{children:n},n))})]}),i.jsxs("section",{className:"doc-firewall",children:[i.jsxs("div",{className:"doc-firewall-head",children:[i.jsx(wo,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Sn.firewall.title}),i.jsx("p",{children:Sn.firewall.body})]})]}),i.jsx("ul",{children:Sn.firewall.points.map(n=>i.jsx("li",{children:n},n))})]}),i.jsxs("section",{className:"doc-command-panel",children:[i.jsxs("div",{className:"doc-command-head",children:[i.jsx(gl,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:Sn.commands.title}),i.jsx("p",{children:Sn.commands.body})]})]}),i.jsxs("div",{className:"doc-command-list",children:[Sn.commands.manager&&i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.manager}),i.jsx("code",{children:Np}),i.jsx("button",{className:"icon-button",onClick:()=>ju(Np),title:"Copy command",type:"button",children:i.jsx(Bu,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.primary}),i.jsx("code",{children:qc}),i.jsx("button",{className:"icon-button",onClick:()=>ju(qc),title:"Copy command",type:"button",children:i.jsx(Bu,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:Sn.commands.slot}),i.jsx("code",{children:`${qc} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>ju(`${qc} 3`),title:"Copy command",type:"button",children:i.jsx(Bu,{size:16})})]})]})]})]}):mc?i.jsx(hs,{children:i.jsx(hh,{hubUrl:Y,devices:Me})}):Ga?i.jsx(hs,{children:i.jsx(sk,{hubUrl:Y,devices:Le,localFeatureAccess:pt,upgradeNotice:Xo,remoteDirectory:Oo,onRemoteDirectoryChange:Cm,targetMode:Uo,selectedTargetIds:qo,onTargetModeChange:Hb,onTargetToggle:n=>nu(o=>o.includes(n)?o.filter(l=>l!==n):[...o,n]),filePickerRef:$b,folderPickerRef:Vb,onBrowserFileImport:n=>{Ep(n)},onBrowserFolderImport:n=>{Ep(n)},onNotice:j,onTransferChange:n=>{if(!n){pa(null);return}const o=n.state==="failed"||n.state==="partially-failed"||n.state==="cancelled"?"failed":n.state==="completed"?"queued":n.state==="sending"?"sending":"reading";pa({id:n.id,status:o,progress:n.progress,message:n.message}),["completed","partially-failed","failed","cancelled"].includes(n.state)&&window.setTimeout(()=>pa(l=>l?.id===n.id?null:l),4500)}})}):Hm?i.jsx(hs,{children:i.jsx(ck,{session:r,currentProductKey:"livedesk",appVersion:"",onSignIn:Qr})}):qi?i.jsx(hs,{children:i.jsx(lk,{hubUrl:Y,mobileLayout:me,runtimeRole:z?.runtimeRole||"hub",runtimeDeviceId:z?.deviceId||"",sessionAccessToken:r?.access_token||"",showThisComputerSetting:!me&&z?.runtimeRole==="hub",onShowThisComputerChange:St,pin:i.jsxs(uk,{children:[i.jsx("div",{className:"settings-section-grid",children:i.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Pair a Client"}),i.jsx("h3",{children:"Connect another local PC"})]}),i.jsx(Ra,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:zv}),i.jsxs("button",{className:"text-button ghost compact",onClick:fv,disabled:!z?.started||tt==="pin",type:"button",children:[i.jsx(My,{size:15}),tt==="pin"?"Creating":"New PIN"]})]})]})}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"File transfer"}),i.jsx("h3",{children:"Client destination folder"})]}),i.jsx(Hu,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:Oo,onChange:n=>Cm(n.target.value),placeholder:"Desktop/VuvoDeskFiles"})]}),i.jsx("p",{className:"settings-help",children:"Blank uses Desktop/VuvoDeskFiles on each Client."})]})]}),desktopUpdate:i.jsx(mk,{}),agent:i.jsx(dk,{hubUrl:Y,showToast:j}),captureGallery:i.jsx(pk,{hubUrl:Y,onToast:j})})}):jm?i.jsxs("section",{className:"pricing-page",children:[i.jsxs("header",{className:"pricing-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(xy,{size:15})," VuvoDesk plans"]}),i.jsx("h2",{children:"Choose the plan that fits your wall"}),i.jsx("p",{children:"Use one account for Personal or Business, or let each operator use a separate Google account in one Team Space."})]}),i.jsx("button",{className:"pricing-close",onClick:()=>mo("wall"),title:"Close pricing",type:"button",children:i.jsx(Ma,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:Ym.name}),i.jsxs("small",{children:[Ka.length,"/",Qk(vc)," managed Clients"]})]}),i.jsxs("div",{className:"pricing-cards","aria-label":"VuvoDesk plans",children:[i.jsxs("article",{className:`pricing-plan-card ${Xe==="free"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),i.jsx("strong",{children:$e.free.price})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.free.audience}),i.jsx("h3",{children:"Free personal screen wall"}),i.jsx("p",{children:$e.free.note}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",_u," devices"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Standard banner helps keep Free available"]})]}),i.jsx("span",{className:"pricing-current-label",children:Xe==="free"?"Current plan":"Included for everyone"})]}),i.jsxs("article",{className:`pricing-plan-card featured ${Xe==="ltd"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge plus",children:[i.jsx(Xh,{size:14})," Plus"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.ltd.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.ltd.audience}),i.jsx("h3",{children:"Ad-free personal wall"}),i.jsxs("p",{children:["Monitor up to ",us," personal computers without the standard banner."]}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",us," devices"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," No standard ad banner"]})]}),i.jsxs("div",{className:"pricing-ltd-offer",children:[i.jsx("span",{children:"Plus LTD"}),i.jsx("strong",{children:$e.ltd.ltd}),i.jsx("small",{children:An?"One-time · available now":"One-time · coming soon"})]}),i.jsxs("div",{className:"pricing-plan-actions",children:[i.jsxs("button",{className:"pricing-plan-button secondary",onClick:Sa?r?()=>lo("plus_monthly"):Qr:void 0,disabled:!Sa||Xe!=="free"||tt==="checkout"||tt==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Xe!=="free"?"Plus active":Sa?r?`Choose Plus · ${$e.ltd.price}/month`:"Sign in for Plus monthly":"Monthly · Coming soon"]}),i.jsxs("button",{className:"pricing-plan-button",onClick:An?r?()=>lo("plus_ltd"):Qr:void 0,disabled:!An||Xe!=="free"||tt==="checkout"||tt==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Xe!=="free"?"Plus active":An?r?`Buy Plus · ${$e.ltd.ltd}`:"Sign in for Plus LTD":"LTD · Coming soon"]})]})]}),i.jsxs("article",{className:`pricing-plan-card pro ${Xe==="pro"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge pro",children:[i.jsx(wo,{size:14})," Pro / Business"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.pro.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.pro.audience}),i.jsx("h3",{children:"School and commercial monitoring"}),i.jsx("p",{children:"For schools, academies, studios, offices, and other commercial use."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",Ou," connected Clients"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Ad-free school, academy, and commercial use"]})]}),i.jsxs("div",{className:"pricing-ltd-offer pro",children:[i.jsx("span",{children:"Pro LTD"}),i.jsx("strong",{children:$e.pro.ltd}),i.jsx("small",{children:An?"One-time · available now":"One-time · coming soon"})]}),i.jsxs("div",{className:"pricing-plan-actions",children:[i.jsxs("button",{className:"pricing-plan-button secondary",onClick:Sa?r?()=>lo("pro_monthly"):Qr:void 0,disabled:!Sa||Xe==="pro"||Xe==="team"||tt==="checkout"||tt==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Xe==="pro"?"Business active":Xe==="team"?"Included with Team":Sa?r?`Choose Pro · ${$e.pro.price}/month`:"Sign in for Pro monthly":"Monthly · Coming soon"]}),i.jsxs("button",{className:"pricing-plan-button",onClick:An?r?()=>lo("pro_ltd"):Qr:void 0,disabled:!An||Xe==="pro"||Xe==="team"||tt==="checkout"||tt==="auth"||u||T||Pe,type:"button",children:[i.jsx(xa,{size:16}),Xe==="pro"?"Business active":Xe==="team"?"Included with Team":An?r?`Buy Pro · ${$e.pro.ltd}`:"Sign in for Pro LTD":"LTD · Coming soon"]})]})]}),i.jsxs("article",{className:`pricing-plan-card team ${Xe==="team"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge team",children:[i.jsx(As,{size:14})," Team"]}),i.jsxs("span",{className:"pricing-plan-price",children:[i.jsx("strong",{children:$e.team.price}),i.jsx("small",{children:"/ month"})]})]}),i.jsx("p",{className:"pricing-plan-audience",children:$e.team.audience}),i.jsx("h3",{children:"One Team Space, separate logins"}),i.jsx("p",{children:"Share the same computers without sharing one Google account."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Up to ",Zp," people"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Commercial use"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," Owner and Operator roles"]}),i.jsxs("li",{children:[i.jsx(Cn,{size:16})," One controller per computer"]})]}),i.jsxs("div",{className:"pricing-team-readiness",children:[i.jsx("span",{children:Jr?"Team subscription":"Team launch group"}),i.jsx("strong",{children:Jr?`${$e.team.price} monthly`:"Contact support"}),i.jsx("small",{children:Jr?"Separate member accounts":"Checkout stays closed until recurring billing is ready"})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:Jr?r?()=>lo("team_monthly"):Qr:void 0,disabled:!Jr||Xe==="team"||tt==="checkout"||tt==="auth"||u||T||Pe,type:"button",children:[i.jsx(As,{size:16}),Xe==="team"?"Team active":Jr?r?`Choose Team · ${$e.team.price}/month`:"Sign in for Team":"Team · Coming soon"]})]})]}),i.jsxs("section",{className:"pricing-includes",children:[i.jsxs("div",{children:[i.jsx(Ra,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ layout slots"})]}),i.jsxs("div",{children:[i.jsx(Cs,{size:17}),i.jsx("span",{children:"Focused control"}),i.jsx("strong",{children:"Local-first"})]}),i.jsxs("div",{children:[i.jsx(of,{size:17}),i.jsx("span",{children:"Remote audio"}),i.jsx("strong",{children:"Available"})]}),i.jsxs("div",{children:[i.jsx(Hu,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(Cn,{size:15})," Free and Plus are personal. Pro / Business covers one person in a school, academy, or other commercial organization. Team gives each operator a separate account in one shared space."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:An?r?()=>lo(Xe==="ltd"?"pro_ltd":"plus_ltd"):Qr:void 0,disabled:Nv,type:"button",children:[i.jsx(xa,{size:18}),Ev]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Ba?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:Om,className:`screen-wall-panel ${jb?"drop-active":""}`,onClick:n=>{n.currentTarget===n.target&&is()},onDragEnter:n=>{n.preventDefault(),tu(!0)},onDragOver:n=>{n.preventDefault(),n.dataTransfer.dropEffect="copy"},onDragLeave:n=>{n.currentTarget===n.target&&tu(!1)},onDrop:Sv,children:[Qv&&i.jsx("div",{className:"desktop-hub-recovery-overlay",children:i.jsxs("div",{className:"desktop-hub-recovery-message",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"desktop-hub-recovery-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Restoring VuvoDesk…"}),i.jsx("small",{children:"Connected computers and video will return automatically."})]})}),Yv&&i.jsx("div",{className:"mobile-hub-recovery-overlay",children:i.jsxs("div",{className:"mobile-hub-recovery-message",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"mobile-hub-recovery-spinner","aria-hidden":"true"}),i.jsx("strong",{children:Kp})]})}),Kv&&i.jsx("div",{className:"mobile-workspace-recovery-failure",children:i.jsxs("div",{className:"mobile-workspace-recovery-failure-message",role:"alert",children:[i.jsx("strong",{children:"Workspace could not be restored"}),i.jsx("small",{children:A}),i.jsx("button",{type:"button",onClick:()=>{E()},children:"Try again"})]})}),nn.length>0&&i.jsx("canvas",{ref:nv,className:"atlas-source-canvas",width:Za?.width||1920,height:Za?.height||1080,"aria-hidden":"true"}),Re?i.jsx("section",{className:"control-focus",children:i.jsxs("div",{className:"control-wall",children:[X&&i.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${Qt(X)}`,children:[i.jsx("strong",{className:"control-computer-name",title:Qt(X),children:Qt(X)}),Cv.map(n=>i.jsxs("button",{className:n.index===Gc?"active":"",onClick:()=>hv(X.deviceId,n.index),title:dM(n),type:"button",children:[i.jsx("span",{children:n.name||`Display ${n.index+1}`}),n.width>0&&n.height>0&&i.jsxs("small",{children:[n.width,"x",n.height]})]},n.index))]}),X&&Ir&&i.jsxs("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:[me&&i.jsxs(i.Fragment,{children:[i.jsx("button",{className:`remote-keyboard-button ${rm?"active":""}`,type:"button","aria-pressed":rm,"aria-label":"Open remote keyboard",title:"Open the phone keyboard for the remote computer",onClick:()=>{const n=tm.current;n&&(n.focus({preventScroll:!0}),n.setSelectionRange(n.value.length,n.value.length))},children:i.jsx(Ry,{size:15,"aria-hidden":"true"})}),i.jsx("textarea",{ref:tm,className:"remote-keyboard-input","aria-label":"Type on the remote computer",autoComplete:"off",autoCorrect:"off",autoCapitalize:"sentences",enterKeyHint:"enter",spellCheck:!1,rows:1,onFocus:()=>am(!0),onBlur:()=>{Ds.current=!1,am(!1)},onCompositionStart:()=>{Ds.current=!0},onCompositionEnd:n=>{Ds.current=!1;const o=n.currentTarget.value;n.currentTarget.value="",Ai.current?.sendText(o)},onInput:n=>{if(Ds.current)return;const o=n.currentTarget.value;n.currentTarget.value="",Ai.current?.sendText(o)},onKeyDown:n=>{n.nativeEvent.isComposing||!ol(n.key)||(n.preventDefault(),n.stopPropagation(),Mp(n.key,"keydown"))},onBeforeInput:n=>{const o=n.nativeEvent.inputType||"";ol(o)&&(n.preventDefault(),n.stopPropagation(),Mp(o,"beforeinput"))}})]}),Ik.map(n=>{const o=n.code==="MetaLeft"&&Nr(X.platform)?"Cmd":n.label,l=Ri.includes(n.code);return i.jsx("button",{className:l?"active":"",type:"button","aria-pressed":l,title:`Hold ${o} on the remote computer`,onClick:()=>Dl.current?.(n.code),children:o},n.code)})]}),X?i.jsx(wd,{device:X,frame:le,selected:!1,controlEnabled:Cr&&kn&&Ir,showStatus:on.showScreenStatus,showDeviceTitle:!1,monitorIndex:_n(X,gt[X.deviceId]),monitorCount:ka(X),onSelect:()=>{},onFocusDevice:()=>Vt(X.deviceId),onOpenControl:()=>si(X.deviceId),onCycleMonitor:n=>ku(X.deviceId,n),onCanvasReady:tv,sendInput:rs,remotePointerFeedback:cv,remoteModifierState:gu,presentationReady:Ql,remoteDiagnostics:Ut?ss.get(X.deviceId):fn?ui.get(X.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},X.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(Ra,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),X&&iu&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(wo,{size:22,"aria-hidden":"true"}),i.jsx("strong",{children:"Accessibility permission required"}),i.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts VuvoDesk, then restart the Mac client."})]}),X&&!iu&&!Ql&&i.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[be!=="error"&&i.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),i.jsx("strong",{children:be==="error"?"Connection failed":"Connecting"}),i.jsx("small",{children:be==="error"?"See the notification for details. Reopen Control to retry.":eo||Pt?"Control stream is recovering. See the notification for details.":pu==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Bt==="list"?i.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[i.jsxs("div",{className:"wall-device-list-head",role:"row",children:[i.jsx("span",{role:"columnheader",children:"Computer"}),i.jsx("span",{role:"columnheader",children:"Status"}),i.jsx("span",{role:"columnheader",children:"CPU"}),i.jsx("span",{role:"columnheader",children:"GPU"}),i.jsx("span",{role:"columnheader",children:"RAM"}),i.jsx("span",{role:"columnheader",children:"VRAM"}),i.jsx("span",{role:"columnheader",children:"Network"}),i.jsx("span",{role:"columnheader",children:"HDD"}),i.jsx("span",{role:"columnheader",children:"Temp"})]}),Gm.length>0?Gm.map(({device:n,slotNumber:o})=>i.jsx(jM,{device:n,slotNumber:o,selected:Ya.has(n.deviceId),updateIndicator:Eu(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote",onSelect:()=>Cu(n.deviceId),onOpenControl:()=>si(n.deviceId)},n.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(Ra,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"No connected computers"})]})]}):nt?i.jsx("div",{className:`screen-wall atlas-slot-wall size-${Bt}`,style:ym,onClick:n=>{n.currentTarget===n.target&&is()},children:qm.map((n,o)=>n?i.jsx(wd,{device:n,frame:ni.get(n.deviceId),selected:Ya.has(n.deviceId),controlEnabled:!1,showStatus:km,monitorIndex:_n(n,gt[n.deviceId]),monitorCount:ka(n),onSelect:()=>Cu(n.deviceId),onFocusDevice:()=>Su(n.deviceId),onOpenControl:()=>si(n.deviceId),onCycleMonitor:l=>ku(n.deviceId,l),onCanvasReady:fs({mode4Enabled:nt,directMode4WallEnabled:Mr,isMac:Nr(n.platform)})==="direct"?Zm:rv,sendInput:rs,remoteModifierState:gu,updateIndicator:Eu(n.deviceId),presentationReady:De.autoStartLive&&Kn.includes(n.deviceId)?Gl.has(n.deviceId):void 0,showPresentationSpinner:De.autoStartLive&&Kn.includes(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},n.deviceId):i.jsx(qh,{index:o},`slot-${o}`))}):i.jsx("div",{className:`screen-wall size-${Bt}`,style:ym,onClick:n=>{n.currentTarget===n.target&&is()},children:qm.map((n,o)=>n?i.jsx(wd,{device:n,frame:ni.get(n.deviceId),selected:Ya.has(n.deviceId),controlEnabled:Cr&&kn&&Ir&&X?.deviceId===n.deviceId,showStatus:km,monitorIndex:_n(n,gt[n.deviceId]),monitorCount:ka(n),onSelect:()=>Cu(n.deviceId),onFocusDevice:()=>Su(n.deviceId),onOpenControl:()=>si(n.deviceId),onCycleMonitor:l=>ku(n.deviceId,l),onCanvasReady:Zm,sendInput:rs,remoteModifierState:gu,updateIndicator:Eu(n.deviceId),presentationReady:De.autoStartLive&&Kn.includes(n.deviceId)?Gl.has(n.deviceId):void 0,showPresentationSpinner:De.autoStartLive&&Kn.includes(n.deviceId),remoteDiagnostics:Ut?ss.get(n.deviceId):fn?ui.get(n.deviceId):void 0,diagnosticsMode:Ut?"debug":"remote"},n.deviceId):i.jsx(qh,{index:o},`slot-${o}`))}),i.jsx(WM,{visible:Jb&&!Re})]}),!qi&&!me&&i.jsxs("aside",{className:`right-dock actions-mode ${Ba?"collapsed":""}`,"aria-label":"VuvoDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>Sm(n=>!n),"aria-label":Ba?"Show control panel":"Hide control panel",title:Ba?"Show control panel":"Hide control panel",type:"button",children:Ba?i.jsx(tg,{size:18}):i.jsx(ng,{size:18})}),!Ba&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:_m,className:"hidden-file-input",type:"file",multiple:!0,onChange:n=>{n.currentTarget.files&&Pp(n.currentTarget.files),n.currentTarget.value=""}}),i.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[i.jsx(bo,{label:"Control",tooltip:X?iu?"Allow Accessibility for the terminal app that starts VuvoDesk, then restart the Mac client.":Cr?Ir?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(X){if(Re&&kn){jn(!1),j("Remote control paused. Screen viewing stays on.");return}si(X.deviceId)}},disabled:!Cr||!!an,active:kn,pressed:Re&&kn,children:i.jsx(Cs,{size:17})}),i.jsx(bo,{label:"Audio",tooltip:X?sr?Zt?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{bv()},disabled:!Qm||!!an,active:Zt,pressed:Zt,children:an==="audio"?i.jsx(ds,{className:"spin",size:17}):i.jsx(of,{size:17})}),i.jsx(bo,{label:yc?"Retry pause":Yi?"Pause video":"Resume video",tooltip:Ki.length===0?"Select one or more Clients to pause video":yc?"Retry every selected Client whose capture shutdown is unconfirmed":Yi?`Pause video for ${Dn.length} selected Client${Dn.length===1?"":"s"}`:`Resume video for ${Dn.length} selected Client${Dn.length===1?"":"s"}`,onClick:()=>{yv()},disabled:Dn.length===0||!!an,active:!Yi,pressed:!Yi,children:an==="video"?i.jsx(ds,{className:"spin",size:17}):!Yi&&!yc?i.jsx(Ay,{size:17}):i.jsx(Iy,{size:17})}),i.jsx(bo,{label:"Send files",tooltip:cn.length===0&&!Re?"Select one or more Clients to send files":X?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{j(`Choose files to send to ${Iv}.`),_m.current?.click()},disabled:!!an||!pt||(Re?!X:cn.length===0),children:i.jsx(Hu,{size:17})}),i.jsx(bo,{label:"Restart",tooltip:X?Qo?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Mu("restart")},disabled:!X||!pt||!!an||!Qo,children:an==="restart"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Ty,{size:17})}),i.jsx(bo,{label:"Sleep",tooltip:X?Qo?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Mu("sleep")},disabled:!X||!pt||!!an||!Qo,children:an==="sleep"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Py,{size:17})}),i.jsx(bo,{label:"Shut down",tooltip:X?Qo?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Mu("shutdown")},disabled:!X||!pt||!!an||!Qo,danger:!0,children:an==="shutdown"?i.jsx(ds,{className:"spin",size:17}):i.jsx(Ey,{size:17})})]})]}),i.jsx(hs,{children:i.jsx(hh,{hubUrl:Y,devices:Me,variant:"dock",selectedDeviceIds:Tv})})]})]})]})})]}),me&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Ei?"active":"",onClick:()=>Mb(n=>{const o=!n;return CM(o),o}),type:"button","aria-label":Ei?"Hide computer stats":"Show computer stats","aria-pressed":Ei,title:Ei?"Hide CPU, GPU, RAM, and online status":"Show CPU, GPU, RAM, and online status",children:[i.jsx(Ny,{size:19}),i.jsx("span",{children:"Stats"})]}),i.jsxs("button",{className:It==="wall"?"active":"",onClick:()=>mo("wall"),type:"button",children:[i.jsx(Jh,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:Re?"active":"",onClick:()=>X&&void si(X.deviceId),disabled:!X||!Cr,type:"button",children:[i.jsx(Cs,{size:19}),i.jsx("span",{children:"Control"})]}),!re&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:Ga?"active":"",onClick:()=>mo("share-files"),type:"button",children:[i.jsx(Zh,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:mc?"active":"",onClick:()=>mo("agents"),type:"button",children:[i.jsx(gl,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:qi?"active":"",onClick:()=>mo("settings"),type:"button",children:[i.jsx(nf,{size:19}),i.jsx("span",{children:"Settings"})]})]})]}),qa&&i.jsxs("aside",{className:`transfer-bar state-${qa.status}`,"aria-live":"polite",children:[i.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:qa.status==="queued"?i.jsx(Cn,{size:18}):qa.status==="failed"?i.jsx(Ma,{size:18}):i.jsx(Fy,{size:18})}),i.jsxs("div",{className:"transfer-bar-copy",children:[i.jsx("p",{children:qa.message}),i.jsx("div",{className:"transfer-bar-track",children:i.jsx("span",{style:{width:`${Math.max(0,Math.min(100,qa.progress))}%`}})})]}),i.jsxs("strong",{children:[Math.max(0,Math.min(100,qa.progress)),"%"]})]}),Da&&i.jsxs("aside",{className:`livedesk-toast tone-${Da.tone}`,role:Da.tone==="error"?"alert":"status","aria-live":Da.tone==="error"?"assertive":"polite","aria-busy":Da.tone==="progress",children:[Da.tone==="progress"&&i.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),i.jsx("span",{children:Da.message}),i.jsx("button",{className:"livedesk-toast-close",onClick:()=>j(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(Ma,{size:15})})]})]})}export{F0 as A,mx as H,ag as a,sx as b,ux as c,dx as d,Wy as f,cx as g,lx as l,Zu as n,Wd as r,Ct as s};
|