livedesk 0.1.404 → 0.1.405
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.
|
@@ -11,7 +11,7 @@ Error generating stack: `+o.message+`
|
|
|
11
11
|
${Pd(a,r)}`}const lb={eyebrow:"Change computer role",title:"Switch this computer to Hub?",description:"LiveDesk 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 LiveDesk restarts.",cancel:"Cancel",confirm:"Switch to Hub",closeLabel:"Close Hub switch confirmation"},cC={en:lb,ko:{eyebrow:"컴퓨터 역할 변경",title:"이 컴퓨터를 Hub로 전환하시겠습니까?",description:"이 컴퓨터의 Client 공유를 중지하고 Hub 역할을 저장한 뒤 로컬 런타임을 재시작하여 같은 창에서 Wall을 엽니다.",restartNotice:"LiveDesk가 재시작되는 동안 이 컴퓨터의 원격 스트림이 종료됩니다.",cancel:"취소",confirm:"Hub로 전환",closeLabel:"Hub 전환 확인 닫기"},ja:{eyebrow:"コンピューターの役割を変更",title:"このコンピューターを Hub に切り替えますか?",description:"このコンピューターの Client 共有を停止し、Hub の役割を保存してローカルランタイムを再起動し、同じウィンドウで Wall を開きます。",restartNotice:"LiveDesk の再起動中、このコンピューターのリモートストリームは終了します。",cancel:"キャンセル",confirm:"Hub に切り替える",closeLabel:"Hub 切り替え確認を閉じる"},zh:{eyebrow:"更改电脑角色",title:"将此电脑切换为 Hub?",description:"LiveDesk 将停止此电脑的 Client 共享,保存 Hub 角色,重启本地运行时,并在同一窗口中打开 Wall。",restartNotice:"LiveDesk 重启期间,此电脑的远程流将会结束。",cancel:"取消",confirm:"切换为 Hub",closeLabel:"关闭 Hub 切换确认"},"zh-TW":{eyebrow:"變更電腦角色",title:"要將此電腦切換為 Hub 嗎?",description:"LiveDesk 將停止此電腦的 Client 分享、儲存 Hub 角色、重新啟動本機執行階段,並在同一視窗中開啟 Wall。",restartNotice:"LiveDesk 重新啟動期間,此電腦的遠端串流將會結束。",cancel:"取消",confirm:"切換為 Hub",closeLabel:"關閉 Hub 切換確認"},es:{eyebrow:"Cambiar función del equipo",title:"¿Cambiar este equipo a Hub?",description:"LiveDesk 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 LiveDesk 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:"LiveDesk 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 LiveDesk.",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:"LiveDesk 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 LiveDesk-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 LiveDesk 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 LiveDesk 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:"LiveDesk 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 LiveDesk.",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:"LiveDesk 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 LiveDesk 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:"LiveDesk 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 LiveDesk 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:"LiveDesk จะหยุดแชร์คอมพิวเตอร์เครื่องนี้ในฐานะ Client บันทึกบทบาท Hub รีสตาร์ทรันไทม์ภายในเครื่อง และเปิด Wall ในหน้าต่างเดิม",restartNotice:"สตรีมระยะไกลจากคอมพิวเตอร์เครื่องนี้จะสิ้นสุดลงระหว่างที่ LiveDesk รีสตาร์ท",cancel:"ยกเลิก",confirm:"เปลี่ยนเป็น Hub",closeLabel:"ปิดการยืนยันการเปลี่ยนเป็น Hub"},hi:{eyebrow:"कंप्यूटर की भूमिका बदलें",title:"इस कंप्यूटर को Hub में बदलें?",description:"LiveDesk इस कंप्यूटर की Client साझेदारी बंद करेगा, Hub भूमिका सहेजेगा, स्थानीय रनटाइम पुनः आरंभ करेगा और इसी विंडो में Wall खोलेगा।",restartNotice:"LiveDesk के पुनः आरंभ होने के दौरान इस कंप्यूटर की रिमोट स्ट्रीम समाप्त हो जाएँगी।",cancel:"रद्द करें",confirm:"Hub में बदलें",closeLabel:"Hub परिवर्तन की पुष्टि बंद करें"},ar:{eyebrow:"تغيير دور الكمبيوتر",title:"هل تريد تحويل هذا الكمبيوتر إلى Hub؟",description:"سيوقف LiveDesk مشاركة هذا الكمبيوتر كـ Client، ويحفظ دور Hub، ويعيد تشغيل وقت التشغيل المحلي، ثم يفتح Wall في النافذة نفسها.",restartNotice:"ستنتهي التدفقات البعيدة من هذا الكمبيوتر أثناء إعادة تشغيل LiveDesk.",cancel:"إلغاء",confirm:"التحويل إلى Hub",closeLabel:"إغلاق تأكيد التحويل إلى Hub"},tr:{eyebrow:"Bilgisayar rolünü değiştir",title:"Bu bilgisayar Hub rolüne geçirilsin mi?",description:"LiveDesk 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:"LiveDesk 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"}};function uC(n){const a=Zh(n);return cC[a]||lb}const dC=[{id:"docs",label:"Doc",icon:Bd},{id:"support",label:"Support",icon:Lc},{id:"pricing",label:"Pricing",icon:Ao},{id:"settings",label:"Settings",icon:qx}],xy=[0,1e3,2e3,5e3,1e4,2e4,3e4];function fC(){return typeof window>"u"?"":window.location.port==="5179"?window.location.origin:"http://127.0.0.1:5179"}async function kc(n,a=!1){const r=a?"":sessionStorage.getItem("livedesk.client.csrf");if(r)return r;const l=await fetch(`${n}/api/runtime/status`,{cache:"no-store"}),c=await l.json().catch(()=>({}));if(!l.ok)throw new Error(c.error||`Client runtime returned HTTP ${l.status}.`);const d=String(c.csrfToken||"");return d&&sessionStorage.setItem("livedesk.client.csrf",d),d}function Nh(n){return`${Math.max(0,Math.min(100,Number(n||0))).toFixed(0)}%`}function Ym(n){return Number.isFinite(n)?`${Math.max(0,Math.min(100,Number(n))).toFixed(0)}%`:"—"}function ob(n){return Number.isFinite(n)?Nh(Number(n)):"0%"}function Tl(n){const a=Number(n);return!Number.isFinite(a)||a<0?"—":a>=1024**4?`${(a/1024**4).toFixed(a>=10*1024**4?0:1)} TB`:a>=1024**3?`${(a/1024**3).toFixed(a>=10*1024**3?0:1)} GB`:`${(a/1024**2).toFixed(0)} MB`}function by(n){const a=Math.max(0,Number(n||0));return a>=1024**3?`${(a/1024**3).toFixed(1)} GB/s`:a>=1024**2?`${(a/1024**2).toFixed(1)} MB/s`:a>=1024?`${(a/1024).toFixed(1)} KB/s`:`${a.toFixed(0)} B/s`}function mC(n,a){const r=Number(n||0)/1073741824,l=Number(a||0)/1024**3;return l>0?`${r.toFixed(1)} / ${l.toFixed(1)} GB`:"Checking..."}function hC(n,a){return!Number.isFinite(a)||Number(a)<=0?"Dedicated memory unavailable":Number.isFinite(n)?`${Tl(n)} / ${Tl(a)}`:`${Tl(a)} available`}function pC(n){const a=Math.max(0,Math.floor(Number(n||0)/60)),r=Math.floor(a/1440),l=Math.floor(a%1440/60),c=a%60;return r>0?`${r}d ${l}h`:l>0?`${l}h ${c}m`:`${c}m`}function ud({icon:n,label:a,value:r,detail:l,percent:c}){return s.jsxs("article",{className:"client-resource-metric",children:[s.jsxs("div",{className:"client-resource-metric-head",children:[s.jsx(n,{size:17}),s.jsx("span",{children:a}),s.jsx("strong",{children:r})]}),s.jsx("small",{title:l,children:l}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:ob(c)}})})]})}function gC(n){const a=n?.user.user_metadata||{},r=a.full_name||a.name||a.preferred_username||n?.user.email||n?.user.id||"Account";return String(r).trim()||"Account"}function vC(n){const a=n?.user.user_metadata||{},r=a.avatar_url||a.picture;return typeof r=="string"?r.trim():""}function yC({page:n,status:a}){const l={docs:{label:"DOC",title:"Using this computer",body:"This computer connects to its assigned Hub automatically. Keep LiveDesk running and manage screens, files, and remote control from the Hub."},pricing:{label:"PRICING",title:"LiveDesk plans",body:"Plans are based on how many computers the Hub manages. This Client computer does not need a separate subscription or setup."},settings:{label:"SETTINGS",title:"Computer preferences",body:"LiveDesk keeps the verified sign-in on this computer and reconnects to the assigned Hub automatically."}}[n];return s.jsxs("section",{className:"client-service-page",children:[s.jsx("span",{className:"client-unified-section-label",children:l.label}),s.jsx("h2",{children:l.title}),s.jsx("p",{children:l.body}),s.jsxs("div",{className:"client-service-page-card",children:[n==="docs"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Automatic connection"}),s.jsx("span",{children:"Start LiveDesk. This computer signs in, finds the Hub, and becomes available without another action."})]}),n==="pricing"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"One plan, managed at the Hub"}),s.jsx("span",{children:"Computer access follows the account and plan used by the Hub."})]}),n==="settings"&&s.jsxs(s.Fragment,{children:[s.jsx("strong",{children:"Saved sign-in"}),s.jsx("span",{children:a?.auth?.persisted?"Enabled on this computer":"Sign in once to enable automatic reconnection"})]})]})]})}function xC({session:n,status:a,pin:r,error:l,roleChangeMessage:c,roleChangeBusy:d,onSignIn:m,onPinChange:p,onSubmitPin:g,onSwitchToHub:v}){const w=a?.connectionState==="connected",x=a?.system?.memoryTotalBytes?Number(a.system.memoryUsedBytes||0)/a.system.memoryTotalBytes*100:0,b=a?.system?.gpus||[],C=b.find(O=>Number.isFinite(O.usagePercent)||Number.isFinite(O.memoryTotalBytes))||b[0],j=Number.isFinite(C?.usagePercent)?Number(C?.usagePercent):null,A=Number.isFinite(C?.memoryTotalBytes)&&Number(C?.memoryTotalBytes)>0&&Number.isFinite(C?.memoryUsedBytes)?Number(C?.memoryUsedBytes)/Number(C?.memoryTotalBytes)*100:null,N=a?.system?.disks||[],k=a?.system?.network,T=k?.interfaces||[],R=[...new Set(T.map(O=>O.name).filter(Boolean))],U=T.map(O=>O.address).filter(Boolean);return s.jsxs("section",{className:"client-home-page",children:[s.jsxs("header",{className:"client-home-heading",children:[s.jsxs("div",{children:[s.jsx("p",{className:"client-unified-eyebrow",children:"THIS COMPUTER"}),s.jsx("h2",{children:a?.deviceName||"This Computer"})]}),s.jsxs("span",{className:`client-unified-role-chip ${w?"connected":""}`,children:[s.jsx(an,{size:15})," ",w?"Online":"Connecting"]})]}),s.jsxs("div",{className:"client-home-layout",children:[s.jsxs("section",{className:"client-main-surface","aria-label":"Client computer",children:[s.jsxs("div",{className:"client-main-surface-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"SYSTEM STATUS"}),s.jsx("strong",{children:"Hardware at a glance"})]}),s.jsxs("small",{children:[s.jsx(Vx,{size:14})," Uptime ",pC(a?.system?.uptimeSeconds)]})]}),s.jsxs("div",{className:"client-system-dashboard",children:[s.jsxs("section",{className:"client-performance-panel","aria-label":"Performance",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"PERFORMANCE"}),s.jsx("strong",{children:"Live resources"})]}),s.jsx("small",{children:"Live updates"})]}),s.jsxs("div",{className:"client-live-metrics",children:[s.jsx(ud,{icon:Wx,label:"CPU",value:Nh(a?.system?.cpuUsagePercent),detail:a?.system?.cpuLogicalCores?`${a.system.cpuLogicalCores} logical cores · Current processor usage`:"Current processor usage",percent:a?.system?.cpuUsagePercent}),s.jsx(ud,{icon:$S,label:"Memory",value:Nh(x),detail:mC(a?.system?.memoryUsedBytes,a?.system?.memoryTotalBytes),percent:x}),s.jsx(ud,{icon:US,label:"GPU",value:Ym(j),detail:C?.name||(a?.system?.hardwareCollecting?"Detecting graphics hardware…":"Graphics usage unavailable"),percent:j}),s.jsx(ud,{icon:El,label:"VRAM",value:Ym(A),detail:hC(C?.memoryUsedBytes,C?.memoryTotalBytes),percent:A})]})]}),s.jsxs("section",{className:"client-storage-panel","aria-label":"Local storage",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"STORAGE"}),s.jsx("strong",{children:"Local drives"})]}),s.jsx("small",{children:N.length>0?`${N.length} ${N.length===1?"drive":"drives"}`:a?.system?.hardwareCollecting?"Detecting…":"Unavailable"})]}),s.jsxs("div",{className:"client-disk-list",children:[N.map(O=>s.jsxs("article",{className:"client-disk-row",children:[s.jsxs("div",{className:"client-disk-row-head",children:[s.jsxs("span",{children:[s.jsx(Ml,{size:16}),s.jsx("strong",{children:O.mount||"Disk"}),s.jsx("small",{children:O.name||"Local disk"})]}),s.jsx("strong",{children:Ym(O.usedPercent)})]}),s.jsxs("small",{children:[Tl(O.freeBytes)," free · ",Tl(O.totalBytes)," total"]}),s.jsx("i",{"aria-hidden":"true",children:s.jsx("b",{style:{width:ob(O.usedPercent)}})})]},`${O.mount}-${O.name||""}`)),N.length===0&&s.jsxs("div",{className:"client-disk-empty",children:[s.jsx(Ml,{size:18}),s.jsx("span",{children:a?.system?.hardwareCollecting?"Detecting local drives…":"Storage information is not available."})]})]})]}),s.jsxs("section",{className:"client-network-panel","aria-label":"Network activity",children:[s.jsxs("div",{className:"client-system-subhead",children:[s.jsxs("div",{children:[s.jsx("span",{className:"client-unified-section-label",children:"NETWORK"}),s.jsx("strong",{children:"Live traffic"})]}),s.jsx("small",{children:R.length>0?R.join(", "):"Detecting adapter"})]}),s.jsxs("div",{className:"client-network-live",children:[s.jsxs("div",{className:"client-network-adapter",children:[s.jsx(Dl,{size:18}),s.jsxs("span",{children:[s.jsx("strong",{children:R.join(", ")||"Network"}),s.jsx("small",{children:U.join(" / ")||"Checking active connection"})]})]}),s.jsxs("div",{className:"client-network-rate download",children:[s.jsx(qS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Receive"}),s.jsx("strong",{children:by(k?.receiveBytesPerSecond)})]})]}),s.jsxs("div",{className:"client-network-rate upload",children:[s.jsx(GS,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Send"}),s.jsx("strong",{children:by(k?.sendBytesPerSecond)})]})]}),s.jsxs("small",{className:"client-network-total",children:["Total ",Tl(k?.receivedBytes)," received / ",Tl(k?.sentBytes)," sent"]})]})]})]})]}),s.jsxs("aside",{className:"client-connection-panel",children:[s.jsx("span",{className:"client-unified-section-label",children:"LIVEDESK SERVICES"}),s.jsx("h3",{children:w?"Connected to the Hub":a?.authenticated?"Finding the Hub":"Connect this computer"}),w?s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"client-unified-copy",children:"This computer is available from the LiveDesk Hub."}),s.jsxs("div",{className:"client-service-status-list",children:[s.jsxs("div",{children:[s.jsx(an,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Screen sharing"}),s.jsx("small",{children:a?.permissions?.screenCapture?"Active":"Waiting"})]})]}),s.jsxs("div",{children:[s.jsx(Bt,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Remote control"}),s.jsx("small",{children:a?.permissions?.remoteInput?"Available":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(No,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"File delivery"}),s.jsx("small",{children:a?.permissions?.files?"Ready to receive":"Unavailable"})]})]}),s.jsxs("div",{children:[s.jsx(pn,{size:17}),s.jsxs("span",{children:[s.jsx("strong",{children:"Computer audio"}),s.jsx("small",{children:a?.permissions?.audio?"Available":"Unavailable"})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"client-unified-copy",children:a?.authenticated?"LiveDesk is checking the registered Hub endpoints. A temporary Hub PIN can be used as a fallback.":"Sign in once on this computer. LiveDesk saves the verified session, finds the Hub, and starts screen sharing automatically."}),!n&&!a?.authenticated?s.jsxs("button",{className:"client-unified-primary",type:"button",onClick:m,children:[s.jsx(Rl,{size:16})," Sign in with Google"]}):s.jsxs("p",{className:"client-unified-success",children:[s.jsx(Fn,{size:16})," Signed in as ",n?.user.email||n?.user.id||a?.userEmail||a?.userId||"saved account"]}),s.jsxs("div",{className:"client-unified-pin-row",children:[s.jsx(Mo,{size:16}),s.jsx("input",{value:r,onChange:O=>p(O.target.value),placeholder:"6-digit Hub PIN",inputMode:"numeric","aria-label":"6-digit Hub PIN"}),s.jsx("button",{className:"client-unified-secondary",type:"button",onClick:g,disabled:r.length!==6,children:"Connect"})]})]}),(l||a?.lastError)&&s.jsxs("p",{className:"client-unified-error",role:"alert",children:[s.jsx(Yx,{size:15})," ",l||a?.lastError]}),c&&s.jsx("p",{className:"client-unified-success",children:c}),s.jsxs("button",{className:"client-unified-secondary full client-hub-switch-trigger",type:"button",onClick:v,disabled:d||!a?.authenticated,children:[s.jsx(El,{size:16})," ",d?"Switching to Hub…":"Switch this computer to Hub"]})]})]})]})}function bC(){const[n,a]=u.useState(null),[r,l]=u.useState(null),[c,d]=u.useState(!1),[m,p]=u.useState(""),[g,v]=u.useState(""),[w,x]=u.useState(""),[b,C]=u.useState(!1),[j,A]=u.useState(!1),[N,k]=u.useState("computer"),[T,R]=u.useState(!1),U=u.useRef(null),O=u.useRef(null),Y=u.useRef(!1),_=u.useRef(!1),D=u.useRef(!1),ne=u.useRef(0),G=u.useMemo(fC,[]),te=u.useMemo(()=>gC(r),[r]),B=u.useMemo(()=>vC(r),[r]),xe=te.slice(0,1).toUpperCase()||"L",se=u.useCallback(async()=>{if(v(""),window.liveDesk?.auth?.signInWithGoogle){const re=await window.liveDesk.auth.signInWithGoogle();return re?.ok===!1?(v(re.error||"LiveDesk could not open the system browser for Google sign-in."),!1):!0}return window.location.assign(`${G}/auth/google`),!0},[G]),K=u.useCallback(async()=>{D.current||(D.current=!0,v("Your saved Google sign-in is incomplete. LiveDesk is reopening sign-in once to repair it."),await pt.auth.signOut({scope:"local"}).catch(()=>{}),l(null),await se()||(D.current=!1))},[se]),I=u.useCallback(async re=>{const Z=vy(re);if(Z)throw new Error(Z);if(Y.current)return!1;Y.current=!0;try{const ze=await window.liveDesk?.auth?.persistSession?.(re);if(ze?.ok===!1)throw new Error(ze.error||"LiveDesk could not validate the desktop session.");for(let Le=0;Le<2;Le+=1){const ae=await kc(G,Le>0),fe=await fetch(`${G}/api/auth/session`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":ae},signal:AbortSignal.timeout(1e4),body:JSON.stringify({accessToken:re.access_token,refreshToken:re.refresh_token,expiresAt:re.expires_at,user:{id:re.user.id,email:re.user.email}})}),Ae=await fe.json().catch(()=>({}));if(fe.status===403&&Le===0){sessionStorage.removeItem("livedesk.client.csrf");continue}if(!fe.ok)throw new Error(Ae.error||`Client runtime returned HTTP ${fe.status}.`);return v(""),!0}throw new Error("Client runtime rejected the session transfer.")}finally{Y.current=!1}},[G]),Q=u.useCallback(async()=>{try{const re=await fetch(`${G}/api/client/status`,{cache:"no-store"}),Z=await re.json().catch(()=>({}));if(!re.ok)throw new Error(Z.error||`Client runtime returned HTTP ${re.status}.`);if(Z.csrfToken&&sessionStorage.setItem("livedesk.client.csrf",Z.csrfToken),String(Z.role||"").toLowerCase()==="hub")throw new Error("This computer is assigned to the Hub role.");a(Z)}catch(re){v(re instanceof Error?re.message:String(re))}},[G]);u.useEffect(()=>{Q();const re=window.setInterval(()=>{Q()},2e3);return()=>window.clearInterval(re)},[Q]);const q=u.useCallback(async()=>{const re=Date.now();if(!(!n?.authenticated||n.connectionState==="connected"||!["waiting","reconnecting"].includes(String(n.agent?.state||""))||re-ne.current<4e3)){ne.current=re;try{const Z=await fetch(`${G}/api/client/reconnect`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await kc(G)},body:JSON.stringify({onlyIfWaiting:!0,reason:"app-active"})});if(!Z.ok)throw new Error(`Client reconnect returned HTTP ${Z.status}.`);await Q()}catch(Z){v(Z instanceof Error?Z.message:String(Z))}}},[G,Q,n]);u.useEffect(()=>{const re=()=>{q()},Z=()=>{q()},ze=()=>{document.visibilityState==="visible"&&q()};return window.addEventListener("online",re),window.addEventListener("focus",Z),document.addEventListener("visibilitychange",ze),()=>{window.removeEventListener("online",re),window.removeEventListener("focus",Z),document.removeEventListener("visibilitychange",ze)}},[q]),u.useEffect(()=>{if(!c||!n||!r?.access_token||n.authenticated)return;if(vy(r)==="refresh-token-required"){K().catch(ae=>{D.current=!1,v(ae instanceof Error?ae.message:String(ae))});return}let re=!1,Z,ze=0;const Le=async()=>{if(re)return;try{const fe=await I(r);if(await Q(),fe)return}catch(fe){v(fe instanceof Error?fe.message:String(fe))}if(re)return;const ae=xy[Math.min(ze,xy.length-1)];ze+=1,Z=window.setTimeout(()=>{Le()},ae)};return Le(),()=>{re=!0,Z!==void 0&&window.clearTimeout(Z)}},[c,Q,K,r,n,I]),u.useEffect(()=>{const re=new URLSearchParams(window.location.search),Z=re.get("auth_error");if(!Z)return;v(Z),re.delete("auth_error");const ze=re.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${ze?`?${ze}`:""}${window.location.hash}`)},[]),u.useEffect(()=>{let re=!0;if(!window.liveDesk?.auth)return l(null),d(!0),Q(),()=>{re=!1};const Z=window.liveDesk?.auth?.onComplete?.(Le=>{Le.ok&&Le.session?pt.auth.setSession(Le.session).catch(ae=>v(ae instanceof Error?ae.message:String(ae))):Le.error&&v(Le.error)});(async()=>{try{const Le=window.liveDesk?.auth?.getSession?await window.liveDesk.auth.getSession():await pt.auth.getSession();if(!re)return;const ae=nb(Le);l(ae),Q()}catch(Le){re&&v(Le instanceof Error?Le.message:String(Le))}finally{re&&d(!0)}})();const{data:ze}=pt.auth.onAuthStateChange((Le,ae)=>{re&&(l(ae),d(!0),Q())});return()=>{re=!1,Z?.(),ze.subscription.unsubscribe()}},[Q]),u.useEffect(()=>{if(!c||!n||_.current||D.current||r||n.authenticated)return;const re=new URLSearchParams(window.location.search);if(!re.has("livedesk_launch"))return;_.current=!0,re.delete("livedesk_launch");const Z=re.toString();window.history.replaceState(window.history.state,"",`${window.location.pathname}${Z?`?${Z}`:""}${window.location.hash}`),se().catch(ze=>v(ze instanceof Error?ze.message:String(ze)))},[c,r,se,n]);const V=async()=>{R(!1),window.liveDesk?.auth?.persistSession?(await pt.auth.signOut(),(await window.liveDesk.auth.persistSession(null))?.runtimeCleared===!1&&v("Signed out locally. The LiveDesk runtime could not be reached to clear its session.")):await fetch(`${G}/api/auth/session`,{method:"DELETE",headers:{"X-LiveDesk-CSRF":await kc(G)}}).catch(()=>{}),l(null),await Q()};u.useEffect(()=>{if(!T)return;const re=ze=>{ze.target instanceof Element&&ze.target.closest(".account-popover, .rail-account")||R(!1)},Z=ze=>{ze.key==="Escape"&&R(!1)};return window.addEventListener("pointerdown",re),window.addEventListener("keydown",Z),()=>{window.removeEventListener("pointerdown",re),window.removeEventListener("keydown",Z)}},[T]);const ce=u.useCallback((re=!0)=>{b||(A(!1),re&&window.requestAnimationFrame(()=>O.current?.focus()))},[b]),be=u.useCallback(()=>{b||!n?.authenticated||(O.current=document.activeElement instanceof HTMLElement?document.activeElement:null,x(""),A(!0))},[b,n?.authenticated]);u.useEffect(()=>{if(!j)return;const re=window.requestAnimationFrame(()=>U.current?.focus()),Z=Le=>{Le.target instanceof Element&&Le.target.closest(".client-hub-switch-popover, .client-hub-switch-trigger")||ce(!1)},ze=Le=>{Le.key==="Escape"&&ce()};return window.addEventListener("pointerdown",Z),window.addEventListener("keydown",ze),()=>{window.cancelAnimationFrame(re),window.removeEventListener("pointerdown",Z),window.removeEventListener("keydown",ze)}},[ce,j]);const X=async()=>{v("");try{const re=await fetch(`${G}/api/client/pin`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await kc(G)},body:JSON.stringify({pin:m})}),Z=await re.json().catch(()=>({}));if(!re.ok||Z?.ok===!1)throw new Error(Z?.error||"PIN could not be accepted.");p(""),await Q()}catch(re){v(re instanceof Error?re.message:String(re))}},$=async()=>{A(!1),C(!0),x(""),v("");try{const re=await fetch(`${G}/api/runtime/switch-role`,{method:"POST",headers:{"Content-Type":"application/json","X-LiveDesk-CSRF":await kc(G)},body:JSON.stringify({role:"hub"})}),Z=await re.json().catch(()=>({}));if(!re.ok||Z?.ok===!1)throw new Error(Z?.error||`Role change failed with HTTP ${re.status}.`);x("Hub role accepted. LiveDesk is restarting this computer with the Hub Wall.");const ze=Number(n?.runtimePid||0);await ab({baseUrl:G,targetRole:"hub",previousRuntimePid:ze,allowedStates:["running"]}),window.location.reload()}catch(re){v(re instanceof Error?re.message:String(re)),C(!1)}},ue=!!(n?.authenticated||r),he=u.useMemo(()=>Zh(),[]),ve=Pd("switch-to-hub",he),Se=Pd("client",he),_e=uC(he);return s.jsxs("main",{className:"app-shell client-unified-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk Client tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ib,{size:25})}),s.jsx("nav",{className:"rail-tools","aria-label":"Client navigation",children:s.jsxs("div",{className:"client-main-tool-slot",children:[s.jsxs("button",{className:"rail-tool client-main-tool client-hub-tool client-hub-switch-trigger accent-blue",type:"button",onClick:be,disabled:b||!n?.authenticated,"aria-busy":b,"aria-expanded":j,"aria-haspopup":"dialog","aria-controls":j?"client-hub-switch-popover":void 0,"aria-label":`Hub. ${ve}`,"data-tooltip":j?void 0:Ah("Hub","switch-to-hub",he),children:[s.jsx(El,{size:19}),s.jsx("span",{children:b?"Switching…":"Hub"})]}),s.jsxs("button",{className:`rail-tool client-main-tool accent-blue ${N==="computer"?"active":""}`,type:"button",onClick:()=>k("computer"),"aria-current":N==="computer"?"page":void 0,"aria-label":`Client. ${Se}`,"data-tooltip":Ah("Client","client",he),children:[s.jsx(an,{size:19}),s.jsx("span",{children:"Client"})]})]})}),s.jsxs("div",{className:"rail-footer",children:[dC.map(re=>{const Z=re.icon;return s.jsxs("button",{className:`rail-tool compact ${N===re.id?"active":""}`,type:"button",onClick:()=>k(re.id),title:re.label,children:[s.jsx(Z,{size:18}),s.jsx("span",{children:re.label})]},re.id)}),s.jsxs("button",{className:`rail-account ${ue?"signed-in":""}`,type:"button",onClick:()=>R(re=>!re),"aria-expanded":T,"aria-haspopup":"dialog",title:ue?"Account":"Sign in",children:[r&&B?s.jsx("img",{src:B,alt:te,referrerPolicy:"no-referrer"}):r?s.jsx("span",{className:"avatar-fallback",children:xe}):ue?s.jsx(Bt,{size:18}):s.jsx(Rl,{size:18}),s.jsx("span",{children:ue?"Account":"Sign in"})]})]})]}),j&&s.jsxs("section",{id:"client-hub-switch-popover",className:"client-hub-switch-popover",role:"dialog","aria-modal":"false","aria-labelledby":"client-hub-switch-title","aria-describedby":"client-hub-switch-description client-hub-switch-restart",children:[s.jsxs("header",{className:"client-hub-switch-head",children:[s.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:s.jsx(El,{size:19})}),s.jsx("span",{className:"client-hub-switch-eyebrow",children:_e.eyebrow}),s.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>ce(),"aria-label":_e.closeLabel,children:s.jsx(Ya,{size:17})})]}),s.jsx("h2",{id:"client-hub-switch-title",children:_e.title}),s.jsx("p",{id:"client-hub-switch-description",children:_e.description}),s.jsxs("p",{id:"client-hub-switch-restart",className:"client-hub-switch-notice",children:[s.jsx(Bt,{size:16,"aria-hidden":"true"}),s.jsx("span",{children:_e.restartNotice})]}),s.jsxs("div",{className:"client-hub-switch-actions",children:[s.jsx("button",{type:"button",onClick:()=>ce(),children:_e.cancel}),s.jsxs("button",{ref:U,className:"primary",type:"button",onClick:()=>{$()},disabled:b||!n?.authenticated,children:[s.jsx(El,{size:16}),_e.confirm]})]})]}),T&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:r&&B?s.jsx("img",{src:B,alt:te,referrerPolicy:"no-referrer"}):r?s.jsx("span",{children:xe}):s.jsx(Rl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:r?te:ue?"Saved account":"Account"}),s.jsx("p",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:r?.user.email||n?.userEmail||n?.userId||"Not signed in"}),s.jsx("dt",{children:"Runtime"}),s.jsx("dd",{children:n?"Local app ready":"Checking local app"}),s.jsx("dt",{children:"Session"}),s.jsx("dd",{children:n?.auth?.persisted?"Saved on this computer":ue?"Active for this run":"Not saved"}),s.jsx("dt",{children:"Role"}),s.jsx("dd",{children:"Client"})]}),ue?s.jsxs("button",{className:"account-popover-action",onClick:()=>{V()},type:"button",children:[s.jsx(Gx,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:()=>{R(!1),se()},type:"button",children:[s.jsx(Rl,{size:16}),"Sign in with Google"]})]}),s.jsxs("section",{className:"desk-stage client-unified-stage",children:[s.jsx("header",{className:"topbar",children:s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(pn,{size:18})}),s.jsxs("div",{children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Client workspace"})]})]})}),N==="support"?s.jsx("section",{className:"client-unified-page",children:s.jsx(tb,{session:r,currentProductKey:"livedesk",appVersion:n?.appVersion||"",onSignIn:()=>{se()}})}):N!=="computer"?s.jsx("section",{className:"client-unified-page",children:s.jsx(yC,{page:N,status:n})}):s.jsx(xC,{session:r,status:n,pin:m,error:g,roleChangeMessage:w,roleChangeBusy:b,onSignIn:()=>{se()},onPinChange:re=>p(re.replace(/\D/g,"").slice(0,6)),onSubmitPin:()=>{X()},onSwitchToHub:be})]})]})}function Lr(n,a,r){if(r<0||a<0||a+r>n.length)throw new Error("Invalid LZO1X block: input overrun.")}function Km(n,a,r){let l=0;for(;Lr(n,a.inputIndex,1),n[a.inputIndex]===0;)l+=1,a.inputIndex+=1;const c=l*255+r+n[a.inputIndex];return a.inputIndex+=1,c}function dd(n,a,r,l){if(Lr(n,a.inputIndex,l),a.outputIndex+l>r.length)throw new Error("Invalid LZO1X block: output overrun.");r.set(n.subarray(a.inputIndex,a.inputIndex+l),a.outputIndex),a.inputIndex+=l,a.outputIndex+=l}function wC(n,a,r,l){const c=a-r;if(c<=0||l<=0)throw new Error("Invalid LZO1X block: invalid match distance.");let d=Math.min(c,l);for(n.set(n.subarray(r,r+d),a);d<l;){const m=Math.min(d,l-d);n.copyWithin(a+d,a,a+m),d+=m}return a+l}function cb(n,a){if(!(n instanceof Uint8Array)||n.length<3||a<0)throw new Error("Invalid LZO1X block.");const r=new Uint8Array(a),l={inputIndex:0,outputIndex:0};let c=0,d=0;if(n[l.inputIndex]>=22){const m=n[l.inputIndex]-17;l.inputIndex+=1,dd(n,l,r,m),c=4}else n[l.inputIndex]>=18&&(c=n[l.inputIndex]-17,l.inputIndex+=1,dd(n,l,r,c));for(;;){Lr(n,l.inputIndex,1);const m=n[l.inputIndex];l.inputIndex+=1;let p,g;if((m&192)!==0)Lr(n,l.inputIndex,1),g=l.outputIndex-((n[l.inputIndex]<<3)+(m>>2&7)+1),l.inputIndex+=1,d=(m>>5)+1,p=m&3;else if((m&32)!==0){d=(m&31)+2,d===2&&(d+=Km(n,l,31)),Lr(n,l.inputIndex,2);const v=n[l.inputIndex]|n[l.inputIndex+1]<<8;l.inputIndex+=2,g=l.outputIndex-((v>>2)+1),p=v&3}else if((m&16)!==0){d=(m&7)+2,d===2&&(d+=Km(n,l,7)),Lr(n,l.inputIndex,2);const v=n[l.inputIndex]|n[l.inputIndex+1]<<8;if(l.inputIndex+=2,g=l.outputIndex-(((m&8)<<11)+(v>>2)),p=v&3,g===l.outputIndex)break;g-=16384}else if(c===0){let v=m+3;v===3&&(v+=Km(n,l,15)),dd(n,l,r,v),c=4;continue}else c!==4?(Lr(n,l.inputIndex,1),p=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+1),l.inputIndex+=1,d=2):(Lr(n,l.inputIndex,1),p=m&3,g=l.outputIndex-((m>>2)+(n[l.inputIndex]<<2)+2049),l.inputIndex+=1,d=3);if(g<0||l.outputIndex+d+p>r.length)throw new Error("Invalid LZO1X block: lookbehind overrun.");l.outputIndex=wC(r,l.outputIndex,g,d),c=p,dd(n,l,r,p)}if(d!==3||l.inputIndex!==n.length||l.outputIndex!==r.length)throw new Error("Invalid LZO1X block: incomplete output.");return r}const wy=16,Sy=8,SC=24*1024*1024,ub=new Uint8Array(new Uint32Array([16909060]).buffer)[0]===4,Mh=new Uint32Array(65536);for(let n=0;n<Mh.length;n+=1){const a=Math.round((n>>11&31)*255/31),r=Math.round((n>>5&63)*255/63),l=Math.round((n&31)*255/31);Mh[n]=ub?(a|r<<8|l<<16|4278190080)>>>0:(a<<24|r<<16|l<<8|255)>>>0}function Rr(n,a){return n[a]|n[a+1]<<8}function CC(n,a){const r=Number(a);if(!Number.isSafeInteger(r)||r<wy||r>SC)throw new Error(`Invalid Mode 5 packet length: ${a}.`);const l=n instanceof Uint8Array?n:new Uint8Array(n),c=cb(l,r);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 d=(c[5]&1)!==0,m=Rr(c,6),p=Rr(c,8),g=Rr(c,10),v=Rr(c,12);if(m<=0||p<=0||m>3840||p>2160)throw new Error(`Invalid Mode 5 frame size: ${m}x${p}.`);if(g<=0||g>256||v>8192)throw new Error(`Invalid Mode 5 tile header: ${g}/${v}.`);const w=[];let x=wy;for(let b=0;b<v;b+=1){if(x+Sy>c.length)throw new Error("Mode 5 tile header is truncated.");const C=Rr(c,x),j=Rr(c,x+2),A=Rr(c,x+4),N=Rr(c,x+6);x+=Sy;const k=A*N*2;if(A<=0||N<=0||A>g||N>g||C+A>m||j+N>p||x+k>c.length)throw new Error(`Invalid Mode 5 tile ${b}.`);w.push({x:C,y:j,width:A,height:N,pixels:c.subarray(x,x+k)}),x+=k}if(x!==c.length)throw new Error(`Mode 5 packet has ${c.length-x} trailing bytes.`);return{keyFrame:d,width:m,height:p,tileSize:g,tiles:w}}function jC(n,a,r,l){if(!(n instanceof Uint8ClampedArray)||n.length!==a*r*4||l.width!==a||l.height!==r)throw new Error("Mode 5 canvas state does not match the packet dimensions.");let c=a,d=r,m=0,p=0;const g=new Uint32Array(n.buffer,n.byteOffset,n.byteLength>>>2);for(const v of l.tiles){const w=ub&&(v.pixels.byteOffset&1)===0?new Uint16Array(v.pixels.buffer,v.pixels.byteOffset,v.pixels.byteLength>>>1):null;let x=0;for(let b=0;b<v.height;b+=1){let C=(v.y+b)*a+v.x;for(let j=0;j<v.width;j+=1){const A=x<<1,N=w?w[x]:v.pixels[A]|v.pixels[A+1]<<8;g[C]=Mh[N],x+=1,C+=1}}c=Math.min(c,v.x),d=Math.min(d,v.y),m=Math.max(m,v.x+v.width),p=Math.max(p,v.y+v.height)}return l.tiles.length>0?{x:c,y:d,width:m-c,height:p-d}:null}const Da=new WeakMap,Uc=new WeakMap,Th=new WeakMap,qc=new Set,Nl=new Set,$d=new WeakMap,Eh=new WeakMap,Rh=new WeakMap,Ud=new WeakMap,db=4,kC=2,AC=2,NC=2,MC=18,TC=40,EC=0,RC=250,fb=80,Cy=5,DC=150,LC=24,_C=180,zC=1200,IC=18,OC=.65,HC=2e3,BC=500,Jh=250,FC=globalThis.LIVEDESK_ENABLE_CANVAS_VISUAL_SAMPLING===!0;let qd=!1;function PC(){return typeof navigator>"u"?!1:/mac/i.test(`${navigator.platform||""} ${navigator.userAgent||""}`)}function $C(){const n=Math.max(1,Number(navigator.hardwareConcurrency||8));return Math.max(4,Math.min(16,Math.round(n/2)))}let Ll={h264DecodeAcceleration:"prefer-hardware",h264HardwareDecoderBudget:$C()};function UC(n){n.h264DecodeAcceleration&&(Ll={...Ll,h264DecodeAcceleration:n.h264DecodeAcceleration}),Number.isFinite(Number(n.h264HardwareDecoderBudget))&&(Ll.h264HardwareDecoderBudget=Math.max(1,Math.min(64,Math.round(Number(n.h264HardwareDecoderBudget)))))}function mb(n,a=Ll.h264DecodeAcceleration){const r=$d.get(n);return r?.requested===a?(r.actual!=="prefer-hardware"&&Nl.delete(n),r.actual):(r&&$d.delete(n),a!=="prefer-hardware"?(Nl.delete(n),a):Nl.has(n)?"prefer-hardware":Nl.size<Ll.h264HardwareDecoderBudget?(Nl.add(n),"prefer-hardware"):"prefer-software")}function tf(n,a){return a!=="prefer-hardware"?!1:($d.set(n,{requested:a,actual:"prefer-software"}),Nl.delete(n),!0)}function qC(n,a,r,l=64){try{let c=Eh.get(n);c||(c={canvas:document.createElement("canvas"),lastHash:"",initialized:!1},Eh.set(n,c));const d=Math.max(8,Math.min(64,Math.round(l))),m=Math.max(1,Math.round(d*Math.max(1,r)/Math.max(1,a)));(c.canvas.width!==d||c.canvas.height!==m)&&(c.canvas.width=d,c.canvas.height=m);const p=c.canvas.getContext("2d",{willReadFrequently:!0});if(!p)return{visualHash:"",visualChanged:!0};p.drawImage(n,0,0,Math.max(1,a),Math.max(1,r),0,0,d,m);const g=p.getImageData(0,0,d,m).data;let v=2166136261;for(let b=0;b<g.length;b+=4)v^=g[b],v=Math.imul(v,16777619),v^=g[b+1],v=Math.imul(v,16777619),v^=g[b+2],v=Math.imul(v,16777619);const w=(v>>>0).toString(16).padStart(8,"0"),x=!c.initialized||w!==c.lastHash;return c.initialized=!0,c.lastHash=w,{visualHash:w,visualChanged:x}}catch{return{visualHash:"",visualChanged:!0}}}function Dh(n,a,r,l=Jh,c=64,d){if(!FC&&d)return hb(n,d);let m=Rh.get(n);m||(m={lastHash:"",initialized:!1,lastCanvasSampleAt:0},Rh.set(n,m));const p=performance.now();if(m.initialized&&l>0&&p-m.lastCanvasSampleAt<l)return{visualHash:m.lastHash,visualChanged:!1};const g=qC(n,a,r,c);return m.initialized=!0,m.lastHash=g.visualHash,m.lastCanvasSampleAt=p,g}function hb(n,a){let r=Ud.get(n);r||(r={lastHash:"",initialized:!1},Ud.set(n,r));const l=String(a.contentHash||""),c=!r.initialized||!l||l!==r.lastHash;return r.initialized=!0,r.lastHash=l,{visualHash:l,visualChanged:c}}function pb(n,a){const r=Th.get(n);if(r)return r;const l=n.getContext("2d",{alpha:!1,desynchronized:a==="interactive"});if(l){const c=l.getContextAttributes?.(),d={context:l,presentation:c?.desynchronized?"desync":"sync"};return Th.set(n,d),d}return null}function GC(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.compression||"").toLowerCase(),l=String(n.mimeType||"").toLowerCase();return a==="mode2-lzo"||r==="lzo1x"||l==="application/vnd.livedesk.lzo-rgb565"||a==="mode2-lz4"||String(n.compression||"").toLowerCase()==="lz4"||l==="application/vnd.livedesk.lz4-raw"}function VC(n){return String(n.frameMode||n.mode||"").toLowerCase()==="mode3-h264-hw"||String(n.codec||"").toLowerCase()==="h264"||String(n.mimeType||"").toLowerCase()==="video/h264"}function WC(n){const a=String(n.frameMode||n.mode||"").toLowerCase(),r=String(n.mimeType||"").toLowerCase();return a==="mode5-lzo-delta"||r==="application/vnd.livedesk.lzo-rgb565-delta"}function jy(n,a,r){let l=r,c=a;if(l===15){let d=255;for(;d===255;){if(c>=n.length)throw new Error("Invalid LZ4 block: length overrun.");d=n[c],c+=1,l+=d}}return{length:l,cursor:c}}function YC(n,a){const r=new Uint8Array(a);let l=0,c=0;for(;l<n.length;){const d=n[l];l+=1;const m=jy(n,l,d>>4);l=m.cursor;const p=m.length;if(l+p>n.length||c+p>r.length)throw new Error("Invalid LZ4 block: literal overrun.");if(r.set(n.subarray(l,l+p),c),l+=p,c+=p,l>=n.length)break;if(l+2>n.length)throw new Error("Invalid LZ4 block: missing offset.");const g=n[l]|n[l+1]<<8;if(l+=2,g<=0||g>c)throw new Error("Invalid LZ4 block: bad match offset.");const v=jy(n,l,d&15);l=v.cursor;const w=v.length+4;if(c+w>r.length)throw new Error("Invalid LZ4 block: match overrun.");let x=c-g;for(let b=0;b<w;b+=1)r[c]=r[x],c+=1,x+=1}if(c!==r.length)throw new Error("Invalid LZ4 block: incomplete output.");return r}function KC(n){const a=Math.max(1,Math.floor(n.width||0)),r=Math.max(1,Math.floor(n.height||0)),l=String(n.compression||"").toLowerCase(),c=String(n.pixelFormat||n.codec||"").toLowerCase();if(l==="lzo1x"||String(n.frameMode||n.mode||"").toLowerCase()==="mode2-lzo"||String(n.mimeType||"").toLowerCase()==="application/vnd.livedesk.lzo-rgb565"){const w=Math.max(1,Math.floor(n.bytesPerPixel||2)),x=a*r*2,b=Math.floor(n.uncompressedByteLength||x);if(w!==2||b!==x)throw new Error(`Invalid mode2 RGB565 frame size: ${b} for ${a}x${r}.`);if(c&&c!=="rgb565le"&&c!=="rgb565")throw new Error(`Unsupported mode2 pixel format: ${c}`);const C=cb(n.payload,x),j=new Uint8ClampedArray(a*r*4);for(let A=0,N=0;A<C.length;A+=2,N+=4){const k=C[A]|C[A+1]<<8,T=k>>11&31,R=k>>5&63,U=k&31;j[N]=T<<3|T>>2,j[N+1]=R<<2|R>>4,j[N+2]=U<<3|U>>2,j[N+3]=255}return new ImageData(j,a,r)}const m=Math.max(1,Math.floor(n.bytesPerPixel||4)),p=Math.max(a*r*m,Math.floor(n.uncompressedByteLength||0)),g=YC(n.payload,p);if(m!==4)throw new Error(`Unsupported mode2 pixel size: ${m}`);const v=new Uint8ClampedArray(a*r*4);if(c==="rgba32"||c==="rgba")v.set(g.subarray(0,v.length));else for(let w=0,x=0;x<v.length;w+=4,x+=4)v[x]=g[w+2],v[x+1]=g[w+1],v[x+2]=g[w],v[x+3]=g[w+3];return new ImageData(v,a,r)}function ky(n,a="smooth"){const r=window.VideoDecoder;if(!r||!window.EncodedVideoChunk)throw new Error("WebCodecs H.264 decode is not supported in this browser.");const l=Da.get(n);if(l&&l.decoder.state!=="closed"&&l.latencyMode===a)return l;l&&Rs(n);let c;return c={decoder:new r({output:m=>{if(Da.get(n)!==c){m.close();return}const p=Number(m.timestamp||0);c.outputSerial+=1;let g=c.pendingFrames.get(p);if(g)c.pendingFrames.delete(p);else if(c.pendingFrames.size>0){const j=c.pendingFrames.entries().next().value;j&&(c.pendingFrames.delete(j[0]),g=j[1],c.timestampFallbacks+=1)}const v=m.displayWidth||m.codedWidth||n.width||960,w=m.displayHeight||m.codedHeight||n.height||540,x=Number(g?.frame.durationUs||0),b=Number(m.duration||0),C=Math.max(16,Math.min(250,(x>0?x:b||83333)/1e3));for(c.targetPaintIntervalMs=C,c.decodedFrames.push({videoFrame:m,pending:g,decodedAt:performance.now(),width:v,height:w,durationMs:C}),c.lastOutputAt=performance.now();c.decodedFrames.length>tp(c);)Gd(c,c.decodedFrames.shift());gb(c),c.renderTimer!==null&&c.renderScheduledAt>0&&performance.now()-c.renderScheduledAt>BC&&(typeof document>"u"||document.visibilityState==="visible")&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),c.renderTimer!==null&&c.decodedFrames.length>=db&&(window.cancelAnimationFrame(c.renderTimer),c.renderTimer=null,c.renderScheduledAt=0),Vd(n,c)},error:()=>{Da.get(n)===c&&(tf(n,c.hardwareAcceleration),ep(c),qc.delete(n),Da.delete(n))}}),configured:!1,configKey:"",codec:"",hardwareAcceleration:mb(n),latencyMode:a,keyFrameSeen:!1,droppedForLatency:0,pendingFrames:new Map,decodedFrames:[],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,lastInputFrameSeq:void 0,targetPaintIntervalMs:1e3/12,nextChunkTimestampUs:0,healthSampleStartedAt:performance.now(),healthInputSerial:0,healthOutputSerial:0},Da.set(n,c),qc.add(n),c}function ep(n){n.renderTimer!==null&&(window.cancelAnimationFrame(n.renderTimer),n.renderTimer=null),n.renderScheduledAt=0,n.flushTimer!==null&&(window.clearTimeout(n.flushTimer),n.flushTimer=null),n.flushInFlight=!1;for(const a of n.decodedFrames)a.videoFrame.close();n.decodedFrames=[],n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0}function Gd(n,a){a&&(a.videoFrame.close(),n.droppedForLatency+=1)}function tp(n){return n.latencyMode==="interactive"?AC:String(n.decodedFrames[0]?.pending?.frame.frameMode||n.decodedFrames[0]?.pending?.frame.mode||"").toLowerCase()==="mode4-h264-atlas"?kC:db}function gb(n,a=performance.now()){const r=tp(n);for(;n.decodedFrames.length>r;)Gd(n,n.decodedFrames.shift());const l=n.latencyMode==="interactive"?fb:RC;let c=n.decodedFrames[0];for(;n.decodedFrames.length>1&&c?.pending&&a-c.pending.queuedAt>l;)Gd(n,n.decodedFrames.shift()),c=n.decodedFrames[0]}function vb(n,a){if(a.hardwareAcceleration!=="prefer-hardware"||a.flushTimer!==null||a.flushInFlight)return;const r=a.latencyMode==="interactive"?LC:DC,l=a.latencyMode==="interactive";a.flushTimer=window.setTimeout(async()=>{a.flushTimer=null;const c=performance.now();for(const[p,g]of a.pendingFrames.entries())c-g.queuedAt>HC&&a.pendingFrames.delete(p);if(Da.get(n)!==a||a.decoder.state!=="configured"||a.pendingFrames.size===0||a.inputSerial<=a.lastFlushInputSerial||!l&&a.lastOutputAt>0&&c-a.lastOutputAt<r)return;const d=a.inputSerial,m=performance.now();a.flushInFlight=!0,a.flushCount+=1;try{await a.decoder.flush(),a.lastFlushInputSerial=Math.max(a.lastFlushInputSerial,d)}catch{Da.get(n)===a&&_d(a)}finally{a.flushInFlight=!1;const p=performance.now()-m;if(l&&p>=_C&&a.hardwareAcceleration==="prefer-hardware"){qd=!0,tf(n,a.hardwareAcceleration),Rs(n);return}Da.get(n)===a&&a.inputSerial>d&&a.pendingFrames.size>0&&(l||performance.now()-a.lastOutputAt>=r)&&vb(n,a)}},r)}function Ay(n,a,r){const l=performance.now();try{(n.width!==r.width||n.height!==r.height)&&(n.width=r.width,n.height=r.height);const c=pb(n,a.latencyMode);if(c?.context.drawImage(r.videoFrame,0,0,r.width,r.height),r.pending){const d=performance.now(),p=a.latencyMode==="interactive"?hb(n,r.pending.frame):Dh(n,r.width,r.height,Jh,64,r.pending.frame);try{a.onPaint?.(r.pending.frame,{deviceId:r.pending.frame.deviceId,frameSeq:r.pending.frame.frameSeq,mode:r.pending.frame.frameMode||r.pending.frame.mode||r.pending.frame.codec||r.pending.frame.mimeType,width:r.width,height:r.height,byteLength:r.pending.frame.byteLength,queuedForMs:Math.max(0,l-r.pending.queuedAt),decodedForMs:Math.max(0,r.decodedAt-r.pending.queuedAt),scheduledForMs:Math.max(0,l-r.decodedAt),drawMs:Math.max(0,d-l),queueSize:r.pending.queueSize,renderQueueSize:a.decodedFrames.length,droppedForLatency:a.droppedForLatency,h264DecodeAcceleration:a.hardwareAcceleration,decoderLabel:a.hardwareAcceleration,decoderFlushCount:a.flushCount,decoderTimestampFallbacks:a.timestampFallbacks,decoderInputCount:a.inputSerial,decoderOutputCount:a.outputSerial,targetPaintIntervalMs:a.targetPaintIntervalMs,canvasPresentation:c?.presentation||"sync",interactiveBufferWaitCount:a.interactiveBufferWaitCount,interactiveBufferWaitMs:a.interactiveBufferWaitMs,interactiveQueueDrainCount:a.interactiveQueueDrainCount,visualHash:p.visualHash,visualChanged:p.visualChanged,paintedAt:d})}catch{}}a.lastPaintAt=performance.now()}finally{r.videoFrame.close()}}function Vd(n,a){if(a.renderTimer!==null||a.decodedFrames.length===0)return;const r=Math.max(16,Math.min(250,a.targetPaintIntervalMs||1e3/12)),l=()=>{if(a.renderTimer=null,a.renderScheduledAt=0,a.decodedFrames.length===0)return;const c=performance.now();if(gb(a,c),a.decodedFrames.length===0)return;if(a.latencyMode==="interactive"){const g=a.targetPaintIntervalMs<=TC,v=a.targetPaintIntervalMs<=20;if(v&&!a.interactiveBufferPrimed){a.interactiveBufferStartedAt<=0&&(a.interactiveBufferStartedAt=c,a.interactiveBufferWaitCount+=1);const A=a.decodedFrames.length>=NC,N=c-a.interactiveBufferStartedAt>=MC;if(!A&&!N){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}a.interactiveBufferWaitMs+=Math.max(0,c-a.interactiveBufferStartedAt),a.interactiveBufferPrimed=!0}else v||(a.interactiveBufferPrimed=!0);const w=a.decodedFrames[0],x=w?.pending?Math.max(0,c-w.pending.queuedAt):0,b=a.lastPaintAt>0?a.lastPaintAt+r:c;if(!(!g||c+Cy>=b||x>=fb)){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const j=a.decodedFrames.shift();if(j)try{Ay(n,a,j)}catch{}a.decodedFrames.length===0&&(a.interactiveQueueDrainCount+=1,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0),Vd(n,a);return}const d=a.lastPaintAt>0?a.lastPaintAt+r:c+EC;if(!(c+Cy>=d||a.decodedFrames.length>=Math.max(1,tp(a)-1))){a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l);return}const p=a.decodedFrames.shift();if(p)try{Ay(n,a,p)}catch{}Vd(n,a)};a.renderScheduledAt=performance.now(),a.renderTimer=window.requestAnimationFrame(l)}function yb(n,a){if(Da.get(n)!==a||a.decoder.state==="closed")return!1;for(a.renderTimer!==null&&(window.cancelAnimationFrame(a.renderTimer),a.renderTimer=null),a.renderScheduledAt=0;a.decodedFrames.length>1;)Gd(a,a.decodedFrames.shift());return a.lastPaintAt=0,a.interactiveBufferPrimed=!1,a.interactiveBufferStartedAt=0,Vd(n,a),!0}function Qm(){if(!(typeof document>"u"||document.visibilityState!=="visible"))for(const n of qc){const a=Da.get(n);if(!a||a.decoder.state==="closed"){qc.delete(n);continue}yb(n,a)}}typeof document<"u"&&typeof window<"u"&&(document.addEventListener("visibilitychange",Qm),window.addEventListener("focus",Qm),window.addEventListener("pageshow",Qm));function Rs(n){Nl.delete(n),qc.delete(n),Ud.delete(n);const a=Da.get(n);if(a){Da.delete(n);try{ep(a),a.decoder.state!=="closed"&&a.decoder.close()}catch{}}}function Ac(n){n&&($d.delete(n),Th.delete(n),Rh.delete(n),Eh.delete(n),Ud.delete(n),Uc.delete(n),Rs(n))}function _d(n,a=1){try{n.decoder.state!=="closed"&&n.decoder.reset()}catch{}n.configured=!1,n.configKey="",n.keyFrameSeen=!1,n.pendingFrames.clear(),ep(n),n.lastPaintAt=0,n.lastOutputAt=0,n.lastInputAt=0,n.interactiveBufferPrimed=!1,n.interactiveBufferStartedAt=0,n.lastInputFrameSeq=void 0,n.nextChunkTimestampUs=0,n.healthSampleStartedAt=performance.now(),n.healthInputSerial=n.inputSerial,n.healthOutputSerial=n.outputSerial,n.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a)))}function fd(n,a,r,l){n.decoder.configure(a),n.configured=!0,n.configKey=r,n.codec=a.codec,n.hardwareAcceleration=l,n.keyFrameSeen=!1,n.nextChunkTimestampUs=0,n.lastInputFrameSeq=void 0}function QC(n,a){if(a.latencyMode!=="interactive"||a.hardwareAcceleration!=="prefer-hardware")return!1;const r=performance.now();if(r-a.healthSampleStartedAt<zC)return!1;const l=a.inputSerial-a.healthInputSerial,c=a.outputSerial-a.healthOutputSerial;return a.healthSampleStartedAt=r,a.healthInputSerial=a.inputSerial,a.healthOutputSerial=a.outputSerial,l<IC||c/Math.max(1,l)>=OC?!1:(qd=!0,tf(n,a.hardwareAcceleration),Rs(n),!0)}function Xm(n,a=1){if(!n)return!1;const r=Da.get(n);return r?(r.droppedForLatency+=Math.max(1,Math.min(1e4,Math.floor(a))),Rs(n),!0):!1}function XC(n){if(!n)return!1;const a=Da.get(n);return a?yb(n,a):!1}function ZC(n,a,r,l="interactive"){Rs(n);const c=performance.now(),d=CC(a.payload,a.uncompressedByteLength||0),m=String(a.streamId||"mode5");let p=Uc.get(n);if(!p||p.streamId!==m||p.width!==d.width||p.height!==d.height){const A=new Uint8ClampedArray(d.width*d.height*4);for(let N=3;N<A.length;N+=4)A[N]=255;p={streamId:m,width:d.width,height:d.height,rgba:A,imageData:new ImageData(A,d.width,d.height),keyFrameSeen:!1,inputSerial:0,outputSerial:0},Uc.set(n,p)}if(!p)throw new Error("Mode 5 canvas state could not be initialized.");p.inputSerial+=1;const v=Number(a.streamFrameSeq||0);if(v>0&&(p.lastStreamFrameSeq=v),!d.keyFrame&&!p.keyFrameSeen)return;d.keyFrame&&(p.keyFrameSeen=!0);const w=jC(p.rgba,p.width,p.height,d),x=performance.now();(n.width!==p.width||n.height!==p.height)&&(n.width=p.width,n.height=p.height);const b=pb(n,l),C=performance.now();w&&b?.context.putImageData(p.imageData,0,0,w.x,w.y,w.width,w.height);const j=performance.now();p.outputSerial+=1,r?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.mimeType,width:p.width,height:p.height,byteLength:a.byteLength,queuedForMs:Math.max(0,j-c),decodedForMs:Math.max(0,x-c),scheduledForMs:0,drawMs:Math.max(0,j-C),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:"prefer-software",decoderLabel:"lzo-rgb565-delta",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:p.inputSerial,decoderOutputCount:p.outputSerial,targetPaintIntervalMs:Math.max(1,Number(a.durationUs||0)/1e3||1e3/30),canvasPresentation:b?.presentation||"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:String(a.contentHash||""),visualChanged:Number(a.deltaVisualTileCount||0)>0,paintedAt:j})}const Zm=[{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 Ny(n,a){for(let r=Math.max(0,a);r+3<n.length;r+=1)if(!(n[r]!==0||n[r+1]!==0)){if(n[r+2]===1)return{index:r,length:3};if(n[r+2]===0&&n[r+3]===1)return{index:r,length:4}}return null}function JC(n){let a=0;for(;a<n.length;){const r=Ny(n,a);if(!r)break;const l=r.index+r.length,c=Ny(n,l),d=c?.index??n.length;if(l<d&&(n[l]&31)===7){const m=[];let p=0;for(let g=l+1;g<d;g+=1){const v=n[g];if(p>=2&&v===3){p=0;continue}m.push(v),p=v===0?p+1:0}if(m.length>=3)return`avc1.${m.slice(0,3).map(g=>g.toString(16).toUpperCase().padStart(2,"0")).join("")}`}a=c?c.index:n.length}return""}function ej(n,a,r,l,c=""){const d=Math.ceil(n/16)*Math.ceil(a/16),m=r>0?1e6/r:30,p=d*m,g=Zm.find(v=>d<=v.maxFrameSize&&p<=v.maxMacroblocksPerSecond)||Zm[Zm.length-1];return JC(l)||c||`avc1.42E0${g.code.toString(16).toUpperCase().padStart(2,"0")}`}function tj(n,a,r,l,c="smooth"){Uc.delete(n);const d=String(a.h264Format||"").toLowerCase()==="avc"?"avc":"annexb",m=Math.max(1,Math.floor(a.width||960)),p=Math.max(1,Math.floor(a.height||540)),g=Math.max(1,Math.floor(a.durationUs||1e6/12));let v=ky(n,c);const w=ej(m,p,g,a.payload,v.codec),x=String(a.frameMode||a.mode||"").toLowerCase(),b=c==="interactive"&&l==="prefer-hardware"&&PC(),j=x==="mode4-h264-atlas"?"prefer-software":mb(n,c==="interactive"&&(qd||b)?"prefer-software":l),A=[a.streamId||"",a.commandId||"",m,p,w,d,j,c].join("|");v.onPaint=r,v.configured&&v.decoder.state!=="configured"&&(v.configured=!1,v.configKey=""),v.configured&&v.configKey!==A&&(Rs(n),v=ky(n,c),v.onPaint=r);const N={codec:w,codedWidth:m,codedHeight:p,hardwareAcceleration:j,optimizeForLatency:!0,avc:{format:d}};v.configured||fd(v,N,A,j);const k=a.isKeyFrame===!0||String(a.chunkType||"").toLowerCase()==="key";Number(a.frameSeq||0);const T=Number(a.streamFrameSeq||0);if(T>0&&v.lastInputFrameSeq!==void 0){if(T<=v.lastInputFrameSeq){if(!k||T===v.lastInputFrameSeq)return;_d(v,v.lastInputFrameSeq-T+1),fd(v,N,A,j)}if(T>v.lastInputFrameSeq+1){if(_d(v,T-v.lastInputFrameSeq-1),!k)return;fd(v,N,A,j)}}if(T>0&&(v.lastInputFrameSeq=T),!k&&!v.keyFrameSeen)return;k&&(v.keyFrameSeen=!0);const R=Number(v.decoder.decodeQueueSize||0);if(R>8){if(v.latencyMode==="interactive"&&v.hardwareAcceleration==="prefer-hardware"){qd=!0,tf(n,v.hardwareAcceleration),Rs(n);return}if(_d(v),!k)return;fd(v,N,A,j),v.keyFrameSeen=!0}const U=v.nextChunkTimestampUs;v.nextChunkTimestampUs+=g,v.pendingFrames.set(U,{frame:a,queuedAt:performance.now(),queueSize:R}),v.inputSerial+=1,v.lastInputAt=performance.now();const O=new EncodedVideoChunk({type:k?"key":"delta",timestamp:U,duration:g,data:a.payload});try{v.decoder.decode(O)}catch(Y){throw Rs(n),Y}vb(n,v),QC(n,v)}async function Jm(n,a,r,l,c,d="smooth"){if(WC(a)){r()||ZC(n,a,l,d);return}if(VC(a)){r()||tj(n,a,l,c,d);return}if(Uc.delete(n),GC(a)){Rs(n);const x=KC(a);if(r())return;(n.width!==x.width||n.height!==x.height)&&(n.width=x.width,n.height=x.height);const b=n.getContext("2d"),C=performance.now();b?.putImageData(x,0,0);const j=performance.now(),A=Dh(n,x.width,x.height,Jh,64,a);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:x.width,height:x.height,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,j-C),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ll.h264DecodeAcceleration,decoderLabel:"lzo-rgb565",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:A.visualHash,visualChanged:A.visualChanged,paintedAt:j});return}Rs(n);const m=new Blob([a.payload],{type:a.mimeType}),p=await createImageBitmap(m);if(r()){p.close();return}const g=a.width||p.width||960,v=a.height||p.height||540;(n.width!==g||n.height!==v)&&(n.width=g,n.height=v);const w=n.getContext("2d");if(w){const x=performance.now();w.clearRect(0,0,g,v),w.drawImage(p,0,0,g,v);const b=performance.now(),C=Dh(n,g,v);l?.(a,{deviceId:a.deviceId,frameSeq:a.frameSeq,mode:a.frameMode||a.mode||a.codec||a.mimeType,width:g,height:v,byteLength:a.byteLength,queuedForMs:0,decodedForMs:0,scheduledForMs:0,drawMs:Math.max(0,b-x),queueSize:0,renderQueueSize:0,droppedForLatency:0,h264DecodeAcceleration:Ll.h264DecodeAcceleration,decoderLabel:"image",decoderFlushCount:0,decoderTimestampFallbacks:0,decoderInputCount:0,decoderOutputCount:0,targetPaintIntervalMs:0,canvasPresentation:"sync",interactiveBufferWaitCount:0,interactiveBufferWaitMs:0,interactiveQueueDrainCount:0,visualHash:C.visualHash,visualChanged:C.visualChanged,paintedAt:b})}p.close()}const My="livedesk_remote_host_targets",nj="livedesk_entitlements",np=new TextDecoder;function aj(n){const r=(Array.isArray(n)?n:[n||Cn]).map(l=>Hr(l||Cn));return[...new Set(r.filter(Boolean))]}function sj(){const[n,a]=u.useState(null),[r,l]=u.useState(!0);return u.useEffect(()=>{let c=!0;const d=window.liveDesk?.auth?.onComplete?.(p=>{p.ok&&p.session&&pt.auth.setSession(p.session)});(window.liveDesk?.auth?.getSession?.()||pt.auth.getSession()).then(p=>{c&&(a(nb(p)),l(!1))});const{data:{subscription:m}}=pt.auth.onAuthStateChange((p,g)=>{a(g),l(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{c=!1,d?.(),m.unsubscribe()}},[]),{session:n,loading:r}}function ij(n,a=!0){const[r,l]=u.useState(null),[c,d]=u.useState([]),[m,p]=u.useState(""),[g,v]=u.useState(""),[w,x]=u.useState(0),b=u.useRef(new Map),C=Array.isArray(n)?n.join(`
|
|
12
12
|
`):String(n||""),j=u.useMemo(()=>aj(n),[C]),A=u.useMemo(()=>j.find(T=>Ic(T)==="loopback")||j[0]||Cn,[j]),N=u.useCallback(async()=>{if(!a){l(null),d([]),v(""),p("");return}let T=null;const R=Date.now(),U=j.filter(O=>(b.current.get(O)||0)<=R);if(U.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const O of U)try{const[Y,_]=await Promise.all([Ge("/api/remote/status",void 0,O),Ge("/api/remote/devices",void 0,O)]);if(!Array.isArray(_.devices))throw new Error("Invalid Hub devices response.");b.current.delete(O),l(Y),d(_.devices),v(O),p("");return}catch(Y){T=Y,b.current.set(O,Date.now()+1e4)}throw v(""),T||new Error("No LiveDesk Hub endpoint is reachable.")},[a,j]),k=u.useCallback(()=>{b.current.clear(),N().catch(T=>{p(T instanceof Error?T.message:String(T))}),x(T=>T+1)},[N]);return u.useEffect(()=>{if(!a){l(null),d([]),v(""),p("");return}let T=!0;const R=async()=>{try{await N()}catch(O){T&&p(O instanceof Error?O.message:String(O))}};R();const U=window.setInterval(R,2500);return()=>{T=!1,window.clearInterval(U)}},[a,N,w]),{status:r,devices:c,error:m,refresh:k,hubBaseUrl:g||A,hubCandidates:j}}function rj(n){const[a,r]=u.useState(null),[l,c]=u.useState(""),d=n?.user?.id||"",m=u.useCallback(async()=>{if(!d){r(null);return}const{data:p,error:g}=await pt.from(My).select("*").eq("user_id",d).maybeSingle();if(g){c(g.message);return}r(p),c("")},[d]);return u.useEffect(()=>{m()},[m]),u.useEffect(()=>{if(!d)return;const p=pt.channel(`livedesk-remote-host-targets-${d.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:My,filter:`user_id=eq.${d}`},g=>r(g.new)).subscribe();return()=>{pt.removeChannel(p)}},[d]),{target:a,error:l,refresh:m}}function lj(n){const[a,r]=u.useState(null),[l,c]=u.useState(!1),[d,m]=u.useState(""),p=n?.user?.id||"",g=u.useCallback(async()=>{if(!p){r(null),m(""),c(!1);return}c(!0);const{data:w,error:x}=await pt.from(nj).select("*").eq("user_id",p).eq("product_key","livedesk").maybeSingle();if(x){m(x.message),c(!1);return}r(w),m(""),c(!1)},[p]);u.useEffect(()=>{g()},[g]);const v=u.useMemo(()=>!a||a.status!=="active"?!1:a.expires_at?new Date(a.expires_at).getTime()>Date.now():!0,[a]);return{entitlement:a,licensed:v,loading:l,error:d,refresh:g}}const Oc={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},oj=2500,cj=3e4,uj=64*1024,dj=6,fj=dj,xb=new Map;function mj(n){return xb.get(n)}const Ty={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function Ey(n){const a=Date.parse(String(n||""));if(!Number.isFinite(a))return 0;const r=Date.now()-a;return r>0&&r<=cj?r:0}function Ry(n,a,r=Cn,l={}){const[c,d]=u.useState(new Map),[m,p]=u.useState("idle"),[g,v]=u.useState(""),[w,x]=u.useState(Oc),b=u.useRef(new Map),C=u.useRef(new Map),j=u.useRef(0),A=u.useRef(new Map),N=u.useRef({enabled:!1,token:"",reason:""}),k=u.useRef(new Set),[T,R]=u.useState(0),U=u.useRef(l.onFrame),O=u.useRef(l.onStreamReady),Y=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),_=u.useMemo(()=>[...n].sort().join(","),[n]),D=Number.isFinite(l.fps)?Number(l.fps):2,ne=Number.isFinite(l.maxWidth)?Number(l.maxWidth):640,G=Number.isFinite(l.maxHeight)?Number(l.maxHeight):360,te=Number.isFinite(l.quality)?Number(l.quality):45,B=String(l.frameMode||l.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",xe=l.streamPurpose==="control"?"control":"wall",se=l.forceRestart===!0,K=String(l.forceRestartToken||"").trim(),I=String(l.restartReason||"").trim();N.current={enabled:se,token:K,reason:I};const Q=u.useMemo(()=>{const ue=Object.entries(l.monitorSelections||{}).filter(([he])=>!!he).sort(([he],[ve])=>he.localeCompare(ve));return JSON.stringify(Object.fromEntries(ue))},[l.monitorSelections]);u.useEffect(()=>{U.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{O.current=l.onStreamReady},[l.onStreamReady]);const q=u.useCallback((ue,he="livedesk-frame-socket-release")=>{ue.disposed=!0;try{ue.socket.readyState===WebSocket.CONNECTING||ue.socket.readyState===WebSocket.OPEN?ue.socket.close(1e3,he):ue.socket.close()}catch{}},[]),V=u.useCallback(()=>{const ue=[...C.current.values()].map(he=>he.socket);if(ue.length===0){p("idle");return}if(ue.some(he=>he.readyState===WebSocket.OPEN)){p("open");return}if(ue.some(he=>he.readyState===WebSocket.CONNECTING)){p("connecting");return}p("closed")},[]),ce=u.useCallback((ue,he,ve,Se)=>{if(he.disposed||he.socket.readyState!==WebSocket.OPEN)return!1;try{return he.socket.send(JSON.stringify({...he.payload,type:"restart-live",deviceIds:[ue],forceRestart:!0,restartReason:ve,restartToken:Se})),!0}catch{return!1}},[]),be=u.useCallback((ue,he)=>{if(!ue||ue.byteLength<5)return;const ve=Date.now(),_e=new DataView(ue).getUint32(0,!1);if(_e<=0||_e+4>ue.byteLength)return;const re=new Uint8Array(ue,4,_e),Z=JSON.parse(np.decode(re));if(Math.max(Ey(Z.receivedAt),Ey(Z.capturedAt))>oj)return;const Le=new Uint8Array(ue,4+_e),ae={deviceId:String(Z.deviceId||""),kind:Z.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||""),commandId:Z.commandId?String(Z.commandId):void 0,sessionId:Z.sessionId?String(Z.sessionId):void 0,captureGeneration:Number(Z.captureGeneration||0)||void 0,streamPurpose:Z.streamPurpose?String(Z.streamPurpose):void 0,width:Number(Z.width||0),height:Number(Z.height||0),sourceWidth:Number(Z.sourceWidth||0)||void 0,sourceHeight:Number(Z.sourceHeight||0)||void 0,mimeType:String(Z.mimeType||"image/jpeg"),mode:Z.mode?String(Z.mode):void 0,frameMode:Z.frameMode?String(Z.frameMode):void 0,frameProfile:Z.frameProfile?String(Z.frameProfile):void 0,encoding:Z.encoding?String(Z.encoding):void 0,codec:Z.codec?String(Z.codec):void 0,compression:Z.compression?String(Z.compression):void 0,pixelFormat:Z.pixelFormat?String(Z.pixelFormat):void 0,bytesPerPixel:Number(Z.bytesPerPixel||0)||0,uncompressedByteLength:Number(Z.uncompressedByteLength||0)||0,h264Format:Z.h264Format?String(Z.h264Format):void 0,isKeyFrame:Z.isKeyFrame===!0,chunkType:Z.chunkType?String(Z.chunkType):void 0,timestampUs:Number(Z.timestampUs||0)||0,durationUs:Number(Z.durationUs||0)||0,sourceGapMs:Number(Z.sourceGapMs||0)||0,agentSendGapMs:Number(Z.agentSendGapMs||0)||0,agentSendDurationMs:Number(Z.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(Z.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(Z.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(Z.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(Z.agentFrameAgeMs||0)||0,droppedByAgent:Number(Z.droppedByAgent||0)||0,hubIngressDropped:Number(Z.hubIngressDropped||0)||0,hubClientDropped:Number(Z.hubClientDropped||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,monitorIndex:Number.isFinite(Number(Z.monitorIndex))?Number(Z.monitorIndex):void 0,monitorCount:Number.isFinite(Number(Z.monitorCount))?Number(Z.monitorCount):void 0,requestedFps:Number(Z.requestedFps||0)||0,effectiveFps:Number(Z.effectiveFps||0)||0,captureAverageMs:Number(Z.captureAverageMs||0)||0,captureP95Ms:Number(Z.captureP95Ms||0)||0,slowFrameCount:Number(Z.slowFrameCount||0)||0,captureHelperRestarts:Number(Z.captureHelperRestarts||0)||0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Number.isFinite(Number(Z.hubPacketEpochMs))?Number(Z.hubPacketEpochMs):void 0,browserReceivedEpochMs:ve,byteLength:Number(Z.byteLength||Le.byteLength),contentHash:Z.contentHash?String(Z.contentHash):void 0,captureMs:Number(Z.captureMs||0)||0,captureStageMs:Number(Z.captureStageMs||0)||0,convertMs:Number(Z.convertMs||0)||0,compressMs:Number(Z.compressMs||0)||0,captureSourceSerial:Number(Z.captureSourceSerial||0)||0,captureSourceSkipped:Number(Z.captureSourceSkipped||0)||0,deltaTileSize:Number(Z.deltaTileSize||0)||0,deltaTileCount:Number(Z.deltaTileCount||0)||0,deltaVisualTileCount:Number(Z.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(Z.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(Z.deltaTotalTiles||0)||0,payload:Le};if(!ae.deviceId)return;const fe={streamId:he.lastFrameStreamId,commandId:he.lastFrameCommandId,order:he.lastFrameOrder},Ae=Number(ae.streamFrameSeq||ae.frameSeq||0),Te=!!fe.commandId&&!!ae.commandId,Be=fe.streamId===ae.streamId&&(!Te||fe.commandId===ae.commandId),Ve=fe.order;if(Be&&Ve>=Ae&&(Ve===Ae||Te))return;he.lastFrameStreamId=ae.streamId,he.lastFrameCommandId=ae.commandId||"",he.lastFrameOrder=Ae;const Je=Y.current;Je.totalFrames+=1,Je.totalBytes+=Le.byteLength,Je.sampleFrames+=1,Je.sampleBytes+=Le.byteLength;const Et=!b.current.has(ae.deviceId);b.current.set(ae.deviceId,ae),Et&&d(new Map(b.current)),U.current?.(ae)},[]);u.useEffect(()=>{const ue=window.setInterval(()=>{const he=performance.now(),ve=Y.current,Se=Math.max(1,he-ve.sampleStartedAt);x({totalFrames:ve.totalFrames,totalBytes:ve.totalBytes,framesPerSecond:ve.sampleFrames*1e3/Se,bytesPerSecond:ve.sampleBytes*1e3/Se,sampleMs:Se,lastUpdatedAt:Date.now()}),d(new Map(b.current)),ve.sampleFrames=0,ve.sampleBytes=0,ve.sampleStartedAt=he},2e3);return()=>{window.clearInterval(ue)}},[]),u.useEffect(()=>{const ue=_?_.split(",").filter(Boolean):[],he=new Set(ue),ve=performance.now();for(const[Se,_e]of C.current.entries())he.has(Se)||(q(_e,"livedesk-device-unsubscribed"),C.current.delete(Se),A.current.delete(Se),b.current.delete(Se));if(ue.length===0){for(const Se of C.current.values())q(Se,"livedesk-no-devices");C.current.clear(),A.current.clear(),b.current=new Map,d(new Map),v(""),Y.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},x(Oc),V();return}Y.current.sampleStartedAt<=0&&(Y.current.sampleStartedAt=ve,x({...Oc,lastUpdatedAt:Date.now()}));for(const Se of ue){const _e=l.monitorSelections?.[Se],re=Number.isFinite(Number(_e))?{[Se]:Number(_e)}:{},Z={type:"subscribe",deviceIds:[Se],autoStartLive:a,fps:D,maxWidth:ne,maxHeight:G,quality:te,mode:B,frameMode:B,streamPurpose:xe,monitorSelections:re},ze=JSON.stringify(Z),Le=C.current.get(Se);if(Le){const Te=Le.socket.readyState===WebSocket.CONNECTING||Le.socket.readyState===WebSocket.OPEN;if(Le.payloadKey===ze&&Te&&!Le.disposed)continue}const ae=Le&&(Le.socket.readyState===WebSocket.CONNECTING||Le.socket.readyState===WebSocket.OPEN)&&!Le.disposed?Le.handoffFrom&&!Le.handoffCompleted?Le.handoffFrom:Le:void 0;Le&&Le!==ae&&q(Le,"livedesk-subscription-superseded");const fe=new WebSocket(ef(`/api/remote/frames/ws?devices=${encodeURIComponent(Se)}`,r));fe.binaryType="arraybuffer";const Ae={socket:fe,payload:Z,payloadKey:ze,generation:j.current+1,disposed:!1,handoffFrom:ae,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1};j.current=Ae.generation,C.current.set(Se,Ae),fe.addEventListener("open",()=>{if(Ae.disposed||C.current.get(Se)!==Ae){q(Ae,"livedesk-stale-frame-socket");return}v("");const Te=N.current,Be=Te.enabled&&(!Te.token||A.current.get(Se)!==Te.token);fe.send(JSON.stringify({...Ae.payload,forceRestart:Be,restartReason:Be?Te.reason:"",restartToken:Be?Te.token:""})),Be&&Te.token&&A.current.set(Se,Te.token);const Ve=Ae.handoffFrom;Ae.handoffFrom=void 0,Ae.handoffCompleted=!0,Ve&&!Ve.disposed&&q(Ve,"livedesk-subscription-replaced"),V()}),fe.addEventListener("message",Te=>{if(Ae.disposed||C.current.get(Se)!==Ae)return;if(typeof Te.data=="string"){try{const Ve=JSON.parse(Te.data);if(Ve?.type==="RemoteFrameSubscriptionError")v(String(Ve.error||"control-stream-start-failed"));else if(Ve?.type==="RemoteFrameLiveAutoStart"){const Et=(Array.isArray(Ve.skipped)?Ve.skipped:[]).find(je=>je?.deviceId===Se);if(Et)v(String(Et.reason||"control-stream-start-failed"));else if(Array.isArray(Ve.started)){const je=Ve.started.find(We=>We?.deviceId===Se);je&&(v(""),je.ready===!0&&je.streamPurpose==="control"&&je.sessionId&&je.commandId&&Number(je.captureGeneration||0)>0&&O.current?.({deviceId:Se,sessionId:String(je.sessionId),streamId:String(je.streamId||""),streamPurpose:"control",commandId:String(je.commandId),captureGeneration:Number(je.captureGeneration),monitorIndex:Number(je.monitorIndex||0)}))}}else Ve?.type==="RemoteFrameStreamReady"&&Ve.deviceId===Se&&Ve.streamPurpose==="control"&&Ve.sessionId&&Ve.commandId&&Number(Ve.captureGeneration||0)>0&&(v(""),O.current?.({deviceId:Se,sessionId:String(Ve.sessionId),streamId:String(Ve.streamId||""),streamPurpose:"control",commandId:String(Ve.commandId),captureGeneration:Number(Ve.captureGeneration),monitorIndex:Number(Ve.monitorIndex||0)}))}catch{}return}const Be=Te.data instanceof ArrayBuffer?Te.data:null;Be&&(v(""),be(Be,Ae))}),fe.addEventListener("error",()=>{Ae.disposed||C.current.get(Se)!==Ae||p("connecting")}),fe.addEventListener("close",()=>{const Te=!Ae.disposed;Ae.disposed=!0;const Be=C.current.get(Se);let Ve=!1;if(Be===Ae){const Je=Ae.handoffFrom;Ae.handoffFrom=void 0,Je&&!Je.disposed&&(Je.socket.readyState===WebSocket.CONNECTING||Je.socket.readyState===WebSocket.OPEN)?(C.current.set(Se,Je),Ve=!0):C.current.delete(Se)}if(V(),Te&&Be===Ae&&!Ve){const Je=window.setTimeout(()=>{k.current.delete(Je),R(Et=>Et+1)},750);k.current.add(Je)}})}V()},[a,q,_,D,B,be,r,G,ne,Q,l.monitorSelections,te,T,xe,V]),u.useEffect(()=>{if(!se||!K)return;const ue=_?_.split(",").filter(Boolean):[];for(const he of ue){if(A.current.get(he)===K)continue;const ve=C.current.get(he);!ve||!ce(he,ve,I,K)||A.current.set(he,K)}},[_,se,K,I,ce]),u.useEffect(()=>()=>{for(const ue of C.current.values())q(ue,"livedesk-hook-unmount");C.current.clear();for(const ue of k.current)window.clearTimeout(ue);k.current.clear()},[q]);const X=u.useCallback((ue,he="browser-stale")=>{const ve=Array.isArray(ue)&&ue.length>0?ue:_.split(",").filter(Boolean);if(ve.length===0)return!1;let Se=!1;for(const _e of ve){const re=C.current.get(_e);!re||re.socket.readyState!==WebSocket.OPEN||(Se=ce(_e,re,he,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Se)}return Se},[_,ce]),$=u.useCallback((ue,he="browser-reconnect")=>{const ve=Array.isArray(ue)&&ue.length>0?ue:_.split(",").filter(Boolean);if(ve.length===0)return!1;let Se=!1;for(const _e of ve){const re=C.current.get(_e);re&&(q(re,`livedesk-${he}`),C.current.delete(_e),A.current.delete(_e),b.current.delete(_e),Se=!0)}return Se&&d(new Map(b.current)),R(_e=>_e+1),V(),!0},[q,_,V]);return{frames:c,state:m,error:g,stats:w,restartLive:X,reconnectLive:$}}function hj(n,a,r=Cn,l={}){const[c,d]=u.useState(null),[m,p]=u.useState(null),[g,v]=u.useState("idle"),[w,x]=u.useState(Oc),b=u.useRef(null),C=u.useRef(l.onFrame),j=u.useRef(null),A=u.useRef(0),N=u.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),k=u.useMemo(()=>[...new Set(n.filter(Boolean))].join(","),[n]),T=u.useMemo(()=>[...new Set((l.captureDeviceIds||n).filter(Boolean))].join(","),[n,l.captureDeviceIds]),R=u.useMemo(()=>JSON.stringify(l.monitorSelections||{}),[l.monitorSelections]),U=u.useMemo(()=>({deviceIds:k.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(l.fps||20),width:Number(l.width||1920),height:Number(l.height||1080),tileWidth:Number(l.tileWidth||320),tileHeight:Number(l.tileHeight||180),monitorSelections:l.monitorSelections||{}}),[T,k,R,l.fps,l.height,l.monitorSelections,l.tileHeight,l.tileWidth,l.width]),O=u.useMemo(()=>JSON.stringify(U),[U]),Y=u.useRef(U);Y.current=U;const _=a&&U.deviceIds.length>0,D=u.useCallback(G=>G.readyState!==WebSocket.OPEN?!1:(G.send(JSON.stringify({type:"configure",...Y.current})),!0),[]);u.useEffect(()=>{C.current=l.onFrame},[l.onFrame]),u.useEffect(()=>{const G=window.setInterval(()=>{const te=N.current,B=performance.now(),xe=Math.max(1,B-te.sampleStartedAt);x({totalFrames:te.totalFrames,totalBytes:te.totalBytes,framesPerSecond:te.sampleFrames*1e3/xe,bytesPerSecond:te.sampleBytes*1e3/xe,sampleMs:xe,lastUpdatedAt:Date.now()});const se=j.current;se&&se.frameSeq!==A.current&&(A.current=se.frameSeq,d(se)),te.sampleFrames=0,te.sampleBytes=0,te.sampleStartedAt=B},1e3);return()=>window.clearInterval(G)},[]),u.useEffect(()=>{if(!_){b.current?.close(),b.current=null,d(null),j.current=null,A.current=0,p(null),v("idle"),x(Oc);return}let G=!1,te=0;const B=()=>{if(G)return;const xe=new WebSocket(ef("/api/remote/atlas/ws",r));xe.binaryType="arraybuffer",b.current=xe,v("connecting"),xe.addEventListener("open",()=>{N.current.sampleStartedAt=performance.now(),v("open"),D(xe)}),xe.addEventListener("message",se=>{if(typeof se.data=="string"){try{const I=JSON.parse(se.data);I?.type==="Mode4AtlasLayout"&&p({layoutVersion:Number(I.layoutVersion||0),width:Number(I.width||1920),height:Number(I.height||1080),columns:Number(I.columns||1),rows:Number(I.rows||1),tiles:Array.isArray(I.tiles)?I.tiles:[]})}catch{}return}const K=se.data instanceof ArrayBuffer?se.data:null;if(!(!K||K.byteLength<5))try{const I=Date.now(),q=new DataView(K).getUint32(0,!1);if(q<=0||q+4>K.byteLength)return;const V=JSON.parse(np.decode(new Uint8Array(K,4,q))),ce=new Uint8Array(K,4+q),be={deviceId:String(V.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(V.frameSeq||0),streamFrameSeq:Number(V.streamFrameSeq||0)||void 0,streamId:String(V.streamId||"mode4-atlas"),commandId:V.commandId?String(V.commandId):void 0,width:Number(V.width||1920),height:Number(V.height||1080),sourceWidth:Number(V.sourceWidth||V.width||1920),sourceHeight:Number(V.sourceHeight||V.height||1080),mimeType:String(V.mimeType||"video/h264"),mode:String(V.mode||"mode4-h264-atlas"),frameMode:String(V.frameMode||"mode4-h264-atlas"),frameProfile:String(V.frameProfile||"mode4-h264-atlas-v1"),encoding:String(V.encoding||"video-atlas"),codec:String(V.codec||"h264"),compression:String(V.compression||"video/h264"),h264Format:String(V.h264Format||"annexb"),isKeyFrame:V.isKeyFrame===!0,chunkType:String(V.chunkType||""),timestampUs:Number(V.timestampUs||0),durationUs:Number(V.durationUs||0),hardwareEncoder:V.hardwareEncoder?String(V.hardwareEncoder):void 0,platformProfile:V.platformProfile?String(V.platformProfile):void 0,capturedAt:String(V.capturedAt||""),receivedAt:String(V.receivedAt||""),hubPacketAt:V.hubPacketAt?String(V.hubPacketAt):void 0,hubPacketEpochMs:Number(V.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:I,byteLength:ce.byteLength,layoutVersion:Number(V.layoutVersion||0),atlasComposeMs:Number(V.atlasComposeMs||0),atlasPoolStarved:Number(V.atlasPoolStarved||0),atlasReadyTiles:Number(V.atlasReadyTiles||0),atlasTileCount:Number(V.atlasTileCount||0),atlasInputRevision:Number(V.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(V.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(V.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(V.atlasSourceMaxAgeMs||0),payload:ce},X=N.current;X.totalFrames+=1,X.totalBytes+=ce.byteLength,X.sampleFrames+=1,X.sampleBytes+=ce.byteLength,j.current=be,A.current===0&&(A.current=be.frameSeq,d(be)),C.current?.(be)}catch{}}),xe.addEventListener("error",()=>v("error")),xe.addEventListener("close",()=>{b.current===xe&&(b.current=null),!G&&(v("closed"),te=window.setTimeout(B,1200))})};return B(),()=>{G=!0,window.clearTimeout(te),b.current?.close(),b.current=null}},[_,r,D]),u.useEffect(()=>{if(!_)return;const G=b.current;G&&D(G)},[O,_,D]);const ne=u.useCallback(()=>{const G=b.current;return G?D(G):!1},[D]);return{frame:c,layout:m,state:g,stats:w,refreshInputs:ne}}function pj(n,a=Cn){const r=u.useRef(null),l=u.useRef(0),c=u.useRef(0),d=u.useRef(new Map),[m,p]=u.useState("idle"),[g,v]=u.useState(""),[w,x]=u.useState(Ty),b=u.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});u.useEffect(()=>{if(!n){r.current?.close(),r.current=null,c.current=0,p("idle"),v(""),x(Ty);return}let j=!1,A=0;const N=()=>{if(j)return;const k=new WebSocket(ef("/api/remote/input/ws",a));r.current=k,b.current.sampleStartedAt=performance.now(),p("connecting"),v(""),k.addEventListener("open",()=>{j||r.current!==k||(v(""),p("open"))}),k.addEventListener("message",T=>{if(!(j||r.current!==k||typeof T.data!="string"))try{const R=JSON.parse(T.data);if(R?.type==="RemoteInputError"){v(String(R.error||R.result?.error||"Remote input failed.")),p("error");return}if(R?.type!=="RemoteInputApplied")return;const U=Number(R.inputSeq||0),O=d.current.get(U);O!==void 0&&(b.current.lastRoundTripMs=Math.max(0,performance.now()-O),d.current.delete(U)),b.current.lastInputSeq=U,b.current.lastAgentApplyMs=Math.max(0,Number(R.agentApplyMs||0))}catch{}}),k.addEventListener("close",()=>{j||r.current!==k||(r.current=null,p("closed"),A=window.setTimeout(N,1200))}),k.addEventListener("error",()=>{!j&&r.current===k&&p("error")})};return N(),()=>{j=!0,window.clearTimeout(A);const k=r.current;r.current=null,k?.close(),d.current.clear()}},[n,a]),u.useEffect(()=>{if(!n)return;const j=window.setInterval(()=>{const A=performance.now(),N=b.current,k=Math.max(1,A-N.sampleStartedAt);x({totalSent:N.totalSent,totalDropped:N.totalDropped,sentPerSecond:N.sampleSent*1e3/k,droppedPerSecond:N.sampleDropped*1e3/k,bufferedAmount:r.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=A},1e3);return()=>window.clearInterval(j)},[n]);const C=u.useCallback((j,A)=>{const N=r.current;if(!N||N.readyState!==WebSocket.OPEN||!j)return!1;const k=String(A.type||"").toLowerCase(),T=k==="pointermove",U=T||k==="wheel",O=b.current;if(T&&N.bufferedAmount>uj)return O.totalDropped+=1,O.sampleDropped+=1,O.lastInputType="pointermove-drop",!1;const Y=l.current+1;l.current=Y;const _=Date.now(),D=!U||Y-c.current>=fj;for(D&&(d.current.set(Y,performance.now()),U&&(c.current=Y)),T||xb.set(j,{inputSeq:Y,inputType:k||"input",sentAt:performance.now()});d.current.size>256;){const ne=d.current.keys().next().value;if(ne===void 0)break;d.current.delete(ne)}return N.send(JSON.stringify({type:"input",requestId:U?"":crypto.randomUUID(),fireAndForget:U,deviceId:j,input:{...A,inputSeq:Y,requestAck:D,issuedAtEpochMs:_,issuedAt:new Date(_).toISOString()}})),O.totalSent+=1,O.sampleSent+=1,O.lastInputType=k||"input",!0},[]);return{state:m,sendInput:C,stats:w,error:g}}function gj(n){const a=String(n||"").toLowerCase();return a.includes("audio/pcm")||a.includes("audio/l16")||a.includes("f32le")||a.includes("s16le")}const md={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,lastUpdatedAt:0},vj=.08,yj=.25,xj=.02,Dy=300,bj=4,hd=1500,eh=5e3,wj=2e3,Sj=1e4,pd=[0,1e3,3e3];function Ly(n){const a=Date.parse(String(n||""));return Number.isFinite(a)?Math.max(0,Date.now()-a):0}function Cj(n,a,r){const l=Math.max(1,Math.min(8,Math.floor(a.channels||2))),c=Math.max(8e3,Math.min(192e3,Math.floor(a.sampleRate||48e3))),d=String(a.mimeType||"").toLowerCase(),m=d.includes("s16le")||d.includes("audio/l16"),p=m?2:4,g=Math.floor(r.byteLength/p),v=Math.floor(g/l),w=n.createBuffer(l,v,c),x=new DataView(r);for(let b=0;b<l;b+=1){const C=w.getChannelData(b);for(let j=0;j<v;j+=1){const N=(j*l+b)*p;C[j]=m?Math.max(-1,Math.min(1,x.getInt16(N,!0)/32768)):Math.max(-1,Math.min(1,x.getFloat32(N,!0)))}}return w}function jj(n,a,r=Cn){const l=u.useRef(null),c=u.useRef(0),[d,m]=u.useState("idle"),[p,g]=u.useState(null),[v,w]=u.useState(md),[x,b]=u.useState("");return u.useEffect(()=>{if(!a||!n){m("idle"),g(null),w(md),b("");return}m("connecting"),g(null),w(md),b("");const C=window.AudioContext||window.webkitAudioContext;if(!C){m("unsupported"),w(md),b("Audio playback is not supported in this browser.");return}const j=new C;l.current=j,c.current=j.currentTime;const A=new WebSocket(ef("/api/remote/audio/ws?devices="+encodeURIComponent(n),r));A.binaryType="arraybuffer";const N=new Set,k={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:!1,helperAlive:!1,captureRestartCount:0,localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(j.state),stalledCount:0,automaticRestarts:0,activeStreamId:"",lastCaptureStatusAt:0,lastPcmAtEpochMs:0};let T=!1,R=0,U=!1,O=0,Y=0;const _=(I=!0)=>{for(const Q of N)try{Q.stop()}catch{}N.clear(),I&&(c.current=j.currentTime+vj)},D=()=>{k.audioContextState=String(j.state),!T&&(k.audioContextState==="suspended"||k.audioContextState==="interrupted"?m("suspended"):k.audioContextState==="closed"&&(m("error"),b("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ne=async()=>{if(T||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),k.audioContextState=String(j.state),!T&&!U&&k.audioContextState==="running"){const I=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=hd,Q=k.lastCaptureStatusAt>0&&performance.now()-k.lastCaptureStatusAt<=eh&&k.captureAlive&&k.helperAlive;m(I?"playing":Q?"silent":"open")}return k.audioContextState==="running"}catch(I){return T||(m("suspended"),b(I instanceof Error?"Audio playback is suspended: "+I.message:"Audio playback is suspended.")),!1}},G=async()=>{if(T||U||A.readyState!==WebSocket.OPEN)return;if(O>=pd.length){m("error"),b("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const I=O;O+=1,U=!0,k.stalledCount+=1,k.automaticRestarts+=1,m("reconnecting");try{const Q=await Ge("/api/remote/devices/"+encodeURIComponent(n)+"/audio/stop",{method:"POST",body:JSON.stringify({})},r);if(Q.ok===!1)throw new Error(Q.error||"Remote audio stop failed.");if(T)return;const q=await Ge("/api/remote/devices/"+encodeURIComponent(n)+"/audio/start",{method:"POST",body:JSON.stringify({streamId:"audio-restart-"+Date.now(),mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},r);if(q.ok===!1)throw new Error(q.error||"Remote audio start failed.");const V=performance.now();R=V,k.lastPacketAt=V,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,Y=V+(pd[I+1]??3e3),b(""),T||m("open")}catch(Q){T||(Y=performance.now()+(pd[I+1]??3e3),m("error"),b(Q instanceof Error?"Remote audio restart failed: "+Q.message:"Remote audio restart failed."))}finally{U=!1}},te=()=>{k.drops+=1},B=window.setInterval(()=>{if(T)return;const I=performance.now(),Q=k.lastPacketAt>0?Math.max(0,I-k.lastPacketAt):R>0?Math.max(0,I-R):0,q=k.lastAcceptedAt>0?Math.max(0,I-k.lastAcceptedAt):0,V=k.lastCaptureStatusAt>0?Math.max(0,I-k.lastCaptureStatusAt):0,ce=A.readyState===WebSocket.OPEN,be=k.lastCaptureStatusAt>0,X=be&&V<=eh,$=be&&(!k.captureAlive||!k.helperAlive)&&V>wj,ue=be&&V>eh,he=!be&&R>0&&I-R>Sj,ve=R>0&&(k.lastAcceptedAt<=0?I-R>hd:q>hd);ce&&R>0&&($||ue||he)?O>=pd.length&&!U?(m("error"),b("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!U&&I>=Y?G():U||m("stalled"):ce&&ve&&!U&&k.audioContextState!=="suspended"&&k.audioContextState!=="interrupted"&&m(X?"silent":"open"),w({queuedMs:Math.max(0,(c.current-j.currentTime)*1e3),browserAgeMs:k.browserAgeMs,captureAgeMs:k.captureAgeMs,captureStatusAgeMs:V,silentForMs:k.silentForMs,captureAlive:k.captureAlive,helperAlive:k.helperAlive,captureRestartCount:k.captureRestartCount,localProcessingAgeMs:k.localProcessingAgeMs,lastPacketAgeMs:Q,lastAcceptedAgeMs:q,framesReceived:k.framesReceived,drops:k.drops,resyncs:k.resyncs,pendingDecodes:k.pendingDecodes,lastFrameSeq:k.lastFrameSeq,audioContextState:k.audioContextState,stalledCount:k.stalledCount,automaticRestarts:k.automaticRestarts,lastUpdatedAt:Date.now()})},250),xe=()=>{D(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&ne()},se=()=>{document.visibilityState==="visible"&&ne()},K=()=>{ne()};return j.addEventListener("statechange",xe),document.addEventListener("visibilitychange",se),window.addEventListener("pageshow",K),window.addEventListener("pointerdown",K),window.addEventListener("keydown",K),m("connecting"),b(""),D(),A.addEventListener("open",()=>{T||(R=performance.now(),k.lastPacketAt=R,k.lastAcceptedAt=0,k.lastCaptureStatusAt=0,k.lastPcmAtEpochMs=0,k.captureAlive=!1,k.helperAlive=!1,k.silentForMs=0,m("open"),A.send(JSON.stringify({type:"subscribe",deviceIds:[n]})),ne())}),A.addEventListener("message",I=>{if(typeof I.data=="string")return;const Q=I.data instanceof ArrayBuffer?I.data:null;if(!Q||Q.byteLength<5)return;const q=performance.now();k.lastPacketAt=q,(async()=>{try{const ce=new DataView(Q).getUint32(0,!1);if(ce<=0||ce+4>Q.byteLength){te();return}const be=new Uint8Array(Q,4,ce),X=JSON.parse(np.decode(be)),$=Q.slice(4+ce),ue=String(X.frameKind||X.kind||"").toLowerCase();if(X.type==="remote.audio.status"||ue==="audio-status"){if(k.lastCaptureStatusAt=q,k.captureAlive=X.captureAlive===!0,k.helperAlive=X.helperAlive===!0,k.captureRestartCount=Math.max(0,Number(X.restartCount||0)||0),k.lastPcmAtEpochMs=Math.max(0,Number(X.lastPcmAtEpochMs||0)||0),k.silentForMs=Math.max(0,Number(X.silentForMs||0)||0),k.captureAgeMs=k.lastPcmAtEpochMs>0?Math.max(0,Date.now()-k.lastPcmAtEpochMs):k.silentForMs,k.captureAlive&&k.helperAlive){if(O=0,Y=0,!U){b("");const ve=String(j.state)==="running",Se=k.lastAcceptedAt>0&&performance.now()-k.lastAcceptedAt<=hd;m(ve?Se?"playing":"silent":"suspended")}}else U||m("stalled");return}const he={deviceId:String(X.deviceId||""),frameSeq:Number(X.frameSeq||0),streamId:String(X.streamId||""),mimeType:String(X.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(X.sampleRate||48e3),channels:Number(X.channels||2),capturedAt:String(X.capturedAt||""),receivedAt:String(X.receivedAt||""),byteLength:Number(X.byteLength||$.byteLength),payload:$};if(!he.deviceId||T)return;if(performance.now()-q>Dy){te();return}if(k.pendingDecodes>=bj){te();return}k.pendingDecodes+=1;try{const ve=gj(he.mimeType)?Cj(j,he,$):await j.decodeAudioData($.slice(0));if(k.localProcessingAgeMs=Math.max(0,performance.now()-q),T)return;if(k.localProcessingAgeMs>Dy){te();return}if(he.frameSeq>0&&he.frameSeq<=k.lastFrameSeq){te();return}if(k.activeStreamId&&he.streamId!==k.activeStreamId&&he.frameSeq<=k.lastFrameSeq){te();return}he.streamId&&he.streamId!==k.activeStreamId&&(k.activeStreamId=he.streamId,k.lastFrameSeq=0,_());const Se=j.currentTime;Math.max(0,c.current-Se)>yj&&(_(),k.resyncs+=1);const re=j.createBufferSource();re.buffer=ve,re.connect(j.destination),N.add(re),re.onended=()=>{N.delete(re),re.onended=null};const Z=Math.max(j.currentTime+xj,c.current);re.start(Z),c.current=Z+ve.duration,k.browserAgeMs=Ly(he.receivedAt),k.captureAgeMs=Ly(he.capturedAt),k.lastAcceptedAt=performance.now(),k.framesReceived+=1,k.lastFrameSeq=he.frameSeq,O=0,Y=0,g(he),ne();const ze=String(j.state)==="running";ze&&b(""),m(ze?"playing":"suspended")}finally{k.pendingDecodes=Math.max(0,k.pendingDecodes-1)}}catch(V){T||(m("error"),b(V instanceof Error?V.message:String(V)))}})()}),A.addEventListener("error",()=>{T||(m("error"),b("Remote audio WebSocket error."))}),A.addEventListener("close",()=>{T||m("closed")}),()=>{T=!0,window.clearInterval(B),j.removeEventListener("statechange",xe),document.removeEventListener("visibilitychange",se),window.removeEventListener("pageshow",K),window.removeEventListener("pointerdown",K),window.removeEventListener("keydown",K),_(!1),A.close(),j.close().catch(()=>{}),l.current===j&&(l.current=null)}},[n,a,r]),{state:d,lastFrame:p,stats:v,error:x}}const kj=3;function _y(n,a,r){const l=Math.max(1,Number(r)||1),c=Math.max(0,Math.min(l,Number(n)-Number(a))),d=Math.min(l/2,kj);return c<=d?0:c>=l-d?1:c/l}function Aj(n,a,r){return{normalizedX:_y(n,r.left,r.width),normalizedY:_y(a,r.top,r.height)}}const ei=Object.freeze({smallDirectDeviceLimit:4,interactiveDirectFps:30,controlWallReuseMaxFps:30,scalableAtlasInputFps:8,atlasOutputFps:20,maxDirectFramesPerSecond:96,directDecodeAcceleration:"prefer-software",directLatencyMode:"interactive",configuredLatencyMode:"smooth"});function Nj(n,a){const r=Math.max(0,Math.floor(Number(a)||0));return n===!0&&r>0&&r<=ei.smallDirectDeviceLimit}function Nc({mode4Enabled:n,directMode4WallEnabled:a,isMac:r}){return!n||a||r?"direct":"atlas"}function Mj({mode4Enabled:n,directMode4WallEnabled:a,adaptiveFps:r,directDeviceCount:l}){const c=Math.max(1,Math.floor(Number(r)||1));if(!n)return c;if(a)return Math.max(ei.interactiveDirectFps,c);const d=Math.max(1,Math.floor(Number(l)||1));return Math.max(1,Math.min(c,Math.floor(ei.maxDirectFramesPerSecond/d)))}function Tj(n,a){return n?{acceleration:ei.directDecodeAcceleration,latencyMode:ei.directLatencyMode}:{acceleration:a,latencyMode:ei.configuredLatencyMode}}const Lh={revision:0,settings:{connection:{usePinToAddDevices:!0,pinValidityMinutes:30,rotatePinAfterPairing:!0,allowNewDevices:!0,approveNewDevices:!0,startWithComputer:!0,keepRunningInTray:!0,showConnectionNotifications:!0},security:{accessMode:"trusted-only",requireEncryptedConnections:!0,allowInternetConnections:!1,allowLanConnections:!0,allowUnencryptedLanFallback:!1,requireNewDeviceApproval:!0,requireAdministratorForSecurityChanges:!0,visibleControlIndicator:!0,lockOnControlEnd:!0,disconnectIdleControlSessions:!0,idleControlMinutes:30,keepSessionHistory:!0,sessionHistoryDays:30},control:{allowKeyboardMouse:!0,allowSystemShortcuts:!0,allowClipboardText:!0,allowRemoteRestart:!1,reconnectAfterRemoteRestart:!0,allowSwitchingMonitors:!0,showConnectionToolbar:!0,showRemoteCursor:!0,openControlOnDoubleClick:!0,startRemoteAudioWithControl:!1,fitRemoteScreen:!0,rememberLastMonitor:!0,keepControlReadyBetweenPages:!0},wall:{performanceMode:"auto",autoStart:!0,connectedOnly:!1,keepEmptySlots:!0,showDeviceStatus:!0,showPerformanceDetails:!1,pauseHiddenTiles:!0,reduceWhenHidden:!0,autoAdjustTileQuality:!0,rememberDevicePositions:!0},filesAudio:{allowFileTransfer:!0,allowFolderSync:!1,askBeforeReceivingFiles:!0,openReceivedFolder:!1,notifyTransferComplete:!0,allowOverwrite:!1,defaultReceiveFolder:"Desktop/LiveDeskFiles",maxFileSizeBytes:1073741824,allowRemoteAudio:!0,startAudioMuted:!1,rememberVolume:!0,automaticallyRecoverAudio:!0,showAudioTroubleshooting:!1,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0,captureSaveLocation:"LiveDesk Captures",captureAutoDelete:"never"},agent:{enabled:!1,defaultPermissionMode:"safe-auto",askBeforeDestructive:!0,allowProcessManagement:!0,allowServiceManagement:!0,allowFileChanges:!0,allowCommandExecution:!1,allowSoftwareInstallation:!1,allowPowerActions:!1,keepAuditHistory:!0,timeoutMinutes:10},advanced:{wallFrameMode:"auto",wallFps:20,wallMaxWidth:960,wallMaxHeight:540,wallQuality:55,controlFrameMode:"mode3-h264-hw",controlFps:30,controlMaxWidth:1920,controlMaxHeight:1080,controlQuality:60,transport:"auto",allowPlainLanFallback:!1,verboseLogs:!1,frameStatistics:!1}}},Ej=[{id:"connection",label:"Connection",icon:Dl},{id:"security",label:"Security",icon:Bt},{id:"control",label:"Control",icon:an},{id:"wall",label:"Wall",icon:Pc},{id:"files-audio",label:"Files & Audio",icon:ko},{id:"agent",label:"Agent",icon:Es},{id:"advanced",label:"Advanced",icon:Fd}];function wl(n,a){return n?.settings?.[a]||Lh.settings[a]}function ht({icon:n,title:a,description:r,children:l,disabled:c=!1,recommended:d=!1}){return s.jsxs("div",{className:`product-setting-row ${c?"disabled":""}`,children:[s.jsx("div",{className:"product-setting-control",children:l}),n&&s.jsx("span",{className:"product-setting-icon",children:s.jsx(n,{size:17})}),s.jsxs("div",{className:"product-setting-copy",children:[s.jsx("strong",{children:a}),d&&s.jsx("em",{children:"Recommended"}),s.jsx("small",{children:r})]})]})}function Tt({checked:n,onChange:a,disabled:r=!1,label:l}){return s.jsxs("label",{className:"product-switch",children:[s.jsx("input",{"aria-label":l,type:"checkbox",checked:n,disabled:r,onChange:c=>a(c.target.checked)}),s.jsx("span",{})]})}function Li({value:n,onChange:a,options:r,disabled:l=!1,label:c}){return s.jsx("select",{"aria-label":c,value:String(n),disabled:l,onChange:d=>a(d.target.value),children:r.map(([d,m])=>s.jsx("option",{value:d,children:m},d))})}function Rj({hubUrl:n="",runtimeRole:a="hub",runtimeDeviceId:r="",sessionAccessToken:l="",initialTab:c="connection",pin:d,wall:m,control:p,agent:g,advancedExtras:v,captureGallery:w}){const[x,b]=u.useState(c),[C,j]=u.useState(null),[A,N]=u.useState("loading"),[k,T]=u.useState(""),[R,U]=u.useState("idle"),[O,Y]=u.useState("");u.useEffect(()=>{let ve=!0;return N("loading"),Ge("/api/settings",void 0,n).then(Se=>{ve&&(j({revision:Number(Se.revision||0),updatedAt:Se.updatedAt,settings:Se.settings}),N("saved"))}).catch(Se=>{ve&&(T(Se instanceof Error?Se.message:String(Se)),j(Lh),N("failed"))}),()=>{ve=!1}},[n]);const _=async(ve,Se,_e)=>{const re=C||Lh,Z=re,ze={...re,settings:{...re.settings,[ve]:{...wl(re,ve),[Se]:_e}}};j(ze),N("saving"),T("");try{const Le=await Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:re.revision,[ve]:{[Se]:_e}})},n);j({revision:Le.revision,updatedAt:Le.updatedAt,settings:Le.settings}),N("saved")}catch(Le){j(Z),N("failed"),T(Le instanceof Error?Le.message:String(Le))}},D=(ve,Se)=>_e=>{_(ve,Se,_e)},ne=async()=>{if(a!=="hub"||!r||!l){U("failed"),Y("Sign in to this Hub before changing its runtime role.");return}U("changing"),Y("");try{const ve=await Ge("/api/runtime/status",void 0,n);await Ge("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${l}`},body:JSON.stringify({role:"client"})},n),U("accepted"),await ab({baseUrl:n,targetRole:"client",previousRuntimePid:Number(ve.runtimePid||0),allowedStates:["running","waiting-auth"]}),oC(5179)}catch(ve){U("failed"),Y(ve instanceof Error?ve.message:String(ve))}},G=wl(C,"security"),te=wl(C,"connection"),B=wl(C,"control"),xe=wl(C,"wall"),se=wl(C,"filesAudio"),K=wl(C,"agent"),I=u.useMemo(()=>G.allowInternetConnections===!1?{label:"Local only",tone:"local",detail:"Internet connections are disabled."}:G.requireEncryptedConnections&&G.requireNewDeviceApproval&&G.accessMode==="trusted-only"?{label:"Protected",tone:"protected",detail:"Encrypted connections and trusted-device approval are active."}:{label:"Needs attention",tone:"attention",detail:"Review access and encryption settings before sharing this Hub."},[G]),Q=`settings-panel-${x}`,q=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"product-settings-hero",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"settings-eyebrow",children:[s.jsx(Dl,{size:14})," Connection"]}),s.jsx("h2",{children:"Connect a device"}),s.jsx("p",{children:"Use the short PIN on the computer you want to add. The PIN is temporary and can be replaced at any time."})]}),s.jsxs("div",{className:"product-save-state",role:"status",children:[s.jsx(Kx,{size:14})," ",A==="saving"?"Saving":A==="failed"?"Failed":A==="loading"?"Loading":"Saved"]})]}),d,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection behavior"}),s.jsx("h3",{children:"New device access"})]}),s.jsx(Mo,{size:20})]}),s.jsx(ht,{icon:Mo,title:"Use PIN to add new devices",description:"Allow temporary PIN pairing from the client.",recommended:!0,children:s.jsx(Tt,{checked:!!te.usePinToAddDevices,onChange:D("connection","usePinToAddDevices"),label:"Use PIN to add new devices"})}),s.jsx(ht,{icon:Bt,title:"Approve new devices on this Hub",description:"Ask for approval before an unfamiliar computer becomes trusted.",children:s.jsx(Tt,{checked:!!te.approveNewDevices,onChange:D("connection","approveNewDevices"),label:"Approve new devices"})}),s.jsx(ht,{icon:pn,title:"Show connection notifications",description:"Show a short notice when a computer connects or leaves.",children:s.jsx(Tt,{checked:!!te.showConnectionNotifications,onChange:D("connection","showConnectionNotifications"),label:"Show connection notifications"})})]}),s.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Runtime role"}),s.jsx("h3",{children:"Use this computer as a Client"})]}),s.jsx(Fd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"This stops the Hub listener, saves the Client role in Supabase, and restarts LiveDesk through the unified launcher."}),R==="accepted"?s.jsx("p",{className:"settings-help runtime-role-success",children:"Role change accepted. LiveDesk is restarting as Client."}):O?s.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:O}):null,s.jsx("button",{className:"settings-reset",onClick:()=>{ne()},disabled:R==="changing"||a!=="hub",type:"button",children:R==="changing"?"Switching role…":"Switch this computer to Client"})]})]}),V=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:`security-status-card ${I.tone}`,children:[s.jsxs("div",{children:[s.jsx("span",{children:"Security status"}),s.jsx("strong",{children:I.label}),s.jsx("small",{children:I.detail})]}),s.jsx(Bt,{size:28})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Access mode"}),s.jsx("h3",{children:"Who may use this Hub?"})]}),s.jsx(Ts,{size:20})]}),s.jsx(ht,{icon:Bt,title:"Access mode",description:"Choose the default boundary for remote sessions.",recommended:!0,children:s.jsx(Li,{value:String(G.accessMode),onChange:D("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["ask-every-time","Ask every time"],["view-only","View only"],["block-remote-access","Block remote access"]]})}),s.jsx(ht,{icon:Dl,title:"Require encrypted connections",description:"External connections cannot disable this protection.",recommended:!0,children:s.jsx(Tt,{checked:!!G.requireEncryptedConnections,onChange:D("security","requireEncryptedConnections"),label:"Require encrypted connections"})}),s.jsx(ht,{icon:Dl,title:"Allow internet connections",description:"Keep off unless you intentionally expose this Hub beyond the LAN.",children:s.jsx(Tt,{checked:!!G.allowInternetConnections,onChange:D("security","allowInternetConnections"),label:"Allow internet connections"})}),s.jsx(ht,{icon:an,title:"Allow LAN connections",description:"Permit connections from the local network.",children:s.jsx(Tt,{checked:!!G.allowLanConnections,onChange:D("security","allowLanConnections"),label:"Allow LAN connections"})}),s.jsx(ht,{icon:Bt,title:"Require approval for new devices",description:"New computers must be approved before remote access is granted.",children:s.jsx(Tt,{checked:!!G.requireNewDeviceApproval,onChange:D("security","requireNewDeviceApproval"),label:"Require approval for new devices"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session protection"}),s.jsx("h3",{children:"End sessions safely"})]}),s.jsx(pn,{size:20})]}),s.jsx(ht,{icon:an,title:"Show an indicator while Control is active",description:"Make active remote control visible on the local computer.",children:s.jsx(Tt,{checked:!!G.visibleControlIndicator,onChange:D("security","visibleControlIndicator"),label:"Show Control indicator"})}),s.jsx(ht,{icon:Ts,title:"Lock the remote computer when Control ends",description:"Protect the local screen after a Control session.",children:s.jsx(Tt,{checked:!!G.lockOnControlEnd,onChange:D("security","lockOnControlEnd"),label:"Lock after Control ends"})}),s.jsx(ht,{icon:pn,title:"Disconnect idle Control sessions",description:"Automatically close inactive Control sessions.",children:s.jsx(Tt,{checked:!!G.disconnectIdleControlSessions,onChange:D("security","disconnectIdleControlSessions"),label:"Disconnect idle sessions"})}),s.jsx(ht,{icon:pn,title:"Idle timeout",description:"Time before an inactive Control session closes.",disabled:!G.disconnectIdleControlSessions,children:s.jsx(Li,{value:Number(G.idleControlMinutes),onChange:ve=>D("security","idleControlMinutes")(Number(ve)),disabled:!G.disconnectIdleControlSessions,label:"Idle timeout",options:[["5","5 minutes"],["15","15 minutes"],["30","30 minutes"],["60","1 hour"],["1440","Never"]]})})]})]}),ce=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Remote use"}),s.jsx("h3",{children:"What can a connected user do?"})]}),s.jsx(an,{size:20})]}),s.jsx(ht,{icon:an,title:"Keyboard and mouse control",description:"Allow the Hub to send keyboard and pointer input.",recommended:!0,children:s.jsx(Tt,{checked:!!B.allowKeyboardMouse,onChange:D("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),s.jsx(ht,{icon:VS,title:"System shortcuts",description:"Allow shortcut keys such as Alt-Tab and the system key.",children:s.jsx(Tt,{checked:!!B.allowSystemShortcuts,onChange:D("control","allowSystemShortcuts"),label:"System shortcuts"})}),s.jsx(ht,{icon:Mo,title:"Clipboard text sharing",description:"Share plain text through the remote session.",children:s.jsx(Tt,{checked:!!B.allowClipboardText,onChange:D("control","allowClipboardText"),label:"Clipboard text sharing"})}),s.jsx(ht,{icon:pn,title:"Remote restart",description:"Allow restart requests from Control.",disabled:!B.allowKeyboardMouse,children:s.jsx(Tt,{checked:!!B.allowRemoteRestart,onChange:D("control","allowRemoteRestart"),disabled:!B.allowKeyboardMouse,label:"Remote restart"})}),s.jsx(ht,{icon:an,title:"Switching monitors",description:"Allow the viewer to select another connected display.",children:s.jsx(Tt,{checked:!!B.allowSwitchingMonitors,onChange:D("control","allowSwitchingMonitors"),label:"Switching monitors"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Session behavior"}),s.jsx("h3",{children:"Make Control predictable"})]}),s.jsx(Fn,{size:20})]}),s.jsx(ht,{icon:an,title:"Open Control on double-click",description:"Double-clicking a Wall tile opens its Control view.",children:s.jsx(Tt,{checked:!!B.openControlOnDoubleClick,onChange:D("control","openControlOnDoubleClick"),label:"Open Control on double-click"})}),s.jsx(ht,{icon:pn,title:"Start audio with Control",description:"Keep audio muted by default for new sessions.",children:s.jsx(Tt,{checked:!!B.startRemoteAudioWithControl,onChange:D("control","startRemoteAudioWithControl"),label:"Start audio with Control"})}),s.jsx(ht,{icon:an,title:"Fit remote screen to window",description:"Scale the remote display to the available Control area.",children:s.jsx(Tt,{checked:!!B.fitRemoteScreen,onChange:D("control","fitRemoteScreen"),label:"Fit remote screen"})}),s.jsx(ht,{icon:pn,title:"Keep Control ready between pages",description:"Faster reconnection for 1 minute.",recommended:!0,children:s.jsx(Tt,{checked:!!B.keepControlReadyBetweenPages,onChange:D("control","keepControlReadyBetweenPages"),label:"Keep Control ready between pages"})})]})]}),be=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Performance mode"}),s.jsx("h3",{children:"Let LiveDesk choose the best path"})]}),s.jsx(Pc,{size:20})]}),s.jsx(ht,{icon:Es,title:"Performance mode",description:"Automatic mode balances responsiveness and image quality.",recommended:!0,children:s.jsx(Li,{value:String(xe.performanceMode),onChange:D("wall","performanceMode"),label:"Performance mode",options:[["auto","Auto"],["responsive","Prioritize responsiveness"],["quality","Prioritize image quality"],["custom","Custom"]]})}),s.jsx("p",{className:"settings-help",children:"Streaming details are available under Advanced for diagnostics and development."})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"What should the Wall show?"})]}),s.jsx(pn,{size:20})]}),[["autoStart","Start Wall automatically","Start a live view when a computer connects."],["connectedOnly","Show only connected devices","Hide disconnected slots."],["keepEmptySlots","Keep empty slots visible","Preserve the layout when a device leaves."],["showDeviceStatus","Show device status on tiles","Display compact machine status."],["showPerformanceDetails","Show performance details","Show advanced frame diagnostics on tiles."],["pauseHiddenTiles","Pause hidden tiles","Reduce capture work for tiles outside the visible area."],["reduceWhenHidden","Reduce activity when the window is hidden","Lower background work when the browser is not visible."],["autoAdjustTileQuality","Automatically adjust tile quality","Adapt tile quality to Wall size and load."]].map(([ve,Se,_e])=>s.jsx(ht,{icon:an,title:Se,description:_e,children:s.jsx(Tt,{checked:!!xe[ve],onChange:D("wall",ve),label:Se})},ve))]})]}),X=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File permissions"}),s.jsx("h3",{children:"Move files deliberately"})]}),s.jsx(ko,{size:20})]}),s.jsx(ht,{icon:ko,title:"Allow file transfer",description:"Permit Hub-to-device file delivery.",recommended:!0,children:s.jsx(Tt,{checked:!!se.allowFileTransfer,onChange:D("filesAudio","allowFileTransfer"),label:"Allow file transfer"})}),s.jsx(ht,{icon:Pc,title:"Allow folder sync",description:"Enable recurring folder synchronization.",disabled:!se.allowFileTransfer,children:s.jsx(Tt,{checked:!!se.allowFolderSync,onChange:D("filesAudio","allowFolderSync"),disabled:!se.allowFileTransfer,label:"Allow folder sync"})}),s.jsx(ht,{icon:Bt,title:"Ask before receiving files",description:"Require local confirmation before a transfer is written.",children:s.jsx(Tt,{checked:!!se.askBeforeReceivingFiles,onChange:D("filesAudio","askBeforeReceivingFiles"),label:"Ask before receiving files"})}),s.jsx(ht,{icon:ko,title:"Allow overwrite",description:"Permit replacing an existing destination file.",children:s.jsx(Tt,{checked:!!se.allowOverwrite,onChange:D("filesAudio","allowOverwrite"),label:"Allow overwrite"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Audio permissions"}),s.jsx("h3",{children:"Remote sound"})]}),s.jsx(pn,{size:20})]}),s.jsx(ht,{icon:pn,title:"Allow remote audio",description:"Permit audio capture from connected computers.",recommended:!0,children:s.jsx(Tt,{checked:!!se.allowRemoteAudio,onChange:D("filesAudio","allowRemoteAudio"),label:"Allow remote audio"})}),s.jsx(ht,{icon:pn,title:"Start audio muted",description:"New audio sessions begin silent.",children:s.jsx(Tt,{checked:!!se.startAudioMuted,onChange:D("filesAudio","startAudioMuted"),label:"Start audio muted"})}),s.jsx(ht,{icon:pn,title:"Automatically recover audio",description:"Recover from temporary capture or transport stalls.",children:s.jsx(Tt,{checked:!!se.automaticallyRecoverAudio,onChange:D("filesAudio","automaticallyRecoverAudio"),label:"Automatically recover audio"})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Capture defaults"}),s.jsx("h3",{children:"Screen recording"})]}),s.jsx(an,{size:20})]}),s.jsx(ht,{icon:pn,title:"Keep a Last 30s buffer",description:"Keep recent video in memory only until you explicitly save it.",children:s.jsx(Tt,{checked:!!se.rollingBufferEnabled,onChange:D("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),s.jsx(ht,{icon:pn,title:"Recording quality",description:"Choose the WebM bitrate profile.",children:s.jsx(Li,{value:String(se.recordingQuality),onChange:D("filesAudio","recordingQuality"),label:"Recording quality",options:[["standard","Standard"],["high","High"]]})}),s.jsx(ht,{icon:pn,title:"Timelapse interval",description:"Capture one frame at the selected interval.",children:s.jsx(Li,{value:Number(se.timelapseIntervalSeconds),onChange:ve=>D("filesAudio","timelapseIntervalSeconds")(Number(ve)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})}),s.jsx(ht,{icon:an,title:"Include remote cursor",description:"Include the cursor indicator when the source provides it.",children:s.jsx(Tt,{checked:!!se.includeRemoteCursor,onChange:D("filesAudio","includeRemoteCursor"),label:"Include remote cursor"})}),s.jsx(ht,{icon:ko,title:"Capture save location",description:"Captures are stored inside the Hub capture library.",children:s.jsx(Li,{value:String(se.captureSaveLocation),onChange:D("filesAudio","captureSaveLocation"),label:"Capture save location",options:[[String(se.captureSaveLocation||"LiveDesk Captures"),"LiveDesk Captures"]]})}),s.jsx(ht,{icon:ko,title:"Automatic deletion",description:"Keep saved captures until you delete them.",children:s.jsx(Li,{value:String(se.captureAutoDelete),onChange:D("filesAudio","captureAutoDelete"),label:"Automatic deletion",options:[["never","Never"],["7-days","After 7 days"],["30-days","After 30 days"]]})})]}),w]}),$=s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent safety"}),s.jsx("h3",{children:"AI workstation operations"})]}),s.jsx(Es,{size:20})]}),s.jsx(ht,{icon:Es,title:"Enable AI Agent on devices",description:"Allow Agent runs to reach connected workstations.",recommended:!0,children:s.jsx(Tt,{checked:!!K.enabled,onChange:D("agent","enabled"),label:"Enable AI Agent"})}),s.jsx(ht,{icon:Bt,title:"Default permission mode",description:"Safe Auto keeps destructive operations behind approval.",children:s.jsx(Li,{value:String(K.defaultPermissionMode),onChange:D("agent","defaultPermissionMode"),label:"Default Agent permission mode",options:[["ask","Ask"],["safe-auto","Safe Auto"],["full-access","Full Access"],["custom","Custom"]]})}),s.jsx(ht,{icon:Bt,title:"Ask before destructive operations",description:"Locked on for Safe Auto and destructive actions.",disabled:!K.enabled,children:s.jsx(Tt,{checked:!!K.askBeforeDestructive,onChange:D("agent","askBeforeDestructive"),disabled:!K.enabled,label:"Ask before destructive operations"})}),s.jsx(ht,{icon:pn,title:"Keep Agent audit history",description:"Retain an inspectable record of Agent runs.",children:s.jsx(Tt,{checked:!!K.keepAuditHistory,onChange:D("agent","keepAuditHistory"),label:"Keep Agent audit history"})}),s.jsx(ht,{icon:pn,title:"Stop Agent tasks after timeout",description:"Maximum runtime for one task.",children:s.jsx(Li,{value:Number(K.timeoutMinutes),onChange:ve=>D("agent","timeoutMinutes")(Number(ve)),label:"Agent task timeout",options:[["1","1 minute"],["5","5 minutes"],["10","10 minutes"],["30","30 minutes"],["60","1 hour"]]})})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Detailed permissions"}),s.jsx("h3",{children:"Capabilities"})]}),s.jsx(Bt,{size:20})]}),[["allowProcessManagement","Allow process management"],["allowServiceManagement","Allow service management"],["allowFileChanges","Allow file changes"],["allowCommandExecution","Allow command execution"],["allowSoftwareInstallation","Allow software installation"],["allowPowerActions","Allow power actions"]].map(([ve,Se])=>s.jsx(ht,{icon:Bt,title:Se,description:ve.includes("allowCommand")||ve.includes("Installation")||ve.includes("Power")?"Disabled by default for safety.":"Applied by the Hub and checked again by the Client.",children:s.jsx(Tt,{checked:!!K[ve],onChange:D("agent",ve),label:Se})},ve))]}),s.jsx("p",{className:"settings-help",children:"The existing Codex runtime and audit controls remain available below in Advanced and the Agent diagnostics panel."})]}),he=x==="connection"?q:x==="security"?V:x==="control"?ce:x==="wall"?be:x==="files-audio"?X:x==="agent"?s.jsxs(s.Fragment,{children:[$,g]}):s.jsxs("div",{className:"settings-tab-content product-settings-content",children:[v,s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer controls"}),s.jsx("h3",{children:"Streaming and diagnostics"})]}),s.jsx(Fd,{size:20})]}),s.jsx("p",{className:"settings-help",children:"Codec, frame rate, resolution, quality, Atlas layout, and decoder preferences are intentionally kept here."}),m,p]})]});return s.jsxs("section",{className:"settings-page",children:[s.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:Ej.map(({id:ve,label:Se,icon:_e})=>s.jsxs("button",{className:x===ve?"active":"",id:`settings-tab-${ve}`,role:"tab","aria-selected":x===ve,"aria-controls":`settings-panel-${ve}`,tabIndex:x===ve?0:-1,onClick:()=>b(ve),type:"button",children:[s.jsx(_e,{size:16}),Se]},ve))}),k&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:k}),s.jsx("section",{className:"settings-page-panel",id:Q,role:"tabpanel","aria-labelledby":`settings-tab-${x}`,tabIndex:0,children:he})]})}function Dj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function Lj({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}function _j({children:n}){return s.jsx("div",{className:"settings-tab-content",children:n})}const bb={enabled:!0,provider:"codex",codexModelId:"",codexReasoningEffort:"medium",codexTaskTimeoutMs:6e5,codexMaxToolCalls:20,codexWorkingDirectory:"",codexResumeSessions:!0,codexShowDetailedEvents:!0,deterministicParserFirst:!0,generateSummary:!0,fallbackSummary:!0,includeRawDeviceDetails:!1,baseUrl:"https://opencode.ai/zen/go/v1",defaultModelId:"deepseek-v4-flash"};function zy(n){return{...bb,...n||{}}}function zj({hubUrl:n}){const[a,r]=u.useState(bb),[l,c]=u.useState(null),[d,m]=u.useState(""),[p,g]=u.useState(""),[v,w]=u.useState(""),[x,b]=u.useState("");u.useEffect(()=>{let D=!0;return Ge("/api/settings/agent",void 0,n).then(ne=>{D&&(c(ne.settings),r(zy(ne.settings)))}).catch(ne=>{D&&b(ne instanceof Error?ne.message:String(ne))}),()=>{D=!1}},[n]);const C=(D,ne)=>r(G=>({...G,[D]:ne})),j=D=>{c(D),r(zy(D))},A=async()=>{g("save"),b(""),w("");try{const D={...a};d.trim()&&(D.apiKey=d.trim());const ne=await Ge("/api/settings/agent",{method:"PUT",body:JSON.stringify(D)},n);j(ne.settings),m(""),w("Agent settings saved.")}catch(D){b(D instanceof Error?D.message:String(D))}finally{g("")}},N=async()=>{g("reset"),b("");try{const D=await Ge("/api/settings/agent/reset",{method:"POST",body:JSON.stringify({})},n);j(D.settings),w("Codex defaults restored.")}catch(D){b(D instanceof Error?D.message:String(D))}finally{g("")}},k=async()=>{g("test"),b(""),w("");try{const D=await Ge("/api/settings/agent/test",{method:"POST",body:JSON.stringify({})},n),ne=await Ge("/api/settings/agent",void 0,n);j(ne.settings),w(`Codex connection verified with ${D.connection?.modelName||"the configured model"}${D.connection?.latencyMs?` in ${D.connection.latencyMs} ms.`:"."}`)}catch(D){b(D instanceof Error?D.message:String(D))}finally{g("")}},T=async()=>{g("clear-key"),b("");try{const D=await Ge("/api/settings/agent/api-key",{method:"DELETE"},n);j(D.settings),m(""),w("The optional OpenCode Go key was removed.")}catch(D){b(D instanceof Error?D.message:String(D))}finally{g("")}},R=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",U=l?.securityStatus,O=U?.state||"unavailable",Y=O==="verified"?"Verified":O==="configured"?"Configured":"Unavailable",_=[["Codex home",U?.isolatedCodexHome],["Environment variables",U?.restrictedEnvironment],["LiveDesk MCP only",U?.livedeskMcpOnly],["Selected-device scope",U?.selectedDeviceScopeEnforced],["Fail-closed execution",U?.failClosed]];return s.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[s.jsx("section",{className:"settings-section-card agent-enable-card",children:s.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.enabled,onChange:D=>C("enabled",D.target.checked)}),s.jsx("span",{children:"Enable Agent AI"})]})}),x&&s.jsx("div",{className:"agent-settings-alert error",role:"alert",children:x}),v&&s.jsx("div",{className:"agent-settings-alert success",role:"status",children:v}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Provider"}),s.jsx("h3",{children:"Codex is the default"})]}),s.jsx(Mo,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Agent provider"}),s.jsxs("select",{value:a.provider,onChange:D=>C("provider",D.target.value),children:[s.jsx("option",{value:"codex",children:"Codex SDK"}),s.jsx("option",{value:"opencode-go",children:"OpenCode Go (optional legacy)"})]})]}),s.jsxs("div",{className:"agent-connection-row",children:[s.jsx("span",{className:`agent-connection-dot ${R?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),s.jsx("span",{children:l?.codexInstallation==="not-installed"?"Codex SDK not installed":l?.codexAuth==="signed-in"?"Codex CLI signed in":l?.codexAuth==="not-signed-in"?"Codex CLI sign-in required":"Codex status not tested"}),s.jsxs("button",{className:"settings-reset",onClick:()=>{k()},disabled:p!==""||a.provider!=="codex",type:"button",children:[s.jsx(WS,{size:15})," ",p==="test"?"Testing":"Test connection"]})]}),s.jsxs("p",{className:"settings-help",children:[s.jsx(YS,{size:12})," Authentication is owned by the installed Codex CLI. LiveDesk never asks for or stores a ChatGPT token."]}),l?.codexPath&&s.jsxs("p",{className:"settings-help",children:["CLI: ",l.codexPath]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Codex runtime"}),s.jsx("h3",{children:"Model and reasoning"})]}),s.jsx(KS,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Model"}),s.jsx("input",{value:a.codexModelId,onChange:D=>C("codexModelId",D.target.value),placeholder:"Codex default",disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Reasoning effort"}),s.jsxs("select",{value:a.codexReasoningEffort,onChange:D=>C("codexReasoningEffort",D.target.value),disabled:a.provider!=="codex",children:[s.jsx("option",{value:"minimal",children:"Minimal"}),s.jsx("option",{value:"low",children:"Low"}),s.jsx("option",{value:"medium",children:"Medium"}),s.jsx("option",{value:"high",children:"High"}),s.jsx("option",{value:"xhigh",children:"Extra high"})]})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Task timeout (ms)"}),s.jsx("input",{type:"number",min:"30000",max:"1800000",step:"10000",value:a.codexTaskTimeoutMs,onChange:D=>C("codexTaskTimeoutMs",Number(D.target.value)),disabled:a.provider!=="codex"})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Max tool calls"}),s.jsx("input",{type:"number",min:"1",max:"100",value:a.codexMaxToolCalls,onChange:D=>C("codexMaxToolCalls",Number(D.target.value)),disabled:a.provider!=="codex"})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Workspace"}),s.jsx("h3",{children:"Restricted execution context"})]}),s.jsx(Bt,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Working directory"}),s.jsx("input",{value:l?.agentWorkspacePath||a.codexWorkingDirectory,readOnly:!0})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexResumeSessions,onChange:D=>C("codexResumeSessions",D.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Allow session resume"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.codexShowDetailedEvents,onChange:D=>C("codexShowDetailedEvents",D.target.checked),disabled:a.provider!=="codex"}),s.jsx("span",{children:"Show detailed Codex events"})]}),s.jsx("p",{className:"settings-help",children:"The agent receives no project path or arbitrary filesystem directory. It can call LiveDesk MCP tools only."})]})]}),a.provider==="opencode-go"&&s.jsxs("section",{className:"settings-section-card agent-legacy-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Developer fallback"}),s.jsx("h3",{children:"OpenCode Go"})]}),s.jsx(Mo,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Base URL"}),s.jsx("input",{value:a.baseUrl,onChange:D=>C("baseUrl",D.target.value)})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"API key"}),s.jsx("input",{type:"password",value:d,onChange:D=>m(D.target.value),placeholder:l?.hasApiKey?l.apiKeyPreview:"Stored only in the Hub",autoComplete:"new-password"})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{T()},disabled:p!==""||!l?.hasApiKey,type:"button",children:[s.jsx(Yh,{size:15})," Clear key"]}),s.jsx("span",{className:"settings-help",children:"This provider does not run the Codex MCP tool loop."})]})]}),s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Agent behavior"}),s.jsx("h3",{children:"Predictable operation"})]}),s.jsx(Fn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.deterministicParserFirst,onChange:D=>C("deterministicParserFirst",D.target.checked)}),s.jsx("span",{children:"Use deterministic parser before Codex"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.generateSummary,onChange:D=>C("generateSummary",D.target.checked)}),s.jsx("span",{children:"Generate task summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.fallbackSummary,onChange:D=>C("fallbackSummary",D.target.checked)}),s.jsx("span",{children:"Fallback to deterministic summaries"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:a.includeRawDeviceDetails,onChange:D=>C("includeRawDeviceDetails",D.target.checked)}),s.jsx("span",{children:"Include raw device details in summaries"})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Safety"}),s.jsx("h3",{children:"Locked execution boundary"})]}),s.jsx(Bt,{size:20})]}),["Arbitrary shell commands","PowerShell and Bash","Filesystem writes, deletes, and installs","Reboot, shutdown, and process termination","Network access and web search"].map(D=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(Yx,{size:15}),s.jsx("span",{children:D}),s.jsx("strong",{children:"Blocked"})]},D)),_.map(([D])=>s.jsxs("div",{className:"agent-safety-row",children:[s.jsx(Bt,{size:15}),s.jsx("span",{children:D}),s.jsx("strong",{className:O==="unavailable"?"agent-safety-failed":O==="configured"?"agent-safety-configured":"agent-safety-verified",children:Y})]},D)),s.jsx("p",{className:"settings-help",children:"Configured means the boundary is present but has not completed runtime verification. Test the connection or start an Agent run to verify it."})]})]}),s.jsxs("div",{className:"settings-action-row agent-settings-actions",children:[s.jsxs("button",{className:"settings-reset",onClick:()=>{N()},disabled:p!=="",type:"button",children:[s.jsx(_c,{size:15})," Reset defaults"]}),s.jsxs("button",{className:"text-button primary",onClick:()=>{A()},disabled:p!=="",type:"button",children:[s.jsx(Kx,{size:15})," ",p==="save"?"Saving":"Save Agent settings"]})]})]})}new Date().valueOf();function ti(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function ap(n,a){return typeof n=="function"?typeof a=="object"?n(a):n():n}function Lo(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function Ij(n,a="data-id"){const r=Lo(n,a);return r?r.getAttribute(a):null}function Gc(n,a="data-id"){const r=Lo(n,a);return r?nf(r,a):null}function nf(n,a="data-id"){const r=n.getAttribute(a);return r?Oj(r):null}function Pn(n){return typeof n=="string"?":"+n:n}function Oj(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Hj(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var La=Hj();function sp(n){Object.assign(La,n)}function Iy(n,a,r){function l(c){const d=Lo(c);if(!d)return;const m=nf(d);if(typeof a=="function")return a(m,c);let p,g=c.target;for(;g!=d;){if(p=g.dataset?g.dataset.action:null,p&&a[p]){a[p](m,c);return}g=g.parentNode}a[r]&&a[r](m,c)}La.addEvent(n,r,l)}function _o(n,a){Iy(n,a,"click"),a.dblclick&&Iy(n,a.dblclick,"dblclick")}function Bj(n,a){for(let r=n.length-1;r>=0;r--)if(n[r]===a){n.splice(r,1);break}}function Fj(n,a,r){for(let l=0;l<Oi.length;l++){if(l===r)continue;const c=Oi[l],d=c.props.parent?.();if(d&&n.contains(d)&&c.node.contains(a))return!0}return!1}var wb=new Date,Wd=!1,gd=[],Oi=[],Oy=n=>{const a=n.target;if(Wd||!a.isConnected){Wd=!1;return}for(let r=Oi.length-1;r>=0;r--){const{node:l,date:c,props:d}=Oi[r];if(!(c>wb)&&!l.contains(a)&&l!==a&&(Fj(l,a,r)||(d.callback&&d.callback(n),d.modal||n.defaultPrevented)))break}},Pj=n=>{wb=new Date,Wd=!0;for(let a=Oi.length-1;a>=0;a--){const{node:r}=Oi[a];if(!r.contains(n.target)&&r!==n.target){Wd=!1;break}}};function ni(n,a){gd.length||(gd=[La.addGlobalEvent("click",Oy,n),La.addGlobalEvent("contextmenu",Oy,n),La.addGlobalEvent("mousedown",Pj,n)]),typeof a!="object"&&(a={callback:a});const r={node:n,date:new Date,props:a};return Oi.push(r),{destroy(){Bj(Oi,r),Oi.length||(gd.forEach(l=>l()),gd=[])}}}var vd=n=>n.indexOf("bottom")!==-1,yd=n=>n.indexOf("left")!==-1,xd=n=>n.indexOf("right")!==-1,th=n=>n.indexOf("top")!==-1,Hy=n=>n.indexOf("fit")!==-1,Mc=n=>n.indexOf("overlap")!==-1,$j=n=>n.split("-").every(a=>["center","fit"].indexOf(a)>-1),Uj=n=>{const a=n.match(/(start|center|end)/);return a?a[0]:null};function qj(n,a){let r=0;const l=La.getTopNode(n);for(;n&&n!==l;){const c=getComputedStyle(n).position;if((c==="absolute"||c==="relative"||c==="fixed")&&(r=parseInt(getComputedStyle(n).zIndex)||0),n=n.parentNode,n===a)break}return r}var Ln,ia,Tc,Qn;function Sb(n,a,r="bottom",l=0,c=0){if(!n)return null;Ln=l,ia=c,Tc="auto";let d=0,m=0,p=r;const g=Cb(n),v=Mc(r)?La.getTopNode(n):g;if(!g)return null;const w=g.getBoundingClientRect(),x=n.getBoundingClientRect(),b=v.getBoundingClientRect(),C=window.getComputedStyle(v),j={left:0,top:0,bottom:0,right:0};for(const U in j){const O=`border-${U}-width`;j[U]=parseFloat(C.getPropertyValue(O))}if(a){const U=qj(a,g);d=Math.max(U+1,20)}if(a){if(Qn=a.getBoundingClientRect(),Hy(r)&&(Tc=Qn.width+"px"),r!=="point")if($j(r))Hy(r)?Ln=0:(Ln=b.width/2,m=1),ia=(b.height-x.height)/2;else{const U=Mc(r)?0:1;Ln=xd(r)?Qn.right+U:Qn.left-U,ia=vd(r)?Qn.bottom+1:Qn.top;const O=Uj(r);O&&(xd(r)||yd(r)?O==="center"?ia-=(x.height-Qn.height)/2:O==="end"&&(ia-=x.height-Qn.height):(vd(r)||th(r))&&(O==="center"?Ln-=(x.width-Qn.width)/2:O==="end"&&(Ln-=x.width-Qn.width),Mc(r)||(Ln+=1)))}}else Qn={left:l,right:l,top:c,bottom:c};const A=(yd(r)||xd(r))&&(vd(r)||th(r));yd(r)&&(m=2);const N=Ln-x.width-b.left;a&&yd(r)&&!A&&N<0&&(Ln=Qn.right,m=0,p=p.replace("left","right"));const k=Ln+x.width*(1-m/2)-b.right;if(k>0)if(!xd(r))Ln=b.right-j.right-x.width;else{const U=Qn.left-b.x-x.width;a&&!A&&U>=0?(Ln=Qn.left-x.width,p=p.replace("right","left")):Ln-=k+j.right}m&&(Ln=Math.round(Ln-x.width*m/2));const T=N<0||k>0||!A;th(r)&&(ia=Qn.top-x.height,a&&ia<b.y&&T&&(ia=Qn.bottom,p=p.replace("top","bottom")));const R=ia+x.height-b.bottom;return R>0&&(a&&vd(r)&&T?(ia-=x.height+Qn.height+1,p=p.replace("bottom","top")):ia-=R+j.bottom),Ln-=w.left+j.left,ia-=w.top+j.top,Ln=(Mc(r)?Ln:Math.max(Ln,0))+v.scrollLeft,ia=(Mc(r)?ia:Math.max(ia,0))+v.scrollTop,Tc=Tc||"auto",{at:p,x:Ln,y:ia,z:d,width:Tc}}function Cb(n){const a=La.getTopNode(n);for(n&&(n=n.parentElement);n;){const r=getComputedStyle(n).position;if(n===a||r==="relative"||r==="absolute"||r==="fixed")return n;n=n.parentNode}return null}function Gj(n){const a=[];let r=n;const l=La.getTopNode(n);for(;r&&r!==l&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&a.push(r),r=r.parentNode;return a}var By=new Date().valueOf();function ip(){return By+=1,By}function la(n){return n<10?"0"+n:n.toString()}function Vj(n){const a=la(n);return a.length==2?"0"+a:a}function jb(n){const a=Math.floor(n/11)*11;return{start:a,end:a+11}}function nh(n){const a=(n.getDay()+6)%7,r=new Date(n.valueOf());r.setDate(n.getDate()+(3-a)),r.setHours(0,0,0,0);const l=new Date(r.getFullYear(),0,1),c=Math.round((r.getTime()-l.getTime())/864e5);return 1+Math.floor(c/7)}var Fy=["",""];function Wj(n,a,r){switch(n){case"%d":return la(a.getDate());case"%m":return la(a.getMonth()+1);case"%j":return a.getDate();case"%n":return a.getMonth()+1;case"%y":return la(a.getFullYear()%100);case"%Y":return a.getFullYear();case"%D":return r.dayShort[a.getDay()];case"%l":return r.dayFull[a.getDay()];case"%M":return r.monthShort[a.getMonth()];case"%F":return r.monthFull[a.getMonth()];case"%h":return la((a.getHours()+11)%12+1);case"%g":return(a.getHours()+11)%12+1;case"%G":return a.getHours();case"%H":return la(a.getHours());case"%i":return la(a.getMinutes());case"%a":return((a.getHours()>11?r.pm:r.am)||Fy)[0];case"%A":return((a.getHours()>11?r.pm:r.am)||Fy)[1];case"%s":return la(a.getSeconds());case"%S":return Vj(a.getMilliseconds());case"%W":return la(nh(a));case"%w":{const l=r.weekStart??1;if(l===1)return la(nh(a));const c=(a.getDay()-l+7)%7,d=(1-l+7)%7,m=new Date(a.valueOf());return m.setDate(a.getDate()+(d-c)),la(nh(m))}case"%c":{let l=a.getFullYear()+"";return l+="-"+la(a.getMonth()+1),l+="-"+la(a.getDate()),l+="T",l+=la(a.getHours()),l+=":"+la(a.getMinutes()),l+=":"+la(a.getSeconds()),l}case"%Q":return Math.floor(a.getMonth()/3)+1;default:return n}}var Yj=/%[a-zA-Z]/g;function To(n,a){return typeof n=="function"?n:function(r){return r?(r.getMonth||(r=new Date(r)),n.replace(Yj,l=>Wj(l,r,a))):""}}function Py(n){return n&&typeof n=="object"&&!Array.isArray(n)}function _h(n,a){for(const r in a){const l=a[r];Py(n[r])&&Py(l)?n[r]=_h({...n[r]},a[r]):n[r]=a[r]}return n}function Wc(n){return{getGroup(a){const r=n[a];return l=>r&&r[l]||l},getRaw(){return n},extend(a,r){if(!a)return this;let l;return r?l=_h({...a},n):l=_h({...n},a),Wc(l)}}}var Kj=eb();const Qj="en-US",Xj={monthFull:["January","February","March","April","May","June","July","August","September","October","November","December"],monthShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayFull:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],hours:"Hours",minutes:"Minutes",done:"Done",clear:"Clear",today:"Today",am:["am","AM"],pm:["pm","PM"],weekStart:0,clockFormat:24},Zj={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},Jj={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},kb={core:Zj,calendar:Xj,formats:Jj,lang:Qj},rp=u.createContext(""),Ab=u.createContext({}),Ds=u.createContext(null),Nb=u.createContext(null),Un=Object.freeze(Object.defineProperty({__proto__:null,fieldId:Nb,helpers:Ab,i18n:Ds,theme:rp},Symbol.toStringTag,{value:"Module"}));function Mb(n){const a=u.useContext(Nb),[r]=u.useState(()=>n||a||ip());return r}function Hc({type:n="",css:a="",icon:r="",disabled:l=!1,title:c="",tooltip:d,text:m="",children:p,onClick:g}){const v=u.useMemo(()=>{let x=n?n.split(" ").filter(b=>b!=="").map(b=>"wx-"+b).join(" "):"";return a+(a?" ":"")+x},[n,a]),w=x=>{g&&g(x)};return s.jsxs("button",{title:c,className:`wx-2ZWgb4 wx-button ${v} ${r&&!p?"wx-icon":""}`,disabled:l,onClick:w,"data-tooltip-text":d,children:[r&&s.jsx("i",{className:"wx-2ZWgb4 "+r}),p||m||" "]})}function ek({id:n,label:a="",inputValue:r="",value:l=!1,onChange:c,disabled:d=!1,css:m=""}){const p=Mb(n),[g,v]=ti(l),w=({target:x})=>{const b=x.checked;v(b),c&&c({value:b,inputValue:r})};return s.jsxs("div",{className:`wx-2IvefP wx-checkbox ${m}`,children:[s.jsx("input",{type:"checkbox",id:p,disabled:d,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),s.jsxs("label",{htmlFor:p,className:"wx-2IvefP wx-label",children:[s.jsx("span",{className:"wx-2IvefP wx-before"}),a&&s.jsx("span",{className:"wx-2IvefP wx-after",children:a})]})]})}function lp({theme:n="",target:a,children:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(null);l.current||(l.current=document.createElement("div"));const p=u.useContext(rp);return u.useEffect(()=>{m(a||tk(c.current)||La.getTopNode(c.current))},[c.current]),s.jsxs(s.Fragment,{children:[s.jsx("span",{ref:c,style:{display:"none"}}),c.current&&d?Kj.createPortal(s.jsx("div",{className:`wx-3ZWsT0 wx-${n||p}-theme`,children:r}),d):null]})}function tk(n){const a=La.getTopNode(n);for(;n&&n!==a&&!n.getAttribute("data-wx-portal-root");)n=n.parentNode;return n}function nk({left:n=0,top:a=0,at:r="bottom",parent:l=null,width:c="auto",css:d="",onCancel:m,children:p,trackScroll:g=!1}){const[v,w]=u.useState(0),[x,b]=u.useState(0),[C,j]=u.useState("auto"),[A,N]=u.useState(!1),k=u.useRef(null),T=u.useRef(null),R=u.useRef(m);u.useEffect(()=>{R.current=m},[m]);function U(Y){return l&&(c+"").indexOf("%")>-1?c.replace(/(\d+)%/,(_,D)=>(D=D*l.offsetWidth/100+"px",c.replace(_,D))):c&&c!=="auto"?c:Y}const O=u.useCallback(()=>{if(!k.current)return;const Y=Sb(k.current,l,r,n,a);Y&&(w(Y.x),b(Y.y),j(U(Y.width)))},[k,l,r,n,a,c]);return u.useLayoutEffect(()=>{const Y=D=>{R.current&&D.target!==T.current&&k.current&&!k.current.contains(D.target)&&R.current(D)};let _;return requestAnimationFrame(()=>{O(),N(!0),g&&k.current&&(T.current=Cb(k.current),T.current&&T.current.addEventListener("scroll",Y,!0)),l&&(_=new ResizeObserver(O),_.observe(l))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",Y,!0),_?.disconnect()}},[]),u.useLayoutEffect(()=>{O()},[l,r,n,a]),u.useEffect(()=>{const Y=_=>{R.current&&R.current(_)};if(k.current)return ni(k.current,{callback:Y,parent:()=>l}).destroy},[l]),s.jsx("div",{ref:k,className:["wx-37M6Fj","wx-popup",d].filter(Boolean).join(" "),style:{position:"absolute",visibility:A?"visible":"hidden",top:x+"px",left:v+"px",width:C},children:p})}function ak({position:n="bottom",align:a="start",autoFit:r=!0,onCancel:l=null,width:c="100%",css:d="",children:m}){const p=u.useRef(null),[g,v]=u.useState(n),[w,x]=u.useState(a),b=u.useRef(l);return u.useEffect(()=>{b.current=l},[l]),u.useEffect(()=>{if(r){const C=p.current;if(C){const j=C.getBoundingClientRect(),A=document.body.getBoundingClientRect();j.right>=A.right&&x("end"),j.bottom>=A.bottom&&v("top")}}},[]),u.useEffect(()=>{if(p.current){const C=j=>{b.current&&b.current(j)};return ni(p.current,C).destroy}},[]),s.jsx("div",{ref:p,className:["wx-dropdown",`wx-${g}-${w}`,d||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:c},children:m})}function op({position:n="bottom",align:a="start",autoFit:r=!0,inline:l=!1,onCancel:c,width:d="100%",children:m,...p}){const[g,v]=u.useState(void 0),w=u.useRef(null),x=u.useMemo(()=>`${n}-${a}`,[n,a]);return u.useLayoutEffect(()=>{w.current&&v(w.current.parentNode)},[]),s.jsxs(s.Fragment,{children:[g&&(l?s.jsx(ak,{onCancel:c,position:n,align:a,autoFit:r,width:d,...p,children:m}):s.jsx(lp,{children:s.jsx(nk,{parent:g,at:x,onCancel:c,width:d,...p,children:m})})),s.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function af(){return Wc(kb)}function sk(){let n=null,a=!1,r=!1,l,c,d,m;const p=(x,b,C,j,A)=>{l=x,c=b,d=C,m=j,r=A},g=x=>{n=x,a=n!==null,d(n)},v=(x,b)=>{if(!r&&x!==null&&l){const C=l.querySelectorAll(".wx-list > .wx-item")[x];C&&(C.scrollIntoView({block:"nearest"}),b&&b.preventDefault())}},w=(x,b)=>{const C=x===null?null:Math.max(0,Math.min(n+x,c.length-1));C!==n&&(g(C),l?v(C,b):requestAnimationFrame(()=>v(C,b)))};return{move:x=>{const b=Gc(x),C=c.findIndex(j=>j.id===b);C!==n&&g(C)},keydown:(x,b)=>{switch(x.code){case"Enter":a?m():g(0);break;case"Space":a||g(0);break;case"Escape":d(n=null);break;case"Tab":d(n=null);break;case"ArrowDown":w(a?1:b||0,x);break;case"ArrowUp":w(a?-1:b||0,x);break}},init:p,navigate:w}}const $y=10,ik=u.memo(function({data:n,checkboxes:a,itemTemplate:r,value:l}){return s.jsxs(s.Fragment,{children:[a&&s.jsx(ek,{id:n.id,css:"wx-list-checkbox",value:l&&l.includes(n.id)}),r?ap(r,{option:n}):n.label]})});function Uy({visibleItems:n,visibleRange:a,navIndex:r,checkboxes:l,itemTemplate:c,value:d,measureRefCallback:m}){return n.map((p,g)=>{const v=a.start+g;return s.jsx("div",{ref:g===0?m:void 0,className:`wx-233fr7 wx-item ${v===r?"wx-focus":""}`,"data-id":p.id,children:s.jsx(ik,{data:p,checkboxes:l,itemTemplate:c,value:d})},p.id)})}function sf({items:n=[],children:a,onSelect:r,onReady:l,virtualized:c=!1,checkboxes:d,multiselect:m,value:p,...g}){const v=u.useRef(),w=u.useRef(!1),x=u.useRef(sk()),[b,C]=u.useState(null),j=u.useRef(b),[A,N]=u.useState(0),[k,T]=u.useState(24),R=u.useRef(!1),U=(u.useContext(Ds)||af()).getGroup("core"),O=u.useRef(n);u.useEffect(()=>{O.current=n},[n]);const Y=u.useRef(p);u.useEffect(()=>{Y.current=p},[p]);const _=u.useRef(0);u.useEffect(()=>{_.current=k},[k]);const D=u.useCallback(X=>{X&&X.stopPropagation();const $=O.current,ue=Y.current,he=j.current;let ve;const Se=$[he]?.id;m?ue&&ue.includes(Se)?ve=ue.filter(_e=>_e!==Se):ve=[...ue||[],Se]:ve=Se,r&&r({id:ve})},[m,r]),ne=u.useRef(D);u.useEffect(()=>{ne.current=D},[D]);const G=u.useCallback(X=>{if(v.current){let $=X*_.current-v.current.clientHeight+_.current;N($),v.current.scrollTop=$}},[_.current]),te=u.useCallback(X=>{v.current=X,c&&(X&&!w.current&&j.current!==null&&requestAnimationFrame(()=>{v.current&&(G(j.current),w.current=!0)}),X||(w.current=!1))},[G]),B=u.useCallback(X=>{if(!X||R.current)return;const $=X.getBoundingClientRect().height;$&&(T($),_.current=$,R.current=!0)},[]);u.useEffect(()=>{x.current.init(v.current,n,X=>{C(X),j.current=X},X=>ne.current(X),c)},[n,v.current,c]),u.useEffect(()=>{const X=(ue,he)=>{x.current.navigate(ue,he),G(j.current)},$=(ue,he)=>{const ve=j.current,Se=O.current;if(ve!==0&&ve!==Se.length-1&&(ue.key==="ArrowDown"||ue.key==="ArrowUp")&&ue.preventDefault(),x.current.keydown(ue,he),v.current){const _e=v.current.scrollTop<=j.current*_.current,re=v.current.scrollTop+v.current.clientHeight>=j.current*_.current+_.current;_e?re||G(j.current):(v.current.scrollTop=j.current*_.current,N(v.current.scrollTop))}};l&&l({navigate:c?X:x.current.navigate,keydown:c?$:x.current.keydown,move:x.current.move})},[]);const xe=u.useRef(0),se=u.useRef(n);se.current!==n&&(se.current=n,xe.current+=1);const K=u.useCallback(()=>{x.current.navigate(null)},[x]),I=u.useCallback(X=>{c&&N(X.target.scrollTop)},[c]),Q=u.useMemo(()=>Math.ceil((v.current?.clientHeight||0)/k),[k,A]),q=u.useMemo(()=>{if(!c)return{start:0,end:n.length};if(!n.length)return{start:0,end:0};const X=Math.floor(A/k),$=X+Q;return{start:Math.max(0,X-$y),end:Math.min(n.length,$+$y)}},[c,n,A,k,Q]),V=u.useMemo(()=>{if(!c)return n;const{start:X,end:$}=q;return n.slice(X,$).map(ue=>({...ue}))},[c,n,q]),ce=q.start*k,be=n.length*k;return u.useEffect(()=>{c&&N(0)},[n,c]),u.useEffect(()=>{b===null&&(w.current=!1)},[b]),b===null?null:s.jsx(op,{onCancel:K,...g,children:s.jsx("div",{className:"wx-233fr7 wx-list",ref:te,onClick:D,onMouseMove:x.current.move,onScroll:I,children:n.length?c?s.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${be}px`},children:s.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${ce}px)`},children:s.jsx(Uy,{visibleRange:q,visibleItems:V,navIndex:b,measureRefCallback:B,checkboxes:d,itemTemplate:a,value:p})})}):s.jsx(Uy,{visibleRange:q,visibleItems:V,navIndex:b,measureRefCallback:B,checkboxes:d,itemTemplate:a,value:p}):s.jsx("div",{className:"wx-233fr7 wx-no-data",children:U("No data")})})},xe.current)}function cp({value:n="",id:a,readonly:r=!1,focus:l=!1,select:c=!1,type:d="text",placeholder:m="",disabled:p=!1,error:g=!1,title:v="",tooltip:w,css:x="",icon:b="",clear:C=!1,onChange:j}){const A=Mb(a),[N,k]=ti(n),T=u.useRef(null),R=u.useMemo(()=>b&&x.indexOf("wx-icon-left")===-1?"wx-icon-right "+x:x,[b,x]),U=u.useMemo(()=>b&&x.indexOf("wx-icon-left")!==-1,[b,x]);u.useEffect(()=>{const ne=setTimeout(()=>{l&&T.current&&T.current.focus(),c&&T.current&&T.current.select()},1);return()=>clearTimeout(ne)},[l,c]);const O=u.useCallback(ne=>{const G=ne.target.value;k(G),j&&j({value:G,input:!0})},[j]),Y=u.useCallback(ne=>j&&j({value:ne.target.value}),[j]);function _(ne){ne.stopPropagation(),k(""),j&&j({value:""})}let D=d;return d!=="password"&&d!=="number"&&(D="text"),u.useEffect(()=>{const ne=Y,G=T.current;return G.addEventListener("change",ne),()=>{G&&G.removeEventListener("change",ne)}},[Y]),s.jsxs("div",{className:`wx-hQ64J4 wx-text ${R} ${g?"wx-error":""} ${p?"wx-disabled":""} ${C?"wx-clear":""}`,"data-tooltip-text":w,children:[s.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:A,readOnly:r,disabled:p,placeholder:m,type:D,title:v,value:N,onInput:O}),C&&!p&&N?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:_}),U&&s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`})]}):b?s.jsx("i",{className:`wx-hQ64J4 wx-icon ${b}`}):null]})}function rk({date:n,type:a,part:r,onShift:l}){const{calendar:c,formats:d}=u.useContext(Ds).getRaw(),m=n.getFullYear(),p=u.useMemo(()=>{switch(a){case"month":return To(d.monthYearFormat,c)(n);case"year":return To(d.yearFormat,c)(n);case"duodecade":{const{start:v,end:w}=jb(m),x=To(d.yearFormat,c);return`${x(new Date(v,0,1))} - ${x(new Date(w,11,31))}`}default:return""}},[n,a,m,c,d]);function g(){l&&l({diff:0,type:a})}return s.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>l&&l({diff:-1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"}),s.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:p}),r!=="left"?s.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>l&&l({diff:1,type:a})}):s.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function up({onClick:n,children:a}){return s.jsx("button",{className:"wx-3s8W4d wx-button",onClick:n,children:a})}function lk({value:n,current:a,part:r="",markers:l=null,css:c="",onCancel:d,onChange:m}){const p=(u.useContext(Ds)||af()).getRaw().calendar,g=(p.weekStart||7)%7,v=p.dayShort.slice(g).concat(p.dayShort.slice(0,g)),w=(O,Y,_)=>new Date(O.getFullYear(),O.getMonth()+(Y||0),O.getDate()+(_||0));let x=r!=="normal";function b(O){const Y=O.getDay();return Y===0||Y===6}function C(){const O=w(a,0,1-a.getDate());return O.setDate(O.getDate()-(O.getDay()-(g-7))%7),O}function j(){const O=w(a,1,-a.getDate());return O.setDate(O.getDate()+(6-O.getDay()+g)%7),O}const A=u.useRef(0);function N(O,Y){Y.timeStamp!==A.current&&(A.current=Y.timeStamp,Y.stopPropagation(),m&&m(new Date(O)),d&&d())}const k=u.useMemo(()=>r=="normal"?[n?w(n).valueOf():0]:n?[n.start?w(n.start).valueOf():0,n.end?w(n.end).valueOf():0]:[0,0],[r,n]),T=u.useMemo(()=>{const O=C(),Y=j(),_=a.getMonth();let D=[];for(let ne=O;ne<=Y;ne.setDate(ne.getDate()+1)){const G={day:ne.getDate(),in:ne.getMonth()===_,date:ne.valueOf()};let te="";if(te+=G.in?"":" wx-inactive",te+=k.indexOf(G.date)>-1?" wx-selected":"",x){const B=G.date==k[0],xe=G.date==k[1];B&&!xe?te+=" wx-left":xe&&!B&&(te+=" wx-right"),G.date>k[0]&&G.date<k[1]&&(te+=" wx-inrange")}if(te+=b(ne)?" wx-weekend":"",l){const B=l(ne);B&&(te+=" "+B)}D.push({...G,css:te})}return D},[a,k,x,l]),R=u.useRef(null);let U=u.useRef({});return U.current.click=N,u.useEffect(()=>{_o(R.current,U.current)},[]),s.jsxs("div",{className:`wx-398RBS wx-month ${c}`,children:[s.jsx("div",{className:"wx-398RBS wx-weekdays",children:v.map(O=>s.jsx("div",{className:"wx-398RBS wx-weekday",children:O},O))}),s.jsx("div",{className:"wx-398RBS wx-days",ref:R,children:T.map(O=>s.jsx("div",{className:`wx-398RBS wx-day ${O.css} ${O.in?"":"wx-out"}`,"data-id":O.date,children:O.day},O.date))})]})}function ok({value:n,current:a,part:r,onCancel:l,onChange:c,onShift:d}){const m=u.useRef(new Date),[p,g]=ti(n||m.current),[v,w]=ti(a||m.current),x=u.useContext(Ds).getRaw().calendar,b=x.monthShort||[],C=u.useMemo(()=>v.getMonth(),[v]),j=u.useCallback((k,T)=>{if(k!=null){T.stopPropagation();const R=new Date(v);R.setMonth(k),w(R),d&&d({current:R})}r==="normal"&&g(new Date(v)),l&&l()},[v,r,d,l]),A=u.useCallback(()=>{const k=new Date(Tb(p,r)||v);k.setMonth(v.getMonth()),k.setFullYear(v.getFullYear()),c&&c(k)},[p,v,r,c]),N=u.useCallback(k=>{const T=k.target.closest("[data-id]");if(T){const R=parseInt(T.getAttribute("data-id"),10);j(R,k)}},[j]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-34U8T8 wx-months",onClick:N,children:b.map((k,T)=>s.jsx("div",{className:"wx-34U8T8 wx-month"+(C===T?" wx-current":""),"data-id":T,children:k},T))}),s.jsx("div",{className:"wx-34U8T8 wx-buttons",children:s.jsx(up,{onClick:A,children:x.done})})]})}const ah="wx-1XEF33",ck=({value:n,current:a,onCancel:r,onChange:l,onShift:c,part:d})=>{const m=u.useContext(Ds).getRaw().calendar,[p,g]=ti(a),[v,w]=ti(n),x=u.useMemo(()=>p.getFullYear(),[p]),b=u.useMemo(()=>{const{start:k,end:T}=jb(x),R=[];for(let U=k;U<=T;++U)R.push(U);return R},[x]),C={click:j};function j(k,T){if(k){T.stopPropagation();const R=new Date(p);R.setFullYear(k),g(R),c&&c({current:R})}d==="normal"&&w(new Date(p)),r&&r()}function A(){const k=new Date(Tb(v,d)||p);k.setFullYear(p.getFullYear()),l&&l(k)}const N=u.useRef(null);return u.useEffect(()=>{N.current&&_o(N.current,C)},[]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:ah+" wx-years",ref:N,children:b.map((k,T)=>s.jsx("div",{className:ah+` wx-year ${x==k?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":k,children:k},T))}),s.jsx("div",{className:ah+" wx-buttons",children:s.jsx(up,{onClick:A,children:m.done})})]})},qy={month:{component:lk,next:dk,prev:uk},year:{component:ok,next:mk,prev:fk},duodecade:{component:ck,next:pk,prev:hk}};function uk(n){return n=new Date(n),n.setMonth(n.getMonth()-1),n}function dk(n){return n=new Date(n),n.setMonth(n.getMonth()+1),n}function fk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-1),n}function mk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+1),n}function hk(n){return n=new Date(n),n.setFullYear(n.getFullYear()-10),n}function pk(n){return n=new Date(n),n.setFullYear(n.getFullYear()+10),n}function Tb(n,a){let r;if(a==="normal")r=n;else{const{start:l,end:c}=n;a==="left"?r=l:a=="right"?r=c:r=l&&c}return r}const gk=["clear","today"];function vk(n){if(n==="done")return-1;if(n==="clear")return null;if(n==="today")return new Date}function yk({value:n,current:a,onCurrentChange:r,part:l="normal",markers:c=null,buttons:d,css:m="",onShift:p,onChange:g}){const v=u.useContext(Ds).getGroup("calendar"),[w,x]=u.useState("month"),b=Array.isArray(d)?d:d?gk:[],C=(T,R)=>{T.preventDefault(),g&&g({value:R})},j=()=>{w==="duodecade"?x("year"):w==="year"&&x("month")},A=T=>{const{diff:R,current:U}=T;if(R===0){w==="month"?x("year"):w==="year"&&x("duodecade");return}if(R){const O=qy[w];r(R>0?O.next(a):O.prev(a))}else U&&r(U);p&&p()},N=T=>{x("month"),g&&g({select:!0,value:T})},k=u.useMemo(()=>qy[w].component,[w]);return s.jsx("div",{className:`wx-2Gr4AS wx-calendar ${l!=="normal"&&l!=="both"?"wx-part":""} ${m}`,children:s.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[s.jsx(rk,{date:a,part:l,type:w,onShift:A}),s.jsxs("div",{children:[s.jsx(k,{value:n,current:a,onCurrentChange:r,part:l,markers:c,onCancel:j,onChange:N,onShift:A}),w==="month"&&b.length>0&&s.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:b.map(T=>s.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:s.jsx(up,{onClick:R=>C(R,vk(T)),children:v(T)})},T))})]})]})})}function dp(n){let{words:a=null,optional:r=!1,children:l}=n,c=u.useContext(Ds);const d=u.useMemo(()=>{let m=c;return(!m||!m.extend)&&(m=Wc(kb)),a!==null&&(m=m.extend(a,r)),m},[a,r,c]);return s.jsx(Ds.Provider,{value:d,children:l})}function Gy(n,a,r,l){if(!n||l){const c=a?new Date(a):new Date;c.setDate(1),r(c)}else if(n.getDate()!==1){const c=new Date(n);c.setDate(1),r(c)}}const xk=["clear","today"];function Eb({value:n,current:a,markers:r=null,buttons:l=xk,css:c="",onChange:d}){const[m,p]=ti(n),[g,v]=ti(a);u.useEffect(()=>{Gy(g,m,v,!1)},[m,g]);const w=u.useCallback(b=>{const C=b.value;C?(p(new Date(C)),Gy(g,new Date(C),v,!0)):p(null),d&&d({value:C?new Date(C):null})},[d,g]),x=u.useCallback(b=>{v(b)},[v]);return g?s.jsx(dp,{children:s.jsx(yk,{value:m,current:g,markers:r,buttons:l,css:c,onChange:w,onCurrentChange:x})}):null}function bk(n){return n||(n={}),n.width||(n.width="unset"),n}const wk=["clear","today"];function Sk({value:n,id:a,disabled:r=!1,error:l=!1,placeholder:c="",format:d="",buttons:m=wk,css:p="",title:g="",tooltip:v,editable:w=!1,clear:x=!1,onChange:b,dropdown:C={}}){const{calendar:j,formats:A}=(u.useContext(Ds)||af()).getRaw(),N=d||A?.dateFormat;let k=typeof N=="function"?N:To(N,j);const[T,R]=u.useState(n),[U,O]=u.useState(!1);u.useEffect(()=>{R(n)},[n]);function Y(){O(!1)}function _(G){const te=G===T||G&&T&&G.valueOf()===T.valueOf()||!G&&!T;R(G),te||b&&b({value:G}),setTimeout(Y,1)}const D=u.useMemo(()=>T?k(T):"",[T,k]);function ne({value:G,input:te}){if(!w&&!x||te)return;let B=typeof w=="function"?w(G):G?new Date(G):null;B=isNaN(B)?T||null:B||null,_(B)}return u.useEffect(()=>{const G=Y;return window.addEventListener("scroll",G),()=>window.removeEventListener("scroll",G)},[]),s.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>O(!0),children:[s.jsx(cp,{css:`wx-date-input ${p}`,title:g,tooltip:v,value:D,id:a,readonly:!w,disabled:r,error:l,placeholder:c,onInput:Y,onChange:ne,icon:"wxi-calendar",clear:x}),U&&!r&&s.jsx(op,{onCancel:Y,...bk(C),children:s.jsx(Eb,{buttons:m,value:T,onChange:G=>_(G.value)})})]})}function Ck({value:n="",options:a=[],textOptions:r=null,placeholder:l="",disabled:c=!1,error:d=!1,title:m="",tooltip:p,textField:g="label",clear:v=!1,css:w="",children:x,onChange:b,dropdown:C={}}){const j=u.useRef(null),A=u.useRef(null);let[N,k]=ti(n);function T(_){j.current=_.navigate,A.current=_.keydown}const R=u.useMemo(()=>N||N===0?(r||a).find(_=>_.id===N):null,[N,r,a]),U=u.useCallback(({id:_})=>{(_||_===0)&&(k(_),j.current(null),b&&b({value:_}))},[k,b]),O=u.useCallback(_=>{_.stopPropagation(),k(""),b&&b({value:""})},[k,b]),Y=u.useCallback(()=>a.findIndex(_=>_.id===N),[a,N]);return s.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${d?"wx-2YgblL wx-error":""} ${c?"wx-2YgblL wx-disabled":""} ${x?"":"wx-2YgblL wx-nowrap"}`,title:m,onClick:()=>j.current(Y()),onKeyDown:_=>A.current(_,Y()),tabIndex:0,"data-tooltip-text":p,children:[s.jsx("div",{className:"wx-2YgblL wx-label",children:R?x?x(R):R[g]:l?s.jsx("span",{className:"wx-2YgblL wx-placeholder",children:l}):" "}),v&&!c&&N?s.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:O}):s.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!c&&s.jsx(sf,{items:a,onReady:T,onSelect:U,...C,children:({option:_})=>x?x(_):_[g]})]})}const jk=({options:n=[],value:a="",css:r="",children:l,onChange:c})=>{const[d,m]=u.useState(a),p=g=>{m(g),c&&c({value:g})};return u.useEffect(()=>{m(a)},[a]),s.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:n.map(g=>s.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===d?"wx-selected":""}`,title:g.title,onClick:()=>p(g.id),"data-tooltip-text":g.tooltip,children:l?ap(l,{option:g}):s.jsxs(s.Fragment,{children:[g.icon&&s.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&s.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function kk({notice:n={}}){function a(){n.remove&&n.remove()}return s.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${n.type?n.type:""}`,role:"status","aria-live":"polite",children:[s.jsx("div",{className:"wx-11sNg5 wx-text",children:n.text}),s.jsx("div",{className:"wx-11sNg5 wx-button",children:s.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:a})})]})}function Ak({data:n=[]}){return s.jsx("div",{className:"wx-3nwoO9 wx-notices",children:n.map(a=>s.jsx(kk,{notice:a},a.id))})}function zh({title:n="",buttons:a=["cancel","ok"],header:r,children:l,footer:c,css:d="",onConfirm:m,onCancel:p}){const g=(u.useContext(Ds)||af()).getGroup("core"),v=u.useRef(null);u.useEffect(()=>{v.current?.focus()},[]);function w(b){switch(b.code){case"Enter":{const C=b.target.tagName;if(C==="TEXTAREA"||C==="BUTTON")return;m&&m({event:b});break}case"Escape":p&&p({event:b});break}}function x(b,C){const j={event:b,button:C};C==="cancel"?p&&p(j):m&&m(j)}return s.jsx("div",{className:`wx-1FxkZa wx-modal ${d}`,ref:v,tabIndex:0,onKeyDown:w,children:s.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(n?s.jsx("div",{className:"wx-1FxkZa wx-header",children:n}):null),s.jsx("div",{children:l}),c||a&&s.jsx("div",{className:"wx-1FxkZa wx-buttons",children:a.map(b=>s.jsx("div",{className:"wx-1FxkZa wx-button",children:s.jsx(Hc,{type:`block ${b==="ok"?"primary":"secondary"}`,onClick:C=>x(C,b),children:g(b)})},b))})]})})}function Nk({children:n},a){const[r,l]=u.useState(null),[c,d]=u.useState([]);return u.useImperativeHandle(a,()=>({showModal:m=>{const p={...m};return l(p),new Promise((g,v)=>{p.resolve=w=>{l(null),g(w)},p.reject=w=>{l(null),v(w)}})},showNotice:m=>{m={...m},m.id=m.id||ip(),m.remove=()=>d(p=>p.filter(g=>g.id!==m.id)),m.expire!=-1&&setTimeout(m.remove,m.expire||5100),d(p=>[...p,m])}}),[]),s.jsxs(s.Fragment,{children:[n,r&&s.jsx(zh,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),s.jsx(Ak,{data:c})]})}const Mk=u.forwardRef(Nk);function Tk(n){let{children:a}=n,r=u.useRef();const l=u.useMemo(()=>({showNotice:c=>r.current.showNotice(c),showModal:c=>r.current.showModal(c)}),[]);return s.jsx(Ab.Provider,{value:l,children:s.jsx(Mk,{ref:r,children:a})})}const Ek=({value:n=!1,type:a="",icon:r="",disabled:l=!1,iconActive:c="",onClick:d,title:m="",tooltip:p,css:g="",text:v="",textActive:w="",children:x,active:b,onChange:C})=>{const[j,A]=ti(n),N=u.useMemo(()=>(j?"pressed":"")+(a?" "+a:""),[j,a]),k=u.useCallback(T=>{let R=!j;d&&d(T),T.defaultPrevented||(A(R),C&&C({value:R}))},[j,d,C]);return j&&b?s.jsx(Hc,{title:m,tooltip:p,text:j&&w||v,css:g,type:N,icon:j&&c||r,onClick:k,disabled:l,children:ap(b,{value:j})}):x?s.jsx(Hc,{title:m,tooltip:p,text:j&&w||v,css:g,type:N,icon:j&&c||r,onClick:k,disabled:l,children:x}):s.jsx(Hc,{title:m,tooltip:p,text:j&&w||v,css:g,type:N,icon:j&&c||r,onClick:k,disabled:l})};function Rk(){return s.jsx(s.Fragment,{})}function Vy(n){const{fonts:a=!0,children:r}=n;return s.jsx(rp.Provider,{value:"willow",children:s.jsxs(s.Fragment,{children:[r&&r&&s.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),a&&s.jsxs(s.Fragment,{children:[s.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),s.jsx(Rk,{}),s.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}sp(La);const fp={grid:{"Add before":"Add before","Add after":"Add after",Copy:"Copy",Cut:"Cut",Paste:"Paste",Delete:"Delete","New row":"New row","Move up":"Move up","Move down":"Move down",Undo:"Undo",Redo:"Redo",selected:"selected"}};new Date().valueOf();var Rb=class{constructor(n){this._nextHandler=null,this._dispatch=n,this.exec=this.exec.bind(this)}async exec(n,a){return this._dispatch(n,a),this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};new Date().valueOf();var Dk=class{constructor(n){const a={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,a),this._pool=r,n&&n.length&&this.parse(n,0)}parse(n,a){const r=this._pool;for(let c=0;c<n.length;c++){const d=n[c];d.parent=d.parent||a,d.data=null,r.set(d.id,d)}for(let c=0;c<n.length;c++){const d=n[c],m=r.get(d.parent);m&&(m.data||(m.data=[]),m.data.push(d))}const l=r.get(a);this.setLevel(l,l.$level+1,!1)}add(n,a){const r=this._pool.get(n.parent||0);n.$level=r.$level+1,this._pool.set(n.id,n),r.data?a===-1?r.data=[...r.data,n]:Wy(r,a,n):r.data=[n]}addAfter(n,a){if(!a)return this.add(n,-1);const r=this.byId(a),l=this.byId(r.parent),c=bd(l,r.id)+1;n.parent=l.id,n.$level=l.$level+1,this.add(n,c)}remove(n){const a=this._pool.get(n);this._remove(a);const r=this._pool.get(a.parent);r.data=r.data.filter(l=>l.id!=n),this._clearBranch(r)}_remove(n){n.data&&n.data.forEach(a=>this._remove(a)),this._pool.delete(n.id)}update(n,a){let r=this._pool.get(n);const l=this._pool.get(r.parent),c=bd(l,r.id);r={...r,...a},l&&c>=0&&(l.data[c]=r,l.data=[...l.data]),this._pool.set(r.id,r)}move(n,a,r){const l=this._pool.get(n),c=a==="child",d=this._pool.get(r),m=d.$level+(c?1:0);if(!l||!d)return;const p=this._pool.get(l.parent),g=c?d:this._pool.get(d.parent);g.data||(g.data=[]);const v=bd(p,l.id);Lk(p,v);const w=c?g.data.length:bd(g,d.id)+(a==="after"?1:0);if(Wy(g,w,l),p.id===g.id&&v===w)return null;l.parent=g.id,l.$level!==m&&(l.$level=m,this.setLevel(l,m+1,!0)),this.update(l.id,l),this._clearBranch(p)}_clearBranch(n){n.data&&!n.data.length&&(n.open&&delete n.open,this.update(n.id,{data:null}))}toArray(){const n=[],a=this._pool.get(0).data;return a&&Db(a,n),n}byId(n){return this._pool.get(n)}getBranch(n){return this._pool.get(n).data}forEach(n){this._pool.forEach((a,r)=>{r!==0&&n(a)})}eachChild(n,a){const r=this.byId(a);!r||!r.data||r.data.forEach((l,c)=>{n(this.byId(l.id),c),this.eachChild(n,l.id)})}setLevel(n,a,r){n.data&&(n.data=n.data.map(l=>(r&&(l={...l},this._pool.set(l.id,l)),l.$level=a,l.data&&this.setLevel(l,a+1,r),l)))}};function Db(n,a){n.forEach(r=>{a.push(r),r.open===!0&&Db(r.data,a)})}function Lk(n,a){const r=[...n.data];r.splice(a,1),n.data=r}function Wy(n,a,r){const l=[...n.data];l.splice(a,0,r),n.data=l}function bd(n,a){return n?.data.findIndex(r=>r.id===a)}var Lb=2,_k=class{constructor(a){a&&(this._writable=a.writable,this._async=a.async),this._values={},this._state={}}setState(a,r=0){const l={};return this._wrapProperties(a,this._state,this._values,"",l,r),l}getState(){return this._values}getReactive(){return this._state}_wrapProperties(a,r,l,c,d,m){for(const p in a){const g=r[p],v=l[p],w=a[p];if(g&&(v===w&&typeof w!="object"||w instanceof Date&&v instanceof Date&&v.getTime()===w.getTime()))continue;const x=c+(c?".":"")+p;g?(g.__parse(w,x,d,m)&&(l[p]=w),m&Lb?d[x]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[p]=this._wrapNested(w,w,x,d):r[p]=this._wrapWritable(w),l[p]=w),d[x]=d[x]||null}}_wrapNested(a,r,l,c){const d=this._wrapWritable(a);return this._wrapProperties(a,d,r,l,c,0),d.__parse=(m,p,g,v)=>(this._wrapProperties(m,d,r,p,g,v),!1),d}_wrapWritable(a){const r=[],l=function(){for(let c=0;c<r.length;c++)r[c](a)};return{subscribe:c=>(r.push(c),this._async?setTimeout(c,1,a):c(a),()=>{const d=r.indexOf(c);d>=0&&r.splice(d,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(l,1):l())},__parse:function(c){return a=c,!0}}}};function Yy(n,a){return Object.defineProperty(n,"__reactive",{value:!0,enumerable:!1,writable:!1}),n}var zk=class{constructor(a,r,l,c){typeof a=="function"?this._setter=a:this._setter=a.setState.bind(a),this._routes=r,this._parsers=l,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(d=>{d.in.forEach(m=>{const p=this._triggers.get(m)||[];p.push(d),this._triggers.set(m,p)}),d.out.forEach(m=>{const p=this._sources.get(m)||{};d.in.forEach(g=>p[g]=!0),this._sources.set(m,p)})}),this._routes.forEach(d=>{d.length=Math.max(...d.in.map(m=>_b(m,this._sources,1)))}),this._bus=c}init(a){const r={};for(const l in a)if(this._prev[l]!==a[l]){const c=this._parsers[l];r[l]=c?c(a[l]):a[l]}this._prev=this._prev?{...this._prev,...a}:{...a},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(a){const r=this._setter(a,Lb);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const a=this._async;if(a){this._async=null,this._triggerUpdates(a.signals,[]);for(const r in a.signals){const l=a.signals[r];l&&l()}}}setState(a,r=[]){const l=this._setter(a);return this._triggerUpdates(l,r),l}_triggerUpdates(a,r){const l=Object.keys(a),c=!r.length;r=r||[];for(let d=0;d<l.length;d++){const m=l[d],p=this._triggers.get(m);p&&p.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}c&&this._execNext(r)}_execNext(a){for(;a.length;){a.sort((l,c)=>l.length<c.length?1:-1);const r=a[a.length-1];a.splice(a.length-1),r.exec(a)}}};function _b(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>_b(d,a,r+1));return Math.max(...c)}var Ik=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(a,r,l){let c=this._handlers[a];c?l&&l.intercept?c.unshift(r):c.push(r):c=this._handlers[a]=[r],l&&l.tag&&this._tag.set(r,l.tag)}intercept(a,r,l){this.on(a,r,{...l,intercept:!0})}detach(a){for(const r in this._handlers){const l=this._handlers[r];for(let c=l.length-1;c>=0;c--)this._tag.get(l[c])===a&&l.splice(c,1)}}async exec(a,r){const l=this._handlers[a];if(l)for(let c=0;c<l.length;c++){const d=l[c](r);if(d===!1||d&&d.then&&await d===!1)return}return this._nextHandler&&await this._nextHandler.exec(a,r),r}setNext(a){return this._nextHandler=a}};const So=1024;function Vc(n){return n<So?`${n} B`:n<So**2?`${(n/So).toFixed(1)} KB`:n<So**3?`${(n/So**2).toFixed(1)} MB`:`${(n/So**3).toFixed(1)} GB`}function Ky(n,a){a||(a={key:"name",order:"asc"});const r=n.filter(m=>m.type==="folder"),l=n.filter(m=>m.type!=="folder"),c=r.sort(Qy(a)),d=l.sort(Qy(a));return[...c,...d]}function Ok(n,a){return typeof n=="string"?n.localeCompare(a,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-a.getTime():(n??0)-(a??0)}function Hk(n,a){return typeof n=="string"?-n.localeCompare(a,void 0,{numeric:!0}):typeof a=="object"?a.getTime()-n.getTime():(a??0)-(n??0)}function Qy({key:n,order:a}){const r=a==="asc"?Ok:Hk;return(l,c)=>r(l[n],c[n])}function mp(n,a){const r=n==="/"?1:n.split("/").length;return r>=a.length?null:a[r].id}function Bk(n){return n.length>1?n[n.length-2].id:null}let Fk=class extends Dk{constructor(a){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(a,"/")}parse(a,r,l){!a||!a.length||(a.forEach(c=>this.parseId(c,l?r:void 0)),super.parse(a,r))}parseId(a,r){if(a.parent===0)return;const l=a.id,c=l.lastIndexOf("/");if(a.parent=r??(c===0?"/":l.slice(0,c)),a.name=l.slice(c+1),a.type=a.type||"file",a.type!=="folder"){const d=a.name.lastIndexOf("."),m=d!==-1?a.name.slice(d+1):"";a.ext=m!=="new"?m?.toLocaleLowerCase():""}}getParents(a){const r=[];let l=this.byId(a);if(!l)return r;for(;l.id!==0;)r.push(l),l=this.byId(l.parent);return r.reverse()}findFiles(a,r="/"){const l=[],c=a.toLocaleLowerCase();return this.eachChild(d=>{d.name.toLowerCase().indexOf(c)!==-1&&l.push(d)},r),l}add(a,r){const l=this.byId(a.parent||"/"),c=a.data?[...a.data]:null;a.data=null,super.add(a,r??l.data?l.data.length:0),c&&c.forEach(d=>this.add(d))}renameFiles(a,r,l){const c=this.byId(a),d=this.normalizeFile(c,r),m=[];return d.data?.forEach(p=>m.push(this.renameFiles(p.id,d.id,l))),m.length&&(d.data=m),l[a]=d.id,d}copyFiles(a,r,l){const c={};return a.forEach(d=>{const m=this.renameFiles(d,r,c);this.add(m),l&&this.remove(d),c[d]=m.id}),c}moveFiles(a,r){if(this.byId(a[0]).parent!==r)return this.copyFiles(a,r,!0)}serialize(a="/"){const r=[],l=this.byId(a);return l?(l.data?.forEach(c=>{const{id:d,date:m,type:p,size:g,lazy:v}=c,w={id:d,date:m,type:p??"file"};v&&(w.lazy=v),g&&(w.size=g),r.push(w);const x=this.serialize(d);x.length&&r.push(...x)}),r):null}normalizeFile(a,r){const l=a.name,c=l.lastIndexOf("."),d=c!==-1?l.slice(c+1):"",m=d?`.${d}`:"";let p=c!==-1?l.slice(0,c):l,g=r+(r==="/"?"":"/")+p;for(;this.byId(g+m);){const v=".new";g+=v,p+=v}return{...a,id:g+m,name:p+m,parent:r,ext:d.toLocaleLowerCase()}}},Pk=class extends _k{in;_router;constructor(a){super({writable:a,async:!1});const r=[];for(let d=0;d<2;d++)r.push({in:["data",`panels.${d}.path`],out:[`panels.${d}._crumbs`],exec:m=>{const{data:p,panels:g}=this.getState(),v=[];v[d]={_crumbs:p.getParents(g[d].path)},this.setState({panels:v},m)}}),r.push({in:["data",`panels.${d}.path`,`panels.${d}._sorts`,"search"],out:[`panels.${d}._files`],exec:m=>{const{data:p,panels:g,search:v}=this.getState();let w;v?w=p.findFiles(v,g[d].path):w=p.byId(g[d].path)?.data||[];const{path:x,_sorts:b}=g[d];w=Ky(w,b[x]);const C=[];C[d]={_files:w},this.setState({panels:C},m)}}),r.push({in:["data",`panels.${d}.selected`,`panels.${d}._sorts`],out:[`panels.${d}._selected`],exec:m=>{const{data:p,panels:g}=this.getState(),v=[];g[d].selected.forEach(j=>{const A=p.byId(j);A&&v.push(A)});const{path:w,_sorts:x}=g[d],b=Ky(v,x[w]),C=[];C[d]={_selected:b},this.setState({panels:C},m)}});this._router=new zk(super.setState.bind(this),r,{data:d=>new Fk(d)});const l=this.in=new Ik;l.on("select-file",({id:d,toggle:m,range:p,panel:g,type:v})=>{const{panels:w,activePanel:x}=this.getState();typeof g>"u"&&(g=x),d||(m=p=!1);let b=[...w[g].selected];if(m){const j=b.indexOf(d);j===-1?b.push(d):b.splice(j,1)}else if(p&&w[g]._lastSelected){const j=w[g]._files;let A=j.findIndex(T=>T.id==w[g]._lastSelected),N=j.findIndex(T=>T.id==d);N<A&&([A,N]=[N,A]);const k=j.slice(A,N+1).map(T=>T.id);b=[...new Set([...b,...k])]}else b=d?[d]:[];const C=[];C[g]={selected:b,_lastSelected:d,_selectNavigation:v==="navigation"},this.setState({panels:C})}),l.on("set-path",({id:d,panel:m,selected:p})=>{const{data:g,activePanel:v}=this.getState(),w=g.byId(d);if(w){const x=[];typeof m>"u"&&(m=v),x[m]={path:d},this.setState({panels:x}),l.exec("select-file",{panel:m}),p&&p.forEach(b=>l.exec("select-file",{id:b,panel:m,toggle:!0})),w.lazy&&l.exec("request-data",{id:d})}}),l.on("provide-data",({id:d,data:m})=>{const{mode:p,data:g}=this.getState(),v=g.byId(d);v&&(v.lazy||(v.data=[]),v.lazy=!1,g.parse(m,d,p==="search"),this.setState({data:g}))}),l.on("open-tree-folder",({id:d,mode:m})=>{const{data:p}=this.getState();p.update(d,{open:m}),this.setState({data:p})}),l.on("show-preview",({mode:d})=>{this.setState({preview:d})}),l.on("rename-file",d=>{const{id:m,name:p}=d,{data:g,panels:v}=this.getState(),w=g.byId(m);if(w.name!==p){w.name=p;const x=g.normalizeFile(w,w.parent);d.newId=x.id,x.data=null,g.add(x);let b={[m]:x.id};w.data?.forEach(j=>b={...g.moveFiles([j.id],x.id),...b});const C=v.map(j=>({selected:j.selected,_crumbs:j._crumbs,_lastSelected:j._lastSelected,_sorts:j._sorts}));g.remove(m),this._updatePanels(C,b),this.setState({data:g,panels:C})}}),l.on("create-file",d=>{const{file:m,parent:p}=d,{data:g}=this.getState(),v=g.normalizeFile(m,p);v.type=m.type||"file",d.newId=v.id,g.add(v),this.setState({data:g}),l.exec("select-file",{id:v.id})}),l.on("delete-files",({ids:d})=>{const{data:m,panels:p}=this.getState(),g=p.map(v=>({selected:v.selected,_crumbs:v._crumbs,_lastSelected:v._lastSelected,_sorts:v._sorts}));d.forEach(v=>m.remove(v)),this._updatePanels(g,{}),this.setState({data:m,panels:g})}),l.on("copy-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot copy a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:v,activePanel:w}=this.getState(),x=g.copyFiles(m,p);d.newIds=m.map(b=>x[b]),this.setState({data:g}),v[w].path==p&&(l.exec("select-file",{}),m.forEach(b=>{l.exec("select-file",{id:x[b],toggle:!0})}))}),l.on("move-files",d=>{const{ids:m,target:p}=d;if(this._isPlacedIntoSelf(m,p)){console.error("You cannot move a folder into itself"),d.skipProvider=!0;return}const{data:g,panels:v,activePanel:w}=this.getState(),x=g.moveFiles(m,p);if(x){d.newIds=m.map(C=>x[C]);const b=v.map(C=>({selected:C.selected,_crumbs:C._crumbs,_lastSelected:C._lastSelected,_sorts:C._sorts}));this._updatePanels(b,x,!0),this.setState({data:g,panels:b}),v[w].path==p&&(l.exec("select-file",{}),m.forEach(C=>{l.exec("select-file",{id:x[C],toggle:!0})}))}});let c=null;l.on("filter-files",({text:d})=>{if(!d){c&&this.setState({...c});return}l.exec("select-file",{});const{panels:m,mode:p}=this.getState();c||(c={panels:m,mode:p,search:""}),this.setState({mode:"search",search:d})}),l.on("set-mode",({mode:d})=>{const{activePanel:m}=this.getState(),p=[];p[m]={_selectNavigation:!1};const g={mode:d,search:"",panels:p};c=null,this.setState(g)}),l.on("set-active-panel",({panel:d})=>{this.setState({activePanel:d})}),l.on("sort-files",({key:d,order:m,panel:p,path:g})=>{const{activePanel:v,panels:w}=this.getState();p=p??v,g=g??w[p].path;const x=[];x[p]={_sorts:{...w[p]._sorts,[g]:{key:d,order:m}}},this.setState({panels:x})}),this.initOnce()}initOnce(){const a=[];for(let l=0;l<2;l++)a[l]=Yy({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...a[l]});const r={panels:Yy(a),data:[],search:""};this._router.init(r)}init(a){const r={...a};this._router.init(r)}setState(a,r){return this._router.setState(a,r)}getFile(a){const{data:r}=this.getState();return r.byId(a)||null}serialize(a){const{data:r}=this.getState();return r.serialize(a)}_updatePanels(a,r,l){const{data:c}=this.getState();a.forEach(d=>{const m=[];d.selected.forEach(v=>{c.byId(v)?m.push(v):!l&&r[v]&&m.push(r[v])}),d.selected=m,c.byId(d._lastSelected)||(d._lastSelected=l?null:r[d._lastSelected]||null);const p={};Object.keys(d._sorts).forEach(v=>{c.byId(v)?p[v]=d._sorts[v]:r[v]&&!l&&(p[r[v]]=d._sorts[v])}),d._sorts=p;const g=d._crumbs[d._crumbs.length-1];g?.id!=="/"&&(r[g.id]?d.path=r[g.id]:c.byId(g.id)||(d.path="/"))})}_isPlacedIntoSelf(a,r){return a.some(l=>l===r||this.getState().data.getParents(r).some(c=>c.id===l))}};function $k(n){switch(n){case"body":return[{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"}];case"add":return[{icon:"mdi mdi-folder-plus-outline",text:"Add new file",id:"add-file"},{icon:"mdi mdi-file-plus-outline",text:"Add new folder",id:"add-folder"},{icon:"mdi mdi-file-upload-outline",text:"Upload file",id:"upload",comp:"upload"}];case"multiselect":return[{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{comp:"separator"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}];default:return[n==="folder"?null:{icon:"wxi-download",text:"Download",hotkey:"Ctrl+D",id:"download"},{icon:"wxi-content-copy",text:"Copy",hotkey:"Ctrl+C",id:"copy"},{icon:"wxi-content-cut",text:"Cut",hotkey:"Ctrl+X",id:"move"},{icon:"wxi-content-paste",text:"Paste",hotkey:"Ctrl+V",id:"paste"},{comp:"separator"},{icon:"wxi-edit",text:"Rename",hotkey:"Ctrl+R",id:"rename"},{icon:"wxi-close",text:"Delete",hotkey:"Delete",id:"delete"}].filter(a=>a!==null)}}function Uk(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function qk(n,a="data-id"){const r=Uk(n,a);return r?r.getAttribute(a):null}new Date().valueOf();function Gk(n,a){const{api:r}=a;function l(d,m){const p=a.getPanel(),g=p.selected,v=m.ctrlKey||m.metaKey,w=m.shiftKey;let x;const b=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?x=a.menuOptions("multiselect"):x=a.menuOptions(b.type,b):x=a.menuOptions("body");const C=`${v?"ctrl+":""}${w?"shift+":""}${d}`,j=x?x.find(N=>N.hotkey?.toLowerCase()===C):!1,A=a.performAction;if(j)switch(C){case"ctrl+c":A("copy");break;case"ctrl+x":A("move");break;case"ctrl+v":A("paste",b);break;case"delete":A("delete");break;case"ctrl+r":m.preventDefault(),A("rename",b);break;case"ctrl+d":m.preventDefault(),A("download",b);break;default:j.handler?.({context:b})}switch(d){case"enter":{if(v||w)break;const{_crumbs:N,_selectNavigation:k}=p;if(k){const T=Bk(N);if(T){const R=mp(T,N);r.exec("set-path",{id:T,selected:[R]})}}else if(g.length===1){const T=r.getFile(g[0]);T&&r.exec(T.type==="folder"?"set-path":"open-file",{id:T.id})}break}case"arrowup":case"arrowleft":{const{_files:N,_selected:k,path:T,_selectNavigation:R}=p;let U;if(k.length){const O=k.at(0).id,Y=N.findIndex(_=>_.id===O);if(Y!==-1){const _=Y-1;N[_]?U=N[_].id:T!=="/"&&!(v||w)&&r.exec("select-file",{type:"navigation"})}}else{if(R)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}U=N.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:v,range:w});break}case"arrowdown":case"arrowright":{const{_files:N,_selected:k,path:T,_selectNavigation:R}=p;let U;if(k.length){const O=k.at(-1).id,Y=N.findIndex(_=>_.id===O);if(Y!==-1){const _=Y+1;N[_]&&(U=N[_].id)}}else{if(T!=="/"&&!R){r.exec("select-file",{type:"navigation"});break}U=N.at(0)?.id}U&&r.exec("select-file",{id:U,toggle:v,range:w});break}}}function c(d){const m=d.code.replace("Key","").toLowerCase();l(m,d),m=="tab"&&setTimeout(()=>{const p=document.activeElement;p.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+qk(p,"data-panel")})})}return n.addEventListener("keydown",c),{destroy:()=>{n.removeEventListener("keydown",c)}}}function Vk(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}function Wk(n,a="data-id"){const r=n.getAttribute(a);return r?Yk(r):null}function Yk(n){if(n.startsWith(":"))return n.substring(1);const a=n*1;return isNaN(a)?n:a}function Kk(){return{detect:()=>!0,addEvent:function(n,a,r){return n.addEventListener(a,r),()=>n.removeEventListener(a,r)},addGlobalEvent:function(n,a){return document.addEventListener(n,a),()=>document.removeEventListener(n,a)},getTopNode:function(){return window.document.body}}}var Qk=Kk();new Date().valueOf();function zb(n){const[a,r]=u.useState(n),l=u.useRef(n);return u.useEffect(()=>{if(l.current!==n){if(Array.isArray(l.current)&&Array.isArray(n)&&l.current.length===0&&n.length===0)return;l.current=n,r(n)}},[n]),[a,r]}function Xk(n,a,r){const[l,c]=u.useState(()=>a);return n||console.warn(`Writable ${r} is not defined`),u.useEffect(()=>n?n.subscribe(m=>{c(()=>m)}):void 0,[n]),l}function lt(n,a){const r=n.getState(),l=n.getReactiveState();return Xk(l[a],r[a],a)}function Zk(n,a){const r=u.useRef(a);r.current=a;const[l,c]=u.useState(1);return u.useEffect(()=>n.subscribe(m=>{r.current=m,c(p=>p+1)}),[n]),[r.current,l]}function hs(n,a){const r=n.getState(),l=n.getReactiveState();return Zk(l[a],r[a])}function Ib(n){const a={};return n.split(";").forEach(r=>{const[l,c]=r.split(":");if(c){let d=l.trim();d.indexOf("-")&&(d=d.replace(/-([a-z])/g,(m,p)=>p.toUpperCase())),a[d]=c.trim()}}),a}function Ob(n){let a=n,r=[];return{subscribe:p=>{r.push(p),p(a)},unsubscribe:p=>{r=r.filter(g=>g!==p)},set:p=>{a=p,r.forEach(g=>g(a))},update:p=>{a=p(a),r.forEach(g=>g(a))}}}function Xy(n,a,r){function l(c){const d=Vk(c);if(!d)return;const m=Wk(d);if(typeof a=="function")return a(m,c);let p,g=c.target;for(;g!=d;){if(p=g.dataset?g.dataset.action:null,p&&a[p]){a[p](m,c);return}g=g.parentNode}a[r]&&a[r](m,c)}return Qk.addEvent(n,r,l)}function Jk(n,a){const r=[Xy(n,a,"click")];return a.dblclick&&r.push(Xy(n,a.dblclick,"dblclick")),()=>{r.forEach(l=>l())}}function Hb(n,a){return n.map((r,l)=>{const c=a(r,l);return r.data&&r.data.length&&(c.data=Hb(r.data,a)),c}).filter(Boolean)}function Bb(n,a){const r=[];return n.forEach(l=>{if(l.data){const c=Bb(l.data,a);c.length&&r.push({...l,data:c})}else a(l)&&r.push(l)}),r}function e1(n){return Hb(n,(a,r)=>{const l={...a,id:a.id||ip()};return l.type&&(l.comp=l.type),l.comp==="separator"&&n[r-1]?.comp==="separator"?null:l})}const Fb={};function t1(n){return Fb[n]||n}function n1(n,a){Fb[n]=a}function a1({onClick:n,onShow:a,option:r}){const l=u.useRef(null),c=u.useCallback(()=>{a(r.data?r.id:!1,l.current)},[a,r]),d=u.useCallback(p=>{if(r.data){p.stopPropagation(),a(r.id,l.current);return}n(p)},[n,a,r]),m=u.useMemo(()=>r&&r.comp?t1(r.comp):null,[r]);return s.jsxs("div",{ref:l,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Pn(r.id),onMouseEnter:c,onClick:d,children:[r.icon?s.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?m?s.jsx(m,{item:r,option:r}):null:s.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?s.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?s.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function hp({options:n,left:a=0,top:r=0,at:l="bottom",parent:c=null,mount:d=null,context:m=null,css:p="",onClick:g,onCancel:v}){const[w,x]=u.useState(-1e4),[b,C]=u.useState(-1e4),[j,A]=u.useState(20),[N,k]=u.useState(),T=u.useRef(null),[R,U]=u.useState(!1),[O,Y]=u.useState(null),_=u.useCallback(()=>{const se=Sb(T.current,c,l,a,r);se&&(x(se.x),C(se.y),k(se.width));let K=se?.z??20;const I=c?Gj(c):[];let Q=0;for(const q of I){const V=parseInt(getComputedStyle(q).zIndex,10);V>Q&&(Q=V)}Q>=K&&(K=Q+1),A(K)},[c,l,a,r]);u.useEffect(()=>{d&&d(_)},[]);const D=u.useCallback(()=>{U(!1)},[]),ne=u.useCallback((se,K)=>{U(se),Y(K)},[]),G=u.useMemo(()=>e1(n),[n]);u.useEffect(()=>{_()},[c,_]);const te=u.useRef(g),B=u.useRef(v),xe=u.useRef(c);return u.useEffect(()=>{te.current=g},[g]),u.useEffect(()=>{B.current=v},[v]),u.useEffect(()=>{xe.current=c},[c]),u.useEffect(()=>{if(!T.current)return;function se(K){B.current?B.current(K):te.current&&te.current({action:null,option:null})}return ni(T.current,{callback:se,modal:!0,parent:()=>xe.current}).destroy},[]),s.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${p}`,style:{position:"absolute",top:b+"px",left:w+"px",width:N,zIndex:j},onMouseLeave:D,children:G.map(se=>s.jsxs(u.Fragment,{children:[se.comp==="separator"?s.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):s.jsx(a1,{option:se,onShow:ne,onClick:K=>{if(!se.data&&!K.defaultPrevented){const I={context:m,action:se,option:se,event:K};se.handler&&se.handler(I),g&&g(I),K.stopPropagation()}}}),se.data&&R===se.id?s.jsx(hp,{css:p,options:se.data,at:"right-overlap",parent:O,context:m,onClick:g,onCancel:v}):null]},se.id))})}const Pb=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:g,onClick:v}=n,[w,x]=u.useState(null),[b,C]=u.useState(null),[j,A]=u.useState(0),[N,k]=u.useState(0),T=u.useRef(null),R=u.useMemo(()=>`data-${d.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[d]),U=u.useMemo(()=>w!==null&&m?Bb(r,D=>m(D,w)):r,[w,m,r]);function O(D){C(null),v&&v(D)}function Y(D){if(T.current===D){T.current=null;return}C(null),v&&v({action:null,option:null})}const _=u.useCallback((D,ne)=>{if(!D){C(null);return}if(D.defaultPrevented)return;const G=D.target;if(G&&G.dataset&&G.dataset.menuIgnore)return;if(b&&b===G){C(null),D.preventDefault();return}A(D.clientX+1),k(D.clientY+1);let te=typeof ne<"u"?ne:Gc(G,R);c&&(te=c(te,D),!te)||(x(te),C(G),T.current=D.nativeEvent||D,D.preventDefault())},[b,R,c]);return u.useImperativeHandle(a,()=>({show:_}),[_]),s.jsxs(s.Fragment,{children:[g?s.jsx("span",{onClick:_,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,b?s.jsx(lp,{children:s.jsx(hp,{css:p,at:l,top:N,left:j,parent:b,context:w,onClick:O,onCancel:Y,options:U},b)}):null]})}),s1=u.forwardRef(function(n,a){const{options:r,at:l="bottom",css:c="",children:d,onClick:m}=n,[p,g]=u.useState(null),v=u.useRef(null);function w(j){g(null),m&&m(j)}function x(j){if(v.current===j){v.current=null;return}g(null),m&&m({action:null,option:null})}const b=u.useCallback(j=>{g(j.target),v.current=j.nativeEvent||j,j.preventDefault()},[]);u.useImperativeHandle(a,()=>({show:b}),[b]);function C(j){let A=j.target;for(;!A.dataset.menuIgnore;)g(A),A=A.parentNode}return s.jsxs(s.Fragment,{children:[s.jsx("span",{onClick:C,"data-menu-ignore":"true",children:d}),p?s.jsx(lp,{children:s.jsx(hp,{css:c,at:l,parent:p,options:r,onClick:w,onCancel:x})}):null]})}),i1=u.forwardRef(function(n,a){const{options:r,at:l="bottom",resolver:c=null,dataKey:d="contextId",filter:m=null,css:p="",children:g,onClick:v}=n,w=u.useRef(null),x=u.useCallback((b,C)=>{w.current.show(b,C)},[]);return u.useImperativeHandle(a,()=>({show:x}),[x]),s.jsxs(s.Fragment,{children:[g?s.jsx("span",{onContextMenu:x,"data-menu-ignore":"true",children:g}):null,s.jsx(Pb,{css:p,at:l,options:r,resolver:c,dataKey:d,filter:m,ref:w,onClick:v})]})}),r1={uploader:{B:"B",KB:"KB",MB:"MB",GB:"GB",TB:"TB",PB:"PB",EB:"EB","Drop files here or":"Drop files here or","select files":"select files"}};let l1=class{constructor(a,r,l,c,d){this.setFiles=a,this.setReady=r,this.setSignal=l,this.setDrag=c,d&&d.length&&this.setFiles(d)}open(a){this.setSignal(["click",a||{}])}getState(){let a="server";const r=this.files;for(let l=0;l<r.length;l++){if(r[l].status==="client")return"client";r[l].status==="error"&&(a="error")}return a}droparea(a,r){r=r||{};const l=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},c=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},d=p=>{p.preventDefault()},m=p=>{p.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,p]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return a.addEventListener("dragenter",l),a.addEventListener("dragleave",c),a.addEventListener("dragover",d,!0),a.addEventListener("drop",m,!0),()=>{a.removeEventListener("dragenter",l),a.removeEventListener("dragleave",c),a.removeEventListener("dragover",d,!0),a.removeEventListener("drop",m,!0)}}updateFile(a,r){const l=this.files.findIndex(d=>d.id===a);if(l===-1)return;const c=[...this.files];return c[l]={...c[l],...r},this.files=c,this.setFiles(this.files),this.files[l]}deleteFile(a){this.files=this.files.filter(r=>r.id!==a),this.setFiles(this.files)}addFile(a,r){r?this.files=[...this.files,a]:this.files=[a],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function $b(n){const[a,r]=u.useState([]),[l,c]=u.useState(Promise.resolve(null)),[d,m]=u.useState(null),[p,g]=u.useState(!1),v=u.useRef();return v.current||(v.current=new l1(r,c,m,g,n)),v.current.files=a,v.current.ready=l,v.current.signal=d,v.current.drag=p,v.current}function o1(n,a){{if(n){const r=n.getGroup(a);if(r)return r}return Wc(r1).getGroup(a)}}const c1=()=>Math.random().toString(36).substr(2,9),u1=({data:n,accept:a="",multiple:r=!0,folder:l=!1,uploadURL:c="",apiOnly:d=!1,disabled:m=!1,children:p,onChange:g,onUpload:v})=>{const w=u.useRef(null),x=u.useRef(null),[b,C]=u.useState({}),j=$b(),A=n||j,N=u.useContext(Un.i18n),k=o1(N,"uploader");u.useEffect(()=>{w.current&&l&&(w.current.webkitdirectory=!0)},[l]),u.useEffect(()=>{if(!d&&x.current&&!m)return A.droparea(x.current)},[d,m,x]);const T=G=>{const te=new FormData;return te.append("upload",G.file),fetch(c,{method:"POST",body:te}).then(B=>B.json()).then(B=>({id:G.id,...B}),()=>({id:G.id,status:"error"})).catch(B=>(console.log(B),{id:G.id,status:"error"}))},R=(G,te)=>{const B=A.updateFile(G,te),xe={...B,status:A.getState()};B&&B.uploaded&&B.uploaded(xe),v&&v(xe),B.temp&&A.deleteFile(B.id)},U=G=>{if(!G)return;const te=typeof c=="function"?c(G):T(G);A.setReady(te.then(B=>{B.status=B.status||"server",R(G.id,B)}).catch(B=>{R(G.id,{status:"error",error:B})}))},O=(G,te)=>{const B={...te||b,id:c1(),status:"client",name:G.name,file:G};B.selected&&B.selected(B),g&&g(B),A.addFile(B,r),U(B),w.current&&(w.current.value="")},Y=(G,te,B)=>{G.isFile?G.file(xe=>{O(xe,B)}):G.isDirectory&&G.createReader().readEntries(xe=>{xe.forEach(se=>{Y(se,te+se.name+"/",B)})})},_=G=>{Array.from(G.target.files).forEach(te=>O(te))},D=(G,te)=>{Array.from(G.dataTransfer.items).forEach(B=>{const xe=B.webkitGetAsEntry();xe&&Y(xe,"",te)})},ne=()=>{w.current&&w.current.click()};return u.useEffect(()=>{if(A.signal){const[G,te,B]=A.signal;C(te),G==="click"?ne():G==="drop"&&D(B,te),A.setSignal(null)}},[A.signal]),d?s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p]}):s.jsxs("div",{className:`wx-at1A8tb8 wx-label ${A.drag?"wx-active":""} ${m?"wx-disabled":""}`,ref:x,children:[s.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:_,accept:a,multiple:r,disabled:m}),p||s.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:s.jsxs("span",{children:[k("Drop files here or")," ",s.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:ne,children:k("select files")})]})})]})};new Date().valueOf();function d1(n,a){if(Object.keys(n).length!==Object.keys(a).length)return!1;for(const r in a){const l=n[r],c=a[r];if(!rf(l,c))return!1}return!0}function rf(n,a){if(typeof n=="number"||typeof n=="string"||typeof n=="boolean"||n===null)return n===a;if(typeof n!=typeof a||(n===null||a===null)&&n!==a||n instanceof Date&&a instanceof Date&&n.getTime()!==a.getTime())return!1;if(typeof n=="object")if(Array.isArray(n)&&Array.isArray(a)){if(n.length!==a.length)return!1;for(let r=n.length-1;r>=0;r--)if(!rf(n[r],a[r]))return!1;return!0}else return d1(n,a);return n===a}function Ih(n){if(typeof n!="object"||n===null)return n;if(n instanceof Date)return new Date(n);if(n instanceof Array)return n.map(Ih);const a={};for(const r in n)a[r]=Ih(n[r]);return a}var Ub=2,f1=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,a=0){const r={};return this._wrapProperties(n,this._state,this._values,"",r,a),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,a,r,l,c,d){for(const m in n){const p=a[m],g=r[m],v=n[m];if(p&&(g===v&&typeof v!="object"||v instanceof Date&&g instanceof Date&&g.getTime()===v.getTime()))continue;const w=l+(l?".":"")+m;p?(p.__parse(v,w,c,d)&&(r[m]=v),d&Ub?c[w]=p.__trigger:p.__trigger()):(v&&v.__reactive?a[m]=this._wrapNested(v,v,w,c):a[m]=this._wrapWritable(v),r[m]=v),c[w]=c[w]||null}}_wrapNested(n,a,r,l){const c=this._wrapWritable(n);return this._wrapProperties(n,c,a,r,l,0),c.__parse=(d,m,p,g)=>(this._wrapProperties(d,c,a,m,p,g),!1),c}_wrapWritable(n){const a=[],r=function(){for(let l=0;l<a.length;l++)a[l](n)};return{subscribe:l=>(a.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const c=a.indexOf(l);c>=0&&a.splice(c,1)}),__trigger:()=>{a.length&&(this._async?setTimeout(r,1):r())},__parse:function(l){return n=l,!0}}}},m1=class{constructor(n,a,r,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=a,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(c=>{c.in.forEach(d=>{const m=this._triggers.get(d)||[];m.push(c),this._triggers.set(d,m)}),c.out.forEach(d=>{const m=this._sources.get(d)||{};c.in.forEach(p=>m[p]=!0),this._sources.set(d,m)})}),this._routes.forEach(c=>{c.length=Math.max(...c.in.map(d=>qb(d,this._sources,1)))}),this._bus=l}init(n){const a={};for(const r in n)if(this._prev[r]!==n[r]){const l=this._parsers[r];a[r]=l?l(n[r]):n[r]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(a),this._bus&&this._bus.exec("init-state",a)}setStateAsync(n){const a=this._setter(n,Ub);return this._async?Object.assign(this._async.signals,a):this._async={signals:a,timer:setTimeout(this._applyState.bind(this),1)},a}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const a in n.signals){const r=n.signals[a];r&&r()}}}setState(n,a=[]){const r=this._setter(n);return this._triggerUpdates(r,a),r}_triggerUpdates(n,a){const r=Object.keys(n),l=!a.length;a=a||[];for(let c=0;c<r.length;c++){const d=r[c],m=this._triggers.get(d);m&&m.forEach(p=>{a.indexOf(p)==-1&&a.push(p)})}l&&this._execNext(a)}_execNext(n){for(;n.length;){n.sort((r,l)=>r.length<l.length?1:-1);const a=n[n.length-1];n.splice(n.length-1),a.exec(n)}}};function qb(n,a,r){const l=a.get(n);if(!l)return r;const c=Object.keys(l).map(d=>qb(d,a,r+1));return Math.max(...c)}var h1=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,a,r){let l=this._handlers[n];l?r&&r.intercept?l.unshift(a):l.push(a):l=this._handlers[n]=[a],r&&r.tag&&this._tag.set(a,r.tag)}intercept(n,a,r){this.on(n,a,{...r,intercept:!0})}detach(n){for(const a in this._handlers){const r=this._handlers[a];for(let l=r.length-1;l>=0;l--)this._tag.get(r[l])===n&&r.splice(l,1)}}async exec(n,a){const r=this._handlers[n];if(r)for(let l=0;l<r.length;l++){const c=r[l](a);if(c===!1||c&&c.then&&await c===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,a),a}setNext(n){return this._nextHandler=n}};function p1(n){return a=>a[n]}function g1(n){return(a,r)=>a[n]=r}function Or(n,a){return(a.getter||p1(a.id))(n)}function sh(n,a,r){return(a.setter||g1(a.id))(n,r)}function v1(n,a){const r=document.createElement("a");r.href=URL.createObjectURL(n),r.download=a,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function Ir(n,a){let r=Or(n,a)??"";return a.template?r=a.template(r,n,a):a.optionsMap&&(Array.isArray(r)?r=r.map(l=>a.optionsMap.get(l)).join(", "):r=a.optionsMap.get(r)),typeof r>"u"?"":r+""}function y1(n,a){const r=/\n|"|;|,/;let l="";const c=a.rows||`
|
|
13
13
|
`,d=a.cols||" ",m=n._columns,p=n.flatData;a.header!==!1&&m[0].header&&(l=Zy("header",m,l,d,c));for(let g=0;g<p.length;g++){const v=[];for(let w=0;w<m.length;w++){let x=Ir(p[g],m[w]);r.test(x)&&(x='"'+x.replace(/"/g,'""')+'"'),v.push(x)}l+=(l?c:"")+v.join(d)}return a.footer!==!1&&m[0].footer&&(l=Zy("footer",m,l,d,c)),l}function Zy(n,a,r,l,c){const d=/\n|"|;|,/;for(let m=0;m<a[0][n].length;m++){const p=[];for(let g=0;g<a.length;g++){let v=(a[g][n][m].text||"")+"";d.test(v)&&(v='"'+v.replace(/"/g,'""')+'"'),p.push(v)}r+=(r?c:"")+p.join(l)}return r}const x1="portrait",b1=100,w1="a4",S1={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function C1(n,a){const r=[];let l=[],c=0;const d=n.filter(p=>!p.hidden),m=j1(a);return d.forEach((p,g)=>{c+p.width<=m?(c+=p.width,l.push(p)):(l.length&&r.push(l),l=[p],c=p.width),g===d.length-1&&l.length&&r.push(l)}),r}function Jy(n,a,r){const l=[];return n.forEach((c,d)=>{const m=c[a];for(let p=0;p<r.length;p++){l[p]||(l[p]=[]);const g={...m[p]};if(l[p][d]!==null){if(!d&&!g.rowspan&&!g.colspan){let v=1,w=n[d+v][a][p],x=g.width;for(;!w.rowspan&&!w.colspan;)v++,w=n[d+v][a][p],x+=w.width;g.colspan=v,g.width=x,g.height=r[p]}if(l[p].push(g),!g.collapsed&&g.colspan>1){let v=g.colspan-1;if(g.colspan+d>n.length){const w=g.colspan-(g.colspan+d-n.length);g.colspan=w,g.width=n.slice(d,d+v+1).reduce((x,b)=>x+b.width,0),w>1&&(v=w-1)}for(let w=0;w<v;w++)l[p].push(null)}if(g.rowspan>1){const v=g.rowspan;for(let w=1;w<v;w++)l[p+w]||(l[p+w]=[]),l[p+w].push(null)}}}if(c.collapsed)for(let p=0;p<l.length;p++){const g=l[p],v=g[d];if(v&&v.collapsed){if(g[d]=null,!p)break}else{const w=v||g.findLast(x=>x?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-c.width)}}}),l.map(c=>c.filter(d=>d&&d.colspan!==0))}function j1(n){const{mode:a,ppi:r,paper:l}=n,{width:c,height:d}=S1[l];return k1(a==="portrait"?c:d,r)}function k1(n,a){return n*a}function A1(n={}){const{mode:a,ppi:r,paper:l}=n;return{mode:a||x1,ppi:r||b1,paper:l||w1}}function Gb(n,a){return n.flexgrow?`min-width:${a}px;width:auto`:`width:${n.width}px; max-width:${n.width}px; height:${n.height}px`}function N1(n,a,r){let l=n[r.id];if(r.filter.type==="richselect"&&l){const c=r.filter.config?.options||a.find(({id:d})=>d==r.id).options;c&&(l=c.find(({id:d})=>d==l).label)}return l??""}const ex=["resize-column","hide-column","update-cell"],M1=["delete-row","update-row","update-cell"],T1=["move-item"],E1=["resize-column","move-item"];class R1{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(a,r,l){this.in=a,this.getState=r,this.setState=l,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:a=>({action:"delete-row",data:{id:a.id},source:{action:"add-row",data:a}})},"delete-row":{handler:a=>{const{id:r}=a,{data:l}=this.getPrev(),c=l.findIndex(d=>d.id===r);return{action:"add-row",data:{id:r,row:l[c],before:c<l.length-1?l[c+1].id:void 0},source:{action:"delete-row",data:a}}}},"update-cell":{handler:a=>{const{id:r,column:l}=a,c=this.getRow(r),d=this.getColumn(l),m=Or(c,d);return rf(m,a.value)?null:{action:"update-cell",data:{id:r,column:l,value:m},source:{action:"update-cell",data:a}}}},"update-row":{handler:a=>{const{id:r,row:l}=a,c=this.getRow(r);for(const d in l)Object.keys(c).includes(d)||(c[d]=void 0);return{action:"update-row",data:{id:r,row:c},source:{action:"update-row",data:a}}}},"copy-row":{handler:a=>{const{id:r}=a,{data:l}=this.getState(),c=l.findIndex(m=>m.id===r),d=l[c];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:d,before:c<l.length-1?l[c+1].id:void 0}}}}},"resize-column":{handler:a=>{const{id:r,width:l}=a,c=this.getColumn(r),{_sizes:d}=this.getState();return{action:"resize-column",data:{id:r,width:c.width??d.columnWidth},source:{action:"resize-column",data:{id:r,width:l}}}}},"hide-column":{handler:a=>{const{id:r}=a,l=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:l.hidden},source:{action:"hide-column",data:a}}}},"collapse-column":{handler:a=>{const{id:r,row:l,mode:c}=a;return{action:"collapse-column",data:{id:r,row:l,mode:typeof c=="boolean"?!c:c},source:{action:"collapse-column",data:a}}}},"move-item":{handler:a=>{const{id:r,target:l,mode:c}=a,{flatData:d}=this.getPrev(),m=d.findIndex(p=>p.id===r);return{action:"move-item",data:{id:r,target:d[m+(m?-1:1)].id,mode:m?"after":"before"},source:{action:"move-item",data:{id:r,target:l,mode:c}}}}},"open-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"close-row",data:{id:r,nested:l},source:{action:"open-row",data:a}}}},"close-row":{handler:a=>{const{id:r,nested:l}=a;return{action:"open-row",data:{id:r,nested:l},source:{action:"close-row",data:a}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const a=this.getHandlers();for(const r in a)this.in.intercept(r,l=>{if(!(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo)){if(E1.includes(r)){(l.inProgress&&!this.progress[r]||typeof l.inProgress!="boolean")&&(T1.includes(r)&&this.setPrev("flatData"),ex.includes(r)&&this.setPrev("columns")),this.progress[r]=l.inProgress;return}M1.includes(r)&&this.setPrev("data"),ex.includes(r)&&this.setPrev("columns")}}),this.in.on(r,l=>{if(l.eventSource==="undo"||l.eventSource==="redo"||l.skipUndo||l.inProgress)return;const c=a[r].handler(l);c&&this.addToHistory(c)})}setPrev(a){this._previousValues[a]=Ih(this.getState()[a])}addToHistory(a){this.undo.push(a),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const a=this.undo.pop();this.redo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const a=this.redo.pop();this.undo.push({...a.source,source:a}),this.in.exec(a.action,{...a.data,eventSource:"redo"}),this.setStateHistory()}resetStateHistory(){this.setState({history:{undo:0,redo:0}})}setStateHistory(){this.setState({history:{undo:this.undo.length,redo:this.redo.length}})}getRow(a){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,a):r.find(l=>l.id===a)}getTreeRow(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a[l];if(a[l].data){const c=this.getTreeRow(a[l].data,r);if(c)return c}}return null}getColumn(a){const{columns:r}=this.getPrev();return r.find(l=>l.id===a)}}function Vb(n,a){return typeof n>"u"||n===null?-1:typeof a>"u"||a===null?1:n===a?0:n>a?1:-1}function D1(n,a){return-Vb(n,a)}function L1(n,a){if(typeof a.sort=="function")return function(l,c){const d=a.sort(l,c);return n==="asc"?d:-d};const r=n==="asc"?Vb:D1;return function(l,c){return r(Or(l,a),Or(c,a))}}function _1(n,a){if(!n||!n.length)return;const r=n.map(l=>{const c=a.find(d=>d.id==l.key);return L1(l.order,c)});return n.length===1?r[0]:function(l,c){for(let d=0;d<r.length;d++){const m=r[d](l,c);if(m!==0)return m}return 0}}const wd=28,z1=20;function I1(){if(typeof document>"u")return"willow";const n=document.querySelector('[class^="wx"][class$="theme"]');return n?n.className.substring(3,n.className.length-6):"willow"}function Yd(n,a,r,l,c){const d=document.createElement("div"),m=document.createElement("div"),p=document.body;c=c?`${c}px`:"auto";let g,v;m.className=a,d.classList.add(`wx-${r}-theme`),d.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${c};white-space:nowrap;`,d.appendChild(m),p.appendChild(d),typeof n!="object"&&(n=[n]);for(let w=0;w<n.length;w++){m.innerText=n[w]+"";const x=d.getBoundingClientRect(),b=Math.ceil(x.width)+(l&&l.length?l[w]:0),C=Math.ceil(x.height);g=Math.max(g||0,b),v=Math.max(v||0,C)}return d.remove(),{width:g,height:v}}function tx(n,a,r,l,c){const d=[];for(let m=0;m<n.length;m++){const p=n[m][a],g=p.length;for(let v=0;v<g;v++){const{text:w,vertical:x,collapsed:b,rowspan:C,css:j}=p[v];if(!w){d[v]=Math.max(d[v]||0,l);continue}let A=0;if(x&&!b){let N=`wx-measure-cell-${a}`;if(N+=j?` ${j}`:"",A=Yd(w,N,c).width,(C>1||!p[v+1])&&r>v+1){const k=C||r-v,T=d.slice(v,v+k).reduce((R,U)=>R+U,0);if(T<A){const R=Math.ceil((A-T)/k);for(let U=v;U<v+k;U++)d[U]=(d[U]||l)+R}continue}}d[v]=Math.max(d[v]||l,A)}}return d}function O1(n,a,r){const l=[],c=[];let d="wx-measure-cell-body";d+=n.css?` ${n.css}`:"";for(let m=0;m<a.length;m++){const p=a[m],g=Ir(p,n);g&&(l.push(g),n.treetoggle?c.push(a[m].$level*wd+(a[m].$count?wd:0)+(n.draggable?wd:0)):n.draggable&&c.push(wd))}return Yd(l,d,r,c).width}function H1(n,a){const r="wx-measure-cell-header",l=n.sort?z1:0;let c=n.header;if(typeof c=="string")return Yd(c,r,a).width+l;let d;Array.isArray(c)||(c=[c]);for(let m=0;m<c.length;m++){const p=c[m],g=typeof p=="string"?p:p.text,v=r+(typeof p=="string"?"":` ${p.css}`);let w=Yd(g,v,a).width;m===c.length-1&&(w+=l),d=Math.max(d||0,w)}return d}const B1={text:(n,a)=>n?n.toString().toLowerCase().indexOf(a.toLowerCase())!==-1:!a,richselect:(n,a)=>typeof a!="number"&&!a?!0:n==a,datepicker:(n,a)=>a?n&&P1(n,a):!0,multiselect:(n,a)=>!a||a?.length===0?!0:Array.isArray(n)?n?.some(r=>a.includes(r)):n&&a.includes(n)};function Wb(n){return B1[n]}function F1(n,a){const r=[];for(const l in n){const c=a.find(g=>g.id==l),{config:d,type:m}=c.header.find(g=>g.filter).filter,p=n[l];r.push(g=>{const v=Or(g,c);return d?.handler?d.handler(v,p):Wb(m)(v,p)})}return l=>{for(let c=0;c<r.length;c++)if(!r[c](l))return!1;return!0}}function P1(n,a){return n.getFullYear()===a.getFullYear()&&n.getMonth()===a.getMonth()&&n.getDate()===a.getDate()}let $1=class extends f1{in;_router;_branches;_xlsxWorker;_historyManager;constructor(a){super({writable:a,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new m1(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:c=>{const{columns:d,sizes:m,_skin:p}=this.getState(),g=this.copyColumns(d),v=g.reduce((b,C)=>Math.max(C.header.length,b),0),w=g.reduce((b,C)=>Math.max(C.footer.length,b),0);g.forEach(this.setCollapsibleColumns);const x=this.normalizeSizes(g,m,v,w,p);for(let b=0;b<g.length;b++)this.normalizeColumns(g,b,"header",v,x),this.normalizeColumns(g,b,"footer",w,x);this.setState({_columns:g,_sizes:x},c)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:c=>{const{data:d,tree:m,dynamic:p,_filterIds:g}=this.getState(),v=g&&new Set(g),w=m?this.flattenRows(d,[],g):v?d.filter(b=>v.has(b.id)):d,x=!p&&w.some(b=>b.rowHeight);this.setState({flatData:w,_rowHeightFromData:x},c)}}],{sizes:c=>({...r,...c})});const l=this.in=new h1;l.on("close-editor",({ignore:c})=>{const{editor:d}=this.getState();d&&(c||l.exec("update-cell",d),this.setState({editor:null}))}),l.on("open-editor",({id:c,column:d})=>{let m=this.getState().editor;m&&l.exec("close-editor",{});const p=this.getRow(c),g=d?this.getColumn(d):this.getNextEditor(p);if(g?.editor){let v=g.editor;if(typeof v=="function"&&(v=v(p,g)),!v)return;m={column:g.id,id:c,value:Or(p,g)??"",renderedValue:Ir(p,g),type:v.type||v},typeof v=="object"&&v.config&&(m.config=v.config,v.config.options&&(m.options=v.config.options)),g.options&&!m.options&&(m.options=g.options),this.setState({editor:m})}}),l.on("editor",({value:c})=>{let d=this.getState().editor;if(d){d={...d},d.value=c;const m=this.getColumn(d.column),p={...this.getRow(d.id)};sh(p,m,c),d.renderedValue=Ir(p,m),this.setState({editor:d})}}),l.on("add-row",c=>{const d=this.getState();let{data:m}=d;const{select:p,_filterIds:g}=d,{row:v,before:w,after:x,select:b}=c;if(c.id=v.id=c.id||v.id||Sd(),w||x){const j=w||x,A=m.findIndex(N=>N.id===j);m=[...m],m.splice(A+(x?1:0),0,c.row)}else m=[...m,c.row];const C={data:m};g&&(C._filterIds=[...g,c.id]),this.setState(C),!(typeof b=="boolean"&&!b)&&(b||p)&&l.exec("select-row",{id:v.id,show:!0})}),l.on("delete-row",c=>{const{data:d,selectedRows:m,focusCell:p,editor:g}=this.getState(),{id:v}=c,w={data:d.filter(x=>x.id!==v)};this.isSelected(v)&&(w.selectedRows=m.filter(x=>x!==v)),g?.id===v&&(w.editor=null),this.setState(w),p?.row===v&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),l.on("update-cell",c=>{const d=this.getState();let{data:m}=d;m=[...m];const{tree:p}=d,{id:g,column:v,value:w}=c,x=this.getColumn(v);if(p){const b={...this._branches[g]};sh(b,x,w);const C=this.updateTreeRow(b);b.$parent===0&&(m=C)}else{const b=m.findIndex(j=>j.id===g),C={...m[b]};sh(C,x,w),m[b]=C}this.setState({data:m})}),l.on("update-row",c=>{let{data:d}=this.getState();const{id:m,row:p}=c,g=d.findIndex(v=>v.id===m);d=[...d],d[g]={...d[g],...p},this.setState({data:d})}),l.on("select-row",({id:c,toggle:d,range:m,mode:p,show:g,column:v})=>{const w=this.getState(),{focusCell:x}=w;let{selectedRows:b}=w;if(b.length||(m=d=!1),m){const{data:C}=this.getState();let j=C.findIndex(N=>N.id===b[b.length-1]),A=C.findIndex(N=>N.id===c);j>A&&([j,A]=[A,j]),C.slice(j,A+1).forEach(N=>{this.isSelected(N.id)||b.push(N.id)})}else if(d&&this.isSelected(c)){if(p===!0)return;b=b.filter(C=>C!==c)}else if(d){if(p===!1)return;b.push(c)}else b=[c];this.setState({selectedRows:[...b]}),x?.row!==c&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:c,column:v})}),this.in.on("focus-cell",c=>{const{row:d,column:m,eventSource:p}=c,{_columns:g,split:v}=this.getState();d&&m?(this.setState({focusCell:{row:d,column:m}}),p!=="click"&&((!v.left||g.findIndex(w=>w.id===c.column)>=v.left)&&(!v.right||g.findIndex(w=>w.id===c.column)<g.length-v.right)?this.in.exec("scroll",{row:d,column:m}):this.in.exec("scroll",{row:d}))):this.setState({focusCell:null})}),l.on("resize-column",c=>{const{id:d,auto:m,maxRows:p,inProgress:g}=c;if(g===!1)return;let v=c.width||0;const w=[...this.getState().columns],x=this.getColumn(d);if(m){if(m==="data"||m===!0){const{flatData:b,_skin:C}=this.getState();let j=b.length;p&&(j=Math.min(p,j));const A=b.slice(0,j);v=O1(x,A,C)}if(m==="header"||m===!0){const{_skin:b}=this.getState();v=Math.max(H1(x,b),v)}}x.width=Math.max(17,v),delete x.flexgrow,this.setState({columns:w})}),l.on("hide-column",c=>{const{id:d,mode:m}=c,p=[...this.getState().columns],g=this.getColumn(d),v=p.reduce((w,x)=>w+(x.hidden?0:1),0);!m||v>1?(g.hidden=!g.hidden,this.setState({columns:p})):c.skipUndo=!0}),l.on("sort-rows",c=>{const{key:d,add:m,sort:p}=c,g=this.getState(),{columns:v,data:w,tree:x}=g;if(p){const T=[...w];T.sort(p),this.setState({data:T});return}const{order:b="asc"}=c;let C=g.sortMarks;const j=Object.keys(C),A=j.length;!m||!A||A===1&&C[d]?C={[d]:{order:b}}:(A===1&&(C[j[0]]={...C[j[0]],index:0}),C={...C,[d]:{order:b,index:typeof m=="number"?m:C[d]?.index??A}});const N=Object.keys(C).sort((T,R)=>C[T].index-C[R].index).map(T=>({key:T,order:C[T].order}));this.setState({sortMarks:C});const k=_1(N,v);if(k){const T=[...w];x?this.sortTree(T,k):T.sort(k),this.setState({data:T})}}),l.on("filter-rows",c=>{const{value:d,key:m,filter:p}=c;if(!Object.keys(c).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:v,tree:w,_columns:x}=g;let b=g.filterValues;const C={};m&&(b={...b,[m]:d},C.filterValues=b);const j=p??F1(b,x);let A=[];w?A=this.filterTree(v,j,A):v.forEach(N=>{j(N)&&A.push(N.id)}),C._filterIds=A,this.setState(C)}),l.on("collapse-column",c=>{const{id:d,row:m,mode:p}=c,g=[...this.getState().columns],v=this.getColumn(d).header,w=Array.isArray(v)?v[m]:v;typeof w=="object"&&(w.collapsed=p??!w.collapsed,this.setState({columns:g}))}),l.on("move-item",c=>{const{id:d,inProgress:m}=c;let{target:p,mode:g="after"}=c;const{data:v,flatData:w,tree:x}=this.getState(),b=w.findIndex(A=>A.id===d);let C;if(g==="up"||g==="down"){if(g==="up"){if(b===0)return;C=b-1,g="before"}else if(g==="down"){if(b===w.length-1)return;C=b+1,g="after"}p=w[C]&&w[C].id}else C=w.findIndex(A=>A.id===p);if(b===-1||C===-1||m===!1)return;let j;x||(j=this.moveItem(d,p,v,g)),this.setState({data:x?this.normalizeTreeRows(j):j})}),l.on("copy-row",c=>{const{id:d,target:m,mode:p="after"}=c,g=this.getState(),{flatData:v,_filterIds:w}=g;let{data:x}=g;const b=this.getRow(d);if(!b)return;const C={...b,id:Sd()};c.id=C.id;const j=v.findIndex(N=>N.id===m);if(j===-1)return;x.splice(j+(p==="after"?1:0),0,C),x=[...x];const A={data:x};w&&(A._filterIds=[...w,C.id]),this.setState(A)}),l.on("open-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!0,m)}),l.on("close-row",c=>{const{id:d,nested:m}=c;this.toggleBranch(d,!1,m)}),l.on("export-data",c=>new Promise((d,m)=>{const p=c.format||"csv",g=`${c.fileName||"data"}.${p}`;if(p==="csv"){const v=y1(this.getState(),c.csv||{});c.download!==!1?v1(new Blob(["\uFEFF"+v],{type:"text/csv"}),g):c.result=v,d(!0)}else m()})),l.on("hotkey",({key:c,event:d,isInput:m})=>{switch(c){case"arrowup":{const{flatData:p,focusCell:g,select:v}=this.getState();if(d.preventDefault(),m)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,x=g?this.getPrevRow(g.row)?.id:p[p.length-1]?.id;w&&x&&(this.in.exec("focus-cell",{row:x,column:w,eventSource:"key"}),v&&this.in.exec("select-row",{id:x}));break}case"arrowdown":{const{flatData:p,focusCell:g,select:v}=this.getState();if(d.preventDefault(),m)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,x=g?this.getNextRow(g.row)?.id:p[0]?.id;w&&x&&(this.in.exec("focus-cell",{row:x,column:w,eventSource:"key"}),v&&this.in.exec("select-row",{id:x}));break}case"arrowright":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const g=this.getNextColumn(p.column,!0)?.id;g&&this.in.exec("focus-cell",{row:p.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:p}=this.getState();if(m)return;if(d.preventDefault(),p){const g=this.getPrevColumn(p.column,!0)?.id;g&&this.in.exec("focus-cell",{row:p.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:p,focusCell:g,select:v}=this.getState();if(p){d.preventDefault();const w=p.column;let x=p.id,b=this.getNextEditor(this.getRow(x),this.getColumn(w));if(!b){const C=this.getNextRow(x);C&&(x=C.id,b=this.getNextEditor(C))}b&&(this.in.exec("open-editor",{id:x,column:b.id}),this.in.exec("focus-cell",{row:x,column:b.id,eventSource:"key"}),v&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:p,focusCell:g,select:v}=this.getState();if(p){d.preventDefault();const w=p.column;let x=p.id,b=this.getPrevEditor(this.getRow(x),this.getColumn(w));if(!b){const C=this.getPrevRow(x);C&&(x=C.id,b=this.getPrevEditor(C))}b&&(this.in.exec("open-editor",{id:x,column:b.id}),this.in.exec("focus-cell",{row:x,column:b.id,eventSource:"key"}),v&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:p}=this.getState();p&&(this.in.exec("close-editor",{ignore:p.type!="multiselect"}),this.in.exec("focus-cell",{row:p.id,column:p.column,eventSource:"key"}));break}case"f2":{const{editor:p,focusCell:g}=this.getState();!p&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:p,tree:g}=this.getState();if(!m&&g&&p&&this.getColumn(p.column).treetoggle){const v=this.getRow(p.row);if(!v.data)return;this.in.exec(v.open?"close-row":"open-row",{id:p.row,nested:!0})}break}case"home":{const{editor:p,focusCell:g}=this.getState();if(!p&&g){d.preventDefault();const v=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:v,eventSource:"key"})}break}case"ctrl+home":{const{editor:p,focusCell:g,flatData:v,select:w}=this.getState();if(!p&&g){d.preventDefault();const x=v[0]?.id,b=this._getFirstVisibleColumn()?.id;x&&b&&(this.in.exec("focus-cell",{row:x,column:b,eventSource:"key"}),w&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}break}case"end":{const{editor:p,focusCell:g}=this.getState();if(!p&&g){d.preventDefault();const v=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:v,eventSource:"key"})}break}case"ctrl+end":{const{editor:p,focusCell:g,flatData:v,select:w}=this.getState();if(!p&&g){d.preventDefault();const x=v.at(-1).id,b=this._getLastVisibleColumn()?.id;x&&b&&(this.in.exec("focus-cell",{row:x,column:b,eventSource:"key"}),w&&!this.isSelected(x)&&this.in.exec("select-row",{id:x}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),l.on("scroll",c=>{const{_columns:d,split:m,_sizes:p,flatData:g,dynamic:v,_rowHeightFromData:w}=this.getState();let x=-1,b=-1,C=0,j=0;if(c.column){x=0;const A=d.findIndex(N=>N.id===c.column);C=d[A].width;for(let N=m.left??0;N<A;N++){const k=d[N];k.hidden||(x+=k.width)}}if(c.row&&!v){const A=g.findIndex(N=>N.id===c.row);A>=0&&(w?(b=g.slice(0,A).reduce((N,k)=>N+(k.rowHeight||p.rowHeight),0),j=g[A].rowHeight):b=p.rowHeight*A)}this.setState({scroll:{top:b,left:x,width:C,height:j||p.rowHeight}})}),l.on("scroll-to",c=>{const d={};c.top!==void 0&&(d.scrollTop=c.top),c.left!==void 0&&(d.scrollLeft=c.left),Object.keys(d).length&&this.setState(d)}),l.on("print",c=>{const d=A1(c);this.setState({_print:d}),this.setStateAsync({_print:null})}),l.on("undo",()=>{this._historyManager?.handleUndo()}),l.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(a){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${a}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(l=>{const c=new Worker(r);c.addEventListener("message",d=>{d.data.type==="init"&&l(c)})})}return this._xlsxWorker}initOnce(){const a={sortMarks:{},_filterIds:null,data:[],filterValues:{},scroll:null,scrollLeft:0,scrollTop:0,editor:null,focusCell:null,_print:null,history:{undo:0,redo:0},search:null};this._router.init(a)}init(a){a.hasOwnProperty("_skin")&&!a._skin&&(a._skin=I1()),a.columns&&a.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(l=>[l.id,l.label])))}),rf(this.getState().data,a.data)||(a.tree?a.data=this.normalizeTreeRows(a.data):a.data=this.normalizeRows(a.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),a.tree&&(a.undo=!1,a.reorder=!1),a.split?.right&&(a.split.right=0),a.undo&&!this._historyManager&&(this._historyManager=new R1(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...a})}setState(a,r){return this._router.setState(a,r)}setStateAsync(a){this._router.setStateAsync(a)}getRow(a){const{tree:r}=this.getState();return r?this._branches[a]:this.getState().data.find(l=>l.id===a)}getRowIndex(a,r){return r||(r=this.getState().flatData),r.findIndex(l=>l.id===a)}getNextRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l+1]}getPrevRow(a){const r=this.getState().flatData,l=this.getRowIndex(a,r);return r[l-1]}getColumn(a){return this.getState().columns.find(r=>r.id===a)}getNextColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getFirstVisibleColumn(c+1):l[c+1]}getPrevColumn(a,r){const l=this.getState()._columns,c=l.findIndex(d=>d.id===a);return r?this._getLastVisibleColumn(c-1):l[c-1]}_getFirstVisibleColumn(a){const r=this.getState()._columns;let l=a??0;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l++;return r[l]}_getLastVisibleColumn(a){const r=this.getState()._columns;let l=a??r.length-1;for(;l<r.length&&(r[l]?.hidden||r[l]?.collapsed);)l--;return r[l]}isCellEditable(a,r){const{editor:l,hidden:c}=r;return!l||c?!1:typeof l=="function"?l(a,r):!0}getNextEditor(a,r){let l=this.getState().columns;if(r){const c=l.findIndex(d=>d.id===r.id);l=l.slice(c+1)}return l.find(c=>this.isCellEditable(a,c))}getPrevEditor(a,r){let l=this.getState().columns;if(r){const c=l.findLastIndex(d=>d.id===r.id);l=l.slice(0,c)}return l.findLast(c=>this.isCellEditable(a,c))}toggleBranch(a,r,l){let c=this._branches[a],{data:d}=this.getState();if(d=[...d],a!==0){c={...c,open:r};const m=this.updateTreeRow(c);c.$parent===0&&(d=m)}l&&c.data?.length&&c.data.forEach(m=>{const p=this.toggleKids(m,r,l);a===0&&(d=p)}),this.setState({data:d})}toggleKids(a,r,l){a={...a,open:r};const c=this.updateTreeRow(a);return l&&a.data?.length&&a.data.forEach(d=>{this.toggleKids(d,r,l)}),c}updateTreeRow(a){const r=a.id;this._branches[r]=a;const l=this._branches[a.$parent],c=l.data.findIndex(d=>d.id===r);return l.data=[...l.data],l.data[c]=a,l.data}isSelected(a){return this.getState().selectedRows.indexOf(a)!==-1}findAndRemove(a,r){for(let l=0;l<a.length;l++){if(a[l].id===r)return a.splice(l,1)[0];if(a[l].data){const c=[...a[l].data],d=this.findAndRemove(c,r);if(d)return a[l]={...a[l],data:c},d}}return null}insertItem(a,r,l,c){for(let d=0;d<a.length;d++){if(a[d].id===r){const m=a[d],p=c==="before"?d:d+1;if(m.data){if(c==="before"){const g=d>0?a[d-1]:null;return g?.data&&g.open?a[d-1]={...g,data:[...g.data,l]}:a.splice(p,0,l),!0}else if(m.open)return a[d]={...m,data:[l,...m.data]},!0}return a.splice(p,0,l),!0}if(a[d].data&&(a[d]={...a[d],data:[...a[d].data]},this.insertItem(a[d].data,r,l,c)))return!0}return!1}moveItem(a,r,l,c){const d=[...l],m=this.findAndRemove(d,a);return this.insertItem(d,r,m,c),d}copyColumns(a){const r=[];for(let l=0;l<a.length;l++){const c={...a[l]};this.copyHeaderFooter(c,"header"),this.copyHeaderFooter(c,"footer"),r[l]=c}return r}copyHeaderFooter(a,r){let l=a[r];l=Array.isArray(l)?[...l]:[l],l.forEach((c,d)=>{l[d]=typeof c=="string"?{text:c}:{...c}}),a[r]=l}setCollapsibleColumns(a,r,l){let c=a.header;for(let d=0;d<c.length;d++){const m=c[d];if(m.collapsible&&m.collapsed){if(m.collapsible!=="first"){a.collapsed=!0,a.width=36,m.vertical=!0;const g=c.length-d;c=c.slice(0,d+1),c[d].rowspan=g}const p=m.colspan;if(p){const g=c[d+1];let v=1;g&&g.colspan&&!g.collapsed&&(v=g.colspan);for(let w=v;w<p;w++){const x=l[r+w];x&&(x.hidden=!0)}}}}}normalizeColumns(a,r,l,c,d){const m=a[r];m.width||(m.width=m.flexgrow?17:d.columnWidth),m._colindex=r+1;const p=m[l],g=d[`${l}RowHeights`];for(let v=0;v<c;v++){const w=p[v];w.id=m.id,v===p.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,c-v):c-v);for(let x=1;x<w.rowspan;x++){p.splice(v+x,0,{_hidden:!0});for(let b=1;b<w.colspan;b++)a[r+b][l].splice(v+x,0,{})}if(w.rowspan){const x=(w.rowspan===c?g:g.slice(v,w.rowspan+v)).reduce((b,C)=>b+C,0);w.height=x,v+w.rowspan!=c&&w.height--}if(w.colspan){let x=m.width,b=m.flexgrow||0;const C=w.colspan;for(let j=1;j<C;j++){const A=a[r+j];A&&(A.hidden?w.colspan-=1:A.flexgrow?b+=A.flexgrow:x+=A.width||d.columnWidth),b?w.flexgrow=b:w.width=x}}else w.width=m.width,w.flexgrow=m.flexgrow;l==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}p.length>c&&(p.length=c),m[l]=p}normalizeRows(a){for(let r=0;r<a.length;r++)a[r].id||(a[r].id=Sd());return a}normalizeTreeRows(a,r,l){return!r&&!l&&(this._branches={0:{data:a}}),a.forEach(c=>{c.id||(c.id=Sd()),c.$level=r||0,c.$parent=l||0,this._branches[c.id]=c,c.data&&(c.data.length?(c.$count=c.data.length,this.normalizeTreeRows(c.data,c.$level+1,c.id)):(delete c.data,delete c.$count,delete c.open))}),a}sortTree(a,r){a.sort(r),a.forEach(l=>{l.data&&this.sortTree(l.data,r)})}filterTree(a,r,l){return a.forEach(c=>{r(c)&&l.push(c.id),c.data&&this.filterTree(c.data,r,l)}),l}flattenRows(a,r,l){const c=r;return a.forEach(d=>{(!l||l.includes(d.id))&&c.push(d),d.data?.length&&d.open!==!1&&this.flattenRows(d.data,c,l)}),c}createFilter(a){const{_columns:r}=this.getState(),l=[];for(const c in a){const d=r.find(v=>v.id==c),{config:m,type:p}=d.header.find(v=>v.filter).filter,g=a[c];l.push(v=>{const w=Or(v,d);return m?.handler?m.handler(w,g):Wb(p)(w,g)})}return c=>{for(let d=0;d<l.length;d++)if(!l[d](c))return!1;return!0}}searchRows(a,r){a=a.trim().toLowerCase();const l={};if(!a)return l;const{flatData:c,columns:d}=this.getState(),m=r?d.filter(p=>r[p.id]):d;return c.forEach(p=>{const g={};m.forEach(v=>{const w=Ir(p,v);String(w).toLowerCase().includes(a)&&(g[v.id]=!0)}),Object.keys(g).length&&(l[p.id]=g)}),l}normalizeSizes(a,r,l,c,d){const m=tx(a,"header",l,r.headerHeight,d),p=tx(a,"footer",c,r.footerHeight,d),g=m.reduce((w,x)=>w+x,0),v=p.reduce((w,x)=>w+x,0);return{...r,headerRowHeights:m,footerRowHeights:p,headerHeight:g,footerHeight:v}}},U1=new Date().valueOf();function Sd(){return"temp://"+U1++}function q1(n,a="data-id"){let r=n;for(!r.tagName&&n.target&&(r=n.target);r;){if(r.getAttribute&&r.getAttribute(a))return r;r=r.parentNode}return null}new Date().valueOf();var G1=class{constructor(){this.store=new Map}configure(n,a){this.node=a;for(const r in n)if(n[r]){const l=r.toLowerCase().replace(/[ ]/g,""),c=n[r];this.store.set(l,c)}}},Eo=[],V1={subscribe:n=>{W1();const a=new G1;return Eo.push(a),n(a),()=>{const r=Eo.findIndex(l=>l===a);r>=0&&Eo.splice(r,1)}}},nx=!1;function W1(){nx||(nx=!0,document.addEventListener("keydown",n=>{if(Eo.length&&(n.ctrlKey||n.altKey||n.metaKey||n.shiftKey||n.key.length>1||n.key===" ")){const a=[];n.ctrlKey&&a.push("ctrl"),n.altKey&&a.push("alt"),n.metaKey&&a.push("meta"),n.shiftKey&&a.push("shift");let r=n.code.replace("Key","").toLocaleLowerCase();n.key===" "&&(r="space"),a.push(r);const l=a.join("+");for(let c=Eo.length-1;c>=0;c--){const d=Eo[c],m=d.store.get(l)||d.store.get(r);m&&d.node.contains(n.target)&&m(n,{key:l,evKey:r})}}}))}const Y1={tab:!0,"shift+tab":!0,arrowup:!0,arrowdown:!0,arrowright:!0,arrowleft:!0,enter:!0,escape:!0,f2:!0,home:!0,end:!0,"ctrl+home":!0,"ctrl+end":!0,"ctrl+z":!0,"ctrl+y":!0};function K1(n,{keys:a,exec:r}){if(!a)return;function l(m){const p=m.target;return p.tagName==="INPUT"||p.tagName==="TEXTAREA"||q1(p,"data-header-id")?.classList.contains("wx-filter")||!!p.closest(".wx-cell.wx-editor")}const c={};for(const m in a){const p=a[m];typeof p<"u"&&(typeof p=="function"?c[m]=p:p&&(c[m]=g=>{const v=l(g);r({key:m,event:g,isInput:v})}))}const d=V1.subscribe(m=>{m.configure(c,n)});return{destroy:()=>{d()}}}function Q1(n,a){let r=null;a.scroll.subscribe(l=>{if(!l||l===r)return;r=l;const{left:c,top:d,height:m,width:p}=l,g=a.getHeight(),v=a.getWidth(),w=a.getScrollMargin();if(d>=0){const x=n.scrollTop;d<x?n.scrollTop=d:d+m>x+g&&(n.scrollTop=d-g+m)}if(c>=0){const x=n.scrollLeft;c<x?n.scrollLeft=c:c+p>x+v-w&&(n.scrollLeft=c-v+p+w)}}),a.scrollLeft?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollLeft-l)>1&&(n.scrollLeft=l)})}),a.scrollTop?.subscribe?.(l=>{requestAnimationFrame(()=>{Math.abs(n.scrollTop-l)>1&&(n.scrollTop=l)})})}const Ka=u.createContext(null);function X1(n,a){const r=new ResizeObserver(l=>{requestAnimationFrame(()=>a(l[0].contentRect))});return r.observe(n.parentNode),{destroy(){r.disconnect()}}}const ax=5,Z1=700;function zd(n){const a=n.getBoundingClientRect(),r=document.body,l=a.top+r.scrollTop-r.clientTop||0,c=a.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(l),x:Math.round(c),width:n.offsetWidth,height:n.offsetHeight}}function Oh(n,a){const r=zd(a);return{x:n.clientX-r.x,y:n.clientY-r.y}}function J1(n,a){const r=a.current;let l=null,c,d,m=!1,p=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function v(){clearTimeout(c),c=null}function w(_){const D=Lo(_);D&&(l={container:g,sourceNode:_.target,from:nf(D),pos:Oh(_,n)},d=l.pos,x(_))}function x(_){if(!l)return;const D=l.pos=Oh(_,n);if(!m){if(!p&&!_?.target?.getAttribute("draggable-data")&&Math.abs(d.x-D.x)<ax&&Math.abs(d.y-D.y)<ax)return;if(O(_)===!1)return Y()}if(p){const ne=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,G=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;l.targetNode=document.elementFromPoint(_.pageX-ne,_.pageY-G)}else l.targetNode=_.target;r.move&&r.move(_,l),g.style.left=-(l.offset?l.offset.x:0)+"px",g.style.top=l.pos.y+(l.offset?l.offset.y:0)+"px"}function b(_){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",m&&r.end&&r.end(_,l),l=d=null,Y()}function C(_){r.getReorder&&!r.getReorder()||_.button===0&&(U(_),window.addEventListener("mousemove",j),window.addEventListener("mouseup",A),w(_))}function j(_){x(_)}function A(_){b(_)}function N(_){if(r.getReorder&&!r.getReorder())return;c=setTimeout(()=>{p=!0,w(_.touches[0])},Z1),U(_);function D(){c&&v(),_.target.removeEventListener("touchmove",k),_.target.removeEventListener("touchend",D),b(_)}_.target.addEventListener("touchmove",k),_.target.addEventListener("touchend",D),n.addEventListener("contextmenu",T)}function k(_){m?(_.preventDefault(),x(_.touches[0])):c&&v()}function T(_){if(m||c)return _.preventDefault(),!1}function R(_){_.preventDefault()}function U(_){if(!r.getDraggableInfo)return;const{hasDraggable:D}=r.getDraggableInfo();(!D||_.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function O(_){if(m=!0,r.start){if(r.start(_,l)===!1)return!1;n.appendChild(g),document.body.style.cursor="move"}}function Y(_){m=p=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",j),window.removeEventListener("mouseup",A),_&&(n.removeEventListener("mousedown",C),n.removeEventListener("touchstart",N),n.removeEventListener("dragstart",R))}return n.addEventListener("mousedown",C),n.addEventListener("touchstart",N),n.addEventListener("dragstart",R),{destroy(){Y(!0)}}}const eA=.004;function tA(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function nA(n,a,r,l){const{node:c,left:d,top:m,bottom:p,sense:g,xScroll:v,yScroll:w}=l,x=Oh(n,c);r.scrollState||(r.scrollState=tA());let b=0,C=0;x.x<d+g?b=-1:x.x>a.width-g&&(b=1),x.y<m+Math.round(g/2)?C=-1:x.y>a.height-p-Math.round(g/2)&&(C=1),(r.scrollState.dirX!==b||r.scrollState.dirY!==C)&&(Yb(r),r.scrollState.dirX=b,r.scrollState.dirY=C),(v&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&aA(r,l,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function aA(n,a,r){n.autoScrollTimer||(n.autoScrollTimer=setTimeout(()=>{n.activeAutoScroll=setInterval(sA,15,n,a,r)},250))}function Yb(n){n.scrollSpeedFactor=1,n.autoScrollTimer&&(n.autoScrollTimer=clearTimeout(n.autoScrollTimer),n.activeAutoScroll=clearInterval(n.activeAutoScroll))}function sA(n,a,r){const{x:l,y:c}=r;n.scrollSpeedFactor+=eA,l!==0&&rA(n,a,l),c!==0&&iA(n,a,c)}function iA(n,a,r){const l=a.node.scrollTop;Kb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollTop",a)}function rA(n,a,r){const l=a.node.scrollLeft;Kb(l+Math.round(a.sense/3)*n.scrollSpeedFactor*r,"scrollLeft",a)}function Kb(n,a,r){r.node[a]=n}function lf(n,a,r,l,c,d){const m={};return n&&(m.width=`${n}px`,m.minWidth=`${n}px`),a&&(m.flexGrow=a),d&&(m.height=`${d}px`),r&&(m.position="sticky",r.left&&(m.left=`${l}px`),r.right&&(m.right=`${c}px`)),m}function Qb(n,a,r){let l="";if(n.fixed)for(const c in n.fixed){let d=n.fixed[c]===-1;!d&&n.fixed.leftSize&&a.colspan&&(d=a.colspan+n._colindex-1===n.fixed.leftSize),l+=d?"wx-shadow ":"wx-fixed "}return l+=a.rowspan>1?"wx-rowspan ":"",l+=a.colspan>1?"wx-colspan ":"",l+=a.vertical?"wx-vertical ":"",l+=r?r(n)+" ":"",l}function lA(n){const{row:a,column:r,cellStyle:l=null,columnStyle:c=null,children:d,focusable:m}=n,p=u.useContext(Ka),g=lt(p,"focusCell"),v=lt(p,"search"),w=lt(p,"reorder"),x=u.useMemo(()=>v?.rows[a.id]&&v.rows[a.id][r.id],[v,a.id,r.id]),b=u.useMemo(()=>lf(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function C(O,Y){let _="wx-cell";return _+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",_+=O?" "+O(r):"",_+=Y?" "+Y(a,r):"",_+=r.treetoggle?" wx-tree-cell":"",_}const j=u.useMemo(()=>C(c,l),[c,l,r,a]),A=u.useMemo(()=>typeof r.draggable=="function"?r.draggable(a,r)!==!1:r.draggable,[r,a]),N=u.useRef(null);u.useEffect(()=>{N.current&&m&&g?.row===a.id&&g?.column===r.id&&N.current.focus()},[g,m,a.id,r.id]);const k=u.useCallback(()=>{m&&!g&&p.exec("focus-cell",{row:a.id,column:r.id,eventSource:"focus"})},[p,m,g,a.id,r.id]);function T(O){const Y=new RegExp(`(${v.value.trim()})`,"gi");return String(O).split(Y).map(_=>({text:_,highlight:Y.test(_)}))}const R=u.useMemo(()=>{const O=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,Y=r.fixed&&r.fixed.right;return[j,O?"wx-shadow":"",Y?"wx-fixed-right":""].filter(Boolean).join(" ")},[j,r]),U=r.cell;return s.jsxs("div",{className:"wx-TSCaXsGV "+R,ref:N,onFocus:k,style:b,"data-row-id":Pn(a.id),"data-col-id":Pn(r.id),tabIndex:m?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?A?s.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):s.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:`${a.$level*28}px`}}),a.$count?s.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${a.open!==!1?"down":"right"}`}):null]}):null,U?s.jsx(U,{api:p,row:a,column:r,onAction:({action:O,data:Y})=>p.exec(O,Y)}):d?d():x?s.jsx("span",{children:T(Ir(a,r)).map(({highlight:O,text:Y},_)=>O?s.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:Y},_):s.jsx("span",{children:Y},_))}):Ir(a,r)]})}function sx(n,a){let r,l;function c(p){r=p.clientX,n.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",d),window.addEventListener("mouseup",m),a&&a.down&&a.down(n)}function d(p){l=p.clientX-r,a&&a.move&&a.move(l)}function m(){n.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",a&&a.up&&a.up(l),window.removeEventListener("mousemove",d),window.removeEventListener("mouseup",m)}return n.addEventListener("mousedown",c),{destroy(){n.removeEventListener("mousedown",c)}}}function oA({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx(cp,{...n.config??{},value:l,onChange:c})}function cA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Ka),d=lt(c,"flatData"),m=u.useMemo(()=>n?.config?.options||a?.options||g(),[n,a,d]),p=u.useMemo(()=>n?.config?.template,[n]);function g(){const x=[];return d.forEach(b=>{const C=Or(b,a);x.includes(C)||x.push(C)}),x.map(b=>({id:b,label:b}))}function v({value:x}){r({value:x,key:a.id})}function w(x){x.key!=="Tab"&&x.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:w,children:s.jsx(Ck,{placeholder:"",clear:!0,...n?.config??{},options:m,value:l,onChange:v,children:x=>p?p(x):x.label})})}function uA({filter:n,column:a,action:r,filterValue:l}){function c({value:d}){r({value:d,key:a.id})}return s.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:s.jsx(Sk,{placeholder:"",clear:!0,...n?.config??{},value:l,onChange:c})})}function Xb(n){const{value:a,options:r=[],placeholder:l="",clear:c=!1,text:d=null,template:m=null,cell:p=null,dropdown:g={},autoOpen:v=!1,onChange:w,onAction:x}=n,[b,C]=zb(a||[]),j=u.useMemo(()=>(b||[]).map(G=>r.find(te=>te.id===G)).filter(Boolean),[b,r]),A=u.useRef(null),N=u.useRef(null),[k,T]=u.useState(null),R=()=>{const G=b||[];if(!G.length)return 0;const te=r.find(B=>G.includes(B.id));return te?r.indexOf(te):0};function U(G){N.current=G.navigate,T(()=>G.keydown),v&&G.navigate(R())}u.useEffect(()=>{v&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function O({id:G}){C(G),w&&w({value:G})}function Y(G){G.stopPropagation(),C([]),w&&w({value:[]})}function _(){N.current?.(R())}function D(){N.current?.(null)}function ne(G){k?.(G,R())}return s.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:_,onKeyDown:ne,tabIndex:0,children:[s.jsx("div",{className:"wx-label wx-aadNNOwy",children:m?m(j):p?s.jsx(p,{data:j,onAction:x}):d?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:d}):j.length?s.jsx("span",{className:"wx-text wx-aadNNOwy",children:j.map(G=>G.label).join(", ")}):l?s.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:l}):" "}),c&&b?.length?s.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:Y}):s.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),s.jsx(sf,{items:r,onReady:U,onSelect:O,multiselect:!0,checkboxes:!0,value:b||[],onCancel:D,...g,children:({option:G})=>s.jsx("div",{className:"wx-option wx-aadNNOwy",children:m?m(G):p?s.jsx(p,{data:G,onAction:x}):G.label})})]})}function dA({filter:n,column:a,action:r,filterValue:l}){const c=u.useContext(Un.i18n)?.getGroup("grid")||Wc(fp).getGroup("grid"),d=u.useMemo(()=>({clear:!0,...n?.config||{}}),[n]),m=u.useMemo(()=>d.options||a.options,[d,a]),p=u.useMemo(()=>{const w=l?.length;return w?w<3?l.map(x=>a.optionsMap.get(x)).join(", "):w+" "+c("selected"):""},[l,a,c]);function g({value:w}){r({value:w,key:a.id})}function v(w){w.key!=="Tab"&&w.preventDefault()}return s.jsx("div",{style:{width:"100%"},onKeyDown:v,children:s.jsx(Xb,{placeholder:"",...d,options:m,value:l||[],text:p,onChange:g})})}const fA={text:oA,richselect:cA,datepicker:uA,multiselect:dA};function mA({filter:n,column:a}){const r=u.useContext(Ka),l=lt(r,"filterValues");function c(m){r.exec("filter-rows",m)}const d=u.useMemo(()=>fA[n.type],[n.type]);return s.jsx(d,{filter:n,column:a,action:c,filterValue:l[a.id]})}function hA(n){const{cell:a,column:r,row:l,lastRow:c,sortRow:d,columnStyle:m,bodyHeight:p,hasSplit:g}=n,v=u.useContext(Ka),w=lt(v,"sortMarks"),x=u.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),b=u.useRef(),C=u.useCallback(se=>{b.current=a.flexgrow?se.parentNode.clientWidth:a.width},[a.flexgrow,a.width]),j=u.useCallback((se,K)=>{v.exec("resize-column",{id:a.id,width:Math.max(1,(b.current||0)+se),inProgress:K})},[v,a.id]),A=u.useCallback(se=>j(se,!0),[j]),N=u.useCallback(se=>j(se,!1),[j]),k=u.useCallback(se=>{if(!r.sort||a.filter)return;let K=x?.order;K&&(K=K==="asc"?"desc":"asc"),v.exec("sort-rows",{key:a.id,add:se.ctrlKey||se.metaKey,order:K})},[v,a.id,a.filter,r.sort,x?.order]),T=u.useCallback(se=>{se&&se.stopPropagation(),v.exec("collapse-column",{id:a.id,row:l})},[v,a.id,l]),R=u.useCallback(se=>{se.key==="Enter"&&T()},[T]),U=u.useCallback(se=>{se.key==="Enter"&&!a.filter&&k(se)},[k,a.filter]),O=u.useMemo(()=>a.collapsed&&r.collapsed,[a.collapsed,r.collapsed]),Y=u.useMemo(()=>O&&!g&&a.collapsible!=="header",[O,g,a.collapsible]),_=u.useMemo(()=>Y?{top:-p/2,position:"absolute"}:{},[Y,p]),D=u.useMemo(()=>lf(a.width,a.flexgrow,r.fixed,r.left,a.right??r.right,a.height+(O&&Y?p:0)),[a.width,a.flexgrow,r.fixed,r.left,a.right,r.right,a.height,O,Y,p]),ne=u.useMemo(()=>Qb(r,a,m),[r,a,m]),G=u.useCallback(()=>Object.fromEntries(Object.entries(a).filter(([se])=>se!=="cell")),[a]),te=`wx-cell ${ne} ${a.css||""} wx-collapsed`,B=["wx-cell",ne,a.css||"",a.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),xe=u.useRef(null);return u.useEffect(()=>{const se=xe.current;if(!se)return;const K=sx(se,{down:C,move:A,up:N});return()=>{typeof K=="function"&&K()}},[C,A,N,sx]),O?s.jsx("div",{className:"wx-RsQD74qC "+te,style:D,role:"button","aria-label":`Expand column ${a.text||""}`,"aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:T,"data-header-id":Pn(r.id),children:s.jsx("div",{className:"wx-RsQD74qC wx-text",style:_,children:a.text||""})}):s.jsxs("div",{className:"wx-RsQD74qC "+B,style:D,onClick:k,"data-header-id":Pn(r.id),tabIndex:!a._hidden&&r.sort&&!a.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":a.colspan>1?a.colspan:void 0,"aria-rowspan":a.rowspan>1?a.rowspan:void 0,"aria-sort":!x?.order||a.filter?"none":x?.order==="asc"?"ascending":"descending",onKeyDown:U,children:[a.collapsible?s.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":a.collapsed?"Expand column":"Collapse column","aria-expanded":!a.collapsed,tabIndex:0,onKeyDown:R,onClick:T,children:s.jsx("i",{className:`wx-RsQD74qC wxi-angle-${a.collapsed?"down":"right"}`})}):null,a.cell?(()=>{const se=a.cell;return s.jsx(se,{api:v,cell:G(),column:r,row:l,onAction:({action:K,data:I})=>v.exec(K,I)})})():a.filter?s.jsx(mA,{filter:a.filter,column:r}):s.jsx("div",{className:"wx-RsQD74qC wx-text",children:a.text||""}),r.resize&&c&&!a._hidden?s.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:xe,onClick:se=>se.stopPropagation(),children:s.jsx("div",{})}):null,d?s.jsx("div",{className:"wx-RsQD74qC wx-sort",children:x?s.jsxs(s.Fragment,{children:[typeof x.index<"u"?s.jsx("div",{className:"wx-RsQD74qC wx-order",children:x.index+1}):null,s.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${x.order==="asc"?"up":"down"}`})]}):null}):null]})}function pA({cell:n,column:a,row:r,columnStyle:l}){const c=u.useContext(Ka),d=u.useMemo(()=>lf(n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right??a?.right,n?.height),[n?.width,n?.flexgrow,a?.fixed,a?.left,n?.right,a?.right,n?.height]),m=u.useMemo(()=>Qb(a,n,l),[a,n,l]),p=u.useCallback(()=>Object.fromEntries(Object.entries(n||{}).filter(([v])=>v!=="cell")),[n]),g=`wx-6Sdi3Dfd wx-cell ${m||""} ${n?.css||""}`+(a?.fixed&&a?.fixed.right?" wx-fixed-right":"");return s.jsx("div",{className:g,style:d,children:!a?.collapsed&&!n?.collapsed?n?.cell?Kh.createElement(n.cell,{api:c,cell:p(),column:a,row:r,onAction:({action:v,data:w})=>c.exec(v,w)}):s.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:n?.text||""}):null})}function ix({deltaLeft:n,contentWidth:a,columns:r,type:l="header",columnStyle:c,bodyHeight:d}){const m=u.useContext(Ka),p=lt(m,"_sizes"),g=lt(m,"split"),v=u.useMemo(()=>p?.[`${l}RowHeights`],[p,l]),w=u.useMemo(()=>{let A=[];if(r&&r.length){const N=r[0][l].length;for(let k=0;k<N;k++){let T=0;A.push([]),r.forEach((R,U)=>{const O={...R[l][k]};T||A[k].push(O),O.colspan>1?T=O.colspan-1:T&&T--})}}return A},[r,l]),x=u.useMemo(()=>g?.left||g?.right,[g]);function b(A){return r.find(N=>N.id===A)}function C(A,N){let k=N;return A.rowspan&&(k+=A.rowspan-1),k===w.length-1}function j(A,N,k){if(!k.sort)return!1;for(let T=w.length-1;T>=0;T--){const R=k.header[T];if(!R.filter&&!R._hidden)return N===T}return C(A,N)}return s.jsx("div",{className:`wx-sAsPVaUK wx-${l}`,style:{paddingLeft:`${n}px`,width:`${a}px`},role:"rowgroup",children:w.map((A,N)=>s.jsx("div",{className:l==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${v?.[N]}px`,display:"flex"},role:"row",children:A.map(k=>{const T=b(k.id);return l==="header"?s.jsx(hA,{cell:k,columnStyle:c,column:T,row:N,lastRow:C(k,N),bodyHeight:d,sortRow:j(k,N,T),hasSplit:x},k.id):s.jsx(pA,{cell:k,columnStyle:c,column:b(k.id),row:N},k.id)})},N))})}function gA({overlay:n}){const a=u.useContext(Ka);function r(c){return typeof c=="function"}const l=n;return s.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(n)?s.jsx(l,{onAction:({action:c,data:d})=>a.exec(c,d)}):n})}function vA(n){const{editor:a,onSave:r,onApply:l}=n,[c,d]=u.useState(a?.value||""),{type:m="text"}=u.useMemo(()=>a?.config||{},[a]),p=u.useRef(null);u.useEffect(()=>{p.current&&p.current.focus()},[]),u.useEffect(()=>{if(!p.current)return;const w=ni(p.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){p.current&&(d(p.current.value),l(p.current.value))}function v({key:w}){w==="Enter"&&r()}return s.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:v,ref:p,type:m,value:c})}function yA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d,m]=u.useState(n?.value),[p,g]=u.useState(n?.renderedValue),[v,w]=u.useState(n?.options||[]),x=u.useMemo(()=>n?.config?.template,[n]),b=u.useMemo(()=>n?.config?.cell,[n]),C=u.useMemo(()=>n?.config?.dropdown||{},[n]),j=u.useMemo(()=>({trackScroll:!0,...C}),[C]),A=u.useMemo(()=>(v||[]).findIndex(_=>_.id===d),[v,d]),N=u.useRef(null),k=u.useRef(null),T=u.useCallback(_=>{N.current=_.navigate,k.current=_.keydown,N.current(A)},[A,N]),R=u.useCallback(_=>{const D=_?.target?.value??"";g(D);const ne=D?(n?.options||[]).filter(G=>(G.label||"").toLowerCase().includes(D.toLowerCase())):n?.options||[];w(ne),ne.length?N.current(-1/0):N.current(null)},[n]),U=u.useRef(null);u.useEffect(()=>{U.current&&U.current.focus()},[]);const O=u.useRef(r);u.useEffect(()=>{O.current=r},[r]),u.useEffect(()=>{if(!U.current)return;const _=ni(U.current,()=>O.current(!0));return()=>_.destroy()},[]),u.useEffect(()=>{m(n?.value),g(n?.renderedValue),w(n?.options||[])},[n]);const Y=u.useCallback(({id:_})=>{l(_),r()},[l,r]);return s.jsxs(s.Fragment,{children:[s.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:U,value:p??"",onChange:R,onKeyDown:_=>k.current?k.current(_,A):void 0}),s.jsx(sf,{items:v,onReady:T,onSelect:Y,...j,onCancel:c,children:({option:_})=>x?x(_):b?s.jsx(b,{data:_,onAction:a}):_.label})]})}function xA({editor:n,onAction:a,onSave:r,onApply:l,onCancel:c}){const[d]=u.useState(()=>n.value||new Date),{template:m,cell:p,dropdown:g={}}=n?.config||{},v=u.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:j}){l(j),r()}const x=u.useRef(null),[b,C]=u.useState(null);return u.useEffect(()=>{x.current&&x.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!b)return;const j=ni(b,()=>r(!0));return()=>j.destroy()},[b,r]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:x,tabIndex:0,onClick:c,onKeyDown:j=>j.preventDefault(),children:m?m(d):p?s.jsx(p,{data:n.value,onAction:a}):s.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:n.renderedValue})}),s.jsx(op,{...v,onCancel:c,children:s.jsx("div",{ref:C,className:"wx-lNWNYUb6",children:s.jsx(Eb,{value:d,onChange:w,buttons:n.config?.buttons})})})]})}function bA(n){const{editor:a}=n,r=n.onAction??n.onaction,l=n.onSave??n.onsave,c=n.onApply??n.onapply,d=n.onCancel??n.oncancel,m=a.config||{},{dropdown:p={}}=m,g=u.useMemo(()=>({trackScroll:!0,...p}),[p]),[v]=u.useState(a.options.find(R=>R.id===a.value)),[w]=u.useState(a.value),[x]=u.useState(a.options),b=u.useMemo(()=>x.findIndex(R=>R.id===w),[x,w]);function C({id:R}){c(R),l()}let j;const[A,N]=u.useState();function k(R){j=R.navigate,N(()=>R.keydown),j(b)}const T=u.useRef(null);return u.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),u.useEffect(()=>{if(!T.current)return;const R=ni(T.current,()=>l(!0));return()=>R.destroy()},[l]),s.jsxs(s.Fragment,{children:[s.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:d,onKeyDown:R=>{A(R,b),R.preventDefault()},children:m.template?m.template(v):m.cell?(()=>{const R=m.cell;return s.jsx(R,{data:v,onAction:r})})():s.jsx("span",{className:"wx-ywGRk611 wx-text",children:a.renderedValue})}),s.jsx(sf,{items:x,onReady:k,onSelect:C,...g,onCancel:d,children:({option:R})=>m.template?m.template(R):m.cell?(()=>{const U=m.cell;return s.jsx(U,{data:R,onAction:r})})():R.label})]})}function wA(n){const{editor:a,onAction:r,onSave:l,onApply:c}=n,d=a?.config||{},m=a?.options??[],p=a?.value||[],g=a?.renderedValue,v=u.useMemo(()=>({trackScroll:!0,...d.dropdown||{}}),[d]);function w({value:b}){c(b)}const x=u.useRef(null);return u.useEffect(()=>{if(!x.current)return;const b=ni(x.current,()=>l(!0));return()=>b.destroy()},[l]),s.jsx("div",{ref:x,className:"wx-value wx-aacZ4gNU",onClick:()=>l(!0),children:s.jsx(Xb,{value:p,options:m,text:g,template:d.template,cell:d.cell,clear:d.clear,dropdown:v,autoOpen:!0,onChange:w,onAction:r})})}const SA={text:vA,combo:yA,datepicker:xA,richselect:bA,multiselect:wA};function CA({column:n,row:a}){const r=u.useContext(Ka),l=lt(r,"editor"),c=u.useCallback((j,A)=>{r.exec("close-editor",{ignore:j}),A&&r.exec("focus-cell",{...A,eventSource:"click"})},[r]),d=u.useCallback(j=>{const A=j?null:{row:l?.id,column:l?.column};c(!1,A)},[l,c]),m=u.useCallback(()=>{c(!0,{row:l?.id,column:l?.column})},[l,c]),p=u.useCallback(j=>{r.exec("editor",{value:j})},[r]),g=u.useCallback(j=>{j.key==="Enter"&&l&&(n.editor.type==="multiselect"?p(l.value):m())},[l,n.editor,m,p]),v=u.useMemo(()=>lf(n.width,n.flexgrow,n.fixed,n.left,n.right),[n.width,n.flexgrow,n.fixed,n.left,n.right]),w=u.useMemo(()=>{let j=n.editor;if(typeof j=="function"&&(j=j(a,n)),!j)return null;let A=typeof j=="string"?j:j.type;return SA[A]},[n,a]),x=u.useRef(null);u.useEffect(()=>{x.current&&typeof v=="string"&&x.current.setAttribute("style",v)},[v]);const b=typeof a.$parent<"u"?"gridcell":"cell",C=typeof a.$parent<"u"?!n.editor:void 0;return s.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:x,style:typeof v=="object"&&v!==null?v:void 0,role:b,"aria-readonly":C,tabIndex:-1,onClick:j=>j.stopPropagation(),onDoubleClick:j=>j.stopPropagation(),onKeyDown:g,children:w?s.jsx(w,{editor:l,onSave:d,onApply:p,onCancel:m,onAction:({action:j,data:A})=>r.exec(j,A)}):null})}function rx(n){const{columns:a,type:r,columnStyle:l}=n,c=u.useContext(Ka),{filterValues:d,_columns:m,_sizes:p}=c.getState();function g(v){return l?" "+l(v):""}return s.jsx(s.Fragment,{children:a.map((v,w)=>s.jsx("tr",{children:v.map(x=>{const b=m.find(A=>A.id===x.id),C=`wx-print-cell-${r}${g(b)}${x.filter?" wx-print-cell-filter":""}${x.vertical?" wx-vertical":""}`,j=x.cell;return s.jsx("th",{style:Ib(Gb(x,p.columnWidth)),className:"wx-Gy81xq2u "+C,rowSpan:x.rowspan,colSpan:x.colspan,children:j?s.jsx(j,{api:c,cell:Object.fromEntries(Object.entries(x).filter(([A])=>A!=="cell")),column:b,row:w}):x.filter?s.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:N1(d,m,x)}):s.jsx("div",{className:"wx-Gy81xq2u wx-text",children:x.text??""})},x.id)})},w))})}function jA(n){const{columns:a,rowStyle:r,columnStyle:l,cellStyle:c,header:d,footer:m,reorder:p}=n,g=u.useContext(Ka),{flatData:v,_sizes:w}=g.getState(),x=d&&Jy(a,"header",w.headerRowHeights),b=m&&Jy(a,"footer",w.footerRowHeights);function C(A,N){let k="";return k+=l?" "+l(N):"",k+=c?" "+c(A,N):"",k}function j(A,N){return typeof N.draggable=="function"?N.draggable(A,N)!==!1:N.draggable}return s.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${a.some(A=>A.flexgrow)?"wx-flex-columns":""}`,children:[d?s.jsx("thead",{children:s.jsx(rx,{columns:x,type:"header",columnStyle:l})}):null,s.jsx("tbody",{children:v.map((A,N)=>s.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(A):""),style:{height:`${A.rowHeight||w.rowHeight}px`},children:a.map(k=>k.collapsed?null:s.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${C(A,k)}`,style:Ib(Gb(k,w.columnWidth)),children:[p&&k.draggable?s.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:j(A,k)?s.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,k.treetoggle?s.jsxs(s.Fragment,{children:[s.jsx("span",{style:{marginLeft:A.$level*28+"px"}}),A.$count?s.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${A.open!==!1?"down":"right"}`}):null]}):null,k.cell?(()=>{const T=k.cell;return s.jsx(T,{api:g,row:A,column:k})})():s.jsx("span",{children:Ir(A,k)})]},k.id))},N))}),m?s.jsx("tfoot",{children:s.jsx(rx,{columns:b,type:"footer",columnStyle:l})}):null]})}function kA(n){const{config:a,...r}=n,l=u.useContext(Ka),{_skin:c,_columns:d}=l.getState(),m=u.useMemo(()=>C1(d,a),[]),p=u.useRef(null);return u.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const v=p.current;if(!v)return;const w=v.cloneNode(!0);g.appendChild(w);const x=`@media print { @page { size: ${a.paper} ${a.mode}; }`,b=document.createElement("style");b.setAttribute("type","text/css"),b.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(b),b.appendChild(document.createTextNode(x)),window.print(),b.remove(),g.classList.remove("wx-print"),w.remove()},[]),s.jsx("div",{className:`wx-4zwCKA7C wx-${c}-theme wx-print-container`,ref:p,children:m.map((g,v)=>s.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:s.jsx(jA,{columns:g,...r})},v))})}function AA(n){const{header:a,footer:r,overlay:l,multiselect:c,onreorder:d,rowStyle:m,columnStyle:p,cellStyle:g,autoRowHeight:v,resize:w,clientWidth:x,clientHeight:b,responsiveLevel:C,hotkeys:j}=n,A=u.useContext(Ka),N=lt(A,"dynamic"),k=lt(A,"_columns"),T=lt(A,"flatData"),R=lt(A,"split"),U=lt(A,"_sizes"),[O,Y]=hs(A,"selectedRows"),_=lt(A,"select"),D=lt(A,"editor"),ne=lt(A,"scrollLeft"),G=lt(A,"scrollTop"),te=lt(A,"tree"),B=lt(A,"focusCell"),xe=lt(A,"_print"),se=lt(A,"undo"),K=lt(A,"reorder"),I=lt(A,"_rowHeightFromData"),[Q,q]=u.useState(0);u.useEffect(()=>{q(ps())},[]);const[V,ce]=u.useState(0),be=u.useMemo(()=>(k||[]).some(ee=>!ee.hidden&&ee.flexgrow),[k]),X=u.useMemo(()=>U?.rowHeight||0,[U]),$=u.useRef(null),[ue,he]=u.useState(null),[ve,Se]=u.useState(null),_e=u.useMemo(()=>{let ee=[],Ne=0;return R&&R.left&&(ee=(k||[]).slice(0,R.left).filter(qe=>!qe.hidden).map(qe=>({...qe})),ee.forEach(qe=>{qe.fixed={left:1,leftSize:R.left},qe.left=Ne,Ne+=qe.width}),ee.length&&(ee[ee.length-1].fixed.left=-1)),{columns:ee,width:Ne}},[R,k]),re=u.useMemo(()=>{let ee=[],Ne=0;if(R&&R.right){ee=(k||[]).slice(R.right*-1).filter(qe=>!qe.hidden).map(qe=>({...qe}));for(let qe=ee.length-1;qe>=0;qe--){const rt=ee[qe];rt.fixed={right:1},rt.right=Ne,Ne+=rt.width}ee.length&&(ee[0].fixed={right:-1})}return{columns:ee,width:Ne}},[R,k]),Z=u.useMemo(()=>{const ee=(k||[]).slice(R?.left||0,(k||[]).length-(R?.right??0)).filter(Ne=>!Ne.hidden);return ee.forEach(Ne=>{Ne.fixed=0}),ee},[k,R]),ze=u.useMemo(()=>(k||[]).reduce((ee,Ne)=>(Ne.hidden||(ee+=Ne.width),ee),0),[k]),Le=1;function ae(ee,Ne,qe){let rt=Ne,Nt=ee;if(Z.length){let Mt=Z.length;for(let Qe=ee;Qe>=0;Qe--)Z[Qe][qe].forEach(ut=>{ut.colspan>1&&Qe>ee-ut.colspan&&Qe<Mt&&(Mt=Qe)});if(Mt!==Z.length&&Mt<ee){for(let Qe=Mt;Qe<ee;Qe++)rt-=Z[Qe].width;Nt=Mt}}return{index:Nt,delta:rt}}const fe=u.useMemo(()=>{let ee,Ne,qe;const rt=ne||0,Nt=(ne||0)+(x||0);let Mt=0,Qe=0,ut=0,kn=0;Z.forEach((cn,vn)=>{rt>ut&&(Mt=vn,kn=ut),ut=ut+cn.width,Nt>ut&&(Qe=vn+Le)});const Wt={header:0,footer:0};for(let cn=Qe;cn>=Mt;cn--)["header","footer"].forEach(vn=>{Z[cn]&&Z[cn][vn].forEach(Fr=>{const zs=Fr.colspan;if(zs&&zs>1){const Pr=zs-(Qe-cn+1);Pr>0&&(Wt[vn]=Math.max(Wt[vn],Pr))}})});const An=ae(Mt,kn,"header"),St=ae(Mt,kn,"footer"),rn=An.delta,Pt=An.index,xa=St.delta,ca=St.index;return be&&ze>(x||0)?ee=Ne=qe=[..._e.columns,...Z,...re.columns]:(ee=[..._e.columns,...Z.slice(Mt,Qe+1),...re.columns],Ne=[..._e.columns,...Z.slice(Pt,Qe+Wt.header+1),...re.columns],qe=[..._e.columns,...Z.slice(ca,Qe+Wt.footer+1),...re.columns]),{data:ee||[],header:Ne||[],footer:qe||[],d:kn,df:xa,dh:rn}},[Z,_e,re,ne,x,be,ze]),Ae=u.useMemo(()=>a&&U?.headerHeight||0,[a,U]),Te=u.useMemo(()=>r&&U?.footerHeight||0,[r,U]),Be=u.useMemo(()=>x&&b?ze>=x:!1,[x,b,ze]),[Ve,Je]=u.useState(!1),Et=u.useMemo(()=>(b||0)-Ae-Te-(Be?Q:0),[b,Ae,Te,Be,Q]),je=u.useMemo(()=>Math.ceil((Et||0)/(X||1))+1,[Et,X]),We=u.useRef([]),[it,ot]=u.useState(0),[gn,Kt]=u.useState(void 0),Ie=u.useMemo(()=>{let ee=0,Ne=0;const qe=2,rt=G||0;if(v){let Qe=rt;for(;Qe>0;)Qe-=We.current[ee]||X,ee++;Ne=rt-Qe;for(let ut=Math.max(0,ee-qe-1);ut<ee;ut++)Ne-=We.current[ee-ut]||X;ee=Math.max(0,ee-qe)}else{if(I){let Qe=0,ut=0;for(let St=0;St<(T||[]).length;St++){const rn=T[St].rowHeight||X;if(ut+rn>rt){Qe=St;break}ut+=rn}ee=Math.max(0,Qe-qe);for(let St=0;St<ee;St++)Ne+=T[St].rowHeight||X;let kn=0,Wt=0;for(let St=Qe+1;St<(T||[]).length;St++){const rn=T[St].rowHeight||X;if(kn++,Wt+rn>Et)break;Wt+=rn}const An=Math.min(N?N.rowCount:(T||[]).length,Qe+kn+qe);return{d:Ne,start:ee,end:An}}ee=Math.floor(rt/(X||1)),ee=Math.max(0,ee-qe),Ne=ee*(X||0)}const Nt=N?N.rowCount:(T||[]).length,Mt=Math.min(Nt,ee+(je||0)+qe);return{d:Ne,start:ee,end:Mt}},[v,I,G,X,N,T,je,Et]),ct=u.useMemo(()=>{const ee=N?N.rowCount:(T||[]).length;if(v)return it+Ie.d+(ee-(gn||0))*(X||0);if(!I)return ee*(X||0);let Ne=0;for(let qe=0;qe<ee;qe++)Ne+=T[qe]?.rowHeight||X;return Ne},[N,T,X,v,I,it,Ie.d,gn]),_t=u.useRef({});_t.current={clientWidth:x,clientHeight:b,fullHeight:ct,headerHeight:Ae,footerHeight:Te,fullWidth:ze,SCROLLSIZE:Q};const Ft=u.useCallback(()=>{const ee=_t.current;Je(ee.clientWidth&&ee.clientHeight?ee.fullHeight+ee.headerHeight+ee.footerHeight>=ee.clientHeight-(ee.fullWidth>=ee.clientWidth?ee.SCROLLSIZE:0):!1)},[]);u.useEffect(()=>{const ee=requestAnimationFrame(Ft);return()=>window.cancelAnimationFrame(ee)},[V,Ft]),u.useEffect(()=>{Ft()},[b,Ft]);const ge=u.useMemo(()=>be&&ze<=(x||0)?(x||0)-0-(Ve?Q:0):ze,[be,ze,x,Ve,Q,Be]),Oe=u.useMemo(()=>be&&ze<=(x||0)?x||0:ge<(x||0)?ze+(Ve?Q:0):-1,[be,ze,x,ge,Ve,Q]),Fe=u.useRef({});u.useEffect(()=>{if(N&&(Fe.current.start!==Ie.start||Fe.current.end!==Ie.end)){const{start:ee,end:Ne}=Ie;Fe.current={start:ee,end:Ne},A&&A.exec&&A.exec("request-data",{row:{start:ee,end:Ne}})}},[N,Ie,A]);const ke=u.useMemo(()=>N?T||[]:(T||[]).slice(Ie.start,Ie.end),[N,T,Ie]),st=u.useMemo(()=>(O||[]).filter(ee=>(ke||[]).some(Ne=>Ne.id===ee)),[Y,ke]),gt=u.useMemo(()=>Ie.start,[Ie.start]),Re=u.useRef({top:G,left:ne});Re.current={top:G,left:ne};const jn=u.useCallback(ee=>{const Ne=ee.target.scrollTop,qe=ee.target.scrollLeft,rt=Re.current;(Ne!==rt.top||qe!==rt.left)&&A.exec("scroll-to",{top:Ne,left:qe})},[A]),Ls=u.useCallback(ee=>{ee.shiftKey&&ee.preventDefault(),$.current&&$.current.focus&&$.current.focus()},[]),nt=u.useCallback(()=>!!(k||[]).find(ee=>!!ee.draggable),[k]),zt=u.useRef(null),zn=u.useRef(null),He=u.useRef({dblclick:(ee,Ne)=>{const qe={id:ee,column:Gc(Ne,"data-col-id")};A.exec("open-editor",qe)},click:(ee,Ne)=>{if(Ne.target.closest("input")||zt.current)return;const qe=Gc(Ne,"data-col-id");if(B?.id!==ee&&A.exec("focus-cell",{row:ee,column:qe,eventSource:"click"}),_===!1)return;const rt=c&&(Ne.ctrlKey||Ne.metaKey),Nt=c&&Ne.shiftKey;(rt||O.length>1||!O.includes(ee))&&A.exec("select-row",{id:ee,toggle:rt,range:Nt})},"toggle-row":ee=>{const Ne=A.getRow(ee);A.exec(Ne.open!==!1?"close-row":"open-row",{id:ee})},"ignore-click":()=>!1}),ya=u.useMemo(()=>({top:Ae,bottom:Te,left:_e.width,xScroll:Be,yScroll:Ve,sense:v&&ve?ve.offsetHeight:Math.max(U?.rowHeight||0,40),node:$.current&&$.current.firstElementChild}),[Ae,Te,_e.width,Be,Ve,v,ve,U]);function dt(ee,Ne){const{container:qe,sourceNode:rt,from:Nt}=Ne;if(nt()&&!rt.getAttribute("draggable-data"))return!1;he(Nt),te&&A.getRow(Nt).open&&A.exec("close-row",{id:Nt,nested:!0});const Mt=Lo(rt),Qe=Mt.cloneNode(!0);Qe.classList.remove("wx-selected"),Qe.querySelectorAll("[tabindex]").forEach(An=>An.setAttribute("tabindex","-1")),qe.appendChild(Qe),Se(Qe);const ut=(ne||0)-fe.d,kn=Ve?Q:0;qe.style.width=Math.min((x||0)-kn,be&&ze<=(x||0)?ge:ge-kn)+ut+"px";const Wt=zd(Mt);Ne.offset={x:ut,y:-Math.round(Wt.height/2)},zn.current||(zn.current=ee.clientY)}function Hi(ee,Ne){const{from:qe}=Ne,rt=Ne.pos,Nt=zd($.current);rt.x=Nt.x;const Mt=ya.top;if(rt.y<Mt)rt.y=Mt;else{const Qe=Nt.height-(Be&&Q>0?Q:Math.round(ya.sense/2))-ya.bottom;rt.y>Qe&&(rt.y=Qe)}if($.current.contains(Ne.targetNode)){const Qe=Lo(Ne.targetNode),ut=Qe&&nf(Qe);if(ut&&ut!==qe){Ne.to=ut;const kn=v?ve?.offsetHeight:U?.rowHeight;if(ve&&((G||0)===0||rt.y>Mt+kn-1)){const Wt=Qe.getBoundingClientRect(),An=zd(ve).y,St=Wt.y,rn=An>St?-1:1,Pt=rn===1?"after":"before",xa=A.getState().flatData,ca=Math.abs(xa.findIndex(vn=>vn.id===qe)-xa.findIndex(vn=>vn.id===ut)),cn=ca!==1?Pt==="before"?"after":"before":Pt;if(ca===1&&(rn===-1&&ee.clientY>zn.current||rn===1&&ee.clientY<zn.current))return;zn.current=ee.clientY,A.exec("move-item",{id:qe,target:ut,mode:cn,inProgress:!0})}}d&&d({event:ee,context:Ne})}nA(ee,Nt,Ne,ya)}function Qt(ee,Ne){const{from:qe,to:rt}=Ne;A.exec("move-item",{id:qe,target:rt,inProgress:!1}),zt.current=setTimeout(()=>{zt.current=0},1),he(null),Se(null),zn.current=null,Yb(Ne)}function ps(){const ee=document.createElement("div");ee.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(ee);const Ne=ee.offsetWidth-ee.clientWidth;return document.body.removeChild(ee),Ne}const bt=u.useMemo(()=>Oe>0?{width:`${Oe}px`}:void 0,[Oe]),qn=u.useRef(null);function _s(){Promise.resolve().then(()=>{let ee=0,Ne=gt;const qe=qn.current;qe&&(Array.from(qe.children).forEach((rt,Nt)=>{We.current[gt+Nt]=rt.offsetHeight,ee+=rt.offsetHeight,Ne++}),ot(ee),Kt(Ne))})}u.useEffect(()=>{ke&&v&&_s()},[ke,v,gt]);let[H,Pe]=u.useState();u.useEffect(()=>{if(B&&(!_||!st.length||st.includes(B.row)))Pe({...B});else if(ke.length&&fe.data.length){if(!H||st.length&&!st.includes(H.row)||ke.findIndex(ee=>ee.id===H.row)===-1||fe.data.findIndex(ee=>ee.id===H.column&&!ee.collapsed)===-1){const ee=st[0]||ke[0].id,Ne=fe.data.findIndex(qe=>!qe.collapsed);Pe(Ne!==-1?{row:ee,column:fe.data[Ne].id}:null)}}else Pe(null)},[B]);const vt=u.useRef(null);u.useEffect(()=>{const ee=$.current;if(!ee)return;const Ne=X1(ee,w);return()=>{typeof Ne=="function"&&Ne()}},[w]);const sn=u.useRef({});Object.assign(sn.current,{start:dt,move:Hi,end:Qt,getReorder:()=>K,getDraggableInfo:()=>({hasDraggable:nt()})}),u.useEffect(()=>{const ee=$.current;return ee?J1(ee,sn).destroy:void 0},[K,$.current]),u.useEffect(()=>{const ee=$.current;return ee?K1(ee,{keys:j!==!1&&{...Y1,"ctrl+z":se,"ctrl+y":se,...j},exec:Ne=>A.exec("hotkey",Ne)}).destroy:void 0},[A,se,j]);const Qa=u.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});Qa.current.getWidth=()=>(x||0)-(Ve?Q:0),Qa.current.getHeight=()=>Et,Qa.current.getScrollMargin=()=>_e.width+re.width,u.useEffect(()=>{Q1(vt.current,Qa.current)},[]);const Br=u.useRef(null);u.useEffect(()=>{const ee=Br.current;if(!ee)return;const Ne=[];Ne.push(ni(ee,()=>B&&A.exec("focus-cell",{eventSource:"click"})).destroy),Ne.push(Jk(ee,He.current)),ce(ee.clientHeight);const qe=new ResizeObserver(()=>{ce(ee.clientHeight)});return qe.observe(ee),Ne.push(()=>qe.disconnect()),()=>Ne.forEach(rt=>rt())},[]);const Xa=`wx-grid ${C?`wx-responsive-${C}`:""}`;return u.useEffect(()=>{B&&(ke.some(ee=>ee.id===B.row)&&fe.data.some(ee=>ee.id===B.column&&!ee.collapsed)||A.exec("focus-cell",{eventSource:"destroy"}))},[B,ke,fe.data,A]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-4VuBwK2D "+Xa,style:{"--header-height":`${Ae}px`,"--footer-height":`${Te}px`,"--split-left-width":`${_e.width}px`,"--split-right-width":`${re.width}px`},children:s.jsx("div",{ref:$,className:"wx-4VuBwK2D wx-table-box",style:bt,role:te?"treegrid":"grid","aria-colcount":fe.data.length,"aria-rowcount":ke.length,"aria-multiselectable":te&&c?!0:void 0,tabIndex:-1,children:s.jsxs("div",{ref:vt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:Be?"scroll":"hidden",overflowY:Ve?"scroll":"hidden"},onScroll:jn,children:[a?s.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:s.jsx(ix,{contentWidth:ge,deltaLeft:fe.dh,columns:fe.header,columnStyle:p,bodyHeight:Et-+r})}):null,s.jsxs("div",{ref:Br,className:"wx-4VuBwK2D wx-body",style:{width:`${ge}px`,height:`${ct}px`},onMouseDown:ee=>Ls(ee),children:[l?s.jsx(gA,{overlay:l}):null,s.jsx("div",{ref:qn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${Ie.d}px`,paddingLeft:`${fe.d}px`},children:ke.map((ee,Ne)=>{const qe=O.indexOf(ee.id)!==-1,rt=ue===ee.id,Nt="wx-row"+(v?" wx-autoheight":"")+(m?" "+m(ee):"")+(qe?" wx-selected":"")+(rt?" wx-inactive":""),Mt=v?{minHeight:`${ee.rowHeight||X}px`}:{height:`${ee.rowHeight||X}px`};return s.jsx("div",{className:"wx-4VuBwK2D "+Nt,"data-id":Pn(ee.id),"data-context-id":Pn(ee.id),style:Mt,role:"row","aria-rowindex":Ne,"aria-expanded":ee.open,"aria-level":te?ee.$level+1:void 0,"aria-selected":te?qe:void 0,tabIndex:-1,children:fe.data.map(Qe=>Qe.collapsed?s.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},Qe.id):D?.id===ee.id&&D.column===Qe.id?s.jsx(CA,{row:ee,column:Qe},Qe.id):s.jsx(lA,{row:ee,column:Qe,columnStyle:p,cellStyle:g,reorder:K,focusable:H?.row===ee.id&&H?.column===Qe.id},Qe.id))},ee.id)})})]}),r&&(T||[]).length?s.jsx(ix,{type:"footer",contentWidth:ge,deltaLeft:fe.df,columns:fe.footer,columnStyle:p}):null]})})}),xe?s.jsx(kA,{config:xe,rowStyle:m,columnStyle:p,cellStyle:g,header:a,footer:r,reorder:K}):null]})}const NA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join(""),MA=u.forwardRef(function({data:n=[],columns:a=[],rowStyle:r=null,columnStyle:l=null,cellStyle:c=null,selectedRows:d,select:m=!0,multiselect:p=!1,header:g=!0,footer:v=!1,dynamic:w=null,overlay:x=null,reorder:b=!1,onReorder:C=null,autoRowHeight:j=!1,sizes:A,split:N,tree:k=!1,autoConfig:T=!1,init:R=null,responsive:U=null,sortMarks:O,undo:Y=!1,hotkeys:_=null,filterValues:D,...ne},G){const te=u.useRef();te.current=ne;const B=u.useMemo(()=>new $1(Ob),[]),xe=u.useMemo(()=>B.in,[B]),se=u.useRef(null);se.current===null&&(se.current=new Rb((re,Z)=>{const ze="on"+NA(re);te.current&&te.current[ze]&&te.current[ze](Z)}),xe.setNext(se.current));const K=u.useMemo(()=>({getState:B.getState.bind(B),getReactiveState:B.getReactive.bind(B),getStores:()=>({data:B}),exec:xe.exec,setNext:re=>(se.current=se.current.setNext(re),se.current),intercept:xe.intercept.bind(xe),on:xe.on.bind(xe),detach:xe.detach.bind(xe),getRow:B.getRow.bind(B),getColumn:B.getColumn.bind(B)}),[B,xe]),[I,Q]=u.useState(0),[q,V]=u.useState(0),[ce,be]=u.useState(null),[X,$]=u.useState(null),ue=u.useMemo(()=>{if(T&&!a.length&&n.length){const re=n[0],Z=[];for(let ze in re)if(ze!=="id"&&ze[0]!=="$"){let Le={id:ze,header:ze[0].toUpperCase()+ze.slice(1)};typeof T=="object"&&(Le={...Le,...T}),Z.push(Le)}return Z}return(X&&X.columns)??a},[T,a,n,X]),he=u.useMemo(()=>(X&&X.sizes)??A,[X,A]),ve=u.useCallback(re=>{if(Q(re.width),V(re.height),U){const Z=Object.keys(U).map(Number).sort((ze,Le)=>ze-Le).find(ze=>re.width<=ze)??null;Z!==ce&&($(U[Z]),be(Z))}},[U,ce]),Se=u.useContext(Un.theme),_e=u.useRef(0);return u.useEffect(()=>{if(!_e.current)R&&R(K);else{const re=B.getState();B.init({data:n,columns:ue,split:N||re.split,sizes:he||re.sizes,selectedRows:d||re.selectedRows,dynamic:w,tree:k,sortMarks:O||re.sortMarks,filterValues:D||re.filterValues,undo:Y,reorder:b,_skin:Se,_select:m})}_e.current++},[B,n,ue,N,he,d,w,k,O,D,Y,b,Se,m,R,K]),_e.current===0&&B.init({data:n,columns:ue,split:N||{left:0},sizes:he||{},selectedRows:d||[],dynamic:w,tree:k,sortMarks:O||{},filterValues:D||{},undo:Y,reorder:b,_skin:Se,select:m}),u.useImperativeHandle(G,()=>({...K}),[K]),s.jsx(Ka.Provider,{value:K,children:s.jsx(dp,{words:fp,optional:!0,children:s.jsx(AA,{header:g,footer:v,overlay:x,rowStyle:r,columnStyle:l,cellStyle:c,onReorder:C,multiselect:p,autoRowHeight:j,clientWidth:I,clientHeight:q,responsiveLevel:ce,resize:ve,hotkeys:_})})})});sp(La);const $n=u.createContext(null),pp=u.createContext(null),gp=u.createContext(null);function TA({children:n}){const a=u.useContext(Un.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=u.useContext($n),[c]=hs(l,"panels"),d=lt(l,"activePanel"),m=c[d].path,[p,g]=u.useState(null),[v,w]=u.useState(null),[x,b]=u.useState(""),[C,j]=u.useState(""),[A,N]=u.useState(!1);function k(){const O=x.trim();if(!O){N(!0);return}p.add?l.exec("create-file",{file:{...p.item,name:O},parent:m}):C!==O&&l.exec("rename-file",{id:p.item.id,name:O}),T()}function T(){g(null),N(null),j(""),b("")}function R(){l.exec("delete-files",{ids:v.selected}),w(null)}const U=u.useMemo(()=>({showPrompt(O){const Y=O.item.name||(O.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);j(Y),b(Y),g({...O})},showConfirm(O){w({...O})}}),[r]);return s.jsxs(pp.Provider,{value:U,children:[s.jsx(Tk,{children:n}),p?s.jsx(zh,{title:r(`Enter ${p.item.type} name`),onConfirm:k,onCancel:T,children:s.jsx(cp,{error:A,select:!0,focus:!0,value:x,onChange:({value:O})=>b(O)})}):null,v?s.jsx(zh,{title:r("Are you sure you want to delete these items:"),onConfirm:R,onCancel:()=>w(null),children:v.selected?s.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:v.selected.map((O,Y)=>s.jsx("li",{children:O},Y))}):null}):null]})}let lx={"7z":!0,rar:!0,zip:!0,css:!0,html:!0,js:!0,php:!0,md:!0,xml:!0,sql:!0,aif:!0,mid:!0,mp3:!0,waw:!0,wma:!0,doc:!0,docx:!0,txt:!0,avi:!0,mov:!0,mp4:!0,mpeg:!0,mpg:!0,pdf:!0,xls:!0,xlsx:!0,gif:!0,jpg:!0,jpeg:!0,png:!0,psd:!0,tiff:!0,svg:!0,folder:!0,file:!0,multiple:!0,search:!0,none:!0};function EA(n){const a=n.lastIndexOf("."),r=a>0&&a<n.length-1?Math.min(10,n.length-a):Math.min(5,n.length),l=n.slice(0,-r),c=n.slice(-r);return[l,c]}function RA({item:n}){const a=u.useContext($n),r=u.useContext(Un.i18n).getGroup("filemanager"),l=u.useContext($n).templates,[c]=hs(a,"panels"),d=lt(a,"activePanel"),m=lt(a,"mode"),p=c[d].selected,g=u.useMemo(()=>l.preview(n,214,163),[l,n]),v=u.useMemo(()=>l.icon(n,"big"),[l,n]),[w,x]=u.useMemo(()=>EA(n.name),[n.name]);return s.jsx(s.Fragment,{children:n.id==="/wx-filemanager-parent-link"?m!=="search"?s.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:s.jsxs("div",{className:`wx-GAOa4kDV wx-back ${n.navigation?"wx-selected":""}`,"data-id":Pn("/wx-filemanager-parent-link"),children:[s.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),s.jsx("span",{children:r("Back to parent folder")})]})}):null:s.jsxs("div",{className:`wx-GAOa4kDV wx-item ${p?.length&&p.indexOf(n.id)>=0?"wx-selected":""}`,"data-id":Pn(n.id),children:[g?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):v?s.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:s.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:v})}):s.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:s.jsx("i",{className:`wx-GAOa4kDV wxi-${n.type}`})}),n.type==="folder"?s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[s.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:x})]})]}),s.jsx("div",{"data-action-id":Pn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):s.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[s.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:s.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[s.jsx("span",{children:w}),s.jsx("span",{children:x})]})}),s.jsx("div",{"data-action-id":Pn(n.id),className:"wx-GAOa4kDV wx-more",children:s.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function Zb(){const n=u.useContext($n),a=u.useContext(Un.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),[l]=hs(n,"panels"),c=lt(n,"activePanel"),d=lt(n,"mode"),m=l[c]._files,p=l[c].selected,g=l[c].path,v=l[c]._crumbs,w=l[c]._selectNavigation,x=u.useCallback((T,R)=>{const U=R&&(R.ctrlKey||R.metaKey),O=R&&R.shiftKey;if(T==="/wx-filemanager-parent-link"){if(p.length&&(U||O))return;n.exec("select-file",{type:"navigation"});return}let Y=T==="body"&&R?null:T;const _=R.target.className.indexOf("wx-more")!==-1||R.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{n.exec("select-file",{id:Y,toggle:U&&!_,range:O&&!_,panel:c})},1)},[n,p,c]),b=u.useCallback(()=>{v.length>1&&n.exec("set-path",{id:v[v.length-2].id,panel:c,selected:[v[v.length-1].id]})},[n,v,c]),C=u.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return b();d==="search"&&n.exec("filter-files",{text:""});const R=m.find(U=>U.id===T);R&&(R.type=="folder"?n.exec("set-path",{id:R.id,panel:c}):n.exec("open-file",{id:R.id}))},[n,b,d,m,c]),j=u.useCallback((T,R)=>{(!p?.length||!p.filter(U=>U?.id===T).length>0)&&x(T,R)},[p,x]),A=u.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...m]:m,[g,r,w,m]),N=u.useRef(null),k=u.useRef();return u.useEffect(()=>{N.current&&(k.current?(k.current.click=x,k.current._dblclick=C,k.current.context=j):(k.current={click:x,dblclick:T=>k.current._dblclick(T),_dblclick:C,context:j},_o(N.current,k.current)))},[x,C,j]),d=="search"&&!A.length?s.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:s.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):s.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&d!=="search"?" wx-has-back-link":"")),"data-id":Pn("body"),ref:N,children:A.map(T=>s.jsx(RA,{item:T},T.id))})}function _l({name:n="",spin:a=!1,onClick:r}){return s.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${n} ${a?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function DA(){const n=u.useContext(Un.i18n).getGroup("filemanager"),a=u.useContext($n),r=lt(a,"activePanel"),[l]=hs(a,"panels"),c=u.useMemo(()=>l[r]._crumbs,[l,r]);function d(){a.exec("filter-files",{text:""})}return s.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[s.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[s.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:s.jsx(_l,{name:"angle-left",onClick:d})}),s.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[n("Search results in")," ",Array.isArray(c)&&c.map((m,p)=>s.jsxs(u.Fragment,{children:[p?"/":null,m.id=="/"?n(m.name):m.name]},p))]})]}),s.jsx(Zb,{})]})}function ih({narrowMode:n,extraInfo:a}){const r=u.useContext($n),{preview:l,icon:c}=r.templates,d=u.useContext(Un.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>To("%D, %d %F %Y, %H:%i",d.getRaw().calendar),[d]),[g,v]=hs(r,"panels"),w=lt(r,"activePanel"),x=lt(r,"preview"),b=lt(r,"search"),C=u.useMemo(()=>{const _=g&&w!=null&&g[w]?._selected?.length||0;return b&&!_},[b,v,w]),j=u.useMemo(()=>{const _=g&&w!=null?g[w]:null;return _?C?_._files:_._selected:[]},[C,v,w]),A=u.useCallback((_,D)=>(_?`${_} ${m(_>1?"folders":"folder")} `:"")+(D?`${D} ${m(D>1?"files":"file")}`:""),[m]),N=u.useCallback(()=>{r.exec("show-preview",{mode:!x})},[r,x]),k=u.useCallback(_=>_.type==="folder"?m("Folder"):_.ext||m("Unknown file"),[m]),T=u.useMemo(()=>{let _,D,ne,G,te,B,xe,se;if(j.length===1&&!C){D=j[0],_=D.name;const K=l(D,400,500);K?(ne=K,G=""):(G=c(D,"big"),ne=""),te=D.type!=="folder"}else{if(D=te=null,_="",j.length){let K=0,I=0,Q=0,q=[],V;j.forEach(be=>{typeof be.size>"u"&&(V=!0,K=void 0),V||(K+=be.size),q.push(k(be)),be.type==="folder"?I++:Q++});const ce=new Set(q);B=ce.size>1?m("multiple"):[...ce][0],xe=A(I,Q),se=K,C||(_=m("Multiple files"))}G=c({type:C?"search":j.length?"multiple":"none"},"big"),ne=""}return{name:_,item:D,previewSrc:ne,iconSrc:G,showDownloadIcon:te,type:B,totalCount:xe,totalSize:se}},[j,C,l,c,m,k,A]),R=u.useCallback(()=>{r.exec("download-file",{id:j[0].id})},[r,j]),U=u.useCallback(async _=>{if(!a||!_)return null;try{return await a(_)}catch(D){return console.log(D),null}},[a]),[O,Y]=u.useState(null);return u.useEffect(()=>{let _=!1;return Y(null),Promise.resolve(U(T.item)).then(D=>{_||Y(D)}).catch(()=>{_||Y(null)}),()=>{_=!0}},[U,T.item]),s.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:j&&j.length?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),s.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?s.jsx(_l,{name:"download",onClick:R}):null,n?s.jsx(_l,{name:"close",onClick:N}):null]})]}),T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C?"search":"file-multiple-outline"}`})})]}),s.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-title",children:m(C?"Found":"Information")}),s.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:k(T.item)}),typeof T.item.size<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Vc(T.item.size)})]}):null,s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Date")}),s.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[p(T.item.date)," "]})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Count")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Type")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:m("Size")}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Vc(T.totalSize)})]}):null]}),O?Object.entries(O).map(([_,D])=>s.jsxs(Kh.Fragment,{children:[s.jsx("span",{className:"wx-O0BTtRrH wx-name",children:_}),s.jsx("span",{className:"wx-O0BTtRrH wx-value",children:D})]},_)):null]})]})]}):s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[s.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[s.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),s.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:n?s.jsx(_l,{name:"close",onClick:N}):null})]}),s.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:s.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:s.jsx("img",{src:T.previewSrc,alt:m("A miniature file preview")})}):T.iconSrc?s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("img",{src:T.iconSrc,alt:m("A miniature file preview")})}):s.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:s.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${C?"search":"message-question-outline"}`})}),s.jsx("span",{className:"wx-O0BTtRrH wx-text",children:C?"":m("Select file or folder to view details")})]})})]})})}function Jb({panel:n}){const a=u.useContext($n),r=u.useContext(Un.i18n),l=u.useMemo(()=>r.getGroup("filemanager"),[r]),[c,d]=hs(a,"panels"),m=u.useMemo(()=>c[n]._files,[d,n]),p=u.useMemo(()=>c[n]._crumbs||[],[d,n]);function g(j){const A=mp(j,p);a.exec("set-path",{id:j,panel:n,...A&&{selected:[A]}})}const[v,w]=u.useState(null);u.useEffect(()=>{m&&w(null)},[m]);function x(){w(!0),a.exec("request-data",{id:p[p.length-1].id}),setTimeout(()=>{w(null)},5e3)}const b=u.useRef(null),C=u.useRef();return u.useEffect(()=>{C.current?C.current.click=g:(C.current={click:g},_o(b.current,C.current))},[g]),s.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:b,children:[s.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:s.jsx(_l,{name:"refresh",spin:!!v,onClick:x})}),p.map((j,A)=>s.jsxs(Kh.Fragment,{children:[A?s.jsx(_l,{name:"angle-right"}):null,s.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Pn(j.id),"data-menu-ignore":"true",children:j.id=="/"?l(j.name):j.name})]},A))]})}function LA({row:n}){const a=u.useContext(Un.i18n),[r]=u.useState(()=>a.getGroup("filemanager")),l=u.useContext($n).templates,[c]=u.useState(()=>l.icon(n,"small"));return s.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:n.id==="/wx-filemanager-parent-link"?s.jsxs(s.Fragment,{children:[s.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):s.jsxs(s.Fragment,{children:[c?s.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:c,height:"24px",width:"24px"}):s.jsx("i",{className:`wx-qgAqG6sL wxi-${n.type}`}),s.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",n.name," "]})]})})}function ew({children:n}){const a=u.useContext($n),r=lt(a,"activePanel"),l=u.useContext(gp),c=u.useRef(null);let d=u.useRef({});return d.current.drop=()=>{const m=c.current,p=Ij(m,"data-panel");p&&p!=r&&a.exec("set-active-panel",{panel:p*1})},d.current.dragEnter=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},d.current.dragLeave=()=>{const m=c.current;m&&m.classList.toggle("wx-active")},u.useEffect(()=>{const m=c.current;return l.droparea(m,d.current)},[]),s.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:c,children:n})}function Hh({panel:n,active:a=!1,onClick:r,onContextMenu:l}){const c=u.useContext($n),d=u.useContext(Un.i18n),m=u.useMemo(()=>d.getGroup("filemanager"),[d]),p=u.useMemo(()=>To("%d %M %Y",d.getRaw().calendar),[d]),[g]=hs(c,"panels"),v=g[n].selected,w=g[n].path,x=g[n]._crumbs,b=g[n]._sorts,C=g[n]._selectNavigation,j=g[n]._files,A=u.useMemo(()=>[{id:"name",header:m("Name"),flexgrow:3,sort:!0,resize:!0,cell:LA},{id:"size",header:m("Size"),width:100,sort:!0,resize:!0,template:B=>typeof B=="number"?Vc(B):""},{id:"date",header:m("Date"),width:120,sort:!0,resize:!0,template:B=>B?p(B):""}],[m,p]),N=u.useRef(null),k=u.useRef(null),T=u.useMemo(()=>C?["/wx-filemanager-parent-link"]:[...v],[C,v]);function R(B,xe){if(xe&&xe.target&&xe.target.className&&xe.target.className.indexOf("wx-grip")!==-1)return;const se=xe&&(xe.ctrlKey||xe.metaKey),K=xe&&xe.shiftKey;if(B==="/wx-filemanager-parent-link"){if(v.length&&(se||K))return;c.exec("select-file",{type:"navigation"});return}let I=B==="body"&&xe?null:B;!N.current&&!k.current?c.exec("select-file",{id:I,toggle:se,range:K,panel:n}):(N.current=null,k.current=null)}function U(){x.length>1&&c.exec("set-path",{id:x[x.length-2].id,panel:n,selected:[x[x.length-1].id]})}function O(B){if(B==="/wx-filemanager-parent-link")return U();const xe=j.find(se=>se.id===B);xe&&(xe.type==="folder"?c.exec("set-path",{id:xe.id,panel:n}):c.exec("open-file",{id:xe.id}))}function Y(B){const xe=B.key,se=b[w];let K=se?"asc":"desc";se&&se.key===xe&&(K=se.order==="asc"?"desc":"asc"),c.exec("sort-files",{key:xe,order:K,panel:n,path:w})}function _(B){B.intercept("sort-rows",xe=>(N.current=!0,Y(xe),!1)),B.intercept("select-row",()=>!1),B.on("resize-column",()=>k.current=!0),B.intercept("hotkey",()=>!1)}const D=u.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:m("Back to parent folder")},...j]:j,[w,j,m]),ne=u.useMemo(()=>{if(D&&b&&b[w]){const{key:B,order:xe}=b[w];return{[B]:{order:xe}}}},[D,b,w]),G=u.useRef(null),te=u.useRef();return u.useEffect(()=>{te.current?(te.current.click=R,te.current._dblclick=O):(te.current={click:R,dblclick:B=>te.current._dblclick(B),_dblclick:O},_o(G.current,te.current))},[R,O]),s.jsxs("div",{onClick:r,onContextMenu:l,className:"wx-SSaVhET7 wx-wrapper",children:[s.jsx(Jb,{panel:n}),s.jsx("div",{"data-id":Pn("body"),className:`wx-SSaVhET7 wx-list ${a?"wx-active":""}`,ref:G,children:s.jsx(ew,{children:s.jsx(MA,{init:_,data:D,columns:A,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:ne})})})]})}function _A(){const n=u.useContext($n),a=lt(n,"activePanel");function r(l){n.exec("set-active-panel",{panel:l})}return s.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Pn("body"),children:[s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:s.jsx(Hh,{panel:0,active:a==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),s.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:s.jsx(Hh,{panel:1,active:a==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function tw({folderIcon:n=!1,folder:a={}}){const r=u.useContext($n),[l,c]=hs(r,"panels"),d=lt(r,"activePanel"),m=u.useMemo(()=>l[d].path,[c,d]),p=u.useContext(Un.i18n),g=u.useMemo(()=>p.getGroup("filemanager"),[p]),v=u.useMemo(()=>!!a.data?.find(C=>C.type==="folder"),[a]),w=u.useMemo(()=>a.id=="/"?g(a.name):a.name,[a,g]),x=u.useMemo(()=>a.$level>1?(a.$level-1)*20:0,[a]),b=a.open;return s.jsxs(s.Fragment,{children:[s.jsxs("li",{"data-id":Pn(a.id),className:`wx-NYfhvGIt wx-folder${m===a.id?" wx-selected":""}`,style:{paddingLeft:`${x}px`},children:[v?s.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${b?"angle-down":"angle-right"}`,"data-action":"toggle"}):s.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),s.jsx("i",{className:"wx-NYfhvGIt "+(n||"wxi-folder")}),s.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),b&&a.data&&a.data.length&&v?s.jsx(s.Fragment,{children:a.data.map(C=>C.type==="folder"?s.jsx(tw,{folder:C},C.id):null)}):null]})}function zA(){const n=u.useContext($n),[a,r]=hs(n,"data"),[l,c]=hs(n,"panels"),d=lt(n,"activePanel"),m=u.useMemo(()=>l[d]._crumbs,[c,d]),p=u.useCallback(C=>{n.exec("open-tree-folder",{id:C,mode:!a.byId(C).open})},[n,r]),g=u.useCallback(C=>{const j=mp(C,m);n.exec("set-path",{id:C,panel:d,...j&&{selected:[j]}})},[n,m,d]),[v,w]=u.useState([]);u.useEffect(()=>{w(a.byId(0).data)},[r]);const x=u.useRef(null),b=u.useRef();return u.useEffect(()=>{b.current?(b.current.click=g,b.current.toggle=p):(b.current={click:g,toggle:p},_o(x.current,b.current))},[g,p]),s.jsx("ul",{ref:x,className:"wx-LyHJ6R6A",children:v.map(C=>C.type==="folder"?s.jsx(tw,{folder:C},C.id):null)})}function IA(){const n=u.useContext($n),a=u.useContext(Un.i18n),r=u.useMemo(()=>a.getGroup("filemanager"),[a]),l=lt(n,"drive"),c=l?l.used:"",d=l?l.total:"";return c&&d?s.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[s.jsx("progress",{value:c,max:d,className:"wx-DetSyKGG wx-progress"}),s.jsxs("p",{children:[Vc(c)," ",r("of")," ",Vc(d)," ",r("used")]})]}):null}function OA({option:n}){const a=u.useContext(Un.i18n).getGroup("filemanager"),r=u.useContext(gp),l=u.useCallback(()=>{r.open({})},[r]);return s.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:l,children:s.jsx("span",{children:a(n.text)})})}function HA({readonly:n,menuOptions:a}){const r=u.useContext(Un.i18n).getGroup("filemanager"),{showPrompt:l}=u.useContext(pp);u.useEffect(()=>{n1("upload",OA)},[]);function c({action:m}){m&&(m.id==="add-file"?l({item:{type:"file",size:0,date:new Date},add:!0}):m.id==="add-folder"&&l({item:{type:"folder",date:new Date},add:!0}))}const d=u.useMemo(()=>a("add").map(m=>(m.text=r(m.text),m)),[a,r]);return s.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!n&&s.jsx("div",{className:"wx-FlucfALM wx-button",children:s.jsx(s1,{options:d,at:"bottom-fit",onClick:c,children:s.jsx(Hc,{type:"primary block",children:r("Add New")})})}),s.jsx("div",{className:"wx-FlucfALM wx-tree",children:s.jsx(zA,{})}),s.jsx(IA,{})]})}function BA({value:n="",onSearch:a}){const[r,l]=zb(n),c=u.useContext(Un.i18n).getGroup("filemanager"),d=u.useRef(null),m=u.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function p(v){const w=v.target.value;l(w),a&&a({value:w})}function g(){l(""),d.current&&d.current.focus(),a&&a({value:""})}return s.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[s.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${m}`,onClick:g}),s.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:d,value:r,onInput:p,placeholder:c("Search")})]})}function FA({narrowMode:n=!1,onShowTree:a}){const r=u.useContext($n),l=u.useContext(Un.i18n).getGroup("filemanager"),c=lt(r,"mode"),d=lt(r,"preview"),m=lt(r,"search"),p=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:x}){r.exec("set-mode",{mode:x})}function v(x){x.preventDefault(),r.exec("show-preview",{mode:!d})}function w(x){r.exec("filter-files",{text:x.value})}return s.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[s.jsxs("div",{className:"wx-5PZQQztG wx-left "+(n?"wx-left-narrow":""),children:[n?c==="panels"||c==="search"?null:s.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Pn("toggle-tree"),children:s.jsx(_l,{onClick:()=>a&&a(),name:"subtask"})}):s.jsx("div",{className:"wx-5PZQQztG wx-name",children:l("Files")}),s.jsx(BA,{onSearch:w,value:m})]}),s.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[n?null:s.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:s.jsx(Ek,{onClick:v,value:d,children:s.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),s.jsx("div",{className:"wx-5PZQQztG wx-modes",children:s.jsx(jk,{value:c,options:p,onChange:g})})]})]})}function PA(){const n=u.useContext($n),a=lt(n,"activePanel");return s.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[s.jsx(Jb,{panel:a}),s.jsx(ew,{children:s.jsx(Zb,{})})]})}function $A({readonly:n=!1,menuOptions:a,extraInfo:r}){const l=u.useRef(null),c=u.useRef(null),[d,m]=u.useState(void 0),[p,g]=u.useState(void 0),[v,w]=u.useState(!1),x=$b(),b=u.useContext($n),{showPrompt:C,showConfirm:j}=u.useContext(pp),A=u.useContext(Un.i18n),N=u.useMemo(()=>A.getGroup("filemanager"),[A]),k=lt(b,"mode"),T=lt(b,"preview"),R=lt(b,"activePanel"),[U,O]=hs(b,"panels"),Y=u.useMemo(()=>(U&&R!=null?U[R]:null)?.selected??[],[O,R]),_=u.useMemo(()=>(U&&R!=null?U[R]:null)?.path,[O,R]),[D,ne]=u.useState([]);u.useEffect(()=>{const ce=l.current;if(!ce)return;const be=new ResizeObserver(X=>{const $=X[0]?.borderBoxSize?.[0]?.inlineSize;typeof $=="number"&&g($<768)});return be.observe(ce),()=>{be.disconnect()}},[]);const G=u.useCallback(()=>{w(ce=>!ce)},[]),te=u.useCallback(ce=>{p&&Gc(ce)!=="toggle-tree"&&w(!1)},[p]);u.useEffect(()=>{const ce=c.current;if(ce)return ni(ce,te).destroy},[te]),u.useEffect(()=>{const ce=c.current;if(!ce)return;const be=new ResizeObserver(()=>{ce&&m(ce.clientWidth)});return be.observe(ce),ce&&m(ce.clientWidth),()=>{be.disconnect()}},[]);const B=u.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),xe=u.useCallback(ce=>{let be=p?[B]:[];return ce==="file"&&(be=[...be,...a().filter(X=>X.id==="download")]),be},[p,B,a]),se=u.useRef(null),K=u.useCallback((ce,be,X)=>{const $=X?[be.id]:Y;switch(ce){case"download":b.exec("download-file",{id:be.id});break;case"copy":case"move":se.current={action:ce,ids:$};break;case"paste":se.current&&b.exec(se.current.action==="copy"?"copy-files":"move-files",{ids:se.current.ids,target:be?.type==="folder"?be.id:_});break;case"rename":C({item:be});break;case"delete":j({selected:$});break;case"preview":b.exec("show-preview",{mode:!T});break}},[b,Y,_,C,j,T]),I=u.useCallback(()=>U?.[R],[U,R]);u.useEffect(()=>{const ce=l.current;if(!ce)return;const be=Gk(ce,{api:b,menuOptions:n?xe:a,performAction:K,getPanel:I});return()=>{typeof be=="function"?be():be&&typeof be.destroy=="function"&&be.destroy()}},[b,n,xe,a,K,I]);const Q=u.useCallback((ce,be)=>{const X=ce?b.getFile(ce):null,$=be.target.closest(".tree-item.folder");let ue;if(n)ue=xe(X?.type);else{switch(ce){case"body":ue=a(ce);break;default:if(X)if(!$&&Y.length>1)ue=p?[B,...a("multiselect")]:a("multiselect");else if(ce==="/")ue=a("folder",X).filter(he=>he.id==="paste");else{const he=a(X.type,X);he&&(ue=p?[B,...he]:he)}}k==="search"&&(ue=ue?.filter(he=>he.id!=="paste"))}if(X?.id&&(!Y.length||!Y.some(he=>he===X.id))&&!$&&b.exec("select-file",{id:X.id}),ue?.length)return ue.forEach(he=>{$&&(he.hotkey=""),he.text&&(he.text=N(he.text)),he.hotkey&&(he.subtext=he.hotkey)}),ne(ue),X||{}},[b,n,xe,a,Y,p,B,k,N]),q=u.useCallback(ce=>{const{action:be,context:X}=ce;be&&K(be.id,X,!be.hotkey)},[K]);async function V(ce){await Promise.resolve();const{name:be,size:X}=ce.file;b.exec("create-file",{file:{name:be,size:X,date:new Date,file:ce.file},parent:_})}return s.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:l,"data-menu-ignore":"false",children:p&&T?s.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:s.jsx(ih,{narrowMode:p,extraInfo:r})}):s.jsxs(s.Fragment,{children:[s.jsx(FA,{narrowMode:p,onShowTree:G}),s.jsx(i1,{dataKey:"id",at:"point",options:D,resolver:Q,onClick:q,children:s.jsxs(Pb,{dataKey:"actionId",options:D,resolver:Q,onClick:q,children:[s.jsx(u1,{data:x,apiOnly:!0,uploadURL:V}),s.jsx(gp.Provider,{value:x,children:s.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:k!=="panels"&&k!=="search"?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",p?"wx-sidebar-narrow":"",v?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:c,children:s.jsx(HA,{readonly:n,menuOptions:a})}),s.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${d||0}px - 10px)`},children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Pn("body"),children:k==="table"?s.jsx(Hh,{panel:R}):s.jsx(PA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(ih,{extraInfo:r})}):null]})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:k==="panels"?s.jsx(_A,{}):s.jsx(DA,{})}),T?s.jsx("div",{className:"wx-RJbNonjJ wx-info",children:s.jsx(ih,{extraInfo:r})}):null]})})})]})})]})})}const UA=n=>n.split("-").map(a=>a?a.charAt(0).toUpperCase()+a.slice(1):"").join("");function qA(n,a){const{type:r,ext:l}=n;if(r==="folder")return!1;let c;return r&&r!=="file"&&lx[r]?c=r:l?c=lx[l]?l:"file":c="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${a}/${c}.svg`}const GA=u.forwardRef(function(n,a){const{data:r=[],mode:l="cards",drive:c=null,preview:d=!1,panels:m=null,activePanel:p=0,readonly:g=!1,menuOptions:v=$k,extraInfo:w=null,init:x=null,icons:b=qA,previews:C=null,...j}=n,A=u.useRef();A.current=j;const N=u.useMemo(()=>new Pk(Ob),[]),k=u.useMemo(()=>N.in,[N]),T=u.useRef(null);T.current===null&&(T.current=new Rb((O,Y)=>{const _="on"+UA(O);A.current&&A.current[_]&&A.current[_](Y)}),k.setNext(T.current));const R=u.useMemo(()=>({getState:N.getState.bind(N),getReactiveState:N.getReactive.bind(N),getStores:()=>({data:N}),exec:k.exec,setNext:O=>(T.current=T.current.setNext(O),T.current),intercept:k.intercept.bind(k),on:k.on.bind(k),detach:k.detach.bind(k),getFile:N.getFile.bind(N),serialize:N.serialize.bind(N),templates:{preview:C||(()=>null),icon:b==="simple"?(()=>null):b}}),[N,k]),U=u.useRef(0);return u.useEffect(()=>{if(!U.current)x&&x(R);else{const O=N.getState();N.init({data:r,mode:l,drive:c,preview:d,panels:m||O.panels||[],activePanel:p})}U.current++},[N,r,l,c,d,m,p,x,R]),U.current===0&&N.init({data:r,mode:l,drive:c,preview:d,panels:m||[],activePanel:p}),u.useImperativeHandle(a,()=>({...R}),[R]),s.jsx($n.Provider,{value:R,children:s.jsx(dp,{words:fp,optional:!0,children:s.jsx(TA,{children:s.jsx($A,{readonly:g,menuOptions:v,extraInfo:w})})})})});function VA({fonts:n=!0,children:a}){return a?s.jsx(Vy,{fonts:n,children:a}):s.jsx(Vy,{fonts:n})}sp(La);function vp(n,a){if(!n||typeof n!="object"||Array.isArray(n))throw new Error(`Invalid Hub ${a} response.`);return n}function Yc(n,a,r){const l=vp(n,r);if(!Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an array.`);return l[a]}function WA(n,a,r){const l=vp(n,r);if(!l[a]||typeof l[a]!="object"||Array.isArray(l[a]))throw new Error(`Invalid Hub ${r} response: ${a} must be an object.`);return l[a]}async function YA(n,a=!1){return Yc(await Ge(`/api/remote/filesystem/roots${a?"?refresh=1":""}`,void 0,n),"roots","filesystem roots")}async function rh(n,a){const r=await Ge(`/api/remote/filesystem/entries?id=${encodeURIComponent(n)}`,void 0,a);return{folder:WA(r,"folder","filesystem entries"),entries:Yc(r,"entries","filesystem entries")}}async function KA(n,a){return Ge("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:n})},a)}async function QA(n,a,r,l){return Ge("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:n,deviceIds:a,remoteDirectory:r})},l)}async function XA(n,a=!1){const r=await Ge(`/api/remote/files/jobs?active=${a?"1":"0"}`,void 0,n);return{jobs:Yc(r,"jobs","file transfer jobs")}}async function ZA(n,a){return Ge(`/api/remote/files/jobs/${encodeURIComponent(n)}`,void 0,a)}async function JA(n,a){return Ge(`/api/remote/files/jobs/${encodeURIComponent(n)}/cancel`,{method:"POST"},a)}async function ox(n){return Yc(await Ge("/api/remote/filesystem/shared-folders",void 0,n),"folders","shared folders")}async function eN(n,a){return Ge("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:n})},a)}async function tN(n,a,r){return Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"PATCH",body:JSON.stringify(a)},r)}async function nN(n,a){return Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function aN(n,a,r,l){const c=await Ge(`/api/remote/filesystem/shared-folders/${encodeURIComponent(n)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:a,remoteDirectory:r})},l),d=vp(c,"shared folder sync");return{ok:d.ok===!0,jobs:Yc(c,"jobs","shared folder sync"),files:Number(d.files||0),totalBytes:Number(d.totalBytes||0)}}function sN(n){return{id:String(n.id),parentId:n.parent,name:n.name,type:n.type==="file"?"file":"folder",size:Number(n.size||0),modifiedAt:n.date?.toISOString()||null,displayPath:String(n.displayPath||n.name),hasChildren:n.lazy===!0||!!n.data?.length,locked:n.locked===!0}}function cx(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function Id(n){return n.driveType==="network"?"network":n.driveType==="removable"?"removable":"local"}function iN(n){const a=n.filter(r=>Id(r)==="local");return a.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||a[0]||n[0]||null}function rN({hubUrl:n,roots:a,loading:r,error:l,onRefreshRoots:c,onImportFiles:d,onImportFolder:m,onSelectionChange:p,onShareItem:g,onAddSyncFolder:v,onNotice:w}){const x=u.useRef(null),b=u.useRef("/"),C=u.useRef(0),j=u.useRef([]),A=u.useRef(new Map),[N,k]=u.useState(null),[T,R]=u.useState([]),[U,O]=u.useState([]),[Y,_]=u.useState(0),[D,ne]=u.useState(null),[G,te]=u.useState(!1),[B,xe]=u.useState(""),[se,K]=u.useState(new Set),I=a.find(ae=>ae.id===N)||null,Q=T[T.length-1]||null,q=I?Q?.svarPath||`/${I.name}`:null,V=q;u.useEffect(()=>{j.current=T,b.current=V||"/"},[V,T]);const ce=u.useMemo(()=>(A.current.clear(),!I||!V||T.length===0?[]:(T.forEach(ae=>A.current.set(ae.svarPath,ae.hubId)),[...T.map((ae,fe)=>({id:ae.svarPath,parent:fe===0?"/":T[fe-1].svarPath,type:"folder",name:ae.name,date:ae.modifiedAt?new Date(ae.modifiedAt):void 0,lazy:!1})),...U.map(ae=>{const fe=`${V}/${ae.name}`;return A.current.set(fe,ae.id),{id:fe,parent:V,name:ae.name,type:ae.type==="file"?"file":"folder",...ae.type==="file"?{size:ae.size}:{},date:ae.modifiedAt?new Date(ae.modifiedAt):void 0,lazy:ae.type!=="file"&&ae.hasChildren===!0,displayPath:ae.displayPath,locked:ae.locked,driveType:ae.driveType,totalBytes:ae.totalBytes,freeBytes:ae.freeBytes}})])),[I,U,V,T]),be=ae=>A.current.get(String(ae))||String(ae),X=ae=>sN({...ae,id:be(String(ae.id)),parent:be(String(ae.parent))}),$=async(ae,fe)=>{const Ae=ae[ae.length-1];if(!Ae)return;const Te=++C.current;te(!0),xe("");try{const Be=await rh(Ae.hubId,n);if(Te!==C.current)return;if(!Array.isArray(Be.entries))throw new Error("Invalid Hub filesystem entries response.");const Ve={...Ae,displayPath:Be.folder.displayPath||Ae.displayPath,modifiedAt:Be.folder.modifiedAt||Ae.modifiedAt},Je=[...ae.slice(0,-1),Ve];j.current=Je,R(Je),O(Be.entries),_(Et=>Et+1)}catch(Be){if(Te!==C.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Ae.hubId,error:Be}),xe(Be instanceof Error?`${fe}: ${Be.message}`:`${fe}: Unable to read this folder.`)}finally{Te===C.current&&te(!1)}},ue=async ae=>{const fe={svarPath:`/${ae.name}`,hubId:ae.id,name:ae.name,displayPath:ae.displayPath,modifiedAt:ae.modifiedAt},Ae=++C.current;k(ae.id),j.current=[fe],R([fe]),b.current=fe.svarPath,O([]),xe(""),te(!0),ne(ae.id),K(Te=>{const Be=new Set(Te);return Be.delete(ae.id),Be});try{const Te=await rh(ae.id,n);if(Ae!==C.current)return;if(!Array.isArray(Te.entries))throw new Error("Invalid Hub filesystem entries response.");const Be={...fe,displayPath:Te.folder.displayPath||fe.displayPath,modifiedAt:Te.folder.modifiedAt||fe.modifiedAt};j.current=[Be],R([Be]),O(Te.entries),_(Ve=>Ve+1)}catch(Te){if(Ae!==C.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:ae.id,error:Te}),K(Be=>new Set(Be).add(ae.id)),xe(Te instanceof Error?`${ae.name}: ${Te.message}`:`${ae.name}: Unable to read this drive.`),w(Te instanceof Error?`${ae.name}: ${Te.message}`:`${ae.name}: Unable to read this drive.`)}finally{Ae===C.current&&(ne(null),te(!1))}},he=ae=>{const fe=j.current;ae<0||ae>=fe.length||ae===fe.length-1||$(fe.slice(0,ae+1),fe[ae].name)},ve=(ae,fe)=>{if(ae.type!=="folder")return;const Ae=j.current,Te=Ae.findIndex(Ve=>Ve.svarPath===fe);if(Te<0)return;const Be={svarPath:`${fe}/${ae.name}`,hubId:ae.id,name:ae.name,displayPath:ae.displayPath,modifiedAt:ae.modifiedAt};$([...Ae.slice(0,Te+1),Be],ae.name)},Se=()=>he(j.current.length-2),_e=ae=>{if(ae.key!=="Enter"&&ae.code!=="Enter"&&ae.code!=="NumpadEnter"||ae.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Ae=x.current;if(!Ae)return;const Te=Ae.getState().panels?.flatMap(Ve=>Ve.selected||[])||[];if(Te.length!==1)return;const Be=Ae.getFile(String(Te[0]));Be?.type==="folder"&&(ae.preventDefault(),ae.stopPropagation(),ve(X(Be),String(Be.parent||b.current)))};u.useEffect(()=>{const ae=a.find(fe=>fe.id===N)||iN(a);if(K(fe=>new Set([...fe].filter(Ae=>a.some(Te=>Te.id===Ae)))),!ae){k(null),j.current=[],R([]),O([]);return}ue(ae)},[a]);const re=ae=>{x.current=ae,ae.on("request-data",async({id:fe})=>{const Ae=String(fe),Te=be(Ae);try{const Be=await rh(Te,n);if(!Array.isArray(Be.entries))throw new Error("Invalid Hub filesystem entries response.");const Ve=Be.entries.map(Je=>{const Et=`${Ae}/${Je.name}`;return A.current.set(Et,Je.id),{id:Et,parent:Ae,name:Je.name,type:Je.type==="file"?"file":"folder",...Je.type==="file"?{size:Je.size}:{},date:Je.modifiedAt?new Date(Je.modifiedAt):void 0,lazy:Je.type!=="file"&&Je.hasChildren===!0,displayPath:Je.displayPath,locked:Je.locked,driveType:Je.driveType,totalBytes:Je.totalBytes,freeBytes:Je.freeBytes}});await ae.exec("provide-data",{id:Ae,data:Ve})}catch(Be){console.error("[LiveDesk FS] nested getEntries failed",{id:Te,error:Be}),w(Be instanceof Error?Be.message:"Unable to read this folder.")}}),ae.intercept("set-path",({id:fe})=>{const Ae=String(fe),Te=j.current.findIndex(Ve=>Ve.svarPath===Ae);if(Te>=0)return he(Te),!1;const Be=ae.getFile(Ae);if(Be?.type==="folder")return ve(X(Be),String(Be.parent||b.current)),!1}),ae.intercept("open-file",()=>!1),ae.on("select-file",()=>{window.setTimeout(()=>{const Te=(ae.getState().panels?.flatMap(Be=>Be.selected||[])||[]).map(Be=>ae.getFile(Be)).filter(Boolean).map(Be=>X(Be));p(Te.map(Be=>Be.id),Te)},0)})},Z=(ae,fe)=>{const Ae=fe?X(fe):null,Te=()=>{const Be=Ae?.type==="file"?String(fe?.parent||b.current):String(fe?.id||b.current);x.current?.exec("request-data",{id:Be})};return ae==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:ae==="multiselect"?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>{(x.current?.getState().panels?.flatMap(Ve=>Ve.selected||[])||[]).forEach(Ve=>{const Je=x.current?.getFile(Ve);Je&&g(X(Je))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te}]:Ae?[{id:"share",text:"Share to workstations",icon:"mdi mdi-share-variant",handler:()=>g(Ae)},...Ae.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>v(Ae)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Al(Ae.displayPath||Ae.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Te},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${Ae.name}
|
|
14
|
-
${Ae.displayPath||""}`)}]:[]},ze=async()=>{try{await c()}catch(ae){w(ae instanceof Error?ae.message:"Unable to refresh Hub drives.")}},Le=[{id:"local",label:"Local drives",icon:Ml,roots:a.filter(ae=>Id(ae)==="local")},{id:"removable",label:"Removable drives",icon:QS,roots:a.filter(ae=>Id(ae)==="removable")},{id:"network",label:"Network drives",icon:Qh,roots:a.filter(ae=>Id(ae)==="network")}];return s.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[s.jsxs("div",{className:"hub-file-explorer-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub file explorer"}),s.jsxs("strong",{children:[s.jsx(Ml,{size:16})," Browse files on this Hub"]})]}),s.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[s.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:s.jsx(Qx,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(XS,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{ze()},title:"Refresh drives",type:"button",children:s.jsx(Do,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(Ml,{size:24}),s.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?s.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[s.jsx(Ts,{size:24}),s.jsx("strong",{children:l})]}):s.jsxs("div",{className:"hub-file-explorer-content",children:[s.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[s.jsxs("div",{className:"hub-drive-sidebar-title",children:[s.jsx(Ml,{size:15}),s.jsx("strong",{children:"This PC"})]}),Le.map(ae=>ae.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(ae.icon,{size:13}),ae.label]}),s.jsx("div",{className:"hub-drive-list",children:ae.roots.map(fe=>{const Ae=ae.icon,Te=se.has(fe.id)||fe.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${N===fe.id?"active":""} ${Te?"unavailable":""}`,onClick:()=>{ue(fe)},"aria-pressed":N===fe.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(Ae,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:fe.name}),s.jsx("small",{children:fe.displayPath||fe.name}),s.jsxs("em",{children:[cx(fe.freeBytes||0)," free / ",cx(fe.totalBytes||0)]})]}),D===fe.id?s.jsx(Js,{className:"hub-drive-item-status spin",size:15}):Te?s.jsx(sy,{className:"hub-drive-item-status",size:15}):null]},fe.id)})})]},ae.id)),a.length===0&&s.jsxs("div",{className:"hub-drive-sidebar-empty",children:[s.jsx(Ts,{size:17}),s.jsx("span",{children:"No drives available."})]})]}),s.jsxs("div",{className:"hub-file-explorer-browser",children:[s.jsxs("div",{className:"hub-file-explorer-navigation",children:[s.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((ae,fe)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[fe>0&&s.jsx(Xh,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${fe===T.length-1?"current":""}`,onClick:()=>he(fe),"aria-current":fe===T.length-1?"location":void 0,type:"button",children:ae.name})]},ae.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[G&&s.jsx(Js,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:Se,disabled:T.length<=1||G,title:"Back to parent folder",type:"button",children:s.jsx(Ux,{size:16})})]})]}),B&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(sy,{size:15}),s.jsx("span",{children:B})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:s.jsx(VA,{fonts:!1,children:s.jsx(GA,{data:ce,panels:q?[{path:q,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:re,icons:"simple",menuOptions:Z},`${I?.id||"no-root"}:${Y}`)})})]})]})]})}class lN extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,r){console.error("[LiveDesk] Share Files runtime error",a,r.componentStack)}render(){return this.state.error?s.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[s.jsx(Jd,{size:24}),s.jsx("strong",{children:"Share Files could not be opened."}),s.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),s.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[s.jsx(Do,{size:15})," Retry"]})]}):this.props.children}}function oN(n){return n.deviceName||n.hostname||n.deviceId}function cN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c}){const d=new Set(r);return s.jsxs("section",{className:"distribution-targets",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:a==="all"?`${n.length} connected`:`${r.length} selected`})]}),s.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx($c,{size:14})," All connected"]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(an,{size:14})," Selected"]})]})]}),s.jsx("div",{className:"file-share-device-list","aria-label":"Connected workstation targets",children:n.length===0?s.jsx("div",{className:"file-share-empty-inline",children:"No connected workstations."}):n.map(m=>{const p=a==="all"||d.has(m.deviceId);return s.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),s.jsx(an,{size:20,"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:oN(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(Fn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function uN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function dN({folders:n,loading:a,busy:r,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,onAdd:g}){return s.jsxs("section",{className:"file-share-sync-panel",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub folders"}),s.jsx("strong",{children:"Continuous sync"})]}),s.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!l||n.length===0,type:"button",children:[s.jsx(Rd,{size:15})," ",r?"Syncing":"Sync all"]})]}),a?s.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?s.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[s.jsx(Rd,{size:28}),s.jsx("strong",{children:"Add a selected Hub folder"}),s.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):s.jsx("div",{className:"file-share-sync-list",children:n.map(v=>s.jsxs("article",{className:`file-share-sync-row state-${v.status}`,children:[s.jsx("div",{className:"file-share-sync-icon",children:s.jsx(Rd,{size:19})}),s.jsxs("div",{className:"file-share-sync-info",children:[s.jsx("strong",{children:v.name}),s.jsx("span",{children:v.displayPath}),s.jsxs("small",{children:[v.fileCount," files / ",uN(v.totalBytes)," · ",v.lastSyncedAt?`Last sync ${sb(v.lastSyncedAt)} ago`:v.message||"Not synced yet"]})]}),s.jsxs("label",{className:"file-share-auto-sync",children:[s.jsx("input",{type:"checkbox",checked:v.autoSync,onChange:()=>m(v)}),s.jsx("span",{children:"Auto"})]}),s.jsxs("button",{className:"text-button compact",onClick:()=>d(v),disabled:r||!l||v.status==="syncing",type:"button",children:[s.jsx(Do,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(v),title:"Remove sync folder",type:"button",children:s.jsx(Yh,{size:15})})]},v.id))})]})}function fN(n){const r=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return s.jsxs("aside",{className:"file-share-distribution-panel",children:[s.jsxs("div",{className:"file-share-distribution-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Distribution"}),s.jsx("strong",{children:"Hub → workstations"})]}),s.jsx(Fc,{size:18})]}),s.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[s.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),s.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?s.jsxs(s.Fragment,{children:[s.jsx(cN,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),s.jsxs("label",{className:"file-share-destination",children:[s.jsx("span",{children:"Destination folder"}),s.jsxs("div",{children:[s.jsx(No,{size:15}),s.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),s.jsxs("div",{className:"file-share-selection-summary",children:[s.jsx("span",{children:"Selected"}),s.jsx("strong",{children:n.selectedSummary})]}),s.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[s.jsx(Fc,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(No,{size:16})," Add selected folder to Sync"]})]}):s.jsx(dN,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:r,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function mN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function ux(n){return n.totalBytes>0?Math.max(0,Math.min(100,Math.round(n.sentBytes/n.totalBytes*100))):n.totalFiles>0?Math.max(0,Math.min(100,Math.round(n.completedFiles/n.totalFiles*100))):n.state==="completed"?100:0}function dx(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} workstation${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} workstation${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function fx(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function hN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,filePickerRef:w,folderPickerRef:x,onBrowserFileImport:b,onBrowserFolderImport:C,onNotice:j,onTransferChange:A}){const N=Array.isArray(a)?a:[],[k,T]=u.useState([]),[R,U]=u.useState(!0),[O,Y]=u.useState(""),[_,D]=u.useState([]),[ne,G]=u.useState([]),[te,B]=u.useState(null),[xe,se]=u.useState(!1),[K,I]=u.useState([]),[Q,q]=u.useState(!0),[V,ce]=u.useState(!1),[be,X]=u.useState("send"),[$,ue]=u.useState([]),he=u.useRef(new Set),ve=u.useMemo(()=>m==="all"?N.map(je=>je.deviceId):p.filter(je=>N.some(We=>We.deviceId===je)),[N,p,m]),Se=$.find(je=>!fx(je.state)),_e=ne.length===1&&ne[0].type==="folder"?ne[0]:null,re=ne.length===0?"Select files or folders from the Hub explorer.":xe?"Calculating selection size...":te?`${te.files} files, ${te.folders} folders · ${mN(te.totalBytes)}`:`${ne.length} item${ne.length===1?"":"s"} selected`,Z=je=>{A({id:je.jobId,state:je.state,progress:ux(je),message:dx(je)})},ze=u.useCallback(async()=>{const je=await YA(n,!0);return T(je),Y(""),je},[n]),Le=async()=>{try{const We=(await XA(n,!0)).jobs||[],it=await Promise.all([...he.current].map(async Kt=>{try{return await ZA(Kt,n)}catch{return null}})),ot=[...We,...it.filter(Boolean)],gn=[...new Map(ot.map(Kt=>[Kt.jobId,Kt])).values()];ue(gn),gn.forEach(Z),gn.filter(Kt=>fx(Kt.state)).forEach(Kt=>he.current.delete(Kt.jobId))}catch{}};u.useEffect(()=>{let je=!0;U(!0),Y(""),Promise.all([ze(),ox(n).then(it=>{je&&I(it)})]).catch(it=>{je&&(Y(it instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(it instanceof Error?it.message:"Hub file system is unavailable."))}).finally(()=>{je&&(U(!1),q(!1))}),Le();const We=window.setInterval(()=>{Le()},800);return()=>{je=!1,window.clearInterval(We)}},[n,ze]),u.useEffect(()=>{if(_.length===0){B(null);return}let je=!1;return se(!0),KA(_,n).then(We=>{je||B(We)}).catch(We=>{je||j(We instanceof Error?We.message:"Unable to calculate selected size.")}).finally(()=>{je||se(!1)}),()=>{je=!0}},[n,_.join("|")]);const ae=(je,We)=>{D(je),G(We)},fe=je=>{je.forEach(We=>he.current.add(We.jobId)),ue(We=>[...new Map([...We,...je].map(it=>[it.jobId,it])).values()]),je.forEach(Z)},Ae=async()=>{if(!r){j(l);return}if(_.length===0){j("Select files or folders from the Hub explorer.");return}if(ve.length===0){j("Choose at least one connected workstation.");return}if(Se){j("A Hub transfer is already running.");return}try{const je=await QA(_,ve,c.trim(),n);he.current.add(je.jobId),j("Hub transfer queued."),await Le()}catch(je){j(je instanceof Error?je.message:"Unable to start Hub transfer.")}},Te=async je=>{const We=je||_e;if(!We||We.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const it=await eN(We.id,n);I(ot=>[...ot.filter(gn=>gn.id!==it.folder.id),it.folder]),X("sync"),j(`${We.name} is ready for Hub sync.`)}catch(it){j(it instanceof Error?it.message:"Unable to add the Hub folder to Sync.")}},Be=async je=>{if(ve.length===0){j("Choose at least one connected workstation.");return}ce(!0),I(We=>We.map(it=>it.id===je.id?{...it,status:"syncing"}:it));try{const We=await aN(je.id,ve,c.trim(),n);fe(We.jobs||[]),j(We.jobs?.length?"Hub sync queued.":"No changed files to sync.");const it=await ox(n);I(it)}catch(We){j(We instanceof Error?We.message:"Unable to sync the Hub folder."),I(it=>it.map(ot=>ot.id===je.id?{...ot,status:"error",message:"Sync failed"}:ot))}finally{ce(!1)}},Ve=async()=>{ce(!0);try{for(const je of K)await Be(je)}finally{ce(!1)}},Je=async je=>{try{const We=await tN(je.id,{autoSync:!je.autoSync},n);I(it=>it.map(ot=>ot.id===je.id?We.folder:ot))}catch(We){j(We instanceof Error?We.message:"Unable to update auto sync.")}},Et=async je=>{try{await nN(je.id,n),I(We=>We.filter(it=>it.id!==je.id))}catch(We){j(We instanceof Error?We.message:"Unable to remove the sync folder.")}};return s.jsxs("section",{className:"livedesk-file-explorer",children:[s.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:je=>{je.currentTarget.files&&b(je.currentTarget.files),je.currentTarget.value=""}}),s.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:je=>{je.currentTarget.files&&C(je.currentTarget.files),je.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(lN,{onRetry:()=>window.location.reload(),children:[s.jsx(rN,{hubUrl:n,roots:k,loading:R,error:O,onRefreshRoots:ze,onImportFiles:()=>w.current?.click(),onImportFolder:()=>x.current?.click(),onSelectionChange:ae,onShareItem:je=>{D([je.id]),G([je]),X("send")},onAddSyncFolder:je=>{D([je.id]),G([je]),Te(je)},onNotice:j}),s.jsx(fN,{devices:N,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:ne,selectedSummary:re,canShare:r&&!Se&&_.length>0&&ve.length>0&&!xe,onShare:()=>{Ae()},canAddSync:!!_e,onAddSync:()=>{Te()},tab:be,onTabChange:X,folders:K,foldersLoading:Q,syncBusy:V,onSyncAll:()=>{Ve()},onSync:je=>{Be(je)},onToggleAuto:je=>{Je(je)},onRemove:je=>{Et(je)},onAddFolder:()=>{Te()}})]})}),Se&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[dx(Se)," · ",ux(Se),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{JA(Se.jobId,n).then(je=>{ue(We=>We.map(it=>it.jobId===je.jobId?je:it)),Z(je)})},title:"Cancel transfer",type:"button",children:s.jsx(Ya,{size:14})})]})})]})}const pN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1,placeholder:g="Ask LiveDesk to work across your machines..."},v){return s.jsxs("form",{className:"agents-composer",onSubmit:w=>{w.preventDefault(),l()},children:[s.jsxs("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:p,children:[s.jsx(ZS,{size:17}),m!==void 0&&s.jsx("span",{className:"agents-suggested-count","aria-hidden":"true",children:m})]}),s.jsx("textarea",{ref:v,value:a,onChange:w=>r(w.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(Js,{className:"spin",size:16}):s.jsx(Fc,{size:16}),p?"Running":"Run"]})]})}),gN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Kd(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Qd(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function vN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function yN(n){switch(n){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function xN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Va(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Cd(n){const a=Va(n);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function bN(n){const a=Va(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function wN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Xd(n,a){if(a.error)return a.error;const r=xN(a.data),l=wN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=Cd(r.freeMemoryBytes),m=Cd(r.totalMemoryBytes),p=Va(r.totalMemoryBytes)&&Va(r.freeMemoryBytes)!==null?`${Math.round(Va(r.freeMemoryBytes)/Va(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof r.root=="string"?r.root:"",d=Cd(r.freeBytes),m=Va(r.totalBytes)&&Va(r.freeBytes)!==null?`${Math.round(Va(r.freeBytes)/Va(r.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU provider",d=bN(r.usageRatio),m=Va(r.temperatureC)!==null?`${Math.round(Va(r.temperatureC))}°C`:"",p=Cd(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Va(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function mx(n,a){const r=Xd(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${r}`)}function SN({state:n,operation:a}){const r=n.status==="completed"?Ii:n.status==="failed"||n.status==="cancelled"?Ya:n.status==="running"?Js:Xx,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Xd(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return s.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[s.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:s.jsx(r,{size:15})}),s.jsx("strong",{children:n.deviceName}),s.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),s.jsx("small",{children:l})]})}function CN({operation:n,states:a,status:r,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(r),[p,g]=u.useState(!1),[v,w]=u.useState("all"),x=u.useMemo(()=>({total:a.length,completed:a.filter(R=>R.status==="completed").length,failed:a.filter(R=>R.status==="failed").length,running:a.filter(R=>R.status==="running").length,queued:a.filter(R=>R.status==="queued").length,cancelled:a.filter(R=>R.status==="cancelled").length}),[a]),b=a.filter(R=>mx(n,R)),C=b.filter(R=>R.status==="completed").length,j=x.failed>0,A=b.length>0,N=a.filter(R=>v==="issues"?mx(n,R):v==="running"?R.status==="running"||R.status==="queued":v==="completed"?R.status==="completed":v==="failed"?R.status==="failed":!0),k=A&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=a.filter(R=>R.status==="completed").map(R=>Xd(n,R)).filter(Boolean).filter((R,U,O)=>O.indexOf(R)===U).slice(0,2);return s.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[s.jsxs("div",{className:"agent-task-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"LiveDesk Agent"}),s.jsx("strong",{children:yN(n)})]}),s.jsx("span",{className:`agent-task-status status-${A?"completed-with-failures":r}`,children:k})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[x.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[x.completed," completed"]}),x.running>0&&s.jsxs("span",{className:"summary-running",children:[x.running," running"]}),x.queued>0&&s.jsxs("span",{children:[x.queued," queued"]}),j&&s.jsxs("span",{className:"summary-failed",children:[x.failed," failed"]}),C>0&&s.jsxs("span",{className:"summary-cancelled",children:[C," warning"]}),x.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[x.cancelled," cancelled"]})]}),T.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[s.jsx("span",{children:"Result"}),T.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,U)=>{const O=R.status==="completed"?"✓":R.status==="failed"?"×":R.status==="cancelled"?"!":R.status==="running"?"…":"·";return s.jsxs("span",{className:`agent-target-chip status-${R.status}`,title:`${R.deviceName}: ${Xd(n,R)}`,"aria-label":`${U+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String(U+1).padStart(2,"0")}),s.jsx("span",{children:O})]},R.deviceId)})}),a.length>0&&s.jsx("div",{className:"agent-task-details-toggle",children:s.jsxs("button",{type:"button",onClick:()=>g(R=>!R),"aria-expanded":p,children:[p?s.jsx(JS,{size:14}):s.jsx(Zx,{size:14}),p?"Hide details":"Show details"]})}),p&&s.jsxs("div",{className:"agent-task-details",children:[s.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(R=>s.jsx("button",{className:v===R?"active":"",onClick:()=>w(R),role:"tab","aria-selected":v===R,type:"button",children:R==="all"?"All":R==="issues"?"Issues only":R[0].toUpperCase()+R.slice(1)},R))}),s.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(R=>s.jsx(SN,{operation:n,state:R},R.deviceId)):s.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&s.jsxs("div",{className:"agent-task-actions",children:[m&&l&&s.jsxs("button",{onClick:l,disabled:d,type:"button",children:[s.jsx(e0,{size:14})," Cancel"]}),!m&&j&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx(_c,{size:14})," Retry failed"]})]})]})}function jN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function kN({approval:n,busy:a=!1,onApprove:r,onReject:l}){return s.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[s.jsxs("div",{className:"agent-approval-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Approval required"}),s.jsx("strong",{children:n.toolName})]}),s.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),s.jsx("p",{children:n.description}),s.jsx("pre",{children:jN(n.arguments)}),s.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),s.jsxs("div",{className:"agent-approval-actions",children:[s.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[s.jsx(Ya,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx(Ii,{size:14})," Once"]}),s.jsx("button",{disabled:a,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),s.jsx("button",{disabled:a,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),s.jsxs("div",{className:"agent-approval-scope",children:[s.jsx(Jd,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function AN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function NN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:g,emptyTitle:v="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const x=u.useRef(null),b=u.useRef(!0),C=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const A=x.current;A&&(j?.type==="user"&&j.id!==C.current&&(b.current=!0),C.current=j?.id||"",b.current&&(A.scrollTop=A.scrollHeight))},[c,n,j?.id,j?.type,g?.message,g?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:x,onScroll:A=>{const N=A.currentTarget;b.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(A=>A.status==="pending").map(A=>s.jsx(kN,{approval:A,busy:p===A.approvalId,onApprove:N=>d(A,N),onReject:()=>m(A)},A.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:v}),s.jsx("span",{children:w})]}),n.map(A=>{if(A.type==="task"){const N=A;return s.jsx(CN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>r(N.batchId),busy:l===N.batchId},N.id)}return s.jsxs("article",{className:`agents-message ${A.type}`,children:[s.jsx("span",{children:A.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:A.text})]},A.id)}),g&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(Js,{"aria-hidden":"true",size:15}),AN(g.stage)]}),s.jsx("p",{children:g.message})]})]})}const hx=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Sn=["windows","macos","linux"],_r={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Sn},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Sn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Sn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Sn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Sn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Sn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Sn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn}};new Set(Object.keys(_r));const MN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"AI workloads":["ai","gpu","comfyui","ollama","인공지능","모델"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},px=["low","medium","high","critical"];function TN(n){return n.reduce((a,r)=>{const l=_r[r].risk;return px.indexOf(l)>px.indexOf(a)?l:a},"low")}function EN(n){return Sn.filter(a=>n.every(r=>_r[r].supportedPlatforms.includes(a)))}function Ue(n,a,r,l,c,d,m={}){const p=m.description||l,g=c.flatMap(w=>w.split(".")),v=[...new Set([...MN[a],...d,...g])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||TN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||EN(c),keywords:v,recommended:m.recommended??!1,enabled:!0}}const nw=[Ue("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target workstations.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Ue("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),Ue("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),Ue("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),Ue("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),Ue("recommended-ai-workers","Recommended","Verify ComfyUI and Ollama workers","Check whether ComfyUI and Ollama workers and their services are available on the current targets.",["process.list","service.status"],["comfyui","ollama","worker"],{recommended:!0}),Ue("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target workstation.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Ue("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),Ue("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),Ue("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Ue("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ue("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),Ue("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),Ue("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ue("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),Ue("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),Ue("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),Ue("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),Ue("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target workstation after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Ue("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),Ue("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target workstation with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Ue("process-close-app","Processes & services","Close an application","Close application [application] on the target workstation and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Ue("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),Ue("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),Ue("ai-comfyui-status","AI workloads","Check ComfyUI availability","Check the ComfyUI process, service state, and GPU readiness on the current targets.",["process.list","service.status","gpu.status"],["comfyui","stable diffusion","image generation"]),Ue("ai-start-comfyui","AI workloads","Start ComfyUI","If ComfyUI is stopped, launch its registered application or service and verify it is running.",["process.list","application.launch","service.status"],["comfyui","start","launch"],{targetSupport:"single"}),Ue("ai-restart-ollama","AI workloads","Restart Ollama","Check Ollama, restart its registered application or service, and verify the worker is ready.",["process.list","application.close","application.launch","service.status"],["ollama","restart","llm"],{targetSupport:"single"}),Ue("ai-stable-diffusion","AI workloads","Check Stable Diffusion workers","Check Stable Diffusion or Automatic1111 processes and their GPU usage on the current targets.",["process.list","gpu.status"],["stable diffusion","automatic1111","sd"]),Ue("ai-gpu-readiness","AI workloads","Check GPU readiness for AI","Check GPU temperature, VRAM, utilization, and system health before an AI workload starts.",["gpu.status","system.health"],["readiness","inference","training"]),Ue("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target workstation.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Ue("ai-llama-cpp","AI workloads","Check llama.cpp workers","Find llama.cpp or local model worker processes and inspect their recent logs.",["process.list","logs.collect"],["llama.cpp","local model","inference"]),Ue("ai-recover-orphan-python","AI workloads","Recover an orphaned Python worker","Find an orphaned Python AI worker, stop the stale process, then launch its registered worker again.",["process.list","process.control","application.launch"],["python","orphaned","recovery"],{targetSupport:"single"}),Ue("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target workstation.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Ue("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target workstation.",["file.read"],["config","settings","read","구성"]),Ue("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),Ue("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),Ue("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),Ue("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target workstation and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Ue("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target workstation and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Ue("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target workstation.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Ue("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target workstation, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Ue("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target workstation, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Ue("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target workstation, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Ue("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target workstation and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Ue("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target workstation and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Ue("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target workstation and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Ue("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),Ue("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target workstation.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Ue("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ue("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ue("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ue("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),Ue("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),Ue("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),Ue("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ue("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),Ue("power-lock","Power & maintenance","Lock the workstation","Lock the target workstation and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Ue("power-logoff","Power & maintenance","Log off the workstation","Log off the target workstation after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Ue("power-sleep","Power & maintenance","Put the workstation to sleep","Put the target workstation to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Ue("power-restart","Power & maintenance","Restart the workstation","Restart the target workstation after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Ue("power-shutdown","Power & maintenance","Shut down the workstation","Shut down the target workstation after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Ue("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target workstation, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Ue("power-timezone","Power & maintenance","Set the workstation timezone","Set the target workstation timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Ue("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target workstation and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Ue("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),Ue("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),Ue("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),Ue("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),Ue("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),Ue("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),Ue("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target workstation.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Ue("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],lh={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function RN(n,a){return n==="safe-auto"?lh:n==="full-access"?{...lh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...lh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function DN(n,a,r){const l=RN(a,r),c=n.requiredOperations.map(d=>l[_r[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[_r[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${_r[d].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a workstation."}:n.requiredOperations.every(d=>_r[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function LN(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function _N(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function zN(n,a){const r=LN(n.platform);if(!r||!a.supportedPlatforms.includes(r))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>_r[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function aw(n,a,r,l,c,d){const m=DN(n,c,d),p=_N(a,r,l),g=p.map(C=>C.deviceId),v={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...v,reason:"Select at least one connected workstation."};if(n.targetSupport==="single"&&p.length!==1)return{...v,reason:"This task supports one workstation at a time."};if(m.state==="blocked")return v;const w=p.filter(C=>zN(C,n)),x=w.map(C=>C.deviceId),b=g.filter(C=>!x.includes(C));return w.length===0?{...v,unsupportedDeviceIds:b,reason:"No current target supports the required platform and client capabilities."}:{...v,available:!0,availableDeviceIds:x,unsupportedDeviceIds:b}}function IN(n,a,r,l,c,d){return n.filter(m=>m.enabled&&aw(m,a,r,l,c,d).available).length}const oh="livedesk.agentPromptRecent",ch="livedesk.agentPromptFavorites",ON={Recommended:Es,"Health & capacity":pn,"Processes & services":i0,"AI workloads":Wx,"Files & configuration":s0,"Software & automation":Fd,"Network & connectivity":Qh,"Power & maintenance":Bt,"Troubleshooting & recovery":a0};function gx(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(r=>typeof r=="string"):[]}catch{return[]}}function jd(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function uh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function HN(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","AI workloads":"AI","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[n]}function BN(n,a,r){if(!r.trim())return!0;const l=r.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function FN(n){return`permission-${n}`}function PN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function $N(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function UN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,g]=u.useState(""),[v,w]=u.useState("all"),[x,b]=u.useState(()=>gx(oh)),[C,j]=u.useState(()=>gx(ch)),[A,N]=u.useState(0),[k,T]=u.useState(""),R=u.useRef(null),U=u.useRef(null),O=u.useMemo(()=>nw.filter(K=>K.enabled),[]),Y=u.useMemo(()=>new Map(O.map(K=>[K.id,aw(K,n,a,r,l,c)])),[c,n,l,r,a,O]),_=u.useMemo(()=>[...Y.values()].filter(K=>K.available).length,[Y]),D=u.useMemo(()=>n.filter(K=>K.connected&&(a==="all"||a==="auto"||r.includes(K.deviceId))).length,[n,r,a]),ne=u.useMemo(()=>{const K=O.filter(I=>BN(I,Y.get(I.id),p));return v==="recent"?x.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):v==="favorites"?C.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):v==="all"?K:K.filter(I=>{const Q=Y.get(I.id);return v==="read-only"?Q.state==="read-only":v==="auto"?Q.state==="auto":v==="approval"?Q.state==="approval":v==="full-access"?Q.state==="full-access":v==="available"?Q.available:v==="unavailable"?!Q.available:I.category===v})},[Y,C,v,x,p,O]),G=u.useMemo(()=>v!=="all"?[{category:uh(v),templates:ne}]:hx.map(K=>({category:K,templates:ne.filter(I=>I.category===K)})).filter(K=>K.templates.length>0),[v,ne]);u.useEffect(()=>{N(K=>Math.min(K,Math.max(0,ne.length-1)))},[ne.length]),u.useEffect(()=>{jd(oh,x)},[x]),u.useEffect(()=>{jd(ch,C)},[C]),u.useEffect(()=>{U.current?.focus();const K=Q=>{Q.target instanceof Node&&!R.current?.contains(Q.target)&&m()},I=Q=>{Q.key==="Escape"&&(Q.preventDefault(),m())};return document.addEventListener("pointerdown",K),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",K),document.removeEventListener("keydown",I)}},[m]);const te=K=>{const I=Y.get(K.id);if(!I.available){T(I.reason||"This task is not available for the current targets and permission policy.");return}const Q=[K.id,...x.filter(q=>q!==K.id)].slice(0,10);b(Q),jd(oh,Q),d(K.prompt),m()},B=K=>{j(I=>{const Q=I.includes(K)?I.filter(q=>q!==K):[K,...I];return jd(ch,Q),Q})},xe=K=>{K.key==="ArrowDown"?(K.preventDefault(),N(I=>Math.min(I+1,Math.max(0,ne.length-1)))):K.key==="ArrowUp"?(K.preventDefault(),N(I=>Math.max(I-1,0))):K.key==="Enter"&&ne[A]&&(K.preventDefault(),te(ne[A]))};let se=-1;return s.jsxs("section",{className:"agents-suggested-tasks",ref:R,"aria-label":"Suggested tasks",children:[s.jsxs("header",{className:"agents-suggested-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"agents-suggested-title",children:[s.jsx(Es,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[_," available · ",O.length," total. Choose a task, edit it, then run it."]})]}),s.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:s.jsx(Ya,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(t0,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:U,value:p,onChange:K=>g(K.target.value),onKeyDown:xe,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),s.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...hx].map(K=>{const I=K==="recent"?Vx:K==="favorites"?Ch:K==="all"?Es:K==="available"?Fn:K==="unavailable"?n0:K==="read-only"||K==="auto"||K==="approval"||K==="full-access"?Bt:ON[K];return s.jsxs("button",{className:v===K?"active":"",type:"button",title:uh(K),"aria-label":uh(K),"aria-pressed":v===K,onClick:()=>{w(K),N(0),T("")},children:[s.jsx(I,{size:12})," ",HN(K)]},K)})}),k&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:k}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[G.map(K=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:K.category}),K.templates.map(I=>{se+=1;const Q=se===A,q=C.includes(I.id),V=Y.get(I.id),ce=V.availableDeviceIds.length+V.unsupportedDeviceIds.length||D,be=V.available?`Available on ${V.availableDeviceIds.length} of ${ce} target${ce===1?"":"s"}`:`Unavailable: ${V.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${Q?"active":""} ${V.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":Q,"aria-disabled":!V.available,onClick:()=>te(I),children:[s.jsx("span",{children:I.title}),s.jsx("small",{className:"agents-suggested-description",children:I.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:I.category}),s.jsx("em",{className:FN(V.state),children:V.label}),s.jsx("em",{className:`risk-${I.risk}`,children:PN(I.risk)}),s.jsx("em",{children:I.supportedPlatforms.map($N).join(" · ")}),s.jsx("em",{className:V.available?"availability-ok":"availability-unavailable",children:be}),V.available&&V.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",V.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${q?"favorite":""}`,type:"button","aria-label":q?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":q,onClick:()=>B(I.id),children:s.jsx(Ch,{size:14,fill:q?"currentColor":"none"})})]},I.id)})]},K.category)),ne.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function qN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter(Qd),g=r.filter(v=>p.some(w=>w.deviceId===v)).length;return s.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[s.jsxs("div",{className:"agents-target-toolbar",children:[s.jsx("span",{className:"agents-section-label",children:"Targets"}),s.jsxs("div",{className:"agents-target-modes",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx($c,{size:14})," All connected ",s.jsx("small",{children:p.length})]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(Ii,{size:14})," Selected ",g]}),s.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[s.jsx(Es,{size:14})," Auto"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx($c,{size:14})," Group ",s.jsx("small",{children:"Soon"})]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(Jd,{size:14}),s.jsx("span",{children:"Permission"}),s.jsxs("select",{value:d,onChange:v=>m(v.target.value),"aria-label":"Agent permission mode",children:[s.jsx("option",{value:"ask",children:"Ask"}),s.jsx("option",{value:"safe-auto",children:"Safe Auto"}),s.jsx("option",{value:"full-access",children:"Full Access"}),s.jsx("option",{value:"custom",children:"Custom"})]}),s.jsx(Zx,{size:13,"aria-hidden":"true"})]})]}),s.jsx("div",{className:"agents-target-list",children:n.length===0?s.jsx("span",{className:"agents-target-empty",children:"No workstations discovered."}):n.map(v=>{const w=Qd(v),x=a==="all"||a==="auto"?w:r.includes(v.deviceId);return s.jsxs("label",{className:`agents-target-option ${x?"selected":""} ${w?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:x,disabled:!w||a!=="selected",onChange:()=>c(v.deviceId)}),s.jsx("span",{className:"agents-target-icon",children:s.jsx(an,{size:15})}),s.jsxs("span",{children:[s.jsx("strong",{children:Kd(v)}),s.jsx("small",{children:w?"Ready":v.connected?"Agent reconnecting":"Offline"})]}),x&&s.jsx(Ii,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},v.deviceId)})})]})}async function GN(n,a){return Ge("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function VN(n,a){return Ge("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function WN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function YN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function KN(n){return Ge("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function QN(n,a,r,l){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function XN(n,a,r,l="User rejected this action."){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function ZN(n,a,r){return Ge(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function JN(n,a){return Ge("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function eM(n,a){return Ge("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function tM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function nM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function aM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function Sl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function kd(n,a){const r=new Map(a.map(l=>[l.deviceId,Kd(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:vN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function sM(n,a){const r=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=r.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function iM(n,a){const r=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${r.filter(p=>{const g=p.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
|
|
14
|
+
${Ae.displayPath||""}`)}]:[]},ze=async()=>{try{await c()}catch(ae){w(ae instanceof Error?ae.message:"Unable to refresh Hub drives.")}},Le=[{id:"local",label:"Local drives",icon:Ml,roots:a.filter(ae=>Id(ae)==="local")},{id:"removable",label:"Removable drives",icon:QS,roots:a.filter(ae=>Id(ae)==="removable")},{id:"network",label:"Network drives",icon:Qh,roots:a.filter(ae=>Id(ae)==="network")}];return s.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[s.jsxs("div",{className:"hub-file-explorer-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub file explorer"}),s.jsxs("strong",{children:[s.jsx(Ml,{size:16})," Browse files on this Hub"]})]}),s.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[s.jsx("button",{className:"icon-button",onClick:d,title:"Import files from this browser",type:"button",children:s.jsx(Qx,{size:16})}),s.jsx("button",{className:"icon-button",onClick:m,title:"Import folder from this browser",type:"button",children:s.jsx(XS,{size:16})}),s.jsx("button",{className:"icon-button",onClick:()=>{ze()},title:"Refresh drives",type:"button",children:s.jsx(Do,{size:16})})]})]}),r?s.jsxs("div",{className:"hub-file-explorer-state",children:[s.jsx(Ml,{size:24}),s.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):l?s.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[s.jsx(Ts,{size:24}),s.jsx("strong",{children:l})]}):s.jsxs("div",{className:"hub-file-explorer-content",children:[s.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[s.jsxs("div",{className:"hub-drive-sidebar-title",children:[s.jsx(Ml,{size:15}),s.jsx("strong",{children:"This PC"})]}),Le.map(ae=>ae.roots.length>0&&s.jsxs("section",{className:"hub-drive-group",children:[s.jsxs("h3",{children:[s.jsx(ae.icon,{size:13}),ae.label]}),s.jsx("div",{className:"hub-drive-list",children:ae.roots.map(fe=>{const Ae=ae.icon,Te=se.has(fe.id)||fe.locked===!0;return s.jsxs("button",{className:`hub-drive-item ${N===fe.id?"active":""} ${Te?"unavailable":""}`,onClick:()=>{ue(fe)},"aria-pressed":N===fe.id,type:"button",children:[s.jsx("span",{className:"hub-drive-item-icon",children:s.jsx(Ae,{size:16})}),s.jsxs("span",{className:"hub-drive-item-copy",children:[s.jsx("strong",{children:fe.name}),s.jsx("small",{children:fe.displayPath||fe.name}),s.jsxs("em",{children:[cx(fe.freeBytes||0)," free / ",cx(fe.totalBytes||0)]})]}),D===fe.id?s.jsx(Js,{className:"hub-drive-item-status spin",size:15}):Te?s.jsx(sy,{className:"hub-drive-item-status",size:15}):null]},fe.id)})})]},ae.id)),a.length===0&&s.jsxs("div",{className:"hub-drive-sidebar-empty",children:[s.jsx(Ts,{size:17}),s.jsx("span",{children:"No drives available."})]})]}),s.jsxs("div",{className:"hub-file-explorer-browser",children:[s.jsxs("div",{className:"hub-file-explorer-navigation",children:[s.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((ae,fe)=>s.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[fe>0&&s.jsx(Xh,{size:13,"aria-hidden":"true"}),s.jsx("button",{className:`hub-file-explorer-breadcrumb ${fe===T.length-1?"current":""}`,onClick:()=>he(fe),"aria-current":fe===T.length-1?"location":void 0,type:"button",children:ae.name})]},ae.svarPath))}),s.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[G&&s.jsx(Js,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),s.jsx("button",{className:"icon-button",onClick:Se,disabled:T.length<=1||G,title:"Back to parent folder",type:"button",children:s.jsx(Ux,{size:16})})]})]}),B&&s.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[s.jsx(sy,{size:15}),s.jsx("span",{children:B})]}),s.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:s.jsx(VA,{fonts:!1,children:s.jsx(GA,{data:ce,panels:q?[{path:q,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:re,icons:"simple",menuOptions:Z},`${I?.id||"no-root"}:${Y}`)})})]})]})]})}class lN extends u.Component{state={error:null};static getDerivedStateFromError(a){return{error:a}}componentDidCatch(a,r){console.error("[LiveDesk] Share Files runtime error",a,r.componentStack)}render(){return this.state.error?s.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[s.jsx(Jd,{size:24}),s.jsx("strong",{children:"Share Files could not be opened."}),s.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),s.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[s.jsx(Do,{size:15})," Retry"]})]}):this.props.children}}function oN(n){return n.deviceName||n.hostname||n.deviceId}function cN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c}){const d=new Set(r);return s.jsxs("section",{className:"distribution-targets",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:a==="all"?`${n.length} connected`:`${r.length} selected`})]}),s.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx($c,{size:14})," All connected"]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(an,{size:14})," Selected"]})]})]}),s.jsx("div",{className:"file-share-device-list","aria-label":"Connected workstation targets",children:n.length===0?s.jsx("div",{className:"file-share-empty-inline",children:"No connected workstations."}):n.map(m=>{const p=a==="all"||d.has(m.deviceId);return s.jsxs("label",{className:`file-share-device-option ${p?"selected":""}`,children:[s.jsx("input",{type:"checkbox",checked:p,disabled:a==="all",onChange:()=>c(m.deviceId)}),s.jsx(an,{size:20,"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:oN(m)}),s.jsxs("small",{children:["Slot ",m.slotNumber?String(m.slotNumber).padStart(3,"0"):"-"," / ",m.platform||"unknown OS"]})]}),s.jsx(Fn,{size:17,"aria-hidden":"true"})]},m.deviceId)})})]})}function uN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function dN({folders:n,loading:a,busy:r,canSync:l,onSyncAll:c,onSync:d,onToggleAuto:m,onRemove:p,onAdd:g}){return s.jsxs("section",{className:"file-share-sync-panel",children:[s.jsxs("div",{className:"file-share-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub folders"}),s.jsx("strong",{children:"Continuous sync"})]}),s.jsxs("button",{className:"text-button compact",onClick:c,disabled:r||!l||n.length===0,type:"button",children:[s.jsx(Rd,{size:15})," ",r?"Syncing":"Sync all"]})]}),a?s.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):n.length===0?s.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[s.jsx(Rd,{size:28}),s.jsx("strong",{children:"Add a selected Hub folder"}),s.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):s.jsx("div",{className:"file-share-sync-list",children:n.map(v=>s.jsxs("article",{className:`file-share-sync-row state-${v.status}`,children:[s.jsx("div",{className:"file-share-sync-icon",children:s.jsx(Rd,{size:19})}),s.jsxs("div",{className:"file-share-sync-info",children:[s.jsx("strong",{children:v.name}),s.jsx("span",{children:v.displayPath}),s.jsxs("small",{children:[v.fileCount," files / ",uN(v.totalBytes)," · ",v.lastSyncedAt?`Last sync ${sb(v.lastSyncedAt)} ago`:v.message||"Not synced yet"]})]}),s.jsxs("label",{className:"file-share-auto-sync",children:[s.jsx("input",{type:"checkbox",checked:v.autoSync,onChange:()=>m(v)}),s.jsx("span",{children:"Auto"})]}),s.jsxs("button",{className:"text-button compact",onClick:()=>d(v),disabled:r||!l||v.status==="syncing",type:"button",children:[s.jsx(Do,{size:14})," Sync now"]}),s.jsx("button",{className:"icon-button",onClick:()=>p(v),title:"Remove sync folder",type:"button",children:s.jsx(Yh,{size:15})})]},v.id))})]})}function fN(n){const r=(n.targetMode==="all"?n.devices.map(l=>l.deviceId):n.selectedTargetIds).length>0;return s.jsxs("aside",{className:"file-share-distribution-panel",children:[s.jsxs("div",{className:"file-share-distribution-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Distribution"}),s.jsx("strong",{children:"Hub → workstations"})]}),s.jsx(Fc,{size:18})]}),s.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[s.jsx("button",{className:n.tab==="send"?"active":"",onClick:()=>n.onTabChange("send"),role:"tab","aria-selected":n.tab==="send",type:"button",children:"Send"}),s.jsx("button",{className:n.tab==="sync"?"active":"",onClick:()=>n.onTabChange("sync"),role:"tab","aria-selected":n.tab==="sync",type:"button",children:"Sync"})]}),n.tab==="send"?s.jsxs(s.Fragment,{children:[s.jsx(cN,{devices:n.devices,mode:n.targetMode,selectedIds:n.selectedTargetIds,onModeChange:n.onTargetModeChange,onToggle:n.onTargetToggle}),s.jsxs("label",{className:"file-share-destination",children:[s.jsx("span",{children:"Destination folder"}),s.jsxs("div",{children:[s.jsx(No,{size:15}),s.jsx("input",{value:n.remoteDirectory,onChange:l=>n.onRemoteDirectoryChange(l.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),s.jsxs("div",{className:"file-share-selection-summary",children:[s.jsx("span",{children:"Selected"}),s.jsx("strong",{children:n.selectedSummary})]}),s.jsxs("button",{className:"file-share-share-button",onClick:n.onShare,disabled:!n.canShare,type:"button",children:[s.jsx(Fc,{size:17})," Share selected"]}),s.jsxs("button",{className:"file-share-secondary-button",onClick:n.onAddSync,disabled:!n.canAddSync,type:"button",children:[s.jsx(No,{size:16})," Add selected folder to Sync"]})]}):s.jsx(dN,{folders:n.folders,loading:n.foldersLoading,busy:n.syncBusy,canSync:r,onSyncAll:n.onSyncAll,onSync:n.onSync,onToggleAuto:n.onToggleAuto,onRemove:n.onRemove,onAdd:n.onAddFolder})]})}function mN(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;return`${r.toFixed(l===0||r>=100?0:1)} ${a[l]}`}function ux(n){return n.totalBytes>0?Math.max(0,Math.min(100,Math.round(n.sentBytes/n.totalBytes*100))):n.totalFiles>0?Math.max(0,Math.min(100,Math.round(n.completedFiles/n.totalFiles*100))):n.state==="completed"?100:0}function dx(n){return n.state==="scanning"?"Scanning selected Hub items":n.state==="queued"?"Preparing transfer":n.state==="sending"?`${n.completedFiles}/${n.totalFiles} · ${n.currentPath||"sending"}`:n.state==="completed"?`Sent ${n.totalFiles} file${n.totalFiles===1?"":"s"} to ${n.targetCount} workstation${n.targetCount===1?"":"s"}`:n.state==="partially-failed"?`${n.failedTargets.length} workstation${n.failedTargets.length===1?"":"s"} failed`:n.state==="cancelled"?"Transfer cancelled":n.error||"Transfer failed"}function fx(n){return["completed","partially-failed","failed","cancelled"].includes(n)}function hN({hubUrl:n,devices:a,localFeatureAccess:r,upgradeNotice:l,remoteDirectory:c,onRemoteDirectoryChange:d,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,filePickerRef:w,folderPickerRef:x,onBrowserFileImport:b,onBrowserFolderImport:C,onNotice:j,onTransferChange:A}){const N=Array.isArray(a)?a:[],[k,T]=u.useState([]),[R,U]=u.useState(!0),[O,Y]=u.useState(""),[_,D]=u.useState([]),[ne,G]=u.useState([]),[te,B]=u.useState(null),[xe,se]=u.useState(!1),[K,I]=u.useState([]),[Q,q]=u.useState(!0),[V,ce]=u.useState(!1),[be,X]=u.useState("send"),[$,ue]=u.useState([]),he=u.useRef(new Set),ve=u.useMemo(()=>m==="all"?N.map(je=>je.deviceId):p.filter(je=>N.some(We=>We.deviceId===je)),[N,p,m]),Se=$.find(je=>!fx(je.state)),_e=ne.length===1&&ne[0].type==="folder"?ne[0]:null,re=ne.length===0?"Select files or folders from the Hub explorer.":xe?"Calculating selection size...":te?`${te.files} files, ${te.folders} folders · ${mN(te.totalBytes)}`:`${ne.length} item${ne.length===1?"":"s"} selected`,Z=je=>{A({id:je.jobId,state:je.state,progress:ux(je),message:dx(je)})},ze=u.useCallback(async()=>{const je=await YA(n,!0);return T(je),Y(""),je},[n]),Le=async()=>{try{const We=(await XA(n,!0)).jobs||[],it=await Promise.all([...he.current].map(async Kt=>{try{return await ZA(Kt,n)}catch{return null}})),ot=[...We,...it.filter(Boolean)],gn=[...new Map(ot.map(Kt=>[Kt.jobId,Kt])).values()];ue(gn),gn.forEach(Z),gn.filter(Kt=>fx(Kt.state)).forEach(Kt=>he.current.delete(Kt.jobId))}catch{}};u.useEffect(()=>{let je=!0;U(!0),Y(""),Promise.all([ze(),ox(n).then(it=>{je&&I(it)})]).catch(it=>{je&&(Y(it instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),j(it instanceof Error?it.message:"Hub file system is unavailable."))}).finally(()=>{je&&(U(!1),q(!1))}),Le();const We=window.setInterval(()=>{Le()},800);return()=>{je=!1,window.clearInterval(We)}},[n,ze]),u.useEffect(()=>{if(_.length===0){B(null);return}let je=!1;return se(!0),KA(_,n).then(We=>{je||B(We)}).catch(We=>{je||j(We instanceof Error?We.message:"Unable to calculate selected size.")}).finally(()=>{je||se(!1)}),()=>{je=!0}},[n,_.join("|")]);const ae=(je,We)=>{D(je),G(We)},fe=je=>{je.forEach(We=>he.current.add(We.jobId)),ue(We=>[...new Map([...We,...je].map(it=>[it.jobId,it])).values()]),je.forEach(Z)},Ae=async()=>{if(!r){j(l);return}if(_.length===0){j("Select files or folders from the Hub explorer.");return}if(ve.length===0){j("Choose at least one connected workstation.");return}if(Se){j("A Hub transfer is already running.");return}try{const je=await QA(_,ve,c.trim(),n);he.current.add(je.jobId),j("Hub transfer queued."),await Le()}catch(je){j(je instanceof Error?je.message:"Unable to start Hub transfer.")}},Te=async je=>{const We=je||_e;if(!We||We.type!=="folder"){j("Select one folder to add it to Sync.");return}try{const it=await eN(We.id,n);I(ot=>[...ot.filter(gn=>gn.id!==it.folder.id),it.folder]),X("sync"),j(`${We.name} is ready for Hub sync.`)}catch(it){j(it instanceof Error?it.message:"Unable to add the Hub folder to Sync.")}},Be=async je=>{if(ve.length===0){j("Choose at least one connected workstation.");return}ce(!0),I(We=>We.map(it=>it.id===je.id?{...it,status:"syncing"}:it));try{const We=await aN(je.id,ve,c.trim(),n);fe(We.jobs||[]),j(We.jobs?.length?"Hub sync queued.":"No changed files to sync.");const it=await ox(n);I(it)}catch(We){j(We instanceof Error?We.message:"Unable to sync the Hub folder."),I(it=>it.map(ot=>ot.id===je.id?{...ot,status:"error",message:"Sync failed"}:ot))}finally{ce(!1)}},Ve=async()=>{ce(!0);try{for(const je of K)await Be(je)}finally{ce(!1)}},Je=async je=>{try{const We=await tN(je.id,{autoSync:!je.autoSync},n);I(it=>it.map(ot=>ot.id===je.id?We.folder:ot))}catch(We){j(We instanceof Error?We.message:"Unable to update auto sync.")}},Et=async je=>{try{await nN(je.id,n),I(We=>We.filter(it=>it.id!==je.id))}catch(We){j(We instanceof Error?We.message:"Unable to remove the sync folder.")}};return s.jsxs("section",{className:"livedesk-file-explorer",children:[s.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:je=>{je.currentTarget.files&&b(je.currentTarget.files),je.currentTarget.value=""}}),s.jsx("input",{ref:x,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:je=>{je.currentTarget.files&&C(je.currentTarget.files),je.currentTarget.value=""}}),s.jsx("div",{className:"file-share-workspace",children:s.jsxs(lN,{onRetry:()=>window.location.reload(),children:[s.jsx(rN,{hubUrl:n,roots:k,loading:R,error:O,onRefreshRoots:ze,onImportFiles:()=>w.current?.click(),onImportFolder:()=>x.current?.click(),onSelectionChange:ae,onShareItem:je=>{D([je.id]),G([je]),X("send")},onAddSyncFolder:je=>{D([je.id]),G([je]),Te(je)},onNotice:j}),s.jsx(fN,{devices:N,targetMode:m,selectedTargetIds:p,onTargetModeChange:g,onTargetToggle:v,remoteDirectory:c,onRemoteDirectoryChange:d,selectedEntries:ne,selectedSummary:re,canShare:r&&!Se&&_.length>0&&ve.length>0&&!xe,onShare:()=>{Ae()},canAddSync:!!_e,onAddSync:()=>{Te()},tab:be,onTabChange:X,folders:K,foldersLoading:Q,syncBusy:V,onSyncAll:()=>{Ve()},onSync:je=>{Be(je)},onToggleAuto:je=>{Je(je)},onRemove:je=>{Et(je)},onAddFolder:()=>{Te()}})]})}),Se&&s.jsx("footer",{className:"file-share-workspace-footer",children:s.jsxs("span",{children:[dx(Se)," · ",ux(Se),"% ",s.jsx("button",{className:"icon-button",onClick:()=>{JA(Se.jobId,n).then(je=>{ue(We=>We.map(it=>it.jobId===je.jobId?je:it)),Z(je)})},title:"Cancel transfer",type:"button",children:s.jsx(Ya,{size:14})})]})})]})}const pN=u.forwardRef(function({value:a,onChange:r,onSubmit:l,onOpenSuggestedTasks:c,suggestedOpen:d=!1,suggestedTaskCount:m,disabled:p=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:v=!1},w){return s.jsxs("form",{className:"agents-composer",onSubmit:x=>{x.preventDefault(),l()},children:[s.jsx("button",{className:`agents-suggested-trigger ${d?"active":""}`,type:"button","aria-label":m===void 0?"Open Suggested tasks":`Open Suggested tasks (${m} available)`,"aria-expanded":d,onClick:c,disabled:p,children:s.jsx(ZS,{size:17})}),s.jsx("textarea",{ref:w,value:a,onChange:x=>r(x.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:v?1:2,disabled:p}),s.jsxs("button",{className:"agents-run-button",type:"submit",disabled:p||!a.trim(),children:[p?s.jsx(Js,{className:"spin",size:16}):s.jsx(Fc,{size:16}),p?"Running":"Run"]})]})}),gN=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Kd(n){return n.deviceName?.trim()||n.hostname?.trim()||n.deviceId}function Qd(n){return n.connected!==!0?!1:n.synthetic===!0?!0:!n.channels||n.channels.control===!0}function vN(n){return n==="running"||n==="completed"||n==="failed"||n==="cancelled"?n:"queued"}function yN(n){switch(n){case"process.list":return"Process list";case"system.health":return"System health";case"gpu.status":return"GPU status";case"disk.status":return"Disk status";case"service.status":return"Service status";case"diagnostics.collect":return"Diagnostics";case"process.control":return"Process control";case"service.control":return"Service control";case"application.launch":return"Launch application";case"application.close":return"Close application";case"file.read":return"Read file";case"file.write":return"Write file";case"file.delete":return"Delete file";case"file.list":return"List directory";case"command.run":return"Run command";case"script.run":return"Run script";case"software.install":return"Install software";case"network.status":return"Network status";case"system.power":return"Power action";case"system.configure":return"System configuration";case"logs.collect":return"Collect logs"}}function xN(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Va(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Cd(n){const a=Va(n);return a===null?"":a<1024**2?`${Math.round(a/1024)}K`:a<1024**3?`${(a/1024**2).toFixed(0)}M`:`${(a/1024**3).toFixed(1)}G`}function bN(n){const a=Va(n);return a===null?"":`${Math.round((a<=1?a:a/100)*100)}%`}function wN(n){return!n||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(n.trim())?"":n.trim()}function Xd(n,a){if(a.error)return a.error;const r=xN(a.data),l=wN(a.result||"");if(!r)return l||a.stage||a.status;if(n==="system.health"){const c=typeof r.machine=="string"?r.machine:"",d=Cd(r.freeMemoryBytes),m=Cd(r.totalMemoryBytes),p=Va(r.totalMemoryBytes)&&Va(r.freeMemoryBytes)!==null?`${Math.round(Va(r.freeMemoryBytes)/Va(r.totalMemoryBytes)*100)}% RAM free`:"";return[c,d&&m?`RAM ${d}/${m}`:"",p,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||l||a.status}if(n==="disk.status"){const c=typeof r.root=="string"?r.root:"",d=Cd(r.freeBytes),m=Va(r.totalBytes)&&Va(r.freeBytes)!==null?`${Math.round(Va(r.freeBytes)/Va(r.totalBytes)*100)}% free`:"";return[c,d&&`${d} free`,m].filter(Boolean).join(" · ")||l||a.status}if(n==="gpu.status"){const c=typeof r.name=="string"&&r.name?r.name:"No GPU provider",d=bN(r.usageRatio),m=Va(r.temperatureC)!==null?`${Math.round(Va(r.temperatureC))}°C`:"",p=Cd(r.freeMemoryBytes);return[c,d&&`GPU ${d}`,m,p&&`${p} free`].filter(Boolean).join(" · ")||l||a.status}if(n==="process.list"){const c=Va(r.count);return c!==null?`${c} matching process${c===1?"":"es"}`:l||a.status}if(n==="network.status"){const c=Array.isArray(r.adapters)?r.adapters.length:null;return c!==null?`${c} active adapter${c===1?"":"s"}`:l||a.status}return l||a.stage||a.status}function mx(n,a){const r=Xd(n,a);return a.status==="failed"||a.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${a.result||""} ${r}`)}function SN({state:n,operation:a}){const r=n.status==="completed"?Ii:n.status==="failed"||n.status==="cancelled"?Ya:n.status==="running"?Js:Xx,l=n.status==="running"?n.stage||"Working":n.status==="completed"?a?Xd(a,n):n.result||"Completed":n.status==="failed"?n.error||"Failed":n.status==="cancelled"?"Cancelled":"Queued";return s.jsxs("div",{className:`agent-target-row status-${n.status}`,"data-agent-target-id":n.deviceId,children:[s.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:s.jsx(r,{size:15})}),s.jsx("strong",{children:n.deviceName}),s.jsx("span",{className:"agent-target-state",children:n.status[0].toUpperCase()+n.status.slice(1)}),s.jsx("small",{children:l})]})}function CN({operation:n,states:a,status:r,onCancel:l,onRetry:c,busy:d=!1}){const m=["running","queued"].includes(r),[p,g]=u.useState(!1),[v,w]=u.useState("all"),x=u.useMemo(()=>({total:a.length,completed:a.filter(R=>R.status==="completed").length,failed:a.filter(R=>R.status==="failed").length,running:a.filter(R=>R.status==="running").length,queued:a.filter(R=>R.status==="queued").length,cancelled:a.filter(R=>R.status==="cancelled").length}),[a]),b=a.filter(R=>mx(n,R)),C=b.filter(R=>R.status==="completed").length,j=x.failed>0,A=b.length>0,N=a.filter(R=>v==="issues"?mx(n,R):v==="running"?R.status==="running"||R.status==="queued":v==="completed"?R.status==="completed":v==="failed"?R.status==="failed":!0),k=A&&!m||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=a.filter(R=>R.status==="completed").map(R=>Xd(n,R)).filter(Boolean).filter((R,U,O)=>O.indexOf(R)===U).slice(0,2);return s.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[s.jsxs("div",{className:"agent-task-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"LiveDesk Agent"}),s.jsx("strong",{children:yN(n)})]}),s.jsx("span",{className:`agent-task-status status-${A?"completed-with-failures":r}`,children:k})]}),s.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[s.jsxs("strong",{children:[x.total," targets"]}),s.jsxs("span",{className:"summary-completed",children:[x.completed," completed"]}),x.running>0&&s.jsxs("span",{className:"summary-running",children:[x.running," running"]}),x.queued>0&&s.jsxs("span",{children:[x.queued," queued"]}),j&&s.jsxs("span",{className:"summary-failed",children:[x.failed," failed"]}),C>0&&s.jsxs("span",{className:"summary-cancelled",children:[C," warning"]}),x.cancelled>0&&s.jsxs("span",{className:"summary-cancelled",children:[x.cancelled," cancelled"]})]}),T.length>0&&s.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[s.jsx("span",{children:"Result"}),T.join(" · ")]}),s.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:a.map((R,U)=>{const O=R.status==="completed"?"✓":R.status==="failed"?"×":R.status==="cancelled"?"!":R.status==="running"?"…":"·";return s.jsxs("span",{className:`agent-target-chip status-${R.status}`,title:`${R.deviceName}: ${Xd(n,R)}`,"aria-label":`${U+1}. ${R.deviceName}: ${R.status}`,children:[s.jsx("b",{children:String(U+1).padStart(2,"0")}),s.jsx("span",{children:O})]},R.deviceId)})}),a.length>0&&s.jsx("div",{className:"agent-task-details-toggle",children:s.jsxs("button",{type:"button",onClick:()=>g(R=>!R),"aria-expanded":p,children:[p?s.jsx(JS,{size:14}):s.jsx(Zx,{size:14}),p?"Hide details":"Show details"]})}),p&&s.jsxs("div",{className:"agent-task-details",children:[s.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(R=>s.jsx("button",{className:v===R?"active":"",onClick:()=>w(R),role:"tab","aria-selected":v===R,type:"button",children:R==="all"?"All":R==="issues"?"Issues only":R[0].toUpperCase()+R.slice(1)},R))}),s.jsx("div",{className:"agent-task-rows",children:N.length>0?N.map(R=>s.jsx(SN,{operation:n,state:R},R.deviceId)):s.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(m||j)&&s.jsxs("div",{className:"agent-task-actions",children:[m&&l&&s.jsxs("button",{onClick:l,disabled:d,type:"button",children:[s.jsx(e0,{size:14})," Cancel"]}),!m&&j&&c&&s.jsxs("button",{onClick:c,disabled:d,type:"button",children:[s.jsx(_c,{size:14})," Retry failed"]})]})]})}function jN(n){try{return JSON.stringify(n,null,2).slice(0,6e3)}catch{return"{}"}}function kN({approval:n,busy:a=!1,onApprove:r,onReject:l}){return s.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[s.jsxs("div",{className:"agent-approval-head",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Approval required"}),s.jsx("strong",{children:n.toolName})]}),s.jsx("span",{className:`agent-approval-risk risk-${n.risk}`,children:n.risk})]}),s.jsx("p",{children:n.description}),s.jsx("pre",{children:jN(n.arguments)}),s.jsxs("small",{children:["Permission: ",n.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),s.jsxs("div",{className:"agent-approval-actions",children:[s.jsxs("button",{className:"reject",disabled:a,onClick:l,type:"button",children:[s.jsx(Ya,{size:14})," Reject"]}),s.jsxs("button",{disabled:a,onClick:()=>r("once"),type:"button",children:[s.jsx(Ii,{size:14})," Once"]}),s.jsx("button",{disabled:a,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),s.jsx("button",{disabled:a,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),s.jsxs("div",{className:"agent-approval-scope",children:[s.jsx(Jd,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function AN(n){return n==="queued"?"Request queued":n==="checking-codex"?"Checking Codex":n==="preparing-tools"?"Preparing tools":n==="thinking"?"Preparing answer":n==="tool-running"?"Working on computers":n==="recovering"?"Retrying safely":n==="waiting-approval"?"Waiting for approval":"Working"}function NN({items:n,onCancel:a,onRetry:r,busyBatchId:l,approvals:c,onApprove:d,onReject:m,busyApprovalId:p,progress:g,emptyTitle:v="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “모든 PC에서 ComfyUI가 실행 중인지 확인해줘”."}){const x=u.useRef(null),b=u.useRef(!0),C=u.useRef(""),j=n[n.length-1];return u.useLayoutEffect(()=>{const A=x.current;A&&(j?.type==="user"&&j.id!==C.current&&(b.current=!0),C.current=j?.id||"",b.current&&(A.scrollTop=A.scrollHeight))},[c,n,j?.id,j?.type,g?.message,g?.stage]),s.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:x,onScroll:A=>{const N=A.currentTarget;b.current=N.scrollHeight-N.scrollTop-N.clientHeight<72},children:[c.filter(A=>A.status==="pending").map(A=>s.jsx(kN,{approval:A,busy:p===A.approvalId,onApprove:N=>d(A,N),onReject:()=>m(A)},A.approvalId)),n.length===0&&s.jsxs("div",{className:"agents-empty-conversation",children:[s.jsx("strong",{children:v}),s.jsx("span",{children:w})]}),n.map(A=>{if(A.type==="task"){const N=A;return s.jsx(CN,{operation:N.operation,states:N.states,status:N.status,onCancel:()=>a(N.batchId,N.agentRunId),onRetry:()=>r(N.batchId),busy:l===N.batchId},N.id)}return s.jsxs("article",{className:`agents-message ${A.type}`,children:[s.jsx("span",{children:A.type==="user"?"You":"LiveDesk Agent"}),s.jsx("p",{children:A.text})]},A.id)}),g&&s.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[s.jsxs("span",{children:[s.jsx(Js,{"aria-hidden":"true",size:15}),AN(g.stage)]}),s.jsx("p",{children:g.message})]})]})}const hx=["Recommended","Health & capacity","Processes & services","AI workloads","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],Sn=["windows","macos","linux"],_r={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:Sn},"service.control":{label:"service control",permissionCategory:"serviceControl",readOnly:!1,risk:"high",supportedPlatforms:["windows","linux"]},"application.launch":{label:"application launch",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Sn},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:Sn},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:Sn},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:Sn},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:Sn},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:Sn},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:Sn},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:Sn},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:Sn}};new Set(Object.keys(_r));const MN={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"AI workloads":["ai","gpu","comfyui","ollama","인공지능","모델"],"Files & configuration":["file","config","directory","파일","설정","폴더"],"Software & automation":["software","install","automation","프로그램","설치","자동화"],"Network & connectivity":["network","connection","adapter","네트워크","연결","어댑터"],"Power & maintenance":["power","maintenance","restart","전원","유지보수","재시작"],"Troubleshooting & recovery":["troubleshooting","recovery","incident","문제해결","복구","장애"]},px=["low","medium","high","critical"];function TN(n){return n.reduce((a,r)=>{const l=_r[r].risk;return px.indexOf(l)>px.indexOf(a)?l:a},"low")}function EN(n){return Sn.filter(a=>n.every(r=>_r[r].supportedPlatforms.includes(a)))}function Ue(n,a,r,l,c,d,m={}){const p=m.description||l,g=c.flatMap(w=>w.split(".")),v=[...new Set([...MN[a],...d,...g])];return{id:n,category:a,title:r,prompt:l,description:p,requiredOperations:c,risk:m.risk||TN(c),targetSupport:m.targetSupport||"single-or-multiple",supportedPlatforms:m.supportedPlatforms||EN(c),keywords:v,recommended:m.recommended??!1,enabled:!0}}const nw=[Ue("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target workstations.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),Ue("recommended-attention","Recommended","Find targets needing attention","Identify current targets with high resource use, low disk space, or service warnings.",["system.health","disk.status","service.status"],["attention","warning","monitor"],{recommended:!0}),Ue("recommended-performance-compare","Recommended","Compare selected performance","Compare CPU, memory, disk, and GPU capacity across the current targets.",["system.health","disk.status","gpu.status"],["compare","benchmark"],{recommended:!0}),Ue("recommended-gpu-vram","Recommended","Review GPU and VRAM availability","Show GPU temperature, utilization, and VRAM availability for the current targets.",["gpu.status"],["graphics","temperature","utilization"],{recommended:!0}),Ue("recommended-low-disk","Recommended","Locate low disk capacity","Find current targets with low free disk capacity and report the affected volumes.",["disk.status"],["storage","free space","capacity"],{recommended:!0}),Ue("recommended-ai-workers","Recommended","Verify ComfyUI and Ollama workers","Check whether ComfyUI and Ollama workers and their services are available on the current targets.",["process.list","service.status"],["comfyui","ollama","worker"],{recommended:!0}),Ue("recommended-recover-ai","Recommended","Recover stopped AI workers","Find stopped AI workers and relaunch the registered worker application or service on the target workstation.",["process.list","application.launch","service.control"],["recover","start","ai worker"],{targetSupport:"single",recommended:!0}),Ue("recommended-incident-diagnostics","Recommended","Collect an incident diagnostic bundle","Collect health, service, network, and recent log diagnostics for the current targets.",["diagnostics.collect","logs.collect","system.health","network.status"],["incident","report","evidence"],{recommended:!0}),Ue("health-cpu-memory","Health & capacity","Check high CPU and memory use","Find current targets with unusually high CPU or memory usage.",["system.health"],["cpu","memory","load","높은 사용량"]),Ue("health-uptime","Health & capacity","Review workstation uptime","Show uptime, boot time, and current system health for the target workstations.",["system.health"],["uptime","boot","가동시간"]),Ue("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),Ue("health-vram-usage","Health & capacity","Check VRAM usage","Report GPU memory usage and remaining VRAM on the current targets.",["gpu.status"],["vram","gpu memory","video memory"]),Ue("health-low-disk","Health & capacity","Find low disk space","Find volumes below a safe free-space threshold on the current targets.",["disk.status"],["disk","storage","free space","디스크"]),Ue("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),Ue("health-system-warnings","Health & capacity","Collect system warnings","Review health, disk, and network status for warnings that need attention.",["system.health","disk.status","network.status"],["warnings","alerts","경고"]),Ue("health-capacity-report","Health & capacity","Build a capacity report","Create a concise capacity report covering CPU, memory, GPU, disk, and network status.",["system.health","gpu.status","disk.status","network.status"],["report","capacity","inventory"]),Ue("process-find-name","Processes & services","Find a running process by name","Find process named [process name] on the current targets.",["process.list"],["find","running","name","실행 중"]),Ue("process-resource-heavy","Processes & services","Find resource-heavy processes","List the processes using the most CPU or memory on the current targets.",["process.list","system.health"],["top","cpu","memory","resource"]),Ue("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target workstation after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),Ue("process-restart-named","Processes & services","Restart a named process","Check process named [process name] and restart it with its registered launch details when available.",["process.list","process.control"],["restart","relaunch","재시작"],{targetSupport:"single"}),Ue("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target workstation with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),Ue("process-close-app","Processes & services","Close an application","Close application [application] on the target workstation and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),Ue("service-status-name","Processes & services","Check a service status","Check service [service name] and report its state on the current targets.",["service.status"],["service","status","서비스 상태"]),Ue("service-restart-name","Processes & services","Restart a service safely","Check service [service name], stop it, wait for it to stop, then start it and verify the result.",["service.status","service.control"],["restart","start","stop","서비스 재시작"],{targetSupport:"single"}),Ue("ai-comfyui-status","AI workloads","Check ComfyUI availability","Check the ComfyUI process, service state, and GPU readiness on the current targets.",["process.list","service.status","gpu.status"],["comfyui","stable diffusion","image generation"]),Ue("ai-start-comfyui","AI workloads","Start ComfyUI","If ComfyUI is stopped, launch its registered application or service and verify it is running.",["process.list","application.launch","service.status"],["comfyui","start","launch"],{targetSupport:"single"}),Ue("ai-restart-ollama","AI workloads","Restart Ollama","Check Ollama, restart its registered application or service, and verify the worker is ready.",["process.list","application.close","application.launch","service.status"],["ollama","restart","llm"],{targetSupport:"single"}),Ue("ai-stable-diffusion","AI workloads","Check Stable Diffusion workers","Check Stable Diffusion or Automatic1111 processes and their GPU usage on the current targets.",["process.list","gpu.status"],["stable diffusion","automatic1111","sd"]),Ue("ai-gpu-readiness","AI workloads","Check GPU readiness for AI","Check GPU temperature, VRAM, utilization, and system health before an AI workload starts.",["gpu.status","system.health"],["readiness","inference","training"]),Ue("ai-worker-logs","AI workloads","Collect AI worker logs","Collect recent logs and relevant log files for the AI worker on the target workstation.",["logs.collect","file.list","file.read"],["logs","diagnostics","worker"],{targetSupport:"single"}),Ue("ai-llama-cpp","AI workloads","Check llama.cpp workers","Find llama.cpp or local model worker processes and inspect their recent logs.",["process.list","logs.collect"],["llama.cpp","local model","inference"]),Ue("ai-recover-orphan-python","AI workloads","Recover an orphaned Python worker","Find an orphaned Python AI worker, stop the stale process, then launch its registered worker again.",["process.list","process.control","application.launch"],["python","orphaned","recovery"],{targetSupport:"single"}),Ue("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target workstation.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),Ue("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target workstation.",["file.read"],["config","settings","read","구성"]),Ue("files-recent-logs","Files & configuration","Find recent log files","List recent log files under [path] and summarize the latest entries.",["file.list","file.read"],["logs","recent","tail"]),Ue("files-update-config","Files & configuration","Update a configuration value","Read configuration file [path], update [change], and report the exact change made.",["file.read","file.write"],["edit","update","설정 변경"],{targetSupport:"single"}),Ue("files-delete-temp","Files & configuration","Delete temporary files","Find temporary files under [path], delete only the requested matches, and report the freed space.",["file.list","file.delete","disk.status"],["cleanup","temp","delete","정리"],{targetSupport:"single"}),Ue("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target workstation and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),Ue("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target workstation and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),Ue("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target workstation.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),Ue("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target workstation, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),Ue("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target workstation, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),Ue("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target workstation, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),Ue("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target workstation and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),Ue("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target workstation and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),Ue("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target workstation and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),Ue("software-verify-install","Software & automation","Verify an installed tool","Check whether [application] is installed, running, and available on the PATH of the current targets.",["process.list","system.health"],["verify","installed","path"]),Ue("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target workstation.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),Ue("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),Ue("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),Ue("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),Ue("network-warnings","Network & connectivity","Review network warnings","Review network status and recent logs for connectivity warnings on the current targets.",["network.status","logs.collect"],["warning","latency","packet loss"]),Ue("network-diagnostics","Network & connectivity","Collect network diagnostics","Collect network status, system diagnostics, and relevant logs for the current targets.",["network.status","diagnostics.collect","logs.collect"],["diagnostics","incident","connectivity"]),Ue("network-service-failures","Network & connectivity","Find network service failures","Check network status and relevant service states on the current targets.",["network.status","service.status"],["service","failure","dns"]),Ue("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),Ue("network-intermittent","Network & connectivity","Investigate intermittent connectivity","Investigate intermittent connectivity using network status, service state, and diagnostics evidence.",["network.status","service.status","diagnostics.collect"],["intermittent","unstable","recovery"]),Ue("power-lock","Power & maintenance","Lock the workstation","Lock the target workstation and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),Ue("power-logoff","Power & maintenance","Log off the workstation","Log off the target workstation after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),Ue("power-sleep","Power & maintenance","Put the workstation to sleep","Put the target workstation to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),Ue("power-restart","Power & maintenance","Restart the workstation","Restart the target workstation after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),Ue("power-shutdown","Power & maintenance","Shut down the workstation","Shut down the target workstation after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),Ue("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target workstation, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),Ue("power-timezone","Power & maintenance","Set the workstation timezone","Set the target workstation timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),Ue("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target workstation and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),Ue("recovery-app-wont-start","Troubleshooting & recovery","Investigate an app that will not start","Inspect [application], review its logs, launch the registered application, and verify the process.",["process.list","application.launch","logs.collect"],["app failure","start","실행 오류"],{targetSupport:"single"}),Ue("recovery-failed-service","Troubleshooting & recovery","Recover a failed service","Inspect service [service name], collect logs, restart it safely, and verify its running state.",["service.status","logs.collect","service.control"],["service failure","recover","서비스 복구"],{targetSupport:"single"}),Ue("recovery-repeated-process","Troubleshooting & recovery","Investigate a repeatedly stopping process","Inspect process [process name], collect diagnostics, stop stale instances, and relaunch the registered process.",["process.list","diagnostics.collect","process.control","application.launch"],["crash loop","process","반복 종료"],{targetSupport:"single"}),Ue("recovery-low-disk","Troubleshooting & recovery","Recover from low disk space","Inspect disk capacity, find temporary files, remove only the requested files, and verify free space.",["disk.status","file.list","file.delete"],["disk full","cleanup","저장공간 부족"],{targetSupport:"single"}),Ue("recovery-gpu-overheating","Troubleshooting & recovery","Investigate GPU overheating","Inspect GPU temperature and processes, then close the specified workload if it is causing the thermal warning.",["gpu.status","process.list","application.close"],["overheating","thermal","GPU 발열"],{targetSupport:"single"}),Ue("recovery-high-vram","Troubleshooting & recovery","Recover high VRAM usage","Inspect VRAM usage and GPU processes, then stop the specified stale workload if necessary.",["gpu.status","process.list","process.control"],["vram","memory pressure","VRAM 부족"],{targetSupport:"single"}),Ue("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target workstation.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),Ue("recovery-incident-report","Troubleshooting & recovery","Create a full incident report","Create a full incident report from health, process, service, network, and log evidence for the current targets.",["system.health","process.list","service.status","network.status","logs.collect"],["incident","report","장애 보고서"])],lh={read:"allow",processControl:"allow",serviceControl:"allow",applicationControl:"ask",fileRead:"allow",fileWrite:"allow",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"allow",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function RN(n,a){return n==="safe-auto"?lh:n==="full-access"?{...lh,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:n==="custom"&&a?a:{...lh,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function DN(n,a,r){const l=RN(a,r),c=n.requiredOperations.map(d=>l[_r[d].permissionCategory]);if(c.includes("deny")){const d=n.requiredOperations.find(m=>l[_r[m].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${_r[d].label}, which is blocked by the current permission policy.`}}return c.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a workstation."}:n.requiredOperations.every(d=>_r[d].readOnly)?{state:"read-only",label:"Read only"}:a==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function LN(n){const a=String(n||"").trim().toLowerCase();return a==="windows"||a==="win32"||a==="win32nt"?"windows":a==="macos"||a==="macosx"||a==="darwin"||a==="osx"?"macos":a==="linux"?"linux":null}function _N(n,a,r){const l=new Set(r);return n.filter(c=>c.connected&&(a==="all"||a==="auto"||l.has(c.deviceId)))}function zN(n,a){const r=LN(n.platform);if(!r||!a.supportedPlatforms.includes(r))return!1;const l=n.capabilities?.agentTools;return!Array.isArray(l)||l.length===0?a.requiredOperations.every(c=>_r[c].readOnly):a.requiredOperations.every(c=>l.includes(c))}function aw(n,a,r,l,c,d){const m=DN(n,c,d),p=_N(a,r,l),g=p.map(C=>C.deviceId),v={...m,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:n.risk,supportedPlatforms:n.supportedPlatforms};if(p.length===0)return{...v,reason:"Select at least one connected workstation."};if(n.targetSupport==="single"&&p.length!==1)return{...v,reason:"This task supports one workstation at a time."};if(m.state==="blocked")return v;const w=p.filter(C=>zN(C,n)),x=w.map(C=>C.deviceId),b=g.filter(C=>!x.includes(C));return w.length===0?{...v,unsupportedDeviceIds:b,reason:"No current target supports the required platform and client capabilities."}:{...v,available:!0,availableDeviceIds:x,unsupportedDeviceIds:b}}function IN(n,a,r,l,c,d){return n.filter(m=>m.enabled&&aw(m,a,r,l,c,d).available).length}const oh="livedesk.agentPromptRecent",ch="livedesk.agentPromptFavorites",ON={Recommended:Es,"Health & capacity":pn,"Processes & services":i0,"AI workloads":Wx,"Files & configuration":s0,"Software & automation":Fd,"Network & connectivity":Qh,"Power & maintenance":Bt,"Troubleshooting & recovery":a0};function gx(n){if(typeof window>"u")return[];try{const a=JSON.parse(window.localStorage.getItem(n)||"[]");return Array.isArray(a)?a.filter(r=>typeof r=="string"):[]}catch{return[]}}function jd(n,a){try{window.localStorage.setItem(n,JSON.stringify(a))}catch{}}function uh(n){return n==="all"?"All tasks":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto allowed":n==="approval"?"Approval required":n==="full-access"?"Full Access":n==="available"?"Available":n==="unavailable"?"Unavailable":n}function HN(n){return n==="all"?"All":n==="recent"?"Recent":n==="favorites"?"Favorites":n==="read-only"?"Read only":n==="auto"?"Auto":n==="approval"?"Approval":n==="full-access"?"Full access":n==="available"?"Available":n==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","AI workloads":"AI","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[n]}function BN(n,a,r){if(!r.trim())return!0;const l=r.trim().toLowerCase();return[n.title,n.prompt,n.description,n.category,n.risk,a.label,...n.keywords,...n.requiredOperations,...n.supportedPlatforms].join(" ").toLowerCase().includes(l)}function FN(n){return`permission-${n}`}function PN(n){return n==="low"?"Low risk":n==="medium"?"Medium risk":n==="high"?"High risk":"Critical risk"}function $N(n){return n==="windows"?"Windows":n==="macos"?"macOS":"Linux"}function UN({devices:n,targetMode:a,selectedIds:r,permissionMode:l,customCategories:c,onSelectPrompt:d,onClose:m}){const[p,g]=u.useState(""),[v,w]=u.useState("all"),[x,b]=u.useState(()=>gx(oh)),[C,j]=u.useState(()=>gx(ch)),[A,N]=u.useState(0),[k,T]=u.useState(""),R=u.useRef(null),U=u.useRef(null),O=u.useMemo(()=>nw.filter(K=>K.enabled),[]),Y=u.useMemo(()=>new Map(O.map(K=>[K.id,aw(K,n,a,r,l,c)])),[c,n,l,r,a,O]),_=u.useMemo(()=>[...Y.values()].filter(K=>K.available).length,[Y]),D=u.useMemo(()=>n.filter(K=>K.connected&&(a==="all"||a==="auto"||r.includes(K.deviceId))).length,[n,r,a]),ne=u.useMemo(()=>{const K=O.filter(I=>BN(I,Y.get(I.id),p));return v==="recent"?x.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):v==="favorites"?C.map(I=>K.find(Q=>Q.id===I)).filter(I=>!!I):v==="all"?K:K.filter(I=>{const Q=Y.get(I.id);return v==="read-only"?Q.state==="read-only":v==="auto"?Q.state==="auto":v==="approval"?Q.state==="approval":v==="full-access"?Q.state==="full-access":v==="available"?Q.available:v==="unavailable"?!Q.available:I.category===v})},[Y,C,v,x,p,O]),G=u.useMemo(()=>v!=="all"?[{category:uh(v),templates:ne}]:hx.map(K=>({category:K,templates:ne.filter(I=>I.category===K)})).filter(K=>K.templates.length>0),[v,ne]);u.useEffect(()=>{N(K=>Math.min(K,Math.max(0,ne.length-1)))},[ne.length]),u.useEffect(()=>{jd(oh,x)},[x]),u.useEffect(()=>{jd(ch,C)},[C]),u.useEffect(()=>{U.current?.focus();const K=Q=>{Q.target instanceof Node&&!R.current?.contains(Q.target)&&m()},I=Q=>{Q.key==="Escape"&&(Q.preventDefault(),m())};return document.addEventListener("pointerdown",K),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",K),document.removeEventListener("keydown",I)}},[m]);const te=K=>{const I=Y.get(K.id);if(!I.available){T(I.reason||"This task is not available for the current targets and permission policy.");return}const Q=[K.id,...x.filter(q=>q!==K.id)].slice(0,10);b(Q),jd(oh,Q),d(K.prompt),m()},B=K=>{j(I=>{const Q=I.includes(K)?I.filter(q=>q!==K):[K,...I];return jd(ch,Q),Q})},xe=K=>{K.key==="ArrowDown"?(K.preventDefault(),N(I=>Math.min(I+1,Math.max(0,ne.length-1)))):K.key==="ArrowUp"?(K.preventDefault(),N(I=>Math.max(I-1,0))):K.key==="Enter"&&ne[A]&&(K.preventDefault(),te(ne[A]))};let se=-1;return s.jsxs("section",{className:"agents-suggested-tasks",ref:R,"aria-label":"Suggested tasks",children:[s.jsxs("header",{className:"agents-suggested-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"agents-suggested-title",children:[s.jsx(Es,{size:15})," Suggested tasks"]}),s.jsxs("small",{children:[_," available · ",O.length," total. Choose a task, edit it, then run it."]})]}),s.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:m,children:s.jsx(Ya,{size:16})})]}),s.jsxs("label",{className:"agents-suggested-search",children:[s.jsx(t0,{size:15,"aria-hidden":"true"}),s.jsx("input",{ref:U,value:p,onChange:K=>g(K.target.value),onKeyDown:xe,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),s.jsx("div",{className:"agents-suggested-filters","aria-label":"Task categories and availability filters",children:["all","recent","favorites","read-only","auto","approval","full-access","available","unavailable",...hx].map(K=>{const I=K==="recent"?Vx:K==="favorites"?Ch:K==="all"?Es:K==="available"?Fn:K==="unavailable"?n0:K==="read-only"||K==="auto"||K==="approval"||K==="full-access"?Bt:ON[K];return s.jsxs("button",{className:v===K?"active":"",type:"button",title:uh(K),"aria-label":uh(K),"aria-pressed":v===K,onClick:()=>{w(K),N(0),T("")},children:[s.jsx(I,{size:12})," ",HN(K)]},K)})}),k&&s.jsx("div",{className:"agents-suggested-notice",role:"status",children:k}),s.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[G.map(K=>s.jsxs("div",{className:"agents-suggested-group",children:[s.jsx("strong",{children:K.category}),K.templates.map(I=>{se+=1;const Q=se===A,q=C.includes(I.id),V=Y.get(I.id),ce=V.availableDeviceIds.length+V.unsupportedDeviceIds.length||D,be=V.available?`Available on ${V.availableDeviceIds.length} of ${ce} target${ce===1?"":"s"}`:`Unavailable: ${V.reason||"not supported by the current targets"}`;return s.jsxs("div",{className:`agents-suggested-item ${Q?"active":""} ${V.available?"":"unavailable"}`,children:[s.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":Q,"aria-disabled":!V.available,onClick:()=>te(I),children:[s.jsx("span",{children:I.title}),s.jsx("small",{className:"agents-suggested-description",children:I.description}),s.jsxs("span",{className:"agents-suggested-meta",children:[s.jsx("em",{children:I.category}),s.jsx("em",{className:FN(V.state),children:V.label}),s.jsx("em",{className:`risk-${I.risk}`,children:PN(I.risk)}),s.jsx("em",{children:I.supportedPlatforms.map($N).join(" · ")}),s.jsx("em",{className:V.available?"availability-ok":"availability-unavailable",children:be}),V.available&&V.unsupportedDeviceIds.length>0&&s.jsxs("em",{className:"availability-warning",children:["Unsupported on ",V.unsupportedDeviceIds.length]})]})]}),s.jsx("button",{className:`agents-suggested-favorite ${q?"favorite":""}`,type:"button","aria-label":q?`Remove ${I.title} from favorites`:`Add ${I.title} to favorites`,"aria-pressed":q,onClick:()=>B(I.id),children:s.jsx(Ch,{size:14,fill:q?"currentColor":"none"})})]},I.id)})]},K.category)),ne.length===0&&s.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function qN({devices:n,mode:a,selectedIds:r,onModeChange:l,onToggle:c,permissionMode:d,onPermissionModeChange:m}){const p=n.filter(Qd),g=r.filter(v=>p.some(w=>w.deviceId===v)).length;return s.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[s.jsxs("div",{className:"agents-target-toolbar",children:[s.jsx("span",{className:"agents-section-label",children:"Targets"}),s.jsxs("div",{className:"agents-target-modes",children:[s.jsxs("button",{className:a==="all"?"active":"",onClick:()=>l("all"),type:"button",children:[s.jsx($c,{size:14})," All connected ",s.jsx("small",{children:p.length})]}),s.jsxs("button",{className:a==="selected"?"active":"",onClick:()=>l("selected"),type:"button",children:[s.jsx(Ii,{size:14})," Selected ",g]}),s.jsxs("button",{className:a==="auto"?"active":"",onClick:()=>l("auto"),type:"button",children:[s.jsx(Es,{size:14})," Auto"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx($c,{size:14})," Group ",s.jsx("small",{children:"Soon"})]})]}),s.jsxs("label",{className:`agents-permission-picker permission-${d}`,children:[s.jsx(Jd,{size:14}),s.jsx("span",{children:"Permission"}),s.jsxs("select",{value:d,onChange:v=>m(v.target.value),"aria-label":"Agent permission mode",children:[s.jsx("option",{value:"ask",children:"Ask"}),s.jsx("option",{value:"safe-auto",children:"Safe Auto"}),s.jsx("option",{value:"full-access",children:"Full Access"}),s.jsx("option",{value:"custom",children:"Custom"})]}),s.jsx(Zx,{size:13,"aria-hidden":"true"})]})]}),s.jsx("div",{className:"agents-target-list",children:n.length===0?s.jsx("span",{className:"agents-target-empty",children:"No workstations discovered."}):n.map(v=>{const w=Qd(v),x=a==="all"||a==="auto"?w:r.includes(v.deviceId);return s.jsxs("label",{className:`agents-target-option ${x?"selected":""} ${w?"":"offline"}`,children:[s.jsx("input",{type:"checkbox",checked:x,disabled:!w||a!=="selected",onChange:()=>c(v.deviceId)}),s.jsx("span",{className:"agents-target-icon",children:s.jsx(an,{size:15})}),s.jsxs("span",{children:[s.jsx("strong",{children:Kd(v)}),s.jsx("small",{children:w?"Ready":v.connected?"Agent reconnecting":"Offline"})]}),x&&s.jsx(Ii,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},v.deviceId)})})]})}async function GN(n,a){return Ge("/api/settings/agent/plan",{method:"POST",body:JSON.stringify({instruction:a})},n)}async function VN(n,a){return Ge("/api/settings/agent/run",{method:"POST",body:JSON.stringify(a)},n)}async function WN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}`,void 0,n)}async function YN(n,a){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function KN(n){return Ge("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},n)}async function QN(n,a,r,l){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:l})},n)}async function XN(n,a,r,l="User rejected this action."){return Ge(`/api/settings/agent/runs/${encodeURIComponent(a)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:l})},n)}async function ZN(n,a,r){return Ge(`/api/settings/agent/policies/${encodeURIComponent(a)}`,{method:"PUT",body:JSON.stringify({categories:r})},n)}async function JN(n,a){return Ge("/api/settings/agent/summary",{method:"POST",body:JSON.stringify(a)},n)}async function eM(n,a){return Ge("/api/remote/tasks",{method:"POST",body:JSON.stringify({instruction:a.instruction,deviceIds:a.deviceIds,operation:a.operation,targetQuery:a.targetQuery,approvalLevel:"read-only"})},n)}async function tM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}`,void 0,n)}async function nM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/cancel`,{method:"POST",body:JSON.stringify({})},n)}async function aM(n,a){return Ge(`/api/remote/tasks/${encodeURIComponent(a)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},n)}function Sl(n){return`${n}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function kd(n,a){const r=new Map(a.map(l=>[l.deviceId,Kd(l)]));return n.results.map(l=>({deviceId:l.deviceId,deviceName:l.deviceName||r.get(l.deviceId)||l.deviceId,status:vN(l.status),stage:l.stage||(l.status==="running"?"Checking processes":void 0),result:l.result,data:l.data,error:l.error,sequence:Number.isSafeInteger(l.sequence)?l.sequence:0}))}function sM(n,a){const r=new Map(a.map(l=>[l.deviceId,l]));return n.map(l=>{const c=r.get(l.deviceId);return!c||c.sequence<=l.sequence?l:c})}function iM(n,a){const r=a.filter(d=>d.status==="completed"),l=a.filter(d=>d.status==="failed");if(n.operation==="process.list"){const m=`${r.filter(p=>{const g=p.result||"";return!/not running|no process/i.test(g)&&/running|online|found/i.test(g)}).length}대에서 요청한 프로세스가 실행 중입니다.`;return l.length>0?`${m}
|
|
15
15
|
${l.map(p=>`${p.deviceName}는 ${p.error||"응답하지 않았습니다."}`).join(`
|
|
16
16
|
`)}`:m}return l.length>0?`${r.length}대 완료, ${l.length}대 실패했습니다.`:`${r.length}대 작업이 완료되었습니다.`}const rM={read:"allow",processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileRead:"ask",fileWrite:"ask",fileDelete:"ask",shell:"ask",script:"ask",softwareInstall:"ask",network:"ask",systemPower:"ask",systemConfiguration:"ask",userAccount:"deny"};function lM(n){return n==="safe-auto"?"Safe Auto":n==="full-access"?"Full Access":n==="custom"?"Custom":"Ask"}function oM(n){return n.replace(/([A-Z])/g," $1").replace(/^./,a=>a.toUpperCase())}function cM(n){const a=n instanceof Error?n.message:String(n);return/agent-ai-disabled/i.test(a)?"Enable AI Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(a)?"The selected workstation is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(a)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":a}function vx({hubUrl:n,devices:a,launchRequest:r,variant:l="page",selectedDeviceIds:c=[]}){const d=l==="dock",[m,p]=u.useState(d?c.length>0?"selected":"auto":"all"),[g,v]=u.useState(c),[w,x]=u.useState("auto"),[b,C]=u.useState(""),[j,A]=u.useState([]),[N,k]=u.useState(""),[T,R]=u.useState(""),[U,O]=u.useState(""),[Y,_]=u.useState("safe-auto"),[D]=u.useState("custom-default"),[ne,G]=u.useState(rM),[te,B]=u.useState([]),[xe,se]=u.useState(""),[K,I]=u.useState(!1),[Q,q]=u.useState(null),[V,ce]=u.useState(!1),[be,X]=u.useState(""),[$,ue]=u.useState(!1),[he,ve]=u.useState(null),Se=u.useRef(null),_e=u.useRef(new Set),re=u.useRef(new Set),Z=u.useRef(new Set),ze=u.useMemo(()=>a.filter(Qd).map(ge=>ge.deviceId),[a]),Le=u.useMemo(()=>IN(nw,a,m,g,Y,ne),[ne,a,Y,g,m]);u.useEffect(()=>{d&&v(c)},[d,c]),u.useEffect(()=>{r?.deviceId&&(p("selected"),v([r.deviceId]),C(r.instruction),ue(!1),window.requestAnimationFrame(()=>{Se.current?.focus(),Se.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const ae=u.useCallback(ge=>{const Oe=kd(ge,a);if(A(Fe=>Fe.map(ke=>ke.type==="task"&&ke.batchId===ge.batchId?{...ke,states:sM(ke.states,Oe),status:ge.status}:ke)),!["running","queued"].includes(ge.status)&&!_e.current.has(ge.batchId)){_e.current.add(ge.batchId);const Fe=Sl("agent-summary");A(ke=>[...ke,{type:"agent",id:Fe,text:iM(ge,Oe)}]),ge.operation&&JN(n,{instruction:ge.instructionPreview,operation:ge.operation,total:Oe.length,completed:Oe.filter(ke=>ke.status==="completed").length,failed:Oe.filter(ke=>ke.status==="failed").length,results:Oe.map(ke=>({deviceName:ke.deviceName,status:ke.status,result:ke.result,error:ke.error}))}).then(ke=>{!ke.ok||!ke.summary||A(st=>st.map(gt=>gt.type==="agent"&>.id===Fe?{...gt,text:ke.summary}:gt))}).catch(()=>{}),k(ke=>ke===ge.batchId?"":ke)}},[a,n]),fe=u.useCallback(async ge=>{const Oe=await tM(n,ge);return ae(Oe),Oe},[n,ae]),Ae=u.useCallback((ge,Oe)=>{Z.current.has(ge.batchId)||(Z.current.add(ge.batchId),A(Fe=>[...Fe,{type:"task",id:Sl("task"),batchId:ge.batchId,agentRunId:Oe,operation:ge.operation||"diagnostics.collect",instruction:ge.instructionPreview,states:kd(ge,a),status:ge.status}])),ae(ge)},[a,ae]),Te=u.useCallback(async ge=>{const Oe=await WN(n,ge);for(const ke of Oe.taskBatches||[])Ae(ke,ge);B(Oe.approvals||[]);const Fe=["running","queued","waiting-approval"].includes(Oe.status);if(ve(Fe?{runId:ge,stage:Oe.stage||Oe.status,message:Oe.progressMessage||(Oe.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:ke=>ke?.runId===ge?null:ke),!Fe&&!re.current.has(ge)){re.current.add(ge);const ke=[Oe.error,Oe.errorMessage].filter(Boolean).join(" — "),st=Oe.finalResponse?.trim()||(Oe.status==="cancelled"?"Codex 작업을 취소했습니다.":ke?`Codex 작업이 완료되지 않았습니다: ${ke}`:"Codex 작업이 완료되었습니다.");A(gt=>[...gt,{type:Oe.status==="failed"?"error":"agent",id:Sl("agent-run-result"),text:st}])}return Oe},[Ae,n]);u.useEffect(()=>{if(!N)return;let ge=!0;const Oe=async()=>{try{const ke=await fe(N);ge&&!["running","queued"].includes(ke.status)&&k("")}catch(ke){ge&&X(ke instanceof Error?ke.message:String(ke))}};Oe();const Fe=window.setInterval(()=>{Oe()},800);return()=>{ge=!1,window.clearInterval(Fe)}},[N,fe]),u.useEffect(()=>{if(!T)return;let ge=!0;const Oe=async()=>{try{const ke=await Te(T);ge&&!["running","queued","waiting-approval"].includes(ke.status)&&(R(""),ce(!1))}catch(ke){ge&&X(ke instanceof Error?ke.message:String(ke))}};Oe();const Fe=window.setInterval(()=>{Oe()},800);return()=>{ge=!1,window.clearInterval(Fe)}},[T,Te]);const Be=async(ge="",Oe,Fe=!1)=>{const ke=(ge||b).trim();if(!ke||N||T)return;let st=null;const gt=Oe||(m==="all"||m==="auto"?ze:g.filter(nt=>ze.includes(nt)));if(gt.length===0){X("Select at least one connected workstation.");return}if(Y==="full-access"&&!V&&!Fe){q({instruction:ke,targetIds:gt});return}if(A(nt=>[...nt,{type:"user",id:Sl("user"),text:ke}]),C(""),ue(!1),X(""),gt.length===0){A(nt=>[...nt,{type:"error",id:Sl("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const jn=w==="ask"?`Read-only request. Inspect and answer without changing workstation state.
|
|
17
17
|
|
|
@@ -21,5 +21,5 @@ ${ke}`:w==="execute"?`Execute this request within the configured LiveDesk approv
|
|
|
21
21
|
|
|
22
22
|
${ke}`:ke,Ls=m==="auto"?`Auto target selection is enabled. Inspect the allowed workstations and use only the most suitable target or targets for this request.
|
|
23
23
|
|
|
24
|
-
${jn}`:jn;if(!st){try{if(Y==="custom"){const zt=await ZN(n,D,ne);if(!zt.ok)throw new Error(zt.error||"Custom Agent policy could not be saved.")}const nt=await VN(n,{instruction:Ls,deviceIds:gt,permissionMode:Y,customPolicyId:D});if(!nt.ok||!nt.runId)throw new Error(nt.error||"Codex Agent run could not be started.");B(nt.approvals||[]),ve({runId:nt.runId,stage:nt.stage||nt.status||"queued",message:nt.progressMessage||"Codex request queued on the Hub."}),R(nt.runId);return}catch(nt){try{const zt=await GN(n,Ls);zt.ok&&zt.plan&&(st={operation:zt.plan.operation,query:zt.plan.targetQuery})}catch{A(zt=>[...zt,{type:"error",id:Sl("unsupported"),text:cM(nt)}])}}if(!st)return}try{const nt=await eM(n,{instruction:Ls,deviceIds:gt,operation:st.operation,targetQuery:st.query});if(!nt.ok||!nt.batch||!nt.batchId)throw new Error(nt.error||"작업을 만들지 못했습니다.");const zt={type:"task",id:Sl("task"),batchId:nt.batchId,operation:st.operation,instruction:ke,states:kd(nt.batch,a),status:nt.batch.status};Z.current.add(nt.batchId),A(zn=>[...zn,zt]),k(nt.batchId)}catch(nt){X(nt instanceof Error?nt.message:String(nt))}},Ve=async(ge,Oe)=>{se(ge.approvalId);try{const Fe=await QN(n,ge.runId,ge.approvalId,Oe);if(!Fe.ok)throw new Error(Fe.error||"Agent approval could not be applied.");await Te(ge.runId)}catch(Fe){X(Fe instanceof Error?Fe.message:String(Fe))}finally{se("")}},Je=async ge=>{se(ge.approvalId);try{const Oe=await XN(n,ge.runId,ge.approvalId);if(!Oe.ok)throw new Error(Oe.error||"Agent approval could not be rejected.");await Te(ge.runId)}catch(Oe){X(Oe instanceof Error?Oe.message:String(Oe))}finally{se("")}},Et=async(ge,Oe)=>{O(ge);try{if(Oe){const ke=await YN(n,Oe);for(const st of ke.taskBatches||[])ae(st);R(st=>st===Oe?"":st),ve(st=>st?.runId===Oe?null:st);return}const Fe=await nM(n,ge);ae(Fe),k(ke=>ke===ge?"":ke)}catch(Fe){X(Fe instanceof Error?Fe.message:String(Fe))}finally{O("")}},je=async()=>{if(!(K||!N&&!T)){I(!0);try{const ge=await KN(n);if(!ge.ok)throw new Error(ge.error||"모든 Agent 작업을 취소하지 못했습니다.");k(""),R(""),ve(null),B([]),A(Oe=>Oe.map(Fe=>Fe.type==="task"&&["queued","running"].includes(Fe.status)?{...Fe,status:"cancelled",states:Fe.states.map(ke=>["queued","running"].includes(ke.status)?{...ke,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:ke)}:Fe))}catch(ge){X(ge instanceof Error?ge.message:String(ge))}finally{I(!1)}}},We=async ge=>{O(ge);try{const Oe=await aM(n,ge);if(!Oe.ok||!Oe.batch||!Oe.batchId)throw new Error(Oe.error||"재시도하지 못했습니다.");_e.current.delete(Oe.batchId),A(Fe=>Fe.map(ke=>ke.type==="task"&&ke.batchId===ge?{...ke,batchId:Oe.batchId,states:kd(Oe.batch,a),status:Oe.batch.status}:ke)),k(Oe.batchId)}catch(Oe){X(Oe instanceof Error?Oe.message:String(Oe))}finally{O("")}},it=ge=>{C(ge),ue(!1),window.requestAnimationFrame(()=>Se.current?.focus())},ot=u.useMemo(()=>a.filter(Qd),[a]),gn=u.useMemo(()=>ot.filter(ge=>g.includes(ge.deviceId)),[ot,g]),Kt=m==="auto"?`Auto · ${ot.length} available`:m==="all"?`All ${ot.length} computers`:gn.length===1?Kd(gn[0]):`${gn.length} selected`,Ie=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":gn.length>0?gn.map(Kd).join(" · "):"Select one or more computers on the Wall.",ct=m==="selected"&&gn.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],_t=m==="selected"?gn.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Ft=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return s.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&s.jsxs("header",{className:"agent-console-header",children:[s.jsxs("div",{className:"agent-console-title",children:[s.jsx("span",{className:"agent-console-mark",children:s.jsx(Es,{size:16})}),s.jsxs("div",{children:[s.jsx("small",{children:"Live agent"}),s.jsx("strong",{children:"Agent Console"})]}),s.jsx("i",{children:"Ready"})]}),s.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:Kt}),s.jsx("small",{children:Ie})]}),s.jsxs("div",{className:"agent-console-target-modes",children:[s.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[s.jsx(Ii,{size:12})," Selected"]}),s.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[s.jsx($c,{size:12})," All"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx($c,{size:12})," Group"]}),s.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[s.jsx(Es,{size:12})," Auto"]})]})]}),s.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(ge=>s.jsxs("button",{className:w===ge?"active":"",onClick:()=>x(ge),type:"button",children:[ge==="auto"?s.jsx(Es,{size:12}):ge==="execute"?s.jsx(an,{size:12}):null,ge[0].toUpperCase()+ge.slice(1)]},ge))})]}),s.jsxs("div",{className:"agents-workspace",children:[(N||T)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[ze.length," workstations · ",lM(Y)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{je()},disabled:K,children:K?"Stopping…":"Stop all"})]}),Q&&s.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:s.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[s.jsx("span",{className:"agents-permission-modal-icon",children:s.jsx(Jd,{size:20})}),s.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),s.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected workstations. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),s.jsxs("div",{className:"agents-permission-modal-actions",children:[s.jsx("button",{type:"button",onClick:()=>q(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const ge=Q;q(null),ce(!0),Be(ge.instruction,ge.targetIds,!0)},children:"Run with Full Access"})]})]})}),be&&s.jsx("div",{className:"agents-error",role:"alert",children:be}),s.jsx(NN,{items:j,onCancel:Et,onRetry:We,busyBatchId:U,approvals:te,onApprove:Ve,onReject:Je,busyApprovalId:xe,progress:he,emptyTitle:d?_t:void 0,emptyBody:d?Ft:void 0}),d&&j.length===0&&!he&&s.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ct.map(ge=>s.jsx("button",{type:"button",onClick:()=>it(ge),children:ge},ge))}),s.jsxs("div",{className:"agents-composer-shell",children:[$&&s.jsx(UN,{devices:a,targetMode:m,selectedIds:g,permissionMode:Y,customCategories:ne,onSelectPrompt:it,onClose:()=>ue(!1)}),s.jsx(pN,{ref:Se,value:b,onChange:C,onSubmit:()=>{Be()},onOpenSuggestedTasks:()=>ue(ge=>!ge),suggestedOpen:$,suggestedTaskCount:Le,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0})]})]}),!d&&s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(qN,{devices:a,mode:m,selectedIds:g,onModeChange:p,onToggle:ge=>v(Oe=>Oe.includes(ge)?Oe.filter(Fe=>Fe!==ge):[...Oe,ge]),permissionMode:Y,onPermissionModeChange:ge=>{_(ge),ge!=="full-access"&&ce(!1)}}),Y==="custom"&&s.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[s.jsxs("div",{className:"agents-custom-policy-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"agents-section-label",children:"Custom policy"}),s.jsx("strong",{children:"Choose what Codex may do automatically."})]}),s.jsx("span",{children:"Denied actions never reach a device."})]}),s.jsx("div",{className:"agents-custom-policy-grid",children:gN.map(ge=>s.jsxs("label",{children:[s.jsx("span",{children:oM(ge)}),s.jsxs("select",{value:ne[ge],onChange:Oe=>G(Fe=>({...Fe,[ge]:Oe.target.value})),children:[s.jsx("option",{value:"allow",children:"Allow automatically"}),s.jsx("option",{value:"ask",children:"Ask every time"}),s.jsx("option",{value:"deny",children:"Deny"})]})]},ge))})]})]})]})}function sw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function iw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function rw(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:sw(a.target)})),c=await fetch(`${Hr(r)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":n.type||"application/octet-stream"},body:n,cache:"no-store"});if(!c.ok)throw new Error(await iw(c));return await c.json()}async function uM(n,a){return await Ge("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:sw(n.target)})},a)}async function dM(n,a,r,l){const c=await fetch(`${Hr(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await iw(c));return await c.json()}async function fM(n,a,r){return await Ge(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function yx(n,a){await Ge(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function mM(n){return await Ge("/api/captures",void 0,n)}function xx(n,a){return`${Hr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function hM(n,a){return await Ge(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function pM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await mM(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async g=>{const v=xx(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:v});return}catch{}window.open(v,"_blank","noopener,noreferrer")};return s.jsxs("section",{className:"capture-gallery",children:[s.jsxs("header",{children:[s.jsxs("div",{children:[s.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),s.jsx("h2",{children:"Saved captures"})]}),s.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[s.jsx(Do,{size:15})," Refresh"]})]}),c?s.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?s.jsx("p",{className:"settings-help",children:"No captures saved yet."}):s.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const v=xx(g.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?s.jsx("img",{src:v,alt:g.target.label}):s.jsx("video",{src:v,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:g.fileName}),s.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(v,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(r0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${v}?download=1`,download:g.fileName,children:s.jsx(Wh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(g)},type:"button",children:s.jsx(l0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&hM(g.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(Yh,{size:15})})]})]})]},g.id)})})]})}function Ad(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),r=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return r>0?`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function bx({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async x=>{try{await x()}catch(b){l?.(b instanceof Error?b.message:String(b))}},g=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
24
|
+
${jn}`:jn;if(!st){try{if(Y==="custom"){const zt=await ZN(n,D,ne);if(!zt.ok)throw new Error(zt.error||"Custom Agent policy could not be saved.")}const nt=await VN(n,{instruction:Ls,deviceIds:gt,permissionMode:Y,customPolicyId:D});if(!nt.ok||!nt.runId)throw new Error(nt.error||"Codex Agent run could not be started.");B(nt.approvals||[]),ve({runId:nt.runId,stage:nt.stage||nt.status||"queued",message:nt.progressMessage||"Codex request queued on the Hub."}),R(nt.runId);return}catch(nt){try{const zt=await GN(n,Ls);zt.ok&&zt.plan&&(st={operation:zt.plan.operation,query:zt.plan.targetQuery})}catch{A(zt=>[...zt,{type:"error",id:Sl("unsupported"),text:cM(nt)}])}}if(!st)return}try{const nt=await eM(n,{instruction:Ls,deviceIds:gt,operation:st.operation,targetQuery:st.query});if(!nt.ok||!nt.batch||!nt.batchId)throw new Error(nt.error||"작업을 만들지 못했습니다.");const zt={type:"task",id:Sl("task"),batchId:nt.batchId,operation:st.operation,instruction:ke,states:kd(nt.batch,a),status:nt.batch.status};Z.current.add(nt.batchId),A(zn=>[...zn,zt]),k(nt.batchId)}catch(nt){X(nt instanceof Error?nt.message:String(nt))}},Ve=async(ge,Oe)=>{se(ge.approvalId);try{const Fe=await QN(n,ge.runId,ge.approvalId,Oe);if(!Fe.ok)throw new Error(Fe.error||"Agent approval could not be applied.");await Te(ge.runId)}catch(Fe){X(Fe instanceof Error?Fe.message:String(Fe))}finally{se("")}},Je=async ge=>{se(ge.approvalId);try{const Oe=await XN(n,ge.runId,ge.approvalId);if(!Oe.ok)throw new Error(Oe.error||"Agent approval could not be rejected.");await Te(ge.runId)}catch(Oe){X(Oe instanceof Error?Oe.message:String(Oe))}finally{se("")}},Et=async(ge,Oe)=>{O(ge);try{if(Oe){const ke=await YN(n,Oe);for(const st of ke.taskBatches||[])ae(st);R(st=>st===Oe?"":st),ve(st=>st?.runId===Oe?null:st);return}const Fe=await nM(n,ge);ae(Fe),k(ke=>ke===ge?"":ke)}catch(Fe){X(Fe instanceof Error?Fe.message:String(Fe))}finally{O("")}},je=async()=>{if(!(K||!N&&!T)){I(!0);try{const ge=await KN(n);if(!ge.ok)throw new Error(ge.error||"모든 Agent 작업을 취소하지 못했습니다.");k(""),R(""),ve(null),B([]),A(Oe=>Oe.map(Fe=>Fe.type==="task"&&["queued","running"].includes(Fe.status)?{...Fe,status:"cancelled",states:Fe.states.map(ke=>["queued","running"].includes(ke.status)?{...ke,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:ke)}:Fe))}catch(ge){X(ge instanceof Error?ge.message:String(ge))}finally{I(!1)}}},We=async ge=>{O(ge);try{const Oe=await aM(n,ge);if(!Oe.ok||!Oe.batch||!Oe.batchId)throw new Error(Oe.error||"재시도하지 못했습니다.");_e.current.delete(Oe.batchId),A(Fe=>Fe.map(ke=>ke.type==="task"&&ke.batchId===ge?{...ke,batchId:Oe.batchId,states:kd(Oe.batch,a),status:Oe.batch.status}:ke)),k(Oe.batchId)}catch(Oe){X(Oe instanceof Error?Oe.message:String(Oe))}finally{O("")}},it=ge=>{C(ge),ue(!1),window.requestAnimationFrame(()=>Se.current?.focus())},ot=u.useMemo(()=>a.filter(Qd),[a]),gn=u.useMemo(()=>ot.filter(ge=>g.includes(ge.deviceId)),[ot,g]),Kt=m==="auto"?`Auto · ${ot.length} available`:m==="all"?`All ${ot.length} computers`:gn.length===1?Kd(gn[0]):`${gn.length} selected`,Ie=m==="auto"?"LiveDesk chooses the best computer for each task.":m==="all"?"The Agent may coordinate every connected computer.":gn.length>0?gn.map(Kd).join(" · "):"Select one or more computers on the Wall.",ct=m==="selected"&&gn.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:m==="all"?["Compare all computer health","Find the busiest computer","Check disk capacity everywhere","Divide a task across computers"]:["Use the fastest computer","Find an idle computer","Choose the best GPU","Check all computer health"],_t=m==="selected"?gn.length>0?"What should this computer do?":"Choose a computer or use Auto.":m==="all"?"Use all your computers together.":"What should LiveDesk handle?",Ft=m==="auto"?"LiveDesk can inspect the available computers and choose the best target.":"Describe the outcome. LiveDesk will plan, request approval when needed, and show progress per computer.";return s.jsxs("section",{className:`agents-page ${d?"agents-dock-console":""}`,children:[d&&s.jsxs("header",{className:"agent-console-header",children:[s.jsxs("div",{className:"agent-console-title",children:[s.jsx("span",{className:"agent-console-mark",children:s.jsx(Es,{size:16})}),s.jsxs("div",{children:[s.jsx("small",{children:"Live agent"}),s.jsx("strong",{children:"Agent Console"})]}),s.jsx("i",{children:"Ready"})]}),s.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Target"}),s.jsx("strong",{children:Kt}),s.jsx("small",{children:Ie})]}),s.jsxs("div",{className:"agent-console-target-modes",children:[s.jsxs("button",{className:m==="selected"?"active":"",onClick:()=>p("selected"),type:"button",children:[s.jsx(Ii,{size:12})," Selected"]}),s.jsxs("button",{className:m==="all"?"active":"",onClick:()=>p("all"),type:"button",children:[s.jsx($c,{size:12})," All"]}),s.jsxs("button",{type:"button",disabled:!0,title:"Saved workstation groups are coming next.",children:[s.jsx($c,{size:12})," Group"]}),s.jsxs("button",{className:m==="auto"?"active":"",onClick:()=>p("auto"),type:"button",children:[s.jsx(Es,{size:12})," Auto"]})]})]}),s.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(ge=>s.jsxs("button",{className:w===ge?"active":"",onClick:()=>x(ge),type:"button",children:[ge==="auto"?s.jsx(Es,{size:12}):ge==="execute"?s.jsx(an,{size:12}):null,ge[0].toUpperCase()+ge.slice(1)]},ge))})]}),s.jsxs("div",{className:"agents-workspace",children:[(N||T)&&s.jsxs("div",{className:"agents-page-status",children:[s.jsxs("span",{children:[ze.length," workstations · ",lM(Y)]}),s.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{je()},disabled:K,children:K?"Stopping…":"Stop all"})]}),Q&&s.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:s.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[s.jsx("span",{className:"agents-permission-modal-icon",children:s.jsx(Jd,{size:20})}),s.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),s.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected workstations. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),s.jsxs("div",{className:"agents-permission-modal-actions",children:[s.jsx("button",{type:"button",onClick:()=>q(null),children:"Cancel"}),s.jsx("button",{type:"button",className:"danger",onClick:()=>{const ge=Q;q(null),ce(!0),Be(ge.instruction,ge.targetIds,!0)},children:"Run with Full Access"})]})]})}),be&&s.jsx("div",{className:"agents-error",role:"alert",children:be}),s.jsx(NN,{items:j,onCancel:Et,onRetry:We,busyBatchId:U,approvals:te,onApprove:Ve,onReject:Je,busyApprovalId:xe,progress:he,emptyTitle:d?_t:void 0,emptyBody:d?Ft:void 0}),d&&j.length===0&&!he&&s.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:ct.map(ge=>s.jsx("button",{type:"button",onClick:()=>it(ge),children:ge},ge))}),s.jsxs("div",{className:"agents-composer-shell",children:[$&&s.jsx(UN,{devices:a,targetMode:m,selectedIds:g,permissionMode:Y,customCategories:ne,onSelectPrompt:it,onClose:()=>ue(!1)}),s.jsx(pN,{ref:Se,value:b,onChange:C,onSubmit:()=>{Be()},onOpenSuggestedTasks:()=>ue(ge=>!ge),suggestedOpen:$,suggestedTaskCount:Le,disabled:!!N||!!T,placeholder:d?"Tell LiveDesk what outcome you want...":void 0,compact:d})]})]}),!d&&s.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[s.jsx(qN,{devices:a,mode:m,selectedIds:g,onModeChange:p,onToggle:ge=>v(Oe=>Oe.includes(ge)?Oe.filter(Fe=>Fe!==ge):[...Oe,ge]),permissionMode:Y,onPermissionModeChange:ge=>{_(ge),ge!=="full-access"&&ce(!1)}}),Y==="custom"&&s.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[s.jsxs("div",{className:"agents-custom-policy-head",children:[s.jsxs("div",{children:[s.jsx("span",{className:"agents-section-label",children:"Custom policy"}),s.jsx("strong",{children:"Choose what Codex may do automatically."})]}),s.jsx("span",{children:"Denied actions never reach a device."})]}),s.jsx("div",{className:"agents-custom-policy-grid",children:gN.map(ge=>s.jsxs("label",{children:[s.jsx("span",{children:oM(ge)}),s.jsxs("select",{value:ne[ge],onChange:Oe=>G(Fe=>({...Fe,[ge]:Oe.target.value})),children:[s.jsx("option",{value:"allow",children:"Allow automatically"}),s.jsx("option",{value:"ask",children:"Ask every time"}),s.jsx("option",{value:"deny",children:"Deny"})]})]},ge))})]})]})]})}function sw(n){return{type:n.type,deviceIds:n.deviceIds,monitorIndex:n.monitorIndex,label:n.label}}async function iw(n){try{return(await n.json()).error||`${n.status} ${n.statusText}`}catch{return`${n.status} ${n.statusText}`}}async function rw(n,a,r){const l=encodeURIComponent(JSON.stringify({kind:a.kind,fileName:a.fileName,mimeType:n.type||"application/octet-stream",durationMs:a.durationMs,target:sw(a.target)})),c=await fetch(`${Hr(r)}/api/captures?metadata=${l}`,{method:"POST",headers:{"Content-Type":n.type||"application/octet-stream"},body:n,cache:"no-store"});if(!c.ok)throw new Error(await iw(c));return await c.json()}async function uM(n,a){return await Ge("/api/capture-sessions",{method:"POST",body:JSON.stringify({...n,target:sw(n.target)})},a)}async function dM(n,a,r,l){const c=await fetch(`${Hr(l)}/api/capture-sessions/${encodeURIComponent(n)}/chunks/${a}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r,cache:"no-store"});if(!c.ok)throw new Error(await iw(c));return await c.json()}async function fM(n,a,r){return await Ge(`/api/capture-sessions/${encodeURIComponent(n)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:a})},r)}async function yx(n,a){await Ge(`/api/capture-sessions/${encodeURIComponent(n)}`,{method:"DELETE"},a)}async function mM(n){return await Ge("/api/captures",void 0,n)}function xx(n,a){return`${Hr(a)}/api/captures/${encodeURIComponent(n)}/content`}async function hM(n,a){return await Ge(`/api/captures/${encodeURIComponent(n)}`,{method:"DELETE"},a)}function pM({hubUrl:n,onToast:a}){const[r,l]=u.useState([]),[c,d]=u.useState(!0),m=u.useCallback(async()=>{d(!0);try{l((await mM(n)).captures||[])}catch(g){a(g instanceof Error?g.message:String(g))}finally{d(!1)}},[n,a]);u.useEffect(()=>{m()},[m]);const p=async g=>{const v=xx(g.id,n);if(navigator.share)try{await navigator.share({title:g.fileName,url:v});return}catch{}window.open(v,"_blank","noopener,noreferrer")};return s.jsxs("section",{className:"capture-gallery",children:[s.jsxs("header",{children:[s.jsxs("div",{children:[s.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),s.jsx("h2",{children:"Saved captures"})]}),s.jsxs("button",{className:"text-button",onClick:()=>{m()},type:"button",children:[s.jsx(Do,{size:15})," Refresh"]})]}),c?s.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?s.jsx("p",{className:"settings-help",children:"No captures saved yet."}):s.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const v=xx(g.id,n);return s.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?s.jsx("img",{src:v,alt:g.target.label}):s.jsx("video",{src:v,controls:!0,preload:"metadata"}),s.jsxs("div",{className:"capture-gallery-card-body",children:[s.jsx("strong",{children:g.fileName}),s.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),s.jsxs("div",{children:[s.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(v,"_blank","noopener,noreferrer"),type:"button",children:s.jsx(r0,{size:15})}),s.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${v}?download=1`,download:g.fileName,children:s.jsx(Wh,{size:15})}),s.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{p(g)},type:"button",children:s.jsx(l0,{size:15})}),s.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&hM(g.id,n).then(()=>m()).catch(w=>a(w instanceof Error?w.message:String(w)))},type:"button",children:s.jsx(Yh,{size:15})})]})]})]},g.id)})})]})}function Ad(n){if(!n)return"";const a=Math.max(0,Math.floor((Date.now()-n)/1e3)),r=Math.floor(a/3600),l=Math.floor(a%3600/60),c=a%60;return r>0?`${String(r).padStart(2,"0")}:${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`:`${String(l).padStart(2,"0")}:${String(c).padStart(2,"0")}`}function bx({controller:n,compact:a=!1,onFirstRollingUse:r,onError:l}){const{state:c,settings:d,videoSupported:m}=n,p=async x=>{try{await x()}catch(b){l?.(b instanceof Error?b.message:String(b))}},g=async()=>{if(d.rollingEnabled){n.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
25
25
|
Nothing is saved until you press Save Last 30s.`))&&n.setRollingEnabled(!0)},v=c.recording?`Stop recording · ${Ad(c.recordingStartedAt)}`:`Start recording · ${c.targetLabel}`,w=c.timelapse?`Stop timelapse · ${Ad(c.timelapseStartedAt)}`:`Start timelapse · ${d.timelapseIntervalSeconds}s interval`;return s.jsxs("div",{className:`capture-toolbar ${a?"compact":""} ${c.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[s.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${c.targetLabel}`,title:`Take screenshot · ${c.targetLabel}`,disabled:c.busy,onClick:()=>{p(n.takeScreenshot)},type:"button",children:s.jsx(o0,{size:17})}),s.jsx("button",{className:`capture-action ${c.recording?"active":""}`,"aria-label":v,title:v,disabled:!m||c.busy||c.timelapse,onClick:()=>{p(c.recording?n.stopRecording:n.startRecording)},type:"button",children:c.recording?s.jsxs(s.Fragment,{children:[s.jsx(iy,{size:14,fill:"currentColor"}),s.jsx("span",{children:Ad(c.recordingStartedAt)})]}):s.jsx(Xx,{size:18})}),s.jsxs("button",{className:"capture-action","aria-label":c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:c.bufferEnabled?`Save last 30 seconds · ${c.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!m||c.recording||c.timelapse||c.busy||c.bufferEnabled&&c.bufferSeconds<1,onClick:()=>c.bufferEnabled?void p(n.saveLast30Seconds):void g(),type:"button",children:[s.jsx(c0,{size:17}),s.jsx("small",{children:"30s"})]}),s.jsx("button",{className:`capture-action ${c.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!m||c.busy||c.recording,onClick:()=>{p(c.timelapse?n.stopTimelapse:n.startTimelapse)},type:"button",children:c.timelapse?s.jsxs(s.Fragment,{children:[s.jsx(iy,{size:14,fill:"currentColor"}),s.jsx("span",{children:Ad(c.timelapseStartedAt)})]}):s.jsx(u0,{size:17})})]})}async function gM(n,a={}){const r=n.filter(x=>x.canvas&&x.canvas.width>0&&x.canvas.height>0),l=Math.max(320,a.maxWidth||1920),c=Math.max(180,a.maxHeight||1080),d=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,m=Math.max(1,Math.ceil(Math.max(1,r.length)/d)),p=Math.floor(l/d),g=Math.floor(c/m),v=document.createElement("canvas");v.width=Math.max(320,p*d),v.height=Math.max(180,g*m);const w=v.getContext("2d",{alpha:!1});if(!w)return v;w.fillStyle="#0b1220",w.fillRect(0,0,v.width,v.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let x=0;x<r.length;x+=1){const b=r[x],C=x%d,j=Math.floor(x/d),A=C*p,N=j*g,k=b.canvas,T=Math.min(p/k.width,g/k.height),R=Math.max(1,Math.floor(k.width*T)),U=Math.max(1,Math.floor(k.height*T)),O=A+Math.floor((p-R)/2),Y=N+Math.floor((g-U)/2);w.drawImage(k,O,Y,R,U),a.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,N+g-28,p,28),w.fillStyle="#f8fafc",w.fillText(b.label,A+9,N+g-9))}return v}function vM(n){return n?.signature||"none"}function yM(n){return n?.label||"No capture target"}function wx(n){return{...n,deviceIds:[...n.deviceIds],sourceCanvas:n.sourceCanvas||null}}function xM(){const n=new Date,a=r=>String(r).padStart(2,"0");return`${n.getFullYear()}${a(n.getMonth()+1)}${a(n.getDate())}_${a(n.getHours())}${a(n.getMinutes())}${a(n.getSeconds())}`}function bM(n){return n.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function wM(n){return`LiveDesk_${n.type==="wall"||n.type==="selection"?"Wall":`${bM(n.label)}_Monitor-${Number(n.monitorIndex||0)+1}`}_${xM()}.png`}async function SM(n,a,r){const l=await new Promise((d,m)=>n.toBlob(p=>p?d(p):m(new Error("Screenshot could not be encoded.")),"image/png")),c=await rw(l,{kind:"screenshot",fileName:wM(a),target:a},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":l})])}catch{}return c.capture}function lw(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(a=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(a))||""}function CM(n,a){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),l=a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return n==="timelapse"?`LiveDesk_Timelapse_${l}_${r}.webm`:`LiveDesk_Recording_${l}_${r}.webm`}async function ow(n){if(typeof MediaRecorder>"u"||typeof n.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const a=lw();if(!a)throw new Error("This browser does not support WebM recording.");const r=n.kind||"recording",l=await uM({kind:r,fileName:CM(r,n.target),mimeType:a,target:n.target},n.hubUrl),c=n.canvas.captureStream(n.frameRequests?0:n.fps),d=new MediaRecorder(c,{mimeType:a,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),m=performance.now();let p=0,g=!1,v=null,w=Promise.resolve();return d.ondataavailable=x=>{if(!x.data||x.data.size===0)return;const b=p++;w=w.then(()=>dM(l.sessionId,b,x.data,n.hubUrl).then(()=>{})).catch(C=>{v=v||(C instanceof Error?C:new Error(String(C))),n.onError?.(v)})},d.onerror=()=>{v=new Error("Video recording stopped unexpectedly."),n.onError?.(v)},d.start(1e3),{requestFrame:()=>{c.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(x=>{d.addEventListener("stop",()=>x(),{once:!0}),d.stop()}),c.getTracks().forEach(x=>x.stop()),await w,v)throw await yx(l.sessionId,n.hubUrl).catch(()=>{}),v;await fM(l.sessionId,Math.max(0,performance.now()-m),n.hubUrl)}},cancel:async()=>{g||(g=!0,d.stop(),c.getTracks().forEach(x=>x.stop()),await yx(l.sessionId,n.hubUrl).catch(()=>{}))}}}class jM{recorder=null;stream=null;segments=[];totalBytes=0;targetSignature="";startedAt=0;maxDurationMs=3e4;maxBytes=128*1024*1024;get seconds(){return!this.startedAt||this.segments.length===0?0:Math.min(30,Math.max(0,(performance.now()-this.segments[0].at)/1e3))}get active(){return this.recorder!==null}async start(a,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof a.captureStream!="function")throw new Error("This browser does not support Last 30s.");const l=lw();if(!l)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=a.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:l,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=c=>{if(!c.data.size)return;const d=performance.now();for(this.segments.push({blob:c.data,at:d}),this.totalBytes+=c.data.size;this.segments.length>1&&(d-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const m=this.segments.shift();this.totalBytes-=m.blob.size}},this.recorder.start(1e3)}stop(){const a=this.recorder;this.recorder=null,a&&a.state!=="inactive"&&(a.ondataavailable=null,a.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(a,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const l=new Blob(this.segments.map(m=>m.blob),{type:this.segments[0].blob.type||"video/webm"}),d=`LiveDesk_Last30s_${a.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall"}_${new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_")}.webm`;return await rw(l,{kind:"last-30s",fileName:d,target:a,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function kM(n,a,r,l,c){const d=await ow({canvas:n,target:a,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:l,onError:c});d.requestFrame?.();const m=window.setInterval(()=>d.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(m),await d.stop()},cancel:async()=>{window.clearInterval(m),await d.cancel()}}}const cw="livedesk.captureSettings";function AM(){const n={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const a=JSON.parse(localStorage.getItem(cw)||"null");return{...n,...a&&typeof a=="object"?a:{}}}catch{return n}}function NM(n){const[a,r]=u.useState(AM),[l,c]=u.useState(0),[d,m]=u.useState(0),[p,g]=u.useState(0),[v,w]=u.useState(!1),x=u.useRef(void 0),b=u.useRef(!1),C=u.useRef(""),j=u.useRef(null),A=u.useRef(null),N=u.useRef(null),k=u.useRef(null),T=u.useRef(new jM),R=n.sourceRegistry.resolveCurrentTarget(),U=vM(R),O=yM(R),Y=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;u.useEffect(()=>{if(localStorage.setItem(cw,JSON.stringify(a)),!b.current)return;const q=JSON.stringify(a);q!==C.current&&(C.current=q,Ge("/api/settings",{method:"PATCH",body:JSON.stringify({revision:x.current,filesAudio:{rollingBufferEnabled:a.rollingEnabled,recordingQuality:a.recordingQuality,timelapseIntervalSeconds:a.timelapseIntervalSeconds,includeRemoteCursor:a.includeRemoteCursor}})},n.hubUrl).then(V=>{x.current=Number(V.revision||x.current||0)}).catch(()=>{}))},[n.hubUrl,a]),u.useEffect(()=>{let q=!0;return Ge("/api/settings",void 0,n.hubUrl).then(V=>{if(!q)return;const ce=V.settings?.filesAudio||{},be=typeof ce.rollingBufferEnabled=="boolean"?ce.rollingBufferEnabled:a.rollingEnabled,X=ce.recordingQuality==="high"?"high":"standard",$=[5,10,30,60].includes(Number(ce.timelapseIntervalSeconds))?Number(ce.timelapseIntervalSeconds):a.timelapseIntervalSeconds,ue=typeof ce.includeRemoteCursor=="boolean"?ce.includeRemoteCursor:a.includeRemoteCursor,he={rollingEnabled:be,recordingQuality:X,timelapseIntervalSeconds:$,includeRemoteCursor:ue};x.current=Number(V.revision||0),C.current=JSON.stringify(he),b.current=!0,r(he)}).catch(()=>{b.current=!0}),()=>{q=!1}},[n.hubUrl]);const _=u.useCallback(async q=>{if(q.sourceCanvas&&q.sourceCanvas.width>0&&q.sourceCanvas.height>0)return{target:wx(q),canvas:q.sourceCanvas,cleanup:()=>{}};const V=await n.sourceRegistry.composeWall(q.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let ce=!1;const be=window.setInterval(async()=>{if(ce)return;const X=await n.sourceRegistry.composeWall(q.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!X||ce||((V.width!==X.width||V.height!==X.height)&&(V.width=X.width,V.height=X.height),V.getContext("2d")?.drawImage(X,0,0))},100);return{target:wx(q),canvas:V,cleanup:()=>{ce=!0,window.clearInterval(be)}}},[n.sourceRegistry]);u.useEffect(()=>{const q=T.current;if(!a.rollingEnabled||!R||!Y){q.stop(),g(0);return}let V=!1,ce=null;return(async()=>{try{if(ce=await _(R),V)return;await q.start(ce.canvas,ce.target);const X=window.setInterval(()=>g(Math.round(q.seconds)),500),$=()=>{window.clearInterval(X),ce?.cleanup()};q.__cleanup=$}catch(X){V||n.onToast(X instanceof Error?X.message:String(X))}})(),()=>{V=!0,q.stop(),q.__cleanup?.(),q.__cleanup=void 0,g(0)}},[_,n.onToast,a.rollingEnabled,U,Y]);const D=u.useCallback(q=>r(V=>({...V,rollingEnabled:q})),[]),ne=u.useCallback(q=>r(V=>({...V,recordingQuality:q})),[]),G=u.useCallback(q=>r(V=>({...V,timelapseIntervalSeconds:q})),[]),te=u.useCallback(async()=>{const q=n.sourceRegistry.resolveCurrentTarget();if(!q)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let V=null;try{V=await _(q),await SM(V.canvas,V.target,n.hubUrl),n.onToast("Screenshot saved")}finally{V?.cleanup(),w(!1)}},[_,n.hubUrl,n.onToast,n.sourceRegistry]),B=u.useCallback(async()=>{if(N.current)throw new Error("Stop the timelapse before recording.");const q=n.sourceRegistry.resolveCurrentTarget();if(!q)throw new Error("화면이 준비된 후 다시 시도하세요.");const V=await _(q),ce=await ow({canvas:V.canvas,target:V.target,fps:q.type==="control"?30:15,hubUrl:n.hubUrl,onError:be=>n.onToast(be.message)});A.current=V.cleanup,j.current=ce,c(Date.now()),n.onToast("Recording started")},[_,n.hubUrl,n.onToast,n.sourceRegistry]),xe=u.useCallback(async()=>{const q=j.current;if(q){w(!0);try{await q.stop(),n.onToast("Recording saved")}finally{j.current=null,A.current?.(),A.current=null,c(0),w(!1)}}},[n.onToast]),se=u.useCallback(async()=>{if(j.current||N.current)throw new Error("Last 30s is unavailable during a recording.");const q=n.sourceRegistry.resolveCurrentTarget();if(!q)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(q,n.hubUrl),n.onToast("Last 30 seconds saved")}finally{w(!1)}},[n.hubUrl,n.onToast,n.sourceRegistry]),K=u.useCallback(async()=>{if(j.current)throw new Error("Stop the recording before starting a timelapse.");const q=n.sourceRegistry.resolveCurrentTarget();if(!q)throw new Error("화면이 준비된 후 다시 시도하세요.");const V=await _(q),ce=await kM(V.canvas,V.target,a.timelapseIntervalSeconds,n.hubUrl,be=>n.onToast(be.message));k.current=V.cleanup,N.current=ce,m(Date.now()),n.onToast("Timelapse started")},[_,n.hubUrl,n.onToast,n.sourceRegistry,a.timelapseIntervalSeconds]),I=u.useCallback(async()=>{const q=N.current;if(q){w(!0);try{await q.stop(),n.onToast("Timelapse saved")}finally{N.current=null,k.current?.(),k.current=null,m(0),w(!1)}}},[n.onToast]);return u.useEffect(()=>{const q=V=>{!j.current&&!N.current||(V.preventDefault(),V.returnValue="")};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[]),u.useEffect(()=>()=>{T.current.stop(),j.current?.cancel(),N.current?.cancel(),A.current?.(),k.current?.()},[]),{state:u.useMemo(()=>({recording:!!j.current,recordingStartedAt:l,timelapse:!!N.current,timelapseStartedAt:d,bufferSeconds:p,bufferEnabled:a.rollingEnabled,busy:v,targetLabel:O}),[p,v,l,a.rollingEnabled,O,d]),settings:a,videoSupported:Y,targetKey:U,setRollingEnabled:D,setRecordingQuality:ne,setTimelapseInterval:G,takeScreenshot:te,startRecording:B,stopRecording:xe,saveLast30Seconds:se,startTimelapse:K,stopTimelapse:I}}const MM=120,TM=999,Ec=5,Rc=30,EM=Number.POSITIVE_INFINITY,uw="livedesk.remoteDirectory",Bh="livedesk.localHubAccessEnabled",dw="livedesk.streamSettings",Fh=16,fw="livedesk.controlStreamSettings",Ph=6,mw="livedesk.wallMonitorSelections",hw=1,dh=512*1024,$h="".trim(),pw="".trim(),Sx="livedesk-adsense-script",fh=!!$h&&!!pw,RM=1e3/60,mh=1500,DM=650,LM=1800,_M=650,zM=2500,Cx=1500,jx=15e3,IM=6e4,kx=240,OM=1024,HM=480,BM=270,Ax="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Nd="LiveDesk is replacing the Hub and verifying the requested version.",Md=5*6e4,FM=5e3;function Dr({label:n,tooltip:a,disabled:r=!1,active:l=!1,danger:c=!1,pressed:d,onClick:m,children:p}){return s.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":a,children:s.jsx("button",{className:`manual-action ${l?"active":""} ${c?"danger":""}`.trim(),onClick:m,disabled:r,"aria-label":n,"aria-pressed":d,type:"button",children:p})})}function PM(n,a){if(a.deviceId!==n.deviceId)return!1;const r=Number(a.browserReceivedEpochMs);if(!Number.isFinite(r)||r<n.startedAtEpochMs)return!1;const l=Number(a.monitorIndex);if(Number.isFinite(l)&&Math.floor(l)!==n.monitorIndex)return!1;const c=String(a.frameMode||a.mode||"").trim().toLowerCase();return!c||c===n.frameMode}const Cl={free:{name:"Free",price:"$0",limit:Ec,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Rc,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:EM,audience:"Business and studios",note:"Commercial use and larger workstation walls."}},gw={"mode1-jpeg":5,"mode3-h264-hw":30,"mode4-h264-atlas":20};function Nx(n,a){const r=m=>{const g=String(m||"").trim().replace(/^v/i,"").match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!g)return null;const v=g[4]?g[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return v.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:v}},l=r(n),c=r(a);if(!l||!c)return!1;for(let m=0;m<3;m+=1){if(l.core[m]>c.core[m])return!0;if(l.core[m]<c.core[m])return!1}if(l.prerelease.length===0||c.prerelease.length===0)return l.prerelease.length===0;const d=Math.max(l.prerelease.length,c.prerelease.length);for(let m=0;m<d;m+=1){const p=l.prerelease[m],g=c.prerelease[m];if(p===void 0||g===void 0)return g===void 0;if(p!==g){if(typeof p=="number"&&typeof g=="number")return p>g;if(typeof p=="number")return!1;if(typeof g=="number"||p>g)return!0;if(p<g)return!1}}return!0}function Ms(n,a){return`${n}:${a}`}const va={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:gw["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},Ra={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-software",fps:30,maxWidth:1920,maxHeight:1080,quality:75,showScreenStatus:!1};function hh(n,a){if(n.length===0)return 0;const r=[...n].sort((c,d)=>c-d),l=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*a)-1));return r[l]}function vw(n,a){n.push(a),n.length>kx&&n.splice(0,n.length-kx)}function Mx(n,a){n.sampleFrames=0,n.sampleStartedAt=a,n.intervalCount=0,n.intervalSumMs=0,n.minIntervalMs=Number.POSITIVE_INFINITY,n.maxIntervalMs=0,n.intervalSamplesMs.length=0,n.seqGapCount=0,n.maxSeqGap=0}function Tx(n,a,r){if(n.lastAt!==void 0){const l=Math.max(0,a-n.lastAt);n.intervalCount+=1,n.intervalSumMs+=l,n.minIntervalMs=Math.min(n.minIntervalMs,l),n.maxIntervalMs=Math.max(n.maxIntervalMs,l),vw(n.intervalSamplesMs,l)}if(n.lastFrameSeq!==void 0){const l=r-n.lastFrameSeq;l!==1&&(n.seqGapCount+=1,n.maxSeqGap=Math.max(n.maxSeqGap,Math.abs(l)))}n.lastAt=a,n.lastFrameSeq=r}function Ex(n){return!n||n.intervalCount<=0?"waiting":`${Math.round(n.averageIntervalMs)}ms avg / p95 ${Math.round(n.p95IntervalMs)}ms / max ${Math.round(n.maxIntervalMs)}ms`}function Rx(n){return!n||n.seqGapCount<=0?"none":`${n.seqGapCount} gaps / max ${n.maxSeqGap}`}function $M(n){return Number.isFinite(n)?String(n):"30+"}const Od=[{id:"mode4-h264-atlas",label:"Mode 4",detail:"Hub H.264 Atlas"},{id:"mode3-h264-hw",label:"Mode 3",detail:"H.264 hardware"}],Uh=[{id:"prefer-software",label:"Software low latency"},{id:"prefer-hardware",label:"Hardware decode"},{id:"no-preference",label:"Browser auto"}],UM=[{id:"mode3-h264-hw",label:"Mode 3 - H.264 hardware"}],Hd=[{id:"640x360",label:"Compact",width:640,height:360},{id:"960x540",label:"Standard",width:960,height:540},{id:"1280x720",label:"HD",width:1280,height:720},{id:"1920x1080",label:"Full HD",width:1920,height:1080},{id:"2560x1440",label:"QHD",width:2560,height:1440},{id:"3840x2160",label:"4K",width:3840,height:2160}],ph=Hd.filter(n=>n.width>=1280),gh=[{id:"auto",label:"Auto by wall size"},{id:"320x180",label:"Standard 320x180",width:320,height:180},{id:"480x270",label:"Sharp 480x270",width:480,height:270}],yp=[1,2,5,8,12,20,30],qM=[20,30,60],Dx=[45,60,75,90],Lx={large:{maxWidth:1280,maxHeight:720},medium:{maxWidth:960,maxHeight:540},small:{maxWidth:640,maxHeight:360}},oa={preserveConfiguredFpsDeviceCount:12,visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,small:32},maxWallFramesPerSecond:ei.maxDirectFramesPerSecond,maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,lowLoadFrameRatio:.58,lowLoadByteRatio:.52,downshiftCooldownMs:1800,recoveryCooldownMs:14e3,minFps:5},_x=2200,GM=8e3,VM=3500,WM=7e3,YM=2,KM=2600,QM=4200,XM=750,ZM=2,zx=4200;function Ix(n,a){return Math.min(3e4,n*2**Math.min(3,Math.max(0,a)))}function Bc(n,a){const r=n.capabilities?.[a];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function fs(n){return n.deviceName||n.hostname||n.deviceId}function JM(){return"npx -y --prefer-online livedesk@latest client"}function eT(){return"npx -y --prefer-online livedesk@latest"}function tT(){try{return localStorage.getItem(uw)||""}catch{return""}}function nT(){try{return localStorage.getItem(Bh)==="1"}catch{return!1}}function Co(n){try{n?localStorage.setItem(Bh,"1"):localStorage.removeItem(Bh)}catch{}}function ms(n,a,r,l){const c=Number(n);return Number.isFinite(c)?Math.max(a,Math.min(r,Math.round(c))):l}function qh(n){const a=String(n||"").trim();return Od.some(r=>r.id===a)?a:va.frameMode}function Zd(n){const a=String(n||"").trim();return Uh.some(r=>r.id===a)?a:va.h264DecodeAcceleration}function Gh(n){return n==="mode3-h264-hw"?n:Ra.frameMode}function yw(n){return gw[n]||12}function xw(n){return n==="mode3-h264-hw"?30:n==="mode4-h264-atlas"?20:30}function Vh(n,a){return ms(n,1,xw(a),yw(a))}function zl(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:{}}function ga(n){const a=zl(n.status),r=zl(a.screens),l=zl(n.capabilities),c=[a.monitorCount,a.screenCount,r.count,l.monitorCount,l.screenCount];for(const d of c){const m=Number(d);if(Number.isFinite(m)&&m>0)return Math.max(1,Math.min(64,Math.floor(m)))}return 1}function zr(n){const a=Number(n);return Number.isFinite(a)&&a>0?Math.floor(a):0}function aT(n){const a=zl(n.status),l=[zl(a.screens).displays,a.displays,a.monitors];for(const c of l)if(!(!Array.isArray(c)||c.length===0))return c.map(d=>zl(d));return[]}function bw(n,a){const r=aT(n),l=r.find(g=>Number(g.index)===a)||r[a]||r[0]||{},c=zr(l.width),d=zr(l.height),m=[l.name,l.displayName,l.deviceName,l.id].find(g=>typeof g=="string"&&g.trim()),p=typeof m=="string"?m.trim():`Display ${a+1}`;return{index:a,name:p,width:c,height:d,primary:l.primary===!0||l.isPrimary===!0}}function sT(n){const a=ga(n);return Array.from({length:a},(r,l)=>bw(n,l))}function iT(n){const a=[n.name||`Display ${n.index+1}`];return n.width>0&&n.height>0&&a.push(`${n.width}x${n.height}`),n.primary&&a.push("Primary"),a.join(" - ")}function ww(n,a){const r=bw(n,a);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const l=zl(n.status),c=zr(l.screenWidth||l.width),d=zr(l.screenHeight||l.height);return c>0&&d>0?{width:c,height:d}:null}function Sw(n){if(!n)return null;const a=zr(n.sourceWidth)||zr(n.width),r=zr(n.sourceHeight)||zr(n.height);return a>0&&r>0?{width:a,height:r}:null}function rT(n,a,r){const d=((typeof a?.monitorIndex=="number"?Ea(a.monitorIndex,Math.max(1,a.monitorCount||1)):r)===r?Sw(a):null)||ww(n,r);return d?Math.max(.25,Math.min(4,d.width/d.height)):16/9}const Td=16/9;function Ea(n,a){const r=Math.max(1,Math.min(64,Math.floor(Number(a)||1))),l=Math.floor(Number(n));return Number.isFinite(l)?Math.max(0,Math.min(r-1,l)):0}function lT(){try{const n=localStorage.getItem(mw);if(!n)return{};const a=JSON.parse(n),r=a&&typeof a=="object"&&!Array.isArray(a)?a.selections:void 0;if(Number(a?.version)!==hw||!r||typeof r!="object"||Array.isArray(r))return{};const l={};for(const[c,d]of Object.entries(r)){const m=c.trim(),p=Math.floor(Number(d));!m||!Number.isFinite(p)||(l[m]=Math.max(0,Math.min(63,p)))}return l}catch{return{}}}function oT(n){try{localStorage.setItem(mw,JSON.stringify({version:hw,selections:n}))}catch{}}function cT(){try{const n=JSON.parse(localStorage.getItem(dw)||"{}"),a=Number(n.version);if(![Fh,15,14,13,12,11].includes(a))return va;const r=qh(n.frameMode),l=ms(n.maxWidth,320,3840,va.maxWidth),c=ms(n.maxHeight,180,2160,va.maxHeight);return{frameMode:r,h264DecodeAcceleration:Zd(n.h264DecodeAcceleration),fps:a<Fh&&r==="mode3-h264-hw"?va.fps:Vh(n.fps,r),maxWidth:l,maxHeight:c,atlasTileWidth:Number(n.atlasTileWidth)>=480?480:320,atlasTileHeight:Number(n.atlasTileHeight)>=270?270:180,atlasTileSizeMode:n.atlasTileSizeMode==="fixed"?"fixed":"auto",quality:ms(n.quality,20,95,va.quality),autoStartLive:typeof n.autoStartLive=="boolean"?n.autoStartLive:va.autoStartLive,showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:va.showScreenStatus,visibleOnlyLive:typeof n.visibleOnlyLive=="boolean"?n.visibleOnlyLive:va.visibleOnlyLive,adaptiveLoadShedding:typeof n.adaptiveLoadShedding=="boolean"?n.adaptiveLoadShedding:va.adaptiveLoadShedding,adaptiveSizeByWall:typeof n.adaptiveSizeByWall=="boolean"?n.adaptiveSizeByWall:va.adaptiveSizeByWall}}catch{return va}}function uT(n){try{localStorage.setItem(dw,JSON.stringify({...n,version:Fh}))}catch{}}function dT(){try{const n=JSON.parse(localStorage.getItem(fw)||"{}"),a=Number(n.version);if(![Ph,5,4,3,2,1].includes(a))return Ra;const r=ms(n.fps,20,60,Ra.fps),l=a<Ph;return{frameMode:l?Ra.frameMode:Gh(n.frameMode),h264DecodeAcceleration:l?Ra.h264DecodeAcceleration:Zd(n.h264DecodeAcceleration),fps:l?Ra.fps:r,maxWidth:ms(n.maxWidth,1280,3840,Ra.maxWidth),maxHeight:ms(n.maxHeight,720,2160,Ra.maxHeight),quality:ms(n.quality,20,95,Ra.quality),showScreenStatus:typeof n.showScreenStatus=="boolean"?n.showScreenStatus:Ra.showScreenStatus}}catch{return Ra}}function fT(n){try{localStorage.setItem(fw,JSON.stringify({...n,version:Ph}))}catch{}}function vh(n,a){return n.length!==a.length?!1:n.every((r,l)=>r===a[l])}function yh(n){return[...new Set(n.filter(Boolean))].sort()}function mT(n){return oa.fallbackVisibleCounts[n]||oa.fallbackVisibleCounts.large}function hT(n,a,r){if(n.frameMode==="mode4-h264-atlas")return n.atlasTileSizeMode==="auto"?a==="large"?{maxWidth:480,maxHeight:270}:{maxWidth:320,maxHeight:180}:{maxWidth:n.atlasTileWidth,maxHeight:n.atlasTileHeight};if(!n.adaptiveSizeByWall)return{maxWidth:n.maxWidth,maxHeight:n.maxHeight};const l=Lx[a]||Lx.large;return{maxWidth:Math.min(n.maxWidth,l.maxWidth),maxHeight:Math.min(n.maxHeight,l.maxHeight)}}function pT(n,a=oa.minFps){const r=[...yp].sort((c,d)=>c-d),l=Math.max(a,Math.floor(n/2));return[...r].reverse().find(c=>c<n&&c>=a)||l}function gT(n,a){return[...yp].sort((l,c)=>l-c).find(l=>l>n&&l<=a)||a}function Dc(n){if(!Number.isFinite(n)||n<=0)return"0 B";const a=["B","KB","MB","GB","TB"];let r=n,l=0;for(;r>=1024&&l<a.length-1;)r/=1024,l+=1;const c=l===0||r>=100?0:1;return`${r.toFixed(c)} ${a[l]}`}function Ox(n){if(!Number.isFinite(n)||!n||n<=0)return"0GB";const a=1024**4,r=1024**3;return n>=a?`${Math.max(1,Math.round(n/a))}TB`:`${Math.max(1,Math.round(n/r))}GB`}function xh(n,a){if(!Number.isFinite(n)||!n||n<=0)return"not reported";const r=Math.max(0,n-Math.max(0,Number(a||0)));return`${Ox(r)} / ${Ox(n)}`}function vT(n){const a=new Uint8Array(n),r=32768;let l="";for(let c=0;c<a.length;c+=r){const d=a.subarray(c,c+r);l+=String.fromCharCode(...d)}return btoa(l)}function Hx(n){return Array.from(n).filter(a=>a.size>=0).map(a=>{const r=a.webkitRelativePath||a.name;return{file:a,relativePath:r,fingerprint:`${a.size}:${a.lastModified}`}})}function yT(n){return n===1?"middle":n===2?"right":"left"}function Bx(n,...a){for(const r of a){const l=n?.[r];if(typeof l=="string"&&l.trim())return l.trim()}return""}function Fx(n){const a=Number(n);return Number.isInteger(a)&&a>=1&&a<=TM?a:0}const xT={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function bT(n,a,r){if(n==="online")return"Online";if(n==="busy")return"Busy";if(n==="stale")return"Stale";if(n==="offline")return"Offline";if(r==="failed")return"Task failed";const l=n==="critical"?"critical":"warn",c=a.find(m=>m.state===l)||a.find(m=>m.state==="critical"||m.state==="warn");if(!c)return n==="critical"?"Issue":"Check";const d=xT[c.id]||c.label;return c.value&&c.value!=="-"?`${d} ${c.value}`:d}function of(n,a){const r=a.split(".");let l=n;for(const c of r){if(l==null)return;if(Array.isArray(l)){const d=Number(c);l=Number.isInteger(d)?l[d]:void 0;continue}if(typeof l=="object"){l=l[c];continue}return}return l}function hn(n,...a){for(const r of a){const l=of(n,r),c=Number(l);if(Number.isFinite(c))return c}}function Wa(n,...a){for(const r of a){const l=of(n,r);if(typeof l=="string"&&l.trim())return l.trim();if(typeof l=="number"&&Number.isFinite(l))return String(l)}return""}function wT(n,...a){for(const r of a){const l=of(n,r);if(typeof l=="boolean")return l;if(/^(1|true|yes|on|online|running|ready)$/i.test(String(l||"").trim()))return!0;if(/^(0|false|no|off|offline|stopped|missing)$/i.test(String(l||"").trim()))return!1}}function _i(n){const a=Number(n);if(Number.isFinite(a))return Math.max(0,Math.min(1,a>1?a/100:a))}function bh(n,a){if(!(typeof n!="number"||typeof a!="number"||!Number.isFinite(n)||!Number.isFinite(a)||n<=0))return _i((n-Math.max(0,a))/n)}function jo(n){return n===void 0?"-":`${Math.round(n*100)}%`}function wh(n){return n===void 0||!Number.isFinite(n)?"":n>=1e3?`${(n/1e3).toFixed(n>=1e4?0:1)}Gb/s`:`${Math.round(n)}Mb/s`}function jl(n,a=.92,r=.78){return n===void 0?"unknown":n>=a?"critical":n>=r?"warn":"good"}function ST(n){return!Number.isFinite(n)||!n||n<=0?"-":n<3600?`${Math.round(n/60)}m`:n<86400?`${Math.round(n/3600)}h`:`${Math.round(n/86400)}d`}function Ed(n,a,r){const l=of(n,`tools.${a}`),c=Wa(n,`tools.${a}.status`,`tooling.${a}.status`,`${a}.status`).toLowerCase(),d=wT(n,`tools.${a}.running`,`tooling.${a}.running`,`${a}.running`),m=Wa(n,`tools.${a}.version`,`tooling.${a}.version`,`${a}.version`),p=Wa(n,`tools.${a}.port`,`tooling.${a}.port`,`${a}.port`);let g="unknown";return c==="busy"?g="busy":["online","running","ready","active"].includes(c)||d===!0?g="online":(["offline","stopped","missing","not-found"].includes(c)||d===!1||l===!1)&&(g="offline"),{id:a,label:r,status:g,detail:g==="offline"?"offline":m||(p?`:${p}`:g==="unknown"?"not reported":g)}}function CT(n){const a=n.status||{},r=hn(a,"cpu.cores","cpuCores","processorCount"),l=hn(a,"loadavg.0","cpu.load1"),c=_i(hn(a,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&l!==void 0?l/Math.max(1,r):void 0)),d=hn(a,"memory.totalBytes","totalMem"),m=hn(a,"memory.freeBytes","freeMem"),p=_i(hn(a,"memory.usedRatio","memory.usedPct","usedMemRatio"))??bh(d,m),g=hn(a,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),v=hn(a,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=_i(hn(a,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??bh(g,v),x=hn(a,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),b=_i(hn(a,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),C=Wa(a,"gpu.name","gpu.model","accelerators.gpu.name"),j=hn(a,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=hn(a,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),N=_i(hn(a,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??bh(j,A),k=hn(a,"gpu.temperatureC","thermal.gpuC"),T=_i(hn(a,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),R=Wa(a,"npu.name","npu.model","accelerators.npu.name"),U=hn(a,"npu.tops","npu.topsInt8","accelerators.npu.tops"),O=hn(a,"network.rxMbps","network.receiveMbps","network.downMbps"),Y=hn(a,"network.txMbps","network.transmitMbps","network.upMbps"),_=hn(a,"network.latencyMs","network.rttMs"),D=_i(hn(a,"network.usedRatio","network.usageRatio","network.saturationRatio")),ne=Wa(a,"network.link","network.interface","network.name"),G=x===void 0?void 0:_i((x-35)/60),te=Wa(a,"workload.role","role","lane")||(Bc(n,"aiAssist")?"Agent worker":Bc(n,"taskDispatch")?"Task worker":"Local machine"),B=Wa(n.latestTask,"status")||Wa(a,"workload.status")||"idle",xe=Wa(n.latestTask,"title","instructionPreview")||Wa(a,"workload.title"),se=Wa(n.latestTask,"resultSummary","error","instructionPreview")||Wa(a,"workload.summary"),K=[Ed(a,"ollama","Ollama"),Ed(a,"lmStudio","LM Studio"),Ed(a,"comfyui","ComfyUI"),Ed(a,"stableDiffusion","Stable Diffusion")],I=K.some(X=>X.status!=="unknown"),Q=Date.parse(n.lastSeenAt||n.connectedAt||""),q=Number.isFinite(Q)?Date.now()-Q:0;let V="online";n.connected?q>5*6e4?V="stale":(x??0)>=86||(k??0)>=88||(c??0)>=.94||(b??0)>=.96||(N??0)>=.96||(T??0)>=.96||(p??0)>=.94||(w??0)>=.94||(_??0)>=200||B==="failed"?V="critical":(x??0)>=78||(k??0)>=80||(c??0)>=.82||(b??0)>=.86||(N??0)>=.88||(T??0)>=.86||(p??0)>=.82||(w??0)>=.86||(_??0)>=80?V="warn":(["queued","running","targeted"].includes(B)||K.some(X=>X.status==="busy"))&&(V="busy"):V="offline";const ce=K.filter(X=>X.status==="online"||X.status==="busy").length,be=[{id:"cpu",label:"CPU",value:jo(c),detail:r?`${r} cores`:l!==void 0?`load ${l.toFixed(1)}`:"not reported",ratio:c,state:jl(c,.92,.78)},{id:"memory",label:"RAM",value:jo(p),detail:xh(d,m),ratio:p,state:jl(p,.92,.78)},{id:"disk",label:"DISK",value:jo(w),detail:xh(g,v),ratio:w,state:jl(w,.92,.82)},{id:"gpu",label:"GPU",value:jo(b),detail:C||(j&&A!==void 0?`${Dc(A)} VRAM free`:k!==void 0?`${Math.round(k)}C`:"not reported"),ratio:b,state:k!==void 0&&k>=88?"critical":k!==void 0&&k>=80?"warn":jl(b,.96,.86)},{id:"vram",label:"VRAM",value:jo(N),detail:xh(j,A),ratio:N,state:jl(N,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?jo(T):U!==void 0?`${Math.round(U)} TOPS`:"-",detail:R||(U!==void 0?"neural engine":"not reported"),ratio:T,state:jl(T,.96,.86)},{id:"temp",label:"TEMP",value:x===void 0?"-":`${Math.round(x)}C`,detail:ce>0?`${ce} local tools`:`uptime ${ST(hn(a,"uptimeSec"))}`,ratio:G,state:x===void 0?"unknown":x>=86?"critical":x>=78?"warn":"good"},{id:"network",label:"NET",value:wh(O)||(_!==void 0?`${Math.round(_)}ms`:ne||"-"),detail:wh(Y)?`${wh(Y)} up`:ne||"not reported",ratio:D,state:_!==void 0&&_>=200?"critical":_!==void 0&&_>=80?"warn":jl(D,.9,.75)}];return{state:V,label:bT(V,be,B),role:te,taskLabel:xe||(B==="idle"?"idle":B),taskStatus:B,taskSummary:se,tools:I?K:K.map(X=>({...X,detail:"not reported"})),metrics:be}}const jT=[{id:"small",label:"Small"},{id:"medium",label:"Medium"},{id:"large",label:"Large"}],kT=[{id:"sync-server",label:"Hub",icon:El,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:Pc,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Dd,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Rd,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:Ld,accent:"violet",tooltip:"agents"}],AT=[{id:"doc",label:"Doc",icon:Bd,accent:"amber"},{id:"support",label:"Support",icon:Lc,accent:"violet"},{id:"pricing",label:"Pricing",icon:Ao,accent:"green"}];function NT(n){return n.replaceAll("npx -y @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx @livedesk/client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx livedesk client","npx -y --prefer-online livedesk@latest client").replaceAll("npx -y livedesk","npx -y --prefer-online livedesk@latest").replaceAll("npx livedesk","npx -y --prefer-online livedesk@latest")}function on(n){return NT(n).replaceAll("Sync Server","Hub").replace(/\bRemoteHub\b/g,"Hub client endpoint").replace(/\bManagers\b/g,"Hubs").replace(/\bManager\b/g,"Hub").replace(/\bmanager\b/g,"Hub").replace(/\bMANAGER\b/g,"HUB").replace(/매니저/g,"Hub")}function kl(n){return n.map(a=>on(a))}function ra(n){return{languageName:n.languageName,languageLabel:n.languageLabel,eyebrow:n.eyebrow,title:on(n.title),intro:on(n.intro),sections:[{title:on(n.managerTitle),body:on(n.managerBody),points:kl(n.managerPoints)},{title:on(n.clientTitle),body:on(n.clientBody),points:kl(n.clientPoints)},{title:on(n.syncTitle),body:on(n.syncBody),points:kl(n.syncPoints)},...n.agentTitle&&n.agentBody&&n.agentPoints?[{title:on(n.agentTitle),body:on(n.agentBody),points:kl(n.agentPoints)}]:[],{title:on(n.platformTitle),body:on(n.platformBody),points:kl(n.platformPoints)}],sync:{title:on(n.syncTitle),body:on(n.syncBody),points:kl(n.syncPoints)},firewall:{title:on(n.firewallTitle),body:on(n.firewallBody),points:kl(n.firewallPoints)},commands:{title:on(n.commandsTitle),body:on(n.commandsBody),manager:on(n.managerCommandLabel),primary:on(n.clientCommandLabel),slot:on(n.slotCommandLabel),manual:on(n.manualCommandLabel)}}}const Ro={ko:ra({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, AI 박스, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 npm-first 원격 작업 데크입니다.",managerTitle:"1. 매니저 실행",managerBody:"화면을 모아 볼 컴퓨터에서 LiveDesk 매니저를 실행합니다. 매니저는 UI와 로컬 서버를 같이 열고 브라우저를 http://127.0.0.1:5179 로 띄웁니다.",managerPoints:["명령은 npx -y livedesk 입니다.","매니저는 Screen Wall/API 포트 5179와 클라이언트 접속 포트 5197을 사용합니다.","기존 LiveDesk 포트가 남아 있으면 기본적으로 정리하고 새로 시작합니다. 필요하면 --no-clean 을 붙입니다."],clientTitle:"2. 워크스테이션 연결",clientBody:"모니터링할 PC에서는 Google 로그인 또는 Hub 화면의 6자리 PIN으로 연결합니다. Hub가 꺼져 있으면 실시간 온라인 알림을 기다리고 적응형 간격으로 다시 확인합니다.",clientPoints:["빈 자리에 자동 배치하려면 npx -y livedesk client 를 실행합니다.","자리 번호를 고정하려면 npx -y livedesk client 3 처럼 번호를 붙입니다.","브라우저 연결 페이지에서 Google 버튼 또는 6자리 PIN 입력 중 하나를 선택합니다."],syncTitle:"3. Sync Server와 자동 발견",syncBody:"Sync Server는 이 매니저를 현재 계정의 활성 Screen Wall로 Supabase에 등록합니다. 클라이언트는 같은 Google 계정으로 로그인한 뒤 그 기록을 읽고 접속 후보들을 순서대로 시도합니다.",syncPoints:["등록 정보에는 host instance, LAN/private 주소, public 후보 주소, pair token, 짧은 lease가 포함됩니다.","같은 LAN 후보를 먼저 쓰고, 필요하면 외부 주소 후보를 시도합니다.","매니저 위치, VPN, 방화벽, 공유기 설정이 바뀌었거나 개발 중 활성 매니저를 바꿀 때 Sync Server를 누릅니다.","이제 livedesk.pages.dev의 Chrome Local Network Access 허용은 기본 실행 경로가 아닙니다. npm 매니저 앱이 실제 서버입니다."],agentTitle:"4. Agent로 여러 장비 작업하기",agentBody:"Agents 화면은 Hub에서 실행되는 Codex 기반 Agent가 연결된 장비를 확인하고, 선택한 권한 범위 안에서 작업을 실행하는 공간입니다. 클라이언트 PC에 Codex 앱이나 Codex SDK를 설치할 필요는 없습니다.",agentPoints:["Suggested tasks에는 현재 72개의 읽기·운영 작업 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Agent 실행은 Hub의 격리된 runtime과 LiveDesk MCP 도구를 통해서만 장비에 전달되며, 모든 작업은 timeout·취소·tool limit·감사 로그 경계를 가집니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["Wall은 Mode 3 H.264와 Mode 4 H.264 Atlas를 사용합니다. Mode 2는 Mode 4의 내부 Atlas 입력에만 한정되며 Wall/Control fallback으로 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot 캡처, xdotool 입력 백엔드가 추가되었습니다. 오디오는 아직 비활성입니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"같은 LAN 안에서는 보통 공유기 포트포워딩이 필요 없습니다. 다른 장소의 PC를 붙이려면 클라이언트가 매니저의 클라이언트 접속 포트에 도달할 수 있어야 합니다.",firewallPoints:["클라이언트 접속 포트는 TCP 5197입니다.","클라이언트 쪽은 나가는 연결이므로 보통 인바운드 포트 개방이 필요 없습니다.","다른 네트워크에서 붙일 때는 매니저 PC 방화벽에서 TCP 5197 인바운드를 허용하고, 공유기에서는 TCP 5197을 매니저 PC로 전달합니다.","Screen Wall/API 포트 5179는 매니저 UI용입니다. 외부 브라우저에서 Wall을 직접 열 필요가 있을 때만 별도로 노출을 검토합니다.","공개 인터넷에 바로 열기보다 VPN, Tailscale, ZeroTier, 고정 IP allowlist를 우선합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:ra({languageName:"English",languageLabel:"Document language",eyebrow:"LiveDesk Manual",title:"Open a local Screen Wall with one command",intro:"LiveDesk is an npm-first remote work deck for monitoring many workstations, AI boxes, Mac minis, and dev machines from one manager PC.",managerTitle:"1. Run the manager",managerBody:"Run LiveDesk on the computer that will watch the screens. The manager starts the UI and local server together, then opens http://127.0.0.1:5179.",managerPoints:["The command is npx -y livedesk.","The manager uses port 5179 for the Screen Wall/API and port 5197 for client connections.","If an old LiveDesk process still owns those ports, startup cleans it by default. Add --no-clean when you want to keep it."],clientTitle:"2. Connect a workstation",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-workstation tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected workstations and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks currently contains 72 read-only and operational templates with search plus permission, platform, and capability availability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","Runs stay inside the Hub-isolated runtime and LiveDesk MCP tools, with timeout, cancellation, tool-call limits, and audit-log boundaries."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Wall uses Mode 3 H.264 and Mode 4 H.264 Atlas. Mode 2 is restricted to internal Mode 4 Atlas input and is never used as a Wall or Control fallback.","Remote audio is available when the selected workstation advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, grim/gnome-screenshot/import/scrot capture, and xdotool input backend. Audio is still disabled."],firewallTitle:"Firewall and remote locations",firewallBody:"On the same LAN, router forwarding is usually unnecessary. For another office, building, or country, clients must be able to reach the manager client port.",firewallPoints:["Client connection port: TCP 5197.","Client machines normally only need outbound access.","For remote networks, allow inbound TCP 5197 on the manager firewall and forward TCP 5197 from the router to the manager PC.","Screen Wall/API port 5179 is for the manager UI. Expose it only if a remote browser must open the Wall directly.","Prefer VPN, Tailscale, ZeroTier, or fixed-IP allowlists over public internet exposure."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:ra({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、AI マシン、Mac mini、開発機を1台の manager PC から監視する npm-first のリモート作業デッキです。",managerTitle:"1. manager を実行",managerBody:"画面を集めて見るコンピューターで LiveDesk manager を実行します。UI とローカルサーバーが同時に起動し、http://127.0.0.1:5179 が開きます。",managerPoints:["コマンドは npx -y livedesk です。","Screen Wall/API は 5179、client 接続は 5197 を使います。","古い LiveDesk プロセスがポートを使っている場合は、基本的に自動で整理して起動します。"],clientTitle:"2. workstation を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","livedesk.pages.dev の Chrome Local Network Access は標準実行経路ではありません。npm manager アプリが実際のサーバーです。"],platformTitle:"4. 現在のプラットフォーム状態",platformBody:"Windows は live screen transfer まで確認済みです。macOS と Linux も同じ npm コマンド経路を目標に対応を広げています。",platformPoints:["Windows: 動作確認済み。","macOS: 画面取得と制御には Screen Recording/Accessibility 権限が必要です。","Linux: linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"同じ LAN なら通常 router forwarding は不要です。外部拠点では client が manager の接続ポートへ到達できる必要があります。",firewallPoints:["client 接続ポートは TCP 5197 です。","client 側は通常 outbound だけで足ります。","外部 network では manager PC の firewall で TCP 5197 inbound を許可し、router から manager PC へ forward します。","5179 は manager UI 用なので、外部ブラウザで Wall を開く必要がある時だけ公開を検討します。","公開 internet より VPN、Tailscale、ZeroTier、IP allowlist を優先してください。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"workstation 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":ra({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作站、AI 主机、Mac mini 和开发机器。",managerTitle:"1. 运行 manager",managerBody:"在负责查看屏幕的电脑上运行 LiveDesk manager。它会同时启动 UI 和本地服务器,并打开 http://127.0.0.1:5179。",managerPoints:["命令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 连接使用 5197。","如果旧的 LiveDesk 进程占用端口,默认会清理后重新启动。"],clientTitle:"2. 连接 workstation",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是默认运行方式。npm manager app 才是真正服务器。"],platformTitle:"4. 当前平台状态",platformBody:"Windows 已确认可传输实时画面。macOS 和 Linux 正按同一 npm 命令路径扩展支持。",platformPoints:["Windows: 已确认可用。","macOS: 画面捕获和控制需要 Screen Recording/Accessibility 权限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot 捕获、xdotool 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"同一 LAN 通常不需要路由端口转发。不同地点连接时,client 必须能访问 manager 的 client 连接端口。",firewallPoints:["client 连接端口是 TCP 5197。","client 机器通常只需要出站访问。","跨网络时,在 manager 防火墙放行 TCP 5197 入站,并在路由器转发到 manager PC。","5179 是 manager UI 端口,仅在需要远程浏览器直接打开 Wall 时考虑暴露。","优先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":ra({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作站、AI 主機、Mac mini 與開發機。",managerTitle:"1. 執行 manager",managerBody:"在負責看畫面的電腦上執行 LiveDesk manager。它會同時啟動 UI 與本機伺服器,並開啟 http://127.0.0.1:5179。",managerPoints:["指令是 npx -y livedesk。","Screen Wall/API 使用 5179,client 連線使用 5197。","若舊的 LiveDesk 程序占用連接埠,預設會清理後重新啟動。"],clientTitle:"2. 連接 workstation",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","livedesk.pages.dev 的 Chrome Local Network Access 不再是預設執行路徑。npm manager app 才是真正伺服器。"],platformTitle:"4. 目前平台狀態",platformBody:"Windows 已確認可傳輸即時畫面。macOS 與 Linux 也沿用相同 npm 指令路徑擴充支援。",platformPoints:["Windows: 已確認可用。","macOS: 畫面擷取與控制需要 Screen Recording/Accessibility 權限。","Linux: 已加入 linux-x64 runtime、grim/gnome-screenshot/import/scrot capture、xdotool input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"同一 LAN 通常不需要路由器轉發。不同地點連線時,client 必須能到達 manager 的 client 連線埠。",firewallPoints:["client 連線埠是 TCP 5197。","client 電腦通常只需要對外連線。","跨網路時,請在 manager 防火牆允許 TCP 5197 inbound,並從路由器轉發到 manager PC。","5179 是 manager UI 連接埠,只在需要遠端瀏覽器直接打開 Wall 時才考慮公開。","優先使用 VPN、Tailscale、ZeroTier 或固定 IP allowlist。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 workstation",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:ra({languageName:"Español",languageLabel:"Idioma del documento",eyebrow:"LiveDesk Manual",title:"Abre un Screen Wall local con un comando",intro:"LiveDesk es una consola npm-first para vigilar muchas estaciones, cajas de IA, Mac mini y equipos de desarrollo desde un PC manager.",managerTitle:"1. Ejecuta el manager",managerBody:"Ejecuta LiveDesk en el equipo que verá las pantallas. El manager inicia la UI y el servidor local juntos y abre http://127.0.0.1:5179.",managerPoints:["El comando es npx -y livedesk.","El manager usa 5179 para Screen Wall/API y 5197 para conexiones client.","Si un proceso antiguo ocupa los puertos, el arranque lo limpia por defecto."],clientTitle:"2. Conecta una workstation",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en livedesk.pages.dev ya no es el flujo principal. La app npm manager es el servidor real."],platformTitle:"4. Estado de plataformas",platformBody:"Windows ya fue verificado con transferencia de pantalla. macOS y Linux siguen el mismo camino npm.",platformPoints:["Windows: verificado.","macOS: captura y control requieren permisos Screen Recording/Accessibility.","Linux: agregado linux-x64 runtime, captura grim/gnome-screenshot/import/scrot y entrada xdotool. Audio aún desactivado."],firewallTitle:"Firewall y sedes remotas",firewallBody:"En la misma LAN normalmente no hace falta port forwarding. Para otra red, los clients deben llegar al puerto client del manager.",firewallPoints:["Puerto de conexión client: TCP 5197.","Los equipos client normalmente solo necesitan salida.","Para redes remotas, permite TCP 5197 inbound en el manager y reenvía TCP 5197 al PC manager.","El puerto 5179 es para la UI del manager; expónlo solo si un navegador remoto debe abrir el Wall.","Prefiere VPN, Tailscale, ZeroTier o allowlist de IP fijas."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:ra({languageName:"Français",languageLabel:"Langue du document",eyebrow:"LiveDesk Manual",title:"Ouvrir un Screen Wall local en une commande",intro:"LiveDesk est un deck npm-first pour surveiller plusieurs postes, machines IA, Mac mini et machines dev depuis un PC manager.",managerTitle:"1. Lancer le manager",managerBody:"Lancez LiveDesk sur l’ordinateur qui observe les écrans. Le manager démarre l’UI et le serveur local, puis ouvre http://127.0.0.1:5179.",managerPoints:["La commande est npx -y livedesk.","Le manager utilise 5179 pour Screen Wall/API et 5197 pour les connexions client.","Si un ancien processus utilise les ports, le démarrage le nettoie par défaut."],clientTitle:"2. Connecter une workstation",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur livedesk.pages.dev n’est plus le chemin par défaut. L’app npm manager est le vrai serveur."],platformTitle:"4. État des plateformes",platformBody:"Windows est vérifié avec transfert d’écran live. macOS et Linux suivent le même chemin npm.",platformPoints:["Windows: vérifié.","macOS: capture et contrôle nécessitent Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot et entrée xdotool ajoutés. Audio désactivé."],firewallTitle:"Firewall et sites distants",firewallBody:"Sur le même LAN, le port forwarding est rarement nécessaire. Depuis un autre réseau, les clients doivent atteindre le port client du manager.",firewallPoints:["Port de connexion client: TCP 5197.","Les machines client ont normalement seulement besoin de sortie réseau.","Pour un réseau distant, autorisez TCP 5197 entrant sur le manager et redirigez TCP 5197 vers le PC manager.","Le port 5179 sert à l’UI manager; exposez-le seulement si un navigateur distant doit ouvrir le Wall.","Préférez VPN, Tailscale, ZeroTier ou allowlist IP fixes."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter workstation",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:ra({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Workstations, AI-Boxen, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte LiveDesk auf dem Computer, der die Screens sieht. Der Manager startet UI und lokalen Server zusammen und öffnet http://127.0.0.1:5179.",managerPoints:["Der Befehl ist npx -y livedesk.","Der Manager nutzt 5179 für Screen Wall/API und 5197 für Client-Verbindungen.","Wenn alte LiveDesk-Prozesse Ports belegen, werden sie beim Start standardmäßig bereinigt."],clientTitle:"2. Workstation verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf livedesk.pages.dev ist nicht mehr der Standardpfad. Die npm Manager App ist der echte Server."],platformTitle:"4. Plattformstatus",platformBody:"Windows wurde mit Live-Screen-Transfer geprüft. macOS und Linux folgen demselben npm-Pfad.",platformPoints:["Windows: verifiziert.","macOS: Capture und Control brauchen Screen Recording/Accessibility Rechte.","Linux: linux-x64 Runtime, grim/gnome-screenshot/import/scrot Capture und xdotool Input Backend sind ergänzt. Audio ist deaktiviert."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"Im gleichen LAN ist Router-Forwarding meist unnötig. Aus anderen Netzwerken müssen Clients den Client-Port des Managers erreichen.",firewallPoints:["Client-Verbindungsport: TCP 5197.","Client-Rechner brauchen normalerweise nur ausgehenden Zugriff.","Für entfernte Netzwerke TCP 5197 inbound am Manager erlauben und vom Router zum Manager-PC forwarden.","Port 5179 ist für die Manager-UI; nur öffnen, wenn ein Remote-Browser die Wall direkt öffnen muss.","VPN, Tailscale, ZeroTier oder feste IP-Allowlists bevorzugen."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Workstation verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":ra({languageName:"Português",languageLabel:"Idioma do documento",eyebrow:"LiveDesk Manual",title:"Abra um Screen Wall local com um comando",intro:"LiveDesk é um deck npm-first para monitorar várias estações, caixas de IA, Mac minis e máquinas dev a partir de um PC manager.",managerTitle:"1. Execute o manager",managerBody:"Rode LiveDesk no computador que verá as telas. O manager inicia a UI e o servidor local juntos e abre http://127.0.0.1:5179.",managerPoints:["O comando é npx -y livedesk.","O manager usa 5179 para Screen Wall/API e 5197 para conexões client.","Se um processo antigo ocupa as portas, a inicialização limpa por padrão."],clientTitle:"2. Conecte uma workstation",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em livedesk.pages.dev não é mais o caminho padrão. O app npm manager é o servidor real."],platformTitle:"4. Estado das plataformas",platformBody:"Windows foi verificado com transferência de tela. macOS e Linux seguem o mesmo caminho npm.",platformPoints:["Windows: verificado.","macOS: captura e controle precisam de permissões Screen Recording/Accessibility.","Linux: runtime linux-x64, captura grim/gnome-screenshot/import/scrot e entrada xdotool adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"Na mesma LAN normalmente não é preciso port forwarding. Em outra rede, clients precisam alcançar a porta client do manager.",firewallPoints:["Porta client: TCP 5197.","Máquinas client normalmente só precisam de saída.","Para redes remotas, permita TCP 5197 inbound no manager e encaminhe TCP 5197 para o PC manager.","A porta 5179 é para a UI do manager; exponha apenas se um navegador remoto precisar abrir o Wall.","Prefira VPN, Tailscale, ZeroTier ou allowlist de IP fixo."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar workstation",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:ra({languageName:"Italiano",languageLabel:"Lingua documento",eyebrow:"LiveDesk Manual",title:"Apri uno Screen Wall locale con un comando",intro:"LiveDesk è un deck npm-first per monitorare workstation, box AI, Mac mini e macchine dev da un solo PC manager.",managerTitle:"1. Avvia il manager",managerBody:"Esegui LiveDesk sul computer che guarderà gli schermi. Il manager avvia UI e server locale e apre http://127.0.0.1:5179.",managerPoints:["Il comando è npx -y livedesk.","Il manager usa 5179 per Screen Wall/API e 5197 per connessioni client.","Se vecchi processi occupano le porte, l’avvio le pulisce di default."],clientTitle:"2. Connetti una workstation",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su livedesk.pages.dev non è più il percorso principale. L’app npm manager è il server reale."],platformTitle:"4. Stato piattaforme",platformBody:"Windows è verificato con trasferimento schermo live. macOS e Linux seguono lo stesso percorso npm.",platformPoints:["Windows: verificato.","macOS: capture e control richiedono permessi Screen Recording/Accessibility.","Linux: aggiunti runtime linux-x64, capture grim/gnome-screenshot/import/scrot e input xdotool. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"Nella stessa LAN di solito non serve port forwarding. Da altre reti, i client devono raggiungere la porta client del manager.",firewallPoints:["Porta client: TCP 5197.","I client normalmente richiedono solo uscita.","Per reti remote, abilita TCP 5197 inbound sul manager e inoltra TCP 5197 al PC manager.","La porta 5179 è per la UI manager; esponila solo se un browser remoto deve aprire il Wall.","Preferisci VPN, Tailscale, ZeroTier o IP allowlist."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti workstation",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:ra({languageName:"Bahasa Indonesia",languageLabel:"Bahasa dokumen",eyebrow:"LiveDesk Manual",title:"Buka Screen Wall lokal dengan satu perintah",intro:"LiveDesk adalah deck npm-first untuk memantau banyak workstation, AI box, Mac mini, dan mesin dev dari satu PC manager.",managerTitle:"1. Jalankan manager",managerBody:"Jalankan LiveDesk di komputer yang melihat layar. Manager membuka UI dan server lokal bersama, lalu membuka http://127.0.0.1:5179.",managerPoints:["Perintahnya npx -y livedesk.","Manager memakai 5179 untuk Screen Wall/API dan 5197 untuk koneksi client.","Jika proses lama memakai port itu, startup membersihkannya secara default."],clientTitle:"2. Hubungkan workstation",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di livedesk.pages.dev bukan jalur utama lagi. App npm manager adalah server sebenarnya."],platformTitle:"4. Status platform",platformBody:"Windows sudah diverifikasi dengan live screen transfer. macOS dan Linux mengikuti jalur npm yang sama.",platformPoints:["Windows: terverifikasi.","macOS: capture dan control perlu izin Screen Recording/Accessibility.","Linux: runtime linux-x64, capture grim/gnome-screenshot/import/scrot, dan input xdotool sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"Di LAN yang sama biasanya tidak perlu port forwarding. Dari jaringan lain, client harus mencapai port client manager.",firewallPoints:["Port client: TCP 5197.","Mesin client biasanya hanya perlu akses keluar.","Untuk jaringan luar, izinkan TCP 5197 inbound di manager dan forward TCP 5197 ke PC manager.","Port 5179 untuk UI manager; buka hanya jika browser luar harus membuka Wall.","Utamakan VPN, Tailscale, ZeroTier, atau IP allowlist."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan workstation",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:ra({languageName:"Tiếng Việt",languageLabel:"Ngôn ngữ tài liệu",eyebrow:"LiveDesk Manual",title:"Mở Screen Wall cục bộ bằng một lệnh",intro:"LiveDesk là deck npm-first để giám sát nhiều workstation, máy AI, Mac mini và máy dev từ một PC manager.",managerTitle:"1. Chạy manager",managerBody:"Chạy LiveDesk trên máy dùng để xem màn hình. Manager khởi động UI và server cục bộ cùng lúc, rồi mở http://127.0.0.1:5179.",managerPoints:["Lệnh là npx -y livedesk.","Manager dùng 5179 cho Screen Wall/API và 5197 cho kết nối client.","Nếu tiến trình cũ giữ port, startup mặc định sẽ dọn và khởi động lại."],clientTitle:"2. Kết nối workstation",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên livedesk.pages.dev không còn là đường chạy chính. App npm manager mới là server thật."],platformTitle:"4. Trạng thái nền tảng",platformBody:"Windows đã được kiểm chứng với truyền màn hình live. macOS và Linux đi theo cùng đường npm.",platformPoints:["Windows: đã kiểm chứng.","macOS: capture và control cần quyền Screen Recording/Accessibility.","Linux: đã thêm runtime linux-x64, capture grim/gnome-screenshot/import/scrot và input xdotool. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"Trong cùng LAN thường không cần port forwarding. Từ mạng khác, client phải truy cập được port client của manager.",firewallPoints:["Port client: TCP 5197.","Máy client thường chỉ cần kết nối outbound.","Với mạng ngoài, cho phép TCP 5197 inbound trên manager và forward TCP 5197 tới PC manager.","Port 5179 dành cho UI manager; chỉ mở nếu trình duyệt từ xa cần mở Wall trực tiếp.","Ưu tiên VPN, Tailscale, ZeroTier hoặc allowlist IP cố định."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối workstation",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:ra({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู workstation, กล่อง AI, Mac mini และเครื่อง dev หลายเครื่องจาก manager PC เครื่องเดียว",managerTitle:"1. รัน manager",managerBody:"รัน LiveDesk บนเครื่องที่ใช้ดูหน้าจอ Manager จะเปิด UI และ local server พร้อมกัน แล้วเปิด http://127.0.0.1:5179",managerPoints:["คำสั่งคือ npx -y livedesk","Manager ใช้ 5179 สำหรับ Screen Wall/API และ 5197 สำหรับ client connection","ถ้า process เก่ายังใช้ port อยู่ startup จะล้างให้โดย default"],clientTitle:"2. เชื่อม workstation",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน livedesk.pages.dev ไม่ใช่ runtime หลักแล้ว app npm manager คือ server จริง"],platformTitle:"4. สถานะ platform",platformBody:"Windows ตรวจสอบแล้วว่าส่งภาพ live ได้ macOS และ Linux ใช้เส้นทาง npm เดียวกัน",platformPoints:["Windows: verified","macOS: capture/control ต้องใช้สิทธิ์ Screen Recording/Accessibility","Linux: เพิ่ม linux-x64 runtime, grim/gnome-screenshot/import/scrot capture และ xdotool input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"ใน LAN เดียวกันปกติไม่ต้อง port forwarding ถ้าอยู่คนละ network client ต้องเข้าถึง client port ของ manager ได้",firewallPoints:["Client port คือ TCP 5197","เครื่อง client ปกติต้องการ outbound เท่านั้น","ถ้าอยู่นอก network ให้เปิด TCP 5197 inbound ที่ manager และ forward TCP 5197 ไปยัง manager PC","Port 5179 เป็น UI ของ manager เปิดเฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง","ควรใช้ VPN, Tailscale, ZeroTier หรือ IP allowlist ก่อนเปิดสู่ public internet"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม workstation",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:ra({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई workstation, AI box, Mac mini और dev machines देखे जा सकते हैं।",managerTitle:"1. manager चलाएं",managerBody:"जिस computer से screens देखनी हैं उस पर LiveDesk manager चलाएं। यह UI और local server साथ में शुरू करता है और http://127.0.0.1:5179 खोलता है।",managerPoints:["कमांड है npx -y livedesk।","Manager Screen Wall/API के लिए 5179 और client connections के लिए 5197 इस्तेमाल करता है।","अगर पुराने LiveDesk ports बचे हों तो startup default रूप से साफ करता है।"],clientTitle:"2. workstation जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","livedesk.pages.dev का Chrome Local Network Access अब default runtime नहीं है। npm manager app ही real server है।"],platformTitle:"4. Platform status",platformBody:"Windows live screen transfer के साथ verified है। macOS और Linux भी इसी npm path पर आगे बढ़ रहे हैं।",platformPoints:["Windows: verified.","macOS: capture/control के लिए Screen Recording/Accessibility permissions चाहिए।","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture और xdotool input backend जोड़े गए हैं। Audio अभी disabled है।"],firewallTitle:"Firewall और remote locations",firewallBody:"Same LAN में आम तौर पर router forwarding जरूरी नहीं। दूसरे network से clients को manager client port तक पहुंचना होगा।",firewallPoints:["Client connection port: TCP 5197.","Client machines को आम तौर पर सिर्फ outbound access चाहिए।","Remote network के लिए manager firewall में TCP 5197 inbound allow करें और router से TCP 5197 manager PC पर forward करें।","5179 manager UI port है; इसे तभी expose करें जब remote browser को Wall खोलना हो।","Public internet से पहले VPN, Tailscale, ZeroTier या fixed IP allowlist बेहतर है।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:ra({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة workstations وأجهزة AI وMac mini وأجهزة تطوير من كمبيوتر manager واحد.",managerTitle:"1. شغل manager",managerBody:"شغل LiveDesk على الكمبيوتر الذي سيعرض الشاشات. يبدأ manager الواجهة والخادم المحلي معا ويفتح http://127.0.0.1:5179.",managerPoints:["الأمر هو npx -y livedesk.","يستخدم manager المنفذ 5179 للواجهة/API والمنفذ 5197 لاتصالات client.","إذا بقيت عملية LiveDesk قديمة على المنافذ، يتم تنظيفها افتراضيا عند التشغيل."],clientTitle:"2. وصل workstation",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على livedesk.pages.dev لم يعد مسار التشغيل الافتراضي. تطبيق npm manager هو الخادم الحقيقي."],platformTitle:"4. حالة المنصات",platformBody:"Windows تم التحقق منه مع نقل شاشة live. macOS وLinux يتبعان نفس مسار npm.",platformPoints:["Windows: تم التحقق.","macOS: capture/control يحتاجان أذونات Screen Recording/Accessibility.","Linux: تمت إضافة linux-x64 runtime وgrim/gnome-screenshot/import/scrot capture وxdotool input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"داخل نفس LAN غالبا لا تحتاج port forwarding. من شبكة أخرى يجب أن يصل client إلى منفذ manager client.",firewallPoints:["منفذ client: TCP 5197.","أجهزة client تحتاج عادة اتصال outbound فقط.","للشبكات البعيدة، اسمح TCP 5197 inbound على manager ووجه TCP 5197 من router إلى manager PC.","المنفذ 5179 مخصص لواجهة manager؛ اكشفه فقط إذا كان متصفح بعيد يحتاج فتح Wall مباشرة.","يفضل VPN أو Tailscale أو ZeroTier أو fixed IP allowlist بدل التعريض العام."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect workstation",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:ra({languageName:"Türkçe",languageLabel:"Belge dili",eyebrow:"LiveDesk Manual",title:"Yerel Screen Wall tek komutla açılsın",intro:"LiveDesk, tek bir manager PC üzerinden birçok workstation, AI box, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda LiveDesk manager çalıştır. Manager UI ve local server birlikte başlar ve http://127.0.0.1:5179 açılır.",managerPoints:["Komut: npx -y livedesk.","Manager Screen Wall/API için 5179, client bağlantıları için 5197 kullanır.","Eski LiveDesk process portları tutuyorsa başlangıç varsayılan olarak temizler."],clientTitle:"2. Workstation bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","livedesk.pages.dev üzerindeki Chrome Local Network Access artık default runtime yolu değil. Gerçek server npm manager app."],platformTitle:"4. Platform durumu",platformBody:"Windows live screen transfer ile doğrulandı. macOS ve Linux aynı npm yolunu takip ediyor.",platformPoints:["Windows: doğrulandı.","macOS: capture/control için Screen Recording/Accessibility izinleri gerekir.","Linux: linux-x64 runtime, grim/gnome-screenshot/import/scrot capture ve xdotool input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"Aynı LAN içinde genelde router forwarding gerekmez. Başka ağdan clients manager client portuna ulaşabilmelidir.",firewallPoints:["Client port: TCP 5197.","Client makineler normalde sadece outbound erişim ister.","Uzak ağ için manager firewall üzerinde TCP 5197 inbound aç ve routerdan TCP 5197yi manager PCye forward et.","5179 manager UI portudur; sadece uzak browser Wall açacaksa expose et.","Public internet yerine VPN, Tailscale, ZeroTier veya sabit IP allowlist tercih et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Workstation bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},MT=Object.entries(Ro).map(([n,a])=>({id:n,label:a.languageName}));function TT(){if(typeof navigator>"u")return"en";const n=navigator.languages?.length?navigator.languages:[navigator.language];for(const a of n){const r=a.toLowerCase();if(Ro[a])return a;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const l=r.split("-")[0];if(Ro[l])return l}return"en"}function Px({index:n}){const a=n+1;return s.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${a}`,children:s.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[s.jsx("span",{className:"slot-grid","aria-hidden":"true"}),s.jsxs("span",{className:"empty-screen",children:[s.jsx(an,{size:24}),s.jsxs("strong",{children:["Slot ",String(a).padStart(3,"0")]})]})]})})}function ET(n){if(!n)return!1;const a=String(n.platform||"").trim().toLowerCase();return zi(a)&&n.capabilities?.screenRecordingPermission===!1}function zi(n){const a=String(n||"").trim().toLowerCase();return a==="macos"||a==="darwin"||a==="mac"||a==="macosx"}function $x(n){if(!n)return!1;const a=String(n.capabilities?.liveCaptureConcurrency||"").trim().toLowerCase();return a==="exclusive"?!0:a==="parallel"?!1:zi(n.platform)}function Sh({device:n,frame:a,selected:r,controlEnabled:l,showStatus:c,monitorIndex:d,monitorCount:m,onSelect:p,onFocusDevice:g,onOpenControl:v,onCycleMonitor:w,onCanvasReady:x,sendInput:b,updateIndicator:C,presentationReady:j,showPresentationSpinner:A=!1}){const N=u.useRef(null),k=u.useRef(null),T=u.useRef(0),R=u.useRef(null),U=CT(n),O=["cpu","gpu","memory","vram"].map($=>U.metrics.find(ue=>ue.id===$)).filter($=>!!$),Y=Ea(d,m),_=m>1,D=j??!!a,ne=ET(n)&&!D,G=A&&n.connected&&!D&&!ne,te=rT(n,a,Y),B=te>=Td?100:te/Td*100,xe=te>=Td?Td/te*100:100,se={"--screen-aspect":te.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,B)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,xe)).toFixed(3)}%`},K=u.useCallback($=>{N.current=$,x(n.deviceId,$)},[n.deviceId,x]),I=$=>{const ue=$.currentTarget.getBoundingClientRect();return Aj($.clientX,$.clientY,ue)},Q=$=>({shiftKey:$.shiftKey,ctrlKey:$.ctrlKey,altKey:$.altKey,metaKey:$.metaKey}),q=u.useCallback(()=>{R.current!==null&&(window.cancelAnimationFrame(R.current),R.current=null)},[]),V=u.useCallback(()=>{const $=k.current;if(!$)return;k.current=null;const ue=Number($.input.normalizedX),he=Number($.input.normalizedY);if(!Number.isFinite(ue)||!Number.isFinite(he))return;b(n.deviceId,{...$.input,normalizedX:ue,normalizedY:he})&&(T.current=performance.now())},[n.deviceId,b]),ce=u.useCallback(()=>{R.current===null&&(R.current=window.requestAnimationFrame(()=>{R.current=null,V()}))},[V]);u.useEffect(()=>()=>{q(),k.current=null},[q]);const be=($,ue)=>{if(!l)return;const he={type:ue,monitorIndex:Y,...I($),button:yT($.button),...Q($)};if(ue==="pointermove"){const ve=performance.now();k.current={input:he},ve-T.current>=RM&&(q(),V()),ce();return}k.current&&(q(),V()),b(n.deviceId,he)},X=u.useCallback($=>{const ue=document.activeElement;ue instanceof HTMLElement&&$.contains(ue)&&ue.classList.contains("monitor-cycle-button")&&ue.blur()},[]);return s.jsx("article",{className:`device-tile ${r?"selected":""} ${n.connected?"online":"offline"}`,"data-live-device-id":n.deviceId,style:se,children:s.jsxs("div",{className:`tile-screen ${D?"has-frame":"is-empty"}`,role:"button",tabIndex:l?-1:0,"aria-pressed":r,onClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||p()},onKeyDown:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||l||($.key==="Enter"||$.key===" ")&&($.preventDefault(),p())},onDoubleClick:$=>{$.target instanceof Element&&$.target.closest(".monitor-cycle")||($.preventDefault(),v())},onPointerLeave:$=>X($.currentTarget),children:[s.jsx("span",{className:`screen-content ${D?"has-frame":"is-empty"}`,children:s.jsx("canvas",{ref:K,className:`remote-canvas ${D?"has-frame":"is-empty"}`,tabIndex:l?0:-1,onPointerDown:$=>{l&&($.preventDefault(),$.stopPropagation(),g(),$.currentTarget.focus(),$.currentTarget.setPointerCapture($.pointerId),be($,"pointerdown"))},onPointerMove:$=>{l&&$.preventDefault(),be($,"pointermove")},onPointerLeave:$=>{l&&(be($,"pointermove"),q(),V())},onPointerUp:$=>{l&&($.preventDefault(),$.stopPropagation(),be($,"pointerup"),$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId))},onPointerCancel:$=>{$.currentTarget.hasPointerCapture($.pointerId)&&$.currentTarget.releasePointerCapture($.pointerId)},onWheel:$=>{l&&($.preventDefault(),b(n.deviceId,{type:"wheel",monitorIndex:Y,...I($),deltaX:$.deltaX,deltaY:$.deltaY,...Q($)}))},onKeyDown:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keydown",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:$.repeat,...Q($)}))},onKeyUp:$=>{l&&($.preventDefault(),$.stopPropagation(),b(n.deviceId,{type:"keyup",monitorIndex:Y,key:$.key,code:$.code,keyCode:$.keyCode||$.which||0,location:$.location,text:$.key.length===1?$.key:"",repeat:!1,...Q($)}))},onContextMenu:$=>l&&$.preventDefault()})}),!D&&s.jsx("span",{className:"empty-screen",children:s.jsx(an,{size:26})}),G&&s.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[s.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),s.jsx("strong",{children:"Preparing video"})]}),ne&&s.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[s.jsx(Bt,{size:24,"aria-hidden":"true"}),s.jsx("strong",{children:"Screen Recording permission required"}),s.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),C&&s.jsxs("span",{className:`wall-update-status state-${C.state}`,role:"status","aria-live":"polite",title:C.error||C.label,children:[C.state==="updated"?s.jsx(Fn,{size:20,"aria-hidden":"true"}):C.state==="failed"?s.jsx(Ya,{size:22,"aria-hidden":"true"}):C.state==="offline"?s.jsx(Dl,{size:22,"aria-hidden":"true"}):s.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),s.jsx("strong",{children:C.label}),C.error?s.jsx("small",{children:C.error}):null]}),c&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`tile-health-pill state-${U.state}`,children:U.label}),s.jsx("span",{className:"tile-metrics","aria-label":`${fs(n)} status`,children:O.map($=>s.jsxs("span",{className:`tile-metric state-${$.state}`,children:[s.jsx("b",{children:$.label}),s.jsx("em",{children:$.value}),$.ratio!==void 0&&s.jsx("i",{style:{width:`${Math.round($.ratio*100)}%`}})]},$.id))})]}),_&&s.jsxs("span",{className:"monitor-cycle","aria-label":`${fs(n)} display ${Y+1} of ${m}`,onPointerDown:$=>$.stopPropagation(),onClick:$=>$.stopPropagation(),onDoubleClick:$=>$.stopPropagation(),children:[s.jsx("button",{className:"monitor-cycle-button previous",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(-1),$.currentTarget.blur()},title:"Previous display",type:"button",children:s.jsx(Jx,{size:18})}),s.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",Y+1,"/",m]}),s.jsx("button",{className:"monitor-cycle-button next",onClick:$=>{$.preventDefault(),$.stopPropagation(),w(1),$.currentTarget.blur()},title:"Next display",type:"button",children:s.jsx(Xh,{size:18})})]}),r&&s.jsx("span",{className:"device-selection-check","aria-hidden":"true",children:s.jsx(Ii,{size:23,strokeWidth:3.5})})]})})}function RT({visible:n}){return u.useEffect(()=>{if(!n||!fh)return;if(!document.getElementById(Sx)){const r=document.createElement("script");r.id=Sx,r.async=!0,r.crossOrigin="anonymous",r.src=`https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=${encodeURIComponent($h)}`,document.head.appendChild(r)}const a=window.setTimeout(()=>{try{window.adsbygoogle=window.adsbygoogle||[],window.adsbygoogle.push({})}catch{}},120);return()=>window.clearTimeout(a)},[n]),n?s.jsxs("aside",{className:`free-ad-banner ${fh?"adsense-ready":"house-ad"}`,"aria-label":"Advertisement",children:[s.jsx("span",{className:"ad-label",children:"Advertisement"}),fh?s.jsx("ins",{className:"adsbygoogle livedesk-ad-unit",style:{display:"block"},"data-ad-client":$h,"data-ad-slot":pw,"data-ad-format":"auto","data-full-width-responsive":"true"}):s.jsxs("div",{className:"house-ad-copy",children:[s.jsx("strong",{children:"Sponsored placement"}),s.jsx("span",{children:"Local AI gear, mini PCs, GPUs, NAS, and developer tools."})]})]}):null}function DT(){const{session:n,loading:a}=sj(),{target:r,error:l,refresh:c}=rj(n),d=u.useMemo(()=>{if(!r?.active)return null;const y=r.expires_at?Date.parse(r.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(y)&&y<=Date.now()?null:r},[r]),m=u.useMemo(()=>yy(d),[d]),p=u.useMemo(()=>m.length>0?[...new Set([...m,Cn])]:[Cn],[m]),[g,v]=u.useState(nT),w=u.useMemo(()=>p.some(y=>!!Ic(y)),[p]),x=!w||g,{status:b,devices:C,error:j,refresh:A,hubBaseUrl:N}=ij(p,x),{entitlement:k,licensed:T,loading:R,error:U,refresh:O}=lj(n),[Y,_]=u.useState([]),[D,ne]=u.useState(""),[G,te]=u.useState(""),[B,xe]=u.useState(""),[se,K]=u.useState(""),[I,Q]=u.useState(""),[q,V]=u.useState("idle"),[ce,be]=u.useState(!1),[X,$]=u.useState(null),[ue,he]=u.useState(""),ve=u.useRef("");ve.current=se;const[Se,_e]=u.useState(!1),[re,Z]=u.useState(!1),ze=u.useRef(""),Le=u.useRef(new Map),ae=u.useRef(0),[fe,Ae]=u.useState(""),[Te,Be]=u.useState(""),[Ve,Je]=u.useState(null);u.useEffect(()=>{fe==="auth"&&n?.access_token&&Ae("")},[fe,n?.access_token]);const[Et,je]=u.useState(""),[We,it]=u.useState(null),ot=u.useRef(null),gn=u.useRef(0),Kt=u.useCallback((y,M,L)=>{const F=String(y||"").trim();if(je(F),ot.current!==null&&(window.clearTimeout(ot.current),ot.current=null),!F){it(null);return}const z=++gn.current;if(it({id:z,message:F,tone:M}),!L)return;const pe=window.setTimeout(()=>{it(de=>de?.id===z?null:de),ot.current===pe&&(ot.current=null)},5e3);ot.current=pe},[]),Ie=u.useCallback((y,M="info")=>{Kt(y,M,!0)},[Kt]),ct=u.useCallback(y=>{Kt(y,"progress",!1)},[Kt]);u.useEffect(()=>()=>{ot.current!==null&&window.clearTimeout(ot.current)},[]);const[_t,Ft]=u.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");u.useEffect(()=>{const y=()=>{Ft(window.location.pathname.startsWith("/support")?"support":M=>M==="support"?"wall":M)};return window.addEventListener("popstate",y),()=>window.removeEventListener("popstate",y)},[]);const[ge,Oe]=u.useState("large"),[Fe,ke]=u.useState(TT),[st,gt]=u.useState(!1),[Re,jn]=u.useState(!1),[Ls,nt]=u.useState(!1),[zt,zn]=u.useState(tT),[He,ya]=u.useState(cT),[dt,Hi]=u.useState(dT),[Qt,ps]=u.useState(lT),[bt,qn]=u.useState(null),[_s,H]=u.useState([]),[Pe,vt]=u.useState(He.fps),[sn,Qa]=u.useState(""),[Br,Xa]=u.useState(0),[ee,Ne]=u.useState(0),[qe,rt]=u.useState(()=>new Set),Nt=u.useRef(new Map),Mt=u.useRef(new Map),Qe=u.useRef(new Map),ut=u.useRef(new Map),kn=u.useRef(new Map),Wt=u.useRef(new Set),An=u.useRef(new Map),St=u.useRef(""),rn=u.useRef(""),Pt=u.useRef(null),xa=u.useRef(null),ca=u.useRef(new Map),cn=u.useRef(null),vn=u.useRef(0),Fr=u.useRef(new Map),[zs,Pr]=u.useState({}),zo=u.useRef(new Map),[Bi,Il]=u.useState({}),[Za,Zt]=u.useState(!1),Ol=u.useRef(null),Ja=u.useRef(null),Xn=u.useRef(0),Is=u.useRef(""),Os=u.useRef(new Map),$r=u.useRef(new Map),Gn=u.useRef(performance.now()),ai=u.useRef(new Map),si=u.useRef(new Map),Hs=u.useRef(new Map),Bs=u.useRef(new Map),Fi=u.useRef(0),Ur=u.useRef(0),gs=u.useRef(0),Hl=u.useRef(0),Bl=u.useRef(0),Io=u.useRef(new Map),es=u.useRef(new Map),[ii,Fs]=u.useState(null),[Fl,_a]=u.useState(!1),[Kc,Oo]=u.useState([]),[za,Pi]=u.useState("all"),[ri,qr]=u.useState([]),[cf,Pl]=u.useState(!1),[Ps,Ho]=u.useState(!0),$i=u.useRef(null),vs=u.useRef(null),Bo=u.useRef(null),$l=u.useRef(null),Qc=u.useRef(!1),Ui=u.useRef(!1),qi=u.useRef(!1),Gi=u.useRef(0),ln=u.useRef(0),ts=_t==="settings",Gr=_t==="pricing",Vi=_t==="doc",Xc=_t==="support",li=_t==="share-files",Vr=_t==="agents",Wi=!ts&&!Gr&&!Vi&&!Xc&&!li&&!Vr,at=_t==="control",ft=He.frameMode==="mode4-h264-atlas",ba=I||dt.frameMode,Yi=ba!=="mode3-h264-hw"?Math.min(30,dt.fps):dt.fps,$s=ba!=="mode3-h264-hw"?{maxWidth:Math.min(1920,dt.maxWidth),maxHeight:Math.min(1080,dt.maxHeight)}:{maxWidth:dt.maxWidth,maxHeight:dt.maxHeight};u.useEffect(()=>{if(b?.started){if(!n?.access_token){Ge("/api/remote/license",{method:"DELETE"},N).catch(()=>{});return}Ge("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},N).catch(y=>{console.warn("[LiveDesk] Hub license sync failed",y)})}},[k?.updated_at,N,n?.access_token,b?.started]),u.useEffect(()=>{!n?.access_token||!b?.started||b.runtimeRole!=="hub"||!b.deviceId||(async()=>{try{const{data:y,error:M}=await pt.rpc("register_livedesk_device",{p_device_id:b.deviceId,p_device_name:b.deviceName||b.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:b.managerVersion||b.managerPackage||""}),L=Array.isArray(y)?y[0]:y;(M||L?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",M||L?.reason||"unknown-error")}catch(y){console.warn("[LiveDesk] Hub device role registration failed",y)}})()},[n?.access_token,b?.deviceId,b?.deviceName,b?.managerPackage,b?.managerVersion,b?.runtimeRole,b?.started]),u.useEffect(()=>{!n?.access_token||!n.refresh_token||!b?.started||b.runtimeRole!=="hub"||qi.current||(qi.current=!0,Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},N||Cn).then(y=>{y.hostTarget?.ok===!1&&console.warn("[LiveDesk] Hub host target publish is waiting for a valid Hub role:",y.hostTarget.error||"unknown-error"),A()}).catch(y=>{console.warn("[LiveDesk] Hub session sync failed:",y)}).finally(()=>{qi.current=!1}))},[N,A,n?.access_token,n?.expires_at,n?.refresh_token,n?.user?.email,n?.user?.id,b?.runtimeRole,b?.started]);const et=u.useMemo(()=>C.filter(y=>y.connected),[C]),Zc=za==="all"?et.length:ri.filter(y=>et.some(M=>M.deviceId===y)).length,uf=u.useMemo(()=>et.reduce((y,M)=>Math.max(y,Fx(M.slotNumber)),0),[et]),Ul=Math.max(MM,et.length,uf),Wr=u.useMemo(()=>{const y=Array(Ul).fill(null),M=[];for(const L of et){const F=Fx(L.slotNumber);F>0&&F<=Ul&&!y[F-1]?y[F-1]=L:M.push(L)}for(const L of M){const F=y.findIndex(z=>!z);F<0?y.push(L):y[F]=L}return y},[et]),Fo=u.useMemo(()=>et.map(y=>y.deviceId),[et]),oi=u.useMemo(()=>new Set(Y),[Y]),ua=u.useMemo(()=>et.filter(y=>oi.has(y.deviceId)),[et,oi]),Ki=u.useMemo(()=>C.find(y=>y.deviceId===D)||ua[0]||null,[C,D,ua]),Vn=u.useMemo(()=>C.find(y=>y.deviceId===G)||null,[G,C]),Us=Vn?Ea(Qt[Vn.deviceId],ga(Vn)):0,Ee=at?Vn:Ki,Jc=u.useMemo(()=>new Set(ri),[ri]),df=u.useMemo(()=>za==="all"?et.map(y=>y.deviceId):et.filter(y=>Jc.has(y.deviceId)).map(y=>y.deviceId),[et,Jc,za]),ff=Ee?Bc(Ee,"control"):!1,ql=zi(Ee?.platform)&&(Ee?.capabilities?.controlPermission===!1||Ee?.capabilities?.accessibilityPermission===!1),Yr=Ee?Bc(Ee,"audio")||Bc(Ee,"remoteAudio"):!1,eu=Array.isArray(Ee?.capabilities?.agentTools)?Ee.capabilities.agentTools.map(String):[],tu=eu.includes("system.power"),nu=eu.includes("command.run"),Yt=T?k?.plan==="pro"?"pro":"ltd":"free",au=Cl[Yt],Gl=au.limit,Qi=u.useMemo(()=>{if(!Number.isFinite(Gl))return new Set(et.map(M=>M.deviceId));const y=Ee?[Ee,...et.filter(M=>M.deviceId!==Ee.deviceId)]:et;return new Set(y.slice(0,Gl).map(M=>M.deviceId))},[Gl,et,Ee]),mf=!Ee||Qi.has(Ee.deviceId),Po=Yt==="free",It=mf,Kr=Yt==="ltd"?`Plus includes up to ${Rc} workstations. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${Ec} workstations. Upgrade to Plus for ${Rc} devices and no ads.`,su=Yt==="free",ns=It&&!!Ee&&ff,$o=It&&!!Ee&&Yr,Qr=u.useMemo(()=>Wr.filter(y=>!!y?.connected).slice(0,mT(ge)).map(y=>y.deviceId),[Wr,ge]),Xr=u.useMemo(()=>ft?Fo:He.visibleOnlyLive?_s.length>0?_s:Qr:Fo,[Qr,ft,_s,He.visibleOnlyLive,Fo]),In=u.useMemo(()=>yh(Xr.filter(y=>Qi.has(y))),[Qi,Xr]),qs=u.useMemo(()=>In.filter(y=>y!==sn),[In,sn]),Vl=u.useMemo(()=>new Map(et.map(y=>[y.deviceId,y.platform])),[et]),as=Nj(ft,In.length),da=u.useMemo(()=>ft?qs.filter(y=>Nc({mode4Enabled:ft,directMode4WallEnabled:as,isMac:zi(Vl.get(y))})==="atlas"):[],[as,ft,Vl,qs]),Zn=u.useMemo(()=>qs.filter(y=>Nc({mode4Enabled:ft,directMode4WallEnabled:as,isMac:zi(Vl.get(y))})==="direct"),[as,ft,Vl,qs]);u.useEffect(()=>{const y=new Set(In);rt(M=>{let L=!1;const F=new Set;for(const z of M)y.has(z)?F.add(z):L=!0;return L?F:M})},[In]);const Zr=u.useMemo(()=>{const y=z=>et.find(pe=>pe.deviceId===z)||null,M=z=>Ea(Qt[z],y(z)?ga(y(z)):0),L=(z,pe=M(z))=>z===B&&(q==="connecting"||q==="active"||q==="warm")?ut.current.get(z)||Mt.current.get(z)||null:ft?ca.current.get(z)||Nt.current.get(z)||null:Nt.current.get(z)||null,F=(z,pe=M(z))=>{const de=y(z);return`${de?fs(de):z} · Monitor ${pe+1}`};return{resolveCurrentTarget(){if(at&&Vn){const $e=Us;return{type:"control",deviceIds:[Vn.deviceId],monitorIndex:$e,label:`${fs(Vn)} · Monitor ${$e+1}`,sourceCanvas:L(Vn.deviceId,$e),signature:`control:${Vn.deviceId}:${$e}:${dt.frameMode}`}}const z=ua.map($e=>$e.deviceId).filter($e=>qs.includes($e)),pe=Ki&&qs.includes(Ki.deviceId)?Ki.deviceId:"",de=z.length>0?z:pe?[pe]:qs,De=z.length===0&&!pe;if(de.length===0)return null;if(de.length===1){const $e=de[0],Xe=M($e);return{type:De?"wall":z.length>1?"selection":"device",deviceIds:de,monitorIndex:Xe,label:De?"Wall":F($e,Xe),sourceCanvas:De?null:L($e,Xe),signature:`${De?"wall":"device"}:${$e}:${Xe}:${ft?"atlas":"direct"}`}}return{type:z.length>1?"selection":"wall",deviceIds:de,label:z.length>1?`${de.length} selected workstations`:"Wall",sourceCanvas:null,signature:`${z.length>1?"selection":"wall"}:${de.join(",")}:${ge}`}},getDeviceCanvas:L,composeWall(z,pe={}){return gM(z.map(de=>{const De=M(de);return{deviceId:de,label:F(de,De),canvas:L(de,De)}}),pe)}}},[et,Vn,B,q,dt.frameMode,Nt,ft,Qt,Us,ua,at,qs,Ki,ge]),Xi=NM({hubUrl:N,sourceRegistry:Zr,onToast:Ie}),Zi=u.useMemo(()=>It&&B&&Qi.has(B)&&(q==="connecting"||q==="active"||q==="warm")?[B]:[],[B,q,It,Qi]),Wl=u.useMemo(()=>yh([...In,...Zi]),[Zi,In]),On=u.useMemo(()=>hT(He,ge),[He,ge]),ci=Mj({mode4Enabled:ft,directMode4WallEnabled:as,adaptiveFps:Pe,directDeviceCount:Zn.length}),Ia=u.useCallback((y,M,L)=>{if(y.width<=0||y.height<=0)return!1;const F=L?Math.min(1,L.maxWidth/y.width,L.maxHeight/y.height):1,z=Math.max(1,Math.round(y.width*F)),pe=Math.max(1,Math.round(y.height*F));(M.width!==z||M.height!==pe)&&(M.width=z,M.height=pe);const de=M.getContext("2d",{alpha:!1});return de?(de.imageSmoothingEnabled=!0,de.imageSmoothingQuality="high",de.drawImage(y,0,0,y.width,y.height,0,0,M.width,M.height),!0):!1},[]),Gs=u.useCallback(y=>{y&&rt(M=>{if(M.has(y))return M;const L=new Set(M);return L.add(y),L})},[]),Jr=u.useCallback(y=>{y&&rt(M=>{if(!M.has(y))return M;const L=new Set(M);return L.delete(y),L})},[]),el=u.useCallback((y,M)=>{if(!M||M.width<=0||M.height<=0)return!1;const L=document.createElement("canvas");return L.width=M.width,L.height=M.height,Ia(M,L)?(Qe.current.set(y,L),Gs(y),!0):!1},[Gs,Ia]),ss=u.useCallback((y,M=!1)=>{if(!Wt.current.has(y))return!1;const L=performance.now(),F=An.current.get(y)||0,z=Math.max(1,Math.min(ei.controlWallReuseMaxFps,Yi)),pe=Yi>z?Math.max(0,1e3/z-2):0;if(!M&&L-F<pe)return!1;const de=ut.current.get(y)||Mt.current.get(y),De=Nt.current.get(y)||ca.current.get(y);return!de||!De||!Ia(de,De,On)?!1:(An.current.set(y,L),Gs(y),!0)},[Yi,On,Gs,Ia]);u.useEffect(()=>{St.current=sn},[sn]);const iu=u.useCallback((y,M)=>{const L=Nt.current.get(y);if(L&&L!==M&&(el(y,L),Ac(L)),M){Nt.current.set(y,M),Qe.current.delete(y),ss(y,!0);return}Nt.current.delete(y),Qe.current.has(y)||Jr(y)},[Jr,ss,el]),hf=u.useCallback((y,M)=>{const L=Mt.current.get(y);if(L&&L!==M&&Ac(L),M){Mt.current.set(y,M);const F=ut.current.get(y)||Qe.current.get(y)||Nt.current.get(y)||ca.current.get(y);F&&Ia(F,M)&&y===G&&Zt(!0);return}Mt.current.delete(y)},[G,Ia]),Yl=u.useCallback((y,M,L)=>{const F=performance.now(),z=Ms(y,L.deviceId);let pe=L;if(y==="control"&&L.visualChanged){const De=mj(L.deviceId),$e=Io.current.get(L.deviceId)||0,Xe=De?F-De.sentAt:Number.POSITIVE_INFINITY;De&&De.inputSeq>$e&&Xe<=Cx&&(pe={...L,inputFeedbackSeq:De.inputSeq,inputFeedbackMs:Math.max(0,Xe),inputFeedbackAt:F},Io.current.set(L.deviceId,De.inputSeq))}$r.current.set(z,F);const de=Fr.current.get(z)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:F,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0};y==="control"&&pe.inputFeedbackMs===void 0&&de.lastInfo?.inputFeedbackMs!==void 0&&de.lastInfo.inputFeedbackAt!==void 0&&F-de.lastInfo.inputFeedbackAt<=Cx&&(pe={...pe,inputFeedbackSeq:de.lastInfo.inputFeedbackSeq,inputFeedbackMs:de.lastInfo.inputFeedbackMs,inputFeedbackAt:de.lastInfo.inputFeedbackAt}),de.totalFrames+=1,de.sampleFrames+=1,Tx(de,F,pe.frameSeq),pe.visualChanged&&(de.totalChangedFrames+=1,de.sampleChangedFrames+=1),de.lastInfo=pe,Fr.current.set(z,de)},[]),Kl=u.useCallback((y,M)=>{Yl("wall",y,M),y.kind==="live"&&Gs(y.deviceId);const L=ce&&B===y.deviceId;St.current!==y.deviceId&&!L&&(Wt.current.delete(y.deviceId),An.current.delete(y.deviceId))},[B,ce,Gs,Yl]),ru=u.useCallback((y,M)=>{Yl("control",y,M),he(pe=>pe&&"");const L=ut.current.get(y.deviceId),F=Mt.current.get(y.deviceId);L&&L.width>0&&L.height>0&&(F&&Ia(L,F),kn.current.set(y.deviceId,{...y,payload:new Uint8Array(0),byteLength:0}),Qe.current.delete(y.deviceId),Wt.current.add(y.deviceId),y.deviceId===B&&(be(!0),V(pe=>pe==="connecting"?"active":pe)),ss(y.deviceId));const z=Ol.current;!z||!PM(z,y)||Zt(!0)},[B,Ia,ss,Yl]);u.useEffect(()=>{const y=window.setInterval(()=>{const M=performance.now(),L={};for(const[F,z]of Fr.current.entries()){const pe=Math.max(1,M-z.sampleStartedAt);L[F]={totalFrames:z.totalFrames,totalChangedFrames:z.totalChangedFrames,framesPerSecond:z.sampleFrames*1e3/pe,changedFramesPerSecond:z.sampleChangedFrames*1e3/pe,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:hh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,decoderInputFps:Math.max(0,(Number(z.lastInfo?.decoderInputCount||0)-z.sampleDecoderInputBase)*1e3/pe),decoderOutputFps:Math.max(0,(Number(z.lastInfo?.decoderOutputCount||0)-z.sampleDecoderOutputBase)*1e3/pe),sampleMs:pe,lastInfo:z.lastInfo},z.sampleDecoderInputBase=Number(z.lastInfo?.decoderInputCount||0),z.sampleDecoderOutputBase=Number(z.lastInfo?.decoderOutputCount||0),z.sampleChangedFrames=0,Mx(z,M)}Pr(L)},1e3);return()=>window.clearInterval(y)},[]);const Nn=u.useCallback((y,M)=>{const L=performance.now(),F=Ms(y,M.deviceId);Os.current.set(F,L),es.current.delete(F),y==="control"&&si.current.delete(F);const z=zo.current.get(F)||{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:[]};if(z.totalFrames+=1,z.sampleFrames+=1,z.sampleBytes+=Math.max(0,Number(M.byteLength||0)),String(M.frameMode||M.mode||M.codec||M.mimeType||"").toLowerCase().includes("h264")){z.sampleH264Frames+=1,Number(M.byteLength||0)<=OM&&(z.sampleTinyFrames+=1);const $e=String(M.contentHash||"");$e&&z.lastContentHash===$e&&(z.sampleRepeatedFrames+=1),z.lastContentHash=$e}const De=Number(M.agentSendGapMs||0);De>0&&De<1e3&&vw(z.sourceSendIntervalsMs,De),z.lastFrame=M,Tx(z,L,M.frameSeq),zo.current.set(F,z)},[]);u.useEffect(()=>{const y=window.setInterval(()=>{const M=performance.now(),L={};for(const[F,z]of zo.current.entries()){const pe=Math.max(1,M-z.sampleStartedAt);L[F]={totalFrames:z.totalFrames,framesPerSecond:z.sampleFrames*1e3/pe,averageIntervalMs:z.intervalCount>0?z.intervalSumMs/z.intervalCount:0,minIntervalMs:Number.isFinite(z.minIntervalMs)?z.minIntervalMs:0,maxIntervalMs:z.maxIntervalMs,p95IntervalMs:hh(z.intervalSamplesMs,.95),intervalCount:z.intervalCount,seqGapCount:z.seqGapCount,maxSeqGap:z.maxSeqGap,averageFrameBytes:z.sampleFrames>0?z.sampleBytes/z.sampleFrames:0,tinyFrameRatio:z.sampleH264Frames>0?z.sampleTinyFrames/z.sampleH264Frames:0,repeatedFrameRatio:z.sampleH264Frames>0?z.sampleRepeatedFrames/z.sampleH264Frames:0,sourceSendAverageMs:z.sourceSendIntervalsMs.length>0?z.sourceSendIntervalsMs.reduce((de,De)=>de+De,0)/z.sourceSendIntervalsMs.length:0,sourceSendP95Ms:hh(z.sourceSendIntervalsMs,.95),sourceSendSampleCount:z.sourceSendIntervalsMs.length,sampleMs:pe,lastFrame:z.lastFrame},z.sampleBytes=0,z.sampleH264Frames=0,z.sampleTinyFrames=0,z.sampleRepeatedFrames=0,z.sourceSendIntervalsMs.length=0,Mx(z,M)}Il(L)},1e3);return()=>window.clearInterval(y)},[]);const Ji=u.useCallback(y=>{Nn("wall",y);const M=Nt.current.get(y.deviceId);if(!M)return;const L=Tj(ft,He.h264DecodeAcceleration);Jm(M,y,()=>Nt.current.get(y.deviceId)!==M,Kl,L.acceleration,L.latencyMode).catch(()=>{})},[Kl,ft,Nn,He.h264DecodeAcceleration]),Uo=u.useCallback(y=>{Nn("control",y);let M=ut.current.get(y.deviceId);M||(M=document.createElement("canvas"),M.setAttribute("aria-hidden","true"),ut.current.set(y.deviceId,M));const L=M,F=ve.current;Jm(L,y,()=>ut.current.get(y.deviceId)!==L,ru,dt.h264DecodeAcceleration,"interactive").catch(z=>{ve.current!==F||ut.current.get(y.deviceId)!==L||B!==y.deviceId||he(z instanceof Error?z.message:String(z||"Control H.264 decode failed"))})},[B,dt.h264DecodeAcceleration,ru,Nn]),lu=u.useCallback(y=>{const M=xa.current;M&&M!==y&&Ac(M),xa.current=y,Fi.current=0,Ur.current=0,gs.current=0,Hl.current=0,Bl.current=0,vn.current=0},[]),ui=u.useCallback(()=>{const y=xa.current,M=cn.current;if(!(!y||!M||y.width<=0||y.height<=0||vn.current!==M.layoutVersion))for(const L of M.tiles){const F=ca.current.get(L.deviceId);if(!F||L.width<=0||L.height<=0)continue;const z=Math.max(1,Math.round(L.width)),pe=Math.max(1,Math.round(L.height)),de=HM,De=BM;(F.width!==de||F.height!==De)&&(F.width=de,F.height=De);const $e=F.getContext("2d",{alpha:!1});if($e){$e.imageSmoothingEnabled=!0,$e.imageSmoothingQuality="high";try{$e.drawImage(y,Math.round(L.x),Math.round(L.y),z,pe,0,0,de,De)}catch{}}}},[]),ou=u.useCallback((y,M)=>{if(M){ca.current.set(y,M),Qe.current.delete(y),window.requestAnimationFrame(ui),window.requestAnimationFrame(()=>ss(y,!0));return}const L=ca.current.get(y);el(y,L),ca.current.delete(y),Qe.current.has(y)||Jr(y)},[Jr,ui,ss,el]),Ql=u.useCallback((y,M)=>{gs.current=performance.now(),vn.current=Number(y.layoutVersion||0),ui();const L=cn.current?.tiles||[],F=L.length>0?Math.round(y.byteLength/L.length):y.byteLength;for(const z of L){const pe={...y,deviceId:z.deviceId,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:F};Kl(pe,{...M,deviceId:z.deviceId,width:z.width,height:z.height,byteLength:F}),St.current===z.deviceId&&ss(z.deviceId,!0)}},[Kl,ui,ss]),pf=u.useCallback(y=>{const M=performance.now();Fi.current<=0&&(Fi.current=M),Ur.current=M;const L=xa.current;if(!L)return;const F=cn.current?.tiles||[],z=F.length>0?Math.round(y.byteLength/F.length):y.byteLength;for(const pe of F)Nn("wall",{...y,deviceId:pe.deviceId,width:pe.width,height:pe.height,sourceWidth:pe.width,sourceHeight:pe.height,byteLength:z});Jm(L,y,()=>xa.current!==L,Ql).catch(()=>{})},[Ql,Nn]),er=u.useMemo(()=>({fps:ci,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:He.quality,mode:ft?"mode3-h264-hw":He.frameMode,frameMode:ft?"mode3-h264-hw":He.frameMode,streamPurpose:"wall",monitorSelections:Qt,onFrame:Ji}),[ci,Ji,On,ft,Qt,He]),Xl=u.useCallback(y=>{if(y.deviceId!==B||y.streamPurpose!=="control"||y.monitorIndex!==Us)return;const M=et.find(L=>L.deviceId===y.deviceId);!M?.sessionId||M.sessionId!==y.sessionId||($(y),V(L=>L==="connecting"?"active":L))},[et,B,Us]);u.useEffect(()=>{$(null)},[B,se,ba,Us]);const tl=u.useMemo(()=>({fps:Yi,maxWidth:$s.maxWidth,maxHeight:$s.maxHeight,quality:dt.quality,mode:ba,frameMode:ba,streamPurpose:"control",forceRestart:se!=="",forceRestartToken:se,restartReason:se?"control-session-start":"",monitorSelections:Qt,onFrame:Uo,onStreamReady:Xl}),[se,dt.quality,Uo,Yi,ba,$s.maxHeight,$s.maxWidth,Xl,Qt]),{frames:Zl,state:tr,error:Vs,stats:fa,restartLive:nr}=Ry(Zn,He.autoStartLive&&Zn.length>0,N,er),{frame:di,layout:ma,state:Jl,stats:cu,refreshInputs:qo}=hj(da,ft&&He.autoStartLive&&da.length>0,N,{fps:ei.atlasOutputFps,width:1920,height:1080,tileWidth:On.maxWidth,tileHeight:On.maxHeight,captureDeviceIds:da,monitorSelections:Qt,onFrame:pf});u.useEffect(()=>{cn.current=ma,ma&&window.requestAnimationFrame(ui)},[ma,ui]),u.useEffect(()=>{if(!ft||Jl!=="open"){Fi.current=0,Ur.current=0,gs.current=0;return}const y=window.setInterval(()=>{const M=xa.current,L=performance.now();if(!M||document.visibilityState!=="visible"||L-Gn.current<mh)return;const F=Ur.current,z=Fi.current;if(F<=0||z<=0||L-F>500)return;const pe=gs.current||z,de=L-pe;if(de>=LM&&L-Bl.current>=zM){Xm(M)&&(Bl.current=L,Hl.current=L);return}de>=DM&&L-Hl.current>=_M&&XC(M)&&(Hl.current=L)},250);return()=>window.clearInterval(y)},[Jl,ft]);const{frames:Go,state:Vo,error:nl,stats:uu,restartLive:al,reconnectLive:eo}=Ry(Zi,Zi.length>0,N,tl),Jn=u.useMemo(()=>{const y=new Map(Zl);if(ft&&di&&da.length>0){const M=new Map((ma?.tiles||[]).map(F=>[F.deviceId,F])),L=Math.max(1,M.size);for(const F of da){const z=M.get(F);z&&y.set(F,{...di,deviceId:F,width:z.width,height:z.height,sourceWidth:z.width,sourceHeight:z.height,byteLength:Math.round(di.byteLength/L)})}}for(const[M,L]of Go.entries())y.set(M,L);for(const M of Xr){if(!Wt.current.has(M)||y.has(M))continue;const L=kn.current.get(M);L&&y.set(M,L)}return y},[di,ma,Go,da,ft,Zl,Xr,ee]),ar=at&&Zi.length>0?Vo:da.length>0?Jl:tr,ea=at&&Zi.length>0?uu:da.length>0?cu:fa;u.useCallback((y,M="browser-stale")=>{const L=nr(y,M),F=al(y,M);return L||F},[al,nr]),u.useEffect(()=>{ft&&da.length>0&&!at&&qo()},[da.length,ft,qo,at]);const ys=u.useCallback((y,M,L)=>{const F=M==="control"?ut.current.get(y)||null:Nt.current.get(y)||null;if(!F||!Xm(F))return!1;const z=performance.now();return Bs.current.set(Ms(M,y),z),!0},[]),sr=u.useCallback(y=>{if(ba!=="mode3-h264-hw"||!B||I)return!1;const M=et.find(De=>De.deviceId===B)||Vn,L=String(M?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(L))return!1;const F="mode5-lzo-delta",z=Ms("control",B),pe=performance.now();Hs.current.set(z,pe),Os.current.delete(z),$r.current.delete(z),ai.current.delete(z),si.current.delete(z),es.current.delete(z),Xm(ut.current.get(B)||null),eo([B],"control-decode-fallback"),Q(F),K(`control-${F}-fallback-${B}-${Date.now()}`),be(!1),Zt(!1);const de=y==="no first frame"||y==="control-first-frame-timeout";return he(De=>De||(de?`Control frame transport timeout; retrying Control with Mode 5 (${y})`:`H.264 decode failed; retrying Control with Mode 5 (${y})`)),V("connecting"),!0},[et,Vn,B,I,ba,eo]);u.useEffect(()=>{const y=at?Vn:null;if(y){Ol.current={deviceId:y.deviceId,monitorIndex:Us,frameMode:ba,startedAtEpochMs:Date.now()},Zt(B===y.deviceId&&ce||qe.has(y.deviceId));return}Ol.current=null,Zt(!1)},[Vn?.sessionId,G,B,ce,ba,Us,at,qe]);const Ws=u.useCallback(async y=>{const M=C.find(de=>de.deviceId===y),L=Nc({mode4Enabled:ft,directMode4WallEnabled:as,isMac:zi(M?.platform)})==="atlas",F=Ea(Qt[y],M?ga(M):1),z=L?{fps:ei.scalableAtlasInputFps,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:60,mode:"mode2-lzo",frameMode:"mode2-lzo",streamPurpose:"atlas",monitorIndex:F}:{fps:ft&&!L?ci:Pe,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:He.quality,mode:ft?"mode3-h264-hw":He.frameMode,frameMode:ft?"mode3-h264-hw":He.frameMode,streamPurpose:"wall",monitorIndex:F},pe=await Ge(`/api/remote/devices/${encodeURIComponent(y)}/live/start`,{method:"POST",body:JSON.stringify(z)},N);if(pe?.ok===!1)throw new Error(pe.error||"wall-stream-start-failed");return pe},[Pe,C,as,ci,On.maxHeight,On.maxWidth,N,ft,Qt,He.frameMode,He.quality]),fi=u.useCallback(async y=>{const M=C.find(z=>z.deviceId===y),L=Nc({mode4Enabled:ft,directMode4WallEnabled:as,isMac:zi(M?.platform)})==="atlas",F=await Ge(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:L?"atlas":"wall",reason:"control-active"})},N);if(F?.ok===!1)throw new Error(F.error||"wall-stream-stop-failed");return F},[C,as,N,ft]),Ys=u.useCallback(async(y,M="control-session-stop")=>{const L=await Ge(`/api/remote/devices/${encodeURIComponent(y)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:M})},N);if(L?.ok===!1)throw new Error(L.error||"control-stream-stop-failed");return L},[N]),wa=u.useCallback(y=>{const M=ut.current.get(y);M&&(Ac(M),ut.current.delete(y));const L=Mt.current.get(y);L&&Ac(L),kn.current.delete(y),Wt.current.delete(y),An.current.delete(y)},[]);u.useEffect(()=>{const y=G&&et.find(z=>z.deviceId===G)||null;if(!at||!It||!y){Is.current&&(++Xn.current,Is.current="");return}if(B===y.deviceId&&(q==="active"||q==="warm"||q==="connecting")){V(z=>z==="warm"?"active":z);return}if(Is.current===y.deviceId)return;const M=++Xn.current,L=B;Is.current=y.deviceId,(async()=>{if(L){if(V("stopping"),await Ys(L,"control-session-switch").catch(()=>{}),M!==Xn.current)return;const de=St.current;if(de&&de!==y.deviceId)try{await Ws(de)}catch(De){Ie(De instanceof Error?De.message:String(De))}finally{St.current===de&&(St.current="",Qa(""))}if(M!==Xn.current)return;wa(L)}if(M!==Xn.current)return;if($x(y)){try{await fi(y.deviceId)}catch(de){M===Xn.current&&(Is.current="",V("error"),Ie(de instanceof Error?de.message:String(de)));return}if(M!==Xn.current){await Ws(y.deviceId).catch(()=>{});return}St.current=y.deviceId,Qa(y.deviceId),Wt.current.add(y.deviceId)}const z=Ms("control",y.deviceId),pe=`control-session-${M}-${y.deviceId}`;Hs.current.set(z,performance.now()),Os.current.delete(z),$r.current.delete(z),es.current.delete(z),si.current.delete(z),Q(""),he(""),K(pe),xe(y.deviceId),be(!1),V("connecting"),Xn.current===M&&Is.current===y.deviceId&&(Is.current="")})()},[et,G,B,q,It,wa,Ie,at,Ws,Ys,fi]),u.useEffect(()=>{if(!B||et.some(L=>L.deviceId===B))return;const y=B,M=++Xn.current;V("stopping"),Ys(y,"control-device-disconnected").catch(()=>{}).finally(()=>{M===Xn.current&&(wa(y),be(!1),K(""),Q(""),he(""),xe(L=>L===y?"":L),V("idle"))})},[et,B,wa,Ys]);const Wo=$x(et.find(y=>y.deviceId===B));u.useEffect(()=>{if(Ja.current!==null&&(window.clearTimeout(Ja.current),Ja.current=null),!B||q==="idle"||q==="stopping"||q==="error"||at||_t==="wall"){B&&!at&&_t==="wall"&&V(L=>L==="warm"||L==="active"?"active":L);return}V(L=>L==="idle"||L==="stopping"?L:"warm");const y=B,M=++Xn.current;return Ja.current=window.setTimeout(()=>{Ja.current=null,V("stopping"),Ys(y,"control-session-warm-timeout").catch(()=>{}).finally(()=>{M===Xn.current&&(wa(y),be(!1),K(""),Q(""),he(""),xe(L=>L===y?"":L),V("idle"))})},IM),()=>{Ja.current!==null&&(window.clearTimeout(Ja.current),Ja.current=null)}},[_t,B,q,wa,at,Ys]),u.useEffect(()=>()=>{Ja.current!==null&&window.clearTimeout(Ja.current)},[]),u.useEffect(()=>{const M=B&&(Wo&&(q==="connecting"||q==="active"||q==="warm"||q==="stopping")||ce&&(q==="active"||q==="warm"))?B:"";if(rn.current=M,Pt.current)return;const L=async()=>{for(;;){const z=rn.current,pe=St.current;if(pe===z)return;if(pe){try{await Ws(pe)}catch(de){Ie(de instanceof Error?de.message:String(de))}finally{St.current===pe&&(St.current="",Qa(""))}continue}if(!z)return;try{await fi(z)}catch(de){rn.current=St.current,Ie(de instanceof Error?de.message:String(de));return}St.current=z,Qa(z),Wt.current.add(z)}};let F;F=L().finally(()=>{Pt.current===F&&(Pt.current=null),St.current!==rn.current&&Xa(z=>z+1)}),Pt.current=F},[B,ce,q,Wo,ft,Ie,Ws,fi,Br]);const is=B&&et.find(y=>y.deviceId===B)||null,xs=!!(at&&Se&&q==="active"&&is?.sessionId&&X?.deviceId===is.deviceId&&X.sessionId===is.sessionId&&X.streamPurpose==="control"&&X.commandId&&X.captureGeneration>0&&X.monitorIndex===Us),{state:Yo,sendInput:ta,stats:Sa,error:rs}=pj(ns&&xs,N),ir=u.useCallback((y,M)=>!xs||!is||!X||y!==is.deviceId?!1:ta(y,{...M,controlSessionId:is.sessionId,controlCommandId:X.commandId,captureGeneration:X.captureGeneration}),[xs,is,X,ta]),Ks=xs&&Yo==="open",{state:mi,lastFrame:to,stats:Hn,error:no}=jj(Ee?.deviceId||"",$o&&re,N),sl=u.useRef(new Map);u.useEffect(()=>{const y=[["hub",j],["registry",l],["license",U],["wall-stream",Vs],["control-stream",nl],["control-decode",ue],["remote-input",rs],["remote-audio",no]];for(const[M,L]of y){const F=String(L||"").trim();if(M==="hub"&&bt?.requiresHubRestart&&bt.stage==="updating"){sl.current.delete(M);continue}if(!F){sl.current.delete(M);continue}sl.current.get(M)!==F&&(sl.current.set(M,F),Ie(F))}},[no,ue,nl,j,rs,U,l,Ie,Vs,bt]),u.useEffect(()=>{if(!at||!Se||!ns||!Ks||!Ee)return;const y=(F,z)=>{const pe=F.target,de=pe?.tagName?.toLowerCase();pe?.isContentEditable||de==="input"||de==="textarea"||de==="select"||(F.preventDefault(),F.stopPropagation(),ir(Ee.deviceId,{type:z,monitorIndex:Ea(Qt[Ee.deviceId],ga(Ee)),key:F.key,code:F.code,keyCode:F.keyCode||F.which||0,location:F.location,text:F.key.length===1?F.key:"",repeat:z==="keydown"?F.repeat:!1,shiftKey:F.shiftKey,ctrlKey:F.ctrlKey,altKey:F.altKey,metaKey:F.metaKey}))},M=F=>y(F,"keydown"),L=F=>y(F,"keyup");return window.addEventListener("keydown",M),window.addEventListener("keyup",L),()=>{window.removeEventListener("keydown",M),window.removeEventListener("keyup",L)}},[ns,Ks,Se,Qt,Ee,ir,at]),u.useEffect(()=>{const y=()=>{document.visibilityState==="visible"&&(Gn.current=performance.now())};return document.addEventListener("visibilitychange",y),window.addEventListener("pageshow",y),()=>{document.removeEventListener("visibilitychange",y),window.removeEventListener("pageshow",y)}},[]),u.useEffect(()=>{if(!B||q!=="connecting"&&q!=="active"&&q!=="warm"||Vo!=="open")return;const y=B,M=Ms("control",y),L=window.setInterval(()=>{const F=performance.now();if(document.visibilityState!=="visible"||F-Gn.current<mh)return;const z=Os.current.get(M)||0,pe=$r.current.get(M)||0,de=ai.current.get(M)||0,De=Hs.current.get(M)||F;Hs.current.has(M)||Hs.current.set(M,De);const $e=z<=0,Xe=$e?F-De>GM:F-z>_x,tn=z>0&&(pe<=0||F-pe>_x);if(!Xe&&tn){const pl=Bs.current.get(M)||0;F-pl>=zx&&ys(y,"control","decoder-paint-stale");return}if(!Xe)return;const dn=si.current.get(M)||0;if(dn>0){if(F-dn<WM)return;si.current.delete(M)}const Wn=es.current.get(M)||0;if(Wn>=YM){if(sr($e?"no first frame":"stale stream"))return;be(!1),Zt(!1),V("error");return}if(F-de<Ix(VM,Wn))return;al([y],$e?"control-first-frame-timeout":"control-receive-stale")&&(ai.current.set(M,F),si.current.set(M,F),Hs.current.set(M,F),es.current.set(M,Wn+1))},650);return()=>window.clearInterval(L)},[Vo,B,q,sr,ys,al]),u.useEffect(()=>{!ue||ba!=="mode3-h264-hw"||sr(ue)||(be(!1),Zt(!1),V("error"))},[ue,ba,sr]),u.useEffect(()=>{!at||!B||!nl||V(y=>y==="error"?y:"error")},[nl,B,at]),u.useEffect(()=>{if(tr!=="open"||!He.autoStartLive||Zn.length===0)return;const y=window.setInterval(()=>{const M=performance.now();if(document.visibilityState!=="visible"||M-Gn.current<mh)return;const L=1e3/Math.max(1,ci||He.fps||1),F=Math.max(KM,Math.ceil(L*4)),z=[];for(const pe of Zn){if(z.length>=ZM)break;const de=Ms("wall",pe),De=Os.current.get(de)||0;if(De<=0)continue;const $e=ai.current.get(de)||0,Xe=$r.current.get(de)||0,tn=M-De>F,dn=Xe<=0||M-Xe>F;if(!tn&&dn){const hl=Bs.current.get(de)||0;M-hl>=zx&&ys(pe,"wall","decoder-paint-stale");continue}if(!tn)continue;const Wn=es.current.get(de)||0;M-$e>=Ix(QM,Wn)&&z.push(pe)}if(z.length>0&&nr(z,"wall-frame-stale"))for(const pe of z){const de=Ms("wall",pe);ai.current.set(de,M),es.current.set(de,(es.current.get(de)||0)+1)}},XM);return()=>window.clearInterval(y)},[ci,Zn,ys,nr,He.autoStartLive,He.fps,tr]),u.useEffect(()=>{vt(He.fps),Gi.current=Date.now(),ln.current=0},[He.fps,He.frameMode,He.adaptiveLoadShedding]),u.useEffect(()=>{UC({h264DecodeAcceleration:He.h264DecodeAcceleration})},[He.h264DecodeAcceleration]),u.useEffect(()=>{if(!It||at||!He.visibleOnlyLive){H([]);return}const y=$i.current;if(!y||typeof IntersectionObserver>"u"){H(Qr);return}const M=Array.from(y.querySelectorAll("[data-live-device-id]"));if(M.length===0){H([]);return}const L=new Map,F=()=>{const pe=yh(M.map(de=>String(de.dataset.liveDeviceId||"")).filter(de=>(L.get(de)||0)>0));H(de=>vh(de,pe)?de:pe)},z=new IntersectionObserver(pe=>{for(const de of pe){const De=String(de.target.dataset.liveDeviceId||"");De&&L.set(De,de.isIntersecting?de.intersectionRatio||.01:0)}F()},{root:null,rootMargin:oa.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return M.forEach(pe=>z.observe(pe)),F(),()=>z.disconnect()},[Qr,It,at,Wr,He.visibleOnlyLive,ge]),u.useEffect(()=>{if(!He.adaptiveLoadShedding||!He.autoStartLive||Zn.length===0)return;const y=He.fps;if(Zn.length<=oa.preserveConfiguredFpsDeviceCount){Pe!==y&&(vt(y),Gi.current=Date.now(),ln.current=0);return}if(tr!=="open"||fa.sampleMs<500)return;const M=Date.now(),L=Zn.length*Pe,F=fa.framesPerSecond,z=fa.bytesPerSecond,pe=Math.max(0,...Zn.map(tn=>Bi[Ms("wall",tn)]?.maxIntervalMs||0)),de=Math.max(0,...Zn.map(tn=>zs[Ms("wall",tn)]?.maxIntervalMs||0)),De=L>8&&F>0&&F<L*.72;if(F>oa.maxWallFramesPerSecond||z>oa.maxWallBytesPerSecond||pe>oa.maxFrameGapMs||de>oa.maxFrameGapMs||De){ln.current=0;const tn=oa.minFps;if(M-Gi.current>=oa.downshiftCooldownMs&&Pe>tn){const dn=Math.max(tn,pT(Pe,tn));dn<Pe&&(vt(dn),Gi.current=M)}return}const Xe=F<oa.maxWallFramesPerSecond*oa.lowLoadFrameRatio&&z<oa.maxWallBytesPerSecond*oa.lowLoadByteRatio;if(!Xe||Pe>=y){Xe||(ln.current=0);return}if(!ln.current){ln.current=M;return}if(M-ln.current>=oa.recoveryCooldownMs){const tn=Math.min(y,gT(Pe,y));tn>Pe&&(vt(tn),Gi.current=M,ln.current=0)}},[Pe,Zn.length,Zn,zs,Bi,tr,fa.bytesPerSecond,fa.framesPerSecond,fa.lastUpdatedAt,fa.sampleMs,He.adaptiveLoadShedding,He.autoStartLive,He.frameMode,He.fps]),u.useEffect(()=>{const y=new URLSearchParams(window.location.search).get("checkout");if(y==="success"){Ie("Checkout returned. Waiting for Dodo confirmation."),O();const M=window.setInterval(()=>{O()},4e3),L=window.setTimeout(()=>{window.clearInterval(M)},45e3);return()=>{window.clearInterval(M),window.clearTimeout(L)}}y==="cancelled"&&Ie("Checkout cancelled.")},[O]),u.useEffect(()=>{!It&&Se&&_e(!1),!It&&re&&Z(!1)},[re,Se,It]),u.useEffect(()=>{const y=Ee?.deviceId||"",M=ze.current;if(ze.current=y,!M||M===y)return;const L=++ae.current,F=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";y&&re&&Le.current.set(y,F);let z=!0;return(async()=>{try{const de=Le.current.get(M);if(Le.current.delete(M),await Ge(`/api/remote/devices/${encodeURIComponent(M)}/audio/stop`,{method:"POST",body:JSON.stringify(de?{streamId:de}:{})},N),!z||L!==ae.current||!re||!y||!It||!Yr)return;const De=await Ge(`/api/remote/devices/${encodeURIComponent(y)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:F,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N);if(De.ok===!1)throw new Error(De.error||"Remote audio start failed.")}catch(de){z&&(Le.current.delete(y),Z(!1),Ie(de instanceof Error?de.message:String(de)))}})(),()=>{z=!1}},[re,It,N,Yr,Ee?.deviceId]),u.useEffect(()=>{const y=et.map(F=>F.deviceId),M=new Set(y),L=new Map(et.map(F=>[F.deviceId,F]));_(F=>{const z=F.filter(pe=>M.has(pe));return vh(F,z)?F:z}),ne(F=>F&&M.has(F)?F:""),te(F=>F&&M.has(F)?F:""),ps(F=>{let z=!1;const pe={};for(const[de,De]of Object.entries(F)){const $e=L.get(de);if(!$e){pe[de]=De;continue}const Xe=Ea(De,$e?ga($e):1);pe[de]=Xe,Xe!==De&&(z=!0)}return z?pe:F}),qr(F=>{const z=F.filter(pe=>M.has(pe));return vh(F,z)?F:z})},[et,Ul]),u.useEffect(()=>{Oo([]),Ho(!1)},[ss]),u.useEffect(()=>{!li||za!=="selected"||ri.length>0||ua.length===0||qr(ua.map(y=>y.deviceId))},[ua,ri.length,za,li]),u.useEffect(()=>{try{localStorage.setItem(uw,zt)}catch{}},[zt]),u.useEffect(()=>{uT(He)},[He]),u.useEffect(()=>{fT(dt)},[dt]),u.useEffect(()=>{oT(Qt)},[Qt]);const na=u.useCallback(async()=>{const y=new Set(p);y.add(Cn);try{const pe=await Ge("/api/remote/status",void 0,Cn);yy({endpoint:pe.agentEndpoint,endpoint_candidates:[...pe.agentEndpointCandidates||[],...pe.hostTargetEndpointCandidates||[]]}).forEach(de=>y.add(de))}catch{}const M=[...y].sort((pe,de)=>{const De=$e=>{const Xe=Ic($e);return Xe==="local"?0:Xe==="loopback"?1:2};return De(pe)-De(de)||pe.localeCompare(de)});let L=!1,F="",z=!1;try{for(const pe of M){const de=Ic(pe);try{if(await Ge("/api/health",void 0,pe),de==="local")return v(!0),Co(!0),pe;de==="loopback"&&(L=!0,F=pe)}catch{de==="local"&&(z=!0)}}return L?(z&&Ie("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),v(!0),Co(!0),F||Cn):(v(!1),Co(!1),"")}catch{return v(!1),Co(!1),""}},[p]),ls=async()=>{if(Ae("auth"),jn(!1),await na(),window.liveDesk?.auth?.signInWithGoogle){const L=await window.liveDesk.auth.signInWithGoogle();L?.ok===!1&&(Ie(L.error||"LiveDesk could not open the system browser for Google sign-in."),Ae(""));return}const{data:y,error:M}=await pt.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});M&&(Ie(M.message),Ae(""))},rr=async()=>{Ae("auth"),jn(!1),await pt.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1?Ie("Signed out locally. The LiveDesk runtime could not be reached to clear its session."):window.liveDesk?.auth?.persistSession||await Ge("/api/auth/session",{method:"DELETE"},Cn).catch(()=>{}),Ae("")};u.useEffect(()=>{if(!Re)return;const y=L=>{L.target instanceof Element&&(L.target.closest(".account-popover, .rail-account")||jn(!1))},M=L=>{L.key==="Escape"&&jn(!1)};return window.addEventListener("pointerdown",y),window.addEventListener("keydown",M),()=>{window.removeEventListener("pointerdown",y),window.removeEventListener("keydown",M)}},[Re]);const il=u.useCallback(async(y={})=>{const M=y.silent===!0,L=y.takeover===!0,F=y.requestLocalAccess===!0;if(!n?.user){M||Ie("Sign in before publishing this host.","error");return}if(!Ui.current){Ui.current=!0,M||(Ae("host"),ct("Hub · 1/4 · Checking the local runtime…"));try{const pe=(F?await na():"")||N||Cn;if(!(b||await Ge("/api/remote/status",void 0,pe)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");M||ct("Hub · 2/4 · Sending the signed-in session to the Hub…");const De=await Ge("/api/auth/session",{method:"POST",body:JSON.stringify({accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}})},pe);if(!De.ok||!De.authenticated)throw new Error(De.error||"hub-session-sync-failed");M||ct("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const $e=await Ge("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:L})},pe);if(!$e.ok)throw new Error($e.error||"host-target-failed");if(!M){ct("Hub · 4/4 · Verifying the endpoint and lease renewal…");const Xe=await Ge("/api/hub/status",void 0,pe);if(!Xe.hostTargetActive)throw new Error(Xe.hostTargetLease?.lastError||"host-target-not-active-after-sync");const tn=Xe.hostTargetEndpoint||Xe.agentEndpoint||"endpoint ready",dn=Number(Xe.connectedDeviceCount||0),Wn=dn>0?`${dn} client${dn===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Ie(`Hub ready · ${tn} · lease auto-renewal active. ${Wn}`,"success"),(F||w)&&(v(!0),Co(!0)),A()}c()}catch(z){if(!M){const pe=z instanceof Error?z.message:String(z);pe.includes("local network access")&&(v(!1),Co(!1)),Ie(`Hub setup failed · ${pe}`,"error")}}finally{Ui.current=!1,M||Ae("")}}},[N,w,A,c,na,n,Ie,ct,b]),rl=u.useCallback(async()=>{if(!(!b?.update?.canApply||fe==="update")){Ae("update");try{const y=await Ge("/api/update/apply",{method:"POST",body:JSON.stringify({})},N||Cn);if(!y.ok)throw new Error(y.error||"LiveDesk update could not be started.");const M=[...new Set((y.targets||[]).map(z=>String(z.deviceId||"").trim()).filter(Boolean))],L=!!(y.managerUpdateAvailable||y.clientPackageUpdateAvailable),F=y.state==="hub-restart-requested"?Date.now():void 0;(M.length>0||L)&&qn({operationId:String(y.operationId||`wall-update-${Date.now()}`),targetIds:M,stage:y.state==="clients-updated"?"updated":"updating",requiresHubRestart:L,initialHostInstanceId:String(b.hostInstanceId||""),targetManagerVersion:String(y.latestVersion||b.update?.latestVersion||""),targetClientVersion:String(y.latestClientVersion||b.update?.latestClientVersion||""),restartRequestedAt:F,restartDeadlineAt:F?F+Md:void 0}),ct(y.state==="hub-restart-requested"?Nd:Ax),A()}catch(y){Ie(y instanceof Error?y.message:String(y),"error")}finally{Ae("")}}},[fe,N,A,Ie,ct,b]);u.useEffect(()=>{const y=bt,M=b?.update;if(!y||y.stage!=="updating"||!M)return;const L=M.restartResult?.operationId===y.operationId?M.restartResult:null;if(L?.outcome==="restored"){const $e=L.error||`The requested Hub ${L.targetVersion||y.targetManagerVersion||"version"} failed verification.`;qn(Xe=>Xe?.operationId===y.operationId?{...Xe,stage:"restored",error:$e}:Xe),Ie(`LiveDesk update did not complete. Hub ${L.fallbackVersion||L.appVersion||"the previous version"} was restored. ${$e}`,"error");return}if(L?.outcome==="failed"){const $e=L.error||"No verified LiveDesk Hub replacement could be started.";qn(Xe=>Xe?.operationId===y.operationId?{...Xe,stage:"failed",error:$e}:Xe),Ie(`LiveDesk Hub update failed. ${$e}`,"error");return}if(M.operationId===y.operationId&&M.state==="failed"){const $e=M.error||"LiveDesk update failed before the Hub replacement completed.";qn(Xe=>Xe?.operationId===y.operationId?{...Xe,stage:"failed",error:$e}:Xe),Ie($e,"error");return}if(M.operationId===y.operationId){if(M.state==="hub-restart-requested"&&!y.restartDeadlineAt){const $e=Date.now();qn(Xe=>Xe?.operationId===y.operationId?{...Xe,restartRequestedAt:$e,restartDeadlineAt:$e+Md}:Xe),ct(Nd)}!y.requiresHubRestart&&M.state==="clients-updated"&&(qn($e=>$e?.operationId===y.operationId?{...$e,stage:"updated"}:$e),Ie("LiveDesk clients updated and reconnected successfully.","success"));return}if(!y.requiresHubRestart)return;const F=b.started===!0&&(!y.initialHostInstanceId||b.hostInstanceId&&b.hostInstanceId!==y.initialHostInstanceId),z=!!M.checkedAt,pe=Nx(M.currentVersion,y.targetManagerVersion),de=!y.targetClientVersion||Nx(M.currentClientVersion,y.targetClientVersion),De=z&&M.state==="idle"&&M.updateAvailable===!1&&pe&&de;F&&De&&(qn($e=>$e?.operationId===y.operationId?{...$e,stage:"updated"}:$e),Ie(`LiveDesk Hub ${M.currentVersion||L?.appVersion||y.targetManagerVersion} restarted and passed version verification.`,"success"))},[Ie,ct,b,bt]),u.useEffect(()=>{const y=bt;if(!y||y.stage!=="updating"||!y.requiresHubRestart||y.restartDeadlineAt)return;const M=()=>{const F=Date.now();qn(z=>z?.operationId===y.operationId&&z.stage==="updating"&&!z.restartDeadlineAt?{...z,restartRequestedAt:F,restartDeadlineAt:F+Md}:z),ct(Nd)};if(b?.update?.state==="hub-restart-requested"){M();return}if(!j)return;const L=window.setTimeout(M,FM);return()=>window.clearTimeout(L)},[j,ct,b?.update?.state,bt]),u.useEffect(()=>{const y=bt;if(!y||y.stage!=="updating"||!y.requiresHubRestart||!y.restartDeadlineAt)return;const M=Math.max(0,y.restartDeadlineAt-Date.now()),L=y.operationId,F=window.setTimeout(()=>{const z=`LiveDesk Hub did not return and verify ${y.targetManagerVersion||"the requested version"} within ${Math.round(Md/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;qn(pe=>pe?.operationId===L&&pe.stage==="updating"?{...pe,stage:"failed",error:z}:pe),Ie(z,"error")},M);return()=>window.clearTimeout(F)},[Ie,bt]),u.useEffect(()=>{if(!bt||bt.stage!=="updated")return;const y=bt.operationId,M=window.setTimeout(()=>{qn(L=>L?.operationId===y?null:L)},8e3);return()=>window.clearTimeout(M)},[bt]),u.useEffect(()=>{if(Et!==Ax&&Et!==Nd)return;const y=b?.update;if(String(y?.state||"")==="failed"){Ie(y?.error||"LiveDesk update failed.","error");return}bt?.stage==="updated"&&Ie("")},[Et,Ie,b?.update?.error,b?.update?.state,bt?.stage]);const Ca=u.useCallback(async()=>{if(!fe){Ae("pin");try{const M=await Ge("/api/remote/pairing-pin",{method:"POST"},N||Cn);if(!M.ok)throw new Error(M.error||"pin-rotation-failed");await A(),Ie("New PIN published.")}catch(y){Ie(y instanceof Error?y.message:String(y))}finally{Ae("")}}},[fe,N,A]),aa=u.useCallback(y=>{y&&(ne(y),_(M=>M.includes(y)?M:[...M,y]))},[]),bs=u.useCallback(y=>{if(!y)return;const M=oi.has(y);ne(L=>M?L===y?"":L:y),_(L=>M?L.filter(F=>F!==y):L.includes(y)?L:[...L,y])},[oi]),sa=u.useCallback(()=>{_([]),ne("")},[Ia]),Oa=u.useCallback(()=>{_(et.map(y=>y.deviceId)),ne("")},[et]),Ha=u.useCallback((y,M)=>{const L=et.find(z=>z.deviceId===y);if(!L)return;const F=ga(L);F<=1||(ps(z=>{const de=(Ea(z[y],F)+M+F)%F;return{...z,[y]:de}}),at&&(Zt(!1),te(y)))},[et,at]);u.useEffect(()=>{const y=M=>{if(at&&Se&&ns)return;const L=M.target,F=L?.tagName?.toLowerCase();L?.isContentEditable||F==="input"||F==="textarea"||F==="select"||((M.ctrlKey||M.metaKey)&&M.key.toLowerCase()==="a"&&(M.preventDefault(),Oa()),M.key==="Escape"&&sa())};return window.addEventListener("keydown",y),()=>window.removeEventListener("keydown",y)},[ns,sa,Se,Oa,at]);const du=(y,M)=>{const L=et.find(z=>z.deviceId===y),F=Ea(M,L?ga(L):1);ps(z=>({...z,[y]:F})),at?(Zt(!1),te(y)):aa(y)},lr=async y=>{if(Zt(!1),te(y),Ft("control"),!Qi.has(y)){_e(!1),Ie(Kr);return}const M=et.find(F=>F.deviceId===y);if(zi(M?.platform)&&(M?.capabilities?.controlPermission===!1||M?.capabilities?.accessibilityPermission===!1)){_e(!1),Ie("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}_e(!0),Ie(`Opening remote control${M?` for ${fs(M)}`:""}.`,"success")},Ko=async()=>{if(!Ee){Ie("Select a workstation before playing audio.");return}if(!It){Ie(Kr);return}if(!Yr){Ie("Selected workstation does not report remote audio support yet.");return}if(Te)return;const y=!re,M=y?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Le.current.get(Ee.deviceId);y&&M?Le.current.set(Ee.deviceId,M):y||Le.current.delete(Ee.deviceId),Be("audio"),Z(y);try{await Ge(`/api/remote/devices/${encodeURIComponent(Ee.deviceId)}/audio/${y?"start":"stop"}`,{method:"POST",body:JSON.stringify({...M?{streamId:M}:{},mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},N),Ie(`${y?"Audio started":"Audio stopped"} for ${fs(Ee)}.`,"success")}catch(L){y&&Le.current.delete(Ee.deviceId),Z(!1),Ie(L instanceof Error?L.message:String(L),"error")}finally{Be("")}},fu=y=>{const M=y instanceof Error?y.message:String(y);return/remote-actions-disabled|allowAgent-blocked-by-settings/i.test(M)?"Remote actions are off. Turn on Settings > Agent > Enable AI Agent first.":/power-actions-disabled/i.test(M)?"Power actions are off. Turn on Settings > Agent > Allow power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(M)?"This workstation needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(M)?"The workstation disconnected before the action could be sent.":M},un=async y=>{if(!Ee||Te)return;const M=Ee,F={lock:"Lock",sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[y];if(!(y!=="lock"&&!window.confirm(`${F} ${fs(M)}? Unsaved work on that computer may be lost.`))){Be(y),Ie(`Sending ${F.toLowerCase()} request to ${fs(M)}...`);try{const z=await Ge(`/api/remote/devices/${encodeURIComponent(M.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:y})},N);if(!z.ok)throw new Error(z.error||"The remote action could not be sent.");Ie(`${F} request sent to ${fs(M)}.`,"success"),A()}catch(z){Ie(fu(z),"error")}finally{Be("")}}},Gt=()=>{Ee&&(Je({id:Date.now(),deviceId:Ee.deviceId,instruction:"Run command "}),_e(!1),Ft("agents"),Ie(`Command runner opened for ${fs(Ee)}.`))},wt=async(y,M,L="files")=>{const F=y.filter(De=>De.file.size>=0);if(F.length===0)return{files:0,bytes:0};if(!It)throw new Error(Kr);if(M.length===0)throw new Error("Select at least one connected workstation.");const z=crypto.randomUUID(),pe=F.reduce((De,$e)=>De+$e.file.size,0);let de=0;Fs({id:z,status:"reading",progress:1,message:`Preparing ${F.length} ${L}`});try{for(let De=0;De<F.length;De+=1){const $e=F[De],Xe=$e.file,tn=Math.max(1,Math.ceil(Xe.size/dh));for(let dn=0;dn<tn;dn+=1){const Wn=dn*dh,hl=Math.min(Xe.size,Wn+dh),pl=Xe.size===0?new ArrayBuffer(0):await Xe.slice(Wn,hl).arrayBuffer(),pr=dn===tn-1;Fs({id:z,status:"sending",progress:Math.max(2,Math.min(98,Math.round(de/Math.max(1,pe)*96))),message:`${De+1}/${F.length} ${$e.relativePath}`});const wi=await Ge("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:z,deviceIds:M,remoteDirectory:zt.trim(),name:Xe.name,relativePath:$e.relativePath,size:Xe.size,type:Xe.type,lastModified:Xe.lastModified,offset:Wn,totalBytes:Xe.size,final:pr,dataBase64:vT(pl)})},N);if(!wi.ok||wi.queued!==M.length)throw new Error(wi.error||`file-chunk-not-queued-${wi.queued}/${M.length}`);de+=pl.byteLength,await new Promise(xu=>window.setTimeout(xu,0))}}return Fs({id:z,status:"queued",progress:100,message:`Sent ${F.length} file${F.length===1?"":"s"} to ${M.length} workstation${M.length===1?"":"s"}`}),window.setTimeout(()=>{Fs(De=>De?.id===z&&De.status==="queued"?null:De)},4500),{files:F.length,bytes:pe}}catch(De){throw Fs({id:z,status:"failed",progress:100,message:De instanceof Error?De.message:String(De)}),De}},ws=async y=>{const M=ua.length>0?ua.map(L=>L.deviceId):Ee?[Ee.deviceId]:[];try{await wt(Hx(y),M)}catch(L){Ie(L instanceof Error?L.message:String(L))}},ha=async y=>{try{await wt(Hx(y),df)}catch(M){Ie(M instanceof Error?M.message:String(M))}};u.useEffect(()=>{Qc.current=!1},[]);const Qo=y=>{y.preventDefault(),y.stopPropagation(),_a(!1),ws(y.dataTransfer.files)},Ba=async(y="ltd")=>{if(!n){Ie("Sign in with Google before checkout.");return}if(T&&y===Yt){Ie("LiveDesk license is already active.");return}if(T&&Yt==="pro"){Ie("LiveDesk Pro is already active.");return}Ae("checkout");try{const{data:M,error:L}=await pt.functions.invoke("dodo-checkout",{body:{plan:y}});if(L)throw L;if(!M?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(M.checkout_url)}catch(M){Ie(M instanceof Error?M.message:String(M)),Ae("")}},Ss=JM(),ll=eT(),or=et.length,Cs=Wl.filter(y=>Jn.has(y)).length,ol=ar==="open"&&ea.sampleMs>0?`${ea.framesPerSecond.toFixed(1)} fps`:ar,Me=Ee?at?Go.get(Ee.deviceId):Jn.get(Ee.deviceId):void 0,cr=Ee?Ea(Qt[Ee.deviceId],ga(Ee)):0,Qs=Ee?sT(Ee):[],js=typeof Me?.monitorIndex=="number"?Ea(Me.monitorIndex,Math.max(1,Me.monitorCount||1)):cr,Fa=(Me&&js===cr?Sw(Me):null)||(Ee?ww(Ee,cr):null);Fa&&`${Fa.width}${Fa.height}`;const ur=Ee?Ms(at?"control":"wall",Ee.deviceId):"",yn=ur?Bi[ur]:void 0,Mn=ur?zs[ur]:void 0,xt=Mn?.lastInfo,pi=yn&&yn.sampleMs>0?`${yn.framesPerSecond.toFixed(1)} fps`:"waiting";yn&&`${yn.totalFrames}${pi}`,Mn&&Mn.sampleMs>0&&`${Mn.framesPerSecond.toFixed(1)}`,Mn&&Mn.sampleMs>0&&`${Mn.changedFramesPerSecond.toFixed(1)}`,xt&&(`${xt.frameSeq}${xt.decoderLabel}${xt.queueSize}${xt.renderQueueSize}${xt.droppedForLatency}${xt.decoderFlushCount}${xt.decoderTimestampFallbacks}${xt.decoderInputCount}${xt.decoderOutputCount}`,xt.visualChanged),xt&&`${Math.round(xt.queuedForMs)}${Math.round(xt.decodedForMs)}${Math.round(xt.scheduledForMs)}${xt.drawMs.toFixed(1)}`,xt?.targetPaintIntervalMs&&`${xt.targetPaintIntervalMs.toFixed(1)}${(1e3/xt.targetPaintIntervalMs).toFixed(1)}`,Mn&&`${Mn.decoderInputFps.toFixed(1)}${Mn.decoderOutputFps.toFixed(1)}`,xt?.canvasPresentation,xt&&`${xt.interactiveBufferWaitCount}${Math.round(xt.interactiveBufferWaitMs)}${xt.interactiveQueueDrainCount}`,yn&&(Me?.frameMode==="mode5-lzo-delta"?`${Dc(yn.averageFrameBytes)}${Me.deltaVisualTileCount||0}${Me.deltaRefreshTileCount||0}${Me.deltaTotalTiles||0}`:`${Dc(yn.averageFrameBytes)}${Math.round(yn.tinyFrameRatio*100)}${Math.round(yn.repeatedFrameRatio*100)}`),yn&&yn.sourceSendSampleCount>0&&`${yn.sourceSendAverageMs.toFixed(1)}${yn.sourceSendP95Ms.toFixed(1)}`,Ex(yn),Ex(Mn),yn&&Mn&&`${Rx(yn)}${Rx(Mn)}`,Me?Me.frameMode||Me.mode||Me.codec||Me.mimeType:at?dt.frameMode:He.frameMode,at?dt.frameMode:He.frameMode,Me?`${Me.width}${Me.height}${Dc(Me.byteLength)}`:at?`${$s.maxWidth}${$s.maxHeight}`:`${He.maxWidth}${He.maxHeight}`,Me&&`${Me.isKeyFrame?"key":String(Me.chunkType||"delta")}`,Me&&Me.monitorCount&&((Me.monitorIndex??0)+1,`${Me.monitorCount}`),Me&&[`src ${Math.round(Me.sourceGapMs||0)}ms`,`gap ${Math.round(Me.agentSendGapMs||0)}ms`,`tx ${Math.round(Me.agentSendDurationMs||0)}ms`,`pace ${Math.round(Me.agentPaceMs||0)}ms`,`queue ${Math.round(Me.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Me.agentFrameAgeMs||0)}ms`,Me.browserReceivedEpochMs&&Me.receivedAt?`hub ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Date.parse(Me.receivedAt)))}ms`:"",Me.browserReceivedEpochMs&&Me.hubPacketEpochMs?`sock ${Math.max(0,Math.round(Me.browserReceivedEpochMs-Me.hubPacketEpochMs))}ms`:"",Me.droppedByAgent?`drop ${Me.droppedByAgent}`:"",Me.hubIngressDropped?`ingress-drop ${Me.hubIngressDropped}`:"",Me.hubClientDropped?`ws-drop ${Me.hubClientDropped}`:"",Me.captureStageMs?`capture ${Math.round(Me.captureStageMs)}ms`:"",Me.requestedFps?`req ${Math.round(Me.requestedFps)}fps`:"",Me.effectiveFps?`eff ${Math.round(Me.effectiveFps)}fps`:"",Me.captureAverageMs?`avg ${Math.round(Me.captureAverageMs)}ms`:"",Me.captureP95Ms?`p95 ${Math.round(Me.captureP95Ms)}ms`:"",Me.slowFrameCount?`slow ${Math.round(Me.slowFrameCount)}`:"",Me.captureHelperRestarts?`helper ${Math.round(Me.captureHelperRestarts)}`:"",Me.convertMs?`rgb565 ${Math.round(Me.convertMs)}ms`:"",Me.compressMs?`lzo ${Math.round(Me.compressMs)}ms`:"",Me.captureSourceSerial?`cap #${Me.captureSourceSerial}`:"",Me.captureSourceSkipped?`cap skip ${Me.captureSourceSkipped}`:"",Me.frameMode==="mode5-lzo-delta"?`tiles ${Me.deltaVisualTileCount||0}+${Me.deltaRefreshTileCount||0}/${Me.deltaTotalTiles||0}@${Me.deltaTileSize||0}`:"",Me.platformProfile||Me.hardwareEncoder||"-",Me.atlasComposeMs?`atlas ${Me.atlasComposeMs.toFixed(1)}ms`:"",Me.atlasPoolStarved?`pool ${Me.atlasPoolStarved}`:"",Me.atlasTileCount?`tiles ${Me.atlasReadyTiles||0}/${Me.atlasTileCount}`:"",Me.atlasInputRevision?`input #${Me.atlasInputRevision}`:"",Me.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Me.atlasSourceMaxAgeMs)}ms`:"",xt?.inputFeedbackMs!==void 0&&xt.inputFeedbackAt!==void 0&&performance.now()-xt.inputFeedbackAt<=jx?`feedback ${Math.round(xt.inputFeedbackMs)}ms`:"",Me.contentHash?`enc ${Me.contentHash.slice(0,6)}`:"",xt?.visualHash?`pix ${xt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Yo==="open"&&[`${Sa.sentPerSecond.toFixed(1)} hz`,Sa.lastInputSeq>0?`rtt ${Math.round(Sa.lastRoundTripMs)}ms`:"",Sa.lastInputSeq>0?`apply ${Sa.lastAgentApplyMs.toFixed(1)}ms`:"",Sa.droppedPerSecond>0?`drop ${Sa.droppedPerSecond.toFixed(1)}/s`:"",Sa.bufferedAmount>0?`buf ${Dc(Sa.bufferedAmount)}`:"",Sa.lastInputType||"ready"].filter(Boolean).join(" / "),xt?.inputFeedbackMs!==void 0&&xt.inputFeedbackAt!==void 0&&performance.now()-xt.inputFeedbackAt<=jx&&`${Math.round(xt.inputFeedbackMs)}${xt.inputFeedbackSeq||0}`,re&&[mi,`context ${Hn.audioContextState}`,`queue ${Math.round(Hn.queuedMs)}ms`,`last ${Math.round(Hn.lastPacketAgeMs)}ms`,`accepted ${Math.round(Hn.lastAcceptedAgeMs)}ms`,`process ${Math.round(Hn.localProcessingAgeMs)}ms`,`remote ${Math.round(Hn.browserAgeMs)}/${Math.round(Hn.captureAgeMs)}ms`,`heartbeat ${Math.round(Hn.captureStatusAgeMs)}ms`,`capture ${Hn.captureAlive&&Hn.helperAlive?"alive":"down"}`,`drop ${Hn.drops}`,`resync ${Hn.resyncs}`,`restart ${Hn.automaticRestarts}`,Hn.pendingDecodes>0?`decode ${Hn.pendingDecodes}`:"",to?`#${to.frameSeq}`:"waiting"].filter(Boolean).join(" / "),Me&&`${Me.frameSeq}${sb(Me.receivedAt||Me.capturedAt)}`;const Jt=Math.max(0,ea.bytesPerSecond*8/1e6),cl=di?.atlasReadyTiles??Cs,ao=di?.atlasTileCount??Cs,gf=cl===ao?`${ao} tiles`:`${cl}/${ao} tiles`,vf=da.length>0;at?`${ol}${Jt.toFixed(Jt>=10?0:1)}`:vf?`${gf}${ol}${Jt.toFixed(Jt>=10?0:1)}`:`${Cs}${ol}${Jt.toFixed(Jt>=10?0:1)}`;const mu=j?"offline":b?.started?"online":"starting",en=ua.length,Xo=at?Ee?fs(Ee):"No workstation":en===0?"No workstation":en>1?`${en} selected`:Ee?fs(Ee):"No workstation",ul=at?[Ee?.deviceId].filter(y=>!!y):ua.map(y=>y.deviceId),xn=Ro[Fe]||Ro.en,dr=xn.sync||Ro.en.sync,gi=a||R?"checking":T?Yt==="pro"?"Pro LTD active":`Plus LTD ${et.length}/${Rc}`:Po?`Free ${et.length}/${Ec}`:`Upgrade ${et.length}/${Ec}`,fr=Yt==="pro"?"Pro active":fe==="checkout"?"Opening":Yt==="ltd"?"Pro $199":"Plus $79",hu=T?Yt==="pro"?"Pro active":"Upgrade to Pro LTD":n?fe==="checkout"?"Opening checkout":Yt==="ltd"?"Buy Pro LTD":"Buy Plus LTD":fe==="auth"?"Opening Google":"Sign in to buy",yf=Yt==="pro"||fe==="checkout"||fe==="auth"||a||R,Zo=n?.user?.user_metadata,os=Bx(Zo,"avatar_url","picture"),vi=Bx(Zo,"full_name","name")||n?.user?.email||"Google",dl=vi.slice(0,1).toUpperCase(),pu=b?.started?"Local app ready":"Start LiveDesk",mr=r?.active?"Published":n?"Not published":"Sign in required",Jo=/^\d{6}$/.test(b?.pairingPin||"")?b?.pairingPin:"------",so=Hd.find(y=>y.width===He.maxWidth&&y.height===He.maxHeight)?.id||`${He.maxWidth}x${He.maxHeight}`,io=He.atlasTileSizeMode==="auto"?"auto":gh.find(y=>y.width===He.atlasTileWidth&&y.height===He.atlasTileHeight)?.id||"320x180",gu=ph.find(y=>y.width===dt.maxWidth&&y.height===dt.maxHeight)?.id||`${dt.maxWidth}x${dt.maxHeight}`,vu=Od.find(y=>y.id===He.frameMode)||Od[0],Tn=y=>{ya(M=>{const L=y.frameMode?qh(y.frameMode):M.frameMode,F=y.frameMode!==void 0&&L!==M.frameMode;return{...M,...y,frameMode:L,fps:Vh(y.fps??(F?yw(L):M.fps),L)}})},yi=y=>{const M=Hd.find(L=>L.id===y);M&&Tn({maxWidth:M.width,maxHeight:M.height})},yu=y=>{if(y==="auto"){Tn({atlasTileSizeMode:"auto"});return}const M=gh.find(L=>L.id===y);!M?.width||!M?.height||Tn({atlasTileSizeMode:"fixed",atlasTileWidth:M.width,atlasTileHeight:M.height})},xi=y=>{y.frameMode!==void 0&&(Q(""),he("")),Hi(M=>{const L=y.frameMode?Gh(y.frameMode):M.frameMode,F=y.frameMode!==void 0&&L!==M.frameMode,z=y.fps??(F?30:M.fps),pe=y.maxWidth??M.maxWidth,de=y.maxHeight??M.maxHeight;return{...M,...y,frameMode:L,fps:ms(z,20,L==="mode3-h264-hw"?60:30,L==="mode3-h264-hw"?60:30),maxWidth:L==="mode3-h264-hw"?pe:Math.min(1920,pe),maxHeight:L==="mode3-h264-hw"?de:Math.min(1080,de)}})},hr=y=>{const M=ph.find(L=>L.id===y);M&&xi({maxWidth:M.width,maxHeight:M.height})},bi=y=>{if(typeof window<"u"&&(y==="support"?window.history.pushState({},"","/support"):_t==="support"&&window.history.pushState({},"","/")),y==="control"){const M=Vn||Ki;if(M&&(Zt(!1),te(M.deviceId)),Ft(y),!It){_e(!1),Ie(Kr);return}_e(!0);return}y==="agents"&&Je(null),y==="wall"&&Ne(M=>M+1),Ft(y),_e(!1)},ks=fe==="update"||bt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(b?.update?.state||""),fl=!!(b?.update?.updateAvailable&&b.update.canApply||ks||!b&&bt),ml=u.useCallback(y=>{if(!bt?.targetIds.includes(y))return;if(bt.stage==="updated")return{state:"updated",label:"Updated"};if(bt.stage==="restored"||bt.stage==="failed")return{state:"failed",label:bt.stage==="restored"?"Update restored":"Update failed",error:bt.error};const M=b?.update?.operationId===bt.operationId?b.update.targets?.find(L=>L.deviceId===y):void 0;switch(M?.state){case"completed":return{state:"updated",label:"Updated"};case"failed":return{state:"failed",label:"Update failed",error:M.error||b?.update?.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return{state:"queued",label:"Queued"};case"waiting":return M.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."};default:return{state:"updating",label:"Verifying..."}}},[b?.update,bt]);return s.jsxs("main",{className:"app-shell",children:[s.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[s.jsx("div",{className:"rail-brand",title:"LiveDesk",children:s.jsx(ib,{size:25})}),s.jsx("nav",{className:"rail-tools",children:kT.map(y=>{const M=y.icon,L=Pd(y.tooltip,Fe);return s.jsxs("button",{className:`rail-tool ${y.id==="sync-server"?"sync-server":""} ${_t===y.id?"active":""} accent-${y.accent}`,onClick:()=>y.id==="sync-server"?void il({takeover:!0,requestLocalAccess:!0}):bi(y.id),"data-tooltip":Ah(y.label,y.tooltip,Fe),"aria-label":`${y.label}. ${L}`,type:"button",disabled:y.id==="sync-server"&&fe==="host","aria-busy":y.id==="sync-server"&&fe==="host",children:[y.id==="sync-server"&&fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(M,{size:19}),s.jsx("span",{children:y.id==="sync-server"&&fe==="host"?"Syncing…":y.label})]},y.id)})}),s.jsxs("div",{className:"rail-footer",children:[AT.map(y=>{const M=y.icon;return s.jsxs("button",{className:`rail-tool compact ${_t===y.id?"active":""} accent-${y.accent}`,onClick:()=>bi(y.id),title:y.label,type:"button",children:[s.jsx(M,{size:18}),s.jsx("span",{children:y.label})]},y.id)}),s.jsxs("button",{className:`rail-tool compact local-settings ${ts?"active":""}`,onClick:()=>{Ft("settings"),typeof window<"u"&&window.history.pushState({},"","/"),jn(!1),_e(!1),gt(!1)},title:"Settings",type:"button",children:[s.jsx(qx,{size:18}),s.jsx("span",{children:"Settings"})]}),s.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{jn(y=>!y)},disabled:a||fe==="auth","aria-expanded":Re,title:n?`Account: ${n.user?.email||vi}`:"Sign in with Google",type:"button",children:[n?os?s.jsx("img",{src:os,alt:vi,referrerPolicy:"no-referrer"}):s.jsx("span",{className:"avatar-fallback",children:dl}):s.jsx(Rl,{size:18}),s.jsx("span",{children:n?"Account":"Google"})]}),Re&&s.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[s.jsxs("div",{className:"account-popover-head",children:[s.jsx("div",{className:"account-popover-avatar",children:n&&os?s.jsx("img",{src:os,alt:vi,referrerPolicy:"no-referrer"}):n?s.jsx("span",{children:dl}):s.jsx(Rl,{size:18})}),s.jsxs("div",{children:[s.jsx("strong",{children:n?vi:"Account"}),s.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),s.jsxs("dl",{className:"account-popover-facts",children:[s.jsx("dt",{children:"User"}),s.jsx("dd",{children:n?.user?.email||"Not signed in"}),s.jsx("dt",{children:"Network"}),s.jsx("dd",{children:pu}),s.jsx("dt",{children:"Access"}),s.jsx("dd",{children:mr}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gi}),s.jsx("dt",{children:"Ads"}),s.jsx("dd",{children:Yt==="free"?"Standard banner":"Removed"})]}),n?s.jsxs("button",{className:"account-popover-action",onClick:rr,disabled:fe==="auth",type:"button",children:[s.jsx(Gx,{size:16}),"Logout"]}):s.jsxs("button",{className:"account-popover-action primary",onClick:ls,disabled:fe==="auth",type:"button",children:[s.jsx(Rl,{size:16}),"Sign in with Google"]})]})]})]}),s.jsxs("section",{className:`desk-stage ${Wi&&!st?"dock-open":""} ${at?"control-stage":""} ${Vr?"agents-stage":""}`,children:[s.jsxs("header",{className:"topbar",children:[s.jsxs("div",{className:"brand",children:[s.jsx("span",{className:"brand-mark",children:s.jsx(pn,{size:18})}),s.jsxs("div",{className:"brand-copy",children:[s.jsx("h1",{children:"LiveDesk"}),s.jsx("p",{children:"Control wall for local machines"})]}),fl?s.jsxs("button",{className:"topbar-update-button",onClick:()=>{rl()},title:bt?.error||`Update LiveDesk to ${b?.update?.latestVersion||bt?.targetManagerVersion||"latest"}`,"aria-label":ks?"LiveDesk update in progress":`Update LiveDesk to ${b?.update?.latestVersion||bt?.targetManagerVersion||"latest"}`,type:"button",disabled:ks||!b?.update?.canApply,"aria-busy":ks,children:[ks?s.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):s.jsx(Wh,{size:19,"aria-hidden":"true"}),ks&&b?.update?.targetCount?s.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[b.update.completedCount||0,"/",b.update.targetCount]}):null]}):null]}),s.jsxs("div",{className:"topbar-tray",children:[li&&!at&&s.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[s.jsxs("div",{children:[s.jsx(Ml,{size:17}),s.jsxs("span",{children:[s.jsx("small",{children:"Source"}),s.jsx("strong",{children:"LiveDesk Hub"})]})]}),s.jsx(Qh,{size:15}),s.jsx(d0,{size:16}),s.jsxs("div",{children:[s.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),s.jsxs("span",{children:[s.jsx("small",{children:"Destination"}),s.jsxs("strong",{children:[Zc," workstation",Zc===1?"":"s"]}),s.jsx("em",{children:zt.trim()||"Desktop/LiveDeskFiles"})]})]})]}),Wi&&!at&&s.jsxs("div",{className:"top-actions",children:[s.jsx(bx,{controller:Xi,onError:Ie}),s.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),s.jsx("div",{className:"segmented-control","aria-label":"Screen size",children:jT.map(y=>s.jsx("button",{className:ge===y.id?"active":"",onClick:()=>Oe(y.id),type:"button",children:y.label},y.id))})]}),at&&s.jsx("div",{className:"top-actions",children:s.jsx(bx,{controller:Xi,onError:Ie})})]})]}),Vi?s.jsxs("section",{className:"doc-page",lang:Fe,dir:Fe==="ar"?"rtl":"ltr",children:[s.jsxs("section",{className:"doc-hero",children:[s.jsxs("div",{className:"doc-hero-copy",children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(Bd,{size:16}),xn.eyebrow]}),s.jsx("h2",{children:xn.title}),s.jsx("p",{children:xn.intro})]}),s.jsxs("label",{className:"doc-language-picker",children:[s.jsxs("span",{children:[s.jsx(f0,{size:17}),xn.languageLabel]}),s.jsx("select",{value:Fe,onChange:y=>ke(y.target.value),children:MT.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),s.jsx("section",{className:"doc-grid",children:xn.sections.map((y,M)=>{const F=[El,Ld,Fm,Bt,Dl][M]||Bd;return s.jsxs("article",{className:"doc-card",children:[s.jsx("div",{className:"doc-card-icon",children:s.jsx(F,{size:19})}),s.jsxs("div",{children:[s.jsx("h3",{children:y.title}),s.jsx("p",{children:y.body}),s.jsx("ul",{children:y.points.map(z=>s.jsx("li",{children:z},z))})]})]},y.title)})}),dr&&s.jsxs("section",{className:"doc-sync",children:[s.jsxs("div",{className:"doc-sync-head",children:[s.jsx(Fm,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:dr.title}),s.jsx("p",{children:dr.body})]})]}),s.jsx("ul",{children:dr.points.map(y=>s.jsx("li",{children:y},y))})]}),s.jsxs("section",{className:"doc-firewall",children:[s.jsxs("div",{className:"doc-firewall-head",children:[s.jsx(Bt,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:xn.firewall.title}),s.jsx("p",{children:xn.firewall.body})]})]}),s.jsx("ul",{children:xn.firewall.points.map(y=>s.jsx("li",{children:y},y))})]}),s.jsxs("section",{className:"doc-command-panel",children:[s.jsxs("div",{className:"doc-command-head",children:[s.jsx(Ld,{size:20}),s.jsxs("div",{children:[s.jsx("h3",{children:xn.commands.title}),s.jsx("p",{children:xn.commands.body})]})]}),s.jsxs("div",{className:"doc-command-list",children:[xn.commands.manager&&s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:xn.commands.manager}),s.jsx("code",{children:ll}),s.jsx("button",{className:"icon-button",onClick:()=>Al(ll),title:"Copy command",type:"button",children:s.jsx(bl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:xn.commands.primary}),s.jsx("code",{children:Ss}),s.jsx("button",{className:"icon-button",onClick:()=>Al(Ss),title:"Copy command",type:"button",children:s.jsx(bl,{size:16})})]}),s.jsxs("div",{className:"doc-command-row",children:[s.jsx("span",{children:xn.commands.slot}),s.jsx("code",{children:`${Ss} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Al(`${Ss} 3`),title:"Copy command",type:"button",children:s.jsx(bl,{size:16})})]})]})]})]}):Vr?s.jsx(vx,{hubUrl:N,devices:C,launchRequest:Ve}):li?s.jsx(hN,{hubUrl:N,devices:et,localFeatureAccess:It,upgradeNotice:Kr,remoteDirectory:zt,onRemoteDirectoryChange:zn,targetMode:za,selectedTargetIds:ri,onTargetModeChange:Pi,onTargetToggle:y=>qr(M=>M.includes(y)?M.filter(L=>L!==y):[...M,y]),filePickerRef:Bo,folderPickerRef:$l,onBrowserFileImport:y=>{ha(y)},onBrowserFolderImport:y=>{ha(y)},onNotice:Ie,onTransferChange:y=>{if(!y){Fs(null);return}const M=y.state==="failed"||y.state==="partially-failed"||y.state==="cancelled"?"failed":y.state==="completed"?"queued":y.state==="sending"?"sending":"reading";Fs({id:y.id,status:M,progress:y.progress,message:y.message}),["completed","partially-failed","failed","cancelled"].includes(y.state)&&window.setTimeout(()=>Fs(L=>L?.id===y.id?null:L),4500)}}):Xc?s.jsx(tb,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:ls}):ts?s.jsx(Rj,{hubUrl:N,runtimeRole:b?.runtimeRole||"hub",runtimeDeviceId:b?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:s.jsxs(Dj,{children:[s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Pair a workstation"}),s.jsx("h3",{children:"Connect another local PC"})]}),s.jsx(an,{size:20})]}),s.jsxs("div",{className:"settings-pin-display",children:[s.jsx("span",{children:"Hub PIN"}),s.jsx("strong",{children:Jo}),s.jsxs("button",{className:"text-button ghost compact",onClick:Ca,disabled:!b?.started||fe==="pin",type:"button",children:[s.jsx(Ts,{size:15}),fe==="pin"?"Creating":"New PIN"]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Hub status"}),s.jsx("h3",{children:mu})]}),s.jsx("span",{className:`settings-status-dot state-${mu}`})]}),s.jsxs("dl",{className:"settings-facts",children:[s.jsx("dt",{children:"Address"}),s.jsx("dd",{children:N||"-"}),s.jsx("dt",{children:"Connected workstations"}),s.jsxs("dd",{children:[or,"/",Ul]}),s.jsx("dt",{children:"Sync access"}),s.jsx("dd",{children:b?.started?"Local app ready":"Start Hub first"}),s.jsx("dt",{children:"Plan"}),s.jsx("dd",{children:gi})]}),s.jsxs("div",{className:"settings-action-row",children:[s.jsxs("button",{className:"text-button primary",onClick:()=>il({takeover:!0,requestLocalAccess:!0}),disabled:!n||fe==="host",type:"button",children:[fe==="host"?s.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):s.jsx(Fm,{size:16}),fe==="host"?"Syncing…":"Sync access"]}),s.jsxs("button",{className:"text-button buy",onClick:()=>Ba(Yt==="ltd"?"pro":"ltd"),disabled:fe==="checkout"||Yt==="pro",type:"button",children:[s.jsx(Ao,{size:16}),fr]})]})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"File transfer"}),s.jsx("h3",{children:"Client destination folder"})]}),s.jsx(No,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Remote folder"}),s.jsx("input",{value:zt,onChange:y=>zn(y.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),s.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each workstation."})]})]}),wall:s.jsx(Lj,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall stream"}),s.jsx("h3",{children:"Frame delivery"})]}),s.jsx(Pc,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:He.frameMode,onChange:y=>Tn({frameMode:qh(y.target.value)}),children:Od.map(y=>s.jsxs("option",{value:y.id,children:[y.label," - ",y.detail]},y.id))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:He.h264DecodeAcceleration,onChange:y=>Tn({h264DecodeAcceleration:Zd(y.target.value)}),children:Uh.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:He.fps,onChange:y=>Tn({fps:Vh(y.target.value,He.frameMode)}),children:yp.filter(y=>y<=xw(He.frameMode)).map(y=>s.jsx("option",{value:y,children:y},y))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:ft?"Atlas tile":"Resolution"}),s.jsx("select",{value:ft?io:so,onChange:y=>ft?yu(y.target.value):yi(y.target.value),children:(ft?gh:Hd).map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:He.quality,onChange:y=>Tn({quality:ms(y.target.value,20,95,va.quality)}),children:Dx.map(y=>s.jsx("option",{value:y,children:y},y))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Wall behavior"}),s.jsx("h3",{children:"Visibility and load"})]}),s.jsx(pn,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:He.autoStartLive,onChange:y=>Tn({autoStartLive:y.target.checked})}),s.jsx("span",{children:"Auto live on connected screens"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:He.visibleOnlyLive,onChange:y=>Tn({visibleOnlyLive:y.target.checked})}),s.jsx("span",{children:"Stream visible tiles first"})]}),!ft&&s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:He.adaptiveSizeByWall,onChange:y=>Tn({adaptiveSizeByWall:y.target.checked})}),s.jsx("span",{children:"Fit stream size to Wall"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:He.adaptiveLoadShedding,onChange:y=>Tn({adaptiveLoadShedding:y.target.checked})}),s.jsx("span",{children:"Reduce FPS under load"})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:He.showScreenStatus,onChange:y=>Tn({showScreenStatus:y.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary",children:[s.jsx("span",{children:vu.label}),s.jsxs("strong",{children:[On.maxWidth,"x",On.maxHeight," / ",Pe,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>ya(va),type:"button",children:[s.jsx(_c,{size:15})," Reset Wall settings"]})]})]})}),control:s.jsx(_j,{children:s.jsxs("div",{className:"settings-section-grid",children:[s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control stream"}),s.jsx("h3",{children:"Low-latency delivery"})]}),s.jsx(Dd,{size:20})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Frame mode"}),s.jsx("select",{value:dt.frameMode,onChange:y=>xi({frameMode:Gh(y.target.value)}),children:UM.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]}),dt.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"H.264 decode"}),s.jsx("select",{value:dt.h264DecodeAcceleration,onChange:y=>xi({h264DecodeAcceleration:Zd(y.target.value)}),children:Uh.map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]}),s.jsxs("div",{className:"settings-field-grid",children:[s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"FPS"}),s.jsx("select",{value:dt.fps,onChange:y=>xi({fps:ms(y.target.value,20,60,Ra.fps)}),children:qM.filter(y=>dt.frameMode==="mode3-h264-hw"||y<=30).map(y=>s.jsx("option",{value:y,children:y},y))})]}),s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Resolution"}),s.jsx("select",{value:gu,onChange:y=>hr(y.target.value),children:ph.filter(y=>dt.frameMode==="mode3-h264-hw"||y.width<=1920).map(y=>s.jsx("option",{value:y.id,children:y.label},y.id))})]})]}),dt.frameMode==="mode3-h264-hw"&&s.jsxs("label",{className:"settings-field",children:[s.jsx("span",{children:"Quality"}),s.jsx("select",{value:dt.quality,onChange:y=>xi({quality:ms(y.target.value,20,95,Ra.quality)}),children:Dx.map(y=>s.jsx("option",{value:y,children:y},y))})]})]}),s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Control behavior"}),s.jsx("h3",{children:"Session display"})]}),s.jsx(an,{size:20})]}),s.jsxs("label",{className:"settings-toggle",children:[s.jsx("input",{type:"checkbox",checked:dt.showScreenStatus,onChange:y=>xi({showScreenStatus:y.target.checked})}),s.jsx("span",{children:"Screen status overlay"})]}),s.jsxs("div",{className:"settings-summary control",children:[s.jsx("span",{children:dt.frameMode==="mode5-lzo-delta"?"Mode 5 tile delta":"Mode 3 H.264"}),s.jsxs("strong",{children:[$s.maxWidth,"x",$s.maxHeight," / ",Yi,"fps"]})]}),s.jsxs("button",{className:"settings-reset",onClick:()=>Hi(Ra),type:"button",children:[s.jsx(_c,{size:15})," Reset Control settings"]})]})]})}),agent:s.jsx(zj,{hubUrl:N}),captureGallery:s.jsx(pM,{hubUrl:N,onToast:Ie}),advancedExtras:s.jsxs("section",{className:"settings-section-card",children:[s.jsxs("div",{className:"settings-section-heading",children:[s.jsxs("div",{children:[s.jsx("span",{children:"Connection commands"}),s.jsx("h3",{children:"Developer setup"})]}),s.jsx(bl,{size:20})]}),s.jsxs("div",{className:"settings-command-list",children:[s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Client"}),s.jsx("code",{children:Ss}),s.jsx("button",{className:"icon-button",onClick:()=>Al(Ss),title:"Copy client command",type:"button",children:s.jsx(bl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Slot example"}),s.jsx("code",{children:`${Ss} 3`}),s.jsx("button",{className:"icon-button",onClick:()=>Al(`${Ss} 3`),title:"Copy slot command",type:"button",children:s.jsx(bl,{size:16})})]}),s.jsxs("div",{className:"settings-command-row",children:[s.jsx("span",{children:"Hub"}),s.jsx("code",{children:ll}),s.jsx("button",{className:"icon-button",onClick:()=>Al(ll),title:"Copy Hub command",type:"button",children:s.jsx(bl,{size:16})})]})]})]})}):Gr?s.jsxs("section",{className:"pricing-page",children:[s.jsxs("header",{className:"pricing-header",children:[s.jsxs("div",{children:[s.jsxs("span",{className:"pricing-eyebrow",children:[s.jsx(Ch,{size:15})," LiveDesk plans"]}),s.jsx("h2",{children:"Choose the plan that fits your wall"}),s.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more workstations, or commercial controls."})]}),s.jsx("button",{className:"pricing-close",onClick:()=>bi("wall"),title:"Close pricing",type:"button",children:s.jsx(Ya,{size:18})})]}),s.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[s.jsx("span",{children:"Current plan"}),s.jsx("strong",{children:au.name}),s.jsxs("small",{children:[et.length,"/",$M(Gl)," connected devices"]})]}),s.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[s.jsxs("article",{className:`pricing-plan-card ${Yt==="free"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),s.jsx("strong",{children:"$0"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Cl.free.audience}),s.jsx("h3",{children:"Monitor your local wall"}),s.jsx("p",{children:Cl.free.note}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Fn,{size:16})," Up to ",Ec," devices"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," Live view and local control"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," Standard ad-supported banner"]})]}),s.jsx("span",{className:"pricing-current-label",children:Yt==="free"?"Current plan":"Included for everyone"})]}),s.jsxs("article",{className:`pricing-plan-card featured ${Yt==="ltd"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge plus",children:[s.jsx(m0,{size:14})," Plus"]}),s.jsx("strong",{children:"$5"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Cl.ltd.audience}),s.jsx("h3",{children:"Ad-free monitoring"}),s.jsx("p",{children:"More room for personal AI workstations without the standard banner."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Fn,{size:16})," Up to ",Rc," devices"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," No standard ad banner"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," ",Cl.ltd.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Ba("ltd"):ls,disabled:Yt!=="free"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Ao,{size:16}),Yt==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),s.jsxs("article",{className:`pricing-plan-card pro ${Yt==="pro"?"current":""}`,children:[s.jsxs("div",{className:"pricing-plan-topline",children:[s.jsxs("span",{className:"pricing-plan-badge pro",children:[s.jsx(Bt,{size:14})," Pro"]}),s.jsx("strong",{children:"$15"})]}),s.jsx("p",{className:"pricing-plan-audience",children:Cl.pro.audience}),s.jsx("h3",{children:"For serious operations"}),s.jsx("p",{children:"Commercial-ready monitoring for larger AI labs, studios, and teams."}),s.jsxs("ul",{children:[s.jsxs("li",{children:[s.jsx(Fn,{size:16})," 30+ workstation walls"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," Commercial use included"]}),s.jsxs("li",{children:[s.jsx(Fn,{size:16})," ",Cl.pro.ltd]})]}),s.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>Ba("pro"):ls,disabled:Yt==="pro"||fe==="checkout"||fe==="auth"||a||R,type:"button",children:[s.jsx(Ao,{size:16}),Yt==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),s.jsxs("section",{className:"pricing-includes",children:[s.jsxs("div",{children:[s.jsx(an,{size:17}),s.jsx("span",{children:"Screen wall"}),s.jsx("strong",{children:"120+ slots"})]}),s.jsxs("div",{children:[s.jsx(Dd,{size:17}),s.jsx("span",{children:"Focused control"}),s.jsx("strong",{children:"Local-first"})]}),s.jsxs("div",{children:[s.jsx(ry,{size:17}),s.jsx("span",{children:"Remote audio"}),s.jsx("strong",{children:"Available"})]}),s.jsxs("div",{children:[s.jsx(No,{size:17}),s.jsx("span",{children:"File transfer"}),s.jsx("strong",{children:"Included"})]})]}),s.jsxs("p",{className:"pricing-note",children:[s.jsx(Fn,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),s.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>Ba(Yt==="ltd"?"pro":"ltd"):ls,disabled:yf,type:"button",children:[s.jsx(Ao,{size:18}),hu]})]}):s.jsx(s.Fragment,{children:s.jsxs("section",{className:`monitor-layout ${st?"dock-collapsed":""}`,children:[s.jsxs("section",{ref:$i,className:`screen-wall-panel ${Fl?"drop-active":""}`,onClick:y=>{y.currentTarget===y.target&&sa()},onDragEnter:y=>{y.preventDefault(),_a(!0)},onDragOver:y=>{y.preventDefault(),y.dataTransfer.dropEffect="copy"},onDragLeave:y=>{y.currentTarget===y.target&&_a(!1)},onDrop:Qo,children:[da.length>0&&s.jsx("canvas",{ref:lu,className:"atlas-source-canvas",width:ma?.width||1920,height:ma?.height||1080,"aria-hidden":"true"}),at?s.jsx("section",{className:"control-focus",children:s.jsxs("div",{className:"control-wall",children:[Ee&&Qs.length>1&&s.jsx("div",{className:"control-monitor-tabs","aria-label":"Select monitor",children:Qs.map(y=>s.jsxs("button",{className:y.index===cr?"active":"",onClick:()=>du(Ee.deviceId,y.index),title:iT(y),type:"button",children:[s.jsx("span",{children:y.name||`Display ${y.index+1}`}),y.width>0&&y.height>0&&s.jsxs("small",{children:[y.width,"x",y.height]})]},y.index))}),Ee?s.jsx(Sh,{device:Ee,frame:Me,selected:!1,controlEnabled:ns&&Se&&Ks,showStatus:dt.showScreenStatus,monitorIndex:Ea(Qt[Ee.deviceId],ga(Ee)),monitorCount:ga(Ee),onSelect:()=>{},onFocusDevice:()=>te(Ee.deviceId),onOpenControl:()=>lr(Ee.deviceId),onCycleMonitor:y=>Ha(Ee.deviceId,y),onCanvasReady:hf,sendInput:ir,presentationReady:Za},Ee.deviceId):s.jsxs("div",{className:"control-empty",children:[s.jsx(an,{size:30}),s.jsx("strong",{children:"No workstation"}),s.jsx("span",{children:"Open a workstation from the Wall."})]}),Ee&&ql&&s.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[s.jsx(Bt,{size:22,"aria-hidden":"true"}),s.jsx("strong",{children:"Accessibility permission required"}),s.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),Ee&&!ql&&!Za&&s.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[q!=="error"&&s.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),s.jsx("strong",{children:q==="error"?"Connection failed":"Connecting"}),s.jsx("small",{children:q==="error"?"See the notification for details. Reopen Control to retry.":nl||ue?"Control stream is recovering. See the notification for details.":ar==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):ft?s.jsx("div",{className:`screen-wall atlas-slot-wall size-${ge}`,onClick:y=>{y.currentTarget===y.target&&sa()},children:Wr.map((y,M)=>y?s.jsx(Sh,{device:y,frame:Jn.get(y.deviceId),selected:oi.has(y.deviceId),controlEnabled:!1,showStatus:He.showScreenStatus,monitorIndex:Ea(Qt[y.deviceId],ga(y)),monitorCount:ga(y),onSelect:()=>bs(y.deviceId),onFocusDevice:()=>aa(y.deviceId),onOpenControl:()=>lr(y.deviceId),onCycleMonitor:L=>Ha(y.deviceId,L),onCanvasReady:Nc({mode4Enabled:ft,directMode4WallEnabled:as,isMac:zi(y.platform)})==="direct"?iu:ou,sendInput:ir,updateIndicator:ml(y.deviceId),presentationReady:He.autoStartLive&&In.includes(y.deviceId)?qe.has(y.deviceId):void 0,showPresentationSpinner:He.autoStartLive&&In.includes(y.deviceId)},y.deviceId):s.jsx(Px,{index:M},`slot-${M}`))}):s.jsx("div",{className:`screen-wall size-${ge}`,onClick:y=>{y.currentTarget===y.target&&sa()},children:Wr.map((y,M)=>y?s.jsx(Sh,{device:y,frame:Jn.get(y.deviceId),selected:oi.has(y.deviceId),controlEnabled:ns&&Se&&Ks&&Ee?.deviceId===y.deviceId,showStatus:He.showScreenStatus,monitorIndex:Ea(Qt[y.deviceId],ga(y)),monitorCount:ga(y),onSelect:()=>bs(y.deviceId),onFocusDevice:()=>aa(y.deviceId),onOpenControl:()=>lr(y.deviceId),onCycleMonitor:L=>Ha(y.deviceId,L),onCanvasReady:iu,sendInput:ir,updateIndicator:ml(y.deviceId),presentationReady:He.autoStartLive&&In.includes(y.deviceId)?qe.has(y.deviceId):void 0,showPresentationSpinner:He.autoStartLive&&In.includes(y.deviceId)},y.deviceId):s.jsx(Px,{index:M},`slot-${M}`))}),s.jsx(RT,{visible:su&&!at})]}),!ts&&s.jsxs("aside",{className:`right-dock actions-mode ${st?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[s.jsx("button",{className:"dock-toggle",onClick:()=>gt(y=>!y),"aria-label":st?"Show control panel":"Hide control panel",title:st?"Show control panel":"Hide control panel",type:"button",children:st?s.jsx(Jx,{size:18}):s.jsx(Xh,{size:18})}),!st&&s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"action-dock",children:[s.jsx("input",{ref:vs,className:"hidden-file-input",type:"file",multiple:!0,onChange:y=>{y.currentTarget.files&&ws(y.currentTarget.files),y.currentTarget.value=""}}),s.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual workstation controls",children:[s.jsx(Dr,{label:"Control",tooltip:Ee?ql?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ns?Ks?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this workstation":"Select a workstation to use Control",onClick:()=>{if(Ee){if(at&&Se){_e(!1),Ie("Remote control paused. Screen viewing stays on.");return}lr(Ee.deviceId)}},disabled:!ns||!!Te,active:Se,pressed:at&&Se,children:s.jsx(Dd,{size:17})}),s.jsx(Dr,{label:"Audio",tooltip:Ee?Yr?re?"Stop hearing this workstation":"Hear this workstation":"Audio is not available on this workstation":"Select a workstation to use Audio",onClick:()=>{Ko()},disabled:!$o||!!Te,active:re,pressed:re,children:Te==="audio"?s.jsx(Js,{className:"spin",size:17}):s.jsx(ry,{size:17})}),s.jsx(Dr,{label:"Send files",tooltip:ua.length===0&&!at?"Select one or more workstations to send files":Ee?"Choose files and send them to the selected workstation":"Select a workstation to send files",onClick:()=>{Ie(`Choose files to send to ${Xo}.`),vs.current?.click()},disabled:!!Te||!It||(at?!Ee:ua.length===0),children:s.jsx(No,{size:17})}),s.jsx(Dr,{label:"Run command",tooltip:Ee?nu?"Run command":"Command runner is not available on this workstation":"Select a workstation to run a command",onClick:Gt,disabled:!Ee||!It||!!Te||!nu,children:s.jsx(Ld,{size:17})}),s.jsx(Dr,{label:"Restart",tooltip:Ee?tu?"Restart workstation":"Restart is not available on this workstation":"Select a workstation to restart",onClick:()=>{un("restart")},disabled:!Ee||!It||!!Te||!tu,children:Te==="restart"?s.jsx(Js,{className:"spin",size:17}):s.jsx(_c,{size:17})}),s.jsx(Dr,{label:"Lock",tooltip:Ee?"Lock workstation":"Select a workstation to lock",onClick:()=>{un("lock")},disabled:!Ee||!It||!!Te,children:Te==="lock"?s.jsx(Js,{className:"spin",size:17}):s.jsx(Ts,{size:17})}),s.jsx(Dr,{label:"Sleep",tooltip:Ee?"Put workstation to sleep":"Select a workstation to put to sleep",onClick:()=>{un("sleep")},disabled:!Ee||!It||!!Te,children:Te==="sleep"?s.jsx(Js,{className:"spin",size:17}):s.jsx(h0,{size:17})}),s.jsx(Dr,{label:"Shut down",tooltip:Ee?"Shut down workstation":"Select a workstation to shut down",onClick:()=>{un("shutdown")},disabled:!Ee||!It||!!Te,danger:!0,children:Te==="shutdown"?s.jsx(Js,{className:"spin",size:17}):s.jsx(p0,{size:17})})]})]}),s.jsx(vx,{hubUrl:N,devices:C,variant:"dock",selectedDeviceIds:ul})]})]})]})})]}),ii&&s.jsxs("aside",{className:`transfer-bar state-${ii.status}`,"aria-live":"polite",children:[s.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:ii.status==="queued"?s.jsx(Fn,{size:18}):ii.status==="failed"?s.jsx(Ya,{size:18}):s.jsx(Qx,{size:18})}),s.jsxs("div",{className:"transfer-bar-copy",children:[s.jsx("p",{children:ii.message}),s.jsx("div",{className:"transfer-bar-track",children:s.jsx("span",{style:{width:`${Math.max(0,Math.min(100,ii.progress))}%`}})})]}),s.jsxs("strong",{children:[Math.max(0,Math.min(100,ii.progress)),"%"]})]}),We&&s.jsxs("aside",{className:`livedesk-toast tone-${We.tone}`,role:We.tone==="error"?"alert":"status","aria-live":We.tone==="error"?"assertive":"polite","aria-busy":We.tone==="progress",children:[We.tone==="progress"&&s.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),s.jsx("span",{children:We.message}),s.jsx("button",{className:"livedesk-toast-close",onClick:()=>Ie(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:s.jsx(Ya,{size:15})})]})]})}function LT(){if(typeof window>"u")return[];const n=window.location.origin;return window.location.port==="5179"?[n]:["http://127.0.0.1:5179"]}function _T(){const[a,r]=u.useState(null);return u.useEffect(()=>{let l=!1,c=!1;const d=async()=>{for(const g of LT())try{const v=await fetch(`${g}/api/runtime`,{cache:"no-store"});if(!v.ok)continue;const x=(await v.json()).role==="hub"?"hub":"client";c=!0,l||r(x);return}catch{}};d();const m=window.setInterval(()=>{d()},1e3),p=window.setTimeout(()=>{!l&&!c&&r("client")},2500);return()=>{l=!0,window.clearInterval(m),window.clearTimeout(p)}},[null]),a?a==="client"?s.jsx(bC,{}):s.jsx(DT,{}):s.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[s.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),s.jsx("strong",{children:"Starting LiveDesk"}),s.jsx("p",{children:"Loading this computer's assigned role..."})]})}C0.createRoot(document.getElementById("root")).render(s.jsx(u.StrictMode,{children:s.jsx(_T,{})}));
|