livedesk 0.1.538 → 0.1.539
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.
|
@@ -174,9 +174,9 @@ registerProcessor(
|
|
|
174
174
|
LiveDeskRemoteAudioProcessor
|
|
175
175
|
);
|
|
176
176
|
`;function z1({eligibleCandidates:t,fallbackHubBaseUrl:n,publicConsole:r,authenticated:o}){const l=[...new Set((Array.isArray(t)?t:[]).map(f=>String(f||"").trim()).filter(Boolean))];if(l.length>0)return Object.freeze({candidates:Object.freeze(l),transport:"auto",reason:"direct-candidate"});const u=String(n||"").trim();return Object.freeze(r&&o&&u?{candidates:Object.freeze([u]),transport:"relay",reason:"authenticated-public-console-fallback"}:{candidates:Object.freeze([]),transport:"auto",reason:"unavailable"})}const aw="livedesk_remote_host_targets",$1="livedesk_entitlements",rw=4e3,U1=2500,Pv=new TextDecoder,cv=new Set;function q1(){const t=[...cv].map(r=>r()),n=r=>t.reduce((o,l)=>o+Number(l[r]||0),0);return{ownerCount:t.length,activeOwnerCount:t.filter(r=>r.active).length,socketCount:n("socketCount"),openSocketCount:n("openSocketCount"),connectingSocketCount:n("connectingSocketCount"),closingSocketCount:n("closingSocketCount"),closingSocketTimerCount:n("closingSocketTimerCount"),closingSocketTimeoutCount:n("closingSocketTimeoutCount"),expectedBindingCount:n("expectedBindingCount"),reconnectTimerCount:n("reconnectTimerCount"),statsTimerCount:n("statsTimerCount"),configurationRefreshTimerCount:n("configurationRefreshTimerCount"),restartTokenCount:n("restartTokenCount"),retainedFrameCount:n("retainedFrameCount"),retainedPayloadBytes:n("retainedPayloadBytes"),owners:t}}function W1(){return pa.snapshot()}function G1(t){const r=(Array.isArray(t)?t:[t||Un]).map(o=>cu(o||Un));return[...new Set(r.filter(Boolean))]}function V1(){const[t,n]=d.useState(null),[r,o]=d.useState(!0);return d.useEffect(()=>{let l=!0;const u=window.liveDesk?.auth?.onComplete?.(h=>{h.ok&&h.session&&$t.auth.setSession(h.session)});(window.liveDesk?.auth?.getSession?.()||$t.auth.getSession()).then(h=>{l&&(n(s0(h)),o(!1))});const{data:{subscription:f}}=$t.auth.onAuthStateChange((h,g)=>{n(g),o(!1),window.liveDesk?.auth?.persistSession?.(g)});return()=>{l=!1,u?.(),f.unsubscribe()}},[]),{session:t,loading:r}}function K1(t,n=!0,r=""){const[o,l]=d.useState(null),[u,f]=d.useState([]),[h,g]=d.useState(""),[y,w]=d.useState(""),b=d.useRef(new Map),S=d.useRef(null),k=Array.isArray(t)?t.join(`
|
|
177
|
-
`):String(t||""),N=d.useMemo(()=>G1(t),[k]),A=d.useMemo(()=>N.find(T=>Yf(T)==="loopback")||N[0]||Un,[N]),j=d.useCallback(async T=>{if(!n){l(null),f([]),w(""),g("");return}let _=null;const B=Date.now(),F=N.filter(D=>(b.current.get(D)||0)<=B),H=z1({eligibleCandidates:F,fallbackHubBaseUrl:A,publicConsole:Av(),authenticated:!!r});if(H.candidates.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const D of H.candidates)try{const[K,z]=await Promise.all([rt("/api/remote/status",{signal:T,timeoutMs:rw,transport:H.transport},D),rt("/api/remote/devices",{signal:T,timeoutMs:rw,transport:H.transport},D)]);if(T?.aborted)throw T.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(z.devices))throw new Error("Invalid Hub devices response.");b.current.delete(D),l(K),f(z.devices),w(D),g("");return}catch(K){if(T?.aborted)throw K;_=K,H.transport==="auto"&&b.current.set(D,Date.now()+1e4)}throw w(""),_||new Error("No LiveDesk Hub endpoint is reachable.")},[r,n,A,N]),I=d.useCallback(()=>{b.current.clear(),Up(S,()=>j()).catch(T=>{g(T instanceof Error?T.message:String(T))})},[j]);return d.useEffect(()=>{if(b.current.clear(),!n){l(null),f([]),w(""),g("");return}let T=!0,_=null;const B=new AbortController,F=()=>{Up(S,()=>j(B.signal)).catch(D=>{T&&!B.signal.aborted&&g(D instanceof Error?D.message:String(D))}).finally(()=>{T&&!B.signal.aborted&&(_=window.setTimeout(F,U1))})};return F(),()=>{T=!1,B.abort(new Error("LiveDesk Hub snapshot polling stopped.")),_!==null&&window.clearTimeout(_)}},[n,j]),{status:o,devices:u,error:h,refresh:I,hubBaseUrl:y||A,hubCandidates:N}}function Q1(t){const[n,r]=d.useState(null),[o,l]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await $t.from(aw).select("*").eq("user_id",u).maybeSingle();if(g){l(g.message);return}r(h),l("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=$t.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:aw,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{$t.removeChannel(h)}},[u]),{target:n,error:o,refresh:f}}function Y1(t){const[n,r]=d.useState(null),[o,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await $t.from($1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:o,error:u,refresh:g}}const Zf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},X1=2500,Z1=3e4,J1=64*1024,eN=64*1024,tN=6,nN=tN,V0=new Map;function aN(t){return V0.get(t)}const sw={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function rN(t,n,r){const o=Number(n);if(!Number.isFinite(o)||o<=0)return 0;const l=r-o,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>Z1?(t.minimumHubClockOffsetMs=l,0):f}function vt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const sN=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function iN(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&sN.every(n=>vt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function oN(t,n,r){if(!t||typeof t!="object")return null;const o=t,l=String(o.deviceId||n||"").trim(),u=String(o.sessionId||"").trim(),f=String(o.streamId||"").trim(),h=o.streamPurpose==="control"?"control":o.streamPurpose==="wall"?"wall":null,g=String(o.commandId||"").trim(),y=Number(o.captureGeneration||0),w=Number(o.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function iw(t,n,r=Un,o={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(Zf),S=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(new Map),A=d.useRef(null);A.current===null&&(A.current=m1());const j=d.useRef(0),I=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),_=d.useRef(new Map),B=d.useRef(null),F=d.useRef(new Map),[H,D]=d.useState(0),K=d.useRef(o.onFrame),z=d.useRef(o.onStreamReady),W=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),q=d.useMemo(()=>[...t].sort().join(","),[t]),V=n&&q.length>0,X=d.useRef(!1);d.useLayoutEffect(()=>(X.current=V,()=>{X.current=!1}),[V]);const ve=Number.isFinite(o.fps)?Number(o.fps):2,J=Number.isFinite(o.maxWidth)?Number(o.maxWidth):640,$=Number.isFinite(o.maxHeight)?Number(o.maxHeight):360,P=Number.isFinite(o.quality)?Number(o.quality):45,se=Number.isFinite(o.configurationRefreshMs)?Math.max(0,Math.round(Number(o.configurationRefreshMs))):0,we=String(o.frameMode||o.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",Z=o.streamPurpose==="control"?"control":"wall",Se=o.forceRestart===!0,ae=String(o.forceRestartToken||"").trim(),ye=String(o.restartReason||"").trim();T.current={enabled:Se,token:ae,reason:ye};const Pe=d.useMemo(()=>{const Me=Object.entries(o.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[qe])=>pe.localeCompare(qe));return JSON.stringify(Object.fromEntries(Me))},[o.monitorSelections]),de=d.useMemo(()=>{const Me=Object.entries(o.connectionSessionIds||{}).filter(([pe])=>!!pe).map(([pe,qe])=>[pe,String(qe||"").trim()]).sort(([pe],[qe])=>pe.localeCompare(qe));return JSON.stringify(Object.fromEntries(Me))},[o.connectionSessionIds]);d.useEffect(()=>{K.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{z.current=o.onStreamReady},[o.onStreamReady]);const Qe=d.useCallback((Me,pe="livedesk-frame-socket-release")=>{p1(Me,pe,A.current)},[]),ue=d.useCallback(Me=>{const pe=_.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),_.current.delete(Me))},[]),_e=d.useCallback(Me=>{const pe=F.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),F.current.delete(Me))},[]),Ze=d.useCallback((Me,pe=!0)=>{for(const qe of _.current.values())window.clearTimeout(qe);_.current.clear();for(const qe of F.current.values())window.clearTimeout(qe);F.current.clear();for(const qe of N.current.values())qe.expectedBinding=void 0,Qe(qe,Me);N.current.clear(),I.current.clear(),S.current=new Map,k.current.clear(),W.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(Zf),h("idle"))},[Qe]),at=d.useCallback(()=>{const Me=[...N.current.values()].map(pe=>pe.socket);if(Me.length===0){h("idle");return}if(Me.some(pe=>pe.readyState===WebSocket.OPEN)){h("open");return}if(Me.some(pe=>pe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),Ee=d.useCallback((Me,pe,qe,Re)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[Me],forceRestart:!0,restartReason:qe,restartToken:Re})),pe.expectedBinding=void 0,ew(pe.sparseTelemetry),!0}catch{return!1}},[]),Ge=d.useCallback((Me,pe)=>{if(pe.disposed||N.current.get(Me)!==pe||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"refresh-live",deviceIds:[Me],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{pe.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),me=d.useCallback((Me,pe)=>{if(!X.current||pe.disposed||!Me||Me.byteLength<5)return;const qe=Date.now(),st=new DataView(Me).getUint32(0,!1);if(st<=0||st+4>Me.byteLength)return;const jt=new Uint8Array(Me,4,st),O=JSON.parse(Pv.decode(jt));b1(O,pe.sparseTelemetry,pe.expectedBinding);const ze=vt(O.hubPacketEpochMs),We=ze!==void 0&&ze>0?ze:void 0,Et=rN(pe,We,qe);if(Et>X1)return;const lt=new Uint8Array(Me,4+st),ht=vt(O.nativeCaptureTelemetryVersion),Je=vt(O.nativeCaptureTelemetryAgeMs),be=vt(O.hubClientDropped),je=vt(O.hubClientQueueDepth),Ae=vt(O.hubClientQueueLimit),fe=vt(O.hubClientBufferedBytes),te=be!==void 0&&je!==void 0&&Ae!==void 0&&fe!==void 0,ce={deviceId:String(O.deviceId||""),kind:O.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(O.frameSeq||0),streamFrameSeq:Number(O.streamFrameSeq||0)||void 0,streamId:String(O.streamId||""),commandId:O.commandId?String(O.commandId):void 0,sessionId:O.sessionId?String(O.sessionId):void 0,captureGeneration:Number(O.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:O.streamPurpose?String(O.streamPurpose):void 0,width:Number(O.width||0),height:Number(O.height||0),sourceWidth:Number(O.sourceWidth||0)||void 0,sourceHeight:Number(O.sourceHeight||0)||void 0,mimeType:String(O.mimeType||"image/jpeg"),mode:O.mode?String(O.mode):void 0,frameMode:O.frameMode?String(O.frameMode):void 0,frameProfile:O.frameProfile?String(O.frameProfile):void 0,encoding:O.encoding?String(O.encoding):void 0,codec:O.codec?String(O.codec):void 0,compression:O.compression?String(O.compression):void 0,pixelFormat:O.pixelFormat?String(O.pixelFormat):void 0,bytesPerPixel:Number(O.bytesPerPixel||0)||0,uncompressedByteLength:Number(O.uncompressedByteLength||0)||0,h264Format:O.h264Format?String(O.h264Format):void 0,isKeyFrame:O.isKeyFrame===!0,chunkType:O.chunkType?String(O.chunkType):void 0,timestampUs:Number(O.timestampUs||0)||0,durationUs:Number(O.durationUs||0)||0,sourceGapMs:Number(O.sourceGapMs||0)||0,agentSendGapMs:Number(O.agentSendGapMs||0)||0,agentSendDurationMs:Number(O.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(O.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(O.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(O.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(O.agentFrameAgeMs||0)||0,inputFeedbackEventId:O.inputFeedbackEventId?String(O.inputFeedbackEventId):void 0,inputFeedbackInputSeq:vt(O.inputFeedbackInputSeq),inputFeedbackInputType:O.inputFeedbackInputType?String(O.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:vt(O.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:vt(O.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:vt(O.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:vt(O.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:vt(O.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:vt(O.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:vt(O.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof O.inputFeedbackCaptureTimestampAvailable=="boolean"?O.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof O.nativeCaptureTelemetryAvailable=="boolean"?O.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:ht===void 0?void 0:Math.max(0,ht),nativeCaptureTelemetryAgeMs:Je===void 0?void 0:Math.max(0,Je),nativeEncoderHardwareAccelerationKnown:typeof O.nativeEncoderHardwareAccelerationKnown=="boolean"?O.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof O.nativeEncoderHardwareAccelerated=="boolean"?O.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:O.nativeEncoderHardwareQueryStatus?String(O.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:vt(O.nativeCaptureDisplayId),nativeCaptureFps:vt(O.nativeCaptureFps),nativeCompressionFps:vt(O.nativeCompressionFps),nativeEncodedFps:vt(O.nativeEncodedFps),nativeCaptureSampleCount:vt(O.nativeCaptureSampleCount),nativeEncodableFrameCount:vt(O.nativeEncodableFrameCount),nativeSkippedFrameCount:vt(O.nativeSkippedFrameCount),nativeCompressionOutputCount:vt(O.nativeCompressionOutputCount),nativeEncodedFrameCount:vt(O.nativeEncodedFrameCount),nativeEncodeFramesInFlight:vt(O.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:vt(O.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:vt(O.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:vt(O.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:vt(O.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:vt(O.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:vt(O.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:vt(O.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:vt(O.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:vt(O.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:vt(O.nativeOutputQueueDepth),nativeOutputQueueBytes:vt(O.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:vt(O.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:vt(O.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:vt(O.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof O.nativeOutputQueueAwaitingKeyFrame=="boolean"?O.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof O.nativeCopyTelemetryAvailable=="boolean"?O.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:vt(O.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:vt(O.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:vt(O.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:vt(O.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:vt(O.pipePayloadAllocationCount),pipePayloadCopyCount:vt(O.pipePayloadCopyCount),pipePayloadCopiedBytes:vt(O.pipePayloadCopiedBytes),handoffDroppedFrameCount:vt(O.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:vt(O.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:vt(O.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:O.nativeCaptureResourceTelemetryAvailable===!0?iN(O):O.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:O.nativeCaptureTelemetryAt?String(O.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(O.droppedByAgent||0)||0,hubIngressDropped:Number(O.hubIngressDropped||0)||0,hubClientDropped:be,transport:O.transport?String(O.transport):void 0,videoTransport:O.videoTransport?String(O.videoTransport):void 0,frameTransportActive:O.frameTransportActive?String(O.frameTransportActive):void 0,frameTransportProtocol:O.frameTransportProtocol?String(O.frameTransportProtocol):void 0,frameTransportState:O.frameTransportState?String(O.frameTransportState):void 0,frameTransportReason:O.frameTransportReason?String(O.frameTransportReason):void 0,frameTransportChangedAt:O.frameTransportChangedAt?String(O.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(O.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(O.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:O.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:te,hubClientQueueDepth:je,hubClientQueueLimit:Ae,hubClientBufferedBytes:fe,udpIncompleteFrames:Number(O.udpIncompleteFrames||0)||0,hardwareEncoder:O.hardwareEncoder?String(O.hardwareEncoder):void 0,platformProfile:O.platformProfile?String(O.platformProfile):void 0,monitorIndex:Number.isFinite(Number(O.monitorIndex))?Number(O.monitorIndex):void 0,monitorCount:Number.isFinite(Number(O.monitorCount))?Number(O.monitorCount):void 0,requestedFps:Number(O.requestedFps||0)||0,effectiveFps:Number(O.effectiveFps||0)||0,captureTimingAvailable:O.captureTimingAvailable===!0,captureAverageMs:vt(O.captureAverageMs),captureP95Ms:vt(O.captureP95Ms),slowFrameCount:Number(O.slowFrameCount||0)||0,captureHelperRestarts:Number(O.captureHelperRestarts||0)||0,capturedAt:String(O.capturedAt||""),receivedAt:String(O.receivedAt||""),hubPacketAt:O.hubPacketAt?String(O.hubPacketAt):void 0,hubPacketEpochMs:We,browserReceivedEpochMs:qe,hubPacketTransitAgeMs:We!==void 0?Et:void 0,byteLength:Number(O.byteLength||lt.byteLength),contentHash:O.contentHash?String(O.contentHash):void 0,captureMs:vt(O.captureMs),captureStageMs:vt(O.captureStageMs),convertMs:Number(O.convertMs||0)||0,compressMs:Number(O.compressMs||0)||0,captureSourceSerial:Number(O.captureSourceSerial||0)||0,captureSourceSkipped:Number(O.captureSourceSkipped||0)||0,deltaTileSize:Number(O.deltaTileSize||0)||0,deltaTileCount:Number(O.deltaTileCount||0)||0,deltaVisualTileCount:Number(O.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(O.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(O.deltaTotalTiles||0)||0,payload:lt};if(!ce.deviceId)return;const Ne=pe.expectedBinding;if(!Ne)return;const He=ce.deviceId===Ne.deviceId&&String(ce.sessionId||"")===Ne.sessionId&&ce.streamId===Ne.streamId&&String(ce.commandId||"")===Ne.commandId&&Number(ce.captureGeneration||0)===Ne.captureGeneration&&Number(ce.monitorIndex??-1)===Ne.monitorIndex&&String(ce.streamPurpose||"")===Ne.streamPurpose;if(!He)return;ce.currentGenerationVerified=He;const Ie=Number(pe.payload.monitorSelections?.[ce.deviceId]);if(Number.isFinite(Ie)&&Number.isFinite(Number(ce.monitorIndex))&&Number(ce.monitorIndex)!==Ie)return;const Lt={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},Xe=Number(ce.streamFrameSeq||ce.frameSeq||0),ut=!!Lt.commandId&&!!ce.commandId,yt=Lt.streamId===ce.streamId&&(!ut||Lt.commandId===ce.commandId),_t=Lt.order;if(yt&&_t>=Xe&&(_t===Xe||ut))return;pe.lastFrameStreamId=ce.streamId,pe.lastFrameCommandId=ce.commandId||"",pe.lastFrameOrder=Xe;const mt=W.current;mt.totalFrames+=1,mt.totalBytes+=lt.byteLength,mt.sampleFrames+=1,mt.sampleBytes+=lt.byteLength;const Vt=!S.current.has(ce.deviceId)&&!k.current.has(ce.deviceId),St=u1(k.current,ce);Vt&&(S.current.set(ce.deviceId,St),k.current.delete(ce.deviceId),u(new Map(S.current))),K.current?.(ce)},[]);d.useEffect(()=>{if(!n||!q)return;W.current.sampleStartedAt=performance.now();const Me=window.setInterval(()=>{if(!X.current)return;const pe=performance.now(),qe=W.current,Re=Math.max(1,pe-qe.sampleStartedAt);b({totalFrames:qe.totalFrames,totalBytes:qe.totalBytes,framesPerSecond:qe.sampleFrames*1e3/Re,bytesPerSecond:qe.sampleBytes*1e3/Re,sampleMs:Re,lastUpdatedAt:Date.now()}),u(d1(S.current,k.current)),qe.sampleFrames=0,qe.sampleBytes=0,qe.sampleStartedAt=pe},2e3);return B.current=Me,()=>{window.clearInterval(Me),B.current===Me&&(B.current=null)}},[n,q]),d.useEffect(()=>{const Me=()=>{const pe=new Set,qe=[...N.current.values()];for(;qe.length>0;){const O=qe.pop();!O||pe.has(O)||(pe.add(O),O.handoffFrom&&qe.push(O.handoffFrom))}const Re=[...S.current.values(),...k.current.values()],st=[...pe],jt=A.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:q,active:X.current,socketCount:st.length+jt.closingSocketCount,openSocketCount:st.filter(O=>O.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:st.filter(O=>O.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:jt.closingSocketCount,closingSocketTimerCount:jt.closingSocketTimerCount,closingSocketTimeoutCount:jt.closingSocketTimeoutCount,expectedBindingCount:st.filter(O=>!!O.expectedBinding).length,reconnectTimerCount:_.current.size,statsTimerCount:B.current===null?0:1,configurationRefreshTimerCount:F.current.size,restartTokenCount:I.current.size,retainedFrameCount:Re.length,retainedPayloadBytes:Re.reduce((O,ze)=>O+Math.max(0,Number(ze.payload?.byteLength||0)),0)}};return cv.add(Me),()=>{cv.delete(Me)}},[q]),d.useEffect(()=>{const Me=q?q.split(",").filter(Boolean):[];if(!V){Ze(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const pe=new Set(Me),qe=performance.now();for(const Re of _.current.keys())pe.has(Re)||ue(Re);for(const Re of F.current.keys())pe.has(Re)||_e(Re);for(const[Re,st]of N.current.entries())pe.has(Re)||(ue(Re),Qe(st,"livedesk-device-unsubscribed"),N.current.delete(Re),I.current.delete(Re),S.current.delete(Re),k.current.delete(Re));W.current.sampleStartedAt<=0&&(W.current.sampleStartedAt=qe,b({...Zf,lastUpdatedAt:Date.now()}));for(const Re of Me){ue(Re),_e(Re);const st=Number(o.monitorSelections?.[Re]),jt=Number.isInteger(st)&&st>=0?st:0,O={[Re]:jt},ze={type:"subscribe",deviceIds:[Re],autoStartLive:n,fps:ve,maxWidth:J,maxHeight:$,quality:P,mode:we,frameMode:we,streamPurpose:Z,monitorSelections:O},We=String(o.connectionSessionIds?.[Re]||"").trim(),Et=JSON.stringify({subscribePayload:ze,connectionSessionId:We}),lt=N.current.get(Re),ht=Number(lt?.payload.monitorSelections?.[Re]),Je=Number(O[Re]),be=!!lt&&Number.isFinite(ht)&&Number.isFinite(Je)&&ht!==Je,je=!!lt&<?.connectionSessionId!==We;if(lt){const yt=lt.socket.readyState===WebSocket.CONNECTING||lt.socket.readyState===WebSocket.OPEN;if(lt.payloadKey===Et&&yt&&!lt.disposed)continue}const Ae=lt&&(lt.socket.readyState===WebSocket.CONNECTING||lt.socket.readyState===WebSocket.OPEN)&&!lt.disposed?lt.handoffFrom&&!lt.handoffCompleted?lt.handoffFrom:lt:void 0,fe=lt&<!==Ae?lt:void 0,te=`/api/remote/frames/ws?devices=${encodeURIComponent(Re)}`,ce=nh(ah(te,r),te);ce.binaryType="arraybuffer";const Ne=y1(),He={socket:ce,payload:ze,payloadKey:Et,connectionSessionId:We,generation:j.current+1,monitorRestartToken:be?`monitor-${Re}-${Je}-${j.current+1}`:"",disposed:!1,handoffFrom:Ae,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Ne,releaseOwnedState:()=>ew(Ne)};j.current=He.generation,(be||je)&&(S.current.delete(Re),k.current.delete(Re),u(new Map(S.current))),N.current.set(Re,He),fe&&(fe.handoffFrom=void 0,Qe(fe,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||He.disposed||N.current.get(Re)!==He){Qe(He,"livedesk-stale-frame-socket");return}ue(Re),y("");const yt=T.current,_t=yt.enabled&&(!yt.token||I.current.get(Re)!==yt.token),mt=_t||He.monitorRestartToken!=="",Vt=_t?yt.token:He.monitorRestartToken,St=_t?yt.reason:He.monitorRestartToken?"monitor-selection-change":"";if(ce.send(JSON.stringify({...He.payload,forceRestart:mt,restartReason:mt?St:"",restartToken:mt?Vt:""})),se>0){const rn=window.setTimeout(()=>{F.current.get(Re)===rn&&F.current.delete(Re),X.current&&Ge(Re,He)},Math.max(1e3,se));F.current.set(Re,rn)}_t&&yt.token&&I.current.set(Re,yt.token);const pn=He.handoffFrom;He.handoffFrom=void 0,He.handoffCompleted=!0,pn&&!pn.disposed&&Qe(pn,"livedesk-subscription-replaced"),at()},Lt=yt=>{if(!X.current||He.disposed||N.current.get(Re)!==He)return;if(typeof yt.data=="string"){try{const mt=JSON.parse(yt.data),Vt=(St,pn=!0)=>{const rn=oN(St,Re,Z);return rn?(He.expectedBinding=rn,pn&&z.current?.(rn),!0):!1};if(mt?.type==="RemoteFrameSubscriptionError")y(String(mt.error||"control-stream-start-failed"));else if(mt?.type==="RemoteFrameLiveAutoStart"){const pn=(Array.isArray(mt.skipped)?mt.skipped:[]).find(rn=>rn?.deviceId===Re);if(pn)pn.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&pn.retryScheduled===!0?y(""):y(String(pn.reason||"control-stream-start-failed"));else if(Array.isArray(mt.started)){const rn=mt.started.find(ya=>ya?.deviceId===Re);rn&&(y(""),Vt(rn,rn.ready===!0))}}else mt?.type==="RemoteFrameStreamReady"&&mt.deviceId===Re&&Vt(mt)&&y("")}catch{}return}const _t=yt.data instanceof ArrayBuffer?yt.data:null;_t&&(y(""),me(_t,He))},Xe=()=>{!X.current||He.disposed||N.current.get(Re)!==He||h("connecting")},ut=()=>{const yt=!He.disposed;He.disposed=!0,He.handoffCompleted=!0;const _t=He.detachListeners;He.detachListeners=void 0,_t?.();const mt=N.current.get(Re);mt===He&&_e(Re);let Vt=!1;if(mt===He){const St=He.handoffFrom;He.handoffFrom=void 0,St&&!St.disposed&&(St.socket.readyState===WebSocket.CONNECTING||St.socket.readyState===WebSocket.OPEN)?(N.current.set(Re,St),Vt=!0):N.current.delete(Re)}if(at(),yt&&X.current&&mt===He&&!Vt){const St=window.setTimeout(()=>{_.current.get(Re)===St&&_.current.delete(Re),X.current&&D(pn=>pn+1)},750);ue(Re),_.current.set(Re,St)}};He.detachListeners=()=>{ce.removeEventListener("open",Ie),ce.removeEventListener("message",Lt),ce.removeEventListener("error",Xe),ce.removeEventListener("close",ut)},ce.addEventListener("open",Ie),ce.addEventListener("message",Lt),ce.addEventListener("error",Xe),ce.addEventListener("close",ut)}at()},[n,_e,ue,Qe,se,de,q,ve,we,me,r,$,J,Pe,o.monitorSelections,P,H,Ze,Ge,Z,V,at]),d.useEffect(()=>{if(!V||!Se||!ae)return;const Me=q?q.split(",").filter(Boolean):[];for(const pe of Me){if(I.current.get(pe)===ae)continue;const qe=N.current.get(pe);!qe||!Ee(pe,qe,ye,ae)||I.current.set(pe,ae)}},[q,Se,ae,ye,Ee,V]),d.useEffect(()=>()=>{Ze("livedesk-hook-unmount",!1)},[Ze]);const ke=d.useCallback((Me,pe="browser-stale")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:q.split(",").filter(Boolean);if(qe.length===0)return!1;let Re=!1;for(const st of qe){const jt=N.current.get(st);!jt||jt.socket.readyState!==WebSocket.OPEN||(Re=Ee(st,jt,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Re)}return Re},[q,Ee,V]),et=d.useCallback((Me,pe="browser-reconnect")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:q.split(",").filter(Boolean);if(qe.length===0)return!1;let Re=!1;for(const st of qe){const jt=N.current.get(st);jt&&(ue(st),Qe(jt,`livedesk-${pe}`),N.current.delete(st),I.current.delete(st),S.current.delete(st),k.current.delete(st),Re=!0)}return Re&&u(new Map(S.current)),D(st=>st+1),at(),!0},[ue,Qe,q,V,at]);return{frames:l,state:f,error:g,stats:w,restartLive:ke,reconnectLive:et}}function lN(t,n,r=Un,o={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(Zf),S=d.useRef(null),k=d.useRef(o.onFrame),N=d.useRef(null),A=d.useRef(0),j=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((o.captureDeviceIds||t).filter(Boolean))].join(","),[t,o.captureDeviceIds]),_=d.useMemo(()=>JSON.stringify(o.monitorSelections||{}),[o.monitorSelections]),B=d.useMemo(()=>{const q=Object.entries(o.connectionSessionIds||{}).filter(([V])=>!!V).map(([V,X])=>[V,String(X||"").trim()]).sort(([V],[X])=>V.localeCompare(X));return JSON.stringify(Object.fromEntries(q))},[o.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(o.fps||20),inputFps:Number(o.inputFps||8),width:Number(o.width||1920),height:Number(o.height||1080),tileWidth:Number(o.tileWidth||320),tileHeight:Number(o.tileHeight||180),monitorSelections:o.monitorSelections||{}}),[T,I,_,o.fps,o.height,o.inputFps,o.monitorSelections,o.tileHeight,o.tileWidth,o.width]),H=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:B}),[F,B]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,z=d.useCallback(q=>q.readyState!==WebSocket.OPEN?!1:(q.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{k.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{if(!K)return;j.current.sampleStartedAt=performance.now();const q=window.setInterval(()=>{const V=j.current,X=performance.now(),ve=Math.max(1,X-V.sampleStartedAt);b({totalFrames:V.totalFrames,totalBytes:V.totalBytes,framesPerSecond:V.sampleFrames*1e3/ve,bytesPerSecond:V.sampleBytes*1e3/ve,sampleMs:ve,lastUpdatedAt:Date.now()});const J=N.current;J&&J.frameSeq!==A.current&&(A.current=J.frameSeq,u(J)),V.sampleFrames=0,V.sampleBytes=0,V.sampleStartedAt=X},1e3);return()=>window.clearInterval(q)},[K]),d.useEffect(()=>{if(!K){S.current?.close(),S.current=null,u(null),N.current=null,A.current=0,h(null),y("idle"),b(Zf);return}let q=!1,V=0;const X=()=>{if(q)return;const ve=nh(ah("/api/remote/atlas/ws",r),"/api/remote/atlas/ws");ve.binaryType="arraybuffer",S.current=ve,y("connecting"),ve.addEventListener("open",()=>{j.current.sampleStartedAt=performance.now(),y("open"),z(ve)}),ve.addEventListener("message",J=>{if(typeof J.data=="string"){try{const P=JSON.parse(J.data);P?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(P.layoutVersion||0),width:Number(P.width||1920),height:Number(P.height||1080),columns:Number(P.columns||1),rows:Number(P.rows||1),tiles:Array.isArray(P.tiles)?P.tiles:[]})}catch{}return}const $=J.data instanceof ArrayBuffer?J.data:null;if(!(!$||$.byteLength<5))try{const P=Date.now(),we=new DataView($).getUint32(0,!1);if(we<=0||we+4>$.byteLength)return;const Z=JSON.parse(Pv.decode(new Uint8Array($,4,we))),Se=new Uint8Array($,4+we),ae=vt(Z.hubClientDropped),ye=vt(Z.hubClientQueueDepth),Pe=vt(Z.hubClientQueueLimit),de=vt(Z.hubClientBufferedBytes),Qe={deviceId:String(Z.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||"mode4-atlas"),commandId:Z.commandId?String(Z.commandId):void 0,width:Number(Z.width||1920),height:Number(Z.height||1080),sourceWidth:Number(Z.sourceWidth||Z.width||1920),sourceHeight:Number(Z.sourceHeight||Z.height||1080),mimeType:String(Z.mimeType||"video/h264"),mode:String(Z.mode||"mode4-h264-atlas"),frameMode:String(Z.frameMode||"mode4-h264-atlas"),frameProfile:String(Z.frameProfile||"mode4-h264-atlas-v1"),encoding:String(Z.encoding||"video-atlas"),codec:String(Z.codec||"h264"),compression:String(Z.compression||"video/h264"),h264Format:String(Z.h264Format||"annexb"),isKeyFrame:Z.isKeyFrame===!0,chunkType:String(Z.chunkType||""),timestampUs:Number(Z.timestampUs||0),durationUs:Number(Z.durationUs||0),transport:Z.transport?String(Z.transport):void 0,videoTransport:Z.videoTransport?String(Z.videoTransport):void 0,frameTransportActive:Z.frameTransportActive?String(Z.frameTransportActive):void 0,frameTransportProtocol:Z.frameTransportProtocol?String(Z.frameTransportProtocol):void 0,frameTransportState:Z.frameTransportState?String(Z.frameTransportState):void 0,frameTransportReason:Z.frameTransportReason?String(Z.frameTransportReason):void 0,frameTransportChangedAt:Z.frameTransportChangedAt?String(Z.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Z.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Z.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Z.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ae!==void 0&&ye!==void 0&&Pe!==void 0&&de!==void 0,hubClientDropped:ae,hubClientQueueDepth:ye,hubClientQueueLimit:Pe,hubClientBufferedBytes:de,udpIncompleteFrames:Number(Z.udpIncompleteFrames||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Number(Z.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:P,byteLength:Se.byteLength,layoutVersion:Number(Z.layoutVersion||0),atlasComposeMs:Number(Z.atlasComposeMs||0),atlasPoolStarved:Number(Z.atlasPoolStarved||0),atlasReadyTiles:Number(Z.atlasReadyTiles||0),atlasTileCount:Number(Z.atlasTileCount||0),atlasInputRevision:Number(Z.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(Z.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(Z.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(Z.atlasSourceMaxAgeMs||0),payload:Se},ue=j.current;ue.totalFrames+=1,ue.totalBytes+=Se.byteLength,ue.sampleFrames+=1,ue.sampleBytes+=Se.byteLength,N.current=Qe,A.current===0&&(A.current=Qe.frameSeq,u(Qe)),k.current?.(Qe)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{S.current===ve&&(S.current=null),!q&&(y("closed"),V=window.setTimeout(X,1200))})};return X(),()=>{q=!0,window.clearTimeout(V),S.current?.close(),S.current=null}},[K,r,z]),d.useEffect(()=>{if(!K)return;const q=S.current;q&&z(q)},[H,K,z]);const W=d.useCallback(()=>{const q=S.current;return q?z(q):!1},[z]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:W}}function cN(t,n=Un){const r=d.useRef(null),o=d.useRef(0),l=d.useRef(0),u=d.useRef(new Map),f=d.useRef(""),[h,g]=d.useState("idle"),[y,w]=d.useState(""),[b,S]=d.useState(sw),k=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!t){r.current?.close(),r.current=null,l.current=0,f.current="",u.current.clear(),g("idle"),w(""),S(sw);return}let A=!1,j=0;const I=()=>{if(A)return;const T=nh(ah("/api/remote/input/ws",n),"/api/remote/input/ws");r.current=T,k.current.sampleStartedAt=performance.now(),g("connecting"),w(""),T.addEventListener("open",()=>{A||r.current!==T||(w(""),g("open"))}),T.addEventListener("message",_=>{if(!(A||r.current!==T||typeof _.data!="string"))try{const B=JSON.parse(_.data),F=Number(B.inputSeq||B.result?.inputSeq||0),H=String(B.deviceId||B.result?.deviceId||""),D=String(B.inputEventId||B.result?.inputEventId||""),K=u.current.get(F);if(H&&(K&&K.deviceId!==H||!K&&f.current&&f.current!==H)||K?.inputEventId&&D&&K.inputEventId!==D)return;if(B?.type==="RemoteInputError"){F>0&&u.current.delete(F),w(String(B.error||B.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(B?.type!=="RemoteInputApplied")return;K&&(k.current.lastRoundTripMs=Math.max(0,performance.now()-K.sentAt),u.current.delete(F)),k.current.lastInputSeq=F,k.current.lastAgentApplyMs=Math.max(0,Number(B.agentApplyMs||0)),w(""),g("open")}catch{}}),T.addEventListener("close",()=>{A||r.current!==T||(r.current=null,g("closed"),j=window.setTimeout(I,1200))}),T.addEventListener("error",()=>{!A&&r.current===T&&g("error")})};return I(),()=>{A=!0,window.clearTimeout(j);const T=r.current;r.current=null,T?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const A=window.setInterval(()=>{const j=performance.now(),I=k.current,T=Math.max(1,j-I.sampleStartedAt);S({totalSent:I.totalSent,totalDropped:I.totalDropped,sentPerSecond:I.sampleSent*1e3/T,droppedPerSecond:I.sampleDropped*1e3/T,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:I.lastInputType,lastInputSeq:I.lastInputSeq,lastRoundTripMs:I.lastRoundTripMs,lastAgentApplyMs:I.lastAgentApplyMs,lastUpdatedAt:Date.now()}),I.sampleSent=0,I.sampleDropped=0,I.sampleStartedAt=j},1e3);return()=>window.clearInterval(A)},[t]);const N=d.useCallback((A,j)=>{const I=r.current;if(!I||I.readyState!==WebSocket.OPEN||!A)return!1;const T=String(j.type||"").toLowerCase(),F=T==="pointermove"||T==="wheel",H=k.current;if(F&&I.bufferedAmount>J1)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${T}-coalescible-drop`,!1;if(!F&&I.bufferedAmount>eN){H.lastInputType=`${T||"input"}-fail-closed`,w("Remote input channel was reset because ordered input could not drain.");try{I.close(4001,"ordered-input-backpressure")}catch{}return!1}const D=o.current+1;o.current=D;const K=`${D}-${crypto.randomUUID()}`,z=Date.now(),W=!F||D-l.current>=nN;for(W&&(u.current.set(D,{sentAt:performance.now(),deviceId:A,inputEventId:K}),F&&(l.current=D)),f.current=A,V0.set(A,{inputSeq:D,inputType:T||"input",sentAt:performance.now()});u.current.size>256;){const q=u.current.keys().next().value;if(q===void 0)break;u.current.delete(q)}try{I.send(JSON.stringify({type:"input",requestId:F?"":crypto.randomUUID(),fireAndForget:F,deviceId:A,input:{...j,inputEventId:K,inputSeq:D,requestAck:W,issuedAtEpochMs:z,issuedAt:new Date(z).toISOString()}}))}catch{u.current.delete(D),w("Remote input channel closed before the ordered input was queued.");try{I.close(4002,"input-send-failed")}catch{}return!1}return H.totalSent+=1,H.sampleSent+=1,H.lastInputType=T||"input",!0},[]);return{state:h,sendInput:N,stats:b,error:y}}const xd={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},uN=.25,ow=300,lw=2,dp=1500,xg=5e3,dN=2e3,cw=1e4,If=[0,1e3,3e3];function uw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function fN(t,n,r=Un,o=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,S]=d.useState(null),[k,N]=d.useState(xd),[A,j]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(S(T=>T===null?T:null),N(T=>T===xd?T:xd))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),S(null),N(xd),j("");return}w("connecting"),S(null),N(xd),j("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),N(xd),j("Audio playback is not supported in this browser.");return}let _=!1,B=null;const F=N1.acquire(({release:H})=>{if(_){H();return}const D=new T({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const z="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),W=nh(ah(z,r),z);W.binaryType="arraybuffer";const q=pa.createOwner({deviceId:t,socket:W,audioContext:D,statsTimer:null});let V=!1;const X=()=>{const te=pa.releaseIfDrained(q);return(te||!pa.hasOwner(q))&&!V&&(V=!0,H()),te},ve=Lv({sampleRate:192e3,channels:8}).capacityBytes,J=P1({maxPendingPackets:ov,maxPendingBytes:ve}),$=S1(),P={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let se=!1,we=!1,Z=null,Se=0,ae=0,ye="",Pe=!1,de=()=>{},Qe="connecting",ue="";const _e=te=>{se||te===Qe||(Qe=te,w(te))},Ze=te=>{se||te===ue||(ue=te,j(te))};let at=0,Ee=!1,Ge=0,me=0,ke=0,et=!1;const Me=()=>{pa.setPendingWorkletPackets(q,J.getPendingPacketCount(),J.getPendingPacketBytes(),J.getPendingPacketHighWater(),J.getPendingByteHighWater())},pe=te=>{P.workletRingCapacityBytes=Math.max(0,Math.min(ve,Number(te.ringCapacityBytes||0)||0)),P.workletRingBufferedBytes=Math.max(0,Math.min(P.workletRingCapacityBytes,Number(te.ringBufferedBytes||0)||0)),P.workletRingBufferedMs=Math.max(0,Math.min(uN*1e3,Number(te.ringBufferedMs||0)||0)),P.workletRingDroppedFrames=Math.max(P.workletRingDroppedFrames,Number(te.ringDroppedFrames||0)||0),P.workletRingUnderflowCount=Math.max(P.workletRingUnderflowCount,Number(te.ringUnderflowCount||0)||0),pa.setPcmRing(q,P.workletRingCapacityBytes,P.workletRingBufferedBytes)},qe=()=>{const te=Z;if(Z=null,Pe=!1,te){te.onprocessorerror=null,te.port.onmessage=null;try{te.disconnect()}catch{}try{te.port.close()}catch{}}J.terminate(),Me(),P.workletRingCapacityBytes=0,P.workletRingBufferedBytes=0,P.workletRingBufferedMs=0,pa.setPcmRing(q,0,0),pa.setWorkletNode(q,0,0,Se),X()},Re=te=>{const ce=te.data||{},Ne=String(ce.type||"");if((Ne==="packet-terminal"||Ne==="processor-error")&&(J.acknowledge(typeof ce.packetId=="number"?ce.packetId:String(ce.packetId||"")),Me()),Ne==="packet-terminal"){const He=Math.max(0,Number(ce.droppedFrames||0)||0);He>0&&(P.workletRingDroppedFrames+=He,P.resyncs+=1)}if(Ne==="ring-configured"||Ne==="ring-state"||Ne==="disposed"){const He=P.workletRingDroppedFrames;pe(ce),P.workletRingDroppedFrames>He&&(P.resyncs+=1)}Ne==="disposed"?qe():Ne==="processor-error"&&de(String(ce.error||"Remote audio worklet processing failed."))},st=()=>{if(!(!Z||!Pe))try{Z.port.postMessage({type:"flush"})}catch{de("Remote audio worklet could not be flushed.")}},jt=()=>{W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},O=()=>{P.audioContextState=String(D.state),!se&&(P.audioContextState==="suspended"||P.audioContextState==="interrupted"?_e("suspended"):P.audioContextState==="closed"&&(_e("error"),Ze("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ze=async()=>{if(se||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),P.audioContextState=String(D.state),!se&&!Ee&&P.audioContextState==="running"){const te=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp,ce=P.lastCaptureStatusAt>0&&performance.now()-P.lastCaptureStatusAt<=xg&&P.captureHealthy;_e(te?"playing":ce?"silent":"open")}return P.audioContextState==="running"}catch(te){return se||(_e("suspended"),Ze(te instanceof Error?"Audio playback is suspended: "+te.message:"Audio playback is suspended.")),!1}},We=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const te=new Blob([H1],{type:"text/javascript"});ye=URL.createObjectURL(te);try{await D.audioWorklet.addModule(ye)}finally{URL.revokeObjectURL(ye),ye=""}if(se||String(D.state)==="closed")return;const ce=new AudioWorkletNode(D,G0,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[lw],channelCount:lw,channelCountMode:"explicit"});Se+=1,Z=ce,ce.port.onmessage=Re,ce.onprocessorerror=()=>{de("Remote audio worklet stopped unexpectedly.")},ce.connect(D.destination),Pe=!0,pa.setWorkletNode(q,1,1,Se)},Et=(te,ce,Ne,He)=>{const Ie=Z;if(se||!Pe||!Ie||ce.byteLength<=0)return!1;const Lt=Iv({sampleRate:te.sampleRate,channels:te.channels,mimeType:te.mimeType}),Xe=++ae;if(!J.claim(Xe,ce.byteLength))return Me(),!1;Me();try{return Ie.port.postMessage({type:"pcm",packetId:Xe,buffer:ce,byteOffset:Ne,byteLength:He,sampleRate:Lt.sampleRate,channels:Lt.channels,mimeType:te.mimeType,sampleFormat:Lt.sampleFormat},[ce]),!0}catch{return J.acknowledge(Xe),Me(),!1}},lt=async()=>{if(se||Ee||W.readyState!==WebSocket.OPEN)return;if(Ge>=If.length){_e("error"),Ze("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const te=Ge;Ge+=1,Ee=!0,P.stalledCount+=1,P.automaticRestarts+=1,_e("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ce=await f(t);if(se||!ce)return;K=ce,jt();const Ne=performance.now();at=Ne,P.lastPacketAt=Ne,P.lastAcceptedAt=0,P.lastCaptureStatusAt=0,P.lastPcmAtEpochMs=0,P.captureAlive=null,P.helperAlive=null,P.helperReady=!1,P.captureHealthy=!1,P.captureStatusFailed=!1,P.captureAwaitingCurrentPcm=!1,P.captureAwaitingSinceAt=0,P.capturePhase="",P.backendKind="",P.helperRequired=!1,P.helperPid=0,P.nativeCallbackDiagnosticsAvailable=!1,P.nativeRejectedCallbackCount=0,P.nativeCurrentnessDropCount=0,P.nativeLastDropReason="",P.silentForMs=0,P.activeStreamId=K,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st(),me=Ne+(If[te+1]??3e3),Ze(""),se||_e("open")}catch(ce){se||(me=performance.now()+(If[te+1]??3e3),_e("error"),Ze(ce instanceof Error?"Remote audio restart failed: "+ce.message:"Remote audio restart failed."))}finally{Ee=!1}},ht=()=>{P.drops+=1},Je=window.setInterval(()=>{if(se)return;const te=performance.now(),ce=P.lastPacketAt>0?Math.max(0,te-P.lastPacketAt):at>0?Math.max(0,te-at):0,Ne=P.lastAcceptedAt>0?Math.max(0,te-P.lastAcceptedAt):0,He=P.lastCaptureStatusAt>0?Math.max(0,te-P.lastCaptureStatusAt):0,Ie=W.readyState===WebSocket.OPEN,Lt=P.lastCaptureStatusAt>0,Xe=Lt&&He<=xg&&P.captureHealthy,ut=Lt&&P.captureStatusFailed&&He>dN,yt=Lt&&He>xg,_t=!Lt&&at>0&&te-at>cw,mt=P.captureAwaitingCurrentPcm&&P.captureAwaitingSinceAt>0&&te-P.captureAwaitingSinceAt>cw,Vt=at>0&&(P.lastAcceptedAt<=0?te-at>dp:Ne>dp);if(Ie&&at>0&&(ut||yt||_t||mt)?Ge>=If.length&&!Ee?(_e("error"),Ze("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Ee&&te>=me?lt():Ee||_e("stalled"):Ie&&Vt&&!Ee&&P.audioContextState!=="suspended"&&P.audioContextState!=="interrupted"&&_e(Xe?"silent":"open"),T1({enabled:I.current,now:te,lastPublishedAt:ke})){ke=te,N({queuedMs:P.workletRingBufferedMs,browserAgeMs:P.browserAgeMs,captureAgeMs:P.captureAgeMs,captureStatusAgeMs:He,silentForMs:P.silentForMs,captureAlive:P.captureAlive,helperAlive:P.helperAlive,helperReady:P.helperReady,captureHealthy:P.captureHealthy,captureAwaitingCurrentPcm:P.captureAwaitingCurrentPcm,capturePhase:P.capturePhase,backendKind:P.backendKind,helperRequired:P.helperRequired,helperPid:P.helperPid,captureRestartCount:P.captureRestartCount,nativeCallbackDiagnosticsAvailable:P.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:P.nativeRejectedCallbackCount,nativeCurrentnessDropCount:P.nativeCurrentnessDropCount,nativeLastDropReason:P.nativeLastDropReason,localProcessingAgeMs:P.localProcessingAgeMs,lastPacketAgeMs:ce,lastAcceptedAgeMs:Ne,framesReceived:P.framesReceived,drops:P.drops,resyncs:P.resyncs,pendingDecodes:P.pendingDecodes,lastFrameSeq:P.lastFrameSeq,audioContextState:P.audioContextState,stalledCount:P.stalledCount,automaticRestarts:P.automaticRestarts,maximumAcceptedGapMs:P.maximumAcceptedGapMs,workletRingCapacityBytes:P.workletRingCapacityBytes,workletRingBufferedBytes:P.workletRingBufferedBytes,workletRingDroppedFrames:P.workletRingDroppedFrames,workletRingUnderflowCount:P.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const St=$.publish();St&&(et=!0,pa.setRetainedFrame(q,1,St.payload.byteLength),S(St))}else!I.current&&et&&(et=!1,$.clear(),pa.setRetainedFrame(q,0,0))},250);pa.setStatsTimer(q,Je);const be=()=>{O(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&ze()},je=()=>{document.visibilityState==="visible"&&ze()},Ae=()=>{ze()};D.addEventListener("statechange",be),document.addEventListener("visibilitychange",je),window.addEventListener("pageshow",Ae),window.addEventListener("pointerdown",Ae),window.addEventListener("keydown",Ae),_e("connecting"),Ze(""),O();const fe=(te,ce,Ne,He,Ie)=>{if(P.localProcessingAgeMs=Math.max(0,performance.now()-Ie),se||P.localProcessingAgeMs>ow||!lv(te,{deviceId:t,streamId:K}))return ht(),!1;P.activeStreamId!==K&&(P.activeStreamId=K,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st());const Lt=D1(te,{deviceId:t,streamId:K,lastFrameSeq:P.lastFrameSeq});if(!Lt.accepted||!Et(te,ce,Ne,He))return ht(),!1;P.browserAgeMs=uw(te.receivedAt),P.captureAgeMs=uw(te.capturedAt);const Xe=performance.now();P.lastAcceptedAt>0&&(P.maximumAcceptedGapMs=Math.max(P.maximumAcceptedGapMs,Xe-P.lastAcceptedAt)),P.lastAcceptedAt=Xe,P.framesReceived+=1,P.lastFrameSeq=Lt.nextFrameSeq,Ge=0,me=0,I.current&&($.accept(te),et=!0,pa.setRetainedFrame(q,1,0)),String(D.state)!=="running"&&ze();const ut=String(D.state)==="running";return ut&&Ze(""),_e(ut?"playing":"suspended"),!0};de=(te="")=>{if(!we){if(we=!0,te&&(pa.recordTerminalFailure(q,te,te.includes("setup failed")?"setup":"processor"),_e(te.includes("AudioWorklet is unavailable")?"unsupported":"error"),Ze(te),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),se=!0,pa.deactivate(q),window.clearInterval(Je),pa.setStatsTimer(q,null),D.removeEventListener("statechange",be),document.removeEventListener("visibilitychange",je),window.removeEventListener("pageshow",Ae),window.removeEventListener("pointerdown",Ae),window.removeEventListener("keydown",Ae),$.clear(),pa.setRetainedFrame(q,0,0),Z)try{Z.port.postMessage({type:"dispose"})}catch{}try{W.close()}catch{}W.readyState===WebSocket.CLOSED&&pa.setSocket(q,null),D.close().catch(()=>{}).finally(()=>{qe(),String(D.state)==="closed"&&pa.setAudioContext(q,null),X()}),g.current===D&&(g.current=null),X()}},We().catch(te=>{de(te instanceof Error?`Remote audio worklet setup failed: ${te.message}`:"Remote audio worklet setup failed.")}),W.addEventListener("open",()=>{se||(at=performance.now(),P.lastPacketAt=at,P.lastAcceptedAt=0,P.lastCaptureStatusAt=0,P.lastPcmAtEpochMs=0,P.captureAlive=null,P.helperAlive=null,P.helperReady=!1,P.captureHealthy=!1,P.captureStatusFailed=!1,P.captureAwaitingCurrentPcm=!1,P.captureAwaitingSinceAt=0,P.capturePhase="",P.backendKind="",P.helperRequired=!1,P.helperPid=0,P.maximumAcceptedGapMs=0,P.silentForMs=0,_e("open"),jt(),ze())}),W.addEventListener("message",te=>{if(typeof te.data=="string")return;const ce=te.data instanceof ArrayBuffer?te.data:null;if(!ce||ce.byteLength<5)return;const Ne=performance.now();P.lastPacketAt=Ne;try{const Ie=new DataView(ce).getUint32(0,!1);if(Ie<=0||Ie+4>ce.byteLength){ht();return}const Lt=new Uint8Array(ce,4,Ie),Xe=JSON.parse(Pv.decode(Lt)),ut=new Uint8Array(ce,4+Ie),yt=String(Xe.deviceId||""),_t=String(Xe.streamId||"");if(!lv({deviceId:yt,streamId:_t},{deviceId:t,streamId:K})){ht();return}const mt=String(Xe.frameKind||Xe.kind||"").toLowerCase();if(Xe.type==="remote.audio.status"||mt==="audio-status"){P.lastCaptureStatusAt=Ne;const St=I1(Xe);if(P.captureAlive=St.captureAlive,P.helperAlive=St.helperAlive,P.helperReady=St.helperReady,P.captureHealthy=St.healthy,P.captureStatusFailed=St.failed,P.captureAwaitingCurrentPcm=St.awaitingCurrentPcm,St.awaitingCurrentPcm?P.captureAwaitingSinceAt||=Ne:P.captureAwaitingSinceAt=0,P.capturePhase=St.capturePhase,P.backendKind=St.backendKind,P.helperRequired=St.helperRequired===!0,P.helperPid=St.helperPid,P.captureRestartCount=Math.max(0,Number(Xe.restartCount||0)||0),P.nativeCallbackDiagnosticsAvailable=Xe.callbackDiagnosticsAvailable===!0,P.nativeRejectedCallbackCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Xe.rejectedCallbackCount||0)||0):0,P.nativeCurrentnessDropCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Xe.currentnessDropCount||0)||0):0,P.nativeLastDropReason=P.nativeCallbackDiagnosticsAvailable?String(Xe.lastDropReason||""):"",P.lastPcmAtEpochMs=Math.max(0,Number(Xe.lastPcmAtEpochMs||0)||0),P.silentForMs=Math.max(0,Number(Xe.silentForMs||0)||0),P.captureAgeMs=P.lastPcmAtEpochMs>0?Math.max(0,Date.now()-P.lastPcmAtEpochMs):P.silentForMs,P.captureHealthy){if(Ge=0,me=0,!Ee){Ze("");const pn=String(D.state)==="running",rn=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp;_e(pn?rn?"playing":"silent":"suspended")}}else P.captureAwaitingCurrentPcm&&!Ee?_e("open"):P.captureStatusFailed&&!Ee&&_e("stalled");return}const Vt={deviceId:yt,frameSeq:Number(Xe.frameSeq||0),streamId:_t,mimeType:String(Xe.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Xe.sampleRate||48e3),channels:Number(Xe.channels||2),capturedAt:String(Xe.capturedAt||""),receivedAt:String(Xe.receivedAt||""),byteLength:Number(Xe.byteLength||ut.byteLength),payload:W0};if(!Vt.deviceId||se)return;if(performance.now()-Ne>ow){ht();return}if(E1(Vt.mimeType)){fe(Vt,ce,ut.byteOffset,ut.byteLength,Ne);return}ht(),_e("error"),Ze(`Unsupported remote audio format "${Vt.mimeType}". Requesting a bounded PCM restart.`),!Ee&&Ge<If.length&&(me=0,lt());return}catch(He){se||(_e("error"),Ze(He instanceof Error?He.message:String(He)))}}),W.addEventListener("error",()=>{se||(_e("error"),Ze("Remote audio WebSocket error."))}),W.addEventListener("close",()=>{pa.setSocket(q,null),X(),se||_e("closed")}),B=()=>{de()}});return F.ready.catch(H=>{_||(w("error"),j(H instanceof Error?`Remote audio owner setup failed: ${H.message}`:"Remote audio owner setup failed."))}),()=>{_=!0,B?B():F.cancel()}},[t,n,r,o,f,h]),{state:y,lastFrame:b,stats:k,error:A}}const mN=3;function dw(t,n,r){const o=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(o,Number(t)-Number(n))),u=Math.min(o/2,mN);return l<=u?0:l>=o-u?1:l/o}function pN(t,n,r){return{normalizedX:dw(t,r.left,r.width),normalizedY:dw(n,r.top,r.height)}}const Kp=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),hN=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),fw=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),uv=64;function _v(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function K0(t){const n=String(t??"");return n===" "?" ":_v(n)}function dv(t){const n=_v(t);return Object.prototype.hasOwnProperty.call(fw,n)?fw[n]:n}function Sg(t={}){const n=K0(t.key),r=Number(t.keyCode??t.which);if(n===" "||n==="Spacebar"||r===32)return"Space";const o=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,l=o===2?"Right":"Left";return n==="Shift"?`Shift${l}`:n==="Control"?`Control${l}`:n==="Alt"||n==="AltGraph"?`Alt${l}`:n==="Meta"||n==="OS"?`Meta${l}`:n?`Key:${o}:${n}`.slice(0,80):""}function fv(t={}){const n=dv(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?Sg({...t,key:n}):n==="Unidentified"?Sg(t):n||Sg(t)}function Lp(t){for(const[n,r]of Object.entries(Kp))if(r.includes(t))return n;return""}function Yl(t,n){return Kp[n].some(r=>t.has(r))}function fp(t,n,r={},o="",l=""){for(const u of Object.keys(Kp)){const f=r[u]===!0,h=Kp[u];if(u===o){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Yl(t,u)&&t.size<uv&&t.add(hN[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function gN(t,n){if(t.length!==n.size)return!1;let r=0;for(const o of n){if(t[r]!==o)return!1;r+=1}return!0}function mw(t){for(const n of[...t])Lp(n)||t.delete(n)}function mv(t){return{shiftKey:Yl(t,"shiftKey"),ctrlKey:Yl(t,"ctrlKey"),altKey:Yl(t,"altKey"),metaKey:Yl(t,"metaKey")}}function vN(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function yN(t,n,r){const o=fv(t),l=K0(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:o,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...mv(r)}}function bN(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(o={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=fv(o);if(!u)return null;const f=Lp(u),h=t.has(u),g=[...t];return f?l==="keydown"?(fp(t,n,o,f,l),t.size<uv&&t.add(u)):(n.has(u)||t.delete(u),fp(t,n,o,f,l)):(fp(t,n,o),l==="keydown"?t.size<uv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!Yl(t,"metaKey")&&mw(t),l==="keydown"&&h&&o.repeat!==!0&&gN(g,t)?null:yN(o,l,t)},modifier(o,l){const u=dv(o),f=Lp(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Yl(t,"metaKey")&&mw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...mv(t)})},reset(o="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:_v(o,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(o={}){const l=typeof o=="string"?dv(o):fv(o);if(t.has(l))return!0;const u=Lp(l);return!!u&&Yl(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...mv(t)}}}}const Q0=64,wN=2;function Y0(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(Q0,n)):1}function Fv(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(Q0-1,n)):0}function X0(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function xN(t,n,r){const o=String(n||"").trim();if(!o)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===o&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:o,sampleId:l,consecutiveSamples:t?.fingerprint===o?t.consecutiveSamples+1:1}}function Z0({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return X0(t)?!!String(n||"").trim()&&Number(r)>=wN:!0}function SN({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:o,consecutiveTopologySamples:l}){const u=Fv(t),f=Y0(n);return u<f||!Z0({platform:r,topologyFingerprint:o,consecutiveTopologySamples:l})?u:f-1}function CN(t,n,r){const o=Fv(t),l=Y0(n);return o<l||X0(r)?o:l-1}function sc(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ha(t){return String(t||"").trim()}function Cg(t,n,r={}){return{deviceId:ha(t),transitionGeneration:sc(n),sessionId:ha(r.sessionId),streamId:ha(r.streamId),commandId:ha(r.commandId),captureGeneration:sc(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Qn(t,n){return!!t&&!!n&&ha(t.deviceId)===ha(n.deviceId)&&sc(t.transitionGeneration)===sc(n.transitionGeneration)}function pw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:o}){const l=ha(t),u=sc(n),f=sc(r);return!!l&&u>0&&u===f&&(!o||ha(o.deviceId)===l)}function hw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function mp(t,n,r){const o=ha(t);return!o||!n||ha(n.deviceId)!==o?!1:!r||ha(r.deviceId)!==o}function kg(t,n){if(!t||!n)return!1;const r=sc(n.captureGeneration),o=ha(n.commandId),l=ha(n.sessionId),u=ha(n.streamId),f=Number(t.monitorIndex);return!r||!o||!l||!u||!Number.isInteger(f)||f<0?!1:ha(t.deviceId)===ha(n.deviceId)&&ha(t.sessionId)===l&&ha(t.streamId)===u&&ha(t.commandId)===o&&sc(t.captureGeneration)===r&&ha(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}const kN=820,MN=500,gw=`(max-width: ${kN}px), (orientation: landscape) and (max-height: ${MN}px) and (pointer: coarse)`,AN="1200px 0px 1800px 0px",NN=960,TN=540,RN=68;function jN(t,n){const r=t&&typeof t=="object"?t:{},o={fps:Math.max(1,Math.floor(Number(r.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(r.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(r.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(r.quality)||1)))};return n?{...o,maxWidth:Math.min(o.maxWidth,NN),maxHeight:Math.min(o.maxHeight,TN),quality:Math.min(o.quality,RN)}:o}function EN(t,n){return!n||!t||typeof t.closest!="function"?null:t.closest(".desk-stage")}function vw(t,n,r){return!!(t||n&&r)}function DN(t,n,r,o=!1,l=o){const u=Number(t?.height),f=Number(n),h=Number(t?.offsetTop),g=o&&Number.isFinite(f)&&f>0,y=g?0:Number.isFinite(h)?Math.max(0,Math.round(h)):0,w=g?f:Number.isFinite(u)&&u>0?u:Number.isFinite(f)&&f>0?f:1,b=Number(t?.width),S=Number(r),k=l&&Number.isFinite(S)&&S>0,N=k?S:Number.isFinite(b)&&b>0?b:Number.isFinite(S)&&S>0?S:1,A=Number(t?.offsetLeft);return{height:Math.max(1,Math.round(w)),width:Math.max(1,Math.round(N)),offsetTop:y,offsetLeft:k?0:Number.isFinite(A)?Math.max(0,Math.round(A)):0}}function IN(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function LN(){let t=Promise.resolve(),n=Promise.resolve();const r=o=>{const l=IN(t,o);return t=l.tail,l.result};return{enqueue:r,enqueueStop(o){const l=r(o);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(o){const l=n;return r(async()=>(await l,o()))}}}function PN(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function _N(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const Xn=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:20,slowWallFps:5,fastWallFps:20,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:24,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function pv(t){return t==="slow"?Xn.slowWallFps:Xn.fastWallFps}function yw({paintStale:t,lastRecoveryAt:n,now:r,recoveryCooldownMs:o,transportRecoveryAfterMs:l}){if(t!==!0)return"none";const u=Math.max(0,Number(r)||0),f=Math.max(0,Number(n)||0),h=f>0?u-f:Number.POSITIVE_INFINITY;return f>0&&h>=Math.max(1,Number(l)||1)?"recover-transport":f<=0||h>=Math.max(1,Number(o)||1)?"reset-decoder":"wait"}function bw({lastReceivedAt:t,lastPaintedAt:n,now:r,staleAfterMs:o}){const l=Math.max(0,Number(t)||0);if(l<=0)return!1;const u=Math.max(0,Number(n)||0),f=u>0?u:l;return Math.max(0,Number(r)||0)-f>Math.max(1,Number(o)||1)}function FN(t){return t==="share-files"||t==="agents"}function ON({captureOwnershipActive:t,localFeatureAccess:n,controlSessionDeviceId:r,planAllowed:o,sessionState:l,controlFocusVisible:u,presentationCanvasMounted:f,wallPresentationVisible:h,wallPresentationCanvasMounted:g,decoderOwnerExists:y}){const w=l==="connecting"||l==="active"||l==="warm";return t!==!0||n!==!0||!String(r||"").trim()||o!==!0||!w?!1:y===!0||u===!0&&f===!0||h===!0&&g===!0}function BN({decodeWidth:t,decodeHeight:n,presentationCssWidth:r,presentationCssHeight:o,devicePixelRatio:l,sourceWidth:u,sourceHeight:f}){const h=Math.max(0,Number(t)||0),g=Math.max(0,Number(n)||0),y=Math.max(0,Number(r)||0),w=Math.max(0,Number(o)||0),b=Math.max(1,Math.min(2,Number(l)||1)),S=Math.max(0,Number(u)||0),k=Math.max(0,Number(f)||0);if(h<=0||g<=0||y<=0||w<=0||S<=0||k<=0)return!1;const N=y*b,A=w*b,j=Math.min(1,N/S,A/k),I=Math.max(1,Math.round(S*j)),T=Math.max(1,Math.round(k*j));return h<I*.9||g<T*.9}function HN({cadenceCredit:t,targetFps:n,sourceFps:r,elapsedSincePaintMs:o=0,nowMs:l=0,scheduledPaintAtMs:u=0,force:f=!1}){const h=Math.max(1,Number(n)||1),g=Math.max(1,Number(r)||1);if(h>=g)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const y=Math.max(0,Number(l)||0),w=Math.max(0,Number(u)||0),b=y>0&&w>0,S=1e3/h,k=Math.min(S/3,1e3/g*.5),N=Number.isFinite(Number(t))?Math.max(0,Math.min(g-Number.EPSILON,Number(t))):0;if(f)return{shouldPaint:!0,nextCadenceCredit:N,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:b?w:y>0?y+S:0};const A=N+h,j=A>=g,I=1e3/h*Xn.controlWallReuseStarvationFactor,T=!j&&Number(o)>=I,_=b&&y+k>=w,B=b?_||T:j||T;let F=w;return B&&y>0&&(!b||T?F=y+S:(F=w+S,F<=y-S&&(F=y+S))),{shouldPaint:B,nextCadenceCredit:T?0:j&&B?A-g:Math.min(g-Number.EPSILON,A),sourceCadencePassthrough:!1,deadlineForced:T,scheduleSelected:_,nextScheduledPaintAtMs:F}}function zN(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const o=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of o){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function $N(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function Lf({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function UN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:o,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function qN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:o,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),S=Math.max(0,Number(o)||0),k=Math.max(0,Number(l)||0),N=Math.max(1,Number(u)||1),A=Math.max(0,Number(f)||0),j=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),T=y*w,_=T>8&&b<T*Xn.missingDeliveryRatio,B=T>8&&S<T*Xn.missingDeliveryRatio,F=k>N||A>I||_||B,H=b>=T*Xn.recoveryDeliveryRatio&&S>=T*Xn.recoveryDeliveryRatio&&k<N*Xn.recoveryByteRatio&&A<I*Xn.recoveryGapRatio&&j<I*Xn.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:_,estimatedMissingPaints:B,overloaded:F,healthyForRecovery:H}}function WN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:o,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(o),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=Xn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Xn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function GN({deviceCount:t,targetFps:n,adaptive:r=!0}){const o=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Xn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Xn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Xn.scalableAtlasMinInputFps,Math.min(Xn.scalableAtlasMaxInputFps,Math.floor(Xn.scalableAtlasAggregateInputFps/o)));return Math.min(l,u)}function VN(t,n){return{acceleration:Xn.directDecodeAcceleration,latencyMode:Xn.directLatencyMode}}const eu={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},KN=[{id:"connection",label:"Connection",icon:eh},{id:"remote-access",label:"Remote Access",icon:ga},{id:"capture-audio",label:"Capture & Audio",icon:Gg},{id:"agent",label:"Agent",icon:ec}];function Pp(t,n){return t?.settings?.[n]||eu.settings[n]||{}}function ww(t,n){return{...t,settings:{...t.settings,[n.section]:{...Pp(t,n.section),[n.key]:n.value}}}}function Mg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function Kc({icon:t,title:n,description:r,children:o,recommended:l=!1}){return i.jsxs("div",{className:"product-setting-row",children:[i.jsx("div",{className:"product-setting-control",children:o}),t&&i.jsx("span",{className:"product-setting-icon",children:i.jsx(t,{size:17})}),i.jsxs("div",{className:"product-setting-copy",children:[i.jsx("strong",{children:n}),l&&i.jsx("em",{children:"Recommended"}),i.jsx("small",{children:r})]})]})}function Pf({checked:t,onChange:n,label:r}){return i.jsxs("label",{className:"product-switch",children:[i.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:o=>n(o.target.checked)}),i.jsx("span",{})]})}function xw({value:t,onChange:n,options:r,label:o}){return i.jsx("select",{"aria-label":o,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>i.jsx("option",{value:l,children:u},l))})}function QN({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:o="",initialTab:l="connection",pin:u,agent:f,captureGallery:h}){const[g,y]=d.useState(l),[w,b]=d.useState(null),[S,k]=d.useState("loading"),[N,A]=d.useState(""),[j,I]=d.useState("idle"),[T,_]=d.useState(""),B=d.useRef(null),F=d.useRef(null),H=d.useRef([]),D=d.useRef(Promise.resolve()),K=d.useRef(0),z=d.useRef(0);d.useEffect(()=>{const Se=++z.current;let ae=!0;return H.current=[],F.current=null,B.current=null,D.current=Promise.resolve(),k("loading"),rt("/api/settings",void 0,t).then(ye=>{if(!ae||Se!==z.current)return;const Pe=Mg(ye);F.current=Pe,B.current=Pe,b(Pe),k("saved")}).catch(ye=>{!ae||Se!==z.current||(A(ye instanceof Error?ye.message:String(ye)),F.current=eu,B.current=eu,b(eu),k("failed"))}),()=>{ae=!1}},[t]);const W=async(Se,ae,ye)=>{const Pe={id:++K.current,section:Se,key:ae,value:ye},de=z.current;H.current.push(Pe);const Qe=ww(B.current||F.current||eu,Pe);B.current=Qe,b(Qe),k("saving"),A(""),D.current=D.current.then(async()=>{if(de!==z.current)return;let ue=null,_e=null;for(let Ee=0;Ee<2&&!ue;Ee+=1){const Ge=F.current||eu;try{const me=await rt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Ge.revision,[Pe.section]:{[Pe.key]:Pe.value}})},t);ue=Mg(me)}catch(me){if(_e=me,Ee!==0||!String(me instanceof Error?me.message:me).startsWith("409 "))break;try{const ke=await rt("/api/settings",void 0,t);if(de!==z.current)return;F.current=Mg(ke)}catch(ke){_e=ke;break}}}if(de!==z.current)return;H.current=H.current.filter(Ee=>Ee.id!==Pe.id),ue&&(F.current=ue);const Ze=F.current||eu,at=H.current.reduce(ww,Ze);B.current=at,b(at),ue?(A(""),k(H.current.length>0?"saving":"saved")):(k(H.current.length>0?"saving":"failed"),A(_e instanceof Error?_e.message:String(_e||"Settings could not be saved.")))}),await D.current},q=(Se,ae)=>ye=>{W(Se,ae,ye)},V=async()=>{if(n!=="hub"||!r||!o){I("failed"),_("Sign in to this Hub before changing its runtime role.");return}I("changing"),_("");try{const Se=await rt("/api/runtime/status",void 0,t);await rt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({role:"client"})},t),I("accepted"),await c0({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),$M(5179)}catch(Se){I("failed"),_(Se instanceof Error?Se.message:String(Se))}},X=Pp(w,"security"),ve=Pp(w,"control"),J=Pp(w,"filesAudio"),$=`settings-panel-${g}`,P=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,i.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime role"}),i.jsx("h3",{children:"Use this computer as a Client"})]}),i.jsx(Kx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),j==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{V()},disabled:j==="changing"||n!=="hub",type:"button",children:j==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),se=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Remote access"}),i.jsx("h3",{children:"Who may connect?"})]}),i.jsx(nl,{size:20})]}),i.jsx(Kc,{icon:ga,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(xw,{value:String(X.accessMode),onChange:q("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Session permissions"}),i.jsx("h3",{children:"What may remote users do?"})]}),i.jsx(Ar,{size:20})]}),i.jsx(Kc,{icon:Ar,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(Pf,{checked:!!ve.allowKeyboardMouse,onChange:q("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(Kc,{icon:Vx,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:i.jsx(Pf,{checked:!!ve.allowRemoteRestart,onChange:q("control","allowRemoteRestart"),label:"Power actions"})}),i.jsx(Kc,{icon:Gg,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:i.jsx(Pf,{checked:!!J.allowFileTransfer,onChange:q("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(Kc,{icon:Jl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(Pf,{checked:!!J.allowRemoteAudio,onChange:q("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),we=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Capture"}),i.jsx("h3",{children:"Recording defaults"})]}),i.jsx(Gg,{size:20})]}),i.jsx(Kc,{icon:Jl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:i.jsx(Pf,{checked:!!J.rollingBufferEnabled,onChange:q("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),i.jsx(Kc,{icon:Jl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:i.jsx(xw,{value:Number(J.timelapseIntervalSeconds),onChange:Se=>q("filesAudio","timelapseIntervalSeconds")(Number(Se)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Z=g==="connection"?P:g==="remote-access"?se:g==="capture-audio"?we:f;return i.jsxs("section",{className:"settings-page",children:[i.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:KN.map(({id:Se,label:ae,icon:ye})=>i.jsxs("button",{className:g===Se?"active":"",id:`settings-tab-${Se}`,role:"tab","aria-selected":g===Se,"aria-controls":`settings-panel-${Se}`,tabIndex:g===Se?0:-1,onClick:()=>y(Se),type:"button",children:[i.jsx(ye,{size:16}),ae]},Se))}),S==="saving"&&i.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),N&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:N}),i.jsx("section",{className:"settings-page-panel",id:$,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Z})]})}function YN({children:t}){return i.jsx("div",{className:"settings-tab-content",children:t})}const Sw={enabled:!1};function Cw(t){return{enabled:t?.enabled===!0}}async function XN(t,n,r){let o=null;for(let l=0;l<2;l+=1){const u=await rt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await rt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(o=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw o}function ZN({hubUrl:t,showToast:n}){const[r,o]=d.useState(Sw),[l,u]=d.useState(null),[f,h]=d.useState(""),[g,y]=d.useState(""),[w,b]=d.useState(""),S=d.useRef(0),k=d.useRef(null);d.useEffect(()=>{let H=!0;k.current?.abort();const D=new AbortController;k.current=D;const K=++S.current;return u(null),o(Sw),h(""),b(""),y(""),rt("/api/settings/agent",{signal:D.signal},t).then(z=>{!H||D.signal.aborted||K!==S.current||(u(z.settings),o(Cw(z.settings)))}).catch(z=>{H&&!D.signal.aborted&&K===S.current&&b(z instanceof Error?z.message:String(z))}),()=>{H=!1,D.abort(),k.current===D&&(k.current=null)}},[t]);const N=(H,D)=>o(K=>({...K,[H]:D})),A=H=>{u(H),o(Cw(H))},j=()=>({generation:S.current,controller:k.current}),I=H=>H.generation===S.current&&H.controller!==null&&H.controller===k.current&&!H.controller.signal.aborted,T=async()=>{if(!l){b("Agent settings are not available yet.");return}const H=j();if(I(H)){h("save"),b(""),y("");try{if(await XN(r.enabled,t,H.controller.signal),!I(H))return;const D=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(D.settings),y("Codex Agent settings saved.")}catch(D){I(H)&&b(D instanceof Error?D.message:String(D))}finally{I(H)&&h("")}}},_=async()=>{const H=j();if(I(H)){h("test"),b(""),y("");try{const D=await rt("/api/settings/agent/test",{method:"POST",signal:H.controller.signal,body:JSON.stringify({})},t);if(!I(H))return;const K=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(K.settings);const z=Number.isFinite(D.connection?.latencyMs)?Math.max(0,Math.round(D.connection.latencyMs)):null;n(`Codex Agent connection verified${z!==null?` in ${z} ms.`:"."}`,"success")}catch(D){I(H)&&b(D instanceof Error?D.message:String(D))}finally{I(H)&&h("")}}},B=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",F=l!==null;return i.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[i.jsx("section",{className:"settings-section-card agent-enable-card",children:i.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[i.jsx("input",{type:"checkbox",checked:r.enabled,onChange:H=>N("enabled",H.target.checked),disabled:!F||f!==""}),i.jsx("span",{children:"Enable Codex Agent"})]})}),w&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:w}),g&&i.jsx("div",{className:"agent-settings-alert success",role:"status",children:g}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Connection"}),i.jsx("h3",{children:"Codex SDK / CLI"})]}),i.jsx(ga,{size:20})]}),i.jsxs("div",{className:"agent-connection-row",children:[i.jsx("span",{className:`agent-connection-dot ${B?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),i.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"}),i.jsxs("button",{className:"settings-reset",onClick:()=>{_()},disabled:f!=="",type:"button",children:[i.jsx(gk,{size:15})," ",f==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(vk,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),i.jsx("div",{className:"settings-action-row agent-settings-actions",children:i.jsxs("button",{className:"text-button primary",onClick:()=>{T()},disabled:!F||f!=="",type:"button",children:[i.jsx(yk,{size:15})," ",f==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function Ov(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Id(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function JN(t,n="data-id"){const r=Id(t,n);return r?r.getAttribute(n):null}function rm(t,n="data-id"){const r=Id(t,n);return r?uh(r,n):null}function uh(t,n="data-id"){const r=t.getAttribute(n);return r?eT(r):null}function Fa(t){return typeof t=="string"?":"+t:t}function eT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function tT(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var cs=tT();function Bv(t){Object.assign(cs,t)}function kw(t,n,r){function o(l){const u=Id(l);if(!u)return;const f=uh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}cs.addEvent(t,r,o)}function Ld(t,n){kw(t,n,"click"),n.dblclick&&kw(t,n.dblclick,"dblclick")}function nT(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function aT(t,n,r){for(let o=0;o<rl.length;o++){if(o===r)continue;const l=rl[o],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var J0=new Date,Qp=!1,pp=[],rl=[],Mw=t=>{const n=t.target;if(Qp||!n.isConnected){Qp=!1;return}for(let r=rl.length-1;r>=0;r--){const{node:o,date:l,props:u}=rl[r];if(!(l>J0)&&!o.contains(n)&&o!==n&&(aT(o,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},rT=t=>{J0=new Date,Qp=!0;for(let n=rl.length-1;n>=0;n--){const{node:r}=rl[n];if(!r.contains(t.target)&&r!==t.target){Qp=!1;break}}};function ho(t,n){pp.length||(pp=[cs.addGlobalEvent("click",Mw,t),cs.addGlobalEvent("contextmenu",Mw,t),cs.addGlobalEvent("mousedown",rT,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return rl.push(r),{destroy(){nT(rl,r),rl.length||(pp.forEach(o=>o()),pp=[])}}}var hp=t=>t.indexOf("bottom")!==-1,gp=t=>t.indexOf("left")!==-1,vp=t=>t.indexOf("right")!==-1,Ag=t=>t.indexOf("top")!==-1,Aw=t=>t.indexOf("fit")!==-1,_f=t=>t.indexOf("overlap")!==-1,sT=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),iT=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function oT(t,n){let r=0;const o=cs.getTopNode(t);for(;t&&t!==o;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,Cr,Ff,ar;function eS(t,n,r="bottom",o=0,l=0){if(!t)return null;ma=o,Cr=l,Ff="auto";let u=0,f=0,h=r;const g=tS(t),y=_f(r)?cs.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),S=y.getBoundingClientRect(),k=window.getComputedStyle(y),N={left:0,top:0,bottom:0,right:0};for(const B in N){const F=`border-${B}-width`;N[B]=parseFloat(k.getPropertyValue(F))}if(n){const B=oT(n,g);u=Math.max(B+1,20)}if(n){if(ar=n.getBoundingClientRect(),Aw(r)&&(Ff=ar.width+"px"),r!=="point")if(sT(r))Aw(r)?ma=0:(ma=S.width/2,f=1),Cr=(S.height-b.height)/2;else{const B=_f(r)?0:1;ma=vp(r)?ar.right+B:ar.left-B,Cr=hp(r)?ar.bottom+1:ar.top;const F=iT(r);F&&(vp(r)||gp(r)?F==="center"?Cr-=(b.height-ar.height)/2:F==="end"&&(Cr-=b.height-ar.height):(hp(r)||Ag(r))&&(F==="center"?ma-=(b.width-ar.width)/2:F==="end"&&(ma-=b.width-ar.width),_f(r)||(ma+=1)))}}else ar={left:o,right:o,top:l,bottom:l};const A=(gp(r)||vp(r))&&(hp(r)||Ag(r));gp(r)&&(f=2);const j=ma-b.width-S.left;n&&gp(r)&&!A&&j<0&&(ma=ar.right,f=0,h=h.replace("left","right"));const I=ma+b.width*(1-f/2)-S.right;if(I>0)if(!vp(r))ma=S.right-N.right-b.width;else{const B=ar.left-S.x-b.width;n&&!A&&B>=0?(ma=ar.left-b.width,h=h.replace("right","left")):ma-=I+N.right}f&&(ma=Math.round(ma-b.width*f/2));const T=j<0||I>0||!A;Ag(r)&&(Cr=ar.top-b.height,n&&Cr<S.y&&T&&(Cr=ar.bottom,h=h.replace("top","bottom")));const _=Cr+b.height-S.bottom;return _>0&&(n&&hp(r)&&T?(Cr-=b.height+ar.height+1,h=h.replace("bottom","top")):Cr-=_+N.bottom),ma-=w.left+N.left,Cr-=w.top+N.top,ma=(_f(r)?ma:Math.max(ma,0))+y.scrollLeft,Cr=(_f(r)?Cr:Math.max(Cr,0))+y.scrollTop,Ff=Ff||"auto",{at:h,x:ma,y:Cr,z:u,width:Ff}}function tS(t){const n=cs.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function lT(t){const n=[];let r=t;const o=cs.getTopNode(t);for(;r&&r!==o&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var Nw=new Date().valueOf();function Hv(){return Nw+=1,Nw}function Mr(t){return t<10?"0"+t:t.toString()}function cT(t){const n=Mr(t);return n.length==2?"0"+n:n}function nS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Ng(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const o=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-o.getTime())/864e5);return 1+Math.floor(l/7)}var Tw=["",""];function uT(t,n,r){switch(t){case"%d":return Mr(n.getDate());case"%m":return Mr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return Mr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return Mr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return Mr(n.getHours());case"%i":return Mr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||Tw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||Tw)[1];case"%s":return Mr(n.getSeconds());case"%S":return cT(n.getMilliseconds());case"%W":return Mr(Ng(n));case"%w":{const o=r.weekStart??1;if(o===1)return Mr(Ng(n));const l=(n.getDay()-o+7)%7,u=(1-o+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),Mr(Ng(f))}case"%c":{let o=n.getFullYear()+"";return o+="-"+Mr(n.getMonth()+1),o+="-"+Mr(n.getDate()),o+="T",o+=Mr(n.getHours()),o+=":"+Mr(n.getMinutes()),o+=":"+Mr(n.getSeconds()),o}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var dT=/%[a-zA-Z]/g;function Td(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(dT,o=>uT(o,r,n))):""}}function Rw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function hv(t,n){for(const r in n){const o=n[r];Rw(t[r])&&Rw(o)?t[r]=hv({...t[r]},n[r]):t[r]=n[r]}return t}function lm(t){return{getGroup(n){const r=t[n];return o=>r&&r[o]||o},getRaw(){return t},extend(n,r){if(!n)return this;let o;return r?o=hv({...n},t):o=hv({...t},n),lm(o)}}}var fT=a0();const mT="en-US",pT={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},hT={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},gT={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},aS={core:hT,calendar:pT,formats:gT,lang:mT},zv=d.createContext(""),rS=d.createContext({}),Mi=d.createContext(null),sS=d.createContext(null),Ba=Object.freeze(Object.defineProperty({__proto__:null,fieldId:sS,helpers:rS,i18n:Mi,theme:zv},Symbol.toStringTag,{value:"Module"}));function iS(t){const n=d.useContext(sS),[r]=d.useState(()=>t||n||Hv());return r}function Jf({type:t="",css:n="",icon:r="",disabled:o=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(S=>S!=="").map(S=>"wx-"+S).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return i.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:o,onClick:w,"data-tooltip-text":u,children:[r&&i.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function vT({id:t,label:n="",inputValue:r="",value:o=!1,onChange:l,disabled:u=!1,css:f=""}){const h=iS(t),[g,y]=po(o),w=({target:b})=>{const S=b.checked;y(S),l&&l({value:S,inputValue:r})};return i.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[i.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),i.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[i.jsx("span",{className:"wx-2IvefP wx-before"}),n&&i.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function $v({theme:t="",target:n,children:r}){const o=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);o.current||(o.current=document.createElement("div"));const h=d.useContext(zv);return d.useEffect(()=>{f(n||yT(l.current)||cs.getTopNode(l.current))},[l.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?fT.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function yT(t){const n=cs.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function bT({left:t=0,top:n=0,at:r="bottom",parent:o=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,S]=d.useState(0),[k,N]=d.useState("auto"),[A,j]=d.useState(!1),I=d.useRef(null),T=d.useRef(null),_=d.useRef(f);d.useEffect(()=>{_.current=f},[f]);function B(H){return o&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*o.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:H}const F=d.useCallback(()=>{if(!I.current)return;const H=eS(I.current,o,r,t,n);H&&(w(H.x),S(H.y),N(B(H.width)))},[I,o,r,t,n,l]);return d.useLayoutEffect(()=>{const H=K=>{_.current&&K.target!==T.current&&I.current&&!I.current.contains(K.target)&&_.current(K)};let D;return requestAnimationFrame(()=>{F(),j(!0),g&&I.current&&(T.current=tS(I.current),T.current&&T.current.addEventListener("scroll",H,!0)),o&&(D=new ResizeObserver(F),D.observe(o))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",H,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[o,r,t,n]),d.useEffect(()=>{const H=D=>{_.current&&_.current(D)};if(I.current)return ho(I.current,{callback:H,parent:()=>o}).destroy},[o]),i.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:A?"visible":"hidden",top:b+"px",left:y+"px",width:k},children:h})}function wT({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:o=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),S=d.useRef(o);return d.useEffect(()=>{S.current=o},[o]),d.useEffect(()=>{if(r){const k=h.current;if(k){const N=k.getBoundingClientRect(),A=document.body.getBoundingClientRect();N.right>=A.right&&b("end"),N.bottom>=A.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const k=N=>{S.current&&S.current(N)};return ho(h.current,k).destroy}},[]),i.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function Uv({position:t="bottom",align:n="start",autoFit:r=!0,inline:o=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),i.jsxs(i.Fragment,{children:[g&&(o?i.jsx(wT,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):i.jsx($v,{children:i.jsx(bT,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),i.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function dh(){return lm(aS)}function xT(){let t=null,n=!1,r=!1,o,l,u,f;const h=(b,S,k,N,A)=>{o=b,l=S,u=k,f=N,r=A},g=b=>{t=b,n=t!==null,u(t)},y=(b,S)=>{if(!r&&b!==null&&o){const k=o.querySelectorAll(".wx-list > .wx-item")[b];k&&(k.scrollIntoView({block:"nearest"}),S&&S.preventDefault())}},w=(b,S)=>{const k=b===null?null:Math.max(0,Math.min(t+b,l.length-1));k!==t&&(g(k),o?y(k,S):requestAnimationFrame(()=>y(k,S)))};return{move:b=>{const S=rm(b),k=l.findIndex(N=>N.id===S);k!==t&&g(k)},keydown:(b,S)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:S||0,b);break;case"ArrowUp":w(n?-1:S||0,b);break}},init:h,navigate:w}}const jw=10,ST=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:o}){return i.jsxs(i.Fragment,{children:[n&&i.jsx(vT,{id:t.id,css:"wx-list-checkbox",value:o&&o.includes(t.id)}),r?Ov(r,{option:t}):t.label]})});function Ew({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:o,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return i.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:i.jsx(ST,{data:h,checkboxes:o,itemTemplate:l,value:u})},h.id)})}function fh({items:t=[],children:n,onSelect:r,onReady:o,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(xT()),[S,k]=d.useState(null),N=d.useRef(S),[A,j]=d.useState(0),[I,T]=d.useState(24),_=d.useRef(!1),B=(d.useContext(Mi)||dh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const H=d.useRef(h);d.useEffect(()=>{H.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ae=>{ae&&ae.stopPropagation();const ye=F.current,Pe=H.current,de=N.current;let Qe;const ue=ye[de]?.id;f?Pe&&Pe.includes(ue)?Qe=Pe.filter(_e=>_e!==ue):Qe=[...Pe||[],ue]:Qe=ue,r&&r({id:Qe})},[f,r]),z=d.useRef(K);d.useEffect(()=>{z.current=K},[K]);const W=d.useCallback(ae=>{if(y.current){let ye=ae*D.current-y.current.clientHeight+D.current;j(ye),y.current.scrollTop=ye}},[D.current]),q=d.useCallback(ae=>{y.current=ae,l&&(ae&&!w.current&&N.current!==null&&requestAnimationFrame(()=>{y.current&&(W(N.current),w.current=!0)}),ae||(w.current=!1))},[W]),V=d.useCallback(ae=>{if(!ae||_.current)return;const ye=ae.getBoundingClientRect().height;ye&&(T(ye),D.current=ye,_.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ae=>{k(ae),N.current=ae},ae=>z.current(ae),l)},[t,y.current,l]),d.useEffect(()=>{const ae=(Pe,de)=>{b.current.navigate(Pe,de),W(N.current)},ye=(Pe,de)=>{const Qe=N.current,ue=F.current;if(Qe!==0&&Qe!==ue.length-1&&(Pe.key==="ArrowDown"||Pe.key==="ArrowUp")&&Pe.preventDefault(),b.current.keydown(Pe,de),y.current){const _e=y.current.scrollTop<=N.current*D.current,Ze=y.current.scrollTop+y.current.clientHeight>=N.current*D.current+D.current;_e?Ze||W(N.current):(y.current.scrollTop=N.current*D.current,j(y.current.scrollTop))}};o&&o({navigate:l?ae:b.current.navigate,keydown:l?ye:b.current.keydown,move:b.current.move})},[]);const X=d.useRef(0),ve=d.useRef(t);ve.current!==t&&(ve.current=t,X.current+=1);const J=d.useCallback(()=>{b.current.navigate(null)},[b]),$=d.useCallback(ae=>{l&&j(ae.target.scrollTop)},[l]),P=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,A]),se=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ae=Math.floor(A/I),ye=ae+P;return{start:Math.max(0,ae-jw),end:Math.min(t.length,ye+jw)}},[l,t,A,I,P]),we=d.useMemo(()=>{if(!l)return t;const{start:ae,end:ye}=se;return t.slice(ae,ye).map(Pe=>({...Pe}))},[l,t,se]),Z=se.start*I,Se=t.length*I;return d.useEffect(()=>{l&&j(0)},[t,l]),d.useEffect(()=>{S===null&&(w.current=!1)},[S]),S===null?null:i.jsx(Uv,{onCancel:J,...g,children:i.jsx("div",{className:"wx-233fr7 wx-list",ref:q,onClick:K,onMouseMove:b.current.move,onScroll:$,children:t.length?l?i.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${Se}px`},children:i.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${Z}px)`},children:i.jsx(Ew,{visibleRange:se,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h})})}):i.jsx(Ew,{visibleRange:se,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h}):i.jsx("div",{className:"wx-233fr7 wx-no-data",children:B("No data")})})},X.current)}function qv({value:t="",id:n,readonly:r=!1,focus:o=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:S="",clear:k=!1,onChange:N}){const A=iS(n),[j,I]=po(t),T=d.useRef(null),_=d.useMemo(()=>S&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[S,b]),B=d.useMemo(()=>S&&b.indexOf("wx-icon-left")!==-1,[S,b]);d.useEffect(()=>{const z=setTimeout(()=>{o&&T.current&&T.current.focus(),l&&T.current&&T.current.select()},1);return()=>clearTimeout(z)},[o,l]);const F=d.useCallback(z=>{const W=z.target.value;I(W),N&&N({value:W,input:!0})},[N]),H=d.useCallback(z=>N&&N({value:z.target.value}),[N]);function D(z){z.stopPropagation(),I(""),N&&N({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const z=H,W=T.current;return W.addEventListener("change",z),()=>{W&&W.removeEventListener("change",z)}},[H]),i.jsxs("div",{className:`wx-hQ64J4 wx-text ${_} ${g?"wx-error":""} ${h?"wx-disabled":""} ${k?"wx-clear":""}`,"data-tooltip-text":w,children:[i.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:A,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:j,onInput:F}),k&&!h&&j?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),B&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`})]}):S?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`}):null]})}function CT({date:t,type:n,part:r,onShift:o}){const{calendar:l,formats:u}=d.useContext(Mi).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return Td(u.monthYearFormat,l)(t);case"year":return Td(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=nS(f),b=Td(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){o&&o({diff:0,type:n})}return i.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>o&&o({diff:-1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"}),i.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>o&&o({diff:1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Wv({onClick:t,children:n}){return i.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function kT({value:t,current:n,part:r="",markers:o=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Mi)||dh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,H,D)=>new Date(F.getFullYear(),F.getMonth()+(H||0),F.getDate()+(D||0));let b=r!=="normal";function S(F){const H=F.getDay();return H===0||H===6}function k(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function N(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const A=d.useRef(0);function j(F,H){H.timeStamp!==A.current&&(A.current=H.timeStamp,H.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),T=d.useMemo(()=>{const F=k(),H=N(),D=n.getMonth();let K=[];for(let z=F;z<=H;z.setDate(z.getDate()+1)){const W={day:z.getDate(),in:z.getMonth()===D,date:z.valueOf()};let q="";if(q+=W.in?"":" wx-inactive",q+=I.indexOf(W.date)>-1?" wx-selected":"",b){const V=W.date==I[0],X=W.date==I[1];V&&!X?q+=" wx-left":X&&!V&&(q+=" wx-right"),W.date>I[0]&&W.date<I[1]&&(q+=" wx-inrange")}if(q+=S(z)?" wx-weekend":"",o){const V=o(z);V&&(q+=" "+V)}K.push({...W,css:q})}return K},[n,I,b,o]),_=d.useRef(null);let B=d.useRef({});return B.current.click=j,d.useEffect(()=>{Ld(_.current,B.current)},[]),i.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[i.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>i.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),i.jsx("div",{className:"wx-398RBS wx-days",ref:_,children:T.map(F=>i.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function MT({value:t,current:n,part:r,onCancel:o,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Mi).getRaw().calendar,S=b.monthShort||[],k=d.useMemo(()=>y.getMonth(),[y]),N=d.useCallback((I,T)=>{if(I!=null){T.stopPropagation();const _=new Date(y);_.setMonth(I),w(_),u&&u({current:_})}r==="normal"&&g(new Date(y)),o&&o()},[y,r,u,o]),A=d.useCallback(()=>{const I=new Date(oS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),j=d.useCallback(I=>{const T=I.target.closest("[data-id]");if(T){const _=parseInt(T.getAttribute("data-id"),10);N(_,I)}},[N]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:j,children:S.map((I,T)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(k===T?" wx-current":""),"data-id":T,children:I},T))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx(Wv,{onClick:A,children:b.done})})]})}const Tg="wx-1XEF33",AT=({value:t,current:n,onCancel:r,onChange:o,onShift:l,part:u})=>{const f=d.useContext(Mi).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),S=d.useMemo(()=>{const{start:I,end:T}=nS(b),_=[];for(let B=I;B<=T;++B)_.push(B);return _},[b]),k={click:N};function N(I,T){if(I){T.stopPropagation();const _=new Date(h);_.setFullYear(I),g(_),l&&l({current:_})}u==="normal"&&w(new Date(h)),r&&r()}function A(){const I=new Date(oS(y,u)||h);I.setFullYear(h.getFullYear()),o&&o(I)}const j=d.useRef(null);return d.useEffect(()=>{j.current&&Ld(j.current,k)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Tg+" wx-years",ref:j,children:S.map((I,T)=>i.jsx("div",{className:Tg+` wx-year ${b==I?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":I,children:I},T))}),i.jsx("div",{className:Tg+" wx-buttons",children:i.jsx(Wv,{onClick:A,children:f.done})})]})},Dw={month:{component:kT,next:TT,prev:NT},year:{component:MT,next:jT,prev:RT},duodecade:{component:AT,next:DT,prev:ET}};function NT(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function TT(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function RT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function jT(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function ET(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function DT(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function oS(t,n){let r;if(n==="normal")r=t;else{const{start:o,end:l}=t;n==="left"?r=o:n=="right"?r=l:r=o&&l}return r}const IT=["clear","today"];function LT(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function PT({value:t,current:n,onCurrentChange:r,part:o="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Mi).getGroup("calendar"),[w,b]=d.useState("month"),S=Array.isArray(u)?u:u?IT:[],k=(T,_)=>{T.preventDefault(),g&&g({value:_})},N=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},A=T=>{const{diff:_,current:B}=T;if(_===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(_){const F=Dw[w];r(_>0?F.next(n):F.prev(n))}else B&&r(B);h&&h()},j=T=>{b("month"),g&&g({select:!0,value:T})},I=d.useMemo(()=>Dw[w].component,[w]);return i.jsx("div",{className:`wx-2Gr4AS wx-calendar ${o!=="normal"&&o!=="both"?"wx-part":""} ${f}`,children:i.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[i.jsx(CT,{date:n,part:o,type:w,onShift:A}),i.jsxs("div",{children:[i.jsx(I,{value:t,current:n,onCurrentChange:r,part:o,markers:l,onCancel:N,onChange:j,onShift:A}),w==="month"&&S.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:S.map(T=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx(Wv,{onClick:_=>k(_,LT(T)),children:y(T)})},T))})]})]})})}function Gv(t){let{words:n=null,optional:r=!1,children:o}=t,l=d.useContext(Mi);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=lm(aS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return i.jsx(Mi.Provider,{value:u,children:o})}function Iw(t,n,r,o){if(!t||o){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const _T=["clear","today"];function lS({value:t,current:n,markers:r=null,buttons:o=_T,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{Iw(g,f,y,!1)},[f,g]);const w=d.useCallback(S=>{const k=S.value;k?(h(new Date(k)),Iw(g,new Date(k),y,!0)):h(null),u&&u({value:k?new Date(k):null})},[u,g]),b=d.useCallback(S=>{y(S)},[y]);return g?i.jsx(Gv,{children:i.jsx(PT,{value:f,current:g,markers:r,buttons:o,css:l,onChange:w,onCurrentChange:b})}):null}function FT(t){return t||(t={}),t.width||(t.width="unset"),t}const OT=["clear","today"];function BT({value:t,id:n,disabled:r=!1,error:o=!1,placeholder:l="",format:u="",buttons:f=OT,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:S,dropdown:k={}}){const{calendar:N,formats:A}=(d.useContext(Mi)||dh()).getRaw(),j=u||A?.dateFormat;let I=typeof j=="function"?j:Td(j,N);const[T,_]=d.useState(t),[B,F]=d.useState(!1);d.useEffect(()=>{_(t)},[t]);function H(){F(!1)}function D(W){const q=W===T||W&&T&&W.valueOf()===T.valueOf()||!W&&!T;_(W),q||S&&S({value:W}),setTimeout(H,1)}const K=d.useMemo(()=>T?I(T):"",[T,I]);function z({value:W,input:q}){if(!w&&!b||q)return;let V=typeof w=="function"?w(W):W?new Date(W):null;V=isNaN(V)?T||null:V||null,D(V)}return d.useEffect(()=>{const W=H;return window.addEventListener("scroll",W),()=>window.removeEventListener("scroll",W)},[]),i.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[i.jsx(qv,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:o,placeholder:l,onInput:H,onChange:z,icon:"wxi-calendar",clear:b}),B&&!r&&i.jsx(Uv,{onCancel:H,...FT(k),children:i.jsx(lS,{buttons:f,value:T,onChange:W=>D(W.value)})})]})}function HT({value:t="",options:n=[],textOptions:r=null,placeholder:o="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:S,dropdown:k={}}){const N=d.useRef(null),A=d.useRef(null);let[j,I]=po(t);function T(D){N.current=D.navigate,A.current=D.keydown}const _=d.useMemo(()=>j||j===0?(r||n).find(D=>D.id===j):null,[j,r,n]),B=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),N.current(null),S&&S({value:D}))},[I,S]),F=d.useCallback(D=>{D.stopPropagation(),I(""),S&&S({value:""})},[I,S]),H=d.useCallback(()=>n.findIndex(D=>D.id===j),[n,j]);return i.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>N.current(H()),onKeyDown:D=>A.current(D,H()),tabIndex:0,"data-tooltip-text":h,children:[i.jsx("div",{className:"wx-2YgblL wx-label",children:_?b?b(_):_[g]:o?i.jsx("span",{className:"wx-2YgblL wx-placeholder",children:o}):" "}),y&&!l&&j?i.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):i.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&i.jsx(fh,{items:n,onReady:T,onSelect:B,...k,children:({option:D})=>b?b(D):D[g]})]})}const zT=({options:t=[],value:n="",css:r="",children:o,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),i.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>i.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:o?Ov(o,{option:g}):i.jsxs(i.Fragment,{children:[g.icon&&i.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&i.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function $T({notice:t={}}){function n(){t.remove&&t.remove()}return i.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[i.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),i.jsx("div",{className:"wx-11sNg5 wx-button",children:i.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function UT({data:t=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>i.jsx($T,{notice:n},n.id))})}function gv({title:t="",buttons:n=["cancel","ok"],header:r,children:o,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Mi)||dh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(S){switch(S.code){case"Enter":{const k=S.target.tagName;if(k==="TEXTAREA"||k==="BUTTON")return;f&&f({event:S});break}case"Escape":h&&h({event:S});break}}function b(S,k){const N={event:S,button:k};k==="cancel"?h&&h(N):f&&f(N)}return i.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:i.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?i.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),i.jsx("div",{children:o}),l||n&&i.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(S=>i.jsx("div",{className:"wx-1FxkZa wx-button",children:i.jsx(Jf,{type:`block ${S==="ok"?"primary":"secondary"}`,onClick:k=>b(k,S),children:g(S)})},S))})]})})}function qT({children:t},n){const[r,o]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return o(h),new Promise((g,y)=>{h.resolve=w=>{o(null),g(w)},h.reject=w=>{o(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||Hv(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),i.jsxs(i.Fragment,{children:[t,r&&i.jsx(gv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),i.jsx(UT,{data:l})]})}const WT=d.forwardRef(qT);function GT(t){let{children:n}=t,r=d.useRef();const o=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return i.jsx(rS.Provider,{value:o,children:i.jsx(WT,{ref:r,children:n})})}const VT=({value:t=!1,type:n="",icon:r="",disabled:o=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:S,onChange:k})=>{const[N,A]=po(t),j=d.useMemo(()=>(N?"pressed":"")+(n?" "+n:""),[N,n]),I=d.useCallback(T=>{let _=!N;u&&u(T),T.defaultPrevented||(A(_),k&&k({value:_}))},[N,u,k]);return N&&S?i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o,children:Ov(S,{value:N})}):b?i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o,children:b}):i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o})};function KT(){return i.jsx(i.Fragment,{})}function Lw(t){const{fonts:n=!0,children:r}=t;return i.jsx(zv.Provider,{value:"willow",children:i.jsxs(i.Fragment,{children:[r&&r&&i.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&i.jsxs(i.Fragment,{children:[i.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),i.jsx(KT,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Bv(cs);const Vv={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 cS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var QT=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const o=r.get(n);this.setLevel(o,o.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:Pw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),o=this.byId(r.parent),l=yp(o,r.id)+1;t.parent=o.id,t.$level=o.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(o=>o.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const o=this._pool.get(r.parent),l=yp(o,r.id);r={...r,...n},o&&l>=0&&(o.data[l]=r,o.data=[...o.data]),this._pool.set(r.id,r)}move(t,n,r){const o=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!o||!u)return;const h=this._pool.get(o.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=yp(h,o.id);YT(h,y);const w=l?g.data.length:yp(g,u.id)+(n==="after"?1:0);if(Pw(g,w,o),h.id===g.id&&y===w)return null;o.parent=g.id,o.$level!==f&&(o.$level=f,this.setLevel(o,f+1,!0)),this.update(o.id,o),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&uS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((o,l)=>{t(this.byId(o.id),l),this.eachChild(t,o.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(o=>(r&&(o={...o},this._pool.set(o.id,o)),o.$level=n,o.data&&this.setLevel(o,n+1,r),o)))}};function uS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&uS(r.data,n)})}function YT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Pw(t,n,r){const o=[...t.data];o.splice(n,0,r),t.data=o}function yp(t,n){return t?.data.findIndex(r=>r.id===n)}var dS=2,XT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const o={};return this._wrapProperties(n,this._state,this._values,"",o,r),o}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,o,l,u,f){for(const h in n){const g=r[h],y=o[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(o[h]=w),f&dS?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),o[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,o,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,o,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],o=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(o,1):o())},__parse:function(l){return n=l,!0}}}};function _w(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var ZT=class{constructor(n,r,o,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=o,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>fS(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const o in n)if(this._prev[o]!==n[o]){const l=this._parsers[o];r[o]=l?l(n[o]):n[o]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,dS);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const o=n.signals[r];o&&o()}}}setState(n,r=[]){const o=this._setter(n);return this._triggerUpdates(o,r),o}_triggerUpdates(n,r){const o=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<o.length;u++){const f=o[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((o,l)=>o.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function fS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>fS(u,n,r+1));return Math.max(...l)}var JT=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,o){let l=this._handlers[n];l?o&&o.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],o&&o.tag&&this._tag.set(r,o.tag)}intercept(n,r,o){this.on(n,r,{...o,intercept:!0})}detach(n){for(const r in this._handlers){const o=this._handlers[r];for(let l=o.length-1;l>=0;l--)this._tag.get(o[l])===n&&o.splice(l,1)}}async exec(n,r){const o=this._handlers[n];if(o)for(let l=0;l<o.length;l++){const u=o[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const Sd=1024;function sm(t){return t<Sd?`${t} B`:t<Sd**2?`${(t/Sd).toFixed(1)} KB`:t<Sd**3?`${(t/Sd**2).toFixed(1)} MB`:`${(t/Sd**3).toFixed(1)} GB`}function Fw(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),o=t.filter(f=>f.type!=="folder"),l=r.sort(Ow(n)),u=o.sort(Ow(n));return[...l,...u]}function eR(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function tR(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function Ow({key:t,order:n}){const r=n==="asc"?eR:tR;return(o,l)=>r(o[t],l[t])}function Kv(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function nR(t){return t.length>1?t[t.length-2].id:null}let aR=class extends QT{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,o){!n||!n.length||(n.forEach(l=>this.parseId(l,o?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const o=n.id,l=o.lastIndexOf("/");if(n.parent=r??(l===0?"/":o.slice(0,l)),n.name=o.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let o=this.byId(n);if(!o)return r;for(;o.id!==0;)r.push(o),o=this.byId(o.parent);return r.reverse()}findFiles(n,r="/"){const o=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&o.push(u)},r),o}add(n,r){const o=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??o.data?o.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,o){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,o))),f.length&&(u.data=f),o[n]=u.id,u}copyFiles(n,r,o){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),o&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],o=this.byId(n);return o?(o.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const o=n.name,l=o.lastIndexOf("."),u=l!==-1?o.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?o.slice(0,l):o,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},rR=class extends XT{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:S}=g[u];w=Fw(w,S[b]);const k=[];k[u]={_files:w},this.setState({panels:k},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(N=>{const A=h.byId(N);A&&y.push(A)});const{path:w,_sorts:b}=g[u],S=Fw(y,b[w]),k=[];k[u]={_selected:S},this.setState({panels:k},f)}});this._router=new ZT(super.setState.bind(this),r,{data:u=>new aR(u)});const o=this.in=new JT;o.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let S=[...w[g].selected];if(f){const N=S.indexOf(u);N===-1?S.push(u):S.splice(N,1)}else if(h&&w[g]._lastSelected){const N=w[g]._files;let A=N.findIndex(T=>T.id==w[g]._lastSelected),j=N.findIndex(T=>T.id==u);j<A&&([A,j]=[j,A]);const I=N.slice(A,j+1).map(T=>T.id);S=[...new Set([...S,...I])]}else S=u?[u]:[];const k=[];k[g]={selected:S,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:k})}),o.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),o.exec("select-file",{panel:f}),h&&h.forEach(S=>o.exec("select-file",{id:S,panel:f,toggle:!0})),w.lazy&&o.exec("request-data",{id:u})}}),o.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),o.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),o.on("show-preview",({mode:u})=>{this.setState({preview:u})}),o.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let S={[f]:b.id};w.data?.forEach(N=>S={...g.moveFiles([N.id],b.id),...S});const k=y.map(N=>({selected:N.selected,_crumbs:N._crumbs,_lastSelected:N._lastSelected,_sorts:N._sorts}));g.remove(f),this._updatePanels(k,S),this.setState({data:g,panels:k})}}),o.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),o.exec("select-file",{id:y.id})}),o.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),o.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(S=>b[S]),this.setState({data:g}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(S=>{o.exec("select-file",{id:b[S],toggle:!0})}))}),o.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(k=>b[k]);const S=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));this._updatePanels(S,b,!0),this.setState({data:g,panels:S}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(k=>{o.exec("select-file",{id:b[k],toggle:!0})}))}});let l=null;o.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}o.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),o.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),o.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),o.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let o=0;o<2;o++)n[o]=_w({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[o]});const r={panels:_w(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,o){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!o&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=o?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!o&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(o=>o===r||this.getState().data.getParents(r).some(l=>l.id===o))}};function sR(t){switch(t){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[t==="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(n=>n!==null)}}function iR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function oR(t,n="data-id"){const r=iR(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function lR(t,n){const{api:r}=n;function o(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const S=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(S.type,S):b=n.menuOptions("body");const k=`${y?"ctrl+":""}${w?"shift+":""}${u}`,N=b?b.find(j=>j.hotkey?.toLowerCase()===k):!1,A=n.performAction;if(N)switch(k){case"ctrl+c":A("copy");break;case"ctrl+x":A("move");break;case"ctrl+v":A("paste",S);break;case"delete":A("delete");break;case"ctrl+r":f.preventDefault(),A("rename",S);break;case"ctrl+d":f.preventDefault(),A("download",S);break;default:N.handler?.({context:S})}switch(u){case"enter":{if(y||w)break;const{_crumbs:j,_selectNavigation:I}=h;if(I){const T=nR(j);if(T){const _=Kv(T,j);r.exec("set-path",{id:T,selected:[_]})}}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:j,_selected:I,path:T,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(0).id,H=j.findIndex(D=>D.id===F);if(H!==-1){const D=H-1;j[D]?B=j[D].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(_)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}B=j.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:j,_selected:I,path:T,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(-1).id,H=j.findIndex(D=>D.id===F);if(H!==-1){const D=H+1;j[D]&&(B=j[D].id)}}else{if(T!=="/"&&!_){r.exec("select-file",{type:"navigation"});break}B=j.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();o(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+oR(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function cR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function uR(t,n="data-id"){const r=t.getAttribute(n);return r?dR(r):null}function dR(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function fR(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var mR=fR();new Date().valueOf();function mS(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function pR(t,n,r){const[o,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),o}function Ot(t,n){const r=t.getState(),o=t.getReactiveState();return pR(o[n],r[n],n)}function hR(t,n){const r=d.useRef(n);r.current=n;const[o,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,o]}function Xs(t,n){const r=t.getState(),o=t.getReactiveState();return hR(o[n],r[n])}function pS(t){const n={};return t.split(";").forEach(r=>{const[o,l]=r.split(":");if(l){let u=o.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function hS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function Bw(t,n,r){function o(l){const u=cR(l);if(!u)return;const f=uR(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return mR.addEvent(t,r,o)}function gR(t,n){const r=[Bw(t,n,"click")];return n.dblclick&&r.push(Bw(t,n.dblclick,"dblclick")),()=>{r.forEach(o=>o())}}function gS(t,n){return t.map((r,o)=>{const l=n(r,o);return r.data&&r.data.length&&(l.data=gS(r.data,n)),l}).filter(Boolean)}function vS(t,n){const r=[];return t.forEach(o=>{if(o.data){const l=vS(o.data,n);l.length&&r.push({...o,data:l})}else n(o)&&r.push(o)}),r}function vR(t){return gS(t,(n,r)=>{const o={...n,id:n.id||Hv()};return o.type&&(o.comp=o.type),o.comp==="separator"&&t[r-1]?.comp==="separator"?null:o})}const yS={};function yR(t){return yS[t]||t}function bR(t,n){yS[t]=n}function wR({onClick:t,onShow:n,option:r}){const o=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,o.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,o.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?yR(r.comp):null,[r]);return i.jsxs("div",{ref:o,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Fa(r.id),onMouseEnter:l,onClick:u,children:[r.icon?i.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?i.jsx(f,{item:r,option:r}):null:i.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?i.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?i.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Qv({options:t,left:n=0,top:r=0,at:o="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[S,k]=d.useState(-1e4),[N,A]=d.useState(20),[j,I]=d.useState(),T=d.useRef(null),[_,B]=d.useState(!1),[F,H]=d.useState(null),D=d.useCallback(()=>{const ve=eS(T.current,l,o,n,r);ve&&(b(ve.x),k(ve.y),I(ve.width));let J=ve?.z??20;const $=l?lT(l):[];let P=0;for(const se of $){const we=parseInt(getComputedStyle(se).zIndex,10);we>P&&(P=we)}P>=J&&(J=P+1),A(J)},[l,o,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{B(!1)},[]),z=d.useCallback((ve,J)=>{B(ve),H(J)},[]),W=d.useMemo(()=>vR(t),[t]);d.useEffect(()=>{D()},[l,D]);const q=d.useRef(g),V=d.useRef(y),X=d.useRef(l);return d.useEffect(()=>{q.current=g},[g]),d.useEffect(()=>{V.current=y},[y]),d.useEffect(()=>{X.current=l},[l]),d.useEffect(()=>{if(!T.current)return;function ve(J){V.current?V.current(J):q.current&&q.current({action:null,option:null})}return ho(T.current,{callback:ve,modal:!0,parent:()=>X.current}).destroy},[]),i.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:S+"px",left:w+"px",width:j,zIndex:N},onMouseLeave:K,children:W.map(ve=>i.jsxs(d.Fragment,{children:[ve.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(wR,{option:ve,onShow:z,onClick:J=>{if(!ve.data&&!J.defaultPrevented){const $={context:f,action:ve,option:ve,event:J};ve.handler&&ve.handler($),g&&g($),J.stopPropagation()}}}),ve.data&&_===ve.id?i.jsx(Qv,{css:h,options:ve.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},ve.id))})}const bS=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[S,k]=d.useState(null),[N,A]=d.useState(0),[j,I]=d.useState(0),T=d.useRef(null),_=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),B=d.useMemo(()=>w!==null&&f?vS(r,K=>f(K,w)):r,[w,f,r]);function F(K){k(null),y&&y(K)}function H(K){if(T.current===K){T.current=null;return}k(null),y&&y({action:null,option:null})}const D=d.useCallback((K,z)=>{if(!K){k(null);return}if(K.defaultPrevented)return;const W=K.target;if(W&&W.dataset&&W.dataset.menuIgnore)return;if(S&&S===W){k(null),K.preventDefault();return}A(K.clientX+1),I(K.clientY+1);let q=typeof z<"u"?z:rm(W,_);l&&(q=l(q,K),!q)||(b(q),k(W),T.current=K.nativeEvent||K,K.preventDefault())},[S,_,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,S?i.jsx($v,{children:i.jsx(Qv,{css:h,at:o,top:j,left:N,parent:S,context:w,onClick:F,onCancel:H,options:B},S)}):null]})}),xR=d.forwardRef(function(t,n){const{options:r,at:o="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(N){g(null),f&&f(N)}function b(N){if(y.current===N){y.current=null;return}g(null),f&&f({action:null,option:null})}const S=d.useCallback(N=>{g(N.target),y.current=N.nativeEvent||N,N.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:S}),[S]);function k(N){let A=N.target;for(;!A.dataset.menuIgnore;)g(A),A=A.parentNode}return i.jsxs(i.Fragment,{children:[i.jsx("span",{onClick:k,"data-menu-ignore":"true",children:u}),h?i.jsx($v,{children:i.jsx(Qv,{css:l,at:o,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),SR=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((S,k)=>{w.current.show(S,k)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,i.jsx(bS,{css:h,at:o,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),CR={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 kR=class{constructor(n,r,o,l,u){this.setFiles=n,this.setReady=r,this.setSignal=o,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let o=0;o<r.length;o++){if(r[o].status==="client")return"client";r[o].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const o=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",o),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",o),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const o=this.files.findIndex(u=>u.id===n);if(o===-1)return;const l=[...this.files];return l[o]={...l[o],...r},this.files=l,this.setFiles(this.files),this.files[o]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function wS(t){const[n,r]=d.useState([]),[o,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new kR(r,l,f,g,t)),y.current.files=n,y.current.ready=o,y.current.signal=u,y.current.drag=h,y.current}function MR(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return lm(CR).getGroup(n)}}const AR=()=>Math.random().toString(36).substr(2,9),NR=({data:t,accept:n="",multiple:r=!0,folder:o=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[S,k]=d.useState({}),N=wS(),A=t||N,j=d.useContext(Ba.i18n),I=MR(j,"uploader");d.useEffect(()=>{w.current&&o&&(w.current.webkitdirectory=!0)},[o]),d.useEffect(()=>{if(!u&&b.current&&!f)return A.droparea(b.current)},[u,f,b]);const T=W=>{const q=new FormData;return q.append("upload",W.file),fetch(l,{method:"POST",body:q}).then(V=>V.json()).then(V=>({id:W.id,...V}),()=>({id:W.id,status:"error"})).catch(V=>(console.log(V),{id:W.id,status:"error"}))},_=(W,q)=>{const V=A.updateFile(W,q),X={...V,status:A.getState()};V&&V.uploaded&&V.uploaded(X),y&&y(X),V.temp&&A.deleteFile(V.id)},B=W=>{if(!W)return;const q=typeof l=="function"?l(W):T(W);A.setReady(q.then(V=>{V.status=V.status||"server",_(W.id,V)}).catch(V=>{_(W.id,{status:"error",error:V})}))},F=(W,q)=>{const V={...q||S,id:AR(),status:"client",name:W.name,file:W};V.selected&&V.selected(V),g&&g(V),A.addFile(V,r),B(V),w.current&&(w.current.value="")},H=(W,q,V)=>{W.isFile?W.file(X=>{F(X,V)}):W.isDirectory&&W.createReader().readEntries(X=>{X.forEach(ve=>{H(ve,q+ve.name+"/",V)})})},D=W=>{Array.from(W.target.files).forEach(q=>F(q))},K=(W,q)=>{Array.from(W.dataTransfer.items).forEach(V=>{const X=V.webkitGetAsEntry();X&&H(X,"",q)})},z=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(A.signal){const[W,q,V]=A.signal;k(q),W==="click"?z():W==="drop"&&K(V,q),A.setSignal(null)}},[A.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):i.jsxs("div",{className:`wx-at1A8tb8 wx-label ${A.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||i.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:i.jsxs("span",{children:[I("Drop files here or")," ",i.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:z,children:I("select files")})]})})]})};new Date().valueOf();function TR(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const o=t[r],l=n[r];if(!mh(o,l))return!1}return!0}function mh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!mh(t[r],n[r]))return!1;return!0}else return TR(t,n);return t===n}function vv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(vv);const n={};for(const r in t)n[r]=vv(t[r]);return n}var xS=2,RR=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,o,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=o+(o?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&xS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,o){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,o,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let o=0;o<n.length;o++)n[o](t)};return{subscribe:o=>(n.push(o),this._async?setTimeout(o,1,t):o(t),()=>{const l=n.indexOf(o);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(o){return t=o,!0}}}},jR=class{constructor(t,n,r,o){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>SS(u,this._sources,1)))}),this._bus=o}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const o=this._parsers[r];n[r]=o?o(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,xS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),o=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}o&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,o)=>r.length<o.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function SS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>SS(u,n,r+1));return Math.max(...l)}var ER=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let o=this._handlers[t];o?r&&r.intercept?o.unshift(n):o.push(n):o=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let o=r.length-1;o>=0;o--)this._tag.get(r[o])===t&&r.splice(o,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let o=0;o<r.length;o++){const l=r[o](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function DR(t){return n=>n[t]}function IR(t){return(n,r)=>n[t]=r}function ic(t,n){return(n.getter||DR(n.id))(t)}function Rg(t,n,r){return(n.setter||IR(n.id))(t,r)}function LR(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function tc(t,n){let r=ic(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(o=>n.optionsMap.get(o)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function PR(t,n){const r=/\n|"|;|,/;let o="";const l=n.rows||`
|
|
178
|
-
`,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(o=Hw("header",f,o,u,l));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=tc(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}o+=(o?l:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(o=Hw("footer",f,o,u,l)),o}function Hw(t,n,r,o,l){const u=/\n|"|;|,/;for(let f=0;f<n[0][t].length;f++){const h=[];for(let g=0;g<n.length;g++){let y=(n[g][t][f].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}r+=(r?l:"")+h.join(o)}return r}const _R="portrait",FR=100,OR="a4",BR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function HR(t,n){const r=[];let o=[],l=0;const u=t.filter(h=>!h.hidden),f=zR(n);return u.forEach((h,g)=>{l+h.width<=f?(l+=h.width,o.push(h)):(o.length&&r.push(o),o=[h],l=h.width),g===u.length-1&&o.length&&r.push(o)}),r}function zw(t,n,r){const o=[];return t.forEach((l,u)=>{const f=l[n];for(let h=0;h<r.length;h++){o[h]||(o[h]=[]);const g={...f[h]};if(o[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,w=t[u+y][n][h],b=g.width;for(;!w.rowspan&&!w.colspan;)y++,w=t[u+y][n][h],b+=w.width;g.colspan=y,g.width=b,g.height=r[h]}if(o[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const w=g.colspan-(g.colspan+u-t.length);g.colspan=w,g.width=t.slice(u,u+y+1).reduce((b,S)=>b+S.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)o[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)o[h+w]||(o[h+w]=[]),o[h+w].push(null)}}}if(l.collapsed)for(let h=0;h<o.length;h++){const g=o[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const w=y||g.findLast(b=>b?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-l.width)}}}),o.map(l=>l.filter(u=>u&&u.colspan!==0))}function zR(t){const{mode:n,ppi:r,paper:o}=t,{width:l,height:u}=BR[o];return $R(n==="portrait"?l:u,r)}function $R(t,n){return t*n}function UR(t={}){const{mode:n,ppi:r,paper:o}=t;return{mode:n||_R,ppi:r||FR,paper:o||OR}}function CS(t,n){return t.flexgrow?`min-width:${n}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function qR(t,n,r){let o=t[r.id];if(r.filter.type==="richselect"&&o){const l=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;l&&(o=l.find(({id:u})=>u==o).label)}return o??""}const $w=["resize-column","hide-column","update-cell"],WR=["delete-row","update-row","update-cell"],GR=["move-item"],VR=["resize-column","move-item"];class KR{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,o){this.in=n,this.getState=r,this.setState=o,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:n=>({action:"delete-row",data:{id:n.id},source:{action:"add-row",data:n}})},"delete-row":{handler:n=>{const{id:r}=n,{data:o}=this.getPrev(),l=o.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:o[l],before:l<o.length-1?o[l+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:o}=n,l=this.getRow(r),u=this.getColumn(o),f=ic(l,u);return mh(f,n.value)?null:{action:"update-cell",data:{id:r,column:o,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:o}=n,l=this.getRow(r);for(const u in o)Object.keys(l).includes(u)||(l[u]=void 0);return{action:"update-row",data:{id:r,row:l},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:o}=this.getState(),l=o.findIndex(f=>f.id===r),u=o[l];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:l<o.length-1?o[l+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:o}=n,l=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:l.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:o}}}}},"hide-column":{handler:n=>{const{id:r}=n,o=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:o.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:o,mode:l}=n;return{action:"collapse-column",data:{id:r,row:o,mode:typeof l=="boolean"?!l:l},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:o,mode:l}=n,{flatData:u}=this.getPrev(),f=u.findIndex(h=>h.id===r);return{action:"move-item",data:{id:r,target:u[f+(f?-1:1)].id,mode:f?"after":"before"},source:{action:"move-item",data:{id:r,target:o,mode:l}}}}},"open-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"close-row",data:{id:r,nested:o},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"open-row",data:{id:r,nested:o},source:{action:"close-row",data:n}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const n=this.getHandlers();for(const r in n)this.in.intercept(r,o=>{if(!(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo)){if(VR.includes(r)){(o.inProgress&&!this.progress[r]||typeof o.inProgress!="boolean")&&(GR.includes(r)&&this.setPrev("flatData"),$w.includes(r)&&this.setPrev("columns")),this.progress[r]=o.inProgress;return}WR.includes(r)&&this.setPrev("data"),$w.includes(r)&&this.setPrev("columns")}}),this.in.on(r,o=>{if(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo||o.inProgress)return;const l=n[r].handler(o);l&&this.addToHistory(l)})}setPrev(n){this._previousValues[n]=vv(this.getState()[n])}addToHistory(n){this.undo.push(n),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const n=this.undo.pop();this.redo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const n=this.redo.pop();this.undo.push({...n.source,source:n}),this.in.exec(n.action,{...n.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(n){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,n):r.find(o=>o.id===n)}getTreeRow(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n[o];if(n[o].data){const l=this.getTreeRow(n[o].data,r);if(l)return l}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(o=>o.id===n)}}function kS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function QR(t,n){return-kS(t,n)}function YR(t,n){if(typeof n.sort=="function")return function(o,l){const u=n.sort(o,l);return t==="asc"?u:-u};const r=t==="asc"?kS:QR;return function(o,l){return r(ic(o,n),ic(l,n))}}function XR(t,n){if(!t||!t.length)return;const r=t.map(o=>{const l=n.find(u=>u.id==o.key);return YR(o.order,l)});return t.length===1?r[0]:function(o,l){for(let u=0;u<r.length;u++){const f=r[u](o,l);if(f!==0)return f}return 0}}const bp=28,ZR=20;function JR(){if(typeof document>"u")return"willow";const t=document.querySelector('[class^="wx"][class$="theme"]');return t?t.className.substring(3,t.className.length-6):"willow"}function Yp(t,n,r,o,l){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;l=l?`${l}px`:"auto";let g,y;f.className=n,u.classList.add(`wx-${r}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${l};white-space:nowrap;`,u.appendChild(f),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let w=0;w<t.length;w++){f.innerText=t[w]+"";const b=u.getBoundingClientRect(),S=Math.ceil(b.width)+(o&&o.length?o[w]:0),k=Math.ceil(b.height);g=Math.max(g||0,S),y=Math.max(y||0,k)}return u.remove(),{width:g,height:y}}function Uw(t,n,r,o,l){const u=[];for(let f=0;f<t.length;f++){const h=t[f][n],g=h.length;for(let y=0;y<g;y++){const{text:w,vertical:b,collapsed:S,rowspan:k,css:N}=h[y];if(!w){u[y]=Math.max(u[y]||0,o);continue}let A=0;if(b&&!S){let j=`wx-measure-cell-${n}`;if(j+=N?` ${N}`:"",A=Yp(w,j,l).width,(k>1||!h[y+1])&&r>y+1){const I=k||r-y,T=u.slice(y,y+I).reduce((_,B)=>_+B,0);if(T<A){const _=Math.ceil((A-T)/I);for(let B=y;B<y+I;B++)u[B]=(u[B]||o)+_}continue}}u[y]=Math.max(u[y]||o,A)}}return u}function ej(t,n,r){const o=[],l=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=tc(h,t);g&&(o.push(g),t.treetoggle?l.push(n[f].$level*bp+(n[f].$count?bp:0)+(t.draggable?bp:0)):t.draggable&&l.push(bp))}return Yp(o,u,r,l).width}function tj(t,n){const r="wx-measure-cell-header",o=t.sort?ZR:0;let l=t.header;if(typeof l=="string")return Yp(l,r,n).width+o;let u;Array.isArray(l)||(l=[l]);for(let f=0;f<l.length;f++){const h=l[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=Yp(g,y,n).width;f===l.length-1&&(w+=o),u=Math.max(u||0,w)}return u}const nj={text:(t,n)=>t?t.toString().toLowerCase().indexOf(n.toLowerCase())!==-1:!n,richselect:(t,n)=>typeof n!="number"&&!n?!0:t==n,datepicker:(t,n)=>n?t&&rj(t,n):!0,multiselect:(t,n)=>!n||n?.length===0?!0:Array.isArray(t)?t?.some(r=>n.includes(r)):t&&n.includes(t)};function MS(t){return nj[t]}function aj(t,n){const r=[];for(const o in t){const l=n.find(g=>g.id==o),{config:u,type:f}=l.header.find(g=>g.filter).filter,h=t[o];r.push(g=>{const y=ic(g,l);return u?.handler?u.handler(y,h):MS(f)(y,h)})}return o=>{for(let l=0;l<r.length;l++)if(!r[l](o))return!1;return!0}}function rj(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let sj=class extends RR{in;_router;_branches;_xlsxWorker;_historyManager;constructor(n){super({writable:n,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new jR(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:l=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((S,k)=>Math.max(k.header.length,S),0),w=g.reduce((S,k)=>Math.max(k.footer.length,S),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let S=0;S<g.length;S++)this.normalizeColumns(g,S,"header",y,b),this.normalizeColumns(g,S,"footer",w,b);this.setState({_columns:g,_sizes:b},l)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:l=>{const{data:u,tree:f,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),w=f?this.flattenRows(u,[],g):y?u.filter(S=>y.has(S.id)):u,b=!h&&w.some(S=>S.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},l)}}],{sizes:l=>({...r,...l})});const o=this.in=new ER;o.on("close-editor",({ignore:l})=>{const{editor:u}=this.getState();u&&(l||o.exec("update-cell",u),this.setState({editor:null}))}),o.on("open-editor",({id:l,column:u})=>{let f=this.getState().editor;f&&o.exec("close-editor",{});const h=this.getRow(l),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;f={column:g.id,id:l,value:ic(h,g)??"",renderedValue:tc(h,g),type:y.type||y},typeof y=="object"&&y.config&&(f.config=y.config,y.config.options&&(f.options=y.config.options)),g.options&&!f.options&&(f.options=g.options),this.setState({editor:f})}}),o.on("editor",({value:l})=>{let u=this.getState().editor;if(u){u={...u},u.value=l;const f=this.getColumn(u.column),h={...this.getRow(u.id)};Rg(h,f,l),u.renderedValue=tc(h,f),this.setState({editor:u})}}),o.on("add-row",l=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:S}=l;if(l.id=y.id=l.id||y.id||wp(),w||b){const N=w||b,A=f.findIndex(j=>j.id===N);f=[...f],f.splice(A+(b?1:0),0,l.row)}else f=[...f,l.row];const k={data:f};g&&(k._filterIds=[...g,l.id]),this.setState(k),!(typeof S=="boolean"&&!S)&&(S||h)&&o.exec("select-row",{id:y.id,show:!0})}),o.on("delete-row",l=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=l,w={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(w.selectedRows=f.filter(b=>b!==y)),g?.id===y&&(w.editor=null),this.setState(w),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),o.on("update-cell",l=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=l,b=this.getColumn(y);if(h){const S={...this._branches[g]};Rg(S,b,w);const k=this.updateTreeRow(S);S.$parent===0&&(f=k)}else{const S=f.findIndex(N=>N.id===g),k={...f[S]};Rg(k,b,w),f[S]=k}this.setState({data:f})}),o.on("update-row",l=>{let{data:u}=this.getState();const{id:f,row:h}=l,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),o.on("select-row",({id:l,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:S}=w;if(S.length||(f=u=!1),f){const{data:k}=this.getState();let N=k.findIndex(j=>j.id===S[S.length-1]),A=k.findIndex(j=>j.id===l);N>A&&([N,A]=[A,N]),k.slice(N,A+1).forEach(j=>{this.isSelected(j.id)||S.push(j.id)})}else if(u&&this.isSelected(l)){if(h===!0)return;S=S.filter(k=>k!==l)}else if(u){if(h===!1)return;S.push(l)}else S=[l];this.setState({selectedRows:[...S]}),b?.row!==l&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:l,column:y})}),this.in.on("focus-cell",l=>{const{row:u,column:f,eventSource:h}=l,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===l.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===l.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),o.on("resize-column",l=>{const{id:u,auto:f,maxRows:h,inProgress:g}=l;if(g===!1)return;let y=l.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:S,_skin:k}=this.getState();let N=S.length;h&&(N=Math.min(h,N));const A=S.slice(0,N);y=ej(b,A,k)}if(f==="header"||f===!0){const{_skin:S}=this.getState();y=Math.max(tj(b,S),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),o.on("hide-column",l=>{const{id:u,mode:f}=l,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((w,b)=>w+(b.hidden?0:1),0);!f||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):l.skipUndo=!0}),o.on("sort-rows",l=>{const{key:u,add:f,sort:h}=l,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const T=[...w];T.sort(h),this.setState({data:T});return}const{order:S="asc"}=l;let k=g.sortMarks;const N=Object.keys(k),A=N.length;!f||!A||A===1&&k[u]?k={[u]:{order:S}}:(A===1&&(k[N[0]]={...k[N[0]],index:0}),k={...k,[u]:{order:S,index:typeof f=="number"?f:k[u]?.index??A}});const j=Object.keys(k).sort((T,_)=>k[T].index-k[_].index).map(T=>({key:T,order:k[T].order}));this.setState({sortMarks:k});const I=XR(j,y);if(I){const T=[...w];b?this.sortTree(T,I):T.sort(I),this.setState({data:T})}}),o.on("filter-rows",l=>{const{value:u,key:f,filter:h}=l;if(!Object.keys(l).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let S=g.filterValues;const k={};f&&(S={...S,[f]:u},k.filterValues=S);const N=h??aj(S,b);let A=[];w?A=this.filterTree(y,N,A):y.forEach(j=>{N(j)&&A.push(j.id)}),k._filterIds=A,this.setState(k)}),o.on("collapse-column",l=>{const{id:u,row:f,mode:h}=l,g=[...this.getState().columns],y=this.getColumn(u).header,w=Array.isArray(y)?y[f]:y;typeof w=="object"&&(w.collapsed=h??!w.collapsed,this.setState({columns:g}))}),o.on("move-item",l=>{const{id:u,inProgress:f}=l;let{target:h,mode:g="after"}=l;const{data:y,flatData:w,tree:b}=this.getState(),S=w.findIndex(A=>A.id===u);let k;if(g==="up"||g==="down"){if(g==="up"){if(S===0)return;k=S-1,g="before"}else if(g==="down"){if(S===w.length-1)return;k=S+1,g="after"}h=w[k]&&w[k].id}else k=w.findIndex(A=>A.id===h);if(S===-1||k===-1||f===!1)return;let N;b||(N=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(N):N})}),o.on("copy-row",l=>{const{id:u,target:f,mode:h="after"}=l,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const S=this.getRow(u);if(!S)return;const k={...S,id:wp()};l.id=k.id;const N=y.findIndex(j=>j.id===f);if(N===-1)return;b.splice(N+(h==="after"?1:0),0,k),b=[...b];const A={data:b};w&&(A._filterIds=[...w,k.id]),this.setState(A)}),o.on("open-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!0,f)}),o.on("close-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!1,f)}),o.on("export-data",l=>new Promise((u,f)=>{const h=l.format||"csv",g=`${l.fileName||"data"}.${h}`;if(h==="csv"){const y=PR(this.getState(),l.csv||{});l.download!==!1?LR(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):l.result=y,u(!0)}else f()})),o.on("hotkey",({key:l,event:u,isInput:f})=>{switch(l){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getNextRow(b);k&&(b=k.id,S=this.getNextEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getPrevRow(b);k&&(b=k.id,S=this.getPrevEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!f&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,S=this._getFirstVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,S=this._getLastVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),o.on("scroll",l=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,S=-1,k=0,N=0;if(l.column){b=0;const A=u.findIndex(j=>j.id===l.column);k=u[A].width;for(let j=f.left??0;j<A;j++){const I=u[j];I.hidden||(b+=I.width)}}if(l.row&&!y){const A=g.findIndex(j=>j.id===l.row);A>=0&&(w?(S=g.slice(0,A).reduce((j,I)=>j+(I.rowHeight||h.rowHeight),0),N=g[A].rowHeight):S=h.rowHeight*A)}this.setState({scroll:{top:S,left:b,width:k,height:N||h.rowHeight}})}),o.on("scroll-to",l=>{const u={};l.top!==void 0&&(u.scrollTop=l.top),l.left!==void 0&&(u.scrollLeft=l.left),Object.keys(u).length&&this.setState(u)}),o.on("print",l=>{const u=UR(l);this.setState({_print:u}),this.setStateAsync({_print:null})}),o.on("undo",()=>{this._historyManager?.handleUndo()}),o.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(n){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${n}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(o=>{const l=new Worker(r);l.addEventListener("message",u=>{u.data.type==="init"&&o(l)})})}return this._xlsxWorker}initOnce(){const n={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(n)}init(n){n.hasOwnProperty("_skin")&&!n._skin&&(n._skin=JR()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(o=>[o.id,o.label])))}),mh(this.getState().data,n.data)||(n.tree?n.data=this.normalizeTreeRows(n.data):n.data=this.normalizeRows(n.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),n.tree&&(n.undo=!1,n.reorder=!1),n.split?.right&&(n.split.right=0),n.undo&&!this._historyManager&&(this._historyManager=new KR(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...n})}setState(n,r){return this._router.setState(n,r)}setStateAsync(n){this._router.setStateAsync(n)}getRow(n){const{tree:r}=this.getState();return r?this._branches[n]:this.getState().data.find(o=>o.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(o=>o.id===n)}getNextRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o+1]}getPrevRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const o=this.getState()._columns,l=o.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(l+1):o[l+1]}getPrevColumn(n,r){const o=this.getState()._columns,l=o.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(l-1):o[l-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let o=n??0;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o++;return r[o]}_getLastVisibleColumn(n){const r=this.getState()._columns;let o=n??r.length-1;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o--;return r[o]}isCellEditable(n,r){const{editor:o,hidden:l}=r;return!o||l?!1:typeof o=="function"?o(n,r):!0}getNextEditor(n,r){let o=this.getState().columns;if(r){const l=o.findIndex(u=>u.id===r.id);o=o.slice(l+1)}return o.find(l=>this.isCellEditable(n,l))}getPrevEditor(n,r){let o=this.getState().columns;if(r){const l=o.findLastIndex(u=>u.id===r.id);o=o.slice(0,l)}return o.findLast(l=>this.isCellEditable(n,l))}toggleBranch(n,r,o){let l=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){l={...l,open:r};const f=this.updateTreeRow(l);l.$parent===0&&(u=f)}o&&l.data?.length&&l.data.forEach(f=>{const h=this.toggleKids(f,r,o);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,o){n={...n,open:r};const l=this.updateTreeRow(n);return o&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,o)}),l}updateTreeRow(n){const r=n.id;this._branches[r]=n;const o=this._branches[n.$parent],l=o.data.findIndex(u=>u.id===r);return o.data=[...o.data],o.data[l]=n,o.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n.splice(o,1)[0];if(n[o].data){const l=[...n[o].data],u=this.findAndRemove(l,r);if(u)return n[o]={...n[o],data:l},u}}return null}insertItem(n,r,o,l){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=l==="before"?u:u+1;if(f.data){if(l==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,o]}:n.splice(h,0,o),!0}else if(f.open)return n[u]={...f,data:[o,...f.data]},!0}return n.splice(h,0,o),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,o,l)))return!0}return!1}moveItem(n,r,o,l){const u=[...o],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,l),u}copyColumns(n){const r=[];for(let o=0;o<n.length;o++){const l={...n[o]};this.copyHeaderFooter(l,"header"),this.copyHeaderFooter(l,"footer"),r[o]=l}return r}copyHeaderFooter(n,r){let o=n[r];o=Array.isArray(o)?[...o]:[o],o.forEach((l,u)=>{o[u]=typeof l=="string"?{text:l}:{...l}}),n[r]=o}setCollapsibleColumns(n,r,o){let l=n.header;for(let u=0;u<l.length;u++){const f=l[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=l.length-u;l=l.slice(0,u+1),l[u].rowspan=g}const h=f.colspan;if(h){const g=l[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=o[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,o,l,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[o],g=u[`${o}RowHeights`];for(let y=0;y<l;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,l-y):l-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let S=1;S<w.colspan;S++)n[r+S][o].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===l?g:g.slice(y,w.rowspan+y)).reduce((S,k)=>S+k,0);w.height=b,y+w.rowspan!=l&&w.height--}if(w.colspan){let b=f.width,S=f.flexgrow||0;const k=w.colspan;for(let N=1;N<k;N++){const A=n[r+N];A&&(A.hidden?w.colspan-=1:A.flexgrow?S+=A.flexgrow:b+=A.width||u.columnWidth),S?w.flexgrow=S:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;o==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>l&&(h.length=l),f[o]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=wp());return n}normalizeTreeRows(n,r,o){return!r&&!o&&(this._branches={0:{data:n}}),n.forEach(l=>{l.id||(l.id=wp()),l.$level=r||0,l.$parent=o||0,this._branches[l.id]=l,l.data&&(l.data.length?(l.$count=l.data.length,this.normalizeTreeRows(l.data,l.$level+1,l.id)):(delete l.data,delete l.$count,delete l.open))}),n}sortTree(n,r){n.sort(r),n.forEach(o=>{o.data&&this.sortTree(o.data,r)})}filterTree(n,r,o){return n.forEach(l=>{r(l)&&o.push(l.id),l.data&&this.filterTree(l.data,r,o)}),o}flattenRows(n,r,o){const l=r;return n.forEach(u=>{(!o||o.includes(u.id))&&l.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,l,o)}),l}createFilter(n){const{_columns:r}=this.getState(),o=[];for(const l in n){const u=r.find(y=>y.id==l),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[l];o.push(y=>{const w=ic(y,u);return f?.handler?f.handler(w,g):MS(h)(w,g)})}return l=>{for(let u=0;u<o.length;u++)if(!o[u](l))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const o={};if(!n)return o;const{flatData:l,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return l.forEach(h=>{const g={};f.forEach(y=>{const w=tc(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(o[h.id]=g)}),o}normalizeSizes(n,r,o,l,u){const f=Uw(n,"header",o,r.headerHeight,u),h=Uw(n,"footer",l,r.footerHeight,u),g=f.reduce((w,b)=>w+b,0),y=h.reduce((w,b)=>w+b,0);return{...r,headerRowHeights:f,footerRowHeights:h,headerHeight:g,footerHeight:y}}},ij=new Date().valueOf();function wp(){return"temp://"+ij++}function oj(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}new Date().valueOf();var lj=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const o=r.toLowerCase().replace(/[ ]/g,""),l=t[r];this.store.set(o,l)}}},Rd=[],cj={subscribe:t=>{uj();const n=new lj;return Rd.push(n),t(n),()=>{const r=Rd.findIndex(o=>o===n);r>=0&&Rd.splice(r,1)}}},qw=!1;function uj(){qw||(qw=!0,document.addEventListener("keydown",t=>{if(Rd.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const n=[];t.ctrlKey&&n.push("ctrl"),t.altKey&&n.push("alt"),t.metaKey&&n.push("meta"),t.shiftKey&&n.push("shift");let r=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(r="space"),n.push(r);const o=n.join("+");for(let l=Rd.length-1;l>=0;l--){const u=Rd[l],f=u.store.get(o)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:o,evKey:r})}}}))}const dj={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 fj(t,{keys:n,exec:r}){if(!n)return;function o(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||oj(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const l={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?l[f]=h:h&&(l[f]=g=>{const y=o(g);r({key:f,event:g,isInput:y})}))}const u=cj.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function mj(t,n){let r=null;n.scroll.subscribe(o=>{if(!o||o===r)return;r=o;const{left:l,top:u,height:f,width:h}=o,g=n.getHeight(),y=n.getWidth(),w=n.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+f>b+g&&(t.scrollTop=u-g+f)}if(l>=0){const b=t.scrollLeft;l<b?t.scrollLeft=l:l+h>b+y-w&&(t.scrollLeft=l-y+h+w)}}),n.scrollLeft?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-o)>1&&(t.scrollLeft=o)})}),n.scrollTop?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-o)>1&&(t.scrollTop=o)})})}const Es=d.createContext(null);function pj(t,n){const r=new ResizeObserver(o=>{requestAnimationFrame(()=>n(o[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const Ww=5,hj=700;function _p(t){const n=t.getBoundingClientRect(),r=document.body,o=n.top+r.scrollTop-r.clientTop||0,l=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(o),x:Math.round(l),width:t.offsetWidth,height:t.offsetHeight}}function yv(t,n){const r=_p(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function gj(t,n){const r=n.current;let o=null,l,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(l),l=null}function w(D){const K=Id(D);K&&(o={container:g,sourceNode:D.target,from:uh(K),pos:yv(D,t)},u=o.pos,b(D))}function b(D){if(!o)return;const K=o.pos=yv(D,t);if(!f){if(!h&&!D?.target?.getAttribute("draggable-data")&&Math.abs(u.x-K.x)<Ww&&Math.abs(u.y-K.y)<Ww)return;if(F(D)===!1)return H()}if(h){const z=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,W=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;o.targetNode=document.elementFromPoint(D.pageX-z,D.pageY-W)}else o.targetNode=D.target;r.move&&r.move(D,o),g.style.left=-(o.offset?o.offset.x:0)+"px",g.style.top=o.pos.y+(o.offset?o.offset.y:0)+"px"}function S(D){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(D,o),o=u=null,H()}function k(D){r.getReorder&&!r.getReorder()||D.button===0&&(B(D),window.addEventListener("mousemove",N),window.addEventListener("mouseup",A),w(D))}function N(D){b(D)}function A(D){S(D)}function j(D){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(D.touches[0])},hj),B(D);function K(){l&&y(),D.target.removeEventListener("touchmove",I),D.target.removeEventListener("touchend",K),S(D)}D.target.addEventListener("touchmove",I),D.target.addEventListener("touchend",K),t.addEventListener("contextmenu",T)}function I(D){f?(D.preventDefault(),b(D.touches[0])):l&&y()}function T(D){if(f||l)return D.preventDefault(),!1}function _(D){D.preventDefault()}function B(D){if(!r.getDraggableInfo)return;const{hasDraggable:K}=r.getDraggableInfo();(!K||D.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(D){if(f=!0,r.start){if(r.start(D,o)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function H(D){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",A),D&&(t.removeEventListener("mousedown",k),t.removeEventListener("touchstart",j),t.removeEventListener("dragstart",_))}return t.addEventListener("mousedown",k),t.addEventListener("touchstart",j),t.addEventListener("dragstart",_),{destroy(){H(!0)}}}const vj=.004;function yj(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function bj(t,n,r,o){const{node:l,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=o,b=yv(t,l);r.scrollState||(r.scrollState=yj());let S=0,k=0;b.x<u+g?S=-1:b.x>n.width-g&&(S=1),b.y<f+Math.round(g/2)?k=-1:b.y>n.height-h-Math.round(g/2)&&(k=1),(r.scrollState.dirX!==S||r.scrollState.dirY!==k)&&(AS(r),r.scrollState.dirX=S,r.scrollState.dirY=k),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&wj(r,o,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function wj(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(xj,15,t,n,r)},250))}function AS(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function xj(t,n,r){const{x:o,y:l}=r;t.scrollSpeedFactor+=vj,o!==0&&Cj(t,n,o),l!==0&&Sj(t,n,l)}function Sj(t,n,r){const o=n.node.scrollTop;NS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function Cj(t,n,r){const o=n.node.scrollLeft;NS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function NS(t,n,r){r.node[n]=t}function ph(t,n,r,o,l,u){const f={};return t&&(f.width=`${t}px`,f.minWidth=`${t}px`),n&&(f.flexGrow=n),u&&(f.height=`${u}px`),r&&(f.position="sticky",r.left&&(f.left=`${o}px`),r.right&&(f.right=`${l}px`)),f}function TS(t,n,r){let o="";if(t.fixed)for(const l in t.fixed){let u=t.fixed[l]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),o+=u?"wx-shadow ":"wx-fixed "}return o+=n.rowspan>1?"wx-rowspan ":"",o+=n.colspan>1?"wx-colspan ":"",o+=n.vertical?"wx-vertical ":"",o+=r?r(t)+" ":"",o}function kj(t){const{row:n,column:r,cellStyle:o=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(Es),g=Ot(h,"focusCell"),y=Ot(h,"search"),w=Ot(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),S=d.useMemo(()=>ph(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function k(F,H){let D="wx-cell";return D+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",D+=F?" "+F(r):"",D+=H?" "+H(n,r):"",D+=r.treetoggle?" wx-tree-cell":"",D}const N=d.useMemo(()=>k(l,o),[l,o,r,n]),A=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),j=d.useRef(null);d.useEffect(()=>{j.current&&f&&g?.row===n.id&&g?.column===r.id&&j.current.focus()},[g,f,n.id,r.id]);const I=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function T(F){const H=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(H).map(D=>({text:D,highlight:H.test(D)}))}const _=d.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,H=r.fixed&&r.fixed.right;return[N,F?"wx-shadow":"",H?"wx-fixed-right":""].filter(Boolean).join(" ")},[N,r]),B=r.cell;return i.jsxs("div",{className:"wx-TSCaXsGV "+_,ref:j,onFocus:I,style:S,"data-row-id":Fa(n.id),"data-col-id":Fa(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?A?i.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):i.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?i.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,B?i.jsx(B,{api:h,row:n,column:r,onAction:({action:F,data:H})=>h.exec(F,H)}):u?u():b?i.jsx("span",{children:T(tc(n,r)).map(({highlight:F,text:H},D)=>F?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:H},D):i.jsx("span",{children:H},D))}):tc(n,r)]})}function Gw(t,n){let r,o;function l(h){r=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",f),n&&n.down&&n.down(t)}function u(h){o=h.clientX-r,n&&n.move&&n.move(o)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(o),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",l),{destroy(){t.removeEventListener("mousedown",l)}}}function Mj({filter:t,column:n,action:r,filterValue:o}){function l({value:u}){r({value:u,key:n.id})}return i.jsx(qv,{...t.config??{},value:o,onChange:l})}function Aj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Es),u=Ot(l,"flatData"),f=d.useMemo(()=>t?.config?.options||n?.options||g(),[t,n,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(S=>{const k=ic(S,n);b.includes(k)||b.push(k)}),b.map(S=>({id:S,label:S}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:w,children:i.jsx(HT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:o,onChange:y,children:b=>h?h(b):b.label})})}function Nj({filter:t,column:n,action:r,filterValue:o}){function l({value:u}){r({value:u,key:n.id})}return i.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:i.jsx(BT,{placeholder:"",clear:!0,...t?.config??{},value:o,onChange:l})})}function RS(t){const{value:n,options:r=[],placeholder:o="",clear:l=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[S,k]=mS(n||[]),N=d.useMemo(()=>(S||[]).map(W=>r.find(q=>q.id===W)).filter(Boolean),[S,r]),A=d.useRef(null),j=d.useRef(null),[I,T]=d.useState(null),_=()=>{const W=S||[];if(!W.length)return 0;const q=r.find(V=>W.includes(V.id));return q?r.indexOf(q):0};function B(W){j.current=W.navigate,T(()=>W.keydown),y&&W.navigate(_())}d.useEffect(()=>{y&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:W}){k(W),w&&w({value:W})}function H(W){W.stopPropagation(),k([]),w&&w({value:[]})}function D(){j.current?.(_())}function K(){j.current?.(null)}function z(W){I?.(W,_())}return i.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:D,onKeyDown:z,tabIndex:0,children:[i.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(N):h?i.jsx(h,{data:N,onAction:b}):u?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):N.length?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:N.map(W=>W.label).join(", ")}):o?i.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:o}):" "}),l&&S?.length?i.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:H}):i.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),i.jsx(fh,{items:r,onReady:B,onSelect:F,multiselect:!0,checkboxes:!0,value:S||[],onCancel:K,...g,children:({option:W})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(W):h?i.jsx(h,{data:W,onAction:b}):W.label})})]})}function Tj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Ba.i18n)?.getGroup("grid")||lm(Vv).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=o?.length;return w?w<3?o.map(b=>n.optionsMap.get(b)).join(", "):w+" "+l("selected"):""},[o,n,l]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:y,children:i.jsx(RS,{placeholder:"",...u,options:f,value:o||[],text:h,onChange:g})})}const Rj={text:Mj,richselect:Aj,datepicker:Nj,multiselect:Tj};function jj({filter:t,column:n}){const r=d.useContext(Es),o=Ot(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>Rj[t.type],[t.type]);return i.jsx(u,{filter:t,column:n,action:l,filterValue:o[n.id]})}function Ej(t){const{cell:n,column:r,row:o,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(Es),w=Ot(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),S=d.useRef(),k=d.useCallback(ve=>{S.current=n.flexgrow?ve.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),N=d.useCallback((ve,J)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(S.current||0)+ve),inProgress:J})},[y,n.id]),A=d.useCallback(ve=>N(ve,!0),[N]),j=d.useCallback(ve=>N(ve,!1),[N]),I=d.useCallback(ve=>{if(!r.sort||n.filter)return;let J=b?.order;J&&(J=J==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:ve.ctrlKey||ve.metaKey,order:J})},[y,n.id,n.filter,r.sort,b?.order]),T=d.useCallback(ve=>{ve&&ve.stopPropagation(),y.exec("collapse-column",{id:n.id,row:o})},[y,n.id,o]),_=d.useCallback(ve=>{ve.key==="Enter"&&T()},[T]),B=d.useCallback(ve=>{ve.key==="Enter"&&!n.filter&&I(ve)},[I,n.filter]),F=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),H=d.useMemo(()=>F&&!g&&n.collapsible!=="header",[F,g,n.collapsible]),D=d.useMemo(()=>H?{top:-h/2,position:"absolute"}:{},[H,h]),K=d.useMemo(()=>ph(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(F&&H?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,F,H,h]),z=d.useMemo(()=>TS(r,n,f),[r,n,f]),W=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([ve])=>ve!=="cell")),[n]),q=`wx-cell ${z} ${n.css||""} wx-collapsed`,V=["wx-cell",z,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),X=d.useRef(null);return d.useEffect(()=>{const ve=X.current;if(!ve)return;const J=Gw(ve,{down:k,move:A,up:j});return()=>{typeof J=="function"&&J()}},[k,A,j,Gw]),F?i.jsx("div",{className:"wx-RsQD74qC "+q,style:K,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:T,"data-header-id":Fa(r.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:D,children:n.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+V,style:K,onClick:I,"data-header-id":Fa(r.id),tabIndex:!n._hidden&&r.sort&&!n.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":n.colspan>1?n.colspan:void 0,"aria-rowspan":n.rowspan>1?n.rowspan:void 0,"aria-sort":!b?.order||n.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:B,children:[n.collapsible?i.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:T,children:i.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const ve=n.cell;return i.jsx(ve,{api:y,cell:W(),column:r,row:o,onAction:({action:J,data:$})=>y.exec(J,$)})})():n.filter?i.jsx(jj,{filter:n.filter,column:r}):i.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&l&&!n._hidden?i.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:X,onClick:ve=>ve.stopPropagation(),children:i.jsx("div",{})}):null,u?i.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?i.jsxs(i.Fragment,{children:[typeof b.index<"u"?i.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,i.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function Dj({cell:t,column:n,row:r,columnStyle:o}){const l=d.useContext(Es),u=d.useMemo(()=>ph(t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right??n?.right,t?.height),[t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right,n?.right,t?.height]),f=d.useMemo(()=>TS(n,t,o),[n,t,o]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${f||""} ${t?.css||""}`+(n?.fixed&&n?.fixed.right?" wx-fixed-right":"");return i.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?Cv.createElement(t.cell,{api:l,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>l.exec(y,w)}):i.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function Vw({deltaLeft:t,contentWidth:n,columns:r,type:o="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(Es),h=Ot(f,"_sizes"),g=Ot(f,"split"),y=d.useMemo(()=>h?.[`${o}RowHeights`],[h,o]),w=d.useMemo(()=>{let A=[];if(r&&r.length){const j=r[0][o].length;for(let I=0;I<j;I++){let T=0;A.push([]),r.forEach((_,B)=>{const F={..._[o][I]};T||A[I].push(F),F.colspan>1?T=F.colspan-1:T&&T--})}}return A},[r,o]),b=d.useMemo(()=>g?.left||g?.right,[g]);function S(A){return r.find(j=>j.id===A)}function k(A,j){let I=j;return A.rowspan&&(I+=A.rowspan-1),I===w.length-1}function N(A,j,I){if(!I.sort)return!1;for(let T=w.length-1;T>=0;T--){const _=I.header[T];if(!_.filter&&!_._hidden)return j===T}return k(A,j)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${o}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((A,j)=>i.jsx("div",{className:o==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[j]}px`,display:"flex"},role:"row",children:A.map(I=>{const T=S(I.id);return o==="header"?i.jsx(Ej,{cell:I,columnStyle:l,column:T,row:j,lastRow:k(I,j),bodyHeight:u,sortRow:N(I,j,T),hasSplit:b},I.id):i.jsx(Dj,{cell:I,columnStyle:l,column:S(I.id),row:j},I.id)})},j))})}function Ij({overlay:t}){const n=d.useContext(Es);function r(l){return typeof l=="function"}const o=t;return i.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?i.jsx(o,{onAction:({action:l,data:u})=>n.exec(l,u)}):t})}function Lj(t){const{editor:n,onSave:r,onApply:o}=t,[l,u]=d.useState(n?.value||""),{type:f="text"}=d.useMemo(()=>n?.config||{},[n]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const w=ho(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),o(h.current.value))}function y({key:w}){w==="Enter"&&r()}return i.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:l})}function Pj({editor:t,onAction:n,onSave:r,onApply:o,onCancel:l}){const[u,f]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,w]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),S=d.useMemo(()=>t?.config?.cell,[t]),k=d.useMemo(()=>t?.config?.dropdown||{},[t]),N=d.useMemo(()=>({trackScroll:!0,...k}),[k]),A=d.useMemo(()=>(y||[]).findIndex(D=>D.id===u),[y,u]),j=d.useRef(null),I=d.useRef(null),T=d.useCallback(D=>{j.current=D.navigate,I.current=D.keydown,j.current(A)},[A,j]),_=d.useCallback(D=>{const K=D?.target?.value??"";g(K);const z=K?(t?.options||[]).filter(W=>(W.label||"").toLowerCase().includes(K.toLowerCase())):t?.options||[];w(z),z.length?j.current(-1/0):j.current(null)},[t]),B=d.useRef(null);d.useEffect(()=>{B.current&&B.current.focus()},[]);const F=d.useRef(r);d.useEffect(()=>{F.current=r},[r]),d.useEffect(()=>{if(!B.current)return;const D=ho(B.current,()=>F.current(!0));return()=>D.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const H=d.useCallback(({id:D})=>{o(D),r()},[o,r]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:B,value:h??"",onChange:_,onKeyDown:D=>I.current?I.current(D,A):void 0}),i.jsx(fh,{items:y,onReady:T,onSelect:H,...N,onCancel:l,children:({option:D})=>b?b(D):S?i.jsx(S,{data:D,onAction:n}):D.label})]})}function _j({editor:t,onAction:n,onSave:r,onApply:o,onCancel:l}){const[u]=d.useState(()=>t.value||new Date),{template:f,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:N}){o(N),r()}const b=d.useRef(null),[S,k]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!S)return;const N=ho(S,()=>r(!0));return()=>N.destroy()},[S,r]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:l,onKeyDown:N=>N.preventDefault(),children:f?f(u):h?i.jsx(h,{data:t.value,onAction:n}):i.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),i.jsx(Uv,{...y,onCancel:l,children:i.jsx("div",{ref:k,className:"wx-lNWNYUb6",children:i.jsx(lS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function Fj(t){const{editor:n}=t,r=t.onAction??t.onaction,o=t.onSave??t.onsave,l=t.onApply??t.onapply,u=t.onCancel??t.oncancel,f=n.config||{},{dropdown:h={}}=f,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(n.options.find(_=>_.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),S=d.useMemo(()=>b.findIndex(_=>_.id===w),[b,w]);function k({id:_}){l(_),o()}let N;const[A,j]=d.useState();function I(_){N=_.navigate,j(()=>_.keydown),N(S)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const _=ho(T.current,()=>o(!0));return()=>_.destroy()},[o]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:_=>{A(_,S),_.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const _=f.cell;return i.jsx(_,{data:y,onAction:r})})():i.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),i.jsx(fh,{items:b,onReady:I,onSelect:k,...g,onCancel:u,children:({option:_})=>f.template?f.template(_):f.cell?(()=>{const B=f.cell;return i.jsx(B,{data:_,onAction:r})})():_.label})]})}function Oj(t){const{editor:n,onAction:r,onSave:o,onApply:l}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:S}){l(S)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const S=ho(b.current,()=>o(!0));return()=>S.destroy()},[o]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>o(!0),children:i.jsx(RS,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const Bj={text:Lj,combo:Pj,datepicker:_j,richselect:Fj,multiselect:Oj};function Hj({column:t,row:n}){const r=d.useContext(Es),o=Ot(r,"editor"),l=d.useCallback((N,A)=>{r.exec("close-editor",{ignore:N}),A&&r.exec("focus-cell",{...A,eventSource:"click"})},[r]),u=d.useCallback(N=>{const A=N?null:{row:o?.id,column:o?.column};l(!1,A)},[o,l]),f=d.useCallback(()=>{l(!0,{row:o?.id,column:o?.column})},[o,l]),h=d.useCallback(N=>{r.exec("editor",{value:N})},[r]),g=d.useCallback(N=>{N.key==="Enter"&&o&&(t.editor.type==="multiselect"?h(o.value):f())},[o,t.editor,f,h]),y=d.useMemo(()=>ph(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let N=t.editor;if(typeof N=="function"&&(N=N(n,t)),!N)return null;let A=typeof N=="string"?N:N.type;return Bj[A]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const S=typeof n.$parent<"u"?"gridcell":"cell",k=typeof n.$parent<"u"?!t.editor:void 0;return i.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:S,"aria-readonly":k,tabIndex:-1,onClick:N=>N.stopPropagation(),onDoubleClick:N=>N.stopPropagation(),onKeyDown:g,children:w?i.jsx(w,{editor:o,onSave:u,onApply:h,onCancel:f,onAction:({action:N,data:A})=>r.exec(N,A)}):null})}function Kw(t){const{columns:n,type:r,columnStyle:o}=t,l=d.useContext(Es),{filterValues:u,_columns:f,_sizes:h}=l.getState();function g(y){return o?" "+o(y):""}return i.jsx(i.Fragment,{children:n.map((y,w)=>i.jsx("tr",{children:y.map(b=>{const S=f.find(A=>A.id===b.id),k=`wx-print-cell-${r}${g(S)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,N=b.cell;return i.jsx("th",{style:pS(CS(b,h.columnWidth)),className:"wx-Gy81xq2u "+k,rowSpan:b.rowspan,colSpan:b.colspan,children:N?i.jsx(N,{api:l,cell:Object.fromEntries(Object.entries(b).filter(([A])=>A!=="cell")),column:S,row:w}):b.filter?i.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:qR(u,f,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function zj(t){const{columns:n,rowStyle:r,columnStyle:o,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(Es),{flatData:y,_sizes:w}=g.getState(),b=u&&zw(n,"header",w.headerRowHeights),S=f&&zw(n,"footer",w.footerRowHeights);function k(A,j){let I="";return I+=o?" "+o(j):"",I+=l?" "+l(A,j):"",I}function N(A,j){return typeof j.draggable=="function"?j.draggable(A,j)!==!1:j.draggable}return i.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(A=>A.flexgrow)?"wx-flex-columns":""}`,children:[u?i.jsx("thead",{children:i.jsx(Kw,{columns:b,type:"header",columnStyle:o})}):null,i.jsx("tbody",{children:y.map((A,j)=>i.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(A):""),style:{height:`${A.rowHeight||w.rowHeight}px`},children:n.map(I=>I.collapsed?null:i.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${k(A,I)}`,style:pS(CS(I,w.columnWidth)),children:[h&&I.draggable?i.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:N(A,I)?i.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,I.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:A.$level*28+"px"}}),A.$count?i.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${A.open!==!1?"down":"right"}`}):null]}):null,I.cell?(()=>{const T=I.cell;return i.jsx(T,{api:g,row:A,column:I})})():i.jsx("span",{children:tc(A,I)})]},I.id))},j))}),f?i.jsx("tfoot",{children:i.jsx(Kw,{columns:S,type:"footer",columnStyle:o})}):null]})}function $j(t){const{config:n,...r}=t,o=d.useContext(Es),{_skin:l,_columns:u}=o.getState(),f=d.useMemo(()=>HR(u,n),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const w=y.cloneNode(!0);g.appendChild(w);const b=`@media print { @page { size: ${n.paper} ${n.mode}; }`,S=document.createElement("style");S.setAttribute("type","text/css"),S.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(S),S.appendChild(document.createTextNode(b)),window.print(),S.remove(),g.classList.remove("wx-print"),w.remove()},[]),i.jsx("div",{className:`wx-4zwCKA7C wx-${l}-theme wx-print-container`,ref:h,children:f.map((g,y)=>i.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:i.jsx(zj,{columns:g,...r})},y))})}function Uj(t){const{header:n,footer:r,overlay:o,multiselect:l,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:S,responsiveLevel:k,hotkeys:N}=t,A=d.useContext(Es),j=Ot(A,"dynamic"),I=Ot(A,"_columns"),T=Ot(A,"flatData"),_=Ot(A,"split"),B=Ot(A,"_sizes"),[F,H]=Xs(A,"selectedRows"),D=Ot(A,"select"),K=Ot(A,"editor"),z=Ot(A,"scrollLeft"),W=Ot(A,"scrollTop"),q=Ot(A,"tree"),V=Ot(A,"focusCell"),X=Ot(A,"_print"),ve=Ot(A,"undo"),J=Ot(A,"reorder"),$=Ot(A,"_rowHeightFromData"),[P,se]=d.useState(0);d.useEffect(()=>{se(ya())},[]);const[we,Z]=d.useState(0),Se=d.useMemo(()=>(I||[]).some(oe=>!oe.hidden&&oe.flexgrow),[I]),ae=d.useMemo(()=>B?.rowHeight||0,[B]),ye=d.useRef(null),[Pe,de]=d.useState(null),[Qe,ue]=d.useState(null),_e=d.useMemo(()=>{let oe=[],$e=0;return _&&_.left&&(oe=(I||[]).slice(0,_.left).filter(tt=>!tt.hidden).map(tt=>({...tt})),oe.forEach(tt=>{tt.fixed={left:1,leftSize:_.left},tt.left=$e,$e+=tt.width}),oe.length&&(oe[oe.length-1].fixed.left=-1)),{columns:oe,width:$e}},[_,I]),Ze=d.useMemo(()=>{let oe=[],$e=0;if(_&&_.right){oe=(I||[]).slice(_.right*-1).filter(tt=>!tt.hidden).map(tt=>({...tt}));for(let tt=oe.length-1;tt>=0;tt--){const Pt=oe[tt];Pt.fixed={right:1},Pt.right=$e,$e+=Pt.width}oe.length&&(oe[0].fixed={right:-1})}return{columns:oe,width:$e}},[_,I]),at=d.useMemo(()=>{const oe=(I||[]).slice(_?.left||0,(I||[]).length-(_?.right??0)).filter($e=>!$e.hidden);return oe.forEach($e=>{$e.fixed=0}),oe},[I,_]),Ee=d.useMemo(()=>(I||[]).reduce((oe,$e)=>($e.hidden||(oe+=$e.width),oe),0),[I]),Ge=1;function me(oe,$e,tt){let Pt=$e,wn=oe;if(at.length){let Oe=at.length;for(let it=oe;it>=0;it--)at[it][tt].forEach(Nt=>{Nt.colspan>1&&it>oe-Nt.colspan&&it<Oe&&(Oe=it)});if(Oe!==at.length&&Oe<oe){for(let it=Oe;it<oe;it++)Pt-=at[it].width;wn=Oe}}return{index:wn,delta:Pt}}const ke=d.useMemo(()=>{let oe,$e,tt;const Pt=z||0,wn=(z||0)+(b||0);let Oe=0,it=0,Nt=0,bt=0;at.forEach((Ht,Pn)=>{Pt>Nt&&(Oe=Pn,bt=Nt),Nt=Nt+Ht.width,wn>Nt&&(it=Pn+Ge)});const Gt={header:0,footer:0};for(let Ht=it;Ht>=Oe;Ht--)["header","footer"].forEach(Pn=>{at[Ht]&&at[Ht][Pn].forEach(Ha=>{const sr=Ha.colspan;if(sr&&sr>1){const Rr=sr-(it-Ht+1);Rr>0&&(Gt[Pn]=Math.max(Gt[Pn],Rr))}})});const ra=me(Oe,bt,"header"),Cn=me(Oe,bt,"footer"),qn=ra.delta,Qt=ra.index,En=Cn.delta,qr=Cn.index;return Se&&Ee>(b||0)?oe=$e=tt=[..._e.columns,...at,...Ze.columns]:(oe=[..._e.columns,...at.slice(Oe,it+1),...Ze.columns],$e=[..._e.columns,...at.slice(Qt,it+Gt.header+1),...Ze.columns],tt=[..._e.columns,...at.slice(qr,it+Gt.footer+1),...Ze.columns]),{data:oe||[],header:$e||[],footer:tt||[],d:bt,df:En,dh:qn}},[at,_e,Ze,z,b,Se,Ee]),et=d.useMemo(()=>n&&B?.headerHeight||0,[n,B]),Me=d.useMemo(()=>r&&B?.footerHeight||0,[r,B]),pe=d.useMemo(()=>b&&S?Ee>=b:!1,[b,S,Ee]),[qe,Re]=d.useState(!1),st=d.useMemo(()=>(S||0)-et-Me-(pe?P:0),[S,et,Me,pe,P]),jt=d.useMemo(()=>Math.ceil((st||0)/(ae||1))+1,[st,ae]),O=d.useRef([]),[ze,We]=d.useState(0),[Et,lt]=d.useState(void 0),ht=d.useMemo(()=>{let oe=0,$e=0;const tt=2,Pt=W||0;if(y){let it=Pt;for(;it>0;)it-=O.current[oe]||ae,oe++;$e=Pt-it;for(let Nt=Math.max(0,oe-tt-1);Nt<oe;Nt++)$e-=O.current[oe-Nt]||ae;oe=Math.max(0,oe-tt)}else{if($){let it=0,Nt=0;for(let Cn=0;Cn<(T||[]).length;Cn++){const qn=T[Cn].rowHeight||ae;if(Nt+qn>Pt){it=Cn;break}Nt+=qn}oe=Math.max(0,it-tt);for(let Cn=0;Cn<oe;Cn++)$e+=T[Cn].rowHeight||ae;let bt=0,Gt=0;for(let Cn=it+1;Cn<(T||[]).length;Cn++){const qn=T[Cn].rowHeight||ae;if(bt++,Gt+qn>st)break;Gt+=qn}const ra=Math.min(j?j.rowCount:(T||[]).length,it+bt+tt);return{d:$e,start:oe,end:ra}}oe=Math.floor(Pt/(ae||1)),oe=Math.max(0,oe-tt),$e=oe*(ae||0)}const wn=j?j.rowCount:(T||[]).length,Oe=Math.min(wn,oe+(jt||0)+tt);return{d:$e,start:oe,end:Oe}},[y,$,W,ae,j,T,jt,st]),Je=d.useMemo(()=>{const oe=j?j.rowCount:(T||[]).length;if(y)return ze+ht.d+(oe-(Et||0))*(ae||0);if(!$)return oe*(ae||0);let $e=0;for(let tt=0;tt<oe;tt++)$e+=T[tt]?.rowHeight||ae;return $e},[j,T,ae,y,$,ze,ht.d,Et]),be=d.useRef({});be.current={clientWidth:b,clientHeight:S,fullHeight:Je,headerHeight:et,footerHeight:Me,fullWidth:Ee,SCROLLSIZE:P};const je=d.useCallback(()=>{const oe=be.current;Re(oe.clientWidth&&oe.clientHeight?oe.fullHeight+oe.headerHeight+oe.footerHeight>=oe.clientHeight-(oe.fullWidth>=oe.clientWidth?oe.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const oe=requestAnimationFrame(je);return()=>window.cancelAnimationFrame(oe)},[we,je]),d.useEffect(()=>{je()},[S,je]);const Ae=d.useMemo(()=>Se&&Ee<=(b||0)?(b||0)-0-(qe?P:0):Ee,[Se,Ee,b,qe,P,pe]),fe=d.useMemo(()=>Se&&Ee<=(b||0)?b||0:Ae<(b||0)?Ee+(qe?P:0):-1,[Se,Ee,b,Ae,qe,P]),te=d.useRef({});d.useEffect(()=>{if(j&&(te.current.start!==ht.start||te.current.end!==ht.end)){const{start:oe,end:$e}=ht;te.current={start:oe,end:$e},A&&A.exec&&A.exec("request-data",{row:{start:oe,end:$e}})}},[j,ht,A]);const ce=d.useMemo(()=>j?T||[]:(T||[]).slice(ht.start,ht.end),[j,T,ht]),Ne=d.useMemo(()=>(F||[]).filter(oe=>(ce||[]).some($e=>$e.id===oe)),[H,ce]),He=d.useMemo(()=>ht.start,[ht.start]),Ie=d.useRef({top:W,left:z});Ie.current={top:W,left:z};const Lt=d.useCallback(oe=>{const $e=oe.target.scrollTop,tt=oe.target.scrollLeft,Pt=Ie.current;($e!==Pt.top||tt!==Pt.left)&&A.exec("scroll-to",{top:$e,left:tt})},[A]),Xe=d.useCallback(oe=>{oe.shiftKey&&oe.preventDefault(),ye.current&&ye.current.focus&&ye.current.focus()},[]),ut=d.useCallback(()=>!!(I||[]).find(oe=>!!oe.draggable),[I]),yt=d.useRef(null),_t=d.useRef(null),mt=d.useRef({dblclick:(oe,$e)=>{const tt={id:oe,column:rm($e,"data-col-id")};A.exec("open-editor",tt)},click:(oe,$e)=>{if($e.target.closest("input")||yt.current)return;const tt=rm($e,"data-col-id");if(V?.id!==oe&&A.exec("focus-cell",{row:oe,column:tt,eventSource:"click"}),D===!1)return;const Pt=l&&($e.ctrlKey||$e.metaKey),wn=l&&$e.shiftKey;(Pt||F.length>1||!F.includes(oe))&&A.exec("select-row",{id:oe,toggle:Pt,range:wn})},"toggle-row":oe=>{const $e=A.getRow(oe);A.exec($e.open!==!1?"close-row":"open-row",{id:oe})},"ignore-click":()=>!1}),Vt=d.useMemo(()=>({top:et,bottom:Me,left:_e.width,xScroll:pe,yScroll:qe,sense:y&&Qe?Qe.offsetHeight:Math.max(B?.rowHeight||0,40),node:ye.current&&ye.current.firstElementChild}),[et,Me,_e.width,pe,qe,y,Qe,B]);function St(oe,$e){const{container:tt,sourceNode:Pt,from:wn}=$e;if(ut()&&!Pt.getAttribute("draggable-data"))return!1;de(wn),q&&A.getRow(wn).open&&A.exec("close-row",{id:wn,nested:!0});const Oe=Id(Pt),it=Oe.cloneNode(!0);it.classList.remove("wx-selected"),it.querySelectorAll("[tabindex]").forEach(ra=>ra.setAttribute("tabindex","-1")),tt.appendChild(it),ue(it);const Nt=(z||0)-ke.d,bt=qe?P:0;tt.style.width=Math.min((b||0)-bt,Se&&Ee<=(b||0)?Ae:Ae-bt)+Nt+"px";const Gt=_p(Oe);$e.offset={x:Nt,y:-Math.round(Gt.height/2)},_t.current||(_t.current=oe.clientY)}function pn(oe,$e){const{from:tt}=$e,Pt=$e.pos,wn=_p(ye.current);Pt.x=wn.x;const Oe=Vt.top;if(Pt.y<Oe)Pt.y=Oe;else{const it=wn.height-(pe&&P>0?P:Math.round(Vt.sense/2))-Vt.bottom;Pt.y>it&&(Pt.y=it)}if(ye.current.contains($e.targetNode)){const it=Id($e.targetNode),Nt=it&&uh(it);if(Nt&&Nt!==tt){$e.to=Nt;const bt=y?Qe?.offsetHeight:B?.rowHeight;if(Qe&&((W||0)===0||Pt.y>Oe+bt-1)){const Gt=it.getBoundingClientRect(),ra=_p(Qe).y,Cn=Gt.y,qn=ra>Cn?-1:1,Qt=qn===1?"after":"before",En=A.getState().flatData,qr=Math.abs(En.findIndex(Pn=>Pn.id===tt)-En.findIndex(Pn=>Pn.id===Nt)),Ht=qr!==1?Qt==="before"?"after":"before":Qt;if(qr===1&&(qn===-1&&oe.clientY>_t.current||qn===1&&oe.clientY<_t.current))return;_t.current=oe.clientY,A.exec("move-item",{id:tt,target:Nt,mode:Ht,inProgress:!0})}}u&&u({event:oe,context:$e})}bj(oe,wn,$e,Vt)}function rn(oe,$e){const{from:tt,to:Pt}=$e;A.exec("move-item",{id:tt,target:Pt,inProgress:!1}),yt.current=setTimeout(()=>{yt.current=0},1),de(null),ue(null),_t.current=null,AS($e)}function ya(){const oe=document.createElement("div");oe.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(oe);const $e=oe.offsetWidth-oe.clientWidth;return document.body.removeChild(oe),$e}const Ct=d.useMemo(()=>fe>0?{width:`${fe}px`}:void 0,[fe]),gn=d.useRef(null);function en(){Promise.resolve().then(()=>{let oe=0,$e=He;const tt=gn.current;tt&&(Array.from(tt.children).forEach((Pt,wn)=>{O.current[He+wn]=Pt.offsetHeight,oe+=Pt.offsetHeight,$e++}),We(oe),lt($e))})}d.useEffect(()=>{ce&&y&&en()},[ce,y,He]);let[U,nt]=d.useState();d.useEffect(()=>{if(V&&(!D||!Ne.length||Ne.includes(V.row)))nt({...V});else if(ce.length&&ke.data.length){if(!U||Ne.length&&!Ne.includes(U.row)||ce.findIndex(oe=>oe.id===U.row)===-1||ke.data.findIndex(oe=>oe.id===U.column&&!oe.collapsed)===-1){const oe=Ne[0]||ce[0].id,$e=ke.data.findIndex(tt=>!tt.collapsed);nt($e!==-1?{row:oe,column:ke.data[$e].id}:null)}}else nt(null)},[V]);const Dt=d.useRef(null);d.useEffect(()=>{const oe=ye.current;if(!oe)return;const $e=pj(oe,w);return()=>{typeof $e=="function"&&$e()}},[w]);const vn=d.useRef({});Object.assign(vn.current,{start:St,move:pn,end:rn,getReorder:()=>J,getDraggableInfo:()=>({hasDraggable:ut()})}),d.useEffect(()=>{const oe=ye.current;return oe?gj(oe,vn).destroy:void 0},[J,ye.current]),d.useEffect(()=>{const oe=ye.current;return oe?fj(oe,{keys:N!==!1&&{...dj,"ctrl+z":ve,"ctrl+y":ve,...N},exec:$e=>A.exec("hotkey",$e)}).destroy:void 0},[A,ve,N]);const Nr=d.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});Nr.current.getWidth=()=>(b||0)-(qe?P:0),Nr.current.getHeight=()=>st,Nr.current.getScrollMargin=()=>_e.width+Ze.width,d.useEffect(()=>{mj(Dt.current,Nr.current)},[]);const Ur=d.useRef(null);d.useEffect(()=>{const oe=Ur.current;if(!oe)return;const $e=[];$e.push(ho(oe,()=>V&&A.exec("focus-cell",{eventSource:"click"})).destroy),$e.push(gR(oe,mt.current)),Z(oe.clientHeight);const tt=new ResizeObserver(()=>{Z(oe.clientHeight)});return tt.observe(oe),$e.push(()=>tt.disconnect()),()=>$e.forEach(Pt=>Pt())},[]);const Tr=`wx-grid ${k?`wx-responsive-${k}`:""}`;return d.useEffect(()=>{V&&(ce.some(oe=>oe.id===V.row)&&ke.data.some(oe=>oe.id===V.column&&!oe.collapsed)||A.exec("focus-cell",{eventSource:"destroy"}))},[V,ce,ke.data,A]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-4VuBwK2D "+Tr,style:{"--header-height":`${et}px`,"--footer-height":`${Me}px`,"--split-left-width":`${_e.width}px`,"--split-right-width":`${Ze.width}px`},children:i.jsx("div",{ref:ye,className:"wx-4VuBwK2D wx-table-box",style:Ct,role:q?"treegrid":"grid","aria-colcount":ke.data.length,"aria-rowcount":ce.length,"aria-multiselectable":q&&l?!0:void 0,tabIndex:-1,children:i.jsxs("div",{ref:Dt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:pe?"scroll":"hidden",overflowY:qe?"scroll":"hidden"},onScroll:Lt,children:[n?i.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:i.jsx(Vw,{contentWidth:Ae,deltaLeft:ke.dh,columns:ke.header,columnStyle:h,bodyHeight:st-+r})}):null,i.jsxs("div",{ref:Ur,className:"wx-4VuBwK2D wx-body",style:{width:`${Ae}px`,height:`${Je}px`},onMouseDown:oe=>Xe(oe),children:[o?i.jsx(Ij,{overlay:o}):null,i.jsx("div",{ref:gn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${ht.d}px`,paddingLeft:`${ke.d}px`},children:ce.map((oe,$e)=>{const tt=F.indexOf(oe.id)!==-1,Pt=Pe===oe.id,wn="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(oe):"")+(tt?" wx-selected":"")+(Pt?" wx-inactive":""),Oe=y?{minHeight:`${oe.rowHeight||ae}px`}:{height:`${oe.rowHeight||ae}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+wn,"data-id":Fa(oe.id),"data-context-id":Fa(oe.id),style:Oe,role:"row","aria-rowindex":$e,"aria-expanded":oe.open,"aria-level":q?oe.$level+1:void 0,"aria-selected":q?tt:void 0,tabIndex:-1,children:ke.data.map(it=>it.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},it.id):K?.id===oe.id&&K.column===it.id?i.jsx(Hj,{row:oe,column:it},it.id):i.jsx(kj,{row:oe,column:it,columnStyle:h,cellStyle:g,reorder:J,focusable:U?.row===oe.id&&U?.column===it.id},it.id))},oe.id)})})]}),r&&(T||[]).length?i.jsx(Vw,{type:"footer",contentWidth:Ae,deltaLeft:ke.df,columns:ke.footer,columnStyle:h}):null]})})}),X?i.jsx($j,{config:X,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:J}):null]})}const qj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),Wj=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:o=null,cellStyle:l=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:S=!1,onReorder:k=null,autoRowHeight:N=!1,sizes:A,split:j,tree:I=!1,autoConfig:T=!1,init:_=null,responsive:B=null,sortMarks:F,undo:H=!1,hotkeys:D=null,filterValues:K,...z},W){const q=d.useRef();q.current=z;const V=d.useMemo(()=>new sj(hS),[]),X=d.useMemo(()=>V.in,[V]),ve=d.useRef(null);ve.current===null&&(ve.current=new cS((Ze,at)=>{const Ee="on"+qj(Ze);q.current&&q.current[Ee]&&q.current[Ee](at)}),X.setNext(ve.current));const J=d.useMemo(()=>({getState:V.getState.bind(V),getReactiveState:V.getReactive.bind(V),getStores:()=>({data:V}),exec:X.exec,setNext:Ze=>(ve.current=ve.current.setNext(Ze),ve.current),intercept:X.intercept.bind(X),on:X.on.bind(X),detach:X.detach.bind(X),getRow:V.getRow.bind(V),getColumn:V.getColumn.bind(V)}),[V,X]),[$,P]=d.useState(0),[se,we]=d.useState(0),[Z,Se]=d.useState(null),[ae,ye]=d.useState(null),Pe=d.useMemo(()=>{if(T&&!n.length&&t.length){const Ze=t[0],at=[];for(let Ee in Ze)if(Ee!=="id"&&Ee[0]!=="$"){let Ge={id:Ee,header:Ee[0].toUpperCase()+Ee.slice(1)};typeof T=="object"&&(Ge={...Ge,...T}),at.push(Ge)}return at}return(ae&&ae.columns)??n},[T,n,t,ae]),de=d.useMemo(()=>(ae&&ae.sizes)??A,[ae,A]),Qe=d.useCallback(Ze=>{if(P(Ze.width),we(Ze.height),B){const at=Object.keys(B).map(Number).sort((Ee,Ge)=>Ee-Ge).find(Ee=>Ze.width<=Ee)??null;at!==Z&&(ye(B[at]),Se(at))}},[B,Z]),ue=d.useContext(Ba.theme),_e=d.useRef(0);return d.useEffect(()=>{if(!_e.current)_&&_(J);else{const Ze=V.getState();V.init({data:t,columns:Pe,split:j||Ze.split,sizes:de||Ze.sizes,selectedRows:u||Ze.selectedRows,dynamic:w,tree:I,sortMarks:F||Ze.sortMarks,filterValues:K||Ze.filterValues,undo:H,reorder:S,_skin:ue,_select:f})}_e.current++},[V,t,Pe,j,de,u,w,I,F,K,H,S,ue,f,_,J]),_e.current===0&&V.init({data:t,columns:Pe,split:j||{left:0},sizes:de||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:K||{},undo:H,reorder:S,_skin:ue,select:f}),d.useImperativeHandle(W,()=>({...J}),[J]),i.jsx(Es.Provider,{value:J,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(Uj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:o,cellStyle:l,onReorder:k,multiselect:h,autoRowHeight:N,clientWidth:$,clientHeight:se,responsiveLevel:Z,resize:Qe,hotkeys:D})})})});Bv(cs);const Oa=d.createContext(null),Yv=d.createContext(null),Xv=d.createContext(null);function Gj({children:t}){const n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=d.useContext(Oa),[l]=Xs(o,"panels"),u=Ot(o,"activePanel"),f=l[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,S]=d.useState(""),[k,N]=d.useState(""),[A,j]=d.useState(!1);function I(){const F=b.trim();if(!F){j(!0);return}h.add?o.exec("create-file",{file:{...h.item,name:F},parent:f}):k!==F&&o.exec("rename-file",{id:h.item.id,name:F}),T()}function T(){g(null),j(null),N(""),S("")}function _(){o.exec("delete-files",{ids:y.selected}),w(null)}const B=d.useMemo(()=>({showPrompt(F){const H=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);N(H),S(H),g({...F})},showConfirm(F){w({...F})}}),[r]);return i.jsxs(Yv.Provider,{value:B,children:[i.jsx(GT,{children:t}),h?i.jsx(gv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:T,children:i.jsx(qv,{error:A,select:!0,focus:!0,value:b,onChange:({value:F})=>S(F)})}):null,y?i.jsx(gv,{title:r("Are you sure you want to delete these items:"),onConfirm:_,onCancel:()=>w(null),children:y.selected?i.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((F,H)=>i.jsx("li",{children:F},H))}):null}):null]})}let Qw={"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 Vj(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),o=t.slice(0,-r),l=t.slice(-r);return[o,l]}function Kj({item:t}){const n=d.useContext(Oa),r=d.useContext(Ba.i18n).getGroup("filemanager"),o=d.useContext(Oa).templates,[l]=Xs(n,"panels"),u=Ot(n,"activePanel"),f=Ot(n,"mode"),h=l[u].selected,g=d.useMemo(()=>o.preview(t,214,163),[o,t]),y=d.useMemo(()=>o.icon(t,"big"),[o,t]),[w,b]=d.useMemo(()=>Vj(t.name),[t.name]);return i.jsx(i.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?i.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:i.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":Fa("/wx-filemanager-parent-link"),children:[i.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),i.jsx("span",{children:r("Back to parent folder")})]})}):null:i.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":Fa(t.id),children:[g?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):i.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:i.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[i.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})]}),i.jsx("div",{"data-action-id":Fa(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})}),i.jsx("div",{"data-action-id":Fa(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function jS(){const t=d.useContext(Oa),n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[o]=Xs(t,"panels"),l=Ot(t,"activePanel"),u=Ot(t,"mode"),f=o[l]._files,h=o[l].selected,g=o[l].path,y=o[l]._crumbs,w=o[l]._selectNavigation,b=d.useCallback((T,_)=>{const B=_&&(_.ctrlKey||_.metaKey),F=_&&_.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(B||F))return;t.exec("select-file",{type:"navigation"});return}let H=T==="body"&&_?null:T;const D=_.target.className.indexOf("wx-more")!==-1||_.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:H,toggle:B&&!D,range:F&&!D,panel:l})},1)},[t,h,l]),S=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:l,selected:[y[y.length-1].id]})},[t,y,l]),k=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return S();u==="search"&&t.exec("filter-files",{text:""});const _=f.find(B=>B.id===T);_&&(_.type=="folder"?t.exec("set-path",{id:_.id,panel:l}):t.exec("open-file",{id:_.id}))},[t,S,u,f,l]),N=d.useCallback((T,_)=>{(!h?.length||!h.filter(B=>B?.id===T).length>0)&&b(T,_)},[h,b]),A=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),j=d.useRef(null),I=d.useRef();return d.useEffect(()=>{j.current&&(I.current?(I.current.click=b,I.current._dblclick=k,I.current.context=N):(I.current={click:b,dblclick:T=>I.current._dblclick(T),_dblclick:k,context:N},Ld(j.current,I.current)))},[b,k,N]),u=="search"&&!A.length?i.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:i.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):i.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":Fa("body"),ref:j,children:A.map(T=>i.jsx(Kj,{item:T},T.id))})}function iu({name:t="",spin:n=!1,onClick:r}){return i.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function Qj(){const t=d.useContext(Ba.i18n).getGroup("filemanager"),n=d.useContext(Oa),r=Ot(n,"activePanel"),[o]=Xs(n,"panels"),l=d.useMemo(()=>o[r]._crumbs,[o,r]);function u(){n.exec("filter-files",{text:""})}return i.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[i.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[i.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:i.jsx(iu,{name:"angle-left",onClick:u})}),i.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(l)&&l.map((f,h)=>i.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),i.jsx(jS,{})]})}function jg({narrowMode:t,extraInfo:n}){const r=d.useContext(Oa),{preview:o,icon:l}=r.templates,u=d.useContext(Ba.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Td("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Xs(r,"panels"),w=Ot(r,"activePanel"),b=Ot(r,"preview"),S=Ot(r,"search"),k=d.useMemo(()=>{const D=g&&w!=null&&g[w]?._selected?.length||0;return S&&!D},[S,y,w]),N=d.useMemo(()=>{const D=g&&w!=null?g[w]:null;return D?k?D._files:D._selected:[]},[k,y,w]),A=d.useCallback((D,K)=>(D?`${D} ${f(D>1?"folders":"folder")} `:"")+(K?`${K} ${f(K>1?"files":"file")}`:""),[f]),j=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(D=>D.type==="folder"?f("Folder"):D.ext||f("Unknown file"),[f]),T=d.useMemo(()=>{let D,K,z,W,q,V,X,ve;if(N.length===1&&!k){K=N[0],D=K.name;const J=o(K,400,500);J?(z=J,W=""):(W=l(K,"big"),z=""),q=K.type!=="folder"}else{if(K=q=null,D="",N.length){let J=0,$=0,P=0,se=[],we;N.forEach(Se=>{typeof Se.size>"u"&&(we=!0,J=void 0),we||(J+=Se.size),se.push(I(Se)),Se.type==="folder"?$++:P++});const Z=new Set(se);V=Z.size>1?f("multiple"):[...Z][0],X=A($,P),ve=J,k||(D=f("Multiple files"))}W=l({type:k?"search":N.length?"multiple":"none"},"big"),z=""}return{name:D,item:K,previewSrc:z,iconSrc:W,showDownloadIcon:q,type:V,totalCount:X,totalSize:ve}},[N,k,o,l,f,I,A]),_=d.useCallback(()=>{r.exec("download-file",{id:N[0].id})},[r,N]),B=d.useCallback(async D=>{if(!n||!D)return null;try{return await n(D)}catch(K){return console.log(K),null}},[n]),[F,H]=d.useState(null);return d.useEffect(()=>{let D=!1;return H(null),Promise.resolve(B(T.item)).then(K=>{D||H(K)}).catch(()=>{D||H(null)}),()=>{D=!0}},[B,T.item]),i.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:N&&N.length?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?i.jsx(iu,{name:"download",onClick:_}):null,t?i.jsx(iu,{name:"close",onClick:j}):null]})]}),T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"file-multiple-outline"}`})})]}),i.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(k?"Found":"Information")}),i.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:I(T.item)}),typeof T.item.size<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:sm(T.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:sm(T.totalSize)})]}):null]}),F?Object.entries(F).map(([D,K])=>i.jsxs(Cv.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:D}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:K})]},D)):null]})]})]}):i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?i.jsx(iu,{name:"close",onClick:j}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"message-question-outline"}`})}),i.jsx("span",{className:"wx-O0BTtRrH wx-text",children:k?"":f("Select file or folder to view details")})]})})]})})}function ES({panel:t}){const n=d.useContext(Oa),r=d.useContext(Ba.i18n),o=d.useMemo(()=>r.getGroup("filemanager"),[r]),[l,u]=Xs(n,"panels"),f=d.useMemo(()=>l[t]._files,[u,t]),h=d.useMemo(()=>l[t]._crumbs||[],[u,t]);function g(N){const A=Kv(N,h);n.exec("set-path",{id:N,panel:t,...A&&{selected:[A]}})}const[y,w]=d.useState(null);d.useEffect(()=>{f&&w(null)},[f]);function b(){w(!0),n.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{w(null)},5e3)}const S=d.useRef(null),k=d.useRef();return d.useEffect(()=>{k.current?k.current.click=g:(k.current={click:g},Ld(S.current,k.current))},[g]),i.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:S,children:[i.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:i.jsx(iu,{name:"refresh",spin:!!y,onClick:b})}),h.map((N,A)=>i.jsxs(Cv.Fragment,{children:[A?i.jsx(iu,{name:"angle-right"}):null,i.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Fa(N.id),"data-menu-ignore":"true",children:N.id=="/"?o(N.name):N.name})]},A))]})}function Yj({row:t}){const n=d.useContext(Ba.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),o=d.useContext(Oa).templates,[l]=d.useState(()=>o.icon(t,"small"));return i.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):i.jsxs(i.Fragment,{children:[l?i.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:l,height:"24px",width:"24px"}):i.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function DS({children:t}){const n=d.useContext(Oa),r=Ot(n,"activePanel"),o=d.useContext(Xv),l=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=l.current,h=JN(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=l.current;return o.droparea(f,u.current)},[]),i.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:l,children:t})}function bv({panel:t,active:n=!1,onClick:r,onContextMenu:o}){const l=d.useContext(Oa),u=d.useContext(Ba.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Td("%d %M %Y",u.getRaw().calendar),[u]),[g]=Xs(l,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,S=g[t]._sorts,k=g[t]._selectNavigation,N=g[t]._files,A=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:Yj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:V=>typeof V=="number"?sm(V):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:V=>V?h(V):""}],[f,h]),j=d.useRef(null),I=d.useRef(null),T=d.useMemo(()=>k?["/wx-filemanager-parent-link"]:[...y],[k,y]);function _(V,X){if(X&&X.target&&X.target.className&&X.target.className.indexOf("wx-grip")!==-1)return;const ve=X&&(X.ctrlKey||X.metaKey),J=X&&X.shiftKey;if(V==="/wx-filemanager-parent-link"){if(y.length&&(ve||J))return;l.exec("select-file",{type:"navigation"});return}let $=V==="body"&&X?null:V;!j.current&&!I.current?l.exec("select-file",{id:$,toggle:ve,range:J,panel:t}):(j.current=null,I.current=null)}function B(){b.length>1&&l.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function F(V){if(V==="/wx-filemanager-parent-link")return B();const X=N.find(ve=>ve.id===V);X&&(X.type==="folder"?l.exec("set-path",{id:X.id,panel:t}):l.exec("open-file",{id:X.id}))}function H(V){const X=V.key,ve=S[w];let J=ve?"asc":"desc";ve&&ve.key===X&&(J=ve.order==="asc"?"desc":"asc"),l.exec("sort-files",{key:X,order:J,panel:t,path:w})}function D(V){V.intercept("sort-rows",X=>(j.current=!0,H(X),!1)),V.intercept("select-row",()=>!1),V.on("resize-column",()=>I.current=!0),V.intercept("hotkey",()=>!1)}const K=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...N]:N,[w,N,f]),z=d.useMemo(()=>{if(K&&S&&S[w]){const{key:V,order:X}=S[w];return{[V]:{order:X}}}},[K,S,w]),W=d.useRef(null),q=d.useRef();return d.useEffect(()=>{q.current?(q.current.click=_,q.current._dblclick=F):(q.current={click:_,dblclick:V=>q.current._dblclick(V),_dblclick:F},Ld(W.current,q.current))},[_,F]),i.jsxs("div",{onClick:r,onContextMenu:o,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(ES,{panel:t}),i.jsx("div",{"data-id":Fa("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:W,children:i.jsx(DS,{children:i.jsx(Wj,{init:D,data:K,columns:A,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:z})})})]})}function Xj(){const t=d.useContext(Oa),n=Ot(t,"activePanel");function r(o){t.exec("set-active-panel",{panel:o})}return i.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Fa("body"),children:[i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:i.jsx(bv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:i.jsx(bv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function IS({folderIcon:t=!1,folder:n={}}){const r=d.useContext(Oa),[o,l]=Xs(r,"panels"),u=Ot(r,"activePanel"),f=d.useMemo(()=>o[u].path,[l,u]),h=d.useContext(Ba.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(k=>k.type==="folder"),[n]),w=d.useMemo(()=>n.id=="/"?g(n.name):n.name,[n,g]),b=d.useMemo(()=>n.$level>1?(n.$level-1)*20:0,[n]),S=n.open;return i.jsxs(i.Fragment,{children:[i.jsxs("li",{"data-id":Fa(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?i.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${S?"angle-down":"angle-right"}`,"data-action":"toggle"}):i.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),i.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),i.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),S&&n.data&&n.data.length&&y?i.jsx(i.Fragment,{children:n.data.map(k=>k.type==="folder"?i.jsx(IS,{folder:k},k.id):null)}):null]})}function Zj(){const t=d.useContext(Oa),[n,r]=Xs(t,"data"),[o,l]=Xs(t,"panels"),u=Ot(t,"activePanel"),f=d.useMemo(()=>o[u]._crumbs,[l,u]),h=d.useCallback(k=>{t.exec("open-tree-folder",{id:k,mode:!n.byId(k).open})},[t,r]),g=d.useCallback(k=>{const N=Kv(k,f);t.exec("set-path",{id:k,panel:u,...N&&{selected:[N]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),S=d.useRef();return d.useEffect(()=>{S.current?(S.current.click=g,S.current.toggle=h):(S.current={click:g,toggle:h},Ld(b.current,S.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(k=>k.type==="folder"?i.jsx(IS,{folder:k},k.id):null)})}function Jj(){const t=d.useContext(Oa),n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=Ot(t,"drive"),l=o?o.used:"",u=o?o.total:"";return l&&u?i.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[i.jsx("progress",{value:l,max:u,className:"wx-DetSyKGG wx-progress"}),i.jsxs("p",{children:[sm(l)," ",r("of")," ",sm(u)," ",r("used")]})]}):null}function eE({option:t}){const n=d.useContext(Ba.i18n).getGroup("filemanager"),r=d.useContext(Xv),o=d.useCallback(()=>{r.open({})},[r]);return i.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:o,children:i.jsx("span",{children:n(t.text)})})}function tE({readonly:t,menuOptions:n}){const r=d.useContext(Ba.i18n).getGroup("filemanager"),{showPrompt:o}=d.useContext(Yv);d.useEffect(()=>{bR("upload",eE)},[]);function l({action:f}){f&&(f.id==="add-file"?o({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&o({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>n("add").map(f=>(f.text=r(f.text),f)),[n,r]);return i.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&i.jsx("div",{className:"wx-FlucfALM wx-button",children:i.jsx(xR,{options:u,at:"bottom-fit",onClick:l,children:i.jsx(Jf,{type:"primary block",children:r("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(Zj,{})}),i.jsx(Jj,{})]})}function nE({value:t="",onSearch:n}){const[r,o]=mS(t),l=d.useContext(Ba.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;o(w),n&&n({value:w})}function g(){o(""),u.current&&u.current.focus(),n&&n({value:""})}return i.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[i.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),i.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:l("Search")})]})}function aE({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(Oa),o=d.useContext(Ba.i18n).getGroup("filemanager"),l=Ot(r,"mode"),u=Ot(r,"preview"),f=Ot(r,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){r.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),r.exec("show-preview",{mode:!u})}function w(b){r.exec("filter-files",{text:b.value})}return i.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[i.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?l==="panels"||l==="search"?null:i.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Fa("toggle-tree"),children:i.jsx(iu,{onClick:()=>n&&n(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:o("Files")}),i.jsx(nE,{onSearch:w,value:f})]}),i.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:i.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:i.jsx(VT,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx(zT,{value:l,options:h,onChange:g})})]})]})}function rE(){const t=d.useContext(Oa),n=Ot(t,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(ES,{panel:n}),i.jsx(DS,{children:i.jsx(jS,{})})]})}function sE({readonly:t=!1,menuOptions:n,extraInfo:r}){const o=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=wS(),S=d.useContext(Oa),{showPrompt:k,showConfirm:N}=d.useContext(Yv),A=d.useContext(Ba.i18n),j=d.useMemo(()=>A.getGroup("filemanager"),[A]),I=Ot(S,"mode"),T=Ot(S,"preview"),_=Ot(S,"activePanel"),[B,F]=Xs(S,"panels"),H=d.useMemo(()=>(B&&_!=null?B[_]:null)?.selected??[],[F,_]),D=d.useMemo(()=>(B&&_!=null?B[_]:null)?.path,[F,_]),[K,z]=d.useState([]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=new ResizeObserver(ae=>{const ye=ae[0]?.borderBoxSize?.[0]?.inlineSize;typeof ye=="number"&&g(ye<768)});return Se.observe(Z),()=>{Se.disconnect()}},[]);const W=d.useCallback(()=>{w(Z=>!Z)},[]),q=d.useCallback(Z=>{h&&rm(Z)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const Z=l.current;if(Z)return ho(Z,q).destroy},[q]),d.useEffect(()=>{const Z=l.current;if(!Z)return;const Se=new ResizeObserver(()=>{Z&&f(Z.clientWidth)});return Se.observe(Z),Z&&f(Z.clientWidth),()=>{Se.disconnect()}},[]);const V=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),X=d.useCallback(Z=>{let Se=h?[V]:[];return Z==="file"&&(Se=[...Se,...n().filter(ae=>ae.id==="download")]),Se},[h,V,n]),ve=d.useRef(null),J=d.useCallback((Z,Se,ae)=>{const ye=ae?[Se.id]:H;switch(Z){case"download":S.exec("download-file",{id:Se.id});break;case"copy":case"move":ve.current={action:Z,ids:ye};break;case"paste":ve.current&&S.exec(ve.current.action==="copy"?"copy-files":"move-files",{ids:ve.current.ids,target:Se?.type==="folder"?Se.id:D});break;case"rename":k({item:Se});break;case"delete":N({selected:ye});break;case"preview":S.exec("show-preview",{mode:!T});break}},[S,H,D,k,N,T]),$=d.useCallback(()=>B?.[_],[B,_]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=lR(Z,{api:S,menuOptions:t?X:n,performAction:J,getPanel:$});return()=>{typeof Se=="function"?Se():Se&&typeof Se.destroy=="function"&&Se.destroy()}},[S,t,X,n,J,$]);const P=d.useCallback((Z,Se)=>{const ae=Z?S.getFile(Z):null,ye=Se.target.closest(".tree-item.folder");let Pe;if(t)Pe=X(ae?.type);else{switch(Z){case"body":Pe=n(Z);break;default:if(ae)if(!ye&&H.length>1)Pe=h?[V,...n("multiselect")]:n("multiselect");else if(Z==="/")Pe=n("folder",ae).filter(de=>de.id==="paste");else{const de=n(ae.type,ae);de&&(Pe=h?[V,...de]:de)}}I==="search"&&(Pe=Pe?.filter(de=>de.id!=="paste"))}if(ae?.id&&(!H.length||!H.some(de=>de===ae.id))&&!ye&&S.exec("select-file",{id:ae.id}),Pe?.length)return Pe.forEach(de=>{ye&&(de.hotkey=""),de.text&&(de.text=j(de.text)),de.hotkey&&(de.subtext=de.hotkey)}),z(Pe),ae||{}},[S,t,X,n,H,h,V,I,j]),se=d.useCallback(Z=>{const{action:Se,context:ae}=Z;Se&&J(Se.id,ae,!Se.hotkey)},[J]);async function we(Z){await Promise.resolve();const{name:Se,size:ae}=Z.file;S.exec("create-file",{file:{name:Se,size:ae,date:new Date,file:Z.file},parent:D})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:o,"data-menu-ignore":"false",children:h&&T?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(jg,{narrowMode:h,extraInfo:r})}):i.jsxs(i.Fragment,{children:[i.jsx(aE,{narrowMode:h,onShowTree:W}),i.jsx(SR,{dataKey:"id",at:"point",options:K,resolver:P,onClick:se,children:i.jsxs(bS,{dataKey:"actionId",options:K,resolver:P,onClick:se,children:[i.jsx(NR,{data:b,apiOnly:!0,uploadURL:we}),i.jsx(Xv.Provider,{value:b,children:i.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:I!=="panels"&&I!=="search"?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:l,children:i.jsx(tE,{readonly:t,menuOptions:n})}),i.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Fa("body"),children:I==="table"?i.jsx(bv,{panel:_}):i.jsx(rE,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:I==="panels"?i.jsx(Xj,{}):i.jsx(Qj,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})})})]})})]})})}const iE=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function oE(t,n){const{type:r,ext:o}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Qw[r]?l=r:o?l=Qw[o]?o:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const lE=d.forwardRef(function(t,n){const{data:r=[],mode:o="cards",drive:l=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=sR,extraInfo:w=null,init:b=null,icons:S=oE,previews:k=null,...N}=t,A=d.useRef();A.current=N;const j=d.useMemo(()=>new rR(hS),[]),I=d.useMemo(()=>j.in,[j]),T=d.useRef(null);T.current===null&&(T.current=new cS((F,H)=>{const D="on"+iE(F);A.current&&A.current[D]&&A.current[D](H)}),I.setNext(T.current));const _=d.useMemo(()=>({getState:j.getState.bind(j),getReactiveState:j.getReactive.bind(j),getStores:()=>({data:j}),exec:I.exec,setNext:F=>(T.current=T.current.setNext(F),T.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:j.getFile.bind(j),serialize:j.serialize.bind(j),templates:{preview:k||(()=>null),icon:S==="simple"?(()=>null):S}}),[j,I]),B=d.useRef(0);return d.useEffect(()=>{if(!B.current)b&&b(_);else{const F=j.getState();j.init({data:r,mode:o,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}B.current++},[j,r,o,l,u,f,h,b,_]),B.current===0&&j.init({data:r,mode:o,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({..._}),[_]),i.jsx(Oa.Provider,{value:_,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(Gj,{children:i.jsx(sE,{readonly:g,menuOptions:y,extraInfo:w})})})})});function cE({fonts:t=!0,children:n}){return n?i.jsx(Lw,{fonts:t,children:n}):i.jsx(Lw,{fonts:t})}Bv(cs);function Zv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function cm(t,n,r){const o=Zv(t,r);if(!Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return o[n]}function uE(t,n,r){const o=Zv(t,r);if(!o[n]||typeof o[n]!="object"||Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return o[n]}async function dE(t,n=!1){return cm(await rt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Eg(t,n){const r=await rt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:uE(r,"folder","filesystem entries"),entries:cm(r,"entries","filesystem entries")}}async function fE(t,n){return rt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function mE(t,n,r,o){return rt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},o)}async function pE(t,n=!1){const r=await rt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:cm(r,"jobs","file transfer jobs")}}async function hE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function gE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function Yw(t){return cm(await rt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function vE(t,n){return rt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function yE(t,n,r){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function bE(t,n){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function wE(t,n,r,o){const l=await rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},o),u=Zv(l,"shared folder sync");return{ok:u.ok===!0,jobs:cm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function xE(t){return{id:String(t.id),parentId:t.parent,name:t.name,type:t.type==="file"?"file":"folder",size:Number(t.size||0),modifiedAt:t.date?.toISOString()||null,displayPath:String(t.displayPath||t.name),hasChildren:t.lazy===!0||!!t.data?.length,locked:t.locked===!0}}function Xw(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Fp(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function SE(t){const n=t.filter(r=>Fp(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function CE(t){const n=String(t.displayPath||"").trim();if(n)return n;const r=String(t.name||"").match(/\(([A-Za-z]:)\)/)?.[1];return r?`${r}\\`:t.name}function kE({hubUrl:t,roots:n,loading:r,error:o,onRefreshRoots:l,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),S=d.useRef("/"),k=d.useRef(0),N=d.useRef([]),A=d.useRef(new Map),[j,I]=d.useState(null),[T,_]=d.useState([]),[B,F]=d.useState([]),[H,D]=d.useState(0),[K,z]=d.useState(null),[W,q]=d.useState(!1),[V,X]=d.useState(""),[ve,J]=d.useState(new Set),$=n.find(me=>me.id===j)||null,P=T[T.length-1]||null,se=$?P?.svarPath||`/${$.name}`:null,we=se;d.useEffect(()=>{N.current=T,S.current=we||"/"},[we,T]);const Z=d.useMemo(()=>(A.current.clear(),!$||!we||T.length===0?[]:(T.forEach(me=>A.current.set(me.svarPath,me.hubId)),[...T.map((me,ke)=>({id:me.svarPath,parent:ke===0?"/":T[ke-1].svarPath,type:"folder",name:me.name,date:me.modifiedAt?new Date(me.modifiedAt):void 0,lazy:!1})),...B.map(me=>{const ke=`${we}/${me.name}`;return A.current.set(ke,me.id),{id:ke,parent:we,name:me.name,type:me.type==="file"?"file":"folder",...me.type==="file"?{size:me.size}:{},date:me.modifiedAt?new Date(me.modifiedAt):void 0,lazy:me.type!=="file"&&me.hasChildren===!0,displayPath:me.displayPath,locked:me.locked,driveType:me.driveType,totalBytes:me.totalBytes,freeBytes:me.freeBytes}})])),[$,B,we,T]),Se=me=>A.current.get(String(me))||String(me),ae=me=>xE({...me,id:Se(String(me.id)),parent:Se(String(me.parent))}),ye=async(me,ke)=>{const et=me[me.length-1];if(!et)return;const Me=++k.current;q(!0),X("");try{const pe=await Eg(et.hubId,t);if(Me!==k.current)return;if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe={...et,displayPath:pe.folder.displayPath||et.displayPath,modifiedAt:pe.folder.modifiedAt||et.modifiedAt},Re=[...me.slice(0,-1),qe];N.current=Re,_(Re),F(pe.entries),D(st=>st+1)}catch(pe){if(Me!==k.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:et.hubId,error:pe}),X(pe instanceof Error?`${ke}: ${pe.message}`:`${ke}: Unable to read this folder.`)}finally{Me===k.current&&q(!1)}},Pe=async me=>{const ke={svarPath:`/${me.name}`,hubId:me.id,name:me.name,pathLabel:CE(me),displayPath:me.displayPath,modifiedAt:me.modifiedAt},et=++k.current;I(me.id),N.current=[ke],_([ke]),S.current=ke.svarPath,F([]),X(""),q(!0),z(me.id),J(Me=>{const pe=new Set(Me);return pe.delete(me.id),pe});try{const Me=await Eg(me.id,t);if(et!==k.current)return;if(!Array.isArray(Me.entries))throw new Error("Invalid Hub filesystem entries response.");const pe={...ke,pathLabel:Me.folder.displayPath||ke.pathLabel,displayPath:Me.folder.displayPath||ke.displayPath,modifiedAt:Me.folder.modifiedAt||ke.modifiedAt};N.current=[pe],_([pe]),F(Me.entries),D(qe=>qe+1)}catch(Me){if(et!==k.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:me.id,error:Me}),J(pe=>new Set(pe).add(me.id)),X(Me instanceof Error?`${me.name}: ${Me.message}`:`${me.name}: Unable to read this drive.`),w(Me instanceof Error?`${me.name}: ${Me.message}`:`${me.name}: Unable to read this drive.`)}finally{et===k.current&&(z(null),q(!1))}},de=me=>{const ke=N.current;me<0||me>=ke.length||me===ke.length-1||ye(ke.slice(0,me+1),ke[me].name)},Qe=(me,ke)=>{if(me.type!=="folder")return;const et=N.current,Me=et.findIndex(qe=>qe.svarPath===ke);if(Me<0)return;const pe={svarPath:`${ke}/${me.name}`,hubId:me.id,name:me.name,pathLabel:me.name,displayPath:me.displayPath,modifiedAt:me.modifiedAt};ye([...et.slice(0,Me+1),pe],me.name)},ue=()=>de(N.current.length-2),_e=me=>{if(me.key!=="Enter"&&me.code!=="Enter"&&me.code!=="NumpadEnter"||me.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const et=b.current;if(!et)return;const Me=et.getState().panels?.flatMap(qe=>qe.selected||[])||[];if(Me.length!==1)return;const pe=et.getFile(String(Me[0]));pe?.type==="folder"&&(me.preventDefault(),me.stopPropagation(),Qe(ae(pe),String(pe.parent||S.current)))};d.useEffect(()=>{const me=n.find(ke=>ke.id===j)||SE(n);if(J(ke=>new Set([...ke].filter(et=>n.some(Me=>Me.id===et)))),!me){I(null),N.current=[],_([]),F([]);return}Pe(me)},[n]);const Ze=me=>{b.current=me,me.on("request-data",async({id:ke})=>{const et=String(ke),Me=Se(et);try{const pe=await Eg(Me,t);if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe=pe.entries.map(Re=>{const st=`${et}/${Re.name}`;return A.current.set(st,Re.id),{id:st,parent:et,name:Re.name,type:Re.type==="file"?"file":"folder",...Re.type==="file"?{size:Re.size}:{},date:Re.modifiedAt?new Date(Re.modifiedAt):void 0,lazy:Re.type!=="file"&&Re.hasChildren===!0,displayPath:Re.displayPath,locked:Re.locked,driveType:Re.driveType,totalBytes:Re.totalBytes,freeBytes:Re.freeBytes}});await me.exec("provide-data",{id:et,data:qe})}catch(pe){console.error("[LiveDesk FS] nested getEntries failed",{id:Me,error:pe}),w(pe instanceof Error?pe.message:"Unable to read this folder.")}}),me.intercept("set-path",({id:ke})=>{const et=String(ke),Me=N.current.findIndex(qe=>qe.svarPath===et);if(Me>=0)return de(Me),!1;const pe=me.getFile(et);if(pe?.type==="folder")return Qe(ae(pe),String(pe.parent||S.current)),!1}),me.intercept("open-file",()=>!1),me.on("select-file",()=>{window.setTimeout(()=>{const Me=(me.getState().panels?.flatMap(pe=>pe.selected||[])||[]).map(pe=>me.getFile(pe)).filter(Boolean).map(pe=>ae(pe));h(Me.map(pe=>pe.id),Me)},0)})},at=(me,ke)=>{const et=ke?ae(ke):null,Me=()=>{const pe=et?.type==="file"?String(ke?.parent||S.current):String(ke?.id||S.current);b.current?.exec("request-data",{id:pe})};return me==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:me==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(qe=>qe.selected||[])||[]).forEach(qe=>{const Re=b.current?.getFile(qe);Re&&g(ae(Re))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me}]:et?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(et)},...et.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(et)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Dp(et.displayPath||et.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${et.name}
|
|
179
|
-
${et.displayPath||""}`)}]:[]},Ee=async()=>{try{await l()}catch(me){w(me instanceof Error?me.message:"Unable to refresh Hub drives.")}},Ge=[{id:"local",label:"Local drives",icon:nu,roots:n.filter(me=>Fp(me)==="local")},{id:"removable",label:"Removable drives",icon:bk,roots:n.filter(me=>Fp(me)==="removable")},{id:"network",label:"Network drives",icon:kv,roots:n.filter(me=>Fp(me)==="network")}];return i.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[i.jsxs("div",{className:"hub-file-explorer-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub file explorer"}),i.jsxs("strong",{children:[i.jsx(nu,{size:16})," Browse files on this Hub"]})]}),i.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[i.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:i.jsx(Qx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:i.jsx(wk,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ee()},title:"Refresh drives",type:"button",children:i.jsx(ou,{size:16})})]})]}),r?i.jsxs("div",{className:"hub-file-explorer-state",children:[i.jsx(nu,{size:24}),i.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):o?i.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[i.jsx(nl,{size:24}),i.jsx("strong",{children:o})]}):i.jsxs("div",{className:"hub-file-explorer-content",children:[i.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[i.jsxs("div",{className:"hub-drive-sidebar-title",children:[i.jsx(nu,{size:15}),i.jsx("strong",{children:"This PC"})]}),Ge.map(me=>me.roots.length>0&&i.jsxs("section",{className:"hub-drive-group",children:[i.jsxs("h3",{children:[i.jsx(me.icon,{size:13}),me.label]}),i.jsx("div",{className:"hub-drive-list",children:me.roots.map(ke=>{const et=me.icon,Me=ve.has(ke.id)||ke.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${j===ke.id?"active":""} ${Me?"unavailable":""}`,onClick:()=>{Pe(ke)},"aria-pressed":j===ke.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(et,{size:16})}),i.jsxs("span",{className:"hub-drive-item-copy",children:[i.jsx("strong",{children:ke.name}),i.jsx("small",{children:ke.displayPath||ke.name}),i.jsxs("em",{children:[Xw(ke.freeBytes||0)," free / ",Xw(ke.totalBytes||0)]})]}),K===ke.id?i.jsx($r,{className:"hub-drive-item-status spin",size:15}):Me?i.jsx(wb,{className:"hub-drive-item-status",size:15}):null]},ke.id)})})]},me.id)),n.length===0&&i.jsxs("div",{className:"hub-drive-sidebar-empty",children:[i.jsx(nl,{size:17}),i.jsx("span",{children:"No drives available."})]})]}),i.jsxs("div",{className:"hub-file-explorer-browser",children:[i.jsxs("div",{className:"hub-file-explorer-navigation",children:[i.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((me,ke)=>i.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ke>0&&i.jsx(Mv,{size:13,"aria-hidden":"true"}),i.jsx("button",{className:`hub-file-explorer-breadcrumb ${ke===T.length-1?"current":""}`,onClick:()=>de(ke),title:me.displayPath||me.pathLabel,"data-hub-folder-id":me.hubId,"aria-current":ke===T.length-1?"location":void 0,type:"button",children:me.pathLabel})]},me.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[W&&i.jsx($r,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:ue,disabled:T.length<=1||W,title:"Back to parent folder",type:"button",children:i.jsx($x,{size:16})})]})]}),V&&i.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[i.jsx(wb,{size:15}),i.jsx("span",{children:V})]}),i.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:i.jsx(cE,{fonts:!1,children:i.jsx(lE,{data:Z,panels:se?[{path:se,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Ze,icons:"simple",menuOptions:at},`${$?.id||"no-root"}:${H}`)})})]})]})]})}class ME extends d.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[LiveDesk] Share Files runtime error",n,r.componentStack)}render(){return this.state.error?i.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[i.jsx(th,{size:24}),i.jsx("strong",{children:"Share Files could not be opened."}),i.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),i.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[i.jsx(ou,{size:15})," Retry"]})]}):this.props.children}}function AE(t){return t.deviceName||t.hostname||t.deviceId}function NE({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:l}){const u=new Set(r);return i.jsxs("section",{className:"distribution-targets",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),i.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(nm,{size:14})," All connected"]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(Ar,{size:14})," Selected"]})]})]}),i.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?i.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return i.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[i.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>l(f.deviceId)}),i.jsx(Ar,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:AE(f)}),i.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),i.jsx(_a,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function TE(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function RE({folders:t,loading:n,busy:r,canSync:o,onSyncAll:l,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return i.jsxs("section",{className:"file-share-sync-panel",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub folders"}),i.jsx("strong",{children:"Continuous sync"})]}),i.jsxs("button",{className:"text-button compact",onClick:l,disabled:r||!o||t.length===0,type:"button",children:[i.jsx(Kf,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?i.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?i.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[i.jsx(Kf,{size:28}),i.jsx("strong",{children:"Add a selected Hub folder"}),i.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):i.jsx("div",{className:"file-share-sync-list",children:t.map(y=>i.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[i.jsx("div",{className:"file-share-sync-icon",children:i.jsx(Kf,{size:19})}),i.jsxs("div",{className:"file-share-sync-info",children:[i.jsx("strong",{children:y.name}),i.jsx("span",{children:y.displayPath}),i.jsxs("small",{children:[y.fileCount," files / ",TE(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${u0(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),i.jsxs("label",{className:"file-share-auto-sync",children:[i.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),i.jsx("span",{children:"Auto"})]}),i.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!o||y.status==="syncing",type:"button",children:[i.jsx(ou,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(Yx,{size:15})})]},y.id))})]})}function jE(t){const r=(t.targetMode==="all"?t.devices.map(o=>o.deviceId):t.selectedTargetIds).length>0;return i.jsxs("aside",{className:"file-share-distribution-panel",children:[i.jsxs("div",{className:"file-share-distribution-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Distribution"}),i.jsx("strong",{children:"Hub → Clients"})]}),i.jsx(tm,{size:18})]}),i.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[i.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),i.jsx("button",{className:t.tab==="sync"?"active":"",onClick:()=>t.onTabChange("sync"),role:"tab","aria-selected":t.tab==="sync",type:"button",children:"Sync"})]}),t.tab==="send"?i.jsxs(i.Fragment,{children:[i.jsx(NE,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),i.jsxs("label",{className:"file-share-destination",children:[i.jsx("span",{children:"Destination folder"}),i.jsxs("div",{children:[i.jsx(Ad,{size:15}),i.jsx("input",{value:t.remoteDirectory,onChange:o=>t.onRemoteDirectoryChange(o.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),i.jsxs("div",{className:"file-share-selection-summary",children:[i.jsx("span",{children:"Selected"}),i.jsx("strong",{children:t.selectedSummary})]}),i.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[i.jsx(tm,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[i.jsx(Ad,{size:16})," Add selected folder to Sync"]})]}):i.jsx(RE,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:r,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function EE(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Zw(t){if(t.state==="completed")return 100;const n=t.totalBytes>0?Math.round(t.sentBytes/t.totalBytes*100):t.totalFiles>0?Math.round(t.completedFiles/t.totalFiles*100):0;return Math.max(0,Math.min(wv(t.state)?100:99,n))}function Jw(t){return t.state==="scanning"?"Scanning selected Hub items":t.state==="queued"?"Preparing transfer":t.state==="sending"?`${t.completedFiles}/${t.totalFiles} · ${t.currentPath||"sending"}`:t.state==="completed"?`Sent ${t.totalFiles} file${t.totalFiles===1?"":"s"} to ${t.targetCount} Client${t.targetCount===1?"":"s"}`:t.state==="partially-failed"?`${t.failedTargets.length} Client${t.failedTargets.length===1?"":"s"} failed`:t.state==="cancelled"?"Transfer cancelled":t.error||"Transfer failed"}function wv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function DE({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:o,remoteDirectory:l,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:S,onBrowserFolderImport:k,onNotice:N,onTransferChange:A}){const j=Array.isArray(n)?n:[],[I,T]=d.useState([]),[_,B]=d.useState(!0),[F,H]=d.useState(""),[D,K]=d.useState([]),[z,W]=d.useState([]),[q,V]=d.useState(null),[X,ve]=d.useState(!1),[J,$]=d.useState([]),[P,se]=d.useState(!0),[we,Z]=d.useState(!1),[Se,ae]=d.useState("send"),[ye,Pe]=d.useState([]),de=d.useRef(new Set),Qe=d.useRef(!1),ue=d.useMemo(()=>f==="all"?j.map(O=>O.deviceId):h.filter(O=>j.some(ze=>ze.deviceId===O)),[j,h,f]),_e=ye.find(O=>!wv(O.state)),Ze=z.length===1&&z[0].type==="folder"?z[0]:null,at=z.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":q?`${q.files} files, ${q.folders} folders · ${EE(q.totalBytes)}`:`${z.length} item${z.length===1?"":"s"} selected`,Ee=O=>{A({id:O.jobId,state:O.state,progress:Zw(O),message:Jw(O)})},Ge=d.useCallback(async()=>{const O=await dE(t,!0);return T(O),H(""),O},[t]),me=async()=>{if(!Qe.current){Qe.current=!0;try{const ze=(await pE(t,!0)).jobs||[],We=await Promise.all([...de.current].map(async ht=>{try{return await hE(ht,t)}catch{return null}})),Et=[...ze,...We.filter(Boolean)],lt=[...new Map(Et.map(ht=>[ht.jobId,ht])).values()];Pe(lt),lt.forEach(Ee),lt.filter(ht=>wv(ht.state)).forEach(ht=>de.current.delete(ht.jobId))}catch{}finally{Qe.current=!1}}};d.useEffect(()=>{let O=!0;B(!0),H(""),Promise.all([Ge(),Yw(t).then(We=>{O&&$(We)})]).catch(We=>{O&&(H(We instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),N(We instanceof Error?We.message:"Hub file system is unavailable."))}).finally(()=>{O&&(B(!1),se(!1))}),me();const ze=window.setInterval(()=>{me()},800);return()=>{O=!1,window.clearInterval(ze)}},[t,Ge]),d.useEffect(()=>{if(D.length===0){V(null);return}let O=!1;return ve(!0),fE(D,t).then(ze=>{O||V(ze)}).catch(ze=>{O||N(ze instanceof Error?ze.message:"Unable to calculate selected size.")}).finally(()=>{O||ve(!1)}),()=>{O=!0}},[t,D.join("|")]);const ke=(O,ze)=>{K(O),W(ze)},et=O=>{O.forEach(ze=>de.current.add(ze.jobId)),Pe(ze=>[...new Map([...ze,...O].map(We=>[We.jobId,We])).values()]),O.forEach(Ee)},Me=async()=>{if(!r){N(o);return}if(D.length===0){N("Select files or folders from the Hub explorer.");return}if(ue.length===0){N("Choose at least one connected Client.");return}if(_e){N("A Hub transfer is already running.");return}try{const O=await mE(D,ue,l.trim(),t);de.current.add(O.jobId),N("Hub transfer queued."),await me()}catch(O){N(O instanceof Error?O.message:"Unable to start Hub transfer.")}},pe=async O=>{const ze=O||Ze;if(!ze||ze.type!=="folder"){N("Select one folder to add it to Sync.");return}try{const We=await vE(ze.id,t);$(Et=>[...Et.filter(lt=>lt.id!==We.folder.id),We.folder]),ae("sync"),N(`${ze.name} is ready for Hub sync.`)}catch(We){N(We instanceof Error?We.message:"Unable to add the Hub folder to Sync.")}},qe=async O=>{if(ue.length===0){N("Choose at least one connected Client.");return}Z(!0),$(ze=>ze.map(We=>We.id===O.id?{...We,status:"syncing"}:We));try{const ze=await wE(O.id,ue,l.trim(),t);et(ze.jobs||[]),N(ze.jobs?.length?"Hub sync queued.":"No changed files to sync.");const We=await Yw(t);$(We)}catch(ze){N(ze instanceof Error?ze.message:"Unable to sync the Hub folder."),$(We=>We.map(Et=>Et.id===O.id?{...Et,status:"error",message:"Sync failed"}:Et))}finally{Z(!1)}},Re=async()=>{Z(!0);try{for(const O of J)await qe(O)}finally{Z(!1)}},st=async O=>{try{const ze=await yE(O.id,{autoSync:!O.autoSync},t);$(We=>We.map(Et=>Et.id===O.id?ze.folder:Et))}catch(ze){N(ze instanceof Error?ze.message:"Unable to update auto sync.")}},jt=async O=>{try{await bE(O.id,t),$(ze=>ze.filter(We=>We.id!==O.id))}catch(ze){N(ze instanceof Error?ze.message:"Unable to remove the sync folder.")}};return i.jsxs("section",{className:"livedesk-file-explorer",children:[i.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:O=>{O.currentTarget.files&&S(O.currentTarget.files),O.currentTarget.value=""}}),i.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:O=>{O.currentTarget.files&&k(O.currentTarget.files),O.currentTarget.value=""}}),i.jsx("div",{className:"file-share-workspace",children:i.jsxs(ME,{onRetry:()=>window.location.reload(),children:[i.jsx(kE,{hubUrl:t,roots:I,loading:_,error:F,onRefreshRoots:Ge,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ke,onShareItem:O=>{K([O.id]),W([O]),ae("send")},onAddSyncFolder:O=>{K([O.id]),W([O]),pe(O)},onNotice:N}),i.jsx(jE,{devices:j,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:z,selectedSummary:at,canShare:r&&!_e&&D.length>0&&ue.length>0&&!X,onShare:()=>{Me()},canAddSync:!!Ze,onAddSync:()=>{pe()},tab:Se,onTabChange:ae,folders:J,foldersLoading:P,syncBusy:we,onSyncAll:()=>{Re()},onSync:O=>{qe(O)},onToggleAuto:O=>{st(O)},onRemove:O=>{jt(O)},onAddFolder:()=>{pe()}})]})}),_e&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Jw(_e)," · ",Zw(_e),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{gE(_e.jobId,t).then(O=>{Pe(ze=>ze.map(We=>We.jobId===O.jobId?O:We)),Ee(O)})},title:"Cancel transfer",type:"button",children:i.jsx(rr,{size:14})})]})})]})}const IE=d.forwardRef(function({value:n,onChange:r,onSubmit:o,onOpenSuggestedTasks:l,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return i.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),o()},children:[i.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":f===void 0?"Open Suggested tasks":`Open Suggested tasks (${f} available)`,"aria-expanded":u,onClick:l,disabled:h,children:i.jsx(xk,{size:17})}),i.jsx("textarea",{ref:w,value:n,onChange:b=>r(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),i.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?i.jsx($r,{className:"spin",size:16}):i.jsx(tm,{size:16}),h?"Running":"Run"]})]})}),LE=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Xp(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function Zp(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function PE(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function _E(t){switch(t){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 FE(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function os(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function xp(t){const n=os(t);return n===null?"":n<1024**2?`${Math.round(n/1024)}K`:n<1024**3?`${(n/1024**2).toFixed(0)}M`:`${(n/1024**3).toFixed(1)}G`}function ex(t){const n=os(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function OE(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Jp(t,n){if(n.error)return n.error;const r=FE(n.data),o=OE(n.result||"");if(!r)return o||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=ex(r.cpuUsageRatio),f=os(r.cores),h=xp(r.freeMemoryBytes),g=xp(r.totalMemoryBytes),y=os(r.totalMemoryBytes)&&os(r.freeMemoryBytes)!==null?`${Math.round(os(r.freeMemoryBytes)/os(r.totalMemoryBytes)*100)}% RAM free`:"";return[l,u&&`CPU ${u}`,f!==null&&`${Math.round(f)} cores`,h&&g?`RAM ${h}/${g}`:"",y,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||o||n.status}if(t==="disk.status"){const l=typeof r.root=="string"?r.root:"",u=xp(r.freeBytes),f=os(r.totalBytes)&&os(r.freeBytes)!==null?`${Math.round(os(r.freeBytes)/os(r.totalBytes)*100)}% free`:"";return[l,u&&`${u} free`,f].filter(Boolean).join(" · ")||o||n.status}if(t==="gpu.status"){const l=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=ex(r.usageRatio),f=os(r.temperatureC)!==null?`${Math.round(os(r.temperatureC))}°C`:"",h=xp(r.freeMemoryBytes);return[l,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||o||n.status}if(t==="process.list"){const l=os(r.count);return l!==null?`${l} matching process${l===1?"":"es"}`:o||n.status}if(t==="network.status"){const l=Array.isArray(r.adapters)?r.adapters.length:null;return l!==null?`${l} active adapter${l===1?"":"s"}`:o||n.status}return o||n.stage||n.status}function tx(t,n){const r=Jp(t,n);return n.status==="failed"||n.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${n.result||""} ${r}`)}function BE({state:t,operation:n}){const r=t.status==="completed"?al:t.status==="failed"||t.status==="cancelled"?rr:t.status==="running"?$r:Xx,o=t.status==="running"?t.stage||"Working":t.status==="completed"?n?Jp(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return i.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[i.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:i.jsx(r,{size:15})}),i.jsx("strong",{children:t.deviceName}),i.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),i.jsx("small",{children:o})]})}function HE({operation:t,states:n,status:r,onCancel:o,onRetry:l,busy:u=!1}){const f=["running","queued"].includes(r),[h,g]=d.useState(!1),[y,w]=d.useState("all"),b=d.useMemo(()=>({total:n.length,completed:n.filter(_=>_.status==="completed").length,failed:n.filter(_=>_.status==="failed").length,running:n.filter(_=>_.status==="running").length,queued:n.filter(_=>_.status==="queued").length,cancelled:n.filter(_=>_.status==="cancelled").length}),[n]),S=n.filter(_=>tx(t,_)),k=S.filter(_=>_.status==="completed").length,N=b.failed>0,A=S.length>0,j=n.filter(_=>y==="issues"?tx(t,_):y==="running"?_.status==="running"||_.status==="queued":y==="completed"?_.status==="completed":y==="failed"?_.status==="failed":!0),I=A&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=n.filter(_=>_.status==="completed").map(_=>Jp(t,_)).filter(Boolean).filter((_,B,F)=>F.indexOf(_)===B).slice(0,2);return i.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[i.jsxs("div",{className:"agent-task-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"LiveDesk Agent"}),i.jsx("strong",{children:_E(t)})]}),i.jsx("span",{className:`agent-task-status status-${A?"completed-with-failures":r}`,children:I})]}),i.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[i.jsxs("strong",{children:[b.total," targets"]}),i.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&i.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&i.jsxs("span",{children:[b.queued," queued"]}),N&&i.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),k>0&&i.jsxs("span",{className:"summary-cancelled",children:[k," warning"]}),b.cancelled>0&&i.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[i.jsx("span",{children:"Result"}),T.join(" · ")]}),i.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((_,B)=>{const F=_.status==="completed"?"✓":_.status==="failed"?"×":_.status==="cancelled"?"!":_.status==="running"?"…":"·";return i.jsxs("span",{className:`agent-target-chip status-${_.status}`,title:`${_.deviceName}: ${Jp(t,_)}`,"aria-label":`${B+1}. ${_.deviceName}: ${_.status}`,children:[i.jsx("b",{children:String(B+1).padStart(2,"0")}),i.jsx("span",{children:F})]},_.deviceId)})}),n.length>0&&i.jsx("div",{className:"agent-task-details-toggle",children:i.jsxs("button",{type:"button",onClick:()=>g(_=>!_),"aria-expanded":h,children:[h?i.jsx(Sk,{size:14}):i.jsx(Zx,{size:14}),h?"Hide details":"Show details"]})}),h&&i.jsxs("div",{className:"agent-task-details",children:[i.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(_=>i.jsx("button",{className:y===_?"active":"",onClick:()=>w(_),role:"tab","aria-selected":y===_,type:"button",children:_==="all"?"All":_==="issues"?"Issues only":_[0].toUpperCase()+_.slice(1)},_))}),i.jsx("div",{className:"agent-task-rows",children:j.length>0?j.map(_=>i.jsx(BE,{operation:t,state:_},_.deviceId)):i.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||N)&&i.jsxs("div",{className:"agent-task-actions",children:[f&&o&&i.jsxs("button",{onClick:o,disabled:u,type:"button",children:[i.jsx(Ck,{size:14})," Cancel"]}),!f&&N&&l&&i.jsxs("button",{onClick:l,disabled:u,type:"button",children:[i.jsx(Vg,{size:14})," Retry failed"]})]})]})}function zE(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function $E({approval:t,busy:n=!1,onApprove:r,onReject:o}){return i.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[i.jsxs("div",{className:"agent-approval-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Approval required"}),i.jsx("strong",{children:t.toolName})]}),i.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),i.jsx("p",{children:t.description}),i.jsx("pre",{children:zE(t.arguments)}),i.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),i.jsxs("div",{className:"agent-approval-actions",children:[i.jsxs("button",{className:"reject",disabled:n,onClick:o,type:"button",children:[i.jsx(rr,{size:14})," Reject"]}),i.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[i.jsx(al,{size:14})," Once"]}),i.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),i.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),i.jsxs("div",{className:"agent-approval-scope",children:[i.jsx(th,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function UE(t){return t==="queued"?"Request queued":t==="checking-codex"?"Checking Codex":t==="preparing-tools"?"Preparing tools":t==="thinking"?"Preparing answer":t==="tool-running"?"Working on computers":t==="recovering"?"Retrying safely":t==="waiting-approval"?"Waiting for approval":"Working"}function qE({items:t,onCancel:n,onRetry:r,busyBatchId:o,approvals:l,onApprove:u,onReject:f,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),S=d.useRef(!0),k=d.useRef(""),N=t[t.length-1];return d.useLayoutEffect(()=>{const A=b.current;A&&(N?.type==="user"&&N.id!==k.current&&(S.current=!0),k.current=N?.id||"",S.current&&(A.scrollTop=A.scrollHeight))},[l,t,N?.id,N?.type,g?.message,g?.stage]),i.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:A=>{const j=A.currentTarget;S.current=j.scrollHeight-j.scrollTop-j.clientHeight<72},children:[l.filter(A=>A.status==="pending").map(A=>i.jsx($E,{approval:A,busy:h===A.approvalId,onApprove:j=>u(A,j),onReject:()=>f(A)},A.approvalId)),t.length===0&&i.jsxs("div",{className:"agents-empty-conversation",children:[i.jsx("strong",{children:y}),i.jsx("span",{children:w})]}),t.map(A=>{if(A.type==="task"){const j=A;return i.jsx(HE,{operation:j.operation,states:j.states,status:j.status,onCancel:()=>n(j.batchId,j.agentRunId),onRetry:()=>r(j.batchId),busy:o===j.batchId},j.id)}return i.jsxs("article",{className:`agents-message ${A.type}`,children:[i.jsx("span",{children:A.type==="user"?"You":"LiveDesk Agent"}),i.jsx("p",{children:A.text})]},A.id)}),g&&i.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[i.jsxs("span",{children:[i.jsx($r,{"aria-hidden":"true",size:15}),UE(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const nx=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],ca=["windows","macos","linux"],Xl={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:ca},"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:ca},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ca},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ca},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:ca},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:ca},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ca},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:ca},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:ca},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:ca},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:ca},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:ca},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:ca},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca}};new Set(Object.keys(Xl));const WE={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"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","문제해결","복구","장애"]},ax=["low","medium","high","critical"];function GE(t){return t.reduce((n,r)=>{const o=Xl[r].risk;return ax.indexOf(o)>ax.indexOf(n)?o:n},"low")}function VE(t){return ca.filter(n=>t.every(r=>Xl[r].supportedPlatforms.includes(n)))}function ct(t,n,r,o,l,u,f={}){const h=f.description||o,g=l.flatMap(w=>w.split(".")),y=[...new Set([...WE[n],...u,...g])];return{id:t,category:n,title:r,prompt:o,description:h,requiredOperations:l,risk:f.risk||GE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||VE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const LS=[ct("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),ct("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}),ct("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}),ct("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}),ct("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}),ct("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),ct("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),ct("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}),ct("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","높은 사용량"]),ct("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ct("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ct("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"]),ct("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","디스크"]),ct("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ct("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","경고"]),ct("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"]),ct("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","실행 중"]),ct("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"]),ct("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),ct("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"}),ct("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),ct("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),ct("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","서비스 상태"]),ct("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"}),ct("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),ct("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),ct("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"]),ct("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"}),ct("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"}),ct("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),ct("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),ct("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),ct("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),ct("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),ct("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),ct("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),ct("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),ct("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),ct("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"]),ct("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),ct("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ct("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ct("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ct("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"]),ct("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"]),ct("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"]),ct("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ct("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"]),ct("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),ct("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),ct("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),ct("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),ct("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),ct("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),ct("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),ct("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),ct("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","장애 보고서"])],Dg={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 KE(t,n){return t==="safe-auto"?Dg:t==="full-access"?{...Dg,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...Dg,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function QE(t,n,r){const o=KE(n,r),l=t.requiredOperations.map(u=>o[Xl[u].permissionCategory]);if(l.includes("deny")){const u=t.requiredOperations.find(f=>o[Xl[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Xl[u].label}, which is blocked by the current permission policy.`}}return l.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>Xl[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function YE(t){const n=String(t||"").trim().toLowerCase();return n==="windows"||n==="win32"||n==="win32nt"?"windows":n==="macos"||n==="macosx"||n==="darwin"||n==="osx"?"macos":n==="linux"?"linux":null}function XE(t,n,r){const o=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||o.has(l.deviceId)))}function ZE(t,n){const r=YE(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const o=t.capabilities?.agentTools;return!Array.isArray(o)||o.length===0?n.requiredOperations.every(l=>Xl[l].readOnly):n.requiredOperations.every(l=>o.includes(l))}function PS(t,n,r,o,l,u){const f=QE(t,l,u),h=XE(n,r,o),g=h.map(k=>k.deviceId),y={...f,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:t.risk,supportedPlatforms:t.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(t.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(f.state==="blocked")return y;const w=h.filter(k=>ZE(k,t)),b=w.map(k=>k.deviceId),S=g.filter(k=>!b.includes(k));return w.length===0?{...y,unsupportedDeviceIds:S,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:S}}function JE(t,n,r,o,l,u){return t.filter(f=>f.enabled&&PS(f,n,r,o,l,u).available).length}const Ig="livedesk.agentPromptRecent",Lg="livedesk.agentPromptFavorites",eD={Recommended:ec,"Health & capacity":Jl,"Processes & services":Nk,"Files & configuration":Ak,"Software & automation":Kx,"Network & connectivity":kv,"Power & maintenance":ga,"Troubleshooting & recovery":Mk};function rx(t){if(typeof window>"u")return[];try{const n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function Sp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function Pg(t){return t==="all"?"All tasks":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto allowed":t==="approval"?"Approval required":t==="full-access"?"Full Access":t==="available"?"Available":t==="unavailable"?"Unavailable":t}function tD(t){return t==="all"?"All":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto":t==="approval"?"Approval":t==="full-access"?"Full access":t==="available"?"Available":t==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function nD(t,n,r){if(!r.trim())return!0;const o=r.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,n.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(o)}function aD(t){return`permission-${t}`}function rD(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function sD(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function iD({devices:t,targetMode:n,selectedIds:r,permissionMode:o,customCategories:l,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,S]=d.useState(()=>rx(Ig)),[k,N]=d.useState(()=>rx(Lg)),[A,j]=d.useState(0),[I,T]=d.useState(""),_=d.useRef(null),B=d.useRef(null),F=d.useMemo(()=>LS.filter(J=>J.enabled),[]),H=d.useMemo(()=>new Map(F.map(J=>[J.id,PS(J,t,n,r,o,l)])),[l,t,o,r,n,F]),D=d.useMemo(()=>[...H.values()].filter(J=>J.available).length,[H]),K=d.useMemo(()=>t.filter(J=>J.connected&&(n==="all"||n==="auto"||r.includes(J.deviceId))).length,[t,r,n]),z=d.useMemo(()=>{const J=F.filter($=>nD($,H.get($.id),h));return y==="recent"?b.map($=>J.find(P=>P.id===$)).filter($=>!!$):y==="favorites"?k.map($=>J.find(P=>P.id===$)).filter($=>!!$):y==="all"?J:J.filter($=>{const P=H.get($.id);return y==="read-only"?P.state==="read-only":y==="auto"?P.state==="auto":y==="approval"?P.state==="approval":y==="full-access"?P.state==="full-access":y==="available"?P.available:y==="unavailable"?!P.available:$.category===y})},[H,k,y,b,h,F]),W=d.useMemo(()=>y!=="all"?[{category:Pg(y),templates:z}]:nx.map(J=>({category:J,templates:z.filter($=>$.category===J)})).filter(J=>J.templates.length>0),[y,z]);d.useEffect(()=>{j(J=>Math.min(J,Math.max(0,z.length-1)))},[z.length]),d.useEffect(()=>{Sp(Ig,b)},[b]),d.useEffect(()=>{Sp(Lg,k)},[k]),d.useEffect(()=>{B.current?.focus();const J=P=>{P.target instanceof Node&&!_.current?.contains(P.target)&&f()},$=P=>{P.key==="Escape"&&(P.preventDefault(),f())};return document.addEventListener("pointerdown",J),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",J),document.removeEventListener("keydown",$)}},[f]);const q=J=>{const $=H.get(J.id);if(!$.available){T($.reason||"This task is not available for the current targets and permission policy.");return}const P=[J.id,...b.filter(se=>se!==J.id)].slice(0,10);S(P),Sp(Ig,P),u(J.prompt),f()},V=J=>{N($=>{const P=$.includes(J)?$.filter(se=>se!==J):[J,...$];return Sp(Lg,P),P})},X=J=>{J.key==="ArrowDown"?(J.preventDefault(),j($=>Math.min($+1,Math.max(0,z.length-1)))):J.key==="ArrowUp"?(J.preventDefault(),j($=>Math.max($-1,0))):J.key==="Enter"&&z[A]&&(J.preventDefault(),q(z[A]))};let ve=-1;return i.jsxs("section",{className:"agents-suggested-tasks",ref:_,"aria-label":"Suggested tasks",children:[i.jsxs("header",{className:"agents-suggested-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"agents-suggested-title",children:[i.jsx(ec,{size:15})," Suggested tasks"]}),i.jsxs("small",{children:[D," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),i.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:i.jsx(rr,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(kk,{size:15,"aria-hidden":"true"}),i.jsx("input",{ref:B,value:h,onChange:J=>g(J.target.value),onKeyDown:X,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),i.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",...nx].map(J=>{const $=J==="recent"?Gx:J==="favorites"?Kg:J==="all"?ec:J==="available"?_a:J==="unavailable"?Jx:J==="read-only"||J==="auto"||J==="approval"||J==="full-access"?ga:eD[J];return i.jsxs("button",{className:y===J?"active":"",type:"button",title:Pg(J),"aria-label":Pg(J),"aria-pressed":y===J,onClick:()=>{w(J),j(0),T("")},children:[i.jsx($,{size:12})," ",tD(J)]},J)})}),I&&i.jsx("div",{className:"agents-suggested-notice",role:"status",children:I}),i.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[W.map(J=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:J.category}),J.templates.map($=>{ve+=1;const P=ve===A,se=k.includes($.id),we=H.get($.id),Z=we.availableDeviceIds.length+we.unsupportedDeviceIds.length||K,Se=we.available?`Available on ${we.availableDeviceIds.length} of ${Z} target${Z===1?"":"s"}`:`Unavailable: ${we.reason||"not supported by the current targets"}`;return i.jsxs("div",{className:`agents-suggested-item ${P?"active":""} ${we.available?"":"unavailable"}`,children:[i.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":P,"aria-disabled":!we.available,onClick:()=>q($),children:[i.jsx("span",{children:$.title}),i.jsx("small",{className:"agents-suggested-description",children:$.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:$.category}),i.jsx("em",{className:aD(we.state),children:we.label}),i.jsx("em",{className:`risk-${$.risk}`,children:rD($.risk)}),i.jsx("em",{children:$.supportedPlatforms.map(sD).join(" · ")}),i.jsx("em",{className:we.available?"availability-ok":"availability-unavailable",children:Se}),we.available&&we.unsupportedDeviceIds.length>0&&i.jsxs("em",{className:"availability-warning",children:["Unsupported on ",we.unsupportedDeviceIds.length]})]})]}),i.jsx("button",{className:`agents-suggested-favorite ${se?"favorite":""}`,type:"button","aria-label":se?`Remove ${$.title} from favorites`:`Add ${$.title} to favorites`,"aria-pressed":se,onClick:()=>V($.id),children:i.jsx(Kg,{size:14,fill:se?"currentColor":"none"})})]},$.id)})]},J.category)),z.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function oD({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:l,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(Zp),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return i.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[i.jsxs("div",{className:"agents-target-toolbar",children:[i.jsx("span",{className:"agents-section-label",children:"Targets"}),i.jsxs("div",{className:"agents-target-modes",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(nm,{size:14})," All connected ",i.jsx("small",{children:h.length})]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(al,{size:14})," Selected ",g]}),i.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>o("auto"),type:"button",children:[i.jsx(ec,{size:14})," Auto"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(nm,{size:14})," Group ",i.jsx("small",{children:"Soon"})]})]}),i.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[i.jsx(th,{size:14}),i.jsx("span",{children:"Permission"}),i.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[i.jsx("option",{value:"ask",children:"Ask"}),i.jsx("option",{value:"safe-auto",children:"Safe Auto"}),i.jsx("option",{value:"full-access",children:"Full Access"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(Zx,{size:13,"aria-hidden":"true"})]})]}),i.jsx("div",{className:"agents-target-list",children:t.length===0?i.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=Zp(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return i.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[i.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>l(y.deviceId)}),i.jsx("span",{className:"agents-target-icon",children:i.jsx(Ar,{size:15})}),i.jsxs("span",{children:[i.jsx("strong",{children:Xp(y)}),i.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&i.jsx(al,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const lD=800,sx=5e3;function cD(){return typeof document>"u"||document.visibilityState==="visible"}function uD(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function ix({poll:t,onResult:n,onError:r,intervalMs:o=lD,isVisible:l=cD,subscribeVisibility:u=uD,setTimeoutImpl:f=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:h=globalThis.clearTimeout.bind(globalThis),createAbortController:g=()=>new AbortController}){if(typeof t!="function")throw new TypeError("Agent polling requires a poll function.");const y={current:null};let w=!0,b=0,S=null,k=null;const N=()=>{S!==null&&(h(S),S=null)},A=()=>{!w||!l()||S!==null||y.current||(S=f(()=>{S=null,j()},o))},j=()=>{if(!w||!l()||y.current)return y.current;const B=++b,F=g();k=F;const H=Up(y,()=>t(F.signal));return H.then(D=>{w&&B===b&&!F.signal.aborted&&n?.(D)},D=>{w&&B===b&&!F.signal.aborted&&r?.(D)}).finally(()=>{k===F&&(k=null),w&&l()&&A()}).catch(()=>{}),H},I=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");N(),b+=1;const B=y.current;if(k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),B)try{await B}catch{}if(!(!w||!l()))return N(),j()},_=u(()=>{if(N(),!l()){b+=1,k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling paused while hidden."));return}j()});return j(),{refresh:I,stop(){w&&(w=!1,b+=1,N(),_?.(),k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function dD(t,n){return rt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function fD(t,n,r={}){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function mD(t,n){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function pD(t){return rt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function hD(t,n,r,o){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:o})},t)}async function gD(t,n,r,o="User rejected this action."){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:o})},t)}async function vD(t,n,r){return rt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function yD(t,n,r={}){return rt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function bD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function wD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function Of(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function _g(t,n){const r=new Map(n.map(o=>[o.deviceId,Xp(o)]));return t.results.map(o=>({deviceId:o.deviceId,deviceName:o.deviceName||r.get(o.deviceId)||o.deviceId,status:PE(o.status),stage:o.stage||(o.status==="running"?"Checking processes":void 0),result:o.result,data:o.data,error:o.error,sequence:Number.isSafeInteger(o.sequence)?o.sequence:0}))}function xD(t,n){const r=new Map(n.map(o=>[o.deviceId,o]));return t.map(o=>{const l=r.get(o.deviceId);return!l||l.sequence<=o.sequence?o:l})}const SD={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 CD(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function kD(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function MD(t){const n=t instanceof Error?t.message:String(t);return/agent-disabled/i.test(n)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(n)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(n)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":n}function ox({hubUrl:t,devices:n,launchRequest:r,variant:o="page",selectedDeviceIds:l=[]}){const u=o==="dock",[f,h]=d.useState(u?l.length>0?"selected":"auto":"all"),[g,y]=d.useState(l),[w,b]=d.useState("auto"),[S,k]=d.useState(""),[N,A]=d.useState([]),[j,I]=d.useState(""),[T,_]=d.useState(""),[B,F]=d.useState(""),[H,D]=d.useState("safe-auto"),[K]=d.useState("custom-default"),[z,W]=d.useState(SD),[q,V]=d.useState([]),[X,ve]=d.useState(""),[J,$]=d.useState(!1),[P,se]=d.useState(null),[we,Z]=d.useState(!1),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(!1),[de,Qe]=d.useState(null),ue=d.useRef(null),_e=d.useRef(null),Ze=d.useRef(null),at=d.useRef(new Set),Ee=d.useRef(new Set),Ge=d.useMemo(()=>n.filter(Zp).map(fe=>fe.deviceId),[n]),me=d.useMemo(()=>JE(LS,n,f,g,H,z),[z,n,H,g,f]);d.useEffect(()=>{u&&y(l)},[u,l]),d.useEffect(()=>{r?.deviceId&&(h("selected"),y([r.deviceId]),k(r.instruction),Pe(!1),window.requestAnimationFrame(()=>{ue.current?.focus(),ue.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const ke=d.useCallback(fe=>{const te=_g(fe,n);A(ce=>ce.map(Ne=>Ne.type==="task"&&Ne.batchId===fe.batchId?{...Ne,states:xD(Ne.states,te),status:fe.status}:Ne)),["running","queued"].includes(fe.status)||I(ce=>ce===fe.batchId?"":ce)},[n]),et=d.useCallback((fe,te)=>{Ee.current.has(fe.batchId)||(Ee.current.add(fe.batchId),A(ce=>[...ce,{type:"task",id:Of("task"),batchId:fe.batchId,agentRunId:te,operation:fe.operation||"diagnostics.collect",instruction:fe.instructionPreview,states:_g(fe,n),status:fe.status}])),ke(fe)},[n,ke]),Me=d.useCallback((fe,te)=>{for(const Ne of te.taskBatches||[])et(Ne,fe);V(te.approvals||[]);const ce=["running","queued","waiting-approval"].includes(te.status);if(Qe(ce?{runId:fe,stage:te.stage||te.status,message:te.progressMessage||(te.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ne=>Ne?.runId===fe?null:Ne),!ce&&!at.current.has(fe)){at.current.add(fe);const Ne=[te.error,te.errorMessage].filter(Boolean).join(" — "),He=te.finalResponse?.trim()||(te.status==="cancelled"?"Codex 작업을 취소했습니다.":Ne?`Codex 작업이 완료되지 않았습니다: ${Ne}`:"Codex 작업이 완료되었습니다.");A(Ie=>[...Ie,{type:te.status==="failed"?"error":"agent",id:Of("agent-run-result"),text:He}])}},[et]),pe=d.useCallback(async fe=>{const te=_e.current;if(!(!te||te.id!==fe))try{return await te.owner.refresh()}catch(ce){if(_e.current!==te)return;throw ce}},[]);d.useEffect(()=>{if(!T){_e.current=null;return}const fe=T,te=ix({poll:Ne=>fD(t,fe,{signal:Ne,timeoutMs:sx}),onResult:Ne=>{Me(fe,Ne),["running","queued","waiting-approval"].includes(Ne.status)||(_(He=>He===fe?"":He),Z(!1))},onError:Ne=>{ae(Ne instanceof Error?Ne.message:String(Ne))}}),ce={id:fe,owner:te};return _e.current=ce,()=>{te.stop(),_e.current===ce&&(_e.current=null)}},[T,t,Me]),d.useEffect(()=>{if(!j){Ze.current=null;return}const fe=j,te=ix({poll:Ne=>yD(t,fe,{signal:Ne,timeoutMs:sx}),onResult:Ne=>{ke(Ne),["running","queued"].includes(Ne.status)||I(He=>He===fe?"":He)},onError:Ne=>{ae(Ne instanceof Error?Ne.message:String(Ne))}}),ce={id:fe,owner:te};return Ze.current=ce,()=>{te.stop(),Ze.current===ce&&(Ze.current=null)}},[j,t,ke]);const qe=async(fe="",te,ce=!1)=>{const Ne=(fe||S).trim();if(!Ne||j||T)return;const He=te||(f==="all"||f==="auto"?Ge:g.filter(ut=>Ge.includes(ut)));if(He.length===0){ae("Select at least one connected Client.");return}if(H==="full-access"&&!we&&!ce){se({instruction:Ne,targetIds:He});return}if(A(ut=>[...ut,{type:"user",id:Of("user"),text:Ne}]),k(""),Pe(!1),ae(""),He.length===0){A(ut=>[...ut,{type:"error",id:Of("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Lt=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
|
|
177
|
+
`):String(t||""),N=d.useMemo(()=>G1(t),[k]),A=d.useMemo(()=>N.find(T=>Yf(T)==="loopback")||N[0]||Un,[N]),j=d.useCallback(async T=>{if(!n){l(null),f([]),w(""),g("");return}let _=null;const B=Date.now(),F=N.filter(D=>(b.current.get(D)||0)<=B),H=z1({eligibleCandidates:F,fallbackHubBaseUrl:A,publicConsole:Av(),authenticated:!!r});if(H.candidates.length===0)throw new Error("No LiveDesk Hub endpoint is reachable. Retrying shortly.");for(const D of H.candidates)try{const[K,z]=await Promise.all([rt("/api/remote/status",{signal:T,timeoutMs:rw,transport:H.transport},D),rt("/api/remote/devices",{signal:T,timeoutMs:rw,transport:H.transport},D)]);if(T?.aborted)throw T.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray(z.devices))throw new Error("Invalid Hub devices response.");b.current.delete(D),l(K),f(z.devices),w(D),g("");return}catch(K){if(T?.aborted)throw K;_=K,H.transport==="auto"&&b.current.set(D,Date.now()+1e4)}throw w(""),_||new Error("No LiveDesk Hub endpoint is reachable.")},[r,n,A,N]),I=d.useCallback(()=>{b.current.clear(),Up(S,()=>j()).catch(T=>{g(T instanceof Error?T.message:String(T))})},[j]);return d.useEffect(()=>{if(b.current.clear(),!n){l(null),f([]),w(""),g("");return}let T=!0,_=null;const B=new AbortController,F=()=>{Up(S,()=>j(B.signal)).catch(D=>{T&&!B.signal.aborted&&g(D instanceof Error?D.message:String(D))}).finally(()=>{T&&!B.signal.aborted&&(_=window.setTimeout(F,U1))})};return F(),()=>{T=!1,B.abort(new Error("LiveDesk Hub snapshot polling stopped.")),_!==null&&window.clearTimeout(_)}},[n,j]),{status:o,devices:u,error:h,refresh:I,hubBaseUrl:y||A,hubCandidates:N}}function Q1(t){const[n,r]=d.useState(null),[o,l]=d.useState(""),u=t?.user?.id||"",f=d.useCallback(async()=>{if(!u){r(null);return}const{data:h,error:g}=await $t.from(aw).select("*").eq("user_id",u).maybeSingle();if(g){l(g.message);return}r(h),l("")},[u]);return d.useEffect(()=>{f()},[f]),d.useEffect(()=>{if(!u)return;const h=$t.channel(`livedesk-remote-host-targets-${u.replace(/[^a-zA-Z0-9]/g,"")}`).on("postgres_changes",{event:"*",schema:"public",table:aw,filter:`user_id=eq.${u}`},g=>r(g.new)).subscribe();return()=>{$t.removeChannel(h)}},[u]),{target:n,error:o,refresh:f}}function Y1(t){const[n,r]=d.useState(null),[o,l]=d.useState(!1),[u,f]=d.useState(""),h=t?.user?.id||"",g=d.useCallback(async()=>{if(!h){r(null),f(""),l(!1);return}l(!0);const{data:w,error:b}=await $t.from($1).select("*").eq("user_id",h).eq("product_key","livedesk").maybeSingle();if(b){f(b.message),l(!1);return}r(w),f(""),l(!1)},[h]);d.useEffect(()=>{g()},[g]);const y=d.useMemo(()=>!n||n.status!=="active"?!1:n.expires_at?new Date(n.expires_at).getTime()>Date.now():!0,[n]);return{entitlement:n,licensed:y,loading:o,error:u,refresh:g}}const Zf={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},X1=2500,Z1=3e4,J1=64*1024,eN=64*1024,tN=6,nN=tN,V0=new Map;function aN(t){return V0.get(t)}const sw={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function rN(t,n,r){const o=Number(n);if(!Number.isFinite(o)||o<=0)return 0;const l=r-o,u=t.minimumHubClockOffsetMs;if(!Number.isFinite(u)||l<Number(u))return t.minimumHubClockOffsetMs=l,0;const f=Math.max(0,l-Number(u));return f>Z1?(t.minimumHubClockOffsetMs=l,0):f}function vt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const sN=["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"];function iN(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&sN.every(n=>vt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function oN(t,n,r){if(!t||typeof t!="object")return null;const o=t,l=String(o.deviceId||n||"").trim(),u=String(o.sessionId||"").trim(),f=String(o.streamId||"").trim(),h=o.streamPurpose==="control"?"control":o.streamPurpose==="wall"?"wall":null,g=String(o.commandId||"").trim(),y=Number(o.captureGeneration||0),w=Number(o.monitorIndex??-1);return!l||l!==n||!h||h!==r||!u||!f||!g||!Number.isSafeInteger(y)||y<=0||!Number.isSafeInteger(w)||w<0?null:{deviceId:l,sessionId:u,streamId:f,streamPurpose:h,commandId:g,captureGeneration:y,monitorIndex:w}}function iw(t,n,r=Un,o={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(Zf),S=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(new Map),A=d.useRef(null);A.current===null&&(A.current=m1());const j=d.useRef(0),I=d.useRef(new Map),T=d.useRef({enabled:!1,token:"",reason:""}),_=d.useRef(new Map),B=d.useRef(null),F=d.useRef(new Map),[H,D]=d.useState(0),K=d.useRef(o.onFrame),z=d.useRef(o.onStreamReady),W=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),q=d.useMemo(()=>[...t].sort().join(","),[t]),V=n&&q.length>0,X=d.useRef(!1);d.useLayoutEffect(()=>(X.current=V,()=>{X.current=!1}),[V]);const ve=Number.isFinite(o.fps)?Number(o.fps):2,J=Number.isFinite(o.maxWidth)?Number(o.maxWidth):640,$=Number.isFinite(o.maxHeight)?Number(o.maxHeight):360,P=Number.isFinite(o.quality)?Number(o.quality):45,se=Number.isFinite(o.configurationRefreshMs)?Math.max(0,Math.round(Number(o.configurationRefreshMs))):0,we=String(o.frameMode||o.mode||"mode3-h264-hw").trim()||"mode3-h264-hw",Z=o.streamPurpose==="control"?"control":"wall",Se=o.forceRestart===!0,ae=String(o.forceRestartToken||"").trim(),ye=String(o.restartReason||"").trim();T.current={enabled:Se,token:ae,reason:ye};const Pe=d.useMemo(()=>{const Me=Object.entries(o.monitorSelections||{}).filter(([pe])=>!!pe).sort(([pe],[qe])=>pe.localeCompare(qe));return JSON.stringify(Object.fromEntries(Me))},[o.monitorSelections]),de=d.useMemo(()=>{const Me=Object.entries(o.connectionSessionIds||{}).filter(([pe])=>!!pe).map(([pe,qe])=>[pe,String(qe||"").trim()]).sort(([pe],[qe])=>pe.localeCompare(qe));return JSON.stringify(Object.fromEntries(Me))},[o.connectionSessionIds]);d.useEffect(()=>{K.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{z.current=o.onStreamReady},[o.onStreamReady]);const Qe=d.useCallback((Me,pe="livedesk-frame-socket-release")=>{p1(Me,pe,A.current)},[]),ue=d.useCallback(Me=>{const pe=_.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),_.current.delete(Me))},[]),_e=d.useCallback(Me=>{const pe=F.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),F.current.delete(Me))},[]),Ze=d.useCallback((Me,pe=!0)=>{for(const qe of _.current.values())window.clearTimeout(qe);_.current.clear();for(const qe of F.current.values())window.clearTimeout(qe);F.current.clear();for(const qe of N.current.values())qe.expectedBinding=void 0,Qe(qe,Me);N.current.clear(),I.current.clear(),S.current=new Map,k.current.clear(),W.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(Zf),h("idle"))},[Qe]),at=d.useCallback(()=>{const Me=[...N.current.values()].map(pe=>pe.socket);if(Me.length===0){h("idle");return}if(Me.some(pe=>pe.readyState===WebSocket.OPEN)){h("open");return}if(Me.some(pe=>pe.readyState===WebSocket.CONNECTING)){h("connecting");return}h("closed")},[]),Ee=d.useCallback((Me,pe,qe,Re)=>{if(pe.disposed||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"restart-live",deviceIds:[Me],forceRestart:!0,restartReason:qe,restartToken:Re})),pe.expectedBinding=void 0,ew(pe.sparseTelemetry),!0}catch{return!1}},[]),Ge=d.useCallback((Me,pe)=>{if(pe.disposed||N.current.get(Me)!==pe||pe.socket.readyState!==WebSocket.OPEN)return!1;try{return pe.socket.send(JSON.stringify({...pe.payload,type:"refresh-live",deviceIds:[Me],forceRestart:!1,reuseExisting:!0,reason:"initial-configuration-settle"})),!0}catch{try{pe.socket.close(4003,"configuration-refresh-failed")}catch{}return!1}},[]),me=d.useCallback((Me,pe)=>{if(!X.current||pe.disposed||!Me||Me.byteLength<5)return;const qe=Date.now(),st=new DataView(Me).getUint32(0,!1);if(st<=0||st+4>Me.byteLength)return;const jt=new Uint8Array(Me,4,st),O=JSON.parse(Pv.decode(jt));b1(O,pe.sparseTelemetry,pe.expectedBinding);const ze=vt(O.hubPacketEpochMs),We=ze!==void 0&&ze>0?ze:void 0,Et=rN(pe,We,qe);if(Et>X1)return;const lt=new Uint8Array(Me,4+st),ht=vt(O.nativeCaptureTelemetryVersion),Je=vt(O.nativeCaptureTelemetryAgeMs),be=vt(O.hubClientDropped),je=vt(O.hubClientQueueDepth),Ae=vt(O.hubClientQueueLimit),fe=vt(O.hubClientBufferedBytes),te=be!==void 0&&je!==void 0&&Ae!==void 0&&fe!==void 0,ce={deviceId:String(O.deviceId||""),kind:O.kind==="thumbnail"?"thumbnail":"live",frameSeq:Number(O.frameSeq||0),streamFrameSeq:Number(O.streamFrameSeq||0)||void 0,streamId:String(O.streamId||""),commandId:O.commandId?String(O.commandId):void 0,sessionId:O.sessionId?String(O.sessionId):void 0,captureGeneration:Number(O.captureGeneration||0)||void 0,currentGenerationVerified:!1,streamPurpose:O.streamPurpose?String(O.streamPurpose):void 0,width:Number(O.width||0),height:Number(O.height||0),sourceWidth:Number(O.sourceWidth||0)||void 0,sourceHeight:Number(O.sourceHeight||0)||void 0,mimeType:String(O.mimeType||"image/jpeg"),mode:O.mode?String(O.mode):void 0,frameMode:O.frameMode?String(O.frameMode):void 0,frameProfile:O.frameProfile?String(O.frameProfile):void 0,encoding:O.encoding?String(O.encoding):void 0,codec:O.codec?String(O.codec):void 0,compression:O.compression?String(O.compression):void 0,pixelFormat:O.pixelFormat?String(O.pixelFormat):void 0,bytesPerPixel:Number(O.bytesPerPixel||0)||0,uncompressedByteLength:Number(O.uncompressedByteLength||0)||0,h264Format:O.h264Format?String(O.h264Format):void 0,isKeyFrame:O.isKeyFrame===!0,chunkType:O.chunkType?String(O.chunkType):void 0,timestampUs:Number(O.timestampUs||0)||0,durationUs:Number(O.durationUs||0)||0,sourceGapMs:Number(O.sourceGapMs||0)||0,agentSendGapMs:Number(O.agentSendGapMs||0)||0,agentSendDurationMs:Number(O.agentSendDurationMs||0)||0,agentSendDurationFrameSeq:Number(O.agentSendDurationFrameSeq||0)||0,agentPaceMs:Number(O.agentPaceMs||0)||0,agentQueueBeforePaceMs:Number(O.agentQueueBeforePaceMs||0)||0,agentFrameAgeMs:Number(O.agentFrameAgeMs||0)||0,inputFeedbackEventId:O.inputFeedbackEventId?String(O.inputFeedbackEventId):void 0,inputFeedbackInputSeq:vt(O.inputFeedbackInputSeq),inputFeedbackInputType:O.inputFeedbackInputType?String(O.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:vt(O.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:vt(O.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:vt(O.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:vt(O.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:vt(O.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:vt(O.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:vt(O.inputFeedbackApplyToCaptureMs),inputFeedbackCaptureTimestampAvailable:typeof O.inputFeedbackCaptureTimestampAvailable=="boolean"?O.inputFeedbackCaptureTimestampAvailable:void 0,nativeCaptureTelemetryAvailable:typeof O.nativeCaptureTelemetryAvailable=="boolean"?O.nativeCaptureTelemetryAvailable:void 0,nativeCaptureTelemetryVersion:ht===void 0?void 0:Math.max(0,ht),nativeCaptureTelemetryAgeMs:Je===void 0?void 0:Math.max(0,Je),nativeEncoderHardwareAccelerationKnown:typeof O.nativeEncoderHardwareAccelerationKnown=="boolean"?O.nativeEncoderHardwareAccelerationKnown:void 0,nativeEncoderHardwareAccelerated:typeof O.nativeEncoderHardwareAccelerated=="boolean"?O.nativeEncoderHardwareAccelerated:void 0,nativeEncoderHardwareQueryStatus:O.nativeEncoderHardwareQueryStatus?String(O.nativeEncoderHardwareQueryStatus):void 0,nativeCaptureDisplayId:vt(O.nativeCaptureDisplayId),nativeCaptureFps:vt(O.nativeCaptureFps),nativeCompressionFps:vt(O.nativeCompressionFps),nativeEncodedFps:vt(O.nativeEncodedFps),nativeCaptureSampleCount:vt(O.nativeCaptureSampleCount),nativeEncodableFrameCount:vt(O.nativeEncodableFrameCount),nativeSkippedFrameCount:vt(O.nativeSkippedFrameCount),nativeCompressionOutputCount:vt(O.nativeCompressionOutputCount),nativeEncodedFrameCount:vt(O.nativeEncodedFrameCount),nativeEncodeFramesInFlight:vt(O.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:vt(O.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:vt(O.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:vt(O.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:vt(O.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:vt(O.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:vt(O.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:vt(O.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:vt(O.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:vt(O.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:vt(O.nativeOutputQueueDepth),nativeOutputQueueBytes:vt(O.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:vt(O.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:vt(O.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:vt(O.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof O.nativeOutputQueueAwaitingKeyFrame=="boolean"?O.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof O.nativeCopyTelemetryAvailable=="boolean"?O.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:vt(O.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:vt(O.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:vt(O.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:vt(O.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:vt(O.pipePayloadAllocationCount),pipePayloadCopyCount:vt(O.pipePayloadCopyCount),pipePayloadCopiedBytes:vt(O.pipePayloadCopiedBytes),handoffDroppedFrameCount:vt(O.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:vt(O.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:vt(O.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:O.nativeCaptureResourceTelemetryAvailable===!0?iN(O):O.nativeCaptureResourceTelemetryAvailable===!1?!1:void 0,nativeCaptureTelemetryAt:O.nativeCaptureTelemetryAt?String(O.nativeCaptureTelemetryAt):void 0,droppedByAgent:Number(O.droppedByAgent||0)||0,hubIngressDropped:Number(O.hubIngressDropped||0)||0,hubClientDropped:be,transport:O.transport?String(O.transport):void 0,videoTransport:O.videoTransport?String(O.videoTransport):void 0,frameTransportActive:O.frameTransportActive?String(O.frameTransportActive):void 0,frameTransportProtocol:O.frameTransportProtocol?String(O.frameTransportProtocol):void 0,frameTransportState:O.frameTransportState?String(O.frameTransportState):void 0,frameTransportReason:O.frameTransportReason?String(O.frameTransportReason):void 0,frameTransportChangedAt:O.frameTransportChangedAt?String(O.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(O.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(O.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:O.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:te,hubClientQueueDepth:je,hubClientQueueLimit:Ae,hubClientBufferedBytes:fe,udpIncompleteFrames:Number(O.udpIncompleteFrames||0)||0,hardwareEncoder:O.hardwareEncoder?String(O.hardwareEncoder):void 0,platformProfile:O.platformProfile?String(O.platformProfile):void 0,monitorIndex:Number.isFinite(Number(O.monitorIndex))?Number(O.monitorIndex):void 0,monitorCount:Number.isFinite(Number(O.monitorCount))?Number(O.monitorCount):void 0,requestedFps:Number(O.requestedFps||0)||0,effectiveFps:Number(O.effectiveFps||0)||0,captureTimingAvailable:O.captureTimingAvailable===!0,captureAverageMs:vt(O.captureAverageMs),captureP95Ms:vt(O.captureP95Ms),slowFrameCount:Number(O.slowFrameCount||0)||0,captureHelperRestarts:Number(O.captureHelperRestarts||0)||0,capturedAt:String(O.capturedAt||""),receivedAt:String(O.receivedAt||""),hubPacketAt:O.hubPacketAt?String(O.hubPacketAt):void 0,hubPacketEpochMs:We,browserReceivedEpochMs:qe,hubPacketTransitAgeMs:We!==void 0?Et:void 0,byteLength:Number(O.byteLength||lt.byteLength),contentHash:O.contentHash?String(O.contentHash):void 0,captureMs:vt(O.captureMs),captureStageMs:vt(O.captureStageMs),convertMs:Number(O.convertMs||0)||0,compressMs:Number(O.compressMs||0)||0,captureSourceSerial:Number(O.captureSourceSerial||0)||0,captureSourceSkipped:Number(O.captureSourceSkipped||0)||0,deltaTileSize:Number(O.deltaTileSize||0)||0,deltaTileCount:Number(O.deltaTileCount||0)||0,deltaVisualTileCount:Number(O.deltaVisualTileCount||0)||0,deltaRefreshTileCount:Number(O.deltaRefreshTileCount||0)||0,deltaTotalTiles:Number(O.deltaTotalTiles||0)||0,payload:lt};if(!ce.deviceId)return;const Ne=pe.expectedBinding;if(!Ne)return;const He=ce.deviceId===Ne.deviceId&&String(ce.sessionId||"")===Ne.sessionId&&ce.streamId===Ne.streamId&&String(ce.commandId||"")===Ne.commandId&&Number(ce.captureGeneration||0)===Ne.captureGeneration&&Number(ce.monitorIndex??-1)===Ne.monitorIndex&&String(ce.streamPurpose||"")===Ne.streamPurpose;if(!He)return;ce.currentGenerationVerified=He;const Ie=Number(pe.payload.monitorSelections?.[ce.deviceId]);if(Number.isFinite(Ie)&&Number.isFinite(Number(ce.monitorIndex))&&Number(ce.monitorIndex)!==Ie)return;const Lt={streamId:pe.lastFrameStreamId,commandId:pe.lastFrameCommandId,order:pe.lastFrameOrder},Xe=Number(ce.streamFrameSeq||ce.frameSeq||0),ut=!!Lt.commandId&&!!ce.commandId,yt=Lt.streamId===ce.streamId&&(!ut||Lt.commandId===ce.commandId),_t=Lt.order;if(yt&&_t>=Xe&&(_t===Xe||ut))return;pe.lastFrameStreamId=ce.streamId,pe.lastFrameCommandId=ce.commandId||"",pe.lastFrameOrder=Xe;const mt=W.current;mt.totalFrames+=1,mt.totalBytes+=lt.byteLength,mt.sampleFrames+=1,mt.sampleBytes+=lt.byteLength;const Vt=!S.current.has(ce.deviceId)&&!k.current.has(ce.deviceId),St=u1(k.current,ce);Vt&&(S.current.set(ce.deviceId,St),k.current.delete(ce.deviceId),u(new Map(S.current))),K.current?.(ce)},[]);d.useEffect(()=>{if(!n||!q)return;W.current.sampleStartedAt=performance.now();const Me=window.setInterval(()=>{if(!X.current)return;const pe=performance.now(),qe=W.current,Re=Math.max(1,pe-qe.sampleStartedAt);b({totalFrames:qe.totalFrames,totalBytes:qe.totalBytes,framesPerSecond:qe.sampleFrames*1e3/Re,bytesPerSecond:qe.sampleBytes*1e3/Re,sampleMs:Re,lastUpdatedAt:Date.now()}),u(d1(S.current,k.current)),qe.sampleFrames=0,qe.sampleBytes=0,qe.sampleStartedAt=pe},2e3);return B.current=Me,()=>{window.clearInterval(Me),B.current===Me&&(B.current=null)}},[n,q]),d.useEffect(()=>{const Me=()=>{const pe=new Set,qe=[...N.current.values()];for(;qe.length>0;){const O=qe.pop();!O||pe.has(O)||(pe.add(O),O.handoffFrom&&qe.push(O.handoffFrom))}const Re=[...S.current.values(),...k.current.values()],st=[...pe],jt=A.current?.snapshot()||{closingSocketCount:0,closingSocketTimerCount:0,closingSocketTimeoutCount:0};return{deviceKey:q,active:X.current,socketCount:st.length+jt.closingSocketCount,openSocketCount:st.filter(O=>O.socket.readyState===WebSocket.OPEN).length,connectingSocketCount:st.filter(O=>O.socket.readyState===WebSocket.CONNECTING).length,closingSocketCount:jt.closingSocketCount,closingSocketTimerCount:jt.closingSocketTimerCount,closingSocketTimeoutCount:jt.closingSocketTimeoutCount,expectedBindingCount:st.filter(O=>!!O.expectedBinding).length,reconnectTimerCount:_.current.size,statsTimerCount:B.current===null?0:1,configurationRefreshTimerCount:F.current.size,restartTokenCount:I.current.size,retainedFrameCount:Re.length,retainedPayloadBytes:Re.reduce((O,ze)=>O+Math.max(0,Number(ze.payload?.byteLength||0)),0)}};return cv.add(Me),()=>{cv.delete(Me)}},[q]),d.useEffect(()=>{const Me=q?q.split(",").filter(Boolean):[];if(!V){Ze(n?"livedesk-no-devices":"livedesk-stream-inactive");return}const pe=new Set(Me),qe=performance.now();for(const Re of _.current.keys())pe.has(Re)||ue(Re);for(const Re of F.current.keys())pe.has(Re)||_e(Re);for(const[Re,st]of N.current.entries())pe.has(Re)||(ue(Re),Qe(st,"livedesk-device-unsubscribed"),N.current.delete(Re),I.current.delete(Re),S.current.delete(Re),k.current.delete(Re));W.current.sampleStartedAt<=0&&(W.current.sampleStartedAt=qe,b({...Zf,lastUpdatedAt:Date.now()}));for(const Re of Me){ue(Re),_e(Re);const st=Number(o.monitorSelections?.[Re]),jt=Number.isInteger(st)&&st>=0?st:0,O={[Re]:jt},ze={type:"subscribe",deviceIds:[Re],autoStartLive:n,fps:ve,maxWidth:J,maxHeight:$,quality:P,mode:we,frameMode:we,streamPurpose:Z,monitorSelections:O},We=String(o.connectionSessionIds?.[Re]||"").trim(),Et=JSON.stringify({subscribePayload:ze,connectionSessionId:We}),lt=N.current.get(Re),ht=Number(lt?.payload.monitorSelections?.[Re]),Je=Number(O[Re]),be=!!lt&&Number.isFinite(ht)&&Number.isFinite(Je)&&ht!==Je,je=!!lt&<?.connectionSessionId!==We;if(lt){const yt=lt.socket.readyState===WebSocket.CONNECTING||lt.socket.readyState===WebSocket.OPEN;if(lt.payloadKey===Et&&yt&&!lt.disposed)continue}const Ae=lt&&(lt.socket.readyState===WebSocket.CONNECTING||lt.socket.readyState===WebSocket.OPEN)&&!lt.disposed?lt.handoffFrom&&!lt.handoffCompleted?lt.handoffFrom:lt:void 0,fe=lt&<!==Ae?lt:void 0,te=`/api/remote/frames/ws?devices=${encodeURIComponent(Re)}`,ce=nh(ah(te,r),te);ce.binaryType="arraybuffer";const Ne=y1(),He={socket:ce,payload:ze,payloadKey:Et,connectionSessionId:We,generation:j.current+1,monitorRestartToken:be?`monitor-${Re}-${Je}-${j.current+1}`:"",disposed:!1,handoffFrom:Ae,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Ne,releaseOwnedState:()=>ew(Ne)};j.current=He.generation,(be||je)&&(S.current.delete(Re),k.current.delete(Re),u(new Map(S.current))),N.current.set(Re,He),fe&&(fe.handoffFrom=void 0,Qe(fe,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||He.disposed||N.current.get(Re)!==He){Qe(He,"livedesk-stale-frame-socket");return}ue(Re),y("");const yt=T.current,_t=yt.enabled&&(!yt.token||I.current.get(Re)!==yt.token),mt=_t||He.monitorRestartToken!=="",Vt=_t?yt.token:He.monitorRestartToken,St=_t?yt.reason:He.monitorRestartToken?"monitor-selection-change":"";if(ce.send(JSON.stringify({...He.payload,forceRestart:mt,restartReason:mt?St:"",restartToken:mt?Vt:""})),se>0){const rn=window.setTimeout(()=>{F.current.get(Re)===rn&&F.current.delete(Re),X.current&&Ge(Re,He)},Math.max(1e3,se));F.current.set(Re,rn)}_t&&yt.token&&I.current.set(Re,yt.token);const pn=He.handoffFrom;He.handoffFrom=void 0,He.handoffCompleted=!0,pn&&!pn.disposed&&Qe(pn,"livedesk-subscription-replaced"),at()},Lt=yt=>{if(!X.current||He.disposed||N.current.get(Re)!==He)return;if(typeof yt.data=="string"){try{const mt=JSON.parse(yt.data),Vt=(St,pn=!0)=>{const rn=oN(St,Re,Z);return rn?(He.expectedBinding=rn,pn&&z.current?.(rn),!0):!1};if(mt?.type==="RemoteFrameSubscriptionError")y(String(mt.error||"control-stream-start-failed"));else if(mt?.type==="RemoteFrameLiveAutoStart"){const pn=(Array.isArray(mt.skipped)?mt.skipped:[]).find(rn=>rn?.deviceId===Re);if(pn)pn.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&pn.retryScheduled===!0?y(""):y(String(pn.reason||"control-stream-start-failed"));else if(Array.isArray(mt.started)){const rn=mt.started.find(ya=>ya?.deviceId===Re);rn&&(y(""),Vt(rn,rn.ready===!0))}}else mt?.type==="RemoteFrameStreamReady"&&mt.deviceId===Re&&Vt(mt)&&y("")}catch{}return}const _t=yt.data instanceof ArrayBuffer?yt.data:null;_t&&(y(""),me(_t,He))},Xe=()=>{!X.current||He.disposed||N.current.get(Re)!==He||h("connecting")},ut=()=>{const yt=!He.disposed;He.disposed=!0,He.handoffCompleted=!0;const _t=He.detachListeners;He.detachListeners=void 0,_t?.();const mt=N.current.get(Re);mt===He&&_e(Re);let Vt=!1;if(mt===He){const St=He.handoffFrom;He.handoffFrom=void 0,St&&!St.disposed&&(St.socket.readyState===WebSocket.CONNECTING||St.socket.readyState===WebSocket.OPEN)?(N.current.set(Re,St),Vt=!0):N.current.delete(Re)}if(at(),yt&&X.current&&mt===He&&!Vt){const St=window.setTimeout(()=>{_.current.get(Re)===St&&_.current.delete(Re),X.current&&D(pn=>pn+1)},750);ue(Re),_.current.set(Re,St)}};He.detachListeners=()=>{ce.removeEventListener("open",Ie),ce.removeEventListener("message",Lt),ce.removeEventListener("error",Xe),ce.removeEventListener("close",ut)},ce.addEventListener("open",Ie),ce.addEventListener("message",Lt),ce.addEventListener("error",Xe),ce.addEventListener("close",ut)}at()},[n,_e,ue,Qe,se,de,q,ve,we,me,r,$,J,Pe,o.monitorSelections,P,H,Ze,Ge,Z,V,at]),d.useEffect(()=>{if(!V||!Se||!ae)return;const Me=q?q.split(",").filter(Boolean):[];for(const pe of Me){if(I.current.get(pe)===ae)continue;const qe=N.current.get(pe);!qe||!Ee(pe,qe,ye,ae)||I.current.set(pe,ae)}},[q,Se,ae,ye,Ee,V]),d.useEffect(()=>()=>{Ze("livedesk-hook-unmount",!1)},[Ze]);const ke=d.useCallback((Me,pe="browser-stale")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:q.split(",").filter(Boolean);if(qe.length===0)return!1;let Re=!1;for(const st of qe){const jt=N.current.get(st);!jt||jt.socket.readyState!==WebSocket.OPEN||(Re=Ee(st,jt,pe,`${Date.now()}-${Math.random().toString(36).slice(2)}`)||Re)}return Re},[q,Ee,V]),et=d.useCallback((Me,pe="browser-reconnect")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:q.split(",").filter(Boolean);if(qe.length===0)return!1;let Re=!1;for(const st of qe){const jt=N.current.get(st);jt&&(ue(st),Qe(jt,`livedesk-${pe}`),N.current.delete(st),I.current.delete(st),S.current.delete(st),k.current.delete(st),Re=!0)}return Re&&u(new Map(S.current)),D(st=>st+1),at(),!0},[ue,Qe,q,V,at]);return{frames:l,state:f,error:g,stats:w,restartLive:ke,reconnectLive:et}}function lN(t,n,r=Un,o={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(Zf),S=d.useRef(null),k=d.useRef(o.onFrame),N=d.useRef(null),A=d.useRef(0),j=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),T=d.useMemo(()=>[...new Set((o.captureDeviceIds||t).filter(Boolean))].join(","),[t,o.captureDeviceIds]),_=d.useMemo(()=>JSON.stringify(o.monitorSelections||{}),[o.monitorSelections]),B=d.useMemo(()=>{const q=Object.entries(o.connectionSessionIds||{}).filter(([V])=>!!V).map(([V,X])=>[V,String(X||"").trim()]).sort(([V],[X])=>V.localeCompare(X));return JSON.stringify(Object.fromEntries(q))},[o.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:T.split(",").filter(Boolean),fps:Number(o.fps||20),inputFps:Number(o.inputFps||8),width:Number(o.width||1920),height:Number(o.height||1080),tileWidth:Number(o.tileWidth||320),tileHeight:Number(o.tileHeight||180),monitorSelections:o.monitorSelections||{}}),[T,I,_,o.fps,o.height,o.inputFps,o.monitorSelections,o.tileHeight,o.tileWidth,o.width]),H=d.useMemo(()=>JSON.stringify({atlasConfiguration:F,connectionSessionKey:B}),[F,B]),D=d.useRef(F);D.current=F;const K=n&&F.deviceIds.length>0,z=d.useCallback(q=>q.readyState!==WebSocket.OPEN?!1:(q.send(JSON.stringify({type:"configure",...D.current})),!0),[]);d.useEffect(()=>{k.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{if(!K)return;j.current.sampleStartedAt=performance.now();const q=window.setInterval(()=>{const V=j.current,X=performance.now(),ve=Math.max(1,X-V.sampleStartedAt);b({totalFrames:V.totalFrames,totalBytes:V.totalBytes,framesPerSecond:V.sampleFrames*1e3/ve,bytesPerSecond:V.sampleBytes*1e3/ve,sampleMs:ve,lastUpdatedAt:Date.now()});const J=N.current;J&&J.frameSeq!==A.current&&(A.current=J.frameSeq,u(J)),V.sampleFrames=0,V.sampleBytes=0,V.sampleStartedAt=X},1e3);return()=>window.clearInterval(q)},[K]),d.useEffect(()=>{if(!K){S.current?.close(),S.current=null,u(null),N.current=null,A.current=0,h(null),y("idle"),b(Zf);return}let q=!1,V=0;const X=()=>{if(q)return;const ve=nh(ah("/api/remote/atlas/ws",r),"/api/remote/atlas/ws");ve.binaryType="arraybuffer",S.current=ve,y("connecting"),ve.addEventListener("open",()=>{j.current.sampleStartedAt=performance.now(),y("open"),z(ve)}),ve.addEventListener("message",J=>{if(typeof J.data=="string"){try{const P=JSON.parse(J.data);P?.type==="Mode4AtlasLayout"&&h({layoutVersion:Number(P.layoutVersion||0),width:Number(P.width||1920),height:Number(P.height||1080),columns:Number(P.columns||1),rows:Number(P.rows||1),tiles:Array.isArray(P.tiles)?P.tiles:[]})}catch{}return}const $=J.data instanceof ArrayBuffer?J.data:null;if(!(!$||$.byteLength<5))try{const P=Date.now(),we=new DataView($).getUint32(0,!1);if(we<=0||we+4>$.byteLength)return;const Z=JSON.parse(Pv.decode(new Uint8Array($,4,we))),Se=new Uint8Array($,4+we),ae=vt(Z.hubClientDropped),ye=vt(Z.hubClientQueueDepth),Pe=vt(Z.hubClientQueueLimit),de=vt(Z.hubClientBufferedBytes),Qe={deviceId:String(Z.deviceId||"__livedesk_mode4_atlas__"),kind:"live",frameSeq:Number(Z.frameSeq||0),streamFrameSeq:Number(Z.streamFrameSeq||0)||void 0,streamId:String(Z.streamId||"mode4-atlas"),commandId:Z.commandId?String(Z.commandId):void 0,width:Number(Z.width||1920),height:Number(Z.height||1080),sourceWidth:Number(Z.sourceWidth||Z.width||1920),sourceHeight:Number(Z.sourceHeight||Z.height||1080),mimeType:String(Z.mimeType||"video/h264"),mode:String(Z.mode||"mode4-h264-atlas"),frameMode:String(Z.frameMode||"mode4-h264-atlas"),frameProfile:String(Z.frameProfile||"mode4-h264-atlas-v1"),encoding:String(Z.encoding||"video-atlas"),codec:String(Z.codec||"h264"),compression:String(Z.compression||"video/h264"),h264Format:String(Z.h264Format||"annexb"),isKeyFrame:Z.isKeyFrame===!0,chunkType:String(Z.chunkType||""),timestampUs:Number(Z.timestampUs||0),durationUs:Number(Z.durationUs||0),transport:Z.transport?String(Z.transport):void 0,videoTransport:Z.videoTransport?String(Z.videoTransport):void 0,frameTransportActive:Z.frameTransportActive?String(Z.frameTransportActive):void 0,frameTransportProtocol:Z.frameTransportProtocol?String(Z.frameTransportProtocol):void 0,frameTransportState:Z.frameTransportState?String(Z.frameTransportState):void 0,frameTransportReason:Z.frameTransportReason?String(Z.frameTransportReason):void 0,frameTransportChangedAt:Z.frameTransportChangedAt?String(Z.frameTransportChangedAt):void 0,frameTransportSwitchCount:Number(Z.frameTransportSwitchCount||0)||0,frameTransportTcpFailureCount:Number(Z.frameTransportTcpFailureCount||0)||0,frameTransportP2pReady:Z.frameTransportP2pReady===!0,hubClientQueueTelemetryAvailable:ae!==void 0&&ye!==void 0&&Pe!==void 0&&de!==void 0,hubClientDropped:ae,hubClientQueueDepth:ye,hubClientQueueLimit:Pe,hubClientBufferedBytes:de,udpIncompleteFrames:Number(Z.udpIncompleteFrames||0)||0,hardwareEncoder:Z.hardwareEncoder?String(Z.hardwareEncoder):void 0,platformProfile:Z.platformProfile?String(Z.platformProfile):void 0,capturedAt:String(Z.capturedAt||""),receivedAt:String(Z.receivedAt||""),hubPacketAt:Z.hubPacketAt?String(Z.hubPacketAt):void 0,hubPacketEpochMs:Number(Z.hubPacketEpochMs||0)||void 0,browserReceivedEpochMs:P,byteLength:Se.byteLength,layoutVersion:Number(Z.layoutVersion||0),atlasComposeMs:Number(Z.atlasComposeMs||0),atlasPoolStarved:Number(Z.atlasPoolStarved||0),atlasReadyTiles:Number(Z.atlasReadyTiles||0),atlasTileCount:Number(Z.atlasTileCount||0),atlasInputRevision:Number(Z.atlasInputRevision||0),atlasSourceNewestAtEpochMs:Number(Z.atlasSourceNewestAtEpochMs||0),atlasSourceOldestAtEpochMs:Number(Z.atlasSourceOldestAtEpochMs||0),atlasSourceMaxAgeMs:Number(Z.atlasSourceMaxAgeMs||0),payload:Se},ue=j.current;ue.totalFrames+=1,ue.totalBytes+=Se.byteLength,ue.sampleFrames+=1,ue.sampleBytes+=Se.byteLength,N.current=Qe,A.current===0&&(A.current=Qe.frameSeq,u(Qe)),k.current?.(Qe)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{S.current===ve&&(S.current=null),!q&&(y("closed"),V=window.setTimeout(X,1200))})};return X(),()=>{q=!0,window.clearTimeout(V),S.current?.close(),S.current=null}},[K,r,z]),d.useEffect(()=>{if(!K)return;const q=S.current;q&&z(q)},[H,K,z]);const W=d.useCallback(()=>{const q=S.current;return q?z(q):!1},[z]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:W}}function cN(t,n=Un){const r=d.useRef(null),o=d.useRef(0),l=d.useRef(0),u=d.useRef(new Map),f=d.useRef(""),[h,g]=d.useState("idle"),[y,w]=d.useState(""),[b,S]=d.useState(sw),k=d.useRef({totalSent:0,totalDropped:0,sampleSent:0,sampleDropped:0,sampleStartedAt:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0});d.useEffect(()=>{if(!t){r.current?.close(),r.current=null,l.current=0,f.current="",u.current.clear(),g("idle"),w(""),S(sw);return}let A=!1,j=0;const I=()=>{if(A)return;const T=nh(ah("/api/remote/input/ws",n),"/api/remote/input/ws");r.current=T,k.current.sampleStartedAt=performance.now(),g("connecting"),w(""),T.addEventListener("open",()=>{A||r.current!==T||(w(""),g("open"))}),T.addEventListener("message",_=>{if(!(A||r.current!==T||typeof _.data!="string"))try{const B=JSON.parse(_.data),F=Number(B.inputSeq||B.result?.inputSeq||0),H=String(B.deviceId||B.result?.deviceId||""),D=String(B.inputEventId||B.result?.inputEventId||""),K=u.current.get(F);if(H&&(K&&K.deviceId!==H||!K&&f.current&&f.current!==H)||K?.inputEventId&&D&&K.inputEventId!==D)return;if(B?.type==="RemoteInputError"){F>0&&u.current.delete(F),w(String(B.error||B.result?.error||"Remote input failed.")),T.readyState===WebSocket.OPEN&&g("open");return}if(B?.type!=="RemoteInputApplied")return;K&&(k.current.lastRoundTripMs=Math.max(0,performance.now()-K.sentAt),u.current.delete(F)),k.current.lastInputSeq=F,k.current.lastAgentApplyMs=Math.max(0,Number(B.agentApplyMs||0)),w(""),g("open")}catch{}}),T.addEventListener("close",()=>{A||r.current!==T||(r.current=null,g("closed"),j=window.setTimeout(I,1200))}),T.addEventListener("error",()=>{!A&&r.current===T&&g("error")})};return I(),()=>{A=!0,window.clearTimeout(j);const T=r.current;r.current=null,T?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const A=window.setInterval(()=>{const j=performance.now(),I=k.current,T=Math.max(1,j-I.sampleStartedAt);S({totalSent:I.totalSent,totalDropped:I.totalDropped,sentPerSecond:I.sampleSent*1e3/T,droppedPerSecond:I.sampleDropped*1e3/T,bufferedAmount:r.current?.bufferedAmount||0,lastInputType:I.lastInputType,lastInputSeq:I.lastInputSeq,lastRoundTripMs:I.lastRoundTripMs,lastAgentApplyMs:I.lastAgentApplyMs,lastUpdatedAt:Date.now()}),I.sampleSent=0,I.sampleDropped=0,I.sampleStartedAt=j},1e3);return()=>window.clearInterval(A)},[t]);const N=d.useCallback((A,j)=>{const I=r.current;if(!I||I.readyState!==WebSocket.OPEN||!A)return!1;const T=String(j.type||"").toLowerCase(),F=T==="pointermove"||T==="wheel",H=k.current;if(F&&I.bufferedAmount>J1)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${T}-coalescible-drop`,!1;if(!F&&I.bufferedAmount>eN){H.lastInputType=`${T||"input"}-fail-closed`,w("Remote input channel was reset because ordered input could not drain.");try{I.close(4001,"ordered-input-backpressure")}catch{}return!1}const D=o.current+1;o.current=D;const K=`${D}-${crypto.randomUUID()}`,z=Date.now(),W=!F||D-l.current>=nN;for(W&&(u.current.set(D,{sentAt:performance.now(),deviceId:A,inputEventId:K}),F&&(l.current=D)),f.current=A,V0.set(A,{inputSeq:D,inputType:T||"input",sentAt:performance.now()});u.current.size>256;){const q=u.current.keys().next().value;if(q===void 0)break;u.current.delete(q)}try{I.send(JSON.stringify({type:"input",requestId:F?"":crypto.randomUUID(),fireAndForget:F,deviceId:A,input:{...j,inputEventId:K,inputSeq:D,requestAck:W,issuedAtEpochMs:z,issuedAt:new Date(z).toISOString()}}))}catch{u.current.delete(D),w("Remote input channel closed before the ordered input was queued.");try{I.close(4002,"input-send-failed")}catch{}return!1}return H.totalSent+=1,H.sampleSent+=1,H.lastInputType=T||"input",!0},[]);return{state:h,sendInput:N,stats:b,error:y}}const xd={queuedMs:0,browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureAwaitingCurrentPcm:!1,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAgeMs:0,lastAcceptedAgeMs:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:"closed",stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0,lastUpdatedAt:0},uN=.25,ow=300,lw=2,dp=1500,xg=5e3,dN=2e3,cw=1e4,If=[0,1e3,3e3];function uw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function fN(t,n,r=Un,o=0,l=!1,u="",f,h){const g=d.useRef(null),[y,w]=d.useState("idle"),[b,S]=d.useState(null),[k,N]=d.useState(xd),[A,j]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(S(T=>T===null?T:null),N(T=>T===xd?T:xd))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),S(null),N(xd),j("");return}w("connecting"),S(null),N(xd),j("");const T=window.AudioContext||window.webkitAudioContext;if(!T){w("unsupported"),N(xd),j("Audio playback is not supported in this browser.");return}let _=!1,B=null;const F=N1.acquire(({release:H})=>{if(_){H();return}const D=new T({latencyHint:"interactive"});g.current=D;let K=String(u||"").trim();const z="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(K?"&streamId="+encodeURIComponent(K):""),W=nh(ah(z,r),z);W.binaryType="arraybuffer";const q=pa.createOwner({deviceId:t,socket:W,audioContext:D,statsTimer:null});let V=!1;const X=()=>{const te=pa.releaseIfDrained(q);return(te||!pa.hasOwner(q))&&!V&&(V=!0,H()),te},ve=Lv({sampleRate:192e3,channels:8}).capacityBytes,J=P1({maxPendingPackets:ov,maxPendingBytes:ve}),$=S1(),P={browserAgeMs:0,captureAgeMs:0,captureStatusAgeMs:0,silentForMs:0,captureAlive:null,helperAlive:null,helperReady:!1,captureHealthy:!1,captureStatusFailed:!1,captureAwaitingCurrentPcm:!1,captureAwaitingSinceAt:0,capturePhase:"",backendKind:"",helperRequired:!1,helperPid:0,captureRestartCount:0,nativeCallbackDiagnosticsAvailable:!1,nativeRejectedCallbackCount:0,nativeCurrentnessDropCount:0,nativeLastDropReason:"",localProcessingAgeMs:0,lastPacketAt:0,lastAcceptedAt:0,framesReceived:0,drops:0,resyncs:0,pendingDecodes:0,lastFrameSeq:0,audioContextState:String(D.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:K,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let se=!1,we=!1,Z=null,Se=0,ae=0,ye="",Pe=!1,de=()=>{},Qe="connecting",ue="";const _e=te=>{se||te===Qe||(Qe=te,w(te))},Ze=te=>{se||te===ue||(ue=te,j(te))};let at=0,Ee=!1,Ge=0,me=0,ke=0,et=!1;const Me=()=>{pa.setPendingWorkletPackets(q,J.getPendingPacketCount(),J.getPendingPacketBytes(),J.getPendingPacketHighWater(),J.getPendingByteHighWater())},pe=te=>{P.workletRingCapacityBytes=Math.max(0,Math.min(ve,Number(te.ringCapacityBytes||0)||0)),P.workletRingBufferedBytes=Math.max(0,Math.min(P.workletRingCapacityBytes,Number(te.ringBufferedBytes||0)||0)),P.workletRingBufferedMs=Math.max(0,Math.min(uN*1e3,Number(te.ringBufferedMs||0)||0)),P.workletRingDroppedFrames=Math.max(P.workletRingDroppedFrames,Number(te.ringDroppedFrames||0)||0),P.workletRingUnderflowCount=Math.max(P.workletRingUnderflowCount,Number(te.ringUnderflowCount||0)||0),pa.setPcmRing(q,P.workletRingCapacityBytes,P.workletRingBufferedBytes)},qe=()=>{const te=Z;if(Z=null,Pe=!1,te){te.onprocessorerror=null,te.port.onmessage=null;try{te.disconnect()}catch{}try{te.port.close()}catch{}}J.terminate(),Me(),P.workletRingCapacityBytes=0,P.workletRingBufferedBytes=0,P.workletRingBufferedMs=0,pa.setPcmRing(q,0,0),pa.setWorkletNode(q,0,0,Se),X()},Re=te=>{const ce=te.data||{},Ne=String(ce.type||"");if((Ne==="packet-terminal"||Ne==="processor-error")&&(J.acknowledge(typeof ce.packetId=="number"?ce.packetId:String(ce.packetId||"")),Me()),Ne==="packet-terminal"){const He=Math.max(0,Number(ce.droppedFrames||0)||0);He>0&&(P.workletRingDroppedFrames+=He,P.resyncs+=1)}if(Ne==="ring-configured"||Ne==="ring-state"||Ne==="disposed"){const He=P.workletRingDroppedFrames;pe(ce),P.workletRingDroppedFrames>He&&(P.resyncs+=1)}Ne==="disposed"?qe():Ne==="processor-error"&&de(String(ce.error||"Remote audio worklet processing failed."))},st=()=>{if(!(!Z||!Pe))try{Z.port.postMessage({type:"flush"})}catch{de("Remote audio worklet could not be flushed.")}},jt=()=>{W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:K?{[t]:K}:{}}))},O=()=>{P.audioContextState=String(D.state),!se&&(P.audioContextState==="suspended"||P.audioContextState==="interrupted"?_e("suspended"):P.audioContextState==="closed"&&(_e("error"),Ze("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},ze=async()=>{if(se||String(D.state)==="closed")return!1;try{if(String(D.state)!=="running"&&await D.resume(),P.audioContextState=String(D.state),!se&&!Ee&&P.audioContextState==="running"){const te=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp,ce=P.lastCaptureStatusAt>0&&performance.now()-P.lastCaptureStatusAt<=xg&&P.captureHealthy;_e(te?"playing":ce?"silent":"open")}return P.audioContextState==="running"}catch(te){return se||(_e("suspended"),Ze(te instanceof Error?"Audio playback is suspended: "+te.message:"Audio playback is suspended.")),!1}},We=async()=>{if(!D.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const te=new Blob([H1],{type:"text/javascript"});ye=URL.createObjectURL(te);try{await D.audioWorklet.addModule(ye)}finally{URL.revokeObjectURL(ye),ye=""}if(se||String(D.state)==="closed")return;const ce=new AudioWorkletNode(D,G0,{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[lw],channelCount:lw,channelCountMode:"explicit"});Se+=1,Z=ce,ce.port.onmessage=Re,ce.onprocessorerror=()=>{de("Remote audio worklet stopped unexpectedly.")},ce.connect(D.destination),Pe=!0,pa.setWorkletNode(q,1,1,Se)},Et=(te,ce,Ne,He)=>{const Ie=Z;if(se||!Pe||!Ie||ce.byteLength<=0)return!1;const Lt=Iv({sampleRate:te.sampleRate,channels:te.channels,mimeType:te.mimeType}),Xe=++ae;if(!J.claim(Xe,ce.byteLength))return Me(),!1;Me();try{return Ie.port.postMessage({type:"pcm",packetId:Xe,buffer:ce,byteOffset:Ne,byteLength:He,sampleRate:Lt.sampleRate,channels:Lt.channels,mimeType:te.mimeType,sampleFormat:Lt.sampleFormat},[ce]),!0}catch{return J.acknowledge(Xe),Me(),!1}},lt=async()=>{if(se||Ee||W.readyState!==WebSocket.OPEN)return;if(Ge>=If.length){_e("error"),Ze("Remote audio stopped sending frames. Toggle Audio off and on to retry.");return}const te=Ge;Ge+=1,Ee=!0,P.stalledCount+=1,P.automaticRestarts+=1,_e("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ce=await f(t);if(se||!ce)return;K=ce,jt();const Ne=performance.now();at=Ne,P.lastPacketAt=Ne,P.lastAcceptedAt=0,P.lastCaptureStatusAt=0,P.lastPcmAtEpochMs=0,P.captureAlive=null,P.helperAlive=null,P.helperReady=!1,P.captureHealthy=!1,P.captureStatusFailed=!1,P.captureAwaitingCurrentPcm=!1,P.captureAwaitingSinceAt=0,P.capturePhase="",P.backendKind="",P.helperRequired=!1,P.helperPid=0,P.nativeCallbackDiagnosticsAvailable=!1,P.nativeRejectedCallbackCount=0,P.nativeCurrentnessDropCount=0,P.nativeLastDropReason="",P.silentForMs=0,P.activeStreamId=K,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st(),me=Ne+(If[te+1]??3e3),Ze(""),se||_e("open")}catch(ce){se||(me=performance.now()+(If[te+1]??3e3),_e("error"),Ze(ce instanceof Error?"Remote audio restart failed: "+ce.message:"Remote audio restart failed."))}finally{Ee=!1}},ht=()=>{P.drops+=1},Je=window.setInterval(()=>{if(se)return;const te=performance.now(),ce=P.lastPacketAt>0?Math.max(0,te-P.lastPacketAt):at>0?Math.max(0,te-at):0,Ne=P.lastAcceptedAt>0?Math.max(0,te-P.lastAcceptedAt):0,He=P.lastCaptureStatusAt>0?Math.max(0,te-P.lastCaptureStatusAt):0,Ie=W.readyState===WebSocket.OPEN,Lt=P.lastCaptureStatusAt>0,Xe=Lt&&He<=xg&&P.captureHealthy,ut=Lt&&P.captureStatusFailed&&He>dN,yt=Lt&&He>xg,_t=!Lt&&at>0&&te-at>cw,mt=P.captureAwaitingCurrentPcm&&P.captureAwaitingSinceAt>0&&te-P.captureAwaitingSinceAt>cw,Vt=at>0&&(P.lastAcceptedAt<=0?te-at>dp:Ne>dp);if(Ie&&at>0&&(ut||yt||_t||mt)?Ge>=If.length&&!Ee?(_e("error"),Ze("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Ee&&te>=me?lt():Ee||_e("stalled"):Ie&&Vt&&!Ee&&P.audioContextState!=="suspended"&&P.audioContextState!=="interrupted"&&_e(Xe?"silent":"open"),T1({enabled:I.current,now:te,lastPublishedAt:ke})){ke=te,N({queuedMs:P.workletRingBufferedMs,browserAgeMs:P.browserAgeMs,captureAgeMs:P.captureAgeMs,captureStatusAgeMs:He,silentForMs:P.silentForMs,captureAlive:P.captureAlive,helperAlive:P.helperAlive,helperReady:P.helperReady,captureHealthy:P.captureHealthy,captureAwaitingCurrentPcm:P.captureAwaitingCurrentPcm,capturePhase:P.capturePhase,backendKind:P.backendKind,helperRequired:P.helperRequired,helperPid:P.helperPid,captureRestartCount:P.captureRestartCount,nativeCallbackDiagnosticsAvailable:P.nativeCallbackDiagnosticsAvailable,nativeRejectedCallbackCount:P.nativeRejectedCallbackCount,nativeCurrentnessDropCount:P.nativeCurrentnessDropCount,nativeLastDropReason:P.nativeLastDropReason,localProcessingAgeMs:P.localProcessingAgeMs,lastPacketAgeMs:ce,lastAcceptedAgeMs:Ne,framesReceived:P.framesReceived,drops:P.drops,resyncs:P.resyncs,pendingDecodes:P.pendingDecodes,lastFrameSeq:P.lastFrameSeq,audioContextState:P.audioContextState,stalledCount:P.stalledCount,automaticRestarts:P.automaticRestarts,maximumAcceptedGapMs:P.maximumAcceptedGapMs,workletRingCapacityBytes:P.workletRingCapacityBytes,workletRingBufferedBytes:P.workletRingBufferedBytes,workletRingDroppedFrames:P.workletRingDroppedFrames,workletRingUnderflowCount:P.workletRingUnderflowCount,lastUpdatedAt:Date.now()});const St=$.publish();St&&(et=!0,pa.setRetainedFrame(q,1,St.payload.byteLength),S(St))}else!I.current&&et&&(et=!1,$.clear(),pa.setRetainedFrame(q,0,0))},250);pa.setStatsTimer(q,Je);const be=()=>{O(),(String(D.state)==="suspended"||String(D.state)==="interrupted")&&ze()},je=()=>{document.visibilityState==="visible"&&ze()},Ae=()=>{ze()};D.addEventListener("statechange",be),document.addEventListener("visibilitychange",je),window.addEventListener("pageshow",Ae),window.addEventListener("pointerdown",Ae),window.addEventListener("keydown",Ae),_e("connecting"),Ze(""),O();const fe=(te,ce,Ne,He,Ie)=>{if(P.localProcessingAgeMs=Math.max(0,performance.now()-Ie),se||P.localProcessingAgeMs>ow||!lv(te,{deviceId:t,streamId:K}))return ht(),!1;P.activeStreamId!==K&&(P.activeStreamId=K,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st());const Lt=D1(te,{deviceId:t,streamId:K,lastFrameSeq:P.lastFrameSeq});if(!Lt.accepted||!Et(te,ce,Ne,He))return ht(),!1;P.browserAgeMs=uw(te.receivedAt),P.captureAgeMs=uw(te.capturedAt);const Xe=performance.now();P.lastAcceptedAt>0&&(P.maximumAcceptedGapMs=Math.max(P.maximumAcceptedGapMs,Xe-P.lastAcceptedAt)),P.lastAcceptedAt=Xe,P.framesReceived+=1,P.lastFrameSeq=Lt.nextFrameSeq,Ge=0,me=0,I.current&&($.accept(te),et=!0,pa.setRetainedFrame(q,1,0)),String(D.state)!=="running"&&ze();const ut=String(D.state)==="running";return ut&&Ze(""),_e(ut?"playing":"suspended"),!0};de=(te="")=>{if(!we){if(we=!0,te&&(pa.recordTerminalFailure(q,te,te.includes("setup failed")?"setup":"processor"),_e(te.includes("AudioWorklet is unavailable")?"unsupported":"error"),Ze(te),h?.(t,K,"browser-audio-playback-failed").catch(()=>{})),se=!0,pa.deactivate(q),window.clearInterval(Je),pa.setStatsTimer(q,null),D.removeEventListener("statechange",be),document.removeEventListener("visibilitychange",je),window.removeEventListener("pageshow",Ae),window.removeEventListener("pointerdown",Ae),window.removeEventListener("keydown",Ae),$.clear(),pa.setRetainedFrame(q,0,0),Z)try{Z.port.postMessage({type:"dispose"})}catch{}try{W.close()}catch{}W.readyState===WebSocket.CLOSED&&pa.setSocket(q,null),D.close().catch(()=>{}).finally(()=>{qe(),String(D.state)==="closed"&&pa.setAudioContext(q,null),X()}),g.current===D&&(g.current=null),X()}},We().catch(te=>{de(te instanceof Error?`Remote audio worklet setup failed: ${te.message}`:"Remote audio worklet setup failed.")}),W.addEventListener("open",()=>{se||(at=performance.now(),P.lastPacketAt=at,P.lastAcceptedAt=0,P.lastCaptureStatusAt=0,P.lastPcmAtEpochMs=0,P.captureAlive=null,P.helperAlive=null,P.helperReady=!1,P.captureHealthy=!1,P.captureStatusFailed=!1,P.captureAwaitingCurrentPcm=!1,P.captureAwaitingSinceAt=0,P.capturePhase="",P.backendKind="",P.helperRequired=!1,P.helperPid=0,P.maximumAcceptedGapMs=0,P.silentForMs=0,_e("open"),jt(),ze())}),W.addEventListener("message",te=>{if(typeof te.data=="string")return;const ce=te.data instanceof ArrayBuffer?te.data:null;if(!ce||ce.byteLength<5)return;const Ne=performance.now();P.lastPacketAt=Ne;try{const Ie=new DataView(ce).getUint32(0,!1);if(Ie<=0||Ie+4>ce.byteLength){ht();return}const Lt=new Uint8Array(ce,4,Ie),Xe=JSON.parse(Pv.decode(Lt)),ut=new Uint8Array(ce,4+Ie),yt=String(Xe.deviceId||""),_t=String(Xe.streamId||"");if(!lv({deviceId:yt,streamId:_t},{deviceId:t,streamId:K})){ht();return}const mt=String(Xe.frameKind||Xe.kind||"").toLowerCase();if(Xe.type==="remote.audio.status"||mt==="audio-status"){P.lastCaptureStatusAt=Ne;const St=I1(Xe);if(P.captureAlive=St.captureAlive,P.helperAlive=St.helperAlive,P.helperReady=St.helperReady,P.captureHealthy=St.healthy,P.captureStatusFailed=St.failed,P.captureAwaitingCurrentPcm=St.awaitingCurrentPcm,St.awaitingCurrentPcm?P.captureAwaitingSinceAt||=Ne:P.captureAwaitingSinceAt=0,P.capturePhase=St.capturePhase,P.backendKind=St.backendKind,P.helperRequired=St.helperRequired===!0,P.helperPid=St.helperPid,P.captureRestartCount=Math.max(0,Number(Xe.restartCount||0)||0),P.nativeCallbackDiagnosticsAvailable=Xe.callbackDiagnosticsAvailable===!0,P.nativeRejectedCallbackCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Xe.rejectedCallbackCount||0)||0):0,P.nativeCurrentnessDropCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Xe.currentnessDropCount||0)||0):0,P.nativeLastDropReason=P.nativeCallbackDiagnosticsAvailable?String(Xe.lastDropReason||""):"",P.lastPcmAtEpochMs=Math.max(0,Number(Xe.lastPcmAtEpochMs||0)||0),P.silentForMs=Math.max(0,Number(Xe.silentForMs||0)||0),P.captureAgeMs=P.lastPcmAtEpochMs>0?Math.max(0,Date.now()-P.lastPcmAtEpochMs):P.silentForMs,P.captureHealthy){if(Ge=0,me=0,!Ee){Ze("");const pn=String(D.state)==="running",rn=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp;_e(pn?rn?"playing":"silent":"suspended")}}else P.captureAwaitingCurrentPcm&&!Ee?_e("open"):P.captureStatusFailed&&!Ee&&_e("stalled");return}const Vt={deviceId:yt,frameSeq:Number(Xe.frameSeq||0),streamId:_t,mimeType:String(Xe.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Xe.sampleRate||48e3),channels:Number(Xe.channels||2),capturedAt:String(Xe.capturedAt||""),receivedAt:String(Xe.receivedAt||""),byteLength:Number(Xe.byteLength||ut.byteLength),payload:W0};if(!Vt.deviceId||se)return;if(performance.now()-Ne>ow){ht();return}if(E1(Vt.mimeType)){fe(Vt,ce,ut.byteOffset,ut.byteLength,Ne);return}ht(),_e("error"),Ze(`Unsupported remote audio format "${Vt.mimeType}". Requesting a bounded PCM restart.`),!Ee&&Ge<If.length&&(me=0,lt());return}catch(He){se||(_e("error"),Ze(He instanceof Error?He.message:String(He)))}}),W.addEventListener("error",()=>{se||(_e("error"),Ze("Remote audio WebSocket error."))}),W.addEventListener("close",()=>{pa.setSocket(q,null),X(),se||_e("closed")}),B=()=>{de()}});return F.ready.catch(H=>{_||(w("error"),j(H instanceof Error?`Remote audio owner setup failed: ${H.message}`:"Remote audio owner setup failed."))}),()=>{_=!0,B?B():F.cancel()}},[t,n,r,o,f,h]),{state:y,lastFrame:b,stats:k,error:A}}const mN=3;function dw(t,n,r){const o=Math.max(1,Number(r)||1),l=Math.max(0,Math.min(o,Number(t)-Number(n))),u=Math.min(o/2,mN);return l<=u?0:l>=o-u?1:l/o}function pN(t,n,r){return{normalizedX:dw(t,r.left,r.width),normalizedY:dw(n,r.top,r.height)}}const Kp=Object.freeze({shiftKey:Object.freeze(["ShiftLeft","ShiftRight"]),ctrlKey:Object.freeze(["ControlLeft","ControlRight"]),altKey:Object.freeze(["AltLeft","AltRight"]),metaKey:Object.freeze(["MetaLeft","MetaRight"])}),hN=Object.freeze({shiftKey:"ShiftLeft",ctrlKey:"ControlLeft",altKey:"AltLeft",metaKey:"MetaLeft"}),fw=Object.freeze({OSLeft:"MetaLeft",OSRight:"MetaRight"}),uv=64;function _v(t,n=80){return String(t||"").replace(/[\u0000-\u001f\u007f]/g,"").trim().slice(0,n)}function K0(t){const n=String(t??"");return n===" "?" ":_v(n)}function dv(t){const n=_v(t);return Object.prototype.hasOwnProperty.call(fw,n)?fw[n]:n}function Sg(t={}){const n=K0(t.key),r=Number(t.keyCode??t.which);if(n===" "||n==="Spacebar"||r===32)return"Space";const o=Number.isFinite(Number(t.location))?Math.max(0,Math.min(3,Math.trunc(Number(t.location)))):0,l=o===2?"Right":"Left";return n==="Shift"?`Shift${l}`:n==="Control"?`Control${l}`:n==="Alt"||n==="AltGraph"?`Alt${l}`:n==="Meta"||n==="OS"?`Meta${l}`:n?`Key:${o}:${n}`.slice(0,80):""}function fv(t={}){const n=dv(t.code);return["Shift","Control","Alt","AltGraph","Meta","OS"].includes(n)?Sg({...t,key:n}):n==="Unidentified"?Sg(t):n||Sg(t)}function Lp(t){for(const[n,r]of Object.entries(Kp))if(r.includes(t))return n;return""}function Yl(t,n){return Kp[n].some(r=>t.has(r))}function fp(t,n,r={},o="",l=""){for(const u of Object.keys(Kp)){const f=r[u]===!0,h=Kp[u];if(u===o){if(l==="keyup"&&!f)for(const g of h)n.has(g)||t.delete(g);continue}if(f){!Yl(t,u)&&t.size<uv&&t.add(hN[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function gN(t,n){if(t.length!==n.size)return!1;let r=0;for(const o of n){if(t[r]!==o)return!1;r+=1}return!0}function mw(t){for(const n of[...t])Lp(n)||t.delete(n)}function mv(t){return{shiftKey:Yl(t,"shiftKey"),ctrlKey:Yl(t,"ctrlKey"),altKey:Yl(t,"altKey"),metaKey:Yl(t,"metaKey")}}function vN(t={},n={}){return{shiftKey:t.shiftKey===!0||n.shiftKey===!0,ctrlKey:t.ctrlKey===!0||n.ctrlKey===!0,altKey:t.altKey===!0||n.altKey===!0,metaKey:t.metaKey===!0||n.metaKey===!0}}function yN(t,n,r){const o=fv(t),l=K0(t.key),u=Number(t.keyCode??t.which),f=Number(t.location);return{type:n,key:l,code:o,keyCode:Number.isFinite(u)?Math.max(0,Math.min(65535,Math.trunc(u))):0,location:Number.isFinite(f)?Math.max(0,Math.min(255,Math.trunc(f))):0,text:l.length===1?l:"",repeat:n==="keydown"&&t.repeat===!0,pressedCodes:[...r],...mv(r)}}function bN(){const t=new Set,n=new Set,r=()=>({pressedCodes:[...t]});return{event(o={},l=""){if(l!=="keydown"&&l!=="keyup")return null;const u=fv(o);if(!u)return null;const f=Lp(u),h=t.has(u),g=[...t];return f?l==="keydown"?(fp(t,n,o,f,l),t.size<uv&&t.add(u)):(n.has(u)||t.delete(u),fp(t,n,o,f,l)):(fp(t,n,o),l==="keydown"?t.size<uv&&t.add(u):t.delete(u)),l==="keyup"&&f==="metaKey"&&!Yl(t,"metaKey")&&mw(t),l==="keydown"&&h&&o.repeat!==!0&&gN(g,t)?null:yN(o,l,t)},modifier(o,l){const u=dv(o),f=Lp(u);if(!f)return null;const h=n.has(u);return l===h?null:(l?(n.add(u),t.add(u)):(n.delete(u),t.delete(u),f==="metaKey"&&!Yl(t,"metaKey")&&mw(t)),{type:l?"keydown":"keyup",key:f==="metaKey"?"Meta":f==="ctrlKey"?"Control":f==="altKey"?"Alt":"Shift",code:u,keyCode:0,location:u.endsWith("Right")?2:1,text:"",repeat:!1,...r(),...mv(t)})},reset(o="keyboard-owner-reset",l=!1){const u=t.size>0;return t.clear(),n.clear(),!u&&!l?null:{type:"keyboard.reset",reason:_v(o,120)||"keyboard-owner-reset",pressedCodes:[],shiftKey:!1,ctrlKey:!1,altKey:!1,metaKey:!1,repeat:!1}},isPressed(o={}){const l=typeof o=="string"?dv(o):fv(o);if(t.has(l))return!0;const u=Lp(l);return!!u&&Yl(t,u)},snapshot(){return{...r(),latchedCodes:[...n],...mv(t)}}}}const Q0=64,wN=2;function Y0(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(Q0,n)):1}function Fv(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(Q0-1,n)):0}function X0(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function xN(t,n,r){const o=String(n||"").trim();if(!o)return t||null;const l=String(r||"").trim();return t&&t.fingerprint===o&&(l?t.sampleId===l:t.sampleId==="")?t:{fingerprint:o,sampleId:l,consecutiveSamples:t?.fingerprint===o?t.consecutiveSamples+1:1}}function Z0({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return X0(t)?!!String(n||"").trim()&&Number(r)>=wN:!0}function SN({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:o,consecutiveTopologySamples:l}){const u=Fv(t),f=Y0(n);return u<f||!Z0({platform:r,topologyFingerprint:o,consecutiveTopologySamples:l})?u:f-1}function CN(t,n,r){const o=Fv(t),l=Y0(n);return o<l||X0(r)?o:l-1}function sc(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function ha(t){return String(t||"").trim()}function Cg(t,n,r={}){return{deviceId:ha(t),transitionGeneration:sc(n),sessionId:ha(r.sessionId),streamId:ha(r.streamId),commandId:ha(r.commandId),captureGeneration:sc(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Qn(t,n){return!!t&&!!n&&ha(t.deviceId)===ha(n.deviceId)&&sc(t.transitionGeneration)===sc(n.transitionGeneration)}function pw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:o}){const l=ha(t),u=sc(n),f=sc(r);return!!l&&u>0&&u===f&&(!o||ha(o.deviceId)===l)}function hw(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function mp(t,n,r){const o=ha(t);return!o||!n||ha(n.deviceId)!==o?!1:!r||ha(r.deviceId)!==o}function kg(t,n){if(!t||!n)return!1;const r=sc(n.captureGeneration),o=ha(n.commandId),l=ha(n.sessionId),u=ha(n.streamId),f=Number(t.monitorIndex);return!r||!o||!l||!u||!Number.isInteger(f)||f<0?!1:ha(t.deviceId)===ha(n.deviceId)&&ha(t.sessionId)===l&&ha(t.streamId)===u&&ha(t.commandId)===o&&sc(t.captureGeneration)===r&&ha(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}const kN=820,MN=500,gw=`(max-width: ${kN}px), (orientation: landscape) and (max-height: ${MN}px) and (pointer: coarse)`,AN="1200px 0px 1800px 0px",NN=960,TN=540,RN=68;function jN(t,n,r,o){return/iPad|iPhone|iPod/i.test(String(t||""))||n==="MacIntel"&&Number(r)>1||typeof o=="boolean"}function EN(t,n){const r=t&&typeof t=="object"?t:{},o={fps:Math.max(1,Math.floor(Number(r.fps)||1)),maxWidth:Math.max(1,Math.floor(Number(r.maxWidth)||1)),maxHeight:Math.max(1,Math.floor(Number(r.maxHeight)||1)),quality:Math.max(1,Math.min(100,Math.floor(Number(r.quality)||1)))};return n?{...o,maxWidth:Math.min(o.maxWidth,NN),maxHeight:Math.min(o.maxHeight,TN),quality:Math.min(o.quality,RN)}:o}function DN(t,n){return!n||!t||typeof t.closest!="function"?null:t.closest(".desk-stage")}function vw(t,n,r){return!!(t||n&&r)}function IN(t,n,r,o=!1,l=o){const u=Number(t?.height),f=Number(n),h=Number(t?.offsetTop),g=o&&Number.isFinite(f)&&f>0,y=g?0:Number.isFinite(h)?Math.max(0,Math.round(h)):0,w=g?f:Number.isFinite(u)&&u>0?u:Number.isFinite(f)&&f>0?f:1,b=Number(t?.width),S=Number(r),k=l&&Number.isFinite(S)&&S>0,N=k?S:Number.isFinite(b)&&b>0?b:Number.isFinite(S)&&S>0?S:1,A=Number(t?.offsetLeft);return{height:Math.max(1,Math.round(w)),width:Math.max(1,Math.round(N)),offsetTop:y,offsetLeft:k?0:Number.isFinite(A)?Math.max(0,Math.round(A)):0}}function LN(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function PN(){let t=Promise.resolve(),n=Promise.resolve();const r=o=>{const l=LN(t,o);return t=l.tail,l.result};return{enqueue:r,enqueueStop(o){const l=r(o);return n=l.then(()=>{}),n.catch(()=>{}),l},enqueueStart(o){const l=n;return r(async()=>(await l,o()))}}}function _N(t={}){return Number(t.generation)===Number(t.currentGeneration)&&t.enabled===!0&&String(t.deviceId||"")!==""&&String(t.deviceId||"")===String(t.currentDeviceId||"")&&t.documentVisible===!0&&t.presentationVisible===!0&&String(t.streamId||"")!==""&&String(t.streamId||"")===String(t.currentStreamId||"")}function FN(t={}){const n=t.ok!==!1,r=n&&t.staleOwner===!0;return{confirmed:n&&(r||t.captureStopConfirmed===!0||t.alreadyStopped===!0),staleOwner:r,preserveNewerOwner:r&&(t.retainedNewerOwner===!0||String(t.activeStreamId||"")!=="")}}const Xn=Object.freeze({automaticDirectH264:!0,interactiveDirectFps:20,slowWallFps:5,fastWallFps:20,directPopulationThrottle:!1,adaptiveMinimumCurrentSampleMs:750,adaptiveDownshiftStableMs:6e3,adaptiveDownshiftConsecutiveSamples:3,missingDeliveryRatio:.72,recoveryDeliveryRatio:.88,recoveryByteRatio:.52,recoveryGapRatio:.7,controlWallReuseMaxFps:24,controlWallReuseStarvationFactor:1.5,scalableAtlasMinInputFps:8,scalableAtlasMaxInputFps:20,scalableAtlasAggregateInputFps:120,atlasOutputFps:20,directDecodeAcceleration:"prefer-hardware",directLatencyMode:"interactive"});function pv(t){return t==="slow"?Xn.slowWallFps:Xn.fastWallFps}function yw({paintStale:t,lastRecoveryAt:n,now:r,recoveryCooldownMs:o,transportRecoveryAfterMs:l}){if(t!==!0)return"none";const u=Math.max(0,Number(r)||0),f=Math.max(0,Number(n)||0),h=f>0?u-f:Number.POSITIVE_INFINITY;return f>0&&h>=Math.max(1,Number(l)||1)?"recover-transport":f<=0||h>=Math.max(1,Number(o)||1)?"reset-decoder":"wait"}function bw({lastReceivedAt:t,lastPaintedAt:n,now:r,staleAfterMs:o}){const l=Math.max(0,Number(t)||0);if(l<=0)return!1;const u=Math.max(0,Number(n)||0),f=u>0?u:l;return Math.max(0,Number(r)||0)-f>Math.max(1,Number(o)||1)}function ON(t){return t==="share-files"||t==="agents"}function BN({captureOwnershipActive:t,localFeatureAccess:n,controlSessionDeviceId:r,planAllowed:o,sessionState:l,controlFocusVisible:u,presentationCanvasMounted:f,wallPresentationVisible:h,wallPresentationCanvasMounted:g,decoderOwnerExists:y}){const w=l==="connecting"||l==="active"||l==="warm";return t!==!0||n!==!0||!String(r||"").trim()||o!==!0||!w?!1:y===!0||u===!0&&f===!0||h===!0&&g===!0}function HN({decodeWidth:t,decodeHeight:n,presentationCssWidth:r,presentationCssHeight:o,devicePixelRatio:l,sourceWidth:u,sourceHeight:f}){const h=Math.max(0,Number(t)||0),g=Math.max(0,Number(n)||0),y=Math.max(0,Number(r)||0),w=Math.max(0,Number(o)||0),b=Math.max(1,Math.min(2,Number(l)||1)),S=Math.max(0,Number(u)||0),k=Math.max(0,Number(f)||0);if(h<=0||g<=0||y<=0||w<=0||S<=0||k<=0)return!1;const N=y*b,A=w*b,j=Math.min(1,N/S,A/k),I=Math.max(1,Math.round(S*j)),T=Math.max(1,Math.round(k*j));return h<I*.9||g<T*.9}function zN({cadenceCredit:t,targetFps:n,sourceFps:r,elapsedSincePaintMs:o=0,nowMs:l=0,scheduledPaintAtMs:u=0,force:f=!1}){const h=Math.max(1,Number(n)||1),g=Math.max(1,Number(r)||1);if(h>=g)return{shouldPaint:!0,nextCadenceCredit:0,sourceCadencePassthrough:!0,nextScheduledPaintAtMs:0};const y=Math.max(0,Number(l)||0),w=Math.max(0,Number(u)||0),b=y>0&&w>0,S=1e3/h,k=Math.min(S/3,1e3/g*.5),N=Number.isFinite(Number(t))?Math.max(0,Math.min(g-Number.EPSILON,Number(t))):0;if(f)return{shouldPaint:!0,nextCadenceCredit:N,sourceCadencePassthrough:!1,nextScheduledPaintAtMs:b?w:y>0?y+S:0};const A=N+h,j=A>=g,I=1e3/h*Xn.controlWallReuseStarvationFactor,T=!j&&Number(o)>=I,_=b&&y+k>=w,B=b?_||T:j||T;let F=w;return B&&y>0&&(!b||T?F=y+S:(F=w+S,F<=y-S&&(F=y+S))),{shouldPaint:B,nextCadenceCredit:T?0:j&&B?A-g:Math.min(g-Number.EPSILON,A),sourceCadencePassthrough:!1,deadlineForced:T,scheduleSelected:_,nextScheduledPaintAtMs:F}}function $N(t,n){const r=Number.isFinite(Number(n))?Math.max(0,Math.floor(Number(n))):Number.POSITIVE_INFINITY;if(r<=0)return[];const o=(Array.isArray(t)?t:[]).filter(f=>f&&String(f.deviceId||"").trim()).slice().sort((f,h)=>{const g=Number.isFinite(Number(f.slotNumber))?Number(f.slotNumber):Number.MAX_SAFE_INTEGER,y=Number.isFinite(Number(h.slotNumber))?Number(h.slotNumber):Number.MAX_SAFE_INTEGER;return g!==y?g-y:String(f.deviceId).localeCompare(String(h.deviceId))}),l=[],u=new Set;for(const f of o){const h=String(f.deviceId).trim();if(!u.has(h)&&(u.add(h),l.push(h),l.length>=r))break}return l}function UN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function Lf({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function qN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:o,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function WN({directDeviceCount:t,requestedFps:n,measuredFramesPerSecond:r,measuredPaintFramesPerSecond:o,measuredBytesPerSecond:l,maxBytesPerSecond:u,worstReceiveGapMs:f,worstPaintP95Ms:h,maxFrameGapMs:g}){const y=Math.max(1,Math.floor(Number(t)||1)),w=Math.max(1,Number(n)||1),b=Math.max(0,Number(r)||0),S=Math.max(0,Number(o)||0),k=Math.max(0,Number(l)||0),N=Math.max(1,Number(u)||1),A=Math.max(0,Number(f)||0),j=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),T=y*w,_=T>8&&b<T*Xn.missingDeliveryRatio,B=T>8&&S<T*Xn.missingDeliveryRatio,F=k>N||A>I||_||B,H=b>=T*Xn.recoveryDeliveryRatio&&S>=T*Xn.recoveryDeliveryRatio&&k<N*Xn.recoveryByteRatio&&A<I*Xn.recoveryGapRatio&&j<I*Xn.recoveryGapRatio;return{expectedFramesPerSecond:T,estimatedMissingFrames:_,estimatedMissingPaints:B,overloaded:F,healthyForRecovery:H}}function GN({receiveSampleMs:t,paintSampleMs:n,currentGenerationVerified:r,frameRequestedFps:o,adaptiveFps:l}){const u=Number(t),f=Number(n),h=Number(o),g=Number(l);return r===!0&&Number.isFinite(u)&&u>=Xn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Xn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function VN({deviceCount:t,targetFps:n,adaptive:r=!0}){const o=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Xn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Xn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Xn.scalableAtlasMinInputFps,Math.min(Xn.scalableAtlasMaxInputFps,Math.floor(Xn.scalableAtlasAggregateInputFps/o)));return Math.min(l,u)}function KN(t,n){return{acceleration:Xn.directDecodeAcceleration,latencyMode:Xn.directLatencyMode}}const eu={revision:0,settings:{security:{accessMode:"trusted-only"},control:{allowKeyboardMouse:!0,allowRemoteRestart:!1},filesAudio:{allowFileTransfer:!0,allowRemoteAudio:!0,rollingBufferEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0}}},QN=[{id:"connection",label:"Connection",icon:eh},{id:"remote-access",label:"Remote Access",icon:ga},{id:"capture-audio",label:"Capture & Audio",icon:Gg},{id:"agent",label:"Agent",icon:ec}];function Pp(t,n){return t?.settings?.[n]||eu.settings[n]||{}}function ww(t,n){return{...t,settings:{...t.settings,[n.section]:{...Pp(t,n.section),[n.key]:n.value}}}}function Mg(t){return{revision:Number(t.revision||0),updatedAt:t.updatedAt,settings:t.settings}}function Kc({icon:t,title:n,description:r,children:o,recommended:l=!1}){return i.jsxs("div",{className:"product-setting-row",children:[i.jsx("div",{className:"product-setting-control",children:o}),t&&i.jsx("span",{className:"product-setting-icon",children:i.jsx(t,{size:17})}),i.jsxs("div",{className:"product-setting-copy",children:[i.jsx("strong",{children:n}),l&&i.jsx("em",{children:"Recommended"}),i.jsx("small",{children:r})]})]})}function Pf({checked:t,onChange:n,label:r}){return i.jsxs("label",{className:"product-switch",children:[i.jsx("input",{"aria-label":r,type:"checkbox",checked:t,onChange:o=>n(o.target.checked)}),i.jsx("span",{})]})}function xw({value:t,onChange:n,options:r,label:o}){return i.jsx("select",{"aria-label":o,value:String(t),onChange:l=>n(l.target.value),children:r.map(([l,u])=>i.jsx("option",{value:l,children:u},l))})}function YN({hubUrl:t="",runtimeRole:n="hub",runtimeDeviceId:r="",sessionAccessToken:o="",initialTab:l="connection",pin:u,agent:f,captureGallery:h}){const[g,y]=d.useState(l),[w,b]=d.useState(null),[S,k]=d.useState("loading"),[N,A]=d.useState(""),[j,I]=d.useState("idle"),[T,_]=d.useState(""),B=d.useRef(null),F=d.useRef(null),H=d.useRef([]),D=d.useRef(Promise.resolve()),K=d.useRef(0),z=d.useRef(0);d.useEffect(()=>{const Se=++z.current;let ae=!0;return H.current=[],F.current=null,B.current=null,D.current=Promise.resolve(),k("loading"),rt("/api/settings",void 0,t).then(ye=>{if(!ae||Se!==z.current)return;const Pe=Mg(ye);F.current=Pe,B.current=Pe,b(Pe),k("saved")}).catch(ye=>{!ae||Se!==z.current||(A(ye instanceof Error?ye.message:String(ye)),F.current=eu,B.current=eu,b(eu),k("failed"))}),()=>{ae=!1}},[t]);const W=async(Se,ae,ye)=>{const Pe={id:++K.current,section:Se,key:ae,value:ye},de=z.current;H.current.push(Pe);const Qe=ww(B.current||F.current||eu,Pe);B.current=Qe,b(Qe),k("saving"),A(""),D.current=D.current.then(async()=>{if(de!==z.current)return;let ue=null,_e=null;for(let Ee=0;Ee<2&&!ue;Ee+=1){const Ge=F.current||eu;try{const me=await rt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:Ge.revision,[Pe.section]:{[Pe.key]:Pe.value}})},t);ue=Mg(me)}catch(me){if(_e=me,Ee!==0||!String(me instanceof Error?me.message:me).startsWith("409 "))break;try{const ke=await rt("/api/settings",void 0,t);if(de!==z.current)return;F.current=Mg(ke)}catch(ke){_e=ke;break}}}if(de!==z.current)return;H.current=H.current.filter(Ee=>Ee.id!==Pe.id),ue&&(F.current=ue);const Ze=F.current||eu,at=H.current.reduce(ww,Ze);B.current=at,b(at),ue?(A(""),k(H.current.length>0?"saving":"saved")):(k(H.current.length>0?"saving":"failed"),A(_e instanceof Error?_e.message:String(_e||"Settings could not be saved.")))}),await D.current},q=(Se,ae)=>ye=>{W(Se,ae,ye)},V=async()=>{if(n!=="hub"||!r||!o){I("failed"),_("Sign in to this Hub before changing its runtime role.");return}I("changing"),_("");try{const Se=await rt("/api/runtime/status",void 0,t);await rt("/api/runtime/role",{method:"POST",headers:{Authorization:`Bearer ${o}`},body:JSON.stringify({role:"client"})},t),I("accepted"),await c0({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),$M(5179)}catch(Se){I("failed"),_(Se instanceof Error?Se.message:String(Se))}},X=Pp(w,"security"),ve=Pp(w,"control"),J=Pp(w,"filesAudio"),$=`settings-panel-${g}`,P=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[u,i.jsxs("section",{className:"settings-section-card runtime-role-settings",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Runtime role"}),i.jsx("h3",{children:"Use this computer as a Client"})]}),i.jsx(Kx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),j==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):T?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:T}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{V()},disabled:j==="changing"||n!=="hub",type:"button",children:j==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),se=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Remote access"}),i.jsx("h3",{children:"Who may connect?"})]}),i.jsx(nl,{size:20})]}),i.jsx(Kc,{icon:ga,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(xw,{value:String(X.accessMode),onChange:q("security","accessMode"),label:"Access mode",options:[["trusted-only","Trusted devices only"],["block-remote-access","Block remote access"]]})})]}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Session permissions"}),i.jsx("h3",{children:"What may remote users do?"})]}),i.jsx(Ar,{size:20})]}),i.jsx(Kc,{icon:Ar,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(Pf,{checked:!!ve.allowKeyboardMouse,onChange:q("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(Kc,{icon:Vx,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:i.jsx(Pf,{checked:!!ve.allowRemoteRestart,onChange:q("control","allowRemoteRestart"),label:"Power actions"})}),i.jsx(Kc,{icon:Gg,title:"File transfer",description:"Allow files to be delivered to connected computers.",children:i.jsx(Pf,{checked:!!J.allowFileTransfer,onChange:q("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(Kc,{icon:Jl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(Pf,{checked:!!J.allowRemoteAudio,onChange:q("filesAudio","allowRemoteAudio"),label:"Remote audio"})})]})]}),we=i.jsxs("div",{className:"settings-tab-content product-settings-content",children:[i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Capture"}),i.jsx("h3",{children:"Recording defaults"})]}),i.jsx(Gg,{size:20})]}),i.jsx(Kc,{icon:Jl,title:"Keep a Last 30s buffer",description:"Keep recent video in memory until you explicitly save it.",children:i.jsx(Pf,{checked:!!J.rollingBufferEnabled,onChange:q("filesAudio","rollingBufferEnabled"),label:"Keep a Last 30s buffer"})}),i.jsx(Kc,{icon:Jl,title:"Timelapse interval",description:"Choose how often a timelapse frame is captured.",children:i.jsx(xw,{value:Number(J.timelapseIntervalSeconds),onChange:Se=>q("filesAudio","timelapseIntervalSeconds")(Number(Se)),label:"Timelapse interval",options:[["5","5 seconds"],["10","10 seconds"],["30","30 seconds"],["60","60 seconds"]]})})]}),h]}),Z=g==="connection"?P:g==="remote-access"?se:g==="capture-audio"?we:f;return i.jsxs("section",{className:"settings-page",children:[i.jsx("div",{className:"settings-page-tabs",role:"tablist","aria-label":"LiveDesk settings",children:QN.map(({id:Se,label:ae,icon:ye})=>i.jsxs("button",{className:g===Se?"active":"",id:`settings-tab-${Se}`,role:"tab","aria-selected":g===Se,"aria-controls":`settings-panel-${Se}`,tabIndex:g===Se?0:-1,onClick:()=>y(Se),type:"button",children:[i.jsx(ye,{size:16}),ae]},Se))}),S==="saving"&&i.jsx("div",{className:"product-save-state",role:"status",children:"Saving settings..."}),N&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:N}),i.jsx("section",{className:"settings-page-panel",id:$,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Z})]})}function XN({children:t}){return i.jsx("div",{className:"settings-tab-content",children:t})}const Sw={enabled:!1};function Cw(t){return{enabled:t?.enabled===!0}}async function ZN(t,n,r){let o=null;for(let l=0;l<2;l+=1){const u=await rt("/api/settings",{signal:r},n);if(u.settings.agent?.enabled===t)return;try{await rt("/api/settings",{method:"PATCH",signal:r,body:JSON.stringify({revision:u.revision,agent:{enabled:t}})},n);return}catch(f){if(o=f,l!==0||!String(f instanceof Error?f.message:f).startsWith("409 "))throw f}}throw o}function JN({hubUrl:t,showToast:n}){const[r,o]=d.useState(Sw),[l,u]=d.useState(null),[f,h]=d.useState(""),[g,y]=d.useState(""),[w,b]=d.useState(""),S=d.useRef(0),k=d.useRef(null);d.useEffect(()=>{let H=!0;k.current?.abort();const D=new AbortController;k.current=D;const K=++S.current;return u(null),o(Sw),h(""),b(""),y(""),rt("/api/settings/agent",{signal:D.signal},t).then(z=>{!H||D.signal.aborted||K!==S.current||(u(z.settings),o(Cw(z.settings)))}).catch(z=>{H&&!D.signal.aborted&&K===S.current&&b(z instanceof Error?z.message:String(z))}),()=>{H=!1,D.abort(),k.current===D&&(k.current=null)}},[t]);const N=(H,D)=>o(K=>({...K,[H]:D})),A=H=>{u(H),o(Cw(H))},j=()=>({generation:S.current,controller:k.current}),I=H=>H.generation===S.current&&H.controller!==null&&H.controller===k.current&&!H.controller.signal.aborted,T=async()=>{if(!l){b("Agent settings are not available yet.");return}const H=j();if(I(H)){h("save"),b(""),y("");try{if(await ZN(r.enabled,t,H.controller.signal),!I(H))return;const D=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(D.settings),y("Codex Agent settings saved.")}catch(D){I(H)&&b(D instanceof Error?D.message:String(D))}finally{I(H)&&h("")}}},_=async()=>{const H=j();if(I(H)){h("test"),b(""),y("");try{const D=await rt("/api/settings/agent/test",{method:"POST",signal:H.controller.signal,body:JSON.stringify({})},t);if(!I(H))return;const K=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(K.settings);const z=Number.isFinite(D.connection?.latencyMs)?Math.max(0,Math.round(D.connection.latencyMs)):null;n(`Codex Agent connection verified${z!==null?` in ${z} ms.`:"."}`,"success")}catch(D){I(H)&&b(D instanceof Error?D.message:String(D))}finally{I(H)&&h("")}}},B=l?.codexInstallation==="installed"&&l.codexAuth==="signed-in",F=l!==null;return i.jsxs("div",{className:"settings-tab-content agent-settings-content",children:[i.jsx("section",{className:"settings-section-card agent-enable-card",children:i.jsxs("label",{className:"settings-toggle agent-enable-toggle",children:[i.jsx("input",{type:"checkbox",checked:r.enabled,onChange:H=>N("enabled",H.target.checked),disabled:!F||f!==""}),i.jsx("span",{children:"Enable Codex Agent"})]})}),w&&i.jsx("div",{className:"agent-settings-alert error",role:"alert",children:w}),g&&i.jsx("div",{className:"agent-settings-alert success",role:"status",children:g}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Connection"}),i.jsx("h3",{children:"Codex SDK / CLI"})]}),i.jsx(ga,{size:20})]}),i.jsxs("div",{className:"agent-connection-row",children:[i.jsx("span",{className:`agent-connection-dot ${B?"connected":l?.codexAuth==="not-signed-in"?"unavailable":""}`}),i.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"}),i.jsxs("button",{className:"settings-reset",onClick:()=>{_()},disabled:f!=="",type:"button",children:[i.jsx(gk,{size:15})," ",f==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(vk,{size:12})," The Hub uses the installed Codex SDK / CLI to plan approved commands and run them through LiveDesk Agent tools on selected computers."]})]}),i.jsx("div",{className:"settings-action-row agent-settings-actions",children:i.jsxs("button",{className:"text-button primary",onClick:()=>{T()},disabled:!F||f!=="",type:"button",children:[i.jsx(yk,{size:15})," ",f==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function po(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function Ov(t,n){return typeof t=="function"?typeof n=="object"?t(n):t():t}function Id(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function eT(t,n="data-id"){const r=Id(t,n);return r?r.getAttribute(n):null}function rm(t,n="data-id"){const r=Id(t,n);return r?uh(r,n):null}function uh(t,n="data-id"){const r=t.getAttribute(n);return r?tT(r):null}function Fa(t){return typeof t=="string"?":"+t:t}function tT(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function nT(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var cs=nT();function Bv(t){Object.assign(cs,t)}function kw(t,n,r){function o(l){const u=Id(l);if(!u)return;const f=uh(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}cs.addEvent(t,r,o)}function Ld(t,n){kw(t,n,"click"),n.dblclick&&kw(t,n.dblclick,"dblclick")}function aT(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function rT(t,n,r){for(let o=0;o<rl.length;o++){if(o===r)continue;const l=rl[o],u=l.props.parent?.();if(u&&t.contains(u)&&l.node.contains(n))return!0}return!1}var J0=new Date,Qp=!1,pp=[],rl=[],Mw=t=>{const n=t.target;if(Qp||!n.isConnected){Qp=!1;return}for(let r=rl.length-1;r>=0;r--){const{node:o,date:l,props:u}=rl[r];if(!(l>J0)&&!o.contains(n)&&o!==n&&(rT(o,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},sT=t=>{J0=new Date,Qp=!0;for(let n=rl.length-1;n>=0;n--){const{node:r}=rl[n];if(!r.contains(t.target)&&r!==t.target){Qp=!1;break}}};function ho(t,n){pp.length||(pp=[cs.addGlobalEvent("click",Mw,t),cs.addGlobalEvent("contextmenu",Mw,t),cs.addGlobalEvent("mousedown",sT,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return rl.push(r),{destroy(){aT(rl,r),rl.length||(pp.forEach(o=>o()),pp=[])}}}var hp=t=>t.indexOf("bottom")!==-1,gp=t=>t.indexOf("left")!==-1,vp=t=>t.indexOf("right")!==-1,Ag=t=>t.indexOf("top")!==-1,Aw=t=>t.indexOf("fit")!==-1,_f=t=>t.indexOf("overlap")!==-1,iT=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),oT=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function lT(t,n){let r=0;const o=cs.getTopNode(t);for(;t&&t!==o;){const l=getComputedStyle(t).position;if((l==="absolute"||l==="relative"||l==="fixed")&&(r=parseInt(getComputedStyle(t).zIndex)||0),t=t.parentNode,t===n)break}return r}var ma,Cr,Ff,ar;function eS(t,n,r="bottom",o=0,l=0){if(!t)return null;ma=o,Cr=l,Ff="auto";let u=0,f=0,h=r;const g=tS(t),y=_f(r)?cs.getTopNode(t):g;if(!g)return null;const w=g.getBoundingClientRect(),b=t.getBoundingClientRect(),S=y.getBoundingClientRect(),k=window.getComputedStyle(y),N={left:0,top:0,bottom:0,right:0};for(const B in N){const F=`border-${B}-width`;N[B]=parseFloat(k.getPropertyValue(F))}if(n){const B=lT(n,g);u=Math.max(B+1,20)}if(n){if(ar=n.getBoundingClientRect(),Aw(r)&&(Ff=ar.width+"px"),r!=="point")if(iT(r))Aw(r)?ma=0:(ma=S.width/2,f=1),Cr=(S.height-b.height)/2;else{const B=_f(r)?0:1;ma=vp(r)?ar.right+B:ar.left-B,Cr=hp(r)?ar.bottom+1:ar.top;const F=oT(r);F&&(vp(r)||gp(r)?F==="center"?Cr-=(b.height-ar.height)/2:F==="end"&&(Cr-=b.height-ar.height):(hp(r)||Ag(r))&&(F==="center"?ma-=(b.width-ar.width)/2:F==="end"&&(ma-=b.width-ar.width),_f(r)||(ma+=1)))}}else ar={left:o,right:o,top:l,bottom:l};const A=(gp(r)||vp(r))&&(hp(r)||Ag(r));gp(r)&&(f=2);const j=ma-b.width-S.left;n&&gp(r)&&!A&&j<0&&(ma=ar.right,f=0,h=h.replace("left","right"));const I=ma+b.width*(1-f/2)-S.right;if(I>0)if(!vp(r))ma=S.right-N.right-b.width;else{const B=ar.left-S.x-b.width;n&&!A&&B>=0?(ma=ar.left-b.width,h=h.replace("right","left")):ma-=I+N.right}f&&(ma=Math.round(ma-b.width*f/2));const T=j<0||I>0||!A;Ag(r)&&(Cr=ar.top-b.height,n&&Cr<S.y&&T&&(Cr=ar.bottom,h=h.replace("top","bottom")));const _=Cr+b.height-S.bottom;return _>0&&(n&&hp(r)&&T?(Cr-=b.height+ar.height+1,h=h.replace("bottom","top")):Cr-=_+N.bottom),ma-=w.left+N.left,Cr-=w.top+N.top,ma=(_f(r)?ma:Math.max(ma,0))+y.scrollLeft,Cr=(_f(r)?Cr:Math.max(Cr,0))+y.scrollTop,Ff=Ff||"auto",{at:h,x:ma,y:Cr,z:u,width:Ff}}function tS(t){const n=cs.getTopNode(t);for(t&&(t=t.parentElement);t;){const r=getComputedStyle(t).position;if(t===n||r==="relative"||r==="absolute"||r==="fixed")return t;t=t.parentNode}return null}function cT(t){const n=[];let r=t;const o=cs.getTopNode(t);for(;r&&r!==o&&!r.getAttribute("data-wx-portal-root");)getComputedStyle(r).position==="absolute"&&n.push(r),r=r.parentNode;return n}var Nw=new Date().valueOf();function Hv(){return Nw+=1,Nw}function Mr(t){return t<10?"0"+t:t.toString()}function uT(t){const n=Mr(t);return n.length==2?"0"+n:n}function nS(t){const n=Math.floor(t/11)*11;return{start:n,end:n+11}}function Ng(t){const n=(t.getDay()+6)%7,r=new Date(t.valueOf());r.setDate(t.getDate()+(3-n)),r.setHours(0,0,0,0);const o=new Date(r.getFullYear(),0,1),l=Math.round((r.getTime()-o.getTime())/864e5);return 1+Math.floor(l/7)}var Tw=["",""];function dT(t,n,r){switch(t){case"%d":return Mr(n.getDate());case"%m":return Mr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return Mr(n.getFullYear()%100);case"%Y":return n.getFullYear();case"%D":return r.dayShort[n.getDay()];case"%l":return r.dayFull[n.getDay()];case"%M":return r.monthShort[n.getMonth()];case"%F":return r.monthFull[n.getMonth()];case"%h":return Mr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return Mr(n.getHours());case"%i":return Mr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||Tw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||Tw)[1];case"%s":return Mr(n.getSeconds());case"%S":return uT(n.getMilliseconds());case"%W":return Mr(Ng(n));case"%w":{const o=r.weekStart??1;if(o===1)return Mr(Ng(n));const l=(n.getDay()-o+7)%7,u=(1-o+7)%7,f=new Date(n.valueOf());return f.setDate(n.getDate()+(u-l)),Mr(Ng(f))}case"%c":{let o=n.getFullYear()+"";return o+="-"+Mr(n.getMonth()+1),o+="-"+Mr(n.getDate()),o+="T",o+=Mr(n.getHours()),o+=":"+Mr(n.getMinutes()),o+=":"+Mr(n.getSeconds()),o}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var fT=/%[a-zA-Z]/g;function Td(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(fT,o=>dT(o,r,n))):""}}function Rw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function hv(t,n){for(const r in n){const o=n[r];Rw(t[r])&&Rw(o)?t[r]=hv({...t[r]},n[r]):t[r]=n[r]}return t}function lm(t){return{getGroup(n){const r=t[n];return o=>r&&r[o]||o},getRaw(){return t},extend(n,r){if(!n)return this;let o;return r?o=hv({...n},t):o=hv({...t},n),lm(o)}}}var mT=a0();const pT="en-US",hT={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},gT={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},vT={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},aS={core:gT,calendar:hT,formats:vT,lang:pT},zv=d.createContext(""),rS=d.createContext({}),Mi=d.createContext(null),sS=d.createContext(null),Ba=Object.freeze(Object.defineProperty({__proto__:null,fieldId:sS,helpers:rS,i18n:Mi,theme:zv},Symbol.toStringTag,{value:"Module"}));function iS(t){const n=d.useContext(sS),[r]=d.useState(()=>t||n||Hv());return r}function Jf({type:t="",css:n="",icon:r="",disabled:o=!1,title:l="",tooltip:u,text:f="",children:h,onClick:g}){const y=d.useMemo(()=>{let b=t?t.split(" ").filter(S=>S!=="").map(S=>"wx-"+S).join(" "):"";return n+(n?" ":"")+b},[t,n]),w=b=>{g&&g(b)};return i.jsxs("button",{title:l,className:`wx-2ZWgb4 wx-button ${y} ${r&&!h?"wx-icon":""}`,disabled:o,onClick:w,"data-tooltip-text":u,children:[r&&i.jsx("i",{className:"wx-2ZWgb4 "+r}),h||f||" "]})}function yT({id:t,label:n="",inputValue:r="",value:o=!1,onChange:l,disabled:u=!1,css:f=""}){const h=iS(t),[g,y]=po(o),w=({target:b})=>{const S=b.checked;y(S),l&&l({value:S,inputValue:r})};return i.jsxs("div",{className:`wx-2IvefP wx-checkbox ${f}`,children:[i.jsx("input",{type:"checkbox",id:h,disabled:u,className:"wx-2IvefP wx-check",checked:g,value:r,onChange:w}),i.jsxs("label",{htmlFor:h,className:"wx-2IvefP wx-label",children:[i.jsx("span",{className:"wx-2IvefP wx-before"}),n&&i.jsx("span",{className:"wx-2IvefP wx-after",children:n})]})]})}function $v({theme:t="",target:n,children:r}){const o=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(null);o.current||(o.current=document.createElement("div"));const h=d.useContext(zv);return d.useEffect(()=>{f(n||bT(l.current)||cs.getTopNode(l.current))},[l.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?mT.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function bT(t){const n=cs.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function wT({left:t=0,top:n=0,at:r="bottom",parent:o=null,width:l="auto",css:u="",onCancel:f,children:h,trackScroll:g=!1}){const[y,w]=d.useState(0),[b,S]=d.useState(0),[k,N]=d.useState("auto"),[A,j]=d.useState(!1),I=d.useRef(null),T=d.useRef(null),_=d.useRef(f);d.useEffect(()=>{_.current=f},[f]);function B(H){return o&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(D,K)=>(K=K*o.offsetWidth/100+"px",l.replace(D,K))):l&&l!=="auto"?l:H}const F=d.useCallback(()=>{if(!I.current)return;const H=eS(I.current,o,r,t,n);H&&(w(H.x),S(H.y),N(B(H.width)))},[I,o,r,t,n,l]);return d.useLayoutEffect(()=>{const H=K=>{_.current&&K.target!==T.current&&I.current&&!I.current.contains(K.target)&&_.current(K)};let D;return requestAnimationFrame(()=>{F(),j(!0),g&&I.current&&(T.current=tS(I.current),T.current&&T.current.addEventListener("scroll",H,!0)),o&&(D=new ResizeObserver(F),D.observe(o))}),()=>{g&&T.current&&T.current.removeEventListener("scroll",H,!0),D?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[o,r,t,n]),d.useEffect(()=>{const H=D=>{_.current&&_.current(D)};if(I.current)return ho(I.current,{callback:H,parent:()=>o}).destroy},[o]),i.jsx("div",{ref:I,className:["wx-37M6Fj","wx-popup",u].filter(Boolean).join(" "),style:{position:"absolute",visibility:A?"visible":"hidden",top:b+"px",left:y+"px",width:k},children:h})}function xT({position:t="bottom",align:n="start",autoFit:r=!0,onCancel:o=null,width:l="100%",css:u="",children:f}){const h=d.useRef(null),[g,y]=d.useState(t),[w,b]=d.useState(n),S=d.useRef(o);return d.useEffect(()=>{S.current=o},[o]),d.useEffect(()=>{if(r){const k=h.current;if(k){const N=k.getBoundingClientRect(),A=document.body.getBoundingClientRect();N.right>=A.right&&b("end"),N.bottom>=A.bottom&&y("top")}}},[]),d.useEffect(()=>{if(h.current){const k=N=>{S.current&&S.current(N)};return ho(h.current,k).destroy}},[]),i.jsx("div",{ref:h,className:["wx-dropdown",`wx-${g}-${w}`,u||"","wx-aaaVytZW"].filter(Boolean).join(" "),style:{width:l},children:f})}function Uv({position:t="bottom",align:n="start",autoFit:r=!0,inline:o=!1,onCancel:l,width:u="100%",children:f,...h}){const[g,y]=d.useState(void 0),w=d.useRef(null),b=d.useMemo(()=>`${t}-${n}`,[t,n]);return d.useLayoutEffect(()=>{w.current&&y(w.current.parentNode)},[]),i.jsxs(i.Fragment,{children:[g&&(o?i.jsx(xT,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):i.jsx($v,{children:i.jsx(wT,{parent:g,at:b,onCancel:l,width:u,...h,children:f})})),i.jsx("span",{ref:w,className:"wx-portal-node wx-32GZ52"})]})}function dh(){return lm(aS)}function ST(){let t=null,n=!1,r=!1,o,l,u,f;const h=(b,S,k,N,A)=>{o=b,l=S,u=k,f=N,r=A},g=b=>{t=b,n=t!==null,u(t)},y=(b,S)=>{if(!r&&b!==null&&o){const k=o.querySelectorAll(".wx-list > .wx-item")[b];k&&(k.scrollIntoView({block:"nearest"}),S&&S.preventDefault())}},w=(b,S)=>{const k=b===null?null:Math.max(0,Math.min(t+b,l.length-1));k!==t&&(g(k),o?y(k,S):requestAnimationFrame(()=>y(k,S)))};return{move:b=>{const S=rm(b),k=l.findIndex(N=>N.id===S);k!==t&&g(k)},keydown:(b,S)=>{switch(b.code){case"Enter":n?f():g(0);break;case"Space":n||g(0);break;case"Escape":u(t=null);break;case"Tab":u(t=null);break;case"ArrowDown":w(n?1:S||0,b);break;case"ArrowUp":w(n?-1:S||0,b);break}},init:h,navigate:w}}const jw=10,CT=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:o}){return i.jsxs(i.Fragment,{children:[n&&i.jsx(yT,{id:t.id,css:"wx-list-checkbox",value:o&&o.includes(t.id)}),r?Ov(r,{option:t}):t.label]})});function Ew({visibleItems:t,visibleRange:n,navIndex:r,checkboxes:o,itemTemplate:l,value:u,measureRefCallback:f}){return t.map((h,g)=>{const y=n.start+g;return i.jsx("div",{ref:g===0?f:void 0,className:`wx-233fr7 wx-item ${y===r?"wx-focus":""}`,"data-id":h.id,children:i.jsx(CT,{data:h,checkboxes:o,itemTemplate:l,value:u})},h.id)})}function fh({items:t=[],children:n,onSelect:r,onReady:o,virtualized:l=!1,checkboxes:u,multiselect:f,value:h,...g}){const y=d.useRef(),w=d.useRef(!1),b=d.useRef(ST()),[S,k]=d.useState(null),N=d.useRef(S),[A,j]=d.useState(0),[I,T]=d.useState(24),_=d.useRef(!1),B=(d.useContext(Mi)||dh()).getGroup("core"),F=d.useRef(t);d.useEffect(()=>{F.current=t},[t]);const H=d.useRef(h);d.useEffect(()=>{H.current=h},[h]);const D=d.useRef(0);d.useEffect(()=>{D.current=I},[I]);const K=d.useCallback(ae=>{ae&&ae.stopPropagation();const ye=F.current,Pe=H.current,de=N.current;let Qe;const ue=ye[de]?.id;f?Pe&&Pe.includes(ue)?Qe=Pe.filter(_e=>_e!==ue):Qe=[...Pe||[],ue]:Qe=ue,r&&r({id:Qe})},[f,r]),z=d.useRef(K);d.useEffect(()=>{z.current=K},[K]);const W=d.useCallback(ae=>{if(y.current){let ye=ae*D.current-y.current.clientHeight+D.current;j(ye),y.current.scrollTop=ye}},[D.current]),q=d.useCallback(ae=>{y.current=ae,l&&(ae&&!w.current&&N.current!==null&&requestAnimationFrame(()=>{y.current&&(W(N.current),w.current=!0)}),ae||(w.current=!1))},[W]),V=d.useCallback(ae=>{if(!ae||_.current)return;const ye=ae.getBoundingClientRect().height;ye&&(T(ye),D.current=ye,_.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ae=>{k(ae),N.current=ae},ae=>z.current(ae),l)},[t,y.current,l]),d.useEffect(()=>{const ae=(Pe,de)=>{b.current.navigate(Pe,de),W(N.current)},ye=(Pe,de)=>{const Qe=N.current,ue=F.current;if(Qe!==0&&Qe!==ue.length-1&&(Pe.key==="ArrowDown"||Pe.key==="ArrowUp")&&Pe.preventDefault(),b.current.keydown(Pe,de),y.current){const _e=y.current.scrollTop<=N.current*D.current,Ze=y.current.scrollTop+y.current.clientHeight>=N.current*D.current+D.current;_e?Ze||W(N.current):(y.current.scrollTop=N.current*D.current,j(y.current.scrollTop))}};o&&o({navigate:l?ae:b.current.navigate,keydown:l?ye:b.current.keydown,move:b.current.move})},[]);const X=d.useRef(0),ve=d.useRef(t);ve.current!==t&&(ve.current=t,X.current+=1);const J=d.useCallback(()=>{b.current.navigate(null)},[b]),$=d.useCallback(ae=>{l&&j(ae.target.scrollTop)},[l]),P=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,A]),se=d.useMemo(()=>{if(!l)return{start:0,end:t.length};if(!t.length)return{start:0,end:0};const ae=Math.floor(A/I),ye=ae+P;return{start:Math.max(0,ae-jw),end:Math.min(t.length,ye+jw)}},[l,t,A,I,P]),we=d.useMemo(()=>{if(!l)return t;const{start:ae,end:ye}=se;return t.slice(ae,ye).map(Pe=>({...Pe}))},[l,t,se]),Z=se.start*I,Se=t.length*I;return d.useEffect(()=>{l&&j(0)},[t,l]),d.useEffect(()=>{S===null&&(w.current=!1)},[S]),S===null?null:i.jsx(Uv,{onCancel:J,...g,children:i.jsx("div",{className:"wx-233fr7 wx-list",ref:q,onClick:K,onMouseMove:b.current.move,onScroll:$,children:t.length?l?i.jsx("div",{className:"wx-233fr7 wx-list-wrapper",style:{height:`${Se}px`},children:i.jsx("div",{className:"wx-233fr7 wx-list-content",style:{transform:`translateY(${Z}px)`},children:i.jsx(Ew,{visibleRange:se,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h})})}):i.jsx(Ew,{visibleRange:se,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h}):i.jsx("div",{className:"wx-233fr7 wx-no-data",children:B("No data")})})},X.current)}function qv({value:t="",id:n,readonly:r=!1,focus:o=!1,select:l=!1,type:u="text",placeholder:f="",disabled:h=!1,error:g=!1,title:y="",tooltip:w,css:b="",icon:S="",clear:k=!1,onChange:N}){const A=iS(n),[j,I]=po(t),T=d.useRef(null),_=d.useMemo(()=>S&&b.indexOf("wx-icon-left")===-1?"wx-icon-right "+b:b,[S,b]),B=d.useMemo(()=>S&&b.indexOf("wx-icon-left")!==-1,[S,b]);d.useEffect(()=>{const z=setTimeout(()=>{o&&T.current&&T.current.focus(),l&&T.current&&T.current.select()},1);return()=>clearTimeout(z)},[o,l]);const F=d.useCallback(z=>{const W=z.target.value;I(W),N&&N({value:W,input:!0})},[N]),H=d.useCallback(z=>N&&N({value:z.target.value}),[N]);function D(z){z.stopPropagation(),I(""),N&&N({value:""})}let K=u;return u!=="password"&&u!=="number"&&(K="text"),d.useEffect(()=>{const z=H,W=T.current;return W.addEventListener("change",z),()=>{W&&W.removeEventListener("change",z)}},[H]),i.jsxs("div",{className:`wx-hQ64J4 wx-text ${_} ${g?"wx-error":""} ${h?"wx-disabled":""} ${k?"wx-clear":""}`,"data-tooltip-text":w,children:[i.jsx("input",{className:"wx-hQ64J4 wx-input",ref:T,id:A,readOnly:r,disabled:h,placeholder:f,type:K,title:y,value:j,onInput:F}),k&&!h&&j?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:D}),B&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`})]}):S?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`}):null]})}function kT({date:t,type:n,part:r,onShift:o}){const{calendar:l,formats:u}=d.useContext(Mi).getRaw(),f=t.getFullYear(),h=d.useMemo(()=>{switch(n){case"month":return Td(u.monthYearFormat,l)(t);case"year":return Td(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=nS(f),b=Td(u.yearFormat,l);return`${b(new Date(y,0,1))} - ${b(new Date(w,11,31))}`}default:return""}},[t,n,f,l,u]);function g(){o&&o({diff:0,type:n})}return i.jsxs("div",{className:"wx-8HQVQV wx-header",children:[r!=="right"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-left",onClick:()=>o&&o({diff:-1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"}),i.jsx("span",{className:"wx-8HQVQV wx-label",onClick:g,children:h}),r!=="left"?i.jsx("i",{className:"wx-8HQVQV wx-pager wxi-angle-right",onClick:()=>o&&o({diff:1,type:n})}):i.jsx("span",{className:"wx-8HQVQV wx-spacer"})]})}function Wv({onClick:t,children:n}){return i.jsx("button",{className:"wx-3s8W4d wx-button",onClick:t,children:n})}function MT({value:t,current:n,part:r="",markers:o=null,css:l="",onCancel:u,onChange:f}){const h=(d.useContext(Mi)||dh()).getRaw().calendar,g=(h.weekStart||7)%7,y=h.dayShort.slice(g).concat(h.dayShort.slice(0,g)),w=(F,H,D)=>new Date(F.getFullYear(),F.getMonth()+(H||0),F.getDate()+(D||0));let b=r!=="normal";function S(F){const H=F.getDay();return H===0||H===6}function k(){const F=w(n,0,1-n.getDate());return F.setDate(F.getDate()-(F.getDay()-(g-7))%7),F}function N(){const F=w(n,1,-n.getDate());return F.setDate(F.getDate()+(6-F.getDay()+g)%7),F}const A=d.useRef(0);function j(F,H){H.timeStamp!==A.current&&(A.current=H.timeStamp,H.stopPropagation(),f&&f(new Date(F)),u&&u())}const I=d.useMemo(()=>r=="normal"?[t?w(t).valueOf():0]:t?[t.start?w(t.start).valueOf():0,t.end?w(t.end).valueOf():0]:[0,0],[r,t]),T=d.useMemo(()=>{const F=k(),H=N(),D=n.getMonth();let K=[];for(let z=F;z<=H;z.setDate(z.getDate()+1)){const W={day:z.getDate(),in:z.getMonth()===D,date:z.valueOf()};let q="";if(q+=W.in?"":" wx-inactive",q+=I.indexOf(W.date)>-1?" wx-selected":"",b){const V=W.date==I[0],X=W.date==I[1];V&&!X?q+=" wx-left":X&&!V&&(q+=" wx-right"),W.date>I[0]&&W.date<I[1]&&(q+=" wx-inrange")}if(q+=S(z)?" wx-weekend":"",o){const V=o(z);V&&(q+=" "+V)}K.push({...W,css:q})}return K},[n,I,b,o]),_=d.useRef(null);let B=d.useRef({});return B.current.click=j,d.useEffect(()=>{Ld(_.current,B.current)},[]),i.jsxs("div",{className:`wx-398RBS wx-month ${l}`,children:[i.jsx("div",{className:"wx-398RBS wx-weekdays",children:y.map(F=>i.jsx("div",{className:"wx-398RBS wx-weekday",children:F},F))}),i.jsx("div",{className:"wx-398RBS wx-days",ref:_,children:T.map(F=>i.jsx("div",{className:`wx-398RBS wx-day ${F.css} ${F.in?"":"wx-out"}`,"data-id":F.date,children:F.day},F.date))})]})}function AT({value:t,current:n,part:r,onCancel:o,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=po(t||f.current),[y,w]=po(n||f.current),b=d.useContext(Mi).getRaw().calendar,S=b.monthShort||[],k=d.useMemo(()=>y.getMonth(),[y]),N=d.useCallback((I,T)=>{if(I!=null){T.stopPropagation();const _=new Date(y);_.setMonth(I),w(_),u&&u({current:_})}r==="normal"&&g(new Date(y)),o&&o()},[y,r,u,o]),A=d.useCallback(()=>{const I=new Date(oS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),j=d.useCallback(I=>{const T=I.target.closest("[data-id]");if(T){const _=parseInt(T.getAttribute("data-id"),10);N(_,I)}},[N]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:j,children:S.map((I,T)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(k===T?" wx-current":""),"data-id":T,children:I},T))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx(Wv,{onClick:A,children:b.done})})]})}const Tg="wx-1XEF33",NT=({value:t,current:n,onCancel:r,onChange:o,onShift:l,part:u})=>{const f=d.useContext(Mi).getRaw().calendar,[h,g]=po(n),[y,w]=po(t),b=d.useMemo(()=>h.getFullYear(),[h]),S=d.useMemo(()=>{const{start:I,end:T}=nS(b),_=[];for(let B=I;B<=T;++B)_.push(B);return _},[b]),k={click:N};function N(I,T){if(I){T.stopPropagation();const _=new Date(h);_.setFullYear(I),g(_),l&&l({current:_})}u==="normal"&&w(new Date(h)),r&&r()}function A(){const I=new Date(oS(y,u)||h);I.setFullYear(h.getFullYear()),o&&o(I)}const j=d.useRef(null);return d.useEffect(()=>{j.current&&Ld(j.current,k)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Tg+" wx-years",ref:j,children:S.map((I,T)=>i.jsx("div",{className:Tg+` wx-year ${b==I?"wx-current":""} ${T===0?"wx-prev-decade":""} ${T===11?"wx-next-decade":""}`,"data-id":I,children:I},T))}),i.jsx("div",{className:Tg+" wx-buttons",children:i.jsx(Wv,{onClick:A,children:f.done})})]})},Dw={month:{component:MT,next:RT,prev:TT},year:{component:AT,next:ET,prev:jT},duodecade:{component:NT,next:IT,prev:DT}};function TT(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function RT(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function jT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function ET(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function DT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function IT(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function oS(t,n){let r;if(n==="normal")r=t;else{const{start:o,end:l}=t;n==="left"?r=o:n=="right"?r=l:r=o&&l}return r}const LT=["clear","today"];function PT(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function _T({value:t,current:n,onCurrentChange:r,part:o="normal",markers:l=null,buttons:u,css:f="",onShift:h,onChange:g}){const y=d.useContext(Mi).getGroup("calendar"),[w,b]=d.useState("month"),S=Array.isArray(u)?u:u?LT:[],k=(T,_)=>{T.preventDefault(),g&&g({value:_})},N=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},A=T=>{const{diff:_,current:B}=T;if(_===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(_){const F=Dw[w];r(_>0?F.next(n):F.prev(n))}else B&&r(B);h&&h()},j=T=>{b("month"),g&&g({select:!0,value:T})},I=d.useMemo(()=>Dw[w].component,[w]);return i.jsx("div",{className:`wx-2Gr4AS wx-calendar ${o!=="normal"&&o!=="both"?"wx-part":""} ${f}`,children:i.jsxs("div",{className:"wx-2Gr4AS wx-wrap",children:[i.jsx(kT,{date:n,part:o,type:w,onShift:A}),i.jsxs("div",{children:[i.jsx(I,{value:t,current:n,onCurrentChange:r,part:o,markers:l,onCancel:N,onChange:j,onShift:A}),w==="month"&&S.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:S.map(T=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx(Wv,{onClick:_=>k(_,PT(T)),children:y(T)})},T))})]})]})})}function Gv(t){let{words:n=null,optional:r=!1,children:o}=t,l=d.useContext(Mi);const u=d.useMemo(()=>{let f=l;return(!f||!f.extend)&&(f=lm(aS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return i.jsx(Mi.Provider,{value:u,children:o})}function Iw(t,n,r,o){if(!t||o){const l=n?new Date(n):new Date;l.setDate(1),r(l)}else if(t.getDate()!==1){const l=new Date(t);l.setDate(1),r(l)}}const FT=["clear","today"];function lS({value:t,current:n,markers:r=null,buttons:o=FT,css:l="",onChange:u}){const[f,h]=po(t),[g,y]=po(n);d.useEffect(()=>{Iw(g,f,y,!1)},[f,g]);const w=d.useCallback(S=>{const k=S.value;k?(h(new Date(k)),Iw(g,new Date(k),y,!0)):h(null),u&&u({value:k?new Date(k):null})},[u,g]),b=d.useCallback(S=>{y(S)},[y]);return g?i.jsx(Gv,{children:i.jsx(_T,{value:f,current:g,markers:r,buttons:o,css:l,onChange:w,onCurrentChange:b})}):null}function OT(t){return t||(t={}),t.width||(t.width="unset"),t}const BT=["clear","today"];function HT({value:t,id:n,disabled:r=!1,error:o=!1,placeholder:l="",format:u="",buttons:f=BT,css:h="",title:g="",tooltip:y,editable:w=!1,clear:b=!1,onChange:S,dropdown:k={}}){const{calendar:N,formats:A}=(d.useContext(Mi)||dh()).getRaw(),j=u||A?.dateFormat;let I=typeof j=="function"?j:Td(j,N);const[T,_]=d.useState(t),[B,F]=d.useState(!1);d.useEffect(()=>{_(t)},[t]);function H(){F(!1)}function D(W){const q=W===T||W&&T&&W.valueOf()===T.valueOf()||!W&&!T;_(W),q||S&&S({value:W}),setTimeout(H,1)}const K=d.useMemo(()=>T?I(T):"",[T,I]);function z({value:W,input:q}){if(!w&&!b||q)return;let V=typeof w=="function"?w(W):W?new Date(W):null;V=isNaN(V)?T||null:V||null,D(V)}return d.useEffect(()=>{const W=H;return window.addEventListener("scroll",W),()=>window.removeEventListener("scroll",W)},[]),i.jsxs("div",{className:"wx-1lKOFG wx-datepicker",onClick:()=>F(!0),children:[i.jsx(qv,{css:`wx-date-input ${h}`,title:g,tooltip:y,value:K,id:n,readonly:!w,disabled:r,error:o,placeholder:l,onInput:H,onChange:z,icon:"wxi-calendar",clear:b}),B&&!r&&i.jsx(Uv,{onCancel:H,...OT(k),children:i.jsx(lS,{buttons:f,value:T,onChange:W=>D(W.value)})})]})}function zT({value:t="",options:n=[],textOptions:r=null,placeholder:o="",disabled:l=!1,error:u=!1,title:f="",tooltip:h,textField:g="label",clear:y=!1,css:w="",children:b,onChange:S,dropdown:k={}}){const N=d.useRef(null),A=d.useRef(null);let[j,I]=po(t);function T(D){N.current=D.navigate,A.current=D.keydown}const _=d.useMemo(()=>j||j===0?(r||n).find(D=>D.id===j):null,[j,r,n]),B=d.useCallback(({id:D})=>{(D||D===0)&&(I(D),N.current(null),S&&S({value:D}))},[I,S]),F=d.useCallback(D=>{D.stopPropagation(),I(""),S&&S({value:""})},[I,S]),H=d.useCallback(()=>n.findIndex(D=>D.id===j),[n,j]);return i.jsxs("div",{className:`wx-2YgblL wx-richselect ${w} ${u?"wx-2YgblL wx-error":""} ${l?"wx-2YgblL wx-disabled":""} ${b?"":"wx-2YgblL wx-nowrap"}`,title:f,onClick:()=>N.current(H()),onKeyDown:D=>A.current(D,H()),tabIndex:0,"data-tooltip-text":h,children:[i.jsx("div",{className:"wx-2YgblL wx-label",children:_?b?b(_):_[g]:o?i.jsx("span",{className:"wx-2YgblL wx-placeholder",children:o}):" "}),y&&!l&&j?i.jsx("i",{className:"wx-2YgblL wx-icon wxi-close",onClick:F}):i.jsx("i",{className:"wx-2YgblL wx-icon wxi-angle-down"}),!l&&i.jsx(fh,{items:n,onReady:T,onSelect:B,...k,children:({option:D})=>b?b(D):D[g]})]})}const $T=({options:t=[],value:n="",css:r="",children:o,onChange:l})=>{const[u,f]=d.useState(n),h=g=>{f(g),l&&l({value:g})};return d.useEffect(()=>{f(n)},[n]),i.jsx("div",{className:`wx-0hMO7P wx-segmented ${r}`,children:t.map(g=>i.jsx("button",{className:`wx-0hMO7P wx-segment ${g.css} ${g.id===u?"wx-selected":""}`,title:g.title,onClick:()=>h(g.id),"data-tooltip-text":g.tooltip,children:o?Ov(o,{option:g}):i.jsxs(i.Fragment,{children:[g.icon&&i.jsx("i",{className:`wx-0hMO7P wx-icon ${g.icon} ${g.label?"":"wx-only"}`}),g.label&&i.jsx("span",{className:"wx-0hMO7P wx-label",children:g.label})]})},g.id))})};function UT({notice:t={}}){function n(){t.remove&&t.remove()}return i.jsxs("div",{className:`wx-11sNg5 wx-notice wx-${t.type?t.type:""}`,role:"status","aria-live":"polite",children:[i.jsx("div",{className:"wx-11sNg5 wx-text",children:t.text}),i.jsx("div",{className:"wx-11sNg5 wx-button",children:i.jsx("i",{className:"wx-11sNg5 wxi-close",onClick:n})})]})}function qT({data:t=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>i.jsx(UT,{notice:n},n.id))})}function gv({title:t="",buttons:n=["cancel","ok"],header:r,children:o,footer:l,css:u="",onConfirm:f,onCancel:h}){const g=(d.useContext(Mi)||dh()).getGroup("core"),y=d.useRef(null);d.useEffect(()=>{y.current?.focus()},[]);function w(S){switch(S.code){case"Enter":{const k=S.target.tagName;if(k==="TEXTAREA"||k==="BUTTON")return;f&&f({event:S});break}case"Escape":h&&h({event:S});break}}function b(S,k){const N={event:S,button:k};k==="cancel"?h&&h(N):f&&f(N)}return i.jsx("div",{className:`wx-1FxkZa wx-modal ${u}`,ref:y,tabIndex:0,onKeyDown:w,children:i.jsxs("div",{className:"wx-1FxkZa wx-window",children:[r||(t?i.jsx("div",{className:"wx-1FxkZa wx-header",children:t}):null),i.jsx("div",{children:o}),l||n&&i.jsx("div",{className:"wx-1FxkZa wx-buttons",children:n.map(S=>i.jsx("div",{className:"wx-1FxkZa wx-button",children:i.jsx(Jf,{type:`block ${S==="ok"?"primary":"secondary"}`,onClick:k=>b(k,S),children:g(S)})},S))})]})})}function WT({children:t},n){const[r,o]=d.useState(null),[l,u]=d.useState([]);return d.useImperativeHandle(n,()=>({showModal:f=>{const h={...f};return o(h),new Promise((g,y)=>{h.resolve=w=>{o(null),g(w)},h.reject=w=>{o(null),y(w)}})},showNotice:f=>{f={...f},f.id=f.id||Hv(),f.remove=()=>u(h=>h.filter(g=>g.id!==f.id)),f.expire!=-1&&setTimeout(f.remove,f.expire||5100),u(h=>[...h,f])}}),[]),i.jsxs(i.Fragment,{children:[t,r&&i.jsx(gv,{title:r.title,buttons:r.buttons,onConfirm:r.resolve,onCancel:r.reject,children:r.message}),i.jsx(qT,{data:l})]})}const GT=d.forwardRef(WT);function VT(t){let{children:n}=t,r=d.useRef();const o=d.useMemo(()=>({showNotice:l=>r.current.showNotice(l),showModal:l=>r.current.showModal(l)}),[]);return i.jsx(rS.Provider,{value:o,children:i.jsx(GT,{ref:r,children:n})})}const KT=({value:t=!1,type:n="",icon:r="",disabled:o=!1,iconActive:l="",onClick:u,title:f="",tooltip:h,css:g="",text:y="",textActive:w="",children:b,active:S,onChange:k})=>{const[N,A]=po(t),j=d.useMemo(()=>(N?"pressed":"")+(n?" "+n:""),[N,n]),I=d.useCallback(T=>{let _=!N;u&&u(T),T.defaultPrevented||(A(_),k&&k({value:_}))},[N,u,k]);return N&&S?i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o,children:Ov(S,{value:N})}):b?i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o,children:b}):i.jsx(Jf,{title:f,tooltip:h,text:N&&w||y,css:g,type:j,icon:N&&l||r,onClick:I,disabled:o})};function QT(){return i.jsx(i.Fragment,{})}function Lw(t){const{fonts:n=!0,children:r}=t;return i.jsx(zv.Provider,{value:"willow",children:i.jsxs(i.Fragment,{children:[r&&r&&i.jsx("div",{className:"wx-theme wx-willow-theme",children:r}),n&&i.jsxs(i.Fragment,{children:[i.jsx("link",{rel:"preconnect",href:"https://cdn.svar.dev",crossOrigin:"true"}),i.jsx(QT,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Bv(cs);const Vv={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 cS=class{constructor(t){this._nextHandler=null,this._dispatch=t,this.exec=this.exec.bind(this)}async exec(t,n){return this._dispatch(t,n),this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};new Date().valueOf();var YT=class{constructor(t){const n={id:0,$level:0,data:[],parent:null},r=new Map;r.set(0,n),this._pool=r,t&&t.length&&this.parse(t,0)}parse(t,n){const r=this._pool;for(let l=0;l<t.length;l++){const u=t[l];u.parent=u.parent||n,u.data=null,r.set(u.id,u)}for(let l=0;l<t.length;l++){const u=t[l],f=r.get(u.parent);f&&(f.data||(f.data=[]),f.data.push(u))}const o=r.get(n);this.setLevel(o,o.$level+1,!1)}add(t,n){const r=this._pool.get(t.parent||0);t.$level=r.$level+1,this._pool.set(t.id,t),r.data?n===-1?r.data=[...r.data,t]:Pw(r,n,t):r.data=[t]}addAfter(t,n){if(!n)return this.add(t,-1);const r=this.byId(n),o=this.byId(r.parent),l=yp(o,r.id)+1;t.parent=o.id,t.$level=o.$level+1,this.add(t,l)}remove(t){const n=this._pool.get(t);this._remove(n);const r=this._pool.get(n.parent);r.data=r.data.filter(o=>o.id!=t),this._clearBranch(r)}_remove(t){t.data&&t.data.forEach(n=>this._remove(n)),this._pool.delete(t.id)}update(t,n){let r=this._pool.get(t);const o=this._pool.get(r.parent),l=yp(o,r.id);r={...r,...n},o&&l>=0&&(o.data[l]=r,o.data=[...o.data]),this._pool.set(r.id,r)}move(t,n,r){const o=this._pool.get(t),l=n==="child",u=this._pool.get(r),f=u.$level+(l?1:0);if(!o||!u)return;const h=this._pool.get(o.parent),g=l?u:this._pool.get(u.parent);g.data||(g.data=[]);const y=yp(h,o.id);XT(h,y);const w=l?g.data.length:yp(g,u.id)+(n==="after"?1:0);if(Pw(g,w,o),h.id===g.id&&y===w)return null;o.parent=g.id,o.$level!==f&&(o.$level=f,this.setLevel(o,f+1,!0)),this.update(o.id,o),this._clearBranch(h)}_clearBranch(t){t.data&&!t.data.length&&(t.open&&delete t.open,this.update(t.id,{data:null}))}toArray(){const t=[],n=this._pool.get(0).data;return n&&uS(n,t),t}byId(t){return this._pool.get(t)}getBranch(t){return this._pool.get(t).data}forEach(t){this._pool.forEach((n,r)=>{r!==0&&t(n)})}eachChild(t,n){const r=this.byId(n);!r||!r.data||r.data.forEach((o,l)=>{t(this.byId(o.id),l),this.eachChild(t,o.id)})}setLevel(t,n,r){t.data&&(t.data=t.data.map(o=>(r&&(o={...o},this._pool.set(o.id,o)),o.$level=n,o.data&&this.setLevel(o,n+1,r),o)))}};function uS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&uS(r.data,n)})}function XT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Pw(t,n,r){const o=[...t.data];o.splice(n,0,r),t.data=o}function yp(t,n){return t?.data.findIndex(r=>r.id===n)}var dS=2,ZT=class{constructor(n){n&&(this._writable=n.writable,this._async=n.async),this._values={},this._state={}}setState(n,r=0){const o={};return this._wrapProperties(n,this._state,this._values,"",o,r),o}getState(){return this._values}getReactive(){return this._state}_wrapProperties(n,r,o,l,u,f){for(const h in n){const g=r[h],y=o[h],w=n[h];if(g&&(y===w&&typeof w!="object"||w instanceof Date&&y instanceof Date&&y.getTime()===w.getTime()))continue;const b=l+(l?".":"")+h;g?(g.__parse(w,b,u,f)&&(o[h]=w),f&dS?u[b]=g.__trigger:g.__trigger()):(w&&w.__reactive?r[h]=this._wrapNested(w,w,b,u):r[h]=this._wrapWritable(w),o[h]=w),u[b]=u[b]||null}}_wrapNested(n,r,o,l){const u=this._wrapWritable(n);return this._wrapProperties(n,u,r,o,l,0),u.__parse=(f,h,g,y)=>(this._wrapProperties(f,u,r,h,g,y),!1),u}_wrapWritable(n){const r=[],o=function(){for(let l=0;l<r.length;l++)r[l](n)};return{subscribe:l=>(r.push(l),this._async?setTimeout(l,1,n):l(n),()=>{const u=r.indexOf(l);u>=0&&r.splice(u,1)}),__trigger:()=>{r.length&&(this._async?setTimeout(o,1):o())},__parse:function(l){return n=l,!0}}}};function _w(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var JT=class{constructor(n,r,o,l){typeof n=="function"?this._setter=n:this._setter=n.setState.bind(n),this._routes=r,this._parsers=o,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(u=>{u.in.forEach(f=>{const h=this._triggers.get(f)||[];h.push(u),this._triggers.set(f,h)}),u.out.forEach(f=>{const h=this._sources.get(f)||{};u.in.forEach(g=>h[g]=!0),this._sources.set(f,h)})}),this._routes.forEach(u=>{u.length=Math.max(...u.in.map(f=>fS(f,this._sources,1)))}),this._bus=l}init(n){const r={};for(const o in n)if(this._prev[o]!==n[o]){const l=this._parsers[o];r[o]=l?l(n[o]):n[o]}this._prev=this._prev?{...this._prev,...n}:{...n},this.setState(r),this._bus&&this._bus.exec("init-state",r)}setStateAsync(n){const r=this._setter(n,dS);return this._async?Object.assign(this._async.signals,r):this._async={signals:r,timer:setTimeout(this._applyState.bind(this),1)},r}_applyState(){const n=this._async;if(n){this._async=null,this._triggerUpdates(n.signals,[]);for(const r in n.signals){const o=n.signals[r];o&&o()}}}setState(n,r=[]){const o=this._setter(n);return this._triggerUpdates(o,r),o}_triggerUpdates(n,r){const o=Object.keys(n),l=!r.length;r=r||[];for(let u=0;u<o.length;u++){const f=o[u],h=this._triggers.get(f);h&&h.forEach(g=>{r.indexOf(g)==-1&&r.push(g)})}l&&this._execNext(r)}_execNext(n){for(;n.length;){n.sort((o,l)=>o.length<l.length?1:-1);const r=n[n.length-1];n.splice(n.length-1),r.exec(n)}}};function fS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>fS(u,n,r+1));return Math.max(...l)}var eR=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(n,r,o){let l=this._handlers[n];l?o&&o.intercept?l.unshift(r):l.push(r):l=this._handlers[n]=[r],o&&o.tag&&this._tag.set(r,o.tag)}intercept(n,r,o){this.on(n,r,{...o,intercept:!0})}detach(n){for(const r in this._handlers){const o=this._handlers[r];for(let l=o.length-1;l>=0;l--)this._tag.get(o[l])===n&&o.splice(l,1)}}async exec(n,r){const o=this._handlers[n];if(o)for(let l=0;l<o.length;l++){const u=o[l](r);if(u===!1||u&&u.then&&await u===!1)return}return this._nextHandler&&await this._nextHandler.exec(n,r),r}setNext(n){return this._nextHandler=n}};const Sd=1024;function sm(t){return t<Sd?`${t} B`:t<Sd**2?`${(t/Sd).toFixed(1)} KB`:t<Sd**3?`${(t/Sd**2).toFixed(1)} MB`:`${(t/Sd**3).toFixed(1)} GB`}function Fw(t,n){n||(n={key:"name",order:"asc"});const r=t.filter(f=>f.type==="folder"),o=t.filter(f=>f.type!=="folder"),l=r.sort(Ow(n)),u=o.sort(Ow(n));return[...l,...u]}function tR(t,n){return typeof t=="string"?t.localeCompare(n,void 0,{numeric:!0}):typeof t=="object"?t.getTime()-n.getTime():(t??0)-(n??0)}function nR(t,n){return typeof t=="string"?-t.localeCompare(n,void 0,{numeric:!0}):typeof n=="object"?n.getTime()-t.getTime():(n??0)-(t??0)}function Ow({key:t,order:n}){const r=n==="asc"?tR:nR;return(o,l)=>r(o[t],l[t])}function Kv(t,n){const r=t==="/"?1:t.split("/").length;return r>=n.length?null:n[r].id}function aR(t){return t.length>1?t[t.length-2].id:null}let rR=class extends YT{constructor(n){const r={id:"/",name:"My files",open:!0,$level:1,parent:0,ext:"",type:"folder"};super([r]),this.parse(n,"/")}parse(n,r,o){!n||!n.length||(n.forEach(l=>this.parseId(l,o?r:void 0)),super.parse(n,r))}parseId(n,r){if(n.parent===0)return;const o=n.id,l=o.lastIndexOf("/");if(n.parent=r??(l===0?"/":o.slice(0,l)),n.name=o.slice(l+1),n.type=n.type||"file",n.type!=="folder"){const u=n.name.lastIndexOf("."),f=u!==-1?n.name.slice(u+1):"";n.ext=f!=="new"?f?.toLocaleLowerCase():""}}getParents(n){const r=[];let o=this.byId(n);if(!o)return r;for(;o.id!==0;)r.push(o),o=this.byId(o.parent);return r.reverse()}findFiles(n,r="/"){const o=[],l=n.toLocaleLowerCase();return this.eachChild(u=>{u.name.toLowerCase().indexOf(l)!==-1&&o.push(u)},r),o}add(n,r){const o=this.byId(n.parent||"/"),l=n.data?[...n.data]:null;n.data=null,super.add(n,r??o.data?o.data.length:0),l&&l.forEach(u=>this.add(u))}renameFiles(n,r,o){const l=this.byId(n),u=this.normalizeFile(l,r),f=[];return u.data?.forEach(h=>f.push(this.renameFiles(h.id,u.id,o))),f.length&&(u.data=f),o[n]=u.id,u}copyFiles(n,r,o){const l={};return n.forEach(u=>{const f=this.renameFiles(u,r,l);this.add(f),o&&this.remove(u),l[u]=f.id}),l}moveFiles(n,r){if(this.byId(n[0]).parent!==r)return this.copyFiles(n,r,!0)}serialize(n="/"){const r=[],o=this.byId(n);return o?(o.data?.forEach(l=>{const{id:u,date:f,type:h,size:g,lazy:y}=l,w={id:u,date:f,type:h??"file"};y&&(w.lazy=y),g&&(w.size=g),r.push(w);const b=this.serialize(u);b.length&&r.push(...b)}),r):null}normalizeFile(n,r){const o=n.name,l=o.lastIndexOf("."),u=l!==-1?o.slice(l+1):"",f=u?`.${u}`:"";let h=l!==-1?o.slice(0,l):o,g=r+(r==="/"?"":"/")+h;for(;this.byId(g+f);){const y=".new";g+=y,h+=y}return{...n,id:g+f,name:h+f,parent:r,ext:u.toLocaleLowerCase()}}},sR=class extends ZT{in;_router;constructor(n){super({writable:n,async:!1});const r=[];for(let u=0;u<2;u++)r.push({in:["data",`panels.${u}.path`],out:[`panels.${u}._crumbs`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];y[u]={_crumbs:h.getParents(g[u].path)},this.setState({panels:y},f)}}),r.push({in:["data",`panels.${u}.path`,`panels.${u}._sorts`,"search"],out:[`panels.${u}._files`],exec:f=>{const{data:h,panels:g,search:y}=this.getState();let w;y?w=h.findFiles(y,g[u].path):w=h.byId(g[u].path)?.data||[];const{path:b,_sorts:S}=g[u];w=Fw(w,S[b]);const k=[];k[u]={_files:w},this.setState({panels:k},f)}}),r.push({in:["data",`panels.${u}.selected`,`panels.${u}._sorts`],out:[`panels.${u}._selected`],exec:f=>{const{data:h,panels:g}=this.getState(),y=[];g[u].selected.forEach(N=>{const A=h.byId(N);A&&y.push(A)});const{path:w,_sorts:b}=g[u],S=Fw(y,b[w]),k=[];k[u]={_selected:S},this.setState({panels:k},f)}});this._router=new JT(super.setState.bind(this),r,{data:u=>new rR(u)});const o=this.in=new eR;o.on("select-file",({id:u,toggle:f,range:h,panel:g,type:y})=>{const{panels:w,activePanel:b}=this.getState();typeof g>"u"&&(g=b),u||(f=h=!1);let S=[...w[g].selected];if(f){const N=S.indexOf(u);N===-1?S.push(u):S.splice(N,1)}else if(h&&w[g]._lastSelected){const N=w[g]._files;let A=N.findIndex(T=>T.id==w[g]._lastSelected),j=N.findIndex(T=>T.id==u);j<A&&([A,j]=[j,A]);const I=N.slice(A,j+1).map(T=>T.id);S=[...new Set([...S,...I])]}else S=u?[u]:[];const k=[];k[g]={selected:S,_lastSelected:u,_selectNavigation:y==="navigation"},this.setState({panels:k})}),o.on("set-path",({id:u,panel:f,selected:h})=>{const{data:g,activePanel:y}=this.getState(),w=g.byId(u);if(w){const b=[];typeof f>"u"&&(f=y),b[f]={path:u},this.setState({panels:b}),o.exec("select-file",{panel:f}),h&&h.forEach(S=>o.exec("select-file",{id:S,panel:f,toggle:!0})),w.lazy&&o.exec("request-data",{id:u})}}),o.on("provide-data",({id:u,data:f})=>{const{mode:h,data:g}=this.getState(),y=g.byId(u);y&&(y.lazy||(y.data=[]),y.lazy=!1,g.parse(f,u,h==="search"),this.setState({data:g}))}),o.on("open-tree-folder",({id:u,mode:f})=>{const{data:h}=this.getState();h.update(u,{open:f}),this.setState({data:h})}),o.on("show-preview",({mode:u})=>{this.setState({preview:u})}),o.on("rename-file",u=>{const{id:f,name:h}=u,{data:g,panels:y}=this.getState(),w=g.byId(f);if(w.name!==h){w.name=h;const b=g.normalizeFile(w,w.parent);u.newId=b.id,b.data=null,g.add(b);let S={[f]:b.id};w.data?.forEach(N=>S={...g.moveFiles([N.id],b.id),...S});const k=y.map(N=>({selected:N.selected,_crumbs:N._crumbs,_lastSelected:N._lastSelected,_sorts:N._sorts}));g.remove(f),this._updatePanels(k,S),this.setState({data:g,panels:k})}}),o.on("create-file",u=>{const{file:f,parent:h}=u,{data:g}=this.getState(),y=g.normalizeFile(f,h);y.type=f.type||"file",u.newId=y.id,g.add(y),this.setState({data:g}),o.exec("select-file",{id:y.id})}),o.on("delete-files",({ids:u})=>{const{data:f,panels:h}=this.getState(),g=h.map(y=>({selected:y.selected,_crumbs:y._crumbs,_lastSelected:y._lastSelected,_sorts:y._sorts}));u.forEach(y=>f.remove(y)),this._updatePanels(g,{}),this.setState({data:f,panels:g})}),o.on("copy-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot copy a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.copyFiles(f,h);u.newIds=f.map(S=>b[S]),this.setState({data:g}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(S=>{o.exec("select-file",{id:b[S],toggle:!0})}))}),o.on("move-files",u=>{const{ids:f,target:h}=u;if(this._isPlacedIntoSelf(f,h)){console.error("You cannot move a folder into itself"),u.skipProvider=!0;return}const{data:g,panels:y,activePanel:w}=this.getState(),b=g.moveFiles(f,h);if(b){u.newIds=f.map(k=>b[k]);const S=y.map(k=>({selected:k.selected,_crumbs:k._crumbs,_lastSelected:k._lastSelected,_sorts:k._sorts}));this._updatePanels(S,b,!0),this.setState({data:g,panels:S}),y[w].path==h&&(o.exec("select-file",{}),f.forEach(k=>{o.exec("select-file",{id:b[k],toggle:!0})}))}});let l=null;o.on("filter-files",({text:u})=>{if(!u){l&&this.setState({...l});return}o.exec("select-file",{});const{panels:f,mode:h}=this.getState();l||(l={panels:f,mode:h,search:""}),this.setState({mode:"search",search:u})}),o.on("set-mode",({mode:u})=>{const{activePanel:f}=this.getState(),h=[];h[f]={_selectNavigation:!1};const g={mode:u,search:"",panels:h};l=null,this.setState(g)}),o.on("set-active-panel",({panel:u})=>{this.setState({activePanel:u})}),o.on("sort-files",({key:u,order:f,panel:h,path:g})=>{const{activePanel:y,panels:w}=this.getState();h=h??y,g=g??w[h].path;const b=[];b[h]={_sorts:{...w[h]._sorts,[g]:{key:u,order:f}}},this.setState({panels:b})}),this.initOnce()}initOnce(){const n=[];for(let o=0;o<2;o++)n[o]=_w({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[o]});const r={panels:_w(n),data:[],search:""};this._router.init(r)}init(n){const r={...n};this._router.init(r)}setState(n,r){return this._router.setState(n,r)}getFile(n){const{data:r}=this.getState();return r.byId(n)||null}serialize(n){const{data:r}=this.getState();return r.serialize(n)}_updatePanels(n,r,o){const{data:l}=this.getState();n.forEach(u=>{const f=[];u.selected.forEach(y=>{l.byId(y)?f.push(y):!o&&r[y]&&f.push(r[y])}),u.selected=f,l.byId(u._lastSelected)||(u._lastSelected=o?null:r[u._lastSelected]||null);const h={};Object.keys(u._sorts).forEach(y=>{l.byId(y)?h[y]=u._sorts[y]:r[y]&&!o&&(h[r[y]]=u._sorts[y])}),u._sorts=h;const g=u._crumbs[u._crumbs.length-1];g?.id!=="/"&&(r[g.id]?u.path=r[g.id]:l.byId(g.id)||(u.path="/"))})}_isPlacedIntoSelf(n,r){return n.some(o=>o===r||this.getState().data.getParents(r).some(l=>l.id===o))}};function iR(t){switch(t){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[t==="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(n=>n!==null)}}function oR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function lR(t,n="data-id"){const r=oR(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function cR(t,n){const{api:r}=n;function o(u,f){const h=n.getPanel(),g=h.selected,y=f.ctrlKey||f.metaKey,w=f.shiftKey;let b;const S=g?.[0]?r.getFile(g[0]):null;g?.length?g.length>1?b=n.menuOptions("multiselect"):b=n.menuOptions(S.type,S):b=n.menuOptions("body");const k=`${y?"ctrl+":""}${w?"shift+":""}${u}`,N=b?b.find(j=>j.hotkey?.toLowerCase()===k):!1,A=n.performAction;if(N)switch(k){case"ctrl+c":A("copy");break;case"ctrl+x":A("move");break;case"ctrl+v":A("paste",S);break;case"delete":A("delete");break;case"ctrl+r":f.preventDefault(),A("rename",S);break;case"ctrl+d":f.preventDefault(),A("download",S);break;default:N.handler?.({context:S})}switch(u){case"enter":{if(y||w)break;const{_crumbs:j,_selectNavigation:I}=h;if(I){const T=aR(j);if(T){const _=Kv(T,j);r.exec("set-path",{id:T,selected:[_]})}}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:j,_selected:I,path:T,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(0).id,H=j.findIndex(D=>D.id===F);if(H!==-1){const D=H-1;j[D]?B=j[D].id:T!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(_)break;if(T!=="/"){r.exec("select-file",{type:"navigation"});break}B=j.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:j,_selected:I,path:T,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(-1).id,H=j.findIndex(D=>D.id===F);if(H!==-1){const D=H+1;j[D]&&(B=j[D].id)}}else{if(T!=="/"&&!_){r.exec("select-file",{type:"navigation"});break}B=j.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}}}function l(u){const f=u.code.replace("Key","").toLowerCase();o(f,u),f=="tab"&&setTimeout(()=>{const h=document.activeElement;h.className.indexOf("table")!=-1&&r.exec("set-active-panel",{panel:+lR(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function uR(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}function dR(t,n="data-id"){const r=t.getAttribute(n);return r?fR(r):null}function fR(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function mR(){return{detect:()=>!0,addEvent:function(t,n,r){return t.addEventListener(n,r),()=>t.removeEventListener(n,r)},addGlobalEvent:function(t,n){return document.addEventListener(t,n),()=>document.removeEventListener(t,n)},getTopNode:function(){return window.document.body}}}var pR=mR();new Date().valueOf();function mS(t){const[n,r]=d.useState(t),o=d.useRef(t);return d.useEffect(()=>{if(o.current!==t){if(Array.isArray(o.current)&&Array.isArray(t)&&o.current.length===0&&t.length===0)return;o.current=t,r(t)}},[t]),[n,r]}function hR(t,n,r){const[o,l]=d.useState(()=>n);return t||console.warn(`Writable ${r} is not defined`),d.useEffect(()=>t?t.subscribe(f=>{l(()=>f)}):void 0,[t]),o}function Ot(t,n){const r=t.getState(),o=t.getReactiveState();return hR(o[n],r[n],n)}function gR(t,n){const r=d.useRef(n);r.current=n;const[o,l]=d.useState(1);return d.useEffect(()=>t.subscribe(f=>{r.current=f,l(h=>h+1)}),[t]),[r.current,o]}function Xs(t,n){const r=t.getState(),o=t.getReactiveState();return gR(o[n],r[n])}function pS(t){const n={};return t.split(";").forEach(r=>{const[o,l]=r.split(":");if(l){let u=o.trim();u.indexOf("-")&&(u=u.replace(/-([a-z])/g,(f,h)=>h.toUpperCase())),n[u]=l.trim()}}),n}function hS(t){let n=t,r=[];return{subscribe:h=>{r.push(h),h(n)},unsubscribe:h=>{r=r.filter(g=>g!==h)},set:h=>{n=h,r.forEach(g=>g(n))},update:h=>{n=h(n),r.forEach(g=>g(n))}}}function Bw(t,n,r){function o(l){const u=uR(l);if(!u)return;const f=dR(u);if(typeof n=="function")return n(f,l);let h,g=l.target;for(;g!=u;){if(h=g.dataset?g.dataset.action:null,h&&n[h]){n[h](f,l);return}g=g.parentNode}n[r]&&n[r](f,l)}return pR.addEvent(t,r,o)}function vR(t,n){const r=[Bw(t,n,"click")];return n.dblclick&&r.push(Bw(t,n.dblclick,"dblclick")),()=>{r.forEach(o=>o())}}function gS(t,n){return t.map((r,o)=>{const l=n(r,o);return r.data&&r.data.length&&(l.data=gS(r.data,n)),l}).filter(Boolean)}function vS(t,n){const r=[];return t.forEach(o=>{if(o.data){const l=vS(o.data,n);l.length&&r.push({...o,data:l})}else n(o)&&r.push(o)}),r}function yR(t){return gS(t,(n,r)=>{const o={...n,id:n.id||Hv()};return o.type&&(o.comp=o.type),o.comp==="separator"&&t[r-1]?.comp==="separator"?null:o})}const yS={};function bR(t){return yS[t]||t}function wR(t,n){yS[t]=n}function xR({onClick:t,onShow:n,option:r}){const o=d.useRef(null),l=d.useCallback(()=>{n(r.data?r.id:!1,o.current)},[n,r]),u=d.useCallback(h=>{if(r.data){h.stopPropagation(),n(r.id,o.current);return}t(h)},[t,n,r]),f=d.useMemo(()=>r&&r.comp?bR(r.comp):null,[r]);return i.jsxs("div",{ref:o,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":Fa(r.id),onMouseEnter:l,onClick:u,children:[r.icon?i.jsx("i",{className:`wx-cDCz9rZQ wx-icon ${r.icon}`}):null,r.comp?f?i.jsx(f,{item:r,option:r}):null:i.jsxs("span",{className:"wx-cDCz9rZQ wx-value",children:[" ",r.text," "]}),r.subtext?i.jsx("span",{className:"wx-cDCz9rZQ wx-subtext",children:r.subtext}):null,r.data?i.jsx("i",{className:"wx-cDCz9rZQ wx-sub-icon wxi-angle-right"}):null]})}function Qv({options:t,left:n=0,top:r=0,at:o="bottom",parent:l=null,mount:u=null,context:f=null,css:h="",onClick:g,onCancel:y}){const[w,b]=d.useState(-1e4),[S,k]=d.useState(-1e4),[N,A]=d.useState(20),[j,I]=d.useState(),T=d.useRef(null),[_,B]=d.useState(!1),[F,H]=d.useState(null),D=d.useCallback(()=>{const ve=eS(T.current,l,o,n,r);ve&&(b(ve.x),k(ve.y),I(ve.width));let J=ve?.z??20;const $=l?cT(l):[];let P=0;for(const se of $){const we=parseInt(getComputedStyle(se).zIndex,10);we>P&&(P=we)}P>=J&&(J=P+1),A(J)},[l,o,n,r]);d.useEffect(()=>{u&&u(D)},[]);const K=d.useCallback(()=>{B(!1)},[]),z=d.useCallback((ve,J)=>{B(ve),H(J)},[]),W=d.useMemo(()=>yR(t),[t]);d.useEffect(()=>{D()},[l,D]);const q=d.useRef(g),V=d.useRef(y),X=d.useRef(l);return d.useEffect(()=>{q.current=g},[g]),d.useEffect(()=>{V.current=y},[y]),d.useEffect(()=>{X.current=l},[l]),d.useEffect(()=>{if(!T.current)return;function ve(J){V.current?V.current(J):q.current&&q.current({action:null,option:null})}return ho(T.current,{callback:ve,modal:!0,parent:()=>X.current}).destroy},[]),i.jsx("div",{ref:T,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:S+"px",left:w+"px",width:j,zIndex:N},onMouseLeave:K,children:W.map(ve=>i.jsxs(d.Fragment,{children:[ve.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(xR,{option:ve,onShow:z,onClick:J=>{if(!ve.data&&!J.defaultPrevented){const $={context:f,action:ve,option:ve,event:J};ve.handler&&ve.handler($),g&&g($),J.stopPropagation()}}}),ve.data&&_===ve.id?i.jsx(Qv,{css:h,options:ve.data,at:"right-overlap",parent:F,context:f,onClick:g,onCancel:y}):null]},ve.id))})}const bS=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,[w,b]=d.useState(null),[S,k]=d.useState(null),[N,A]=d.useState(0),[j,I]=d.useState(0),T=d.useRef(null),_=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),B=d.useMemo(()=>w!==null&&f?vS(r,K=>f(K,w)):r,[w,f,r]);function F(K){k(null),y&&y(K)}function H(K){if(T.current===K){T.current=null;return}k(null),y&&y({action:null,option:null})}const D=d.useCallback((K,z)=>{if(!K){k(null);return}if(K.defaultPrevented)return;const W=K.target;if(W&&W.dataset&&W.dataset.menuIgnore)return;if(S&&S===W){k(null),K.preventDefault();return}A(K.clientX+1),I(K.clientY+1);let q=typeof z<"u"?z:rm(W,_);l&&(q=l(q,K),!q)||(b(q),k(W),T.current=K.nativeEvent||K,K.preventDefault())},[S,_,l]);return d.useImperativeHandle(n,()=>({show:D}),[D]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:D,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,S?i.jsx($v,{children:i.jsx(Qv,{css:h,at:o,top:j,left:N,parent:S,context:w,onClick:F,onCancel:H,options:B},S)}):null]})}),SR=d.forwardRef(function(t,n){const{options:r,at:o="bottom",css:l="",children:u,onClick:f}=t,[h,g]=d.useState(null),y=d.useRef(null);function w(N){g(null),f&&f(N)}function b(N){if(y.current===N){y.current=null;return}g(null),f&&f({action:null,option:null})}const S=d.useCallback(N=>{g(N.target),y.current=N.nativeEvent||N,N.preventDefault()},[]);d.useImperativeHandle(n,()=>({show:S}),[S]);function k(N){let A=N.target;for(;!A.dataset.menuIgnore;)g(A),A=A.parentNode}return i.jsxs(i.Fragment,{children:[i.jsx("span",{onClick:k,"data-menu-ignore":"true",children:u}),h?i.jsx($v,{children:i.jsx(Qv,{css:l,at:o,parent:h,options:r,onClick:w,onCancel:b})}):null]})}),CR=d.forwardRef(function(t,n){const{options:r,at:o="bottom",resolver:l=null,dataKey:u="contextId",filter:f=null,css:h="",children:g,onClick:y}=t,w=d.useRef(null),b=d.useCallback((S,k)=>{w.current.show(S,k)},[]);return d.useImperativeHandle(n,()=>({show:b}),[b]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onContextMenu:b,"data-menu-ignore":"true",children:g}):null,i.jsx(bS,{css:h,at:o,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),kR={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 MR=class{constructor(n,r,o,l,u){this.setFiles=n,this.setReady=r,this.setSignal=o,this.setDrag=l,u&&u.length&&this.setFiles(u)}open(n){this.setSignal(["click",n||{}])}getState(){let n="server";const r=this.files;for(let o=0;o<r.length;o++){if(r[o].status==="client")return"client";r[o].status==="error"&&(n="error")}return n}droparea(n,r){r=r||{};const o=()=>{r.dragEnter&&r.dragEnter(),this.setDrag(!0)},l=()=>{r.dragLeave&&r.dragLeave(),this.setDrag(!1)},u=h=>{h.preventDefault()},f=h=>{h.preventDefault(),this.setDrag(!1),this.setSignal(["drop",r,h]),r.dragLeave&&r.dragLeave(),r.drop&&r.drop()};return n.addEventListener("dragenter",o),n.addEventListener("dragleave",l),n.addEventListener("dragover",u,!0),n.addEventListener("drop",f,!0),()=>{n.removeEventListener("dragenter",o),n.removeEventListener("dragleave",l),n.removeEventListener("dragover",u,!0),n.removeEventListener("drop",f,!0)}}updateFile(n,r){const o=this.files.findIndex(u=>u.id===n);if(o===-1)return;const l=[...this.files];return l[o]={...l[o],...r},this.files=l,this.setFiles(this.files),this.files[o]}deleteFile(n){this.files=this.files.filter(r=>r.id!==n),this.setFiles(this.files)}addFile(n,r){r?this.files=[...this.files,n]:this.files=[n],this.setFiles(this.files)}deleteAll(){this.files=[],this.setFiles(this.files)}};function wS(t){const[n,r]=d.useState([]),[o,l]=d.useState(Promise.resolve(null)),[u,f]=d.useState(null),[h,g]=d.useState(!1),y=d.useRef();return y.current||(y.current=new MR(r,l,f,g,t)),y.current.files=n,y.current.ready=o,y.current.signal=u,y.current.drag=h,y.current}function AR(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return lm(kR).getGroup(n)}}const NR=()=>Math.random().toString(36).substr(2,9),TR=({data:t,accept:n="",multiple:r=!0,folder:o=!1,uploadURL:l="",apiOnly:u=!1,disabled:f=!1,children:h,onChange:g,onUpload:y})=>{const w=d.useRef(null),b=d.useRef(null),[S,k]=d.useState({}),N=wS(),A=t||N,j=d.useContext(Ba.i18n),I=AR(j,"uploader");d.useEffect(()=>{w.current&&o&&(w.current.webkitdirectory=!0)},[o]),d.useEffect(()=>{if(!u&&b.current&&!f)return A.droparea(b.current)},[u,f,b]);const T=W=>{const q=new FormData;return q.append("upload",W.file),fetch(l,{method:"POST",body:q}).then(V=>V.json()).then(V=>({id:W.id,...V}),()=>({id:W.id,status:"error"})).catch(V=>(console.log(V),{id:W.id,status:"error"}))},_=(W,q)=>{const V=A.updateFile(W,q),X={...V,status:A.getState()};V&&V.uploaded&&V.uploaded(X),y&&y(X),V.temp&&A.deleteFile(V.id)},B=W=>{if(!W)return;const q=typeof l=="function"?l(W):T(W);A.setReady(q.then(V=>{V.status=V.status||"server",_(W.id,V)}).catch(V=>{_(W.id,{status:"error",error:V})}))},F=(W,q)=>{const V={...q||S,id:NR(),status:"client",name:W.name,file:W};V.selected&&V.selected(V),g&&g(V),A.addFile(V,r),B(V),w.current&&(w.current.value="")},H=(W,q,V)=>{W.isFile?W.file(X=>{F(X,V)}):W.isDirectory&&W.createReader().readEntries(X=>{X.forEach(ve=>{H(ve,q+ve.name+"/",V)})})},D=W=>{Array.from(W.target.files).forEach(q=>F(q))},K=(W,q)=>{Array.from(W.dataTransfer.items).forEach(V=>{const X=V.webkitGetAsEntry();X&&H(X,"",q)})},z=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(A.signal){const[W,q,V]=A.signal;k(q),W==="click"?z():W==="drop"&&K(V,q),A.setSignal(null)}},[A.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h]}):i.jsxs("div",{className:`wx-at1A8tb8 wx-label ${A.drag?"wx-active":""} ${f?"wx-disabled":""}`,ref:b,children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:D,accept:n,multiple:r,disabled:f}),h||i.jsx("div",{className:"wx-at1A8tb8 wx-dropzone",children:i.jsxs("span",{children:[I("Drop files here or")," ",i.jsx("span",{className:"wx-at1A8tb8 wx-action",onClick:z,children:I("select files")})]})})]})};new Date().valueOf();function RR(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in n){const o=t[r],l=n[r];if(!mh(o,l))return!1}return!0}function mh(t,n){if(typeof t=="number"||typeof t=="string"||typeof t=="boolean"||t===null)return t===n;if(typeof t!=typeof n||(t===null||n===null)&&t!==n||t instanceof Date&&n instanceof Date&&t.getTime()!==n.getTime())return!1;if(typeof t=="object")if(Array.isArray(t)&&Array.isArray(n)){if(t.length!==n.length)return!1;for(let r=t.length-1;r>=0;r--)if(!mh(t[r],n[r]))return!1;return!0}else return RR(t,n);return t===n}function vv(t){if(typeof t!="object"||t===null)return t;if(t instanceof Date)return new Date(t);if(t instanceof Array)return t.map(vv);const n={};for(const r in t)n[r]=vv(t[r]);return n}var xS=2,jR=class{constructor(t){t&&(this._writable=t.writable,this._async=t.async),this._values={},this._state={}}setState(t,n=0){const r={};return this._wrapProperties(t,this._state,this._values,"",r,n),r}getState(){return this._values}getReactive(){return this._state}_wrapProperties(t,n,r,o,l,u){for(const f in t){const h=n[f],g=r[f],y=t[f];if(h&&(g===y&&typeof y!="object"||y instanceof Date&&g instanceof Date&&g.getTime()===y.getTime()))continue;const w=o+(o?".":"")+f;h?(h.__parse(y,w,l,u)&&(r[f]=y),u&xS?l[w]=h.__trigger:h.__trigger()):(y&&y.__reactive?n[f]=this._wrapNested(y,y,w,l):n[f]=this._wrapWritable(y),r[f]=y),l[w]=l[w]||null}}_wrapNested(t,n,r,o){const l=this._wrapWritable(t);return this._wrapProperties(t,l,n,r,o,0),l.__parse=(u,f,h,g)=>(this._wrapProperties(u,l,n,f,h,g),!1),l}_wrapWritable(t){const n=[],r=function(){for(let o=0;o<n.length;o++)n[o](t)};return{subscribe:o=>(n.push(o),this._async?setTimeout(o,1,t):o(t),()=>{const l=n.indexOf(o);l>=0&&n.splice(l,1)}),__trigger:()=>{n.length&&(this._async?setTimeout(r,1):r())},__parse:function(o){return t=o,!0}}}},ER=class{constructor(t,n,r,o){typeof t=="function"?this._setter=t:this._setter=t.setState.bind(t),this._routes=n,this._parsers=r,this._prev={},this._triggers=new Map,this._sources=new Map,this._routes.forEach(l=>{l.in.forEach(u=>{const f=this._triggers.get(u)||[];f.push(l),this._triggers.set(u,f)}),l.out.forEach(u=>{const f=this._sources.get(u)||{};l.in.forEach(h=>f[h]=!0),this._sources.set(u,f)})}),this._routes.forEach(l=>{l.length=Math.max(...l.in.map(u=>SS(u,this._sources,1)))}),this._bus=o}init(t){const n={};for(const r in t)if(this._prev[r]!==t[r]){const o=this._parsers[r];n[r]=o?o(t[r]):t[r]}this._prev=this._prev?{...this._prev,...t}:{...t},this.setState(n),this._bus&&this._bus.exec("init-state",n)}setStateAsync(t){const n=this._setter(t,xS);return this._async?Object.assign(this._async.signals,n):this._async={signals:n,timer:setTimeout(this._applyState.bind(this),1)},n}_applyState(){const t=this._async;if(t){this._async=null,this._triggerUpdates(t.signals,[]);for(const n in t.signals){const r=t.signals[n];r&&r()}}}setState(t,n=[]){const r=this._setter(t);return this._triggerUpdates(r,n),r}_triggerUpdates(t,n){const r=Object.keys(t),o=!n.length;n=n||[];for(let l=0;l<r.length;l++){const u=r[l],f=this._triggers.get(u);f&&f.forEach(h=>{n.indexOf(h)==-1&&n.push(h)})}o&&this._execNext(n)}_execNext(t){for(;t.length;){t.sort((r,o)=>r.length<o.length?1:-1);const n=t[t.length-1];t.splice(t.length-1),n.exec(t)}}};function SS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>SS(u,n,r+1));return Math.max(...l)}var DR=class{constructor(){this._nextHandler=null,this._handlers={},this._tag=new WeakMap,this.exec=this.exec.bind(this)}on(t,n,r){let o=this._handlers[t];o?r&&r.intercept?o.unshift(n):o.push(n):o=this._handlers[t]=[n],r&&r.tag&&this._tag.set(n,r.tag)}intercept(t,n,r){this.on(t,n,{...r,intercept:!0})}detach(t){for(const n in this._handlers){const r=this._handlers[n];for(let o=r.length-1;o>=0;o--)this._tag.get(r[o])===t&&r.splice(o,1)}}async exec(t,n){const r=this._handlers[t];if(r)for(let o=0;o<r.length;o++){const l=r[o](n);if(l===!1||l&&l.then&&await l===!1)return}return this._nextHandler&&await this._nextHandler.exec(t,n),n}setNext(t){return this._nextHandler=t}};function IR(t){return n=>n[t]}function LR(t){return(n,r)=>n[t]=r}function ic(t,n){return(n.getter||IR(n.id))(t)}function Rg(t,n,r){return(n.setter||LR(n.id))(t,r)}function PR(t,n){const r=document.createElement("a");r.href=URL.createObjectURL(t),r.download=n,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function tc(t,n){let r=ic(t,n)??"";return n.template?r=n.template(r,t,n):n.optionsMap&&(Array.isArray(r)?r=r.map(o=>n.optionsMap.get(o)).join(", "):r=n.optionsMap.get(r)),typeof r>"u"?"":r+""}function _R(t,n){const r=/\n|"|;|,/;let o="";const l=n.rows||`
|
|
178
|
+
`,u=n.cols||" ",f=t._columns,h=t.flatData;n.header!==!1&&f[0].header&&(o=Hw("header",f,o,u,l));for(let g=0;g<h.length;g++){const y=[];for(let w=0;w<f.length;w++){let b=tc(h[g],f[w]);r.test(b)&&(b='"'+b.replace(/"/g,'""')+'"'),y.push(b)}o+=(o?l:"")+y.join(u)}return n.footer!==!1&&f[0].footer&&(o=Hw("footer",f,o,u,l)),o}function Hw(t,n,r,o,l){const u=/\n|"|;|,/;for(let f=0;f<n[0][t].length;f++){const h=[];for(let g=0;g<n.length;g++){let y=(n[g][t][f].text||"")+"";u.test(y)&&(y='"'+y.replace(/"/g,'""')+'"'),h.push(y)}r+=(r?l:"")+h.join(o)}return r}const FR="portrait",OR=100,BR="a4",HR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function zR(t,n){const r=[];let o=[],l=0;const u=t.filter(h=>!h.hidden),f=$R(n);return u.forEach((h,g)=>{l+h.width<=f?(l+=h.width,o.push(h)):(o.length&&r.push(o),o=[h],l=h.width),g===u.length-1&&o.length&&r.push(o)}),r}function zw(t,n,r){const o=[];return t.forEach((l,u)=>{const f=l[n];for(let h=0;h<r.length;h++){o[h]||(o[h]=[]);const g={...f[h]};if(o[h][u]!==null){if(!u&&!g.rowspan&&!g.colspan){let y=1,w=t[u+y][n][h],b=g.width;for(;!w.rowspan&&!w.colspan;)y++,w=t[u+y][n][h],b+=w.width;g.colspan=y,g.width=b,g.height=r[h]}if(o[h].push(g),!g.collapsed&&g.colspan>1){let y=g.colspan-1;if(g.colspan+u>t.length){const w=g.colspan-(g.colspan+u-t.length);g.colspan=w,g.width=t.slice(u,u+y+1).reduce((b,S)=>b+S.width,0),w>1&&(y=w-1)}for(let w=0;w<y;w++)o[h].push(null)}if(g.rowspan>1){const y=g.rowspan;for(let w=1;w<y;w++)o[h+w]||(o[h+w]=[]),o[h+w].push(null)}}}if(l.collapsed)for(let h=0;h<o.length;h++){const g=o[h],y=g[u];if(y&&y.collapsed){if(g[u]=null,!h)break}else{const w=y||g.findLast(b=>b?.colspan>=1);w&&(w.colspan=w.colspan-1,w.width=w.width-l.width)}}}),o.map(l=>l.filter(u=>u&&u.colspan!==0))}function $R(t){const{mode:n,ppi:r,paper:o}=t,{width:l,height:u}=HR[o];return UR(n==="portrait"?l:u,r)}function UR(t,n){return t*n}function qR(t={}){const{mode:n,ppi:r,paper:o}=t;return{mode:n||FR,ppi:r||OR,paper:o||BR}}function CS(t,n){return t.flexgrow?`min-width:${n}px;width:auto`:`width:${t.width}px; max-width:${t.width}px; height:${t.height}px`}function WR(t,n,r){let o=t[r.id];if(r.filter.type==="richselect"&&o){const l=r.filter.config?.options||n.find(({id:u})=>u==r.id).options;l&&(o=l.find(({id:u})=>u==o).label)}return o??""}const $w=["resize-column","hide-column","update-cell"],GR=["delete-row","update-row","update-cell"],VR=["move-item"],KR=["resize-column","move-item"];class QR{undo=[];redo=[];progress={};in;getState;setState;_previousValues={};constructor(n,r,o){this.in=n,this.getState=r,this.setState=o,this.setHandlers(),this.resetStateHistory()}getHandlers(){return{"add-row":{handler:n=>({action:"delete-row",data:{id:n.id},source:{action:"add-row",data:n}})},"delete-row":{handler:n=>{const{id:r}=n,{data:o}=this.getPrev(),l=o.findIndex(u=>u.id===r);return{action:"add-row",data:{id:r,row:o[l],before:l<o.length-1?o[l+1].id:void 0},source:{action:"delete-row",data:n}}}},"update-cell":{handler:n=>{const{id:r,column:o}=n,l=this.getRow(r),u=this.getColumn(o),f=ic(l,u);return mh(f,n.value)?null:{action:"update-cell",data:{id:r,column:o,value:f},source:{action:"update-cell",data:n}}}},"update-row":{handler:n=>{const{id:r,row:o}=n,l=this.getRow(r);for(const u in o)Object.keys(l).includes(u)||(l[u]=void 0);return{action:"update-row",data:{id:r,row:l},source:{action:"update-row",data:n}}}},"copy-row":{handler:n=>{const{id:r}=n,{data:o}=this.getState(),l=o.findIndex(f=>f.id===r),u=o[l];return{action:"delete-row",data:{id:r},source:{action:"add-row",data:{id:r,row:u,before:l<o.length-1?o[l+1].id:void 0}}}}},"resize-column":{handler:n=>{const{id:r,width:o}=n,l=this.getColumn(r),{_sizes:u}=this.getState();return{action:"resize-column",data:{id:r,width:l.width??u.columnWidth},source:{action:"resize-column",data:{id:r,width:o}}}}},"hide-column":{handler:n=>{const{id:r}=n,o=this.getColumn(r);return{action:"hide-column",data:{id:r,mode:o.hidden},source:{action:"hide-column",data:n}}}},"collapse-column":{handler:n=>{const{id:r,row:o,mode:l}=n;return{action:"collapse-column",data:{id:r,row:o,mode:typeof l=="boolean"?!l:l},source:{action:"collapse-column",data:n}}}},"move-item":{handler:n=>{const{id:r,target:o,mode:l}=n,{flatData:u}=this.getPrev(),f=u.findIndex(h=>h.id===r);return{action:"move-item",data:{id:r,target:u[f+(f?-1:1)].id,mode:f?"after":"before"},source:{action:"move-item",data:{id:r,target:o,mode:l}}}}},"open-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"close-row",data:{id:r,nested:o},source:{action:"open-row",data:n}}}},"close-row":{handler:n=>{const{id:r,nested:o}=n;return{action:"open-row",data:{id:r,nested:o},source:{action:"close-row",data:n}}}}}}resetHistory(){this.undo=[],this.redo=[],this.progress={},this.resetStateHistory()}getPrev(){return this._previousValues}setHandlers(){const n=this.getHandlers();for(const r in n)this.in.intercept(r,o=>{if(!(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo)){if(KR.includes(r)){(o.inProgress&&!this.progress[r]||typeof o.inProgress!="boolean")&&(VR.includes(r)&&this.setPrev("flatData"),$w.includes(r)&&this.setPrev("columns")),this.progress[r]=o.inProgress;return}GR.includes(r)&&this.setPrev("data"),$w.includes(r)&&this.setPrev("columns")}}),this.in.on(r,o=>{if(o.eventSource==="undo"||o.eventSource==="redo"||o.skipUndo||o.inProgress)return;const l=n[r].handler(o);l&&this.addToHistory(l)})}setPrev(n){this._previousValues[n]=vv(this.getState()[n])}addToHistory(n){this.undo.push(n),this.redo=[],this.setStateHistory()}handleUndo(){if(!this.undo.length)return;const n=this.undo.pop();this.redo.push({...n.source,source:n}),this.in.exec(n.action,{...n.data,eventSource:"undo"}),this.setStateHistory()}handleRedo(){if(!this.redo.length)return;const n=this.redo.pop();this.undo.push({...n.source,source:n}),this.in.exec(n.action,{...n.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(n){const{data:r}=this.getPrev();return this.getState().tree?this.getTreeRow(r,n):r.find(o=>o.id===n)}getTreeRow(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n[o];if(n[o].data){const l=this.getTreeRow(n[o].data,r);if(l)return l}}return null}getColumn(n){const{columns:r}=this.getPrev();return r.find(o=>o.id===n)}}function kS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function YR(t,n){return-kS(t,n)}function XR(t,n){if(typeof n.sort=="function")return function(o,l){const u=n.sort(o,l);return t==="asc"?u:-u};const r=t==="asc"?kS:YR;return function(o,l){return r(ic(o,n),ic(l,n))}}function ZR(t,n){if(!t||!t.length)return;const r=t.map(o=>{const l=n.find(u=>u.id==o.key);return XR(o.order,l)});return t.length===1?r[0]:function(o,l){for(let u=0;u<r.length;u++){const f=r[u](o,l);if(f!==0)return f}return 0}}const bp=28,JR=20;function ej(){if(typeof document>"u")return"willow";const t=document.querySelector('[class^="wx"][class$="theme"]');return t?t.className.substring(3,t.className.length-6):"willow"}function Yp(t,n,r,o,l){const u=document.createElement("div"),f=document.createElement("div"),h=document.body;l=l?`${l}px`:"auto";let g,y;f.className=n,u.classList.add(`wx-${r}-theme`),u.style.cssText=`height:auto;position:absolute;top:0px;left:100px;overflow:hidden;width=${l};white-space:nowrap;`,u.appendChild(f),h.appendChild(u),typeof t!="object"&&(t=[t]);for(let w=0;w<t.length;w++){f.innerText=t[w]+"";const b=u.getBoundingClientRect(),S=Math.ceil(b.width)+(o&&o.length?o[w]:0),k=Math.ceil(b.height);g=Math.max(g||0,S),y=Math.max(y||0,k)}return u.remove(),{width:g,height:y}}function Uw(t,n,r,o,l){const u=[];for(let f=0;f<t.length;f++){const h=t[f][n],g=h.length;for(let y=0;y<g;y++){const{text:w,vertical:b,collapsed:S,rowspan:k,css:N}=h[y];if(!w){u[y]=Math.max(u[y]||0,o);continue}let A=0;if(b&&!S){let j=`wx-measure-cell-${n}`;if(j+=N?` ${N}`:"",A=Yp(w,j,l).width,(k>1||!h[y+1])&&r>y+1){const I=k||r-y,T=u.slice(y,y+I).reduce((_,B)=>_+B,0);if(T<A){const _=Math.ceil((A-T)/I);for(let B=y;B<y+I;B++)u[B]=(u[B]||o)+_}continue}}u[y]=Math.max(u[y]||o,A)}}return u}function tj(t,n,r){const o=[],l=[];let u="wx-measure-cell-body";u+=t.css?` ${t.css}`:"";for(let f=0;f<n.length;f++){const h=n[f],g=tc(h,t);g&&(o.push(g),t.treetoggle?l.push(n[f].$level*bp+(n[f].$count?bp:0)+(t.draggable?bp:0)):t.draggable&&l.push(bp))}return Yp(o,u,r,l).width}function nj(t,n){const r="wx-measure-cell-header",o=t.sort?JR:0;let l=t.header;if(typeof l=="string")return Yp(l,r,n).width+o;let u;Array.isArray(l)||(l=[l]);for(let f=0;f<l.length;f++){const h=l[f],g=typeof h=="string"?h:h.text,y=r+(typeof h=="string"?"":` ${h.css}`);let w=Yp(g,y,n).width;f===l.length-1&&(w+=o),u=Math.max(u||0,w)}return u}const aj={text:(t,n)=>t?t.toString().toLowerCase().indexOf(n.toLowerCase())!==-1:!n,richselect:(t,n)=>typeof n!="number"&&!n?!0:t==n,datepicker:(t,n)=>n?t&&sj(t,n):!0,multiselect:(t,n)=>!n||n?.length===0?!0:Array.isArray(t)?t?.some(r=>n.includes(r)):t&&n.includes(t)};function MS(t){return aj[t]}function rj(t,n){const r=[];for(const o in t){const l=n.find(g=>g.id==o),{config:u,type:f}=l.header.find(g=>g.filter).filter,h=t[o];r.push(g=>{const y=ic(g,l);return u?.handler?u.handler(y,h):MS(f)(y,h)})}return o=>{for(let l=0;l<r.length;l++)if(!r[l](o))return!1;return!0}}function sj(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let ij=class extends jR{in;_router;_branches;_xlsxWorker;_historyManager;constructor(n){super({writable:n,async:!1});const r={rowHeight:37,columnWidth:160,headerHeight:36,footerHeight:36};this._router=new ER(super.setState.bind(this),[{in:["columns","sizes","_skin"],out:["_columns","_sizes"],exec:l=>{const{columns:u,sizes:f,_skin:h}=this.getState(),g=this.copyColumns(u),y=g.reduce((S,k)=>Math.max(k.header.length,S),0),w=g.reduce((S,k)=>Math.max(k.footer.length,S),0);g.forEach(this.setCollapsibleColumns);const b=this.normalizeSizes(g,f,y,w,h);for(let S=0;S<g.length;S++)this.normalizeColumns(g,S,"header",y,b),this.normalizeColumns(g,S,"footer",w,b);this.setState({_columns:g,_sizes:b},l)}},{in:["data","tree","_filterIds"],out:["flatData","_rowHeightFromData"],exec:l=>{const{data:u,tree:f,dynamic:h,_filterIds:g}=this.getState(),y=g&&new Set(g),w=f?this.flattenRows(u,[],g):y?u.filter(S=>y.has(S.id)):u,b=!h&&w.some(S=>S.rowHeight);this.setState({flatData:w,_rowHeightFromData:b},l)}}],{sizes:l=>({...r,...l})});const o=this.in=new DR;o.on("close-editor",({ignore:l})=>{const{editor:u}=this.getState();u&&(l||o.exec("update-cell",u),this.setState({editor:null}))}),o.on("open-editor",({id:l,column:u})=>{let f=this.getState().editor;f&&o.exec("close-editor",{});const h=this.getRow(l),g=u?this.getColumn(u):this.getNextEditor(h);if(g?.editor){let y=g.editor;if(typeof y=="function"&&(y=y(h,g)),!y)return;f={column:g.id,id:l,value:ic(h,g)??"",renderedValue:tc(h,g),type:y.type||y},typeof y=="object"&&y.config&&(f.config=y.config,y.config.options&&(f.options=y.config.options)),g.options&&!f.options&&(f.options=g.options),this.setState({editor:f})}}),o.on("editor",({value:l})=>{let u=this.getState().editor;if(u){u={...u},u.value=l;const f=this.getColumn(u.column),h={...this.getRow(u.id)};Rg(h,f,l),u.renderedValue=tc(h,f),this.setState({editor:u})}}),o.on("add-row",l=>{const u=this.getState();let{data:f}=u;const{select:h,_filterIds:g}=u,{row:y,before:w,after:b,select:S}=l;if(l.id=y.id=l.id||y.id||wp(),w||b){const N=w||b,A=f.findIndex(j=>j.id===N);f=[...f],f.splice(A+(b?1:0),0,l.row)}else f=[...f,l.row];const k={data:f};g&&(k._filterIds=[...g,l.id]),this.setState(k),!(typeof S=="boolean"&&!S)&&(S||h)&&o.exec("select-row",{id:y.id,show:!0})}),o.on("delete-row",l=>{const{data:u,selectedRows:f,focusCell:h,editor:g}=this.getState(),{id:y}=l,w={data:u.filter(b=>b.id!==y)};this.isSelected(y)&&(w.selectedRows=f.filter(b=>b!==y)),g?.id===y&&(w.editor=null),this.setState(w),h?.row===y&&this.in.exec("focus-cell",{eventSource:"delete-row"})}),o.on("update-cell",l=>{const u=this.getState();let{data:f}=u;f=[...f];const{tree:h}=u,{id:g,column:y,value:w}=l,b=this.getColumn(y);if(h){const S={...this._branches[g]};Rg(S,b,w);const k=this.updateTreeRow(S);S.$parent===0&&(f=k)}else{const S=f.findIndex(N=>N.id===g),k={...f[S]};Rg(k,b,w),f[S]=k}this.setState({data:f})}),o.on("update-row",l=>{let{data:u}=this.getState();const{id:f,row:h}=l,g=u.findIndex(y=>y.id===f);u=[...u],u[g]={...u[g],...h},this.setState({data:u})}),o.on("select-row",({id:l,toggle:u,range:f,mode:h,show:g,column:y})=>{const w=this.getState(),{focusCell:b}=w;let{selectedRows:S}=w;if(S.length||(f=u=!1),f){const{data:k}=this.getState();let N=k.findIndex(j=>j.id===S[S.length-1]),A=k.findIndex(j=>j.id===l);N>A&&([N,A]=[A,N]),k.slice(N,A+1).forEach(j=>{this.isSelected(j.id)||S.push(j.id)})}else if(u&&this.isSelected(l)){if(h===!0)return;S=S.filter(k=>k!==l)}else if(u){if(h===!1)return;S.push(l)}else S=[l];this.setState({selectedRows:[...S]}),b?.row!==l&&this.in.exec("focus-cell",{eventSource:"select-row"}),g&&this.in.exec("scroll",{row:l,column:y})}),this.in.on("focus-cell",l=>{const{row:u,column:f,eventSource:h}=l,{_columns:g,split:y}=this.getState();u&&f?(this.setState({focusCell:{row:u,column:f}}),h!=="click"&&((!y.left||g.findIndex(w=>w.id===l.column)>=y.left)&&(!y.right||g.findIndex(w=>w.id===l.column)<g.length-y.right)?this.in.exec("scroll",{row:u,column:f}):this.in.exec("scroll",{row:u}))):this.setState({focusCell:null})}),o.on("resize-column",l=>{const{id:u,auto:f,maxRows:h,inProgress:g}=l;if(g===!1)return;let y=l.width||0;const w=[...this.getState().columns],b=this.getColumn(u);if(f){if(f==="data"||f===!0){const{flatData:S,_skin:k}=this.getState();let N=S.length;h&&(N=Math.min(h,N));const A=S.slice(0,N);y=tj(b,A,k)}if(f==="header"||f===!0){const{_skin:S}=this.getState();y=Math.max(nj(b,S),y)}}b.width=Math.max(17,y),delete b.flexgrow,this.setState({columns:w})}),o.on("hide-column",l=>{const{id:u,mode:f}=l,h=[...this.getState().columns],g=this.getColumn(u),y=h.reduce((w,b)=>w+(b.hidden?0:1),0);!f||y>1?(g.hidden=!g.hidden,this.setState({columns:h})):l.skipUndo=!0}),o.on("sort-rows",l=>{const{key:u,add:f,sort:h}=l,g=this.getState(),{columns:y,data:w,tree:b}=g;if(h){const T=[...w];T.sort(h),this.setState({data:T});return}const{order:S="asc"}=l;let k=g.sortMarks;const N=Object.keys(k),A=N.length;!f||!A||A===1&&k[u]?k={[u]:{order:S}}:(A===1&&(k[N[0]]={...k[N[0]],index:0}),k={...k,[u]:{order:S,index:typeof f=="number"?f:k[u]?.index??A}});const j=Object.keys(k).sort((T,_)=>k[T].index-k[_].index).map(T=>({key:T,order:k[T].order}));this.setState({sortMarks:k});const I=ZR(j,y);if(I){const T=[...w];b?this.sortTree(T,I):T.sort(I),this.setState({data:T})}}),o.on("filter-rows",l=>{const{value:u,key:f,filter:h}=l;if(!Object.keys(l).length){this.setState({filterValues:{},_filterIds:null});return}const g=this.getState(),{data:y,tree:w,_columns:b}=g;let S=g.filterValues;const k={};f&&(S={...S,[f]:u},k.filterValues=S);const N=h??rj(S,b);let A=[];w?A=this.filterTree(y,N,A):y.forEach(j=>{N(j)&&A.push(j.id)}),k._filterIds=A,this.setState(k)}),o.on("collapse-column",l=>{const{id:u,row:f,mode:h}=l,g=[...this.getState().columns],y=this.getColumn(u).header,w=Array.isArray(y)?y[f]:y;typeof w=="object"&&(w.collapsed=h??!w.collapsed,this.setState({columns:g}))}),o.on("move-item",l=>{const{id:u,inProgress:f}=l;let{target:h,mode:g="after"}=l;const{data:y,flatData:w,tree:b}=this.getState(),S=w.findIndex(A=>A.id===u);let k;if(g==="up"||g==="down"){if(g==="up"){if(S===0)return;k=S-1,g="before"}else if(g==="down"){if(S===w.length-1)return;k=S+1,g="after"}h=w[k]&&w[k].id}else k=w.findIndex(A=>A.id===h);if(S===-1||k===-1||f===!1)return;let N;b||(N=this.moveItem(u,h,y,g)),this.setState({data:b?this.normalizeTreeRows(N):N})}),o.on("copy-row",l=>{const{id:u,target:f,mode:h="after"}=l,g=this.getState(),{flatData:y,_filterIds:w}=g;let{data:b}=g;const S=this.getRow(u);if(!S)return;const k={...S,id:wp()};l.id=k.id;const N=y.findIndex(j=>j.id===f);if(N===-1)return;b.splice(N+(h==="after"?1:0),0,k),b=[...b];const A={data:b};w&&(A._filterIds=[...w,k.id]),this.setState(A)}),o.on("open-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!0,f)}),o.on("close-row",l=>{const{id:u,nested:f}=l;this.toggleBranch(u,!1,f)}),o.on("export-data",l=>new Promise((u,f)=>{const h=l.format||"csv",g=`${l.fileName||"data"}.${h}`;if(h==="csv"){const y=_R(this.getState(),l.csv||{});l.download!==!1?PR(new Blob(["\uFEFF"+y],{type:"text/csv"}),g):l.result=y,u(!0)}else f()})),o.on("hotkey",({key:l,event:u,isInput:f})=>{switch(l){case"arrowup":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getPrevRow(g.row)?.id:h[h.length-1]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowdown":{const{flatData:h,focusCell:g,select:y}=this.getState();if(u.preventDefault(),f)return;const w=g?g.column:this._getFirstVisibleColumn()?.id,b=g?this.getNextRow(g.row)?.id:h[0]?.id;w&&b&&(this.in.exec("focus-cell",{row:b,column:w,eventSource:"key"}),y&&this.in.exec("select-row",{id:b}));break}case"arrowright":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getNextColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"arrowleft":{const{focusCell:h}=this.getState();if(f)return;if(u.preventDefault(),h){const g=this.getPrevColumn(h.column,!0)?.id;g&&this.in.exec("focus-cell",{row:h.row,column:g,eventSource:"key"})}break}case"tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getNextEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getNextRow(b);k&&(b=k.id,S=this.getNextEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"shift+tab":{const{editor:h,focusCell:g,select:y}=this.getState();if(h){u.preventDefault();const w=h.column;let b=h.id,S=this.getPrevEditor(this.getRow(b),this.getColumn(w));if(!S){const k=this.getPrevRow(b);k&&(b=k.id,S=this.getPrevEditor(k))}S&&(this.in.exec("open-editor",{id:b,column:S.id}),this.in.exec("focus-cell",{row:b,column:S.id,eventSource:"key"}),y&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}else g&&this.in.exec("focus-cell",{eventSource:"key"});break}case"escape":{const{editor:h}=this.getState();h&&(this.in.exec("close-editor",{ignore:h.type!="multiselect"}),this.in.exec("focus-cell",{row:h.id,column:h.column,eventSource:"key"}));break}case"f2":{const{editor:h,focusCell:g}=this.getState();!h&&g&&this.in.exec("open-editor",{id:g.row,column:g.column});break}case"enter":{const{focusCell:h,tree:g}=this.getState();if(!f&&g&&h&&this.getColumn(h.column).treetoggle){const y=this.getRow(h.row);if(!y.data)return;this.in.exec(y.open?"close-row":"open-row",{id:h.row,nested:!0})}break}case"home":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getFirstVisibleColumn()?.id;this.in.exec("focus-cell",{row:g.row,column:y,eventSource:"key"})}break}case"ctrl+home":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y[0]?.id,S=this._getFirstVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"end":{const{editor:h,focusCell:g}=this.getState();if(!h&&g){u.preventDefault();const y=this._getLastVisibleColumn()?.id,w=g.row;this.in.exec("focus-cell",{row:w,column:y,eventSource:"key"})}break}case"ctrl+end":{const{editor:h,focusCell:g,flatData:y,select:w}=this.getState();if(!h&&g){u.preventDefault();const b=y.at(-1).id,S=this._getLastVisibleColumn()?.id;b&&S&&(this.in.exec("focus-cell",{row:b,column:S,eventSource:"key"}),w&&!this.isSelected(b)&&this.in.exec("select-row",{id:b}))}break}case"ctrl+z":{this.in.exec("undo",{});break}case"ctrl+y":{this.in.exec("redo",{});break}}}),o.on("scroll",l=>{const{_columns:u,split:f,_sizes:h,flatData:g,dynamic:y,_rowHeightFromData:w}=this.getState();let b=-1,S=-1,k=0,N=0;if(l.column){b=0;const A=u.findIndex(j=>j.id===l.column);k=u[A].width;for(let j=f.left??0;j<A;j++){const I=u[j];I.hidden||(b+=I.width)}}if(l.row&&!y){const A=g.findIndex(j=>j.id===l.row);A>=0&&(w?(S=g.slice(0,A).reduce((j,I)=>j+(I.rowHeight||h.rowHeight),0),N=g[A].rowHeight):S=h.rowHeight*A)}this.setState({scroll:{top:S,left:b,width:k,height:N||h.rowHeight}})}),o.on("scroll-to",l=>{const u={};l.top!==void 0&&(u.scrollTop=l.top),l.left!==void 0&&(u.scrollLeft=l.left),Object.keys(u).length&&this.setState(u)}),o.on("print",l=>{const u=qR(l);this.setState({_print:u}),this.setStateAsync({_print:null})}),o.on("undo",()=>{this._historyManager?.handleUndo()}),o.on("redo",()=>{this._historyManager?.handleRedo()}),this.initOnce()}getXlsxWorker(n){if(!this._xlsxWorker){const r=window.URL.createObjectURL(new Blob([`importScripts('${n}');`],{type:"text/javascript"}));this._xlsxWorker=new Promise(o=>{const l=new Worker(r);l.addEventListener("message",u=>{u.data.type==="init"&&o(l)})})}return this._xlsxWorker}initOnce(){const n={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(n)}init(n){n.hasOwnProperty("_skin")&&!n._skin&&(n._skin=ej()),n.columns&&n.columns.forEach(r=>{r.options&&(r.optionsMap=new Map(r.options.map(o=>[o.id,o.label])))}),mh(this.getState().data,n.data)||(n.tree?n.data=this.normalizeTreeRows(n.data):n.data=this.normalizeRows(n.data),this.setState({_filterIds:null,filterValues:{},sortMarks:{},search:null}),this._historyManager&&this._historyManager.resetHistory()),n.tree&&(n.undo=!1,n.reorder=!1),n.split?.right&&(n.split.right=0),n.undo&&!this._historyManager&&(this._historyManager=new QR(this.in,this.getState.bind(this),this.setState.bind(this))),this._router.init({...n})}setState(n,r){return this._router.setState(n,r)}setStateAsync(n){this._router.setStateAsync(n)}getRow(n){const{tree:r}=this.getState();return r?this._branches[n]:this.getState().data.find(o=>o.id===n)}getRowIndex(n,r){return r||(r=this.getState().flatData),r.findIndex(o=>o.id===n)}getNextRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o+1]}getPrevRow(n){const r=this.getState().flatData,o=this.getRowIndex(n,r);return r[o-1]}getColumn(n){return this.getState().columns.find(r=>r.id===n)}getNextColumn(n,r){const o=this.getState()._columns,l=o.findIndex(u=>u.id===n);return r?this._getFirstVisibleColumn(l+1):o[l+1]}getPrevColumn(n,r){const o=this.getState()._columns,l=o.findIndex(u=>u.id===n);return r?this._getLastVisibleColumn(l-1):o[l-1]}_getFirstVisibleColumn(n){const r=this.getState()._columns;let o=n??0;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o++;return r[o]}_getLastVisibleColumn(n){const r=this.getState()._columns;let o=n??r.length-1;for(;o<r.length&&(r[o]?.hidden||r[o]?.collapsed);)o--;return r[o]}isCellEditable(n,r){const{editor:o,hidden:l}=r;return!o||l?!1:typeof o=="function"?o(n,r):!0}getNextEditor(n,r){let o=this.getState().columns;if(r){const l=o.findIndex(u=>u.id===r.id);o=o.slice(l+1)}return o.find(l=>this.isCellEditable(n,l))}getPrevEditor(n,r){let o=this.getState().columns;if(r){const l=o.findLastIndex(u=>u.id===r.id);o=o.slice(0,l)}return o.findLast(l=>this.isCellEditable(n,l))}toggleBranch(n,r,o){let l=this._branches[n],{data:u}=this.getState();if(u=[...u],n!==0){l={...l,open:r};const f=this.updateTreeRow(l);l.$parent===0&&(u=f)}o&&l.data?.length&&l.data.forEach(f=>{const h=this.toggleKids(f,r,o);n===0&&(u=h)}),this.setState({data:u})}toggleKids(n,r,o){n={...n,open:r};const l=this.updateTreeRow(n);return o&&n.data?.length&&n.data.forEach(u=>{this.toggleKids(u,r,o)}),l}updateTreeRow(n){const r=n.id;this._branches[r]=n;const o=this._branches[n.$parent],l=o.data.findIndex(u=>u.id===r);return o.data=[...o.data],o.data[l]=n,o.data}isSelected(n){return this.getState().selectedRows.indexOf(n)!==-1}findAndRemove(n,r){for(let o=0;o<n.length;o++){if(n[o].id===r)return n.splice(o,1)[0];if(n[o].data){const l=[...n[o].data],u=this.findAndRemove(l,r);if(u)return n[o]={...n[o],data:l},u}}return null}insertItem(n,r,o,l){for(let u=0;u<n.length;u++){if(n[u].id===r){const f=n[u],h=l==="before"?u:u+1;if(f.data){if(l==="before"){const g=u>0?n[u-1]:null;return g?.data&&g.open?n[u-1]={...g,data:[...g.data,o]}:n.splice(h,0,o),!0}else if(f.open)return n[u]={...f,data:[o,...f.data]},!0}return n.splice(h,0,o),!0}if(n[u].data&&(n[u]={...n[u],data:[...n[u].data]},this.insertItem(n[u].data,r,o,l)))return!0}return!1}moveItem(n,r,o,l){const u=[...o],f=this.findAndRemove(u,n);return this.insertItem(u,r,f,l),u}copyColumns(n){const r=[];for(let o=0;o<n.length;o++){const l={...n[o]};this.copyHeaderFooter(l,"header"),this.copyHeaderFooter(l,"footer"),r[o]=l}return r}copyHeaderFooter(n,r){let o=n[r];o=Array.isArray(o)?[...o]:[o],o.forEach((l,u)=>{o[u]=typeof l=="string"?{text:l}:{...l}}),n[r]=o}setCollapsibleColumns(n,r,o){let l=n.header;for(let u=0;u<l.length;u++){const f=l[u];if(f.collapsible&&f.collapsed){if(f.collapsible!=="first"){n.collapsed=!0,n.width=36,f.vertical=!0;const g=l.length-u;l=l.slice(0,u+1),l[u].rowspan=g}const h=f.colspan;if(h){const g=l[u+1];let y=1;g&&g.colspan&&!g.collapsed&&(y=g.colspan);for(let w=y;w<h;w++){const b=o[r+w];b&&(b.hidden=!0)}}}}}normalizeColumns(n,r,o,l,u){const f=n[r];f.width||(f.width=f.flexgrow?17:u.columnWidth),f._colindex=r+1;const h=f[o],g=u[`${o}RowHeights`];for(let y=0;y<l;y++){const w=h[y];w.id=f.id,y===h.length-1&&(w.rowspan=w.rowspan?Math.min(w.rowspan,l-y):l-y);for(let b=1;b<w.rowspan;b++){h.splice(y+b,0,{_hidden:!0});for(let S=1;S<w.colspan;S++)n[r+S][o].splice(y+b,0,{})}if(w.rowspan){const b=(w.rowspan===l?g:g.slice(y,w.rowspan+y)).reduce((S,k)=>S+k,0);w.height=b,y+w.rowspan!=l&&w.height--}if(w.colspan){let b=f.width,S=f.flexgrow||0;const k=w.colspan;for(let N=1;N<k;N++){const A=n[r+N];A&&(A.hidden?w.colspan-=1:A.flexgrow?S+=A.flexgrow:b+=A.width||u.columnWidth),S?w.flexgrow=S:w.width=b}}else w.width=f.width,w.flexgrow=f.flexgrow;o==="header"&&w.filter&&typeof w.filter=="string"&&(w.filter={type:w.filter})}h.length>l&&(h.length=l),f[o]=h}normalizeRows(n){for(let r=0;r<n.length;r++)n[r].id||(n[r].id=wp());return n}normalizeTreeRows(n,r,o){return!r&&!o&&(this._branches={0:{data:n}}),n.forEach(l=>{l.id||(l.id=wp()),l.$level=r||0,l.$parent=o||0,this._branches[l.id]=l,l.data&&(l.data.length?(l.$count=l.data.length,this.normalizeTreeRows(l.data,l.$level+1,l.id)):(delete l.data,delete l.$count,delete l.open))}),n}sortTree(n,r){n.sort(r),n.forEach(o=>{o.data&&this.sortTree(o.data,r)})}filterTree(n,r,o){return n.forEach(l=>{r(l)&&o.push(l.id),l.data&&this.filterTree(l.data,r,o)}),o}flattenRows(n,r,o){const l=r;return n.forEach(u=>{(!o||o.includes(u.id))&&l.push(u),u.data?.length&&u.open!==!1&&this.flattenRows(u.data,l,o)}),l}createFilter(n){const{_columns:r}=this.getState(),o=[];for(const l in n){const u=r.find(y=>y.id==l),{config:f,type:h}=u.header.find(y=>y.filter).filter,g=n[l];o.push(y=>{const w=ic(y,u);return f?.handler?f.handler(w,g):MS(h)(w,g)})}return l=>{for(let u=0;u<o.length;u++)if(!o[u](l))return!1;return!0}}searchRows(n,r){n=n.trim().toLowerCase();const o={};if(!n)return o;const{flatData:l,columns:u}=this.getState(),f=r?u.filter(h=>r[h.id]):u;return l.forEach(h=>{const g={};f.forEach(y=>{const w=tc(h,y);String(w).toLowerCase().includes(n)&&(g[y.id]=!0)}),Object.keys(g).length&&(o[h.id]=g)}),o}normalizeSizes(n,r,o,l,u){const f=Uw(n,"header",o,r.headerHeight,u),h=Uw(n,"footer",l,r.footerHeight,u),g=f.reduce((w,b)=>w+b,0),y=h.reduce((w,b)=>w+b,0);return{...r,headerRowHeights:f,footerRowHeights:h,headerHeight:g,footerHeight:y}}},oj=new Date().valueOf();function wp(){return"temp://"+oj++}function lj(t,n="data-id"){let r=t;for(!r.tagName&&t.target&&(r=t.target);r;){if(r.getAttribute&&r.getAttribute(n))return r;r=r.parentNode}return null}new Date().valueOf();var cj=class{constructor(){this.store=new Map}configure(t,n){this.node=n;for(const r in t)if(t[r]){const o=r.toLowerCase().replace(/[ ]/g,""),l=t[r];this.store.set(o,l)}}},Rd=[],uj={subscribe:t=>{dj();const n=new cj;return Rd.push(n),t(n),()=>{const r=Rd.findIndex(o=>o===n);r>=0&&Rd.splice(r,1)}}},qw=!1;function dj(){qw||(qw=!0,document.addEventListener("keydown",t=>{if(Rd.length&&(t.ctrlKey||t.altKey||t.metaKey||t.shiftKey||t.key.length>1||t.key===" ")){const n=[];t.ctrlKey&&n.push("ctrl"),t.altKey&&n.push("alt"),t.metaKey&&n.push("meta"),t.shiftKey&&n.push("shift");let r=t.code.replace("Key","").toLocaleLowerCase();t.key===" "&&(r="space"),n.push(r);const o=n.join("+");for(let l=Rd.length-1;l>=0;l--){const u=Rd[l],f=u.store.get(o)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:o,evKey:r})}}}))}const fj={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 mj(t,{keys:n,exec:r}){if(!n)return;function o(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||lj(h,"data-header-id")?.classList.contains("wx-filter")||!!h.closest(".wx-cell.wx-editor")}const l={};for(const f in n){const h=n[f];typeof h<"u"&&(typeof h=="function"?l[f]=h:h&&(l[f]=g=>{const y=o(g);r({key:f,event:g,isInput:y})}))}const u=uj.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function pj(t,n){let r=null;n.scroll.subscribe(o=>{if(!o||o===r)return;r=o;const{left:l,top:u,height:f,width:h}=o,g=n.getHeight(),y=n.getWidth(),w=n.getScrollMargin();if(u>=0){const b=t.scrollTop;u<b?t.scrollTop=u:u+f>b+g&&(t.scrollTop=u-g+f)}if(l>=0){const b=t.scrollLeft;l<b?t.scrollLeft=l:l+h>b+y-w&&(t.scrollLeft=l-y+h+w)}}),n.scrollLeft?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollLeft-o)>1&&(t.scrollLeft=o)})}),n.scrollTop?.subscribe?.(o=>{requestAnimationFrame(()=>{Math.abs(t.scrollTop-o)>1&&(t.scrollTop=o)})})}const Es=d.createContext(null);function hj(t,n){const r=new ResizeObserver(o=>{requestAnimationFrame(()=>n(o[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const Ww=5,gj=700;function _p(t){const n=t.getBoundingClientRect(),r=document.body,o=n.top+r.scrollTop-r.clientTop||0,l=n.left+r.scrollLeft-r.clientLeft||0;return{y:Math.round(o),x:Math.round(l),width:t.offsetWidth,height:t.offsetHeight}}function yv(t,n){const r=_p(n);return{x:t.clientX-r.x,y:t.clientY-r.y}}function vj(t,n){const r=n.current;let o=null,l,u,f=!1,h=!1;const g=document.createElement("DIV");g.className="wx-drag-zone",g.setAttribute("tabindex",-1);function y(){clearTimeout(l),l=null}function w(D){const K=Id(D);K&&(o={container:g,sourceNode:D.target,from:uh(K),pos:yv(D,t)},u=o.pos,b(D))}function b(D){if(!o)return;const K=o.pos=yv(D,t);if(!f){if(!h&&!D?.target?.getAttribute("draggable-data")&&Math.abs(u.x-K.x)<Ww&&Math.abs(u.y-K.y)<Ww)return;if(F(D)===!1)return H()}if(h){const z=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,W=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;o.targetNode=document.elementFromPoint(D.pageX-z,D.pageY-W)}else o.targetNode=D.target;r.move&&r.move(D,o),g.style.left=-(o.offset?o.offset.x:0)+"px",g.style.top=o.pos.y+(o.offset?o.offset.y:0)+"px"}function S(D){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(D,o),o=u=null,H()}function k(D){r.getReorder&&!r.getReorder()||D.button===0&&(B(D),window.addEventListener("mousemove",N),window.addEventListener("mouseup",A),w(D))}function N(D){b(D)}function A(D){S(D)}function j(D){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(D.touches[0])},gj),B(D);function K(){l&&y(),D.target.removeEventListener("touchmove",I),D.target.removeEventListener("touchend",K),S(D)}D.target.addEventListener("touchmove",I),D.target.addEventListener("touchend",K),t.addEventListener("contextmenu",T)}function I(D){f?(D.preventDefault(),b(D.touches[0])):l&&y()}function T(D){if(f||l)return D.preventDefault(),!1}function _(D){D.preventDefault()}function B(D){if(!r.getDraggableInfo)return;const{hasDraggable:K}=r.getDraggableInfo();(!K||D.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(D){if(f=!0,r.start){if(r.start(D,o)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function H(D){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",A),D&&(t.removeEventListener("mousedown",k),t.removeEventListener("touchstart",j),t.removeEventListener("dragstart",_))}return t.addEventListener("mousedown",k),t.addEventListener("touchstart",j),t.addEventListener("dragstart",_),{destroy(){H(!0)}}}const yj=.004;function bj(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function wj(t,n,r,o){const{node:l,left:u,top:f,bottom:h,sense:g,xScroll:y,yScroll:w}=o,b=yv(t,l);r.scrollState||(r.scrollState=bj());let S=0,k=0;b.x<u+g?S=-1:b.x>n.width-g&&(S=1),b.y<f+Math.round(g/2)?k=-1:b.y>n.height-h-Math.round(g/2)&&(k=1),(r.scrollState.dirX!==S||r.scrollState.dirY!==k)&&(AS(r),r.scrollState.dirX=S,r.scrollState.dirY=k),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&xj(r,o,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function xj(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(Sj,15,t,n,r)},250))}function AS(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function Sj(t,n,r){const{x:o,y:l}=r;t.scrollSpeedFactor+=yj,o!==0&&kj(t,n,o),l!==0&&Cj(t,n,l)}function Cj(t,n,r){const o=n.node.scrollTop;NS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function kj(t,n,r){const o=n.node.scrollLeft;NS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function NS(t,n,r){r.node[n]=t}function ph(t,n,r,o,l,u){const f={};return t&&(f.width=`${t}px`,f.minWidth=`${t}px`),n&&(f.flexGrow=n),u&&(f.height=`${u}px`),r&&(f.position="sticky",r.left&&(f.left=`${o}px`),r.right&&(f.right=`${l}px`)),f}function TS(t,n,r){let o="";if(t.fixed)for(const l in t.fixed){let u=t.fixed[l]===-1;!u&&t.fixed.leftSize&&n.colspan&&(u=n.colspan+t._colindex-1===t.fixed.leftSize),o+=u?"wx-shadow ":"wx-fixed "}return o+=n.rowspan>1?"wx-rowspan ":"",o+=n.colspan>1?"wx-colspan ":"",o+=n.vertical?"wx-vertical ":"",o+=r?r(t)+" ":"",o}function Mj(t){const{row:n,column:r,cellStyle:o=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(Es),g=Ot(h,"focusCell"),y=Ot(h,"search"),w=Ot(h,"reorder"),b=d.useMemo(()=>y?.rows[n.id]&&y.rows[n.id][r.id],[y,n.id,r.id]),S=d.useMemo(()=>ph(r.width,r.flexgrow,r.fixed,r.left,r.right),[r.width,r.flexgrow,r.fixed,r.left,r.right]);function k(F,H){let D="wx-cell";return D+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",D+=F?" "+F(r):"",D+=H?" "+H(n,r):"",D+=r.treetoggle?" wx-tree-cell":"",D}const N=d.useMemo(()=>k(l,o),[l,o,r,n]),A=d.useMemo(()=>typeof r.draggable=="function"?r.draggable(n,r)!==!1:r.draggable,[r,n]),j=d.useRef(null);d.useEffect(()=>{j.current&&f&&g?.row===n.id&&g?.column===r.id&&j.current.focus()},[g,f,n.id,r.id]);const I=d.useCallback(()=>{f&&!g&&h.exec("focus-cell",{row:n.id,column:r.id,eventSource:"focus"})},[h,f,g,n.id,r.id]);function T(F){const H=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(H).map(D=>({text:D,highlight:H.test(D)}))}const _=d.useMemo(()=>{const F=r.fixed&&r.fixed.left===-1||r.fixed.right===-1,H=r.fixed&&r.fixed.right;return[N,F?"wx-shadow":"",H?"wx-fixed-right":""].filter(Boolean).join(" ")},[N,r]),B=r.cell;return i.jsxs("div",{className:"wx-TSCaXsGV "+_,ref:j,onFocus:I,style:S,"data-row-id":Fa(n.id),"data-col-id":Fa(r.id),tabIndex:f?"0":"-1",role:"gridcell","aria-colindex":r._colindex,"aria-readonly":r.editor?void 0:!0,children:[w&&r.draggable?A?i.jsx("i",{"draggable-data":"true",className:"wx-TSCaXsGV wx-draggable wxi-drag"}):i.jsx("i",{className:"wx-TSCaXsGV wx-draggable-stub"}):null,r.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:`${n.$level*28}px`}}),n.$count?i.jsx("i",{"data-action":"toggle-row",className:`wx-TSCaXsGV wx-table-tree-toggle wxi-menu-${n.open!==!1?"down":"right"}`}):null]}):null,B?i.jsx(B,{api:h,row:n,column:r,onAction:({action:F,data:H})=>h.exec(F,H)}):u?u():b?i.jsx("span",{children:T(tc(n,r)).map(({highlight:F,text:H},D)=>F?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:H},D):i.jsx("span",{children:H},D))}):tc(n,r)]})}function Gw(t,n){let r,o;function l(h){r=h.clientX,t.style.opacity=1,document.body.style.cursor="ew-resize",document.body.style.userSelect="none",window.addEventListener("mousemove",u),window.addEventListener("mouseup",f),n&&n.down&&n.down(t)}function u(h){o=h.clientX-r,n&&n.move&&n.move(o)}function f(){t.style.opacity="",document.body.style.cursor="",document.body.style.userSelect="",n&&n.up&&n.up(o),window.removeEventListener("mousemove",u),window.removeEventListener("mouseup",f)}return t.addEventListener("mousedown",l),{destroy(){t.removeEventListener("mousedown",l)}}}function Aj({filter:t,column:n,action:r,filterValue:o}){function l({value:u}){r({value:u,key:n.id})}return i.jsx(qv,{...t.config??{},value:o,onChange:l})}function Nj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Es),u=Ot(l,"flatData"),f=d.useMemo(()=>t?.config?.options||n?.options||g(),[t,n,u]),h=d.useMemo(()=>t?.config?.template,[t]);function g(){const b=[];return u.forEach(S=>{const k=ic(S,n);b.includes(k)||b.push(k)}),b.map(S=>({id:S,label:S}))}function y({value:b}){r({value:b,key:n.id})}function w(b){b.key!=="Tab"&&b.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:w,children:i.jsx(zT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:o,onChange:y,children:b=>h?h(b):b.label})})}function Tj({filter:t,column:n,action:r,filterValue:o}){function l({value:u}){r({value:u,key:n.id})}return i.jsx("div",{className:"wx-aaaK5VYO",style:{width:"100%"},children:i.jsx(HT,{placeholder:"",clear:!0,...t?.config??{},value:o,onChange:l})})}function RS(t){const{value:n,options:r=[],placeholder:o="",clear:l=!1,text:u=null,template:f=null,cell:h=null,dropdown:g={},autoOpen:y=!1,onChange:w,onAction:b}=t,[S,k]=mS(n||[]),N=d.useMemo(()=>(S||[]).map(W=>r.find(q=>q.id===W)).filter(Boolean),[S,r]),A=d.useRef(null),j=d.useRef(null),[I,T]=d.useState(null),_=()=>{const W=S||[];if(!W.length)return 0;const q=r.find(V=>W.includes(V.id));return q?r.indexOf(q):0};function B(W){j.current=W.navigate,T(()=>W.keydown),y&&W.navigate(_())}d.useEffect(()=>{y&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:W}){k(W),w&&w({value:W})}function H(W){W.stopPropagation(),k([]),w&&w({value:[]})}function D(){j.current?.(_())}function K(){j.current?.(null)}function z(W){I?.(W,_())}return i.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:D,onKeyDown:z,tabIndex:0,children:[i.jsx("div",{className:"wx-label wx-aadNNOwy",children:f?f(N):h?i.jsx(h,{data:N,onAction:b}):u?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:u}):N.length?i.jsx("span",{className:"wx-text wx-aadNNOwy",children:N.map(W=>W.label).join(", ")}):o?i.jsx("span",{className:"wx-placeholder wx-aadNNOwy",children:o}):" "}),l&&S?.length?i.jsx("i",{className:"wx-icon wxi-close wx-aadNNOwy",onClick:H}):i.jsx("i",{className:"wx-icon wxi-angle-down wx-aadNNOwy"}),i.jsx(fh,{items:r,onReady:B,onSelect:F,multiselect:!0,checkboxes:!0,value:S||[],onCancel:K,...g,children:({option:W})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(W):h?i.jsx(h,{data:W,onAction:b}):W.label})})]})}function Rj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Ba.i18n)?.getGroup("grid")||lm(Vv).getGroup("grid"),u=d.useMemo(()=>({clear:!0,...t?.config||{}}),[t]),f=d.useMemo(()=>u.options||n.options,[u,n]),h=d.useMemo(()=>{const w=o?.length;return w?w<3?o.map(b=>n.optionsMap.get(b)).join(", "):w+" "+l("selected"):""},[o,n,l]);function g({value:w}){r({value:w,key:n.id})}function y(w){w.key!=="Tab"&&w.preventDefault()}return i.jsx("div",{style:{width:"100%"},onKeyDown:y,children:i.jsx(RS,{placeholder:"",...u,options:f,value:o||[],text:h,onChange:g})})}const jj={text:Aj,richselect:Nj,datepicker:Tj,multiselect:Rj};function Ej({filter:t,column:n}){const r=d.useContext(Es),o=Ot(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>jj[t.type],[t.type]);return i.jsx(u,{filter:t,column:n,action:l,filterValue:o[n.id]})}function Dj(t){const{cell:n,column:r,row:o,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(Es),w=Ot(y,"sortMarks"),b=d.useMemo(()=>w?w[r.id]:void 0,[w,r.id]),S=d.useRef(),k=d.useCallback(ve=>{S.current=n.flexgrow?ve.parentNode.clientWidth:n.width},[n.flexgrow,n.width]),N=d.useCallback((ve,J)=>{y.exec("resize-column",{id:n.id,width:Math.max(1,(S.current||0)+ve),inProgress:J})},[y,n.id]),A=d.useCallback(ve=>N(ve,!0),[N]),j=d.useCallback(ve=>N(ve,!1),[N]),I=d.useCallback(ve=>{if(!r.sort||n.filter)return;let J=b?.order;J&&(J=J==="asc"?"desc":"asc"),y.exec("sort-rows",{key:n.id,add:ve.ctrlKey||ve.metaKey,order:J})},[y,n.id,n.filter,r.sort,b?.order]),T=d.useCallback(ve=>{ve&&ve.stopPropagation(),y.exec("collapse-column",{id:n.id,row:o})},[y,n.id,o]),_=d.useCallback(ve=>{ve.key==="Enter"&&T()},[T]),B=d.useCallback(ve=>{ve.key==="Enter"&&!n.filter&&I(ve)},[I,n.filter]),F=d.useMemo(()=>n.collapsed&&r.collapsed,[n.collapsed,r.collapsed]),H=d.useMemo(()=>F&&!g&&n.collapsible!=="header",[F,g,n.collapsible]),D=d.useMemo(()=>H?{top:-h/2,position:"absolute"}:{},[H,h]),K=d.useMemo(()=>ph(n.width,n.flexgrow,r.fixed,r.left,n.right??r.right,n.height+(F&&H?h:0)),[n.width,n.flexgrow,r.fixed,r.left,n.right,r.right,n.height,F,H,h]),z=d.useMemo(()=>TS(r,n,f),[r,n,f]),W=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([ve])=>ve!=="cell")),[n]),q=`wx-cell ${z} ${n.css||""} wx-collapsed`,V=["wx-cell",z,n.css||"",n.filter?"wx-filter":"",r.fixed&&r.fixed.right?"wx-fixed-right":""].filter(Boolean).join(" "),X=d.useRef(null);return d.useEffect(()=>{const ve=X.current;if(!ve)return;const J=Gw(ve,{down:k,move:A,up:j});return()=>{typeof J=="function"&&J()}},[k,A,j,Gw]),F?i.jsx("div",{className:"wx-RsQD74qC "+q,style:K,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:T,"data-header-id":Fa(r.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:D,children:n.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+V,style:K,onClick:I,"data-header-id":Fa(r.id),tabIndex:!n._hidden&&r.sort&&!n.filter?0:void 0,role:"columnheader","aria-colindex":r._colindex,"aria-colspan":n.colspan>1?n.colspan:void 0,"aria-rowspan":n.rowspan>1?n.rowspan:void 0,"aria-sort":!b?.order||n.filter?"none":b?.order==="asc"?"ascending":"descending",onKeyDown:B,children:[n.collapsible?i.jsx("div",{className:"wx-RsQD74qC wx-collapse",role:"button","aria-label":n.collapsed?"Expand column":"Collapse column","aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:T,children:i.jsx("i",{className:`wx-RsQD74qC wxi-angle-${n.collapsed?"down":"right"}`})}):null,n.cell?(()=>{const ve=n.cell;return i.jsx(ve,{api:y,cell:W(),column:r,row:o,onAction:({action:J,data:$})=>y.exec(J,$)})})():n.filter?i.jsx(Ej,{filter:n.filter,column:r}):i.jsx("div",{className:"wx-RsQD74qC wx-text",children:n.text||""}),r.resize&&l&&!n._hidden?i.jsx("div",{className:"wx-RsQD74qC wx-grip",role:"presentation","aria-label":"Resize column",ref:X,onClick:ve=>ve.stopPropagation(),children:i.jsx("div",{})}):null,u?i.jsx("div",{className:"wx-RsQD74qC wx-sort",children:b?i.jsxs(i.Fragment,{children:[typeof b.index<"u"?i.jsx("div",{className:"wx-RsQD74qC wx-order",children:b.index+1}):null,i.jsx("i",{className:`wx-RsQD74qC wxi-arrow-${b.order==="asc"?"up":"down"}`})]}):null}):null]})}function Ij({cell:t,column:n,row:r,columnStyle:o}){const l=d.useContext(Es),u=d.useMemo(()=>ph(t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right??n?.right,t?.height),[t?.width,t?.flexgrow,n?.fixed,n?.left,t?.right,n?.right,t?.height]),f=d.useMemo(()=>TS(n,t,o),[n,t,o]),h=d.useCallback(()=>Object.fromEntries(Object.entries(t||{}).filter(([y])=>y!=="cell")),[t]),g=`wx-6Sdi3Dfd wx-cell ${f||""} ${t?.css||""}`+(n?.fixed&&n?.fixed.right?" wx-fixed-right":"");return i.jsx("div",{className:g,style:u,children:!n?.collapsed&&!t?.collapsed?t?.cell?Cv.createElement(t.cell,{api:l,cell:h(),column:n,row:r,onAction:({action:y,data:w})=>l.exec(y,w)}):i.jsx("div",{className:"wx-6Sdi3Dfd wx-text",children:t?.text||""}):null})}function Vw({deltaLeft:t,contentWidth:n,columns:r,type:o="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(Es),h=Ot(f,"_sizes"),g=Ot(f,"split"),y=d.useMemo(()=>h?.[`${o}RowHeights`],[h,o]),w=d.useMemo(()=>{let A=[];if(r&&r.length){const j=r[0][o].length;for(let I=0;I<j;I++){let T=0;A.push([]),r.forEach((_,B)=>{const F={..._[o][I]};T||A[I].push(F),F.colspan>1?T=F.colspan-1:T&&T--})}}return A},[r,o]),b=d.useMemo(()=>g?.left||g?.right,[g]);function S(A){return r.find(j=>j.id===A)}function k(A,j){let I=j;return A.rowspan&&(I+=A.rowspan-1),I===w.length-1}function N(A,j,I){if(!I.sort)return!1;for(let T=w.length-1;T>=0;T--){const _=I.header[T];if(!_.filter&&!_._hidden)return j===T}return k(A,j)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${o}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((A,j)=>i.jsx("div",{className:o==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[j]}px`,display:"flex"},role:"row",children:A.map(I=>{const T=S(I.id);return o==="header"?i.jsx(Dj,{cell:I,columnStyle:l,column:T,row:j,lastRow:k(I,j),bodyHeight:u,sortRow:N(I,j,T),hasSplit:b},I.id):i.jsx(Ij,{cell:I,columnStyle:l,column:S(I.id),row:j},I.id)})},j))})}function Lj({overlay:t}){const n=d.useContext(Es);function r(l){return typeof l=="function"}const o=t;return i.jsx("div",{className:"wx-1ty666CQ wx-overlay",children:r(t)?i.jsx(o,{onAction:({action:l,data:u})=>n.exec(l,u)}):t})}function Pj(t){const{editor:n,onSave:r,onApply:o}=t,[l,u]=d.useState(n?.value||""),{type:f="text"}=d.useMemo(()=>n?.config||{},[n]),h=d.useRef(null);d.useEffect(()=>{h.current&&h.current.focus()},[]),d.useEffect(()=>{if(!h.current)return;const w=ho(h.current,()=>r(!0));return()=>w.destroy()},[r]);function g(){h.current&&(u(h.current.value),o(h.current.value))}function y({key:w}){w==="Enter"&&r()}return i.jsx("input",{className:"wx-e7Ao5ejY wx-text",onInput:g,onKeyDown:y,ref:h,type:f,value:l})}function _j({editor:t,onAction:n,onSave:r,onApply:o,onCancel:l}){const[u,f]=d.useState(t?.value),[h,g]=d.useState(t?.renderedValue),[y,w]=d.useState(t?.options||[]),b=d.useMemo(()=>t?.config?.template,[t]),S=d.useMemo(()=>t?.config?.cell,[t]),k=d.useMemo(()=>t?.config?.dropdown||{},[t]),N=d.useMemo(()=>({trackScroll:!0,...k}),[k]),A=d.useMemo(()=>(y||[]).findIndex(D=>D.id===u),[y,u]),j=d.useRef(null),I=d.useRef(null),T=d.useCallback(D=>{j.current=D.navigate,I.current=D.keydown,j.current(A)},[A,j]),_=d.useCallback(D=>{const K=D?.target?.value??"";g(K);const z=K?(t?.options||[]).filter(W=>(W.label||"").toLowerCase().includes(K.toLowerCase())):t?.options||[];w(z),z.length?j.current(-1/0):j.current(null)},[t]),B=d.useRef(null);d.useEffect(()=>{B.current&&B.current.focus()},[]);const F=d.useRef(r);d.useEffect(()=>{F.current=r},[r]),d.useEffect(()=>{if(!B.current)return;const D=ho(B.current,()=>F.current(!0));return()=>D.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const H=d.useCallback(({id:D})=>{o(D),r()},[o,r]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:B,value:h??"",onChange:_,onKeyDown:D=>I.current?I.current(D,A):void 0}),i.jsx(fh,{items:y,onReady:T,onSelect:H,...N,onCancel:l,children:({option:D})=>b?b(D):S?i.jsx(S,{data:D,onAction:n}):D.label})]})}function Fj({editor:t,onAction:n,onSave:r,onApply:o,onCancel:l}){const[u]=d.useState(()=>t.value||new Date),{template:f,cell:h,dropdown:g={}}=t?.config||{},y=d.useMemo(()=>({trackScroll:!0,width:"auto",...g}),[g]);function w({value:N}){o(N),r()}const b=d.useRef(null),[S,k]=d.useState(null);return d.useEffect(()=>{b.current&&b.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!S)return;const N=ho(S,()=>r(!0));return()=>N.destroy()},[S,r]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-lNWNYUb6 wx-value",ref:b,tabIndex:0,onClick:l,onKeyDown:N=>N.preventDefault(),children:f?f(u):h?i.jsx(h,{data:t.value,onAction:n}):i.jsx("span",{className:"wx-lNWNYUb6 wx-text",children:t.renderedValue})}),i.jsx(Uv,{...y,onCancel:l,children:i.jsx("div",{ref:k,className:"wx-lNWNYUb6",children:i.jsx(lS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function Oj(t){const{editor:n}=t,r=t.onAction??t.onaction,o=t.onSave??t.onsave,l=t.onApply??t.onapply,u=t.onCancel??t.oncancel,f=n.config||{},{dropdown:h={}}=f,g=d.useMemo(()=>({trackScroll:!0,...h}),[h]),[y]=d.useState(n.options.find(_=>_.id===n.value)),[w]=d.useState(n.value),[b]=d.useState(n.options),S=d.useMemo(()=>b.findIndex(_=>_.id===w),[b,w]);function k({id:_}){l(_),o()}let N;const[A,j]=d.useState();function I(_){N=_.navigate,j(()=>_.keydown),N(S)}const T=d.useRef(null);return d.useEffect(()=>{T.current&&T.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!T.current)return;const _=ho(T.current,()=>o(!0));return()=>_.destroy()},[o]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:T,className:"wx-ywGRk611 wx-value",tabIndex:0,onClick:u,onKeyDown:_=>{A(_,S),_.preventDefault()},children:f.template?f.template(y):f.cell?(()=>{const _=f.cell;return i.jsx(_,{data:y,onAction:r})})():i.jsx("span",{className:"wx-ywGRk611 wx-text",children:n.renderedValue})}),i.jsx(fh,{items:b,onReady:I,onSelect:k,...g,onCancel:u,children:({option:_})=>f.template?f.template(_):f.cell?(()=>{const B=f.cell;return i.jsx(B,{data:_,onAction:r})})():_.label})]})}function Bj(t){const{editor:n,onAction:r,onSave:o,onApply:l}=t,u=n?.config||{},f=n?.options??[],h=n?.value||[],g=n?.renderedValue,y=d.useMemo(()=>({trackScroll:!0,...u.dropdown||{}}),[u]);function w({value:S}){l(S)}const b=d.useRef(null);return d.useEffect(()=>{if(!b.current)return;const S=ho(b.current,()=>o(!0));return()=>S.destroy()},[o]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>o(!0),children:i.jsx(RS,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const Hj={text:Pj,combo:_j,datepicker:Fj,richselect:Oj,multiselect:Bj};function zj({column:t,row:n}){const r=d.useContext(Es),o=Ot(r,"editor"),l=d.useCallback((N,A)=>{r.exec("close-editor",{ignore:N}),A&&r.exec("focus-cell",{...A,eventSource:"click"})},[r]),u=d.useCallback(N=>{const A=N?null:{row:o?.id,column:o?.column};l(!1,A)},[o,l]),f=d.useCallback(()=>{l(!0,{row:o?.id,column:o?.column})},[o,l]),h=d.useCallback(N=>{r.exec("editor",{value:N})},[r]),g=d.useCallback(N=>{N.key==="Enter"&&o&&(t.editor.type==="multiselect"?h(o.value):f())},[o,t.editor,f,h]),y=d.useMemo(()=>ph(t.width,t.flexgrow,t.fixed,t.left,t.right),[t.width,t.flexgrow,t.fixed,t.left,t.right]),w=d.useMemo(()=>{let N=t.editor;if(typeof N=="function"&&(N=N(n,t)),!N)return null;let A=typeof N=="string"?N:N.type;return Hj[A]},[t,n]),b=d.useRef(null);d.useEffect(()=>{b.current&&typeof y=="string"&&b.current.setAttribute("style",y)},[y]);const S=typeof n.$parent<"u"?"gridcell":"cell",k=typeof n.$parent<"u"?!t.editor:void 0;return i.jsx("div",{className:"wx-8l724t2g wx-cell wx-editor",ref:b,style:typeof y=="object"&&y!==null?y:void 0,role:S,"aria-readonly":k,tabIndex:-1,onClick:N=>N.stopPropagation(),onDoubleClick:N=>N.stopPropagation(),onKeyDown:g,children:w?i.jsx(w,{editor:o,onSave:u,onApply:h,onCancel:f,onAction:({action:N,data:A})=>r.exec(N,A)}):null})}function Kw(t){const{columns:n,type:r,columnStyle:o}=t,l=d.useContext(Es),{filterValues:u,_columns:f,_sizes:h}=l.getState();function g(y){return o?" "+o(y):""}return i.jsx(i.Fragment,{children:n.map((y,w)=>i.jsx("tr",{children:y.map(b=>{const S=f.find(A=>A.id===b.id),k=`wx-print-cell-${r}${g(S)}${b.filter?" wx-print-cell-filter":""}${b.vertical?" wx-vertical":""}`,N=b.cell;return i.jsx("th",{style:pS(CS(b,h.columnWidth)),className:"wx-Gy81xq2u "+k,rowSpan:b.rowspan,colSpan:b.colspan,children:N?i.jsx(N,{api:l,cell:Object.fromEntries(Object.entries(b).filter(([A])=>A!=="cell")),column:S,row:w}):b.filter?i.jsx("div",{className:"wx-Gy81xq2u wx-print-filter",children:WR(u,f,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function $j(t){const{columns:n,rowStyle:r,columnStyle:o,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(Es),{flatData:y,_sizes:w}=g.getState(),b=u&&zw(n,"header",w.headerRowHeights),S=f&&zw(n,"footer",w.footerRowHeights);function k(A,j){let I="";return I+=o?" "+o(j):"",I+=l?" "+l(A,j):"",I}function N(A,j){return typeof j.draggable=="function"?j.draggable(A,j)!==!1:j.draggable}return i.jsxs("table",{className:`wx-8NTMLH0z wx-print-grid ${n.some(A=>A.flexgrow)?"wx-flex-columns":""}`,children:[u?i.jsx("thead",{children:i.jsx(Kw,{columns:b,type:"header",columnStyle:o})}):null,i.jsx("tbody",{children:y.map((A,j)=>i.jsx("tr",{className:"wx-8NTMLH0z wx-row"+(r?" "+r(A):""),style:{height:`${A.rowHeight||w.rowHeight}px`},children:n.map(I=>I.collapsed?null:i.jsxs("td",{className:`wx-8NTMLH0z wx-print-cell wx-cell ${k(A,I)}`,style:pS(CS(I,w.columnWidth)),children:[h&&I.draggable?i.jsx("span",{className:"wx-8NTMLH0z wx-print-draggable",children:N(A,I)?i.jsx("i",{className:"wx-8NTMLH0z wxi-drag"}):null}):null,I.treetoggle?i.jsxs(i.Fragment,{children:[i.jsx("span",{style:{marginLeft:A.$level*28+"px"}}),A.$count?i.jsx("i",{className:`wx-8NTMLH0z wx-print-grid-tree-toggle wxi-menu-${A.open!==!1?"down":"right"}`}):null]}):null,I.cell?(()=>{const T=I.cell;return i.jsx(T,{api:g,row:A,column:I})})():i.jsx("span",{children:tc(A,I)})]},I.id))},j))}),f?i.jsx("tfoot",{children:i.jsx(Kw,{columns:S,type:"footer",columnStyle:o})}):null]})}function Uj(t){const{config:n,...r}=t,o=d.useContext(Es),{_skin:l,_columns:u}=o.getState(),f=d.useMemo(()=>zR(u,n),[]),h=d.useRef(null);return d.useEffect(()=>{const g=document.body;g.classList.add("wx-print");const y=h.current;if(!y)return;const w=y.cloneNode(!0);g.appendChild(w);const b=`@media print { @page { size: ${n.paper} ${n.mode}; }`,S=document.createElement("style");S.setAttribute("type","text/css"),S.setAttribute("media","print"),document.getElementsByTagName("head")[0].appendChild(S),S.appendChild(document.createTextNode(b)),window.print(),S.remove(),g.classList.remove("wx-print"),w.remove()},[]),i.jsx("div",{className:`wx-4zwCKA7C wx-${l}-theme wx-print-container`,ref:h,children:f.map((g,y)=>i.jsx("div",{className:"wx-4zwCKA7C wx-print-grid-wrapper",children:i.jsx($j,{columns:g,...r})},y))})}function qj(t){const{header:n,footer:r,overlay:o,multiselect:l,onreorder:u,rowStyle:f,columnStyle:h,cellStyle:g,autoRowHeight:y,resize:w,clientWidth:b,clientHeight:S,responsiveLevel:k,hotkeys:N}=t,A=d.useContext(Es),j=Ot(A,"dynamic"),I=Ot(A,"_columns"),T=Ot(A,"flatData"),_=Ot(A,"split"),B=Ot(A,"_sizes"),[F,H]=Xs(A,"selectedRows"),D=Ot(A,"select"),K=Ot(A,"editor"),z=Ot(A,"scrollLeft"),W=Ot(A,"scrollTop"),q=Ot(A,"tree"),V=Ot(A,"focusCell"),X=Ot(A,"_print"),ve=Ot(A,"undo"),J=Ot(A,"reorder"),$=Ot(A,"_rowHeightFromData"),[P,se]=d.useState(0);d.useEffect(()=>{se(ya())},[]);const[we,Z]=d.useState(0),Se=d.useMemo(()=>(I||[]).some(oe=>!oe.hidden&&oe.flexgrow),[I]),ae=d.useMemo(()=>B?.rowHeight||0,[B]),ye=d.useRef(null),[Pe,de]=d.useState(null),[Qe,ue]=d.useState(null),_e=d.useMemo(()=>{let oe=[],$e=0;return _&&_.left&&(oe=(I||[]).slice(0,_.left).filter(tt=>!tt.hidden).map(tt=>({...tt})),oe.forEach(tt=>{tt.fixed={left:1,leftSize:_.left},tt.left=$e,$e+=tt.width}),oe.length&&(oe[oe.length-1].fixed.left=-1)),{columns:oe,width:$e}},[_,I]),Ze=d.useMemo(()=>{let oe=[],$e=0;if(_&&_.right){oe=(I||[]).slice(_.right*-1).filter(tt=>!tt.hidden).map(tt=>({...tt}));for(let tt=oe.length-1;tt>=0;tt--){const Pt=oe[tt];Pt.fixed={right:1},Pt.right=$e,$e+=Pt.width}oe.length&&(oe[0].fixed={right:-1})}return{columns:oe,width:$e}},[_,I]),at=d.useMemo(()=>{const oe=(I||[]).slice(_?.left||0,(I||[]).length-(_?.right??0)).filter($e=>!$e.hidden);return oe.forEach($e=>{$e.fixed=0}),oe},[I,_]),Ee=d.useMemo(()=>(I||[]).reduce((oe,$e)=>($e.hidden||(oe+=$e.width),oe),0),[I]),Ge=1;function me(oe,$e,tt){let Pt=$e,wn=oe;if(at.length){let Oe=at.length;for(let it=oe;it>=0;it--)at[it][tt].forEach(Nt=>{Nt.colspan>1&&it>oe-Nt.colspan&&it<Oe&&(Oe=it)});if(Oe!==at.length&&Oe<oe){for(let it=Oe;it<oe;it++)Pt-=at[it].width;wn=Oe}}return{index:wn,delta:Pt}}const ke=d.useMemo(()=>{let oe,$e,tt;const Pt=z||0,wn=(z||0)+(b||0);let Oe=0,it=0,Nt=0,bt=0;at.forEach((Ht,Pn)=>{Pt>Nt&&(Oe=Pn,bt=Nt),Nt=Nt+Ht.width,wn>Nt&&(it=Pn+Ge)});const Gt={header:0,footer:0};for(let Ht=it;Ht>=Oe;Ht--)["header","footer"].forEach(Pn=>{at[Ht]&&at[Ht][Pn].forEach(Ha=>{const sr=Ha.colspan;if(sr&&sr>1){const Rr=sr-(it-Ht+1);Rr>0&&(Gt[Pn]=Math.max(Gt[Pn],Rr))}})});const ra=me(Oe,bt,"header"),Cn=me(Oe,bt,"footer"),qn=ra.delta,Qt=ra.index,En=Cn.delta,qr=Cn.index;return Se&&Ee>(b||0)?oe=$e=tt=[..._e.columns,...at,...Ze.columns]:(oe=[..._e.columns,...at.slice(Oe,it+1),...Ze.columns],$e=[..._e.columns,...at.slice(Qt,it+Gt.header+1),...Ze.columns],tt=[..._e.columns,...at.slice(qr,it+Gt.footer+1),...Ze.columns]),{data:oe||[],header:$e||[],footer:tt||[],d:bt,df:En,dh:qn}},[at,_e,Ze,z,b,Se,Ee]),et=d.useMemo(()=>n&&B?.headerHeight||0,[n,B]),Me=d.useMemo(()=>r&&B?.footerHeight||0,[r,B]),pe=d.useMemo(()=>b&&S?Ee>=b:!1,[b,S,Ee]),[qe,Re]=d.useState(!1),st=d.useMemo(()=>(S||0)-et-Me-(pe?P:0),[S,et,Me,pe,P]),jt=d.useMemo(()=>Math.ceil((st||0)/(ae||1))+1,[st,ae]),O=d.useRef([]),[ze,We]=d.useState(0),[Et,lt]=d.useState(void 0),ht=d.useMemo(()=>{let oe=0,$e=0;const tt=2,Pt=W||0;if(y){let it=Pt;for(;it>0;)it-=O.current[oe]||ae,oe++;$e=Pt-it;for(let Nt=Math.max(0,oe-tt-1);Nt<oe;Nt++)$e-=O.current[oe-Nt]||ae;oe=Math.max(0,oe-tt)}else{if($){let it=0,Nt=0;for(let Cn=0;Cn<(T||[]).length;Cn++){const qn=T[Cn].rowHeight||ae;if(Nt+qn>Pt){it=Cn;break}Nt+=qn}oe=Math.max(0,it-tt);for(let Cn=0;Cn<oe;Cn++)$e+=T[Cn].rowHeight||ae;let bt=0,Gt=0;for(let Cn=it+1;Cn<(T||[]).length;Cn++){const qn=T[Cn].rowHeight||ae;if(bt++,Gt+qn>st)break;Gt+=qn}const ra=Math.min(j?j.rowCount:(T||[]).length,it+bt+tt);return{d:$e,start:oe,end:ra}}oe=Math.floor(Pt/(ae||1)),oe=Math.max(0,oe-tt),$e=oe*(ae||0)}const wn=j?j.rowCount:(T||[]).length,Oe=Math.min(wn,oe+(jt||0)+tt);return{d:$e,start:oe,end:Oe}},[y,$,W,ae,j,T,jt,st]),Je=d.useMemo(()=>{const oe=j?j.rowCount:(T||[]).length;if(y)return ze+ht.d+(oe-(Et||0))*(ae||0);if(!$)return oe*(ae||0);let $e=0;for(let tt=0;tt<oe;tt++)$e+=T[tt]?.rowHeight||ae;return $e},[j,T,ae,y,$,ze,ht.d,Et]),be=d.useRef({});be.current={clientWidth:b,clientHeight:S,fullHeight:Je,headerHeight:et,footerHeight:Me,fullWidth:Ee,SCROLLSIZE:P};const je=d.useCallback(()=>{const oe=be.current;Re(oe.clientWidth&&oe.clientHeight?oe.fullHeight+oe.headerHeight+oe.footerHeight>=oe.clientHeight-(oe.fullWidth>=oe.clientWidth?oe.SCROLLSIZE:0):!1)},[]);d.useEffect(()=>{const oe=requestAnimationFrame(je);return()=>window.cancelAnimationFrame(oe)},[we,je]),d.useEffect(()=>{je()},[S,je]);const Ae=d.useMemo(()=>Se&&Ee<=(b||0)?(b||0)-0-(qe?P:0):Ee,[Se,Ee,b,qe,P,pe]),fe=d.useMemo(()=>Se&&Ee<=(b||0)?b||0:Ae<(b||0)?Ee+(qe?P:0):-1,[Se,Ee,b,Ae,qe,P]),te=d.useRef({});d.useEffect(()=>{if(j&&(te.current.start!==ht.start||te.current.end!==ht.end)){const{start:oe,end:$e}=ht;te.current={start:oe,end:$e},A&&A.exec&&A.exec("request-data",{row:{start:oe,end:$e}})}},[j,ht,A]);const ce=d.useMemo(()=>j?T||[]:(T||[]).slice(ht.start,ht.end),[j,T,ht]),Ne=d.useMemo(()=>(F||[]).filter(oe=>(ce||[]).some($e=>$e.id===oe)),[H,ce]),He=d.useMemo(()=>ht.start,[ht.start]),Ie=d.useRef({top:W,left:z});Ie.current={top:W,left:z};const Lt=d.useCallback(oe=>{const $e=oe.target.scrollTop,tt=oe.target.scrollLeft,Pt=Ie.current;($e!==Pt.top||tt!==Pt.left)&&A.exec("scroll-to",{top:$e,left:tt})},[A]),Xe=d.useCallback(oe=>{oe.shiftKey&&oe.preventDefault(),ye.current&&ye.current.focus&&ye.current.focus()},[]),ut=d.useCallback(()=>!!(I||[]).find(oe=>!!oe.draggable),[I]),yt=d.useRef(null),_t=d.useRef(null),mt=d.useRef({dblclick:(oe,$e)=>{const tt={id:oe,column:rm($e,"data-col-id")};A.exec("open-editor",tt)},click:(oe,$e)=>{if($e.target.closest("input")||yt.current)return;const tt=rm($e,"data-col-id");if(V?.id!==oe&&A.exec("focus-cell",{row:oe,column:tt,eventSource:"click"}),D===!1)return;const Pt=l&&($e.ctrlKey||$e.metaKey),wn=l&&$e.shiftKey;(Pt||F.length>1||!F.includes(oe))&&A.exec("select-row",{id:oe,toggle:Pt,range:wn})},"toggle-row":oe=>{const $e=A.getRow(oe);A.exec($e.open!==!1?"close-row":"open-row",{id:oe})},"ignore-click":()=>!1}),Vt=d.useMemo(()=>({top:et,bottom:Me,left:_e.width,xScroll:pe,yScroll:qe,sense:y&&Qe?Qe.offsetHeight:Math.max(B?.rowHeight||0,40),node:ye.current&&ye.current.firstElementChild}),[et,Me,_e.width,pe,qe,y,Qe,B]);function St(oe,$e){const{container:tt,sourceNode:Pt,from:wn}=$e;if(ut()&&!Pt.getAttribute("draggable-data"))return!1;de(wn),q&&A.getRow(wn).open&&A.exec("close-row",{id:wn,nested:!0});const Oe=Id(Pt),it=Oe.cloneNode(!0);it.classList.remove("wx-selected"),it.querySelectorAll("[tabindex]").forEach(ra=>ra.setAttribute("tabindex","-1")),tt.appendChild(it),ue(it);const Nt=(z||0)-ke.d,bt=qe?P:0;tt.style.width=Math.min((b||0)-bt,Se&&Ee<=(b||0)?Ae:Ae-bt)+Nt+"px";const Gt=_p(Oe);$e.offset={x:Nt,y:-Math.round(Gt.height/2)},_t.current||(_t.current=oe.clientY)}function pn(oe,$e){const{from:tt}=$e,Pt=$e.pos,wn=_p(ye.current);Pt.x=wn.x;const Oe=Vt.top;if(Pt.y<Oe)Pt.y=Oe;else{const it=wn.height-(pe&&P>0?P:Math.round(Vt.sense/2))-Vt.bottom;Pt.y>it&&(Pt.y=it)}if(ye.current.contains($e.targetNode)){const it=Id($e.targetNode),Nt=it&&uh(it);if(Nt&&Nt!==tt){$e.to=Nt;const bt=y?Qe?.offsetHeight:B?.rowHeight;if(Qe&&((W||0)===0||Pt.y>Oe+bt-1)){const Gt=it.getBoundingClientRect(),ra=_p(Qe).y,Cn=Gt.y,qn=ra>Cn?-1:1,Qt=qn===1?"after":"before",En=A.getState().flatData,qr=Math.abs(En.findIndex(Pn=>Pn.id===tt)-En.findIndex(Pn=>Pn.id===Nt)),Ht=qr!==1?Qt==="before"?"after":"before":Qt;if(qr===1&&(qn===-1&&oe.clientY>_t.current||qn===1&&oe.clientY<_t.current))return;_t.current=oe.clientY,A.exec("move-item",{id:tt,target:Nt,mode:Ht,inProgress:!0})}}u&&u({event:oe,context:$e})}wj(oe,wn,$e,Vt)}function rn(oe,$e){const{from:tt,to:Pt}=$e;A.exec("move-item",{id:tt,target:Pt,inProgress:!1}),yt.current=setTimeout(()=>{yt.current=0},1),de(null),ue(null),_t.current=null,AS($e)}function ya(){const oe=document.createElement("div");oe.style.cssText="position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;min-height:100px;overflow-y:scroll;",document.body.appendChild(oe);const $e=oe.offsetWidth-oe.clientWidth;return document.body.removeChild(oe),$e}const Ct=d.useMemo(()=>fe>0?{width:`${fe}px`}:void 0,[fe]),gn=d.useRef(null);function en(){Promise.resolve().then(()=>{let oe=0,$e=He;const tt=gn.current;tt&&(Array.from(tt.children).forEach((Pt,wn)=>{O.current[He+wn]=Pt.offsetHeight,oe+=Pt.offsetHeight,$e++}),We(oe),lt($e))})}d.useEffect(()=>{ce&&y&&en()},[ce,y,He]);let[U,nt]=d.useState();d.useEffect(()=>{if(V&&(!D||!Ne.length||Ne.includes(V.row)))nt({...V});else if(ce.length&&ke.data.length){if(!U||Ne.length&&!Ne.includes(U.row)||ce.findIndex(oe=>oe.id===U.row)===-1||ke.data.findIndex(oe=>oe.id===U.column&&!oe.collapsed)===-1){const oe=Ne[0]||ce[0].id,$e=ke.data.findIndex(tt=>!tt.collapsed);nt($e!==-1?{row:oe,column:ke.data[$e].id}:null)}}else nt(null)},[V]);const Dt=d.useRef(null);d.useEffect(()=>{const oe=ye.current;if(!oe)return;const $e=hj(oe,w);return()=>{typeof $e=="function"&&$e()}},[w]);const vn=d.useRef({});Object.assign(vn.current,{start:St,move:pn,end:rn,getReorder:()=>J,getDraggableInfo:()=>({hasDraggable:ut()})}),d.useEffect(()=>{const oe=ye.current;return oe?vj(oe,vn).destroy:void 0},[J,ye.current]),d.useEffect(()=>{const oe=ye.current;return oe?mj(oe,{keys:N!==!1&&{...fj,"ctrl+z":ve,"ctrl+y":ve,...N},exec:$e=>A.exec("hotkey",$e)}).destroy:void 0},[A,ve,N]);const Nr=d.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});Nr.current.getWidth=()=>(b||0)-(qe?P:0),Nr.current.getHeight=()=>st,Nr.current.getScrollMargin=()=>_e.width+Ze.width,d.useEffect(()=>{pj(Dt.current,Nr.current)},[]);const Ur=d.useRef(null);d.useEffect(()=>{const oe=Ur.current;if(!oe)return;const $e=[];$e.push(ho(oe,()=>V&&A.exec("focus-cell",{eventSource:"click"})).destroy),$e.push(vR(oe,mt.current)),Z(oe.clientHeight);const tt=new ResizeObserver(()=>{Z(oe.clientHeight)});return tt.observe(oe),$e.push(()=>tt.disconnect()),()=>$e.forEach(Pt=>Pt())},[]);const Tr=`wx-grid ${k?`wx-responsive-${k}`:""}`;return d.useEffect(()=>{V&&(ce.some(oe=>oe.id===V.row)&&ke.data.some(oe=>oe.id===V.column&&!oe.collapsed)||A.exec("focus-cell",{eventSource:"destroy"}))},[V,ce,ke.data,A]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-4VuBwK2D "+Tr,style:{"--header-height":`${et}px`,"--footer-height":`${Me}px`,"--split-left-width":`${_e.width}px`,"--split-right-width":`${Ze.width}px`},children:i.jsx("div",{ref:ye,className:"wx-4VuBwK2D wx-table-box",style:Ct,role:q?"treegrid":"grid","aria-colcount":ke.data.length,"aria-rowcount":ce.length,"aria-multiselectable":q&&l?!0:void 0,tabIndex:-1,children:i.jsxs("div",{ref:Dt,className:"wx-4VuBwK2D wx-scroll",style:{overflowX:pe?"scroll":"hidden",overflowY:qe?"scroll":"hidden"},onScroll:Lt,children:[n?i.jsx("div",{className:"wx-4VuBwK2D wx-header-wrapper",children:i.jsx(Vw,{contentWidth:Ae,deltaLeft:ke.dh,columns:ke.header,columnStyle:h,bodyHeight:st-+r})}):null,i.jsxs("div",{ref:Ur,className:"wx-4VuBwK2D wx-body",style:{width:`${Ae}px`,height:`${Je}px`},onMouseDown:oe=>Xe(oe),children:[o?i.jsx(Lj,{overlay:o}):null,i.jsx("div",{ref:gn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${ht.d}px`,paddingLeft:`${ke.d}px`},children:ce.map((oe,$e)=>{const tt=F.indexOf(oe.id)!==-1,Pt=Pe===oe.id,wn="wx-row"+(y?" wx-autoheight":"")+(f?" "+f(oe):"")+(tt?" wx-selected":"")+(Pt?" wx-inactive":""),Oe=y?{minHeight:`${oe.rowHeight||ae}px`}:{height:`${oe.rowHeight||ae}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+wn,"data-id":Fa(oe.id),"data-context-id":Fa(oe.id),style:Oe,role:"row","aria-rowindex":$e,"aria-expanded":oe.open,"aria-level":q?oe.$level+1:void 0,"aria-selected":q?tt:void 0,tabIndex:-1,children:ke.data.map(it=>it.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},it.id):K?.id===oe.id&&K.column===it.id?i.jsx(zj,{row:oe,column:it},it.id):i.jsx(Mj,{row:oe,column:it,columnStyle:h,cellStyle:g,reorder:J,focusable:U?.row===oe.id&&U?.column===it.id},it.id))},oe.id)})})]}),r&&(T||[]).length?i.jsx(Vw,{type:"footer",contentWidth:Ae,deltaLeft:ke.df,columns:ke.footer,columnStyle:h}):null]})})}),X?i.jsx(Uj,{config:X,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:J}):null]})}const Wj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),Gj=d.forwardRef(function({data:t=[],columns:n=[],rowStyle:r=null,columnStyle:o=null,cellStyle:l=null,selectedRows:u,select:f=!0,multiselect:h=!1,header:g=!0,footer:y=!1,dynamic:w=null,overlay:b=null,reorder:S=!1,onReorder:k=null,autoRowHeight:N=!1,sizes:A,split:j,tree:I=!1,autoConfig:T=!1,init:_=null,responsive:B=null,sortMarks:F,undo:H=!1,hotkeys:D=null,filterValues:K,...z},W){const q=d.useRef();q.current=z;const V=d.useMemo(()=>new ij(hS),[]),X=d.useMemo(()=>V.in,[V]),ve=d.useRef(null);ve.current===null&&(ve.current=new cS((Ze,at)=>{const Ee="on"+Wj(Ze);q.current&&q.current[Ee]&&q.current[Ee](at)}),X.setNext(ve.current));const J=d.useMemo(()=>({getState:V.getState.bind(V),getReactiveState:V.getReactive.bind(V),getStores:()=>({data:V}),exec:X.exec,setNext:Ze=>(ve.current=ve.current.setNext(Ze),ve.current),intercept:X.intercept.bind(X),on:X.on.bind(X),detach:X.detach.bind(X),getRow:V.getRow.bind(V),getColumn:V.getColumn.bind(V)}),[V,X]),[$,P]=d.useState(0),[se,we]=d.useState(0),[Z,Se]=d.useState(null),[ae,ye]=d.useState(null),Pe=d.useMemo(()=>{if(T&&!n.length&&t.length){const Ze=t[0],at=[];for(let Ee in Ze)if(Ee!=="id"&&Ee[0]!=="$"){let Ge={id:Ee,header:Ee[0].toUpperCase()+Ee.slice(1)};typeof T=="object"&&(Ge={...Ge,...T}),at.push(Ge)}return at}return(ae&&ae.columns)??n},[T,n,t,ae]),de=d.useMemo(()=>(ae&&ae.sizes)??A,[ae,A]),Qe=d.useCallback(Ze=>{if(P(Ze.width),we(Ze.height),B){const at=Object.keys(B).map(Number).sort((Ee,Ge)=>Ee-Ge).find(Ee=>Ze.width<=Ee)??null;at!==Z&&(ye(B[at]),Se(at))}},[B,Z]),ue=d.useContext(Ba.theme),_e=d.useRef(0);return d.useEffect(()=>{if(!_e.current)_&&_(J);else{const Ze=V.getState();V.init({data:t,columns:Pe,split:j||Ze.split,sizes:de||Ze.sizes,selectedRows:u||Ze.selectedRows,dynamic:w,tree:I,sortMarks:F||Ze.sortMarks,filterValues:K||Ze.filterValues,undo:H,reorder:S,_skin:ue,_select:f})}_e.current++},[V,t,Pe,j,de,u,w,I,F,K,H,S,ue,f,_,J]),_e.current===0&&V.init({data:t,columns:Pe,split:j||{left:0},sizes:de||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:K||{},undo:H,reorder:S,_skin:ue,select:f}),d.useImperativeHandle(W,()=>({...J}),[J]),i.jsx(Es.Provider,{value:J,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(qj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:o,cellStyle:l,onReorder:k,multiselect:h,autoRowHeight:N,clientWidth:$,clientHeight:se,responsiveLevel:Z,resize:Qe,hotkeys:D})})})});Bv(cs);const Oa=d.createContext(null),Yv=d.createContext(null),Xv=d.createContext(null);function Vj({children:t}){const n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=d.useContext(Oa),[l]=Xs(o,"panels"),u=Ot(o,"activePanel"),f=l[u].path,[h,g]=d.useState(null),[y,w]=d.useState(null),[b,S]=d.useState(""),[k,N]=d.useState(""),[A,j]=d.useState(!1);function I(){const F=b.trim();if(!F){j(!0);return}h.add?o.exec("create-file",{file:{...h.item,name:F},parent:f}):k!==F&&o.exec("rename-file",{id:h.item.id,name:F}),T()}function T(){g(null),j(null),N(""),S("")}function _(){o.exec("delete-files",{ids:y.selected}),w(null)}const B=d.useMemo(()=>({showPrompt(F){const H=F.item.name||(F.item.type==="folder"?r("New folder"):`${r("New file")}.txt`);N(H),S(H),g({...F})},showConfirm(F){w({...F})}}),[r]);return i.jsxs(Yv.Provider,{value:B,children:[i.jsx(VT,{children:t}),h?i.jsx(gv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:T,children:i.jsx(qv,{error:A,select:!0,focus:!0,value:b,onChange:({value:F})=>S(F)})}):null,y?i.jsx(gv,{title:r("Are you sure you want to delete these items:"),onConfirm:_,onCancel:()=>w(null),children:y.selected?i.jsx("ul",{className:"wx-gq7BMzEP wx-list",children:y.selected.map((F,H)=>i.jsx("li",{children:F},H))}):null}):null]})}let Qw={"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 Kj(t){const n=t.lastIndexOf("."),r=n>0&&n<t.length-1?Math.min(10,t.length-n):Math.min(5,t.length),o=t.slice(0,-r),l=t.slice(-r);return[o,l]}function Qj({item:t}){const n=d.useContext(Oa),r=d.useContext(Ba.i18n).getGroup("filemanager"),o=d.useContext(Oa).templates,[l]=Xs(n,"panels"),u=Ot(n,"activePanel"),f=Ot(n,"mode"),h=l[u].selected,g=d.useMemo(()=>o.preview(t,214,163),[o,t]),y=d.useMemo(()=>o.icon(t,"big"),[o,t]),[w,b]=d.useMemo(()=>Kj(t.name),[t.name]);return i.jsx(i.Fragment,{children:t.id==="/wx-filemanager-parent-link"?f!=="search"?i.jsx("div",{className:"wx-GAOa4kDV wx-back-item",children:i.jsxs("div",{className:`wx-GAOa4kDV wx-back ${t.navigation?"wx-selected":""}`,"data-id":Fa("/wx-filemanager-parent-link"),children:[i.jsx("i",{className:"wx-GAOa4kDV wxi-arrow-left"}),i.jsx("span",{children:r("Back to parent folder")})]})}):null:i.jsxs("div",{className:`wx-GAOa4kDV wx-item ${h?.length&&h.indexOf(t.id)>=0?"wx-selected":""}`,"data-id":Fa(t.id),children:[g?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-preview",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:r("A miniature file preview"),src:g})}):y?i.jsx("div",{className:"wx-GAOa4kDV wx-preview wx-file-icon",children:i.jsx("img",{className:"wx-GAOa4kDV wx-card-preview",alt:"",src:y})}):i.jsx("div",{className:"wx-GAOa4kDV wx-preview",children:i.jsx("i",{className:`wx-GAOa4kDV wxi-${t.type}`})}),t.type==="folder"?i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsxs("div",{className:"wx-GAOa4kDV wx-folder-name",children:[i.jsx("span",{className:"wx-GAOa4kDV wx-type",children:r("Folder")}),i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})]}),i.jsx("div",{"data-action-id":Fa(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]}):i.jsxs("div",{className:"wx-GAOa4kDV wx-info",children:[i.jsx("div",{className:"wx-GAOa4kDV wx-file-name",children:i.jsxs("span",{className:"wx-GAOa4kDV wx-name",children:[i.jsx("span",{children:w}),i.jsx("span",{children:b})]})}),i.jsx("div",{"data-action-id":Fa(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function jS(){const t=d.useContext(Oa),n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),[o]=Xs(t,"panels"),l=Ot(t,"activePanel"),u=Ot(t,"mode"),f=o[l]._files,h=o[l].selected,g=o[l].path,y=o[l]._crumbs,w=o[l]._selectNavigation,b=d.useCallback((T,_)=>{const B=_&&(_.ctrlKey||_.metaKey),F=_&&_.shiftKey;if(T==="/wx-filemanager-parent-link"){if(h.length&&(B||F))return;t.exec("select-file",{type:"navigation"});return}let H=T==="body"&&_?null:T;const D=_.target.className.indexOf("wx-more")!==-1||_.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:H,toggle:B&&!D,range:F&&!D,panel:l})},1)},[t,h,l]),S=d.useCallback(()=>{y.length>1&&t.exec("set-path",{id:y[y.length-2].id,panel:l,selected:[y[y.length-1].id]})},[t,y,l]),k=d.useCallback(T=>{if(T==="/wx-filemanager-parent-link")return S();u==="search"&&t.exec("filter-files",{text:""});const _=f.find(B=>B.id===T);_&&(_.type=="folder"?t.exec("set-path",{id:_.id,panel:l}):t.exec("open-file",{id:_.id}))},[t,S,u,f,l]),N=d.useCallback((T,_)=>{(!h?.length||!h.filter(B=>B?.id===T).length>0)&&b(T,_)},[h,b]),A=d.useMemo(()=>g!=="/"?[{id:"/wx-filemanager-parent-link",name:r("Back to parent folder"),navigation:w},...f]:f,[g,r,w,f]),j=d.useRef(null),I=d.useRef();return d.useEffect(()=>{j.current&&(I.current?(I.current.click=b,I.current._dblclick=k,I.current.context=N):(I.current={click:b,dblclick:T=>I.current._dblclick(T),_dblclick:k,context:N},Ld(j.current,I.current)))},[b,k,N]),u=="search"&&!A.length?i.jsx("div",{className:"wx-iyjASZCY wx-not-found",children:i.jsx("div",{className:"wx-iyjASZCY wx-not-found-text",children:r("Looks like nothing is here")})}):i.jsx("div",{tabIndex:0,className:"wx-iyjASZCY "+("wx-cards"+(g!=="/"&&u!=="search"?" wx-has-back-link":"")),"data-id":Fa("body"),ref:j,children:A.map(T=>i.jsx(Qj,{item:T},T.id))})}function iu({name:t="",spin:n=!1,onClick:r}){return i.jsx("i",{"data-menu-ignore":"true",className:`wx-uwcvNSAG wx-icon wxi-${t} ${n?"wx-spin":""} ${r?"wx-clickable":""}`,onClick:()=>{r&&r()}})}function Yj(){const t=d.useContext(Ba.i18n).getGroup("filemanager"),n=d.useContext(Oa),r=Ot(n,"activePanel"),[o]=Xs(n,"panels"),l=d.useMemo(()=>o[r]._crumbs,[o,r]);function u(){n.exec("filter-files",{text:""})}return i.jsxs("div",{className:"wx-GDJvtROw wx-search",children:[i.jsxs("div",{className:"wx-GDJvtROw wx-toolbar",children:[i.jsx("div",{className:"wx-GDJvtROw wx-back-icon",children:i.jsx(iu,{name:"angle-left",onClick:u})}),i.jsxs("div",{className:"wx-GDJvtROw wx-text",children:[t("Search results in")," ",Array.isArray(l)&&l.map((f,h)=>i.jsxs(d.Fragment,{children:[h?"/":null,f.id=="/"?t(f.name):f.name]},h))]})]}),i.jsx(jS,{})]})}function jg({narrowMode:t,extraInfo:n}){const r=d.useContext(Oa),{preview:o,icon:l}=r.templates,u=d.useContext(Ba.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Td("%D, %d %F %Y, %H:%i",u.getRaw().calendar),[u]),[g,y]=Xs(r,"panels"),w=Ot(r,"activePanel"),b=Ot(r,"preview"),S=Ot(r,"search"),k=d.useMemo(()=>{const D=g&&w!=null&&g[w]?._selected?.length||0;return S&&!D},[S,y,w]),N=d.useMemo(()=>{const D=g&&w!=null?g[w]:null;return D?k?D._files:D._selected:[]},[k,y,w]),A=d.useCallback((D,K)=>(D?`${D} ${f(D>1?"folders":"folder")} `:"")+(K?`${K} ${f(K>1?"files":"file")}`:""),[f]),j=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(D=>D.type==="folder"?f("Folder"):D.ext||f("Unknown file"),[f]),T=d.useMemo(()=>{let D,K,z,W,q,V,X,ve;if(N.length===1&&!k){K=N[0],D=K.name;const J=o(K,400,500);J?(z=J,W=""):(W=l(K,"big"),z=""),q=K.type!=="folder"}else{if(K=q=null,D="",N.length){let J=0,$=0,P=0,se=[],we;N.forEach(Se=>{typeof Se.size>"u"&&(we=!0,J=void 0),we||(J+=Se.size),se.push(I(Se)),Se.type==="folder"?$++:P++});const Z=new Set(se);V=Z.size>1?f("multiple"):[...Z][0],X=A($,P),ve=J,k||(D=f("Multiple files"))}W=l({type:k?"search":N.length?"multiple":"none"},"big"),z=""}return{name:D,item:K,previewSrc:z,iconSrc:W,showDownloadIcon:q,type:V,totalCount:X,totalSize:ve}},[N,k,o,l,f,I,A]),_=d.useCallback(()=>{r.exec("download-file",{id:N[0].id})},[r,N]),B=d.useCallback(async D=>{if(!n||!D)return null;try{return await n(D)}catch(K){return console.log(K),null}},[n]),[F,H]=d.useState(null);return d.useEffect(()=>{let D=!1;return H(null),Promise.resolve(B(T.item)).then(K=>{D||H(K)}).catch(()=>{D||H(null)}),()=>{D=!0}},[B,T.item]),i.jsx("div",{className:"wx-O0BTtRrH wx-wrapper",children:N&&N.length?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-preview",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[T.showDownloadIcon?i.jsx(iu,{name:"download",onClick:_}):null,t?i.jsx(iu,{name:"close",onClick:j}):null]})]}),T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:T.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${T.item.type}`}):i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"file-multiple-outline"}`})})]}),i.jsxs("div",{className:"wx-O0BTtRrH wx-info-panel",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-title",children:f(k?"Found":"Information")}),i.jsxs("div",{className:"wx-O0BTtRrH wx-list",children:[T.item?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:I(T.item)}),typeof T.item.size<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:sm(T.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(T.item.date)," "]})]}):i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Count")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:T.type}),typeof T.totalSize<"u"?i.jsxs(i.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Size")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:sm(T.totalSize)})]}):null]}),F?Object.entries(F).map(([D,K])=>i.jsxs(Cv.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:D}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:K})]},D)):null]})]})]}):i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info-panel",children:[i.jsxs("div",{className:"wx-O0BTtRrH wx-toolbar",children:[i.jsx("div",{className:"wx-O0BTtRrH wx-name",children:T.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?i.jsx(iu,{name:"close",onClick:j}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[T.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:T.previewSrc,alt:f("A miniature file preview")})}):T.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:T.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${k?"search":"message-question-outline"}`})}),i.jsx("span",{className:"wx-O0BTtRrH wx-text",children:k?"":f("Select file or folder to view details")})]})})]})})}function ES({panel:t}){const n=d.useContext(Oa),r=d.useContext(Ba.i18n),o=d.useMemo(()=>r.getGroup("filemanager"),[r]),[l,u]=Xs(n,"panels"),f=d.useMemo(()=>l[t]._files,[u,t]),h=d.useMemo(()=>l[t]._crumbs||[],[u,t]);function g(N){const A=Kv(N,h);n.exec("set-path",{id:N,panel:t,...A&&{selected:[A]}})}const[y,w]=d.useState(null);d.useEffect(()=>{f&&w(null)},[f]);function b(){w(!0),n.exec("request-data",{id:h[h.length-1].id}),setTimeout(()=>{w(null)},5e3)}const S=d.useRef(null),k=d.useRef();return d.useEffect(()=>{k.current?k.current.click=g:(k.current={click:g},Ld(S.current,k.current))},[g]),i.jsxs("div",{className:"wx-SNY5LTYx wx-breadcrumbs","data-menu-ignore":"true",ref:S,children:[i.jsx("div",{className:"wx-SNY5LTYx wx-refresh-icon",children:i.jsx(iu,{name:"refresh",spin:!!y,onClick:b})}),h.map((N,A)=>i.jsxs(Cv.Fragment,{children:[A?i.jsx(iu,{name:"angle-right"}):null,i.jsx("div",{className:"wx-SNY5LTYx wx-item","data-id":Fa(N.id),"data-menu-ignore":"true",children:N.id=="/"?o(N.name):N.name})]},A))]})}function Xj({row:t}){const n=d.useContext(Ba.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),o=d.useContext(Oa).templates,[l]=d.useState(()=>o.icon(t,"small"));return i.jsx("div",{className:"wx-qgAqG6sL wx-name-cell",children:t.id==="/wx-filemanager-parent-link"?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-qgAqG6sL wxi-arrow-left"}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",r("Back to parent folder")]})]}):i.jsxs(i.Fragment,{children:[l?i.jsx("img",{className:"wx-qgAqG6sL wx-icon",alt:"",src:l,height:"24px",width:"24px"}):i.jsx("i",{className:`wx-qgAqG6sL wxi-${t.type}`}),i.jsxs("span",{className:"wx-qgAqG6sL wx-name",children:[" ",t.name," "]})]})})}function DS({children:t}){const n=d.useContext(Oa),r=Ot(n,"activePanel"),o=d.useContext(Xv),l=d.useRef(null);let u=d.useRef({});return u.current.drop=()=>{const f=l.current,h=eT(f,"data-panel");h&&h!=r&&n.exec("set-active-panel",{panel:h*1})},u.current.dragEnter=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},u.current.dragLeave=()=>{const f=l.current;f&&f.classList.toggle("wx-active")},d.useEffect(()=>{const f=l.current;return o.droparea(f,u.current)},[]),i.jsx("div",{className:"wx-LT9X7tb7 wx-upload-area",ref:l,children:t})}function bv({panel:t,active:n=!1,onClick:r,onContextMenu:o}){const l=d.useContext(Oa),u=d.useContext(Ba.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Td("%d %M %Y",u.getRaw().calendar),[u]),[g]=Xs(l,"panels"),y=g[t].selected,w=g[t].path,b=g[t]._crumbs,S=g[t]._sorts,k=g[t]._selectNavigation,N=g[t]._files,A=d.useMemo(()=>[{id:"name",header:f("Name"),flexgrow:3,sort:!0,resize:!0,cell:Xj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:V=>typeof V=="number"?sm(V):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:V=>V?h(V):""}],[f,h]),j=d.useRef(null),I=d.useRef(null),T=d.useMemo(()=>k?["/wx-filemanager-parent-link"]:[...y],[k,y]);function _(V,X){if(X&&X.target&&X.target.className&&X.target.className.indexOf("wx-grip")!==-1)return;const ve=X&&(X.ctrlKey||X.metaKey),J=X&&X.shiftKey;if(V==="/wx-filemanager-parent-link"){if(y.length&&(ve||J))return;l.exec("select-file",{type:"navigation"});return}let $=V==="body"&&X?null:V;!j.current&&!I.current?l.exec("select-file",{id:$,toggle:ve,range:J,panel:t}):(j.current=null,I.current=null)}function B(){b.length>1&&l.exec("set-path",{id:b[b.length-2].id,panel:t,selected:[b[b.length-1].id]})}function F(V){if(V==="/wx-filemanager-parent-link")return B();const X=N.find(ve=>ve.id===V);X&&(X.type==="folder"?l.exec("set-path",{id:X.id,panel:t}):l.exec("open-file",{id:X.id}))}function H(V){const X=V.key,ve=S[w];let J=ve?"asc":"desc";ve&&ve.key===X&&(J=ve.order==="asc"?"desc":"asc"),l.exec("sort-files",{key:X,order:J,panel:t,path:w})}function D(V){V.intercept("sort-rows",X=>(j.current=!0,H(X),!1)),V.intercept("select-row",()=>!1),V.on("resize-column",()=>I.current=!0),V.intercept("hotkey",()=>!1)}const K=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...N]:N,[w,N,f]),z=d.useMemo(()=>{if(K&&S&&S[w]){const{key:V,order:X}=S[w];return{[V]:{order:X}}}},[K,S,w]),W=d.useRef(null),q=d.useRef();return d.useEffect(()=>{q.current?(q.current.click=_,q.current._dblclick=F):(q.current={click:_,dblclick:V=>q.current._dblclick(V),_dblclick:F},Ld(W.current,q.current))},[_,F]),i.jsxs("div",{onClick:r,onContextMenu:o,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(ES,{panel:t}),i.jsx("div",{"data-id":Fa("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:W,children:i.jsx(DS,{children:i.jsx(Gj,{init:D,data:K,columns:A,selectedRows:T,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:z})})})]})}function Zj(){const t=d.useContext(Oa),n=Ot(t,"activePanel");function r(o){t.exec("set-active-panel",{panel:o})}return i.jsxs("div",{className:"wx-L55BfJa2 wx-panels","data-id":Fa("body"),children:[i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":0,children:i.jsx(bv,{panel:0,active:n==0,onClick:()=>r(0),onContextMenu:()=>r(0)})}),i.jsx("div",{className:"wx-L55BfJa2 wx-item","data-panel":1,children:i.jsx(bv,{panel:1,active:n==1,onClick:()=>r(1),onContextMenu:()=>r(1)})})]})}function IS({folderIcon:t=!1,folder:n={}}){const r=d.useContext(Oa),[o,l]=Xs(r,"panels"),u=Ot(r,"activePanel"),f=d.useMemo(()=>o[u].path,[l,u]),h=d.useContext(Ba.i18n),g=d.useMemo(()=>h.getGroup("filemanager"),[h]),y=d.useMemo(()=>!!n.data?.find(k=>k.type==="folder"),[n]),w=d.useMemo(()=>n.id=="/"?g(n.name):n.name,[n,g]),b=d.useMemo(()=>n.$level>1?(n.$level-1)*20:0,[n]),S=n.open;return i.jsxs(i.Fragment,{children:[i.jsxs("li",{"data-id":Fa(n.id),className:`wx-NYfhvGIt wx-folder${f===n.id?" wx-selected":""}`,style:{paddingLeft:`${b}px`},children:[y?i.jsx("i",{className:`wx-NYfhvGIt wx-toggle wxi-${S?"angle-down":"angle-right"}`,"data-action":"toggle"}):i.jsx("span",{className:"wx-NYfhvGIt wx-toggle-placeholder"}),i.jsx("i",{className:"wx-NYfhvGIt "+(t||"wxi-folder")}),i.jsxs("span",{className:"wx-NYfhvGIt wx-name",children:[" ",w," "]})]}),S&&n.data&&n.data.length&&y?i.jsx(i.Fragment,{children:n.data.map(k=>k.type==="folder"?i.jsx(IS,{folder:k},k.id):null)}):null]})}function Jj(){const t=d.useContext(Oa),[n,r]=Xs(t,"data"),[o,l]=Xs(t,"panels"),u=Ot(t,"activePanel"),f=d.useMemo(()=>o[u]._crumbs,[l,u]),h=d.useCallback(k=>{t.exec("open-tree-folder",{id:k,mode:!n.byId(k).open})},[t,r]),g=d.useCallback(k=>{const N=Kv(k,f);t.exec("set-path",{id:k,panel:u,...N&&{selected:[N]}})},[t,f,u]),[y,w]=d.useState([]);d.useEffect(()=>{w(n.byId(0).data)},[r]);const b=d.useRef(null),S=d.useRef();return d.useEffect(()=>{S.current?(S.current.click=g,S.current.toggle=h):(S.current={click:g,toggle:h},Ld(b.current,S.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(k=>k.type==="folder"?i.jsx(IS,{folder:k},k.id):null)})}function eE(){const t=d.useContext(Oa),n=d.useContext(Ba.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=Ot(t,"drive"),l=o?o.used:"",u=o?o.total:"";return l&&u?i.jsxs("div",{className:"wx-DetSyKGG wx-drive",children:[i.jsx("progress",{value:l,max:u,className:"wx-DetSyKGG wx-progress"}),i.jsxs("p",{children:[sm(l)," ",r("of")," ",sm(u)," ",r("used")]})]}):null}function tE({option:t}){const n=d.useContext(Ba.i18n).getGroup("filemanager"),r=d.useContext(Xv),o=d.useCallback(()=>{r.open({})},[r]);return i.jsx("div",{className:"wx-9XiKcxq5 wx-upload-button",onClick:o,children:i.jsx("span",{children:n(t.text)})})}function nE({readonly:t,menuOptions:n}){const r=d.useContext(Ba.i18n).getGroup("filemanager"),{showPrompt:o}=d.useContext(Yv);d.useEffect(()=>{wR("upload",tE)},[]);function l({action:f}){f&&(f.id==="add-file"?o({item:{type:"file",size:0,date:new Date},add:!0}):f.id==="add-folder"&&o({item:{type:"folder",date:new Date},add:!0}))}const u=d.useMemo(()=>n("add").map(f=>(f.text=r(f.text),f)),[n,r]);return i.jsxs("div",{className:"wx-FlucfALM wx-wrapper",children:[!t&&i.jsx("div",{className:"wx-FlucfALM wx-button",children:i.jsx(SR,{options:u,at:"bottom-fit",onClick:l,children:i.jsx(Jf,{type:"primary block",children:r("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(Jj,{})}),i.jsx(eE,{})]})}function aE({value:t="",onSearch:n}){const[r,o]=mS(t),l=d.useContext(Ba.i18n).getGroup("filemanager"),u=d.useRef(null),f=d.useMemo(()=>r!==""?"wxi-close":"wxi-search",[r]);function h(y){const w=y.target.value;o(w),n&&n({value:w})}function g(){o(""),u.current&&u.current.focus(),n&&n({value:""})}return i.jsxs("div",{className:"wx-lUZMtgT1 wx-search-input",children:[i.jsx("i",{className:`wx-lUZMtgT1 wx-icon ${f}`,onClick:g}),i.jsx("input",{type:"text",className:"wx-lUZMtgT1 wx-text",ref:u,value:r,onInput:h,placeholder:l("Search")})]})}function rE({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(Oa),o=d.useContext(Ba.i18n).getGroup("filemanager"),l=Ot(r,"mode"),u=Ot(r,"preview"),f=Ot(r,"search"),h=[{icon:"wxi-view-sequential",id:"table"},{icon:"wxi-view-grid",id:"cards"},{icon:"wxi-view-column",id:"panels"}];function g({value:b}){r.exec("set-mode",{mode:b})}function y(b){b.preventDefault(),r.exec("show-preview",{mode:!u})}function w(b){r.exec("filter-files",{text:b.value})}return i.jsxs("div",{className:"wx-5PZQQztG wx-toolbar",children:[i.jsxs("div",{className:"wx-5PZQQztG wx-left "+(t?"wx-left-narrow":""),children:[t?l==="panels"||l==="search"?null:i.jsx("div",{className:"wx-5PZQQztG wx-sidebar-icon","data-id":Fa("toggle-tree"),children:i.jsx(iu,{onClick:()=>n&&n(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:o("Files")}),i.jsx(aE,{onSearch:w,value:f})]}),i.jsxs("div",{className:"wx-5PZQQztG wx-right",children:[t?null:i.jsx("div",{className:"wx-5PZQQztG wx-preview-icon",children:i.jsx(KT,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx($T,{value:l,options:h,onChange:g})})]})]})}function sE(){const t=d.useContext(Oa),n=Ot(t,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(ES,{panel:n}),i.jsx(DS,{children:i.jsx(jS,{})})]})}function iE({readonly:t=!1,menuOptions:n,extraInfo:r}){const o=d.useRef(null),l=d.useRef(null),[u,f]=d.useState(void 0),[h,g]=d.useState(void 0),[y,w]=d.useState(!1),b=wS(),S=d.useContext(Oa),{showPrompt:k,showConfirm:N}=d.useContext(Yv),A=d.useContext(Ba.i18n),j=d.useMemo(()=>A.getGroup("filemanager"),[A]),I=Ot(S,"mode"),T=Ot(S,"preview"),_=Ot(S,"activePanel"),[B,F]=Xs(S,"panels"),H=d.useMemo(()=>(B&&_!=null?B[_]:null)?.selected??[],[F,_]),D=d.useMemo(()=>(B&&_!=null?B[_]:null)?.path,[F,_]),[K,z]=d.useState([]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=new ResizeObserver(ae=>{const ye=ae[0]?.borderBoxSize?.[0]?.inlineSize;typeof ye=="number"&&g(ye<768)});return Se.observe(Z),()=>{Se.disconnect()}},[]);const W=d.useCallback(()=>{w(Z=>!Z)},[]),q=d.useCallback(Z=>{h&&rm(Z)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const Z=l.current;if(Z)return ho(Z,q).destroy},[q]),d.useEffect(()=>{const Z=l.current;if(!Z)return;const Se=new ResizeObserver(()=>{Z&&f(Z.clientWidth)});return Se.observe(Z),Z&&f(Z.clientWidth),()=>{Se.disconnect()}},[]);const V=d.useMemo(()=>({icon:"wxi-eye",text:"Preview",id:"preview"}),[]),X=d.useCallback(Z=>{let Se=h?[V]:[];return Z==="file"&&(Se=[...Se,...n().filter(ae=>ae.id==="download")]),Se},[h,V,n]),ve=d.useRef(null),J=d.useCallback((Z,Se,ae)=>{const ye=ae?[Se.id]:H;switch(Z){case"download":S.exec("download-file",{id:Se.id});break;case"copy":case"move":ve.current={action:Z,ids:ye};break;case"paste":ve.current&&S.exec(ve.current.action==="copy"?"copy-files":"move-files",{ids:ve.current.ids,target:Se?.type==="folder"?Se.id:D});break;case"rename":k({item:Se});break;case"delete":N({selected:ye});break;case"preview":S.exec("show-preview",{mode:!T});break}},[S,H,D,k,N,T]),$=d.useCallback(()=>B?.[_],[B,_]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=cR(Z,{api:S,menuOptions:t?X:n,performAction:J,getPanel:$});return()=>{typeof Se=="function"?Se():Se&&typeof Se.destroy=="function"&&Se.destroy()}},[S,t,X,n,J,$]);const P=d.useCallback((Z,Se)=>{const ae=Z?S.getFile(Z):null,ye=Se.target.closest(".tree-item.folder");let Pe;if(t)Pe=X(ae?.type);else{switch(Z){case"body":Pe=n(Z);break;default:if(ae)if(!ye&&H.length>1)Pe=h?[V,...n("multiselect")]:n("multiselect");else if(Z==="/")Pe=n("folder",ae).filter(de=>de.id==="paste");else{const de=n(ae.type,ae);de&&(Pe=h?[V,...de]:de)}}I==="search"&&(Pe=Pe?.filter(de=>de.id!=="paste"))}if(ae?.id&&(!H.length||!H.some(de=>de===ae.id))&&!ye&&S.exec("select-file",{id:ae.id}),Pe?.length)return Pe.forEach(de=>{ye&&(de.hotkey=""),de.text&&(de.text=j(de.text)),de.hotkey&&(de.subtext=de.hotkey)}),z(Pe),ae||{}},[S,t,X,n,H,h,V,I,j]),se=d.useCallback(Z=>{const{action:Se,context:ae}=Z;Se&&J(Se.id,ae,!Se.hotkey)},[J]);async function we(Z){await Promise.resolve();const{name:Se,size:ae}=Z.file;S.exec("create-file",{file:{name:Se,size:ae,date:new Date,file:Z.file},parent:D})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:o,"data-menu-ignore":"false",children:h&&T?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(jg,{narrowMode:h,extraInfo:r})}):i.jsxs(i.Fragment,{children:[i.jsx(rE,{narrowMode:h,onShowTree:W}),i.jsx(CR,{dataKey:"id",at:"point",options:K,resolver:P,onClick:se,children:i.jsxs(bS,{dataKey:"actionId",options:K,resolver:P,onClick:se,children:[i.jsx(TR,{data:b,apiOnly:!0,uploadURL:we}),i.jsx(Xv.Provider,{value:b,children:i.jsx("div",{className:"wx-RJbNonjJ wx-content-wrapper wx-flex",children:I!=="panels"&&I!=="search"?i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-RJbNonjJ "+["wx-sidebar",h?"wx-sidebar-narrow":"",y?"wx-sidebar-visible":""].filter(Boolean).join(" "),ref:l,children:i.jsx(nE,{readonly:t,menuOptions:n})}),i.jsxs("div",{className:"wx-RJbNonjJ wx-content",style:{width:`calc(100% - ${u||0}px - 10px)`},children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,"data-id":Fa("body"),children:I==="table"?i.jsx(bv,{panel:_}):i.jsx(sE,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})]}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:`wx-RJbNonjJ wx-content-item${T?"":"-fit"}`,children:I==="panels"?i.jsx(Zj,{}):i.jsx(Yj,{})}),T?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})})})]})})]})})}const oE=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function lE(t,n){const{type:r,ext:o}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Qw[r]?l=r:o?l=Qw[o]?o:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const cE=d.forwardRef(function(t,n){const{data:r=[],mode:o="cards",drive:l=null,preview:u=!1,panels:f=null,activePanel:h=0,readonly:g=!1,menuOptions:y=iR,extraInfo:w=null,init:b=null,icons:S=lE,previews:k=null,...N}=t,A=d.useRef();A.current=N;const j=d.useMemo(()=>new sR(hS),[]),I=d.useMemo(()=>j.in,[j]),T=d.useRef(null);T.current===null&&(T.current=new cS((F,H)=>{const D="on"+oE(F);A.current&&A.current[D]&&A.current[D](H)}),I.setNext(T.current));const _=d.useMemo(()=>({getState:j.getState.bind(j),getReactiveState:j.getReactive.bind(j),getStores:()=>({data:j}),exec:I.exec,setNext:F=>(T.current=T.current.setNext(F),T.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:j.getFile.bind(j),serialize:j.serialize.bind(j),templates:{preview:k||(()=>null),icon:S==="simple"?(()=>null):S}}),[j,I]),B=d.useRef(0);return d.useEffect(()=>{if(!B.current)b&&b(_);else{const F=j.getState();j.init({data:r,mode:o,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}B.current++},[j,r,o,l,u,f,h,b,_]),B.current===0&&j.init({data:r,mode:o,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({..._}),[_]),i.jsx(Oa.Provider,{value:_,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(Vj,{children:i.jsx(iE,{readonly:g,menuOptions:y,extraInfo:w})})})})});function uE({fonts:t=!0,children:n}){return n?i.jsx(Lw,{fonts:t,children:n}):i.jsx(Lw,{fonts:t})}Bv(cs);function Zv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function cm(t,n,r){const o=Zv(t,r);if(!Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an array.`);return o[n]}function dE(t,n,r){const o=Zv(t,r);if(!o[n]||typeof o[n]!="object"||Array.isArray(o[n]))throw new Error(`Invalid Hub ${r} response: ${n} must be an object.`);return o[n]}async function fE(t,n=!1){return cm(await rt(`/api/remote/filesystem/roots${n?"?refresh=1":""}`,void 0,t),"roots","filesystem roots")}async function Eg(t,n){const r=await rt(`/api/remote/filesystem/entries?id=${encodeURIComponent(t)}`,void 0,n);return{folder:dE(r,"folder","filesystem entries"),entries:cm(r,"entries","filesystem entries")}}async function mE(t,n){return rt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function pE(t,n,r,o){return rt("/api/remote/files/from-hub",{method:"POST",body:JSON.stringify({itemIds:t,deviceIds:n,remoteDirectory:r})},o)}async function hE(t,n=!1){const r=await rt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:cm(r,"jobs","file transfer jobs")}}async function gE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function vE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function Yw(t){return cm(await rt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function yE(t,n){return rt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function bE(t,n,r){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function wE(t,n){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function xE(t,n,r,o){const l=await rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}/sync`,{method:"POST",body:JSON.stringify({deviceIds:n,remoteDirectory:r})},o),u=Zv(l,"shared folder sync");return{ok:u.ok===!0,jobs:cm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function SE(t){return{id:String(t.id),parentId:t.parent,name:t.name,type:t.type==="file"?"file":"folder",size:Number(t.size||0),modifiedAt:t.date?.toISOString()||null,displayPath:String(t.displayPath||t.name),hasChildren:t.lazy===!0||!!t.data?.length,locked:t.locked===!0}}function Xw(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Fp(t){return t.driveType==="network"?"network":t.driveType==="removable"?"removable":"local"}function CE(t){const n=t.filter(r=>Fp(r)==="local");return n.find(r=>/\bC:/i.test(`${r.name} ${r.displayPath||""}`))||n[0]||t[0]||null}function kE(t){const n=String(t.displayPath||"").trim();if(n)return n;const r=String(t.name||"").match(/\(([A-Za-z]:)\)/)?.[1];return r?`${r}\\`:t.name}function ME({hubUrl:t,roots:n,loading:r,error:o,onRefreshRoots:l,onImportFiles:u,onImportFolder:f,onSelectionChange:h,onShareItem:g,onAddSyncFolder:y,onNotice:w}){const b=d.useRef(null),S=d.useRef("/"),k=d.useRef(0),N=d.useRef([]),A=d.useRef(new Map),[j,I]=d.useState(null),[T,_]=d.useState([]),[B,F]=d.useState([]),[H,D]=d.useState(0),[K,z]=d.useState(null),[W,q]=d.useState(!1),[V,X]=d.useState(""),[ve,J]=d.useState(new Set),$=n.find(me=>me.id===j)||null,P=T[T.length-1]||null,se=$?P?.svarPath||`/${$.name}`:null,we=se;d.useEffect(()=>{N.current=T,S.current=we||"/"},[we,T]);const Z=d.useMemo(()=>(A.current.clear(),!$||!we||T.length===0?[]:(T.forEach(me=>A.current.set(me.svarPath,me.hubId)),[...T.map((me,ke)=>({id:me.svarPath,parent:ke===0?"/":T[ke-1].svarPath,type:"folder",name:me.name,date:me.modifiedAt?new Date(me.modifiedAt):void 0,lazy:!1})),...B.map(me=>{const ke=`${we}/${me.name}`;return A.current.set(ke,me.id),{id:ke,parent:we,name:me.name,type:me.type==="file"?"file":"folder",...me.type==="file"?{size:me.size}:{},date:me.modifiedAt?new Date(me.modifiedAt):void 0,lazy:me.type!=="file"&&me.hasChildren===!0,displayPath:me.displayPath,locked:me.locked,driveType:me.driveType,totalBytes:me.totalBytes,freeBytes:me.freeBytes}})])),[$,B,we,T]),Se=me=>A.current.get(String(me))||String(me),ae=me=>SE({...me,id:Se(String(me.id)),parent:Se(String(me.parent))}),ye=async(me,ke)=>{const et=me[me.length-1];if(!et)return;const Me=++k.current;q(!0),X("");try{const pe=await Eg(et.hubId,t);if(Me!==k.current)return;if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe={...et,displayPath:pe.folder.displayPath||et.displayPath,modifiedAt:pe.folder.modifiedAt||et.modifiedAt},Re=[...me.slice(0,-1),qe];N.current=Re,_(Re),F(pe.entries),D(st=>st+1)}catch(pe){if(Me!==k.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:et.hubId,error:pe}),X(pe instanceof Error?`${ke}: ${pe.message}`:`${ke}: Unable to read this folder.`)}finally{Me===k.current&&q(!1)}},Pe=async me=>{const ke={svarPath:`/${me.name}`,hubId:me.id,name:me.name,pathLabel:kE(me),displayPath:me.displayPath,modifiedAt:me.modifiedAt},et=++k.current;I(me.id),N.current=[ke],_([ke]),S.current=ke.svarPath,F([]),X(""),q(!0),z(me.id),J(Me=>{const pe=new Set(Me);return pe.delete(me.id),pe});try{const Me=await Eg(me.id,t);if(et!==k.current)return;if(!Array.isArray(Me.entries))throw new Error("Invalid Hub filesystem entries response.");const pe={...ke,pathLabel:Me.folder.displayPath||ke.pathLabel,displayPath:Me.folder.displayPath||ke.displayPath,modifiedAt:Me.folder.modifiedAt||ke.modifiedAt};N.current=[pe],_([pe]),F(Me.entries),D(qe=>qe+1)}catch(Me){if(et!==k.current)return;console.error("[LiveDesk FS] getEntries failed",{rootId:me.id,error:Me}),J(pe=>new Set(pe).add(me.id)),X(Me instanceof Error?`${me.name}: ${Me.message}`:`${me.name}: Unable to read this drive.`),w(Me instanceof Error?`${me.name}: ${Me.message}`:`${me.name}: Unable to read this drive.`)}finally{et===k.current&&(z(null),q(!1))}},de=me=>{const ke=N.current;me<0||me>=ke.length||me===ke.length-1||ye(ke.slice(0,me+1),ke[me].name)},Qe=(me,ke)=>{if(me.type!=="folder")return;const et=N.current,Me=et.findIndex(qe=>qe.svarPath===ke);if(Me<0)return;const pe={svarPath:`${ke}/${me.name}`,hubId:me.id,name:me.name,pathLabel:me.name,displayPath:me.displayPath,modifiedAt:me.modifiedAt};ye([...et.slice(0,Me+1),pe],me.name)},ue=()=>de(N.current.length-2),_e=me=>{if(me.key!=="Enter"&&me.code!=="Enter"&&me.code!=="NumpadEnter"||me.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const et=b.current;if(!et)return;const Me=et.getState().panels?.flatMap(qe=>qe.selected||[])||[];if(Me.length!==1)return;const pe=et.getFile(String(Me[0]));pe?.type==="folder"&&(me.preventDefault(),me.stopPropagation(),Qe(ae(pe),String(pe.parent||S.current)))};d.useEffect(()=>{const me=n.find(ke=>ke.id===j)||CE(n);if(J(ke=>new Set([...ke].filter(et=>n.some(Me=>Me.id===et)))),!me){I(null),N.current=[],_([]),F([]);return}Pe(me)},[n]);const Ze=me=>{b.current=me,me.on("request-data",async({id:ke})=>{const et=String(ke),Me=Se(et);try{const pe=await Eg(Me,t);if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe=pe.entries.map(Re=>{const st=`${et}/${Re.name}`;return A.current.set(st,Re.id),{id:st,parent:et,name:Re.name,type:Re.type==="file"?"file":"folder",...Re.type==="file"?{size:Re.size}:{},date:Re.modifiedAt?new Date(Re.modifiedAt):void 0,lazy:Re.type!=="file"&&Re.hasChildren===!0,displayPath:Re.displayPath,locked:Re.locked,driveType:Re.driveType,totalBytes:Re.totalBytes,freeBytes:Re.freeBytes}});await me.exec("provide-data",{id:et,data:qe})}catch(pe){console.error("[LiveDesk FS] nested getEntries failed",{id:Me,error:pe}),w(pe instanceof Error?pe.message:"Unable to read this folder.")}}),me.intercept("set-path",({id:ke})=>{const et=String(ke),Me=N.current.findIndex(qe=>qe.svarPath===et);if(Me>=0)return de(Me),!1;const pe=me.getFile(et);if(pe?.type==="folder")return Qe(ae(pe),String(pe.parent||S.current)),!1}),me.intercept("open-file",()=>!1),me.on("select-file",()=>{window.setTimeout(()=>{const Me=(me.getState().panels?.flatMap(pe=>pe.selected||[])||[]).map(pe=>me.getFile(pe)).filter(Boolean).map(pe=>ae(pe));h(Me.map(pe=>pe.id),Me)},0)})},at=(me,ke)=>{const et=ke?ae(ke):null,Me=()=>{const pe=et?.type==="file"?String(ke?.parent||S.current):String(ke?.id||S.current);b.current?.exec("request-data",{id:pe})};return me==="body"?[{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w("Select a file or folder to view its properties.")}]:me==="multiselect"?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>{(b.current?.getState().panels?.flatMap(qe=>qe.selected||[])||[]).forEach(qe=>{const Re=b.current?.getFile(qe);Re&&g(ae(Re))})}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me}]:et?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(et)},...et.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(et)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Dp(et.displayPath||et.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${et.name}
|
|
179
|
+
${et.displayPath||""}`)}]:[]},Ee=async()=>{try{await l()}catch(me){w(me instanceof Error?me.message:"Unable to refresh Hub drives.")}},Ge=[{id:"local",label:"Local drives",icon:nu,roots:n.filter(me=>Fp(me)==="local")},{id:"removable",label:"Removable drives",icon:bk,roots:n.filter(me=>Fp(me)==="removable")},{id:"network",label:"Network drives",icon:kv,roots:n.filter(me=>Fp(me)==="network")}];return i.jsxs("section",{className:"hub-file-explorer-panel","aria-label":"Hub file explorer",children:[i.jsxs("div",{className:"hub-file-explorer-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub file explorer"}),i.jsxs("strong",{children:[i.jsx(nu,{size:16})," Browse files on this Hub"]})]}),i.jsxs("div",{className:"hub-file-explorer-heading-actions",children:[i.jsx("button",{className:"icon-button",onClick:u,title:"Import files from this browser",type:"button",children:i.jsx(Qx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:i.jsx(wk,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ee()},title:"Refresh drives",type:"button",children:i.jsx(ou,{size:16})})]})]}),r?i.jsxs("div",{className:"hub-file-explorer-state",children:[i.jsx(nu,{size:24}),i.jsx("strong",{children:"Connecting to LiveDesk Hub file system..."})]}):o?i.jsxs("div",{className:"hub-file-explorer-state error",role:"alert",children:[i.jsx(nl,{size:24}),i.jsx("strong",{children:o})]}):i.jsxs("div",{className:"hub-file-explorer-content",children:[i.jsxs("aside",{className:"hub-file-explorer-drive-sidebar","aria-label":"Hub drives",children:[i.jsxs("div",{className:"hub-drive-sidebar-title",children:[i.jsx(nu,{size:15}),i.jsx("strong",{children:"This PC"})]}),Ge.map(me=>me.roots.length>0&&i.jsxs("section",{className:"hub-drive-group",children:[i.jsxs("h3",{children:[i.jsx(me.icon,{size:13}),me.label]}),i.jsx("div",{className:"hub-drive-list",children:me.roots.map(ke=>{const et=me.icon,Me=ve.has(ke.id)||ke.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${j===ke.id?"active":""} ${Me?"unavailable":""}`,onClick:()=>{Pe(ke)},"aria-pressed":j===ke.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(et,{size:16})}),i.jsxs("span",{className:"hub-drive-item-copy",children:[i.jsx("strong",{children:ke.name}),i.jsx("small",{children:ke.displayPath||ke.name}),i.jsxs("em",{children:[Xw(ke.freeBytes||0)," free / ",Xw(ke.totalBytes||0)]})]}),K===ke.id?i.jsx($r,{className:"hub-drive-item-status spin",size:15}):Me?i.jsx(wb,{className:"hub-drive-item-status",size:15}):null]},ke.id)})})]},me.id)),n.length===0&&i.jsxs("div",{className:"hub-drive-sidebar-empty",children:[i.jsx(nl,{size:17}),i.jsx("span",{children:"No drives available."})]})]}),i.jsxs("div",{className:"hub-file-explorer-browser",children:[i.jsxs("div",{className:"hub-file-explorer-navigation",children:[i.jsx("nav",{className:"hub-file-explorer-breadcrumbs","aria-label":"Current Hub folder",children:T.map((me,ke)=>i.jsxs("span",{className:"hub-file-explorer-breadcrumb-item",children:[ke>0&&i.jsx(Mv,{size:13,"aria-hidden":"true"}),i.jsx("button",{className:`hub-file-explorer-breadcrumb ${ke===T.length-1?"current":""}`,onClick:()=>de(ke),title:me.displayPath||me.pathLabel,"data-hub-folder-id":me.hubId,"aria-current":ke===T.length-1?"location":void 0,type:"button",children:me.pathLabel})]},me.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[W&&i.jsx($r,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:ue,disabled:T.length<=1||W,title:"Back to parent folder",type:"button",children:i.jsx($x,{size:16})})]})]}),V&&i.jsxs("div",{className:"hub-file-explorer-folder-error",role:"alert",children:[i.jsx(wb,{size:15}),i.jsx("span",{children:V})]}),i.jsx("div",{className:"hub-file-explorer-svar",onKeyDownCapture:_e,children:i.jsx(uE,{fonts:!1,children:i.jsx(cE,{data:Z,panels:se?[{path:se,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Ze,icons:"simple",menuOptions:at},`${$?.id||"no-root"}:${H}`)})})]})]})]})}class AE extends d.Component{state={error:null};static getDerivedStateFromError(n){return{error:n}}componentDidCatch(n,r){console.error("[LiveDesk] Share Files runtime error",n,r.componentStack)}render(){return this.state.error?i.jsxs("section",{className:"file-share-error-boundary",role:"alert",children:[i.jsx(th,{size:24}),i.jsx("strong",{children:"Share Files could not be opened."}),i.jsx("span",{children:this.state.error.message||"An unexpected file explorer error occurred."}),i.jsxs("button",{className:"text-button",onClick:this.props.onRetry,type:"button",children:[i.jsx(ou,{size:15})," Retry"]})]}):this.props.children}}function NE(t){return t.deviceName||t.hostname||t.deviceId}function TE({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:l}){const u=new Set(r);return i.jsxs("section",{className:"distribution-targets",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:n==="all"?`${t.length} connected`:`${r.length} selected`})]}),i.jsxs("div",{className:"file-share-tabs compact","aria-label":"File transfer targets",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(nm,{size:14})," All connected"]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(Ar,{size:14})," Selected"]})]})]}),i.jsx("div",{className:"file-share-device-list","aria-label":"Connected Client targets",children:t.length===0?i.jsx("div",{className:"file-share-empty-inline",children:"No connected Clients."}):t.map(f=>{const h=n==="all"||u.has(f.deviceId);return i.jsxs("label",{className:`file-share-device-option ${h?"selected":""}`,children:[i.jsx("input",{type:"checkbox",checked:h,disabled:n==="all",onChange:()=>l(f.deviceId)}),i.jsx(Ar,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:NE(f)}),i.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),i.jsx(_a,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function RE(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function jE({folders:t,loading:n,busy:r,canSync:o,onSyncAll:l,onSync:u,onToggleAuto:f,onRemove:h,onAdd:g}){return i.jsxs("section",{className:"file-share-sync-panel",children:[i.jsxs("div",{className:"file-share-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Hub folders"}),i.jsx("strong",{children:"Continuous sync"})]}),i.jsxs("button",{className:"text-button compact",onClick:l,disabled:r||!o||t.length===0,type:"button",children:[i.jsx(Kf,{size:15})," ",r?"Syncing":"Sync all"]})]}),n?i.jsx("div",{className:"file-share-empty-state",children:"Loading Hub sync folders..."}):t.length===0?i.jsxs("button",{className:"file-share-empty-state interactive",onClick:g,type:"button",children:[i.jsx(Kf,{size:28}),i.jsx("strong",{children:"Add a selected Hub folder"}),i.jsx("span",{children:"Hub keeps the manifest and can sync while this browser is closed."})]}):i.jsx("div",{className:"file-share-sync-list",children:t.map(y=>i.jsxs("article",{className:`file-share-sync-row state-${y.status}`,children:[i.jsx("div",{className:"file-share-sync-icon",children:i.jsx(Kf,{size:19})}),i.jsxs("div",{className:"file-share-sync-info",children:[i.jsx("strong",{children:y.name}),i.jsx("span",{children:y.displayPath}),i.jsxs("small",{children:[y.fileCount," files / ",RE(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${u0(y.lastSyncedAt)} ago`:y.message||"Not synced yet"]})]}),i.jsxs("label",{className:"file-share-auto-sync",children:[i.jsx("input",{type:"checkbox",checked:y.autoSync,onChange:()=>f(y)}),i.jsx("span",{children:"Auto"})]}),i.jsxs("button",{className:"text-button compact",onClick:()=>u(y),disabled:r||!o||y.status==="syncing",type:"button",children:[i.jsx(ou,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(Yx,{size:15})})]},y.id))})]})}function EE(t){const r=(t.targetMode==="all"?t.devices.map(o=>o.deviceId):t.selectedTargetIds).length>0;return i.jsxs("aside",{className:"file-share-distribution-panel",children:[i.jsxs("div",{className:"file-share-distribution-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Distribution"}),i.jsx("strong",{children:"Hub → Clients"})]}),i.jsx(tm,{size:18})]}),i.jsxs("div",{className:"file-share-tabs",role:"tablist","aria-label":"Distribution mode",children:[i.jsx("button",{className:t.tab==="send"?"active":"",onClick:()=>t.onTabChange("send"),role:"tab","aria-selected":t.tab==="send",type:"button",children:"Send"}),i.jsx("button",{className:t.tab==="sync"?"active":"",onClick:()=>t.onTabChange("sync"),role:"tab","aria-selected":t.tab==="sync",type:"button",children:"Sync"})]}),t.tab==="send"?i.jsxs(i.Fragment,{children:[i.jsx(TE,{devices:t.devices,mode:t.targetMode,selectedIds:t.selectedTargetIds,onModeChange:t.onTargetModeChange,onToggle:t.onTargetToggle}),i.jsxs("label",{className:"file-share-destination",children:[i.jsx("span",{children:"Destination folder"}),i.jsxs("div",{children:[i.jsx(Ad,{size:15}),i.jsx("input",{value:t.remoteDirectory,onChange:o=>t.onRemoteDirectoryChange(o.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("small",{children:"Blank uses Desktop/LiveDeskFiles."})]}),i.jsxs("div",{className:"file-share-selection-summary",children:[i.jsx("span",{children:"Selected"}),i.jsx("strong",{children:t.selectedSummary})]}),i.jsxs("button",{className:"file-share-share-button",onClick:t.onShare,disabled:!t.canShare,type:"button",children:[i.jsx(tm,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[i.jsx(Ad,{size:16})," Add selected folder to Sync"]})]}):i.jsx(jE,{folders:t.folders,loading:t.foldersLoading,busy:t.syncBusy,canSync:r,onSyncAll:t.onSyncAll,onSync:t.onSync,onToggleAuto:t.onToggleAuto,onRemove:t.onRemove,onAdd:t.onAddFolder})]})}function DE(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;return`${r.toFixed(o===0||r>=100?0:1)} ${n[o]}`}function Zw(t){if(t.state==="completed")return 100;const n=t.totalBytes>0?Math.round(t.sentBytes/t.totalBytes*100):t.totalFiles>0?Math.round(t.completedFiles/t.totalFiles*100):0;return Math.max(0,Math.min(wv(t.state)?100:99,n))}function Jw(t){return t.state==="scanning"?"Scanning selected Hub items":t.state==="queued"?"Preparing transfer":t.state==="sending"?`${t.completedFiles}/${t.totalFiles} · ${t.currentPath||"sending"}`:t.state==="completed"?`Sent ${t.totalFiles} file${t.totalFiles===1?"":"s"} to ${t.targetCount} Client${t.targetCount===1?"":"s"}`:t.state==="partially-failed"?`${t.failedTargets.length} Client${t.failedTargets.length===1?"":"s"} failed`:t.state==="cancelled"?"Transfer cancelled":t.error||"Transfer failed"}function wv(t){return["completed","partially-failed","failed","cancelled"].includes(t)}function IE({hubUrl:t,devices:n,localFeatureAccess:r,upgradeNotice:o,remoteDirectory:l,onRemoteDirectoryChange:u,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,filePickerRef:w,folderPickerRef:b,onBrowserFileImport:S,onBrowserFolderImport:k,onNotice:N,onTransferChange:A}){const j=Array.isArray(n)?n:[],[I,T]=d.useState([]),[_,B]=d.useState(!0),[F,H]=d.useState(""),[D,K]=d.useState([]),[z,W]=d.useState([]),[q,V]=d.useState(null),[X,ve]=d.useState(!1),[J,$]=d.useState([]),[P,se]=d.useState(!0),[we,Z]=d.useState(!1),[Se,ae]=d.useState("send"),[ye,Pe]=d.useState([]),de=d.useRef(new Set),Qe=d.useRef(!1),ue=d.useMemo(()=>f==="all"?j.map(O=>O.deviceId):h.filter(O=>j.some(ze=>ze.deviceId===O)),[j,h,f]),_e=ye.find(O=>!wv(O.state)),Ze=z.length===1&&z[0].type==="folder"?z[0]:null,at=z.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":q?`${q.files} files, ${q.folders} folders · ${DE(q.totalBytes)}`:`${z.length} item${z.length===1?"":"s"} selected`,Ee=O=>{A({id:O.jobId,state:O.state,progress:Zw(O),message:Jw(O)})},Ge=d.useCallback(async()=>{const O=await fE(t,!0);return T(O),H(""),O},[t]),me=async()=>{if(!Qe.current){Qe.current=!0;try{const ze=(await hE(t,!0)).jobs||[],We=await Promise.all([...de.current].map(async ht=>{try{return await gE(ht,t)}catch{return null}})),Et=[...ze,...We.filter(Boolean)],lt=[...new Map(Et.map(ht=>[ht.jobId,ht])).values()];Pe(lt),lt.forEach(Ee),lt.filter(ht=>wv(ht.state)).forEach(ht=>de.current.delete(ht.jobId))}catch{}finally{Qe.current=!1}}};d.useEffect(()=>{let O=!0;B(!0),H(""),Promise.all([Ge(),Yw(t).then(We=>{O&&$(We)})]).catch(We=>{O&&(H(We instanceof Error?"Hub file system is unavailable. Make sure LiveDesk Hub is running on this computer.":"Hub file system is unavailable."),N(We instanceof Error?We.message:"Hub file system is unavailable."))}).finally(()=>{O&&(B(!1),se(!1))}),me();const ze=window.setInterval(()=>{me()},800);return()=>{O=!1,window.clearInterval(ze)}},[t,Ge]),d.useEffect(()=>{if(D.length===0){V(null);return}let O=!1;return ve(!0),mE(D,t).then(ze=>{O||V(ze)}).catch(ze=>{O||N(ze instanceof Error?ze.message:"Unable to calculate selected size.")}).finally(()=>{O||ve(!1)}),()=>{O=!0}},[t,D.join("|")]);const ke=(O,ze)=>{K(O),W(ze)},et=O=>{O.forEach(ze=>de.current.add(ze.jobId)),Pe(ze=>[...new Map([...ze,...O].map(We=>[We.jobId,We])).values()]),O.forEach(Ee)},Me=async()=>{if(!r){N(o);return}if(D.length===0){N("Select files or folders from the Hub explorer.");return}if(ue.length===0){N("Choose at least one connected Client.");return}if(_e){N("A Hub transfer is already running.");return}try{const O=await pE(D,ue,l.trim(),t);de.current.add(O.jobId),N("Hub transfer queued."),await me()}catch(O){N(O instanceof Error?O.message:"Unable to start Hub transfer.")}},pe=async O=>{const ze=O||Ze;if(!ze||ze.type!=="folder"){N("Select one folder to add it to Sync.");return}try{const We=await yE(ze.id,t);$(Et=>[...Et.filter(lt=>lt.id!==We.folder.id),We.folder]),ae("sync"),N(`${ze.name} is ready for Hub sync.`)}catch(We){N(We instanceof Error?We.message:"Unable to add the Hub folder to Sync.")}},qe=async O=>{if(ue.length===0){N("Choose at least one connected Client.");return}Z(!0),$(ze=>ze.map(We=>We.id===O.id?{...We,status:"syncing"}:We));try{const ze=await xE(O.id,ue,l.trim(),t);et(ze.jobs||[]),N(ze.jobs?.length?"Hub sync queued.":"No changed files to sync.");const We=await Yw(t);$(We)}catch(ze){N(ze instanceof Error?ze.message:"Unable to sync the Hub folder."),$(We=>We.map(Et=>Et.id===O.id?{...Et,status:"error",message:"Sync failed"}:Et))}finally{Z(!1)}},Re=async()=>{Z(!0);try{for(const O of J)await qe(O)}finally{Z(!1)}},st=async O=>{try{const ze=await bE(O.id,{autoSync:!O.autoSync},t);$(We=>We.map(Et=>Et.id===O.id?ze.folder:Et))}catch(ze){N(ze instanceof Error?ze.message:"Unable to update auto sync.")}},jt=async O=>{try{await wE(O.id,t),$(ze=>ze.filter(We=>We.id!==O.id))}catch(ze){N(ze instanceof Error?ze.message:"Unable to remove the sync folder.")}};return i.jsxs("section",{className:"livedesk-file-explorer",children:[i.jsx("input",{ref:w,className:"hidden-file-input",type:"file",multiple:!0,onChange:O=>{O.currentTarget.files&&S(O.currentTarget.files),O.currentTarget.value=""}}),i.jsx("input",{ref:b,className:"hidden-file-input",type:"file",multiple:!0,webkitdirectory:"",directory:"",onChange:O=>{O.currentTarget.files&&k(O.currentTarget.files),O.currentTarget.value=""}}),i.jsx("div",{className:"file-share-workspace",children:i.jsxs(AE,{onRetry:()=>window.location.reload(),children:[i.jsx(ME,{hubUrl:t,roots:I,loading:_,error:F,onRefreshRoots:Ge,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ke,onShareItem:O=>{K([O.id]),W([O]),ae("send")},onAddSyncFolder:O=>{K([O.id]),W([O]),pe(O)},onNotice:N}),i.jsx(EE,{devices:j,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:z,selectedSummary:at,canShare:r&&!_e&&D.length>0&&ue.length>0&&!X,onShare:()=>{Me()},canAddSync:!!Ze,onAddSync:()=>{pe()},tab:Se,onTabChange:ae,folders:J,foldersLoading:P,syncBusy:we,onSyncAll:()=>{Re()},onSync:O=>{qe(O)},onToggleAuto:O=>{st(O)},onRemove:O=>{jt(O)},onAddFolder:()=>{pe()}})]})}),_e&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Jw(_e)," · ",Zw(_e),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{vE(_e.jobId,t).then(O=>{Pe(ze=>ze.map(We=>We.jobId===O.jobId?O:We)),Ee(O)})},title:"Cancel transfer",type:"button",children:i.jsx(rr,{size:14})})]})})]})}const LE=d.forwardRef(function({value:n,onChange:r,onSubmit:o,onOpenSuggestedTasks:l,suggestedOpen:u=!1,suggestedTaskCount:f,disabled:h=!1,placeholder:g="Ask LiveDesk to work across your machines...",compact:y=!1},w){return i.jsxs("form",{className:"agents-composer",onSubmit:b=>{b.preventDefault(),o()},children:[i.jsx("button",{className:`agents-suggested-trigger ${u?"active":""}`,type:"button","aria-label":f===void 0?"Open Suggested tasks":`Open Suggested tasks (${f} available)`,"aria-expanded":u,onClick:l,disabled:h,children:i.jsx(xk,{size:17})}),i.jsx("textarea",{ref:w,value:n,onChange:b=>r(b.target.value.slice(0,4e3)),placeholder:g,"aria-label":"Ask LiveDesk",rows:y?1:2,disabled:h}),i.jsxs("button",{className:"agents-run-button",type:"submit",disabled:h||!n.trim(),children:[h?i.jsx($r,{className:"spin",size:16}):i.jsx(tm,{size:16}),h?"Running":"Run"]})]})}),PE=["read","processControl","serviceControl","applicationControl","fileRead","fileWrite","fileDelete","shell","script","softwareInstall","network","systemPower","systemConfiguration","userAccount"];function Xp(t){return t.deviceName?.trim()||t.hostname?.trim()||t.deviceId}function Zp(t){return t.connected!==!0?!1:t.synthetic===!0?!0:!t.channels||t.channels.control===!0}function _E(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function FE(t){switch(t){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 OE(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function os(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function xp(t){const n=os(t);return n===null?"":n<1024**2?`${Math.round(n/1024)}K`:n<1024**3?`${(n/1024**2).toFixed(0)}M`:`${(n/1024**3).toFixed(1)}G`}function ex(t){const n=os(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function BE(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Jp(t,n){if(n.error)return n.error;const r=OE(n.data),o=BE(n.result||"");if(!r)return o||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=ex(r.cpuUsageRatio),f=os(r.cores),h=xp(r.freeMemoryBytes),g=xp(r.totalMemoryBytes),y=os(r.totalMemoryBytes)&&os(r.freeMemoryBytes)!==null?`${Math.round(os(r.freeMemoryBytes)/os(r.totalMemoryBytes)*100)}% RAM free`:"";return[l,u&&`CPU ${u}`,f!==null&&`${Math.round(f)} cores`,h&&g?`RAM ${h}/${g}`:"",y,typeof r.platform=="string"?r.platform:""].filter(Boolean).join(" · ")||o||n.status}if(t==="disk.status"){const l=typeof r.root=="string"?r.root:"",u=xp(r.freeBytes),f=os(r.totalBytes)&&os(r.freeBytes)!==null?`${Math.round(os(r.freeBytes)/os(r.totalBytes)*100)}% free`:"";return[l,u&&`${u} free`,f].filter(Boolean).join(" · ")||o||n.status}if(t==="gpu.status"){const l=typeof r.name=="string"&&r.name?r.name:"No GPU detected",u=ex(r.usageRatio),f=os(r.temperatureC)!==null?`${Math.round(os(r.temperatureC))}°C`:"",h=xp(r.freeMemoryBytes);return[l,u&&`GPU ${u}`,f,h&&`${h} free`].filter(Boolean).join(" · ")||o||n.status}if(t==="process.list"){const l=os(r.count);return l!==null?`${l} matching process${l===1?"":"es"}`:o||n.status}if(t==="network.status"){const l=Array.isArray(r.adapters)?r.adapters.length:null;return l!==null?`${l} active adapter${l===1?"":"s"}`:o||n.status}return o||n.stage||n.status}function tx(t,n){const r=Jp(t,n);return n.status==="failed"||n.status==="cancelled"||/\b(?:warning|failed|error|offline|not running|low|timeout|timed out)\b/i.test(`${n.result||""} ${r}`)}function HE({state:t,operation:n}){const r=t.status==="completed"?al:t.status==="failed"||t.status==="cancelled"?rr:t.status==="running"?$r:Xx,o=t.status==="running"?t.stage||"Working":t.status==="completed"?n?Jp(n,t):t.result||"Completed":t.status==="failed"?t.error||"Failed":t.status==="cancelled"?"Cancelled":"Queued";return i.jsxs("div",{className:`agent-target-row status-${t.status}`,"data-agent-target-id":t.deviceId,children:[i.jsx("span",{className:"agent-target-status","aria-hidden":"true",children:i.jsx(r,{size:15})}),i.jsx("strong",{children:t.deviceName}),i.jsx("span",{className:"agent-target-state",children:t.status[0].toUpperCase()+t.status.slice(1)}),i.jsx("small",{children:o})]})}function zE({operation:t,states:n,status:r,onCancel:o,onRetry:l,busy:u=!1}){const f=["running","queued"].includes(r),[h,g]=d.useState(!1),[y,w]=d.useState("all"),b=d.useMemo(()=>({total:n.length,completed:n.filter(_=>_.status==="completed").length,failed:n.filter(_=>_.status==="failed").length,running:n.filter(_=>_.status==="running").length,queued:n.filter(_=>_.status==="queued").length,cancelled:n.filter(_=>_.status==="cancelled").length}),[n]),S=n.filter(_=>tx(t,_)),k=S.filter(_=>_.status==="completed").length,N=b.failed>0,A=S.length>0,j=n.filter(_=>y==="issues"?tx(t,_):y==="running"?_.status==="running"||_.status==="queued":y==="completed"?_.status==="completed":y==="failed"?_.status==="failed":!0),I=A&&!f||r==="completed-with-failures"?"Completed with issues":r[0]?.toUpperCase()+r.slice(1),T=n.filter(_=>_.status==="completed").map(_=>Jp(t,_)).filter(Boolean).filter((_,B,F)=>F.indexOf(_)===B).slice(0,2);return i.jsxs("section",{className:"agent-task-block","aria-label":"Task execution",children:[i.jsxs("div",{className:"agent-task-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"LiveDesk Agent"}),i.jsx("strong",{children:FE(t)})]}),i.jsx("span",{className:`agent-task-status status-${A?"completed-with-failures":r}`,children:I})]}),i.jsxs("div",{className:"agent-task-summary","aria-label":"Task summary",children:[i.jsxs("strong",{children:[b.total," targets"]}),i.jsxs("span",{className:"summary-completed",children:[b.completed," completed"]}),b.running>0&&i.jsxs("span",{className:"summary-running",children:[b.running," running"]}),b.queued>0&&i.jsxs("span",{children:[b.queued," queued"]}),N&&i.jsxs("span",{className:"summary-failed",children:[b.failed," failed"]}),k>0&&i.jsxs("span",{className:"summary-cancelled",children:[k," warning"]}),b.cancelled>0&&i.jsxs("span",{className:"summary-cancelled",children:[b.cancelled," cancelled"]})]}),T.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:T.join(" · "),children:[i.jsx("span",{children:"Result"}),T.join(" · ")]}),i.jsx("div",{className:"agent-target-chips","aria-label":"Target status overview",children:n.map((_,B)=>{const F=_.status==="completed"?"✓":_.status==="failed"?"×":_.status==="cancelled"?"!":_.status==="running"?"…":"·";return i.jsxs("span",{className:`agent-target-chip status-${_.status}`,title:`${_.deviceName}: ${Jp(t,_)}`,"aria-label":`${B+1}. ${_.deviceName}: ${_.status}`,children:[i.jsx("b",{children:String(B+1).padStart(2,"0")}),i.jsx("span",{children:F})]},_.deviceId)})}),n.length>0&&i.jsx("div",{className:"agent-task-details-toggle",children:i.jsxs("button",{type:"button",onClick:()=>g(_=>!_),"aria-expanded":h,children:[h?i.jsx(Sk,{size:14}):i.jsx(Zx,{size:14}),h?"Hide details":"Show details"]})}),h&&i.jsxs("div",{className:"agent-task-details",children:[i.jsx("div",{className:"agent-task-filters",role:"tablist","aria-label":"Task result filter",children:["all","issues","running","completed","failed"].map(_=>i.jsx("button",{className:y===_?"active":"",onClick:()=>w(_),role:"tab","aria-selected":y===_,type:"button",children:_==="all"?"All":_==="issues"?"Issues only":_[0].toUpperCase()+_.slice(1)},_))}),i.jsx("div",{className:"agent-task-rows",children:j.length>0?j.map(_=>i.jsx(HE,{operation:t,state:_},_.deviceId)):i.jsx("small",{className:"agent-task-no-results",children:"No targets match this filter."})})]}),(f||N)&&i.jsxs("div",{className:"agent-task-actions",children:[f&&o&&i.jsxs("button",{onClick:o,disabled:u,type:"button",children:[i.jsx(Ck,{size:14})," Cancel"]}),!f&&N&&l&&i.jsxs("button",{onClick:l,disabled:u,type:"button",children:[i.jsx(Vg,{size:14})," Retry failed"]})]})]})}function $E(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function UE({approval:t,busy:n=!1,onApprove:r,onReject:o}){return i.jsxs("article",{className:"agent-approval-card","aria-label":"Agent approval required",children:[i.jsxs("div",{className:"agent-approval-head",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Approval required"}),i.jsx("strong",{children:t.toolName})]}),i.jsx("span",{className:`agent-approval-risk risk-${t.risk}`,children:t.risk})]}),i.jsx("p",{children:t.description}),i.jsx("pre",{children:$E(t.arguments)}),i.jsxs("small",{children:["Permission: ",t.permissionMode," · Scope: selected devices only · Expires in 5 minutes"]}),i.jsxs("div",{className:"agent-approval-actions",children:[i.jsxs("button",{className:"reject",disabled:n,onClick:o,type:"button",children:[i.jsx(rr,{size:14})," Reject"]}),i.jsxs("button",{disabled:n,onClick:()=>r("once"),type:"button",children:[i.jsx(al,{size:14})," Once"]}),i.jsx("button",{disabled:n,onClick:()=>r("same-action-this-run"),type:"button",children:"Allow same action"}),i.jsx("button",{disabled:n,onClick:()=>r("category-this-run"),type:"button",children:"Allow category"})]}),i.jsxs("div",{className:"agent-approval-scope",children:[i.jsx(th,{size:13})," Approval is bound to this run, tool, arguments, selected devices, and policy hash."]})]})}function qE(t){return t==="queued"?"Request queued":t==="checking-codex"?"Checking Codex":t==="preparing-tools"?"Preparing tools":t==="thinking"?"Preparing answer":t==="tool-running"?"Working on computers":t==="recovering"?"Retrying safely":t==="waiting-approval"?"Waiting for approval":"Working"}function WE({items:t,onCancel:n,onRetry:r,busyBatchId:o,approvals:l,onApprove:u,onReject:f,busyApprovalId:h,progress:g,emptyTitle:y="Ask LiveDesk to work across your machines.",emptyBody:w="Start with a read-only request such as “현재 대상에서 CPU와 메모리 상태를 확인해줘”."}){const b=d.useRef(null),S=d.useRef(!0),k=d.useRef(""),N=t[t.length-1];return d.useLayoutEffect(()=>{const A=b.current;A&&(N?.type==="user"&&N.id!==k.current&&(S.current=!0),k.current=N?.id||"",S.current&&(A.scrollTop=A.scrollHeight))},[l,t,N?.id,N?.type,g?.message,g?.stage]),i.jsxs("section",{className:"agents-conversation","aria-live":"polite",ref:b,onScroll:A=>{const j=A.currentTarget;S.current=j.scrollHeight-j.scrollTop-j.clientHeight<72},children:[l.filter(A=>A.status==="pending").map(A=>i.jsx(UE,{approval:A,busy:h===A.approvalId,onApprove:j=>u(A,j),onReject:()=>f(A)},A.approvalId)),t.length===0&&i.jsxs("div",{className:"agents-empty-conversation",children:[i.jsx("strong",{children:y}),i.jsx("span",{children:w})]}),t.map(A=>{if(A.type==="task"){const j=A;return i.jsx(zE,{operation:j.operation,states:j.states,status:j.status,onCancel:()=>n(j.batchId,j.agentRunId),onRetry:()=>r(j.batchId),busy:o===j.batchId},j.id)}return i.jsxs("article",{className:`agents-message ${A.type}`,children:[i.jsx("span",{children:A.type==="user"?"You":"LiveDesk Agent"}),i.jsx("p",{children:A.text})]},A.id)}),g&&i.jsxs("article",{className:"agents-message agent agents-progress-message",role:"status",children:[i.jsxs("span",{children:[i.jsx($r,{"aria-hidden":"true",size:15}),qE(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const nx=["Recommended","Health & capacity","Processes & services","Files & configuration","Software & automation","Network & connectivity","Power & maintenance","Troubleshooting & recovery"],ca=["windows","macos","linux"],Xl={"system.health":{label:"system health",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"gpu.status":{label:"GPU status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"disk.status":{label:"disk status",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"process.list":{label:"process inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"service.status":{label:"service inspection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"diagnostics.collect":{label:"diagnostics collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca},"process.control":{label:"process control",permissionCategory:"processControl",readOnly:!1,risk:"high",supportedPlatforms:ca},"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:ca},"application.close":{label:"application close",permissionCategory:"applicationControl",readOnly:!1,risk:"medium",supportedPlatforms:ca},"file.read":{label:"file reading",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ca},"file.write":{label:"file writing",permissionCategory:"fileWrite",readOnly:!1,risk:"high",supportedPlatforms:ca},"file.delete":{label:"file deletion",permissionCategory:"fileDelete",readOnly:!1,risk:"critical",supportedPlatforms:ca},"file.list":{label:"directory listing",permissionCategory:"fileRead",readOnly:!0,risk:"low",supportedPlatforms:ca},"command.run":{label:"command execution",permissionCategory:"shell",readOnly:!1,risk:"critical",supportedPlatforms:ca},"script.run":{label:"script execution",permissionCategory:"script",readOnly:!1,risk:"high",supportedPlatforms:ca},"software.install":{label:"software installation",permissionCategory:"softwareInstall",readOnly:!1,risk:"high",supportedPlatforms:ca},"network.status":{label:"network inspection",permissionCategory:"network",readOnly:!0,risk:"low",supportedPlatforms:ca},"system.power":{label:"power control",permissionCategory:"systemPower",readOnly:!1,risk:"critical",supportedPlatforms:ca},"system.configure":{label:"system configuration",permissionCategory:"systemConfiguration",readOnly:!1,risk:"critical",supportedPlatforms:ca},"logs.collect":{label:"log collection",permissionCategory:"read",readOnly:!0,risk:"low",supportedPlatforms:ca}};new Set(Object.keys(Xl));const GE={Recommended:["recommended","overview","fleet","요약","추천"],"Health & capacity":["health","capacity","performance","상태","성능","용량"],"Processes & services":["process","service","application","프로세스","서비스","앱"],"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","문제해결","복구","장애"]},ax=["low","medium","high","critical"];function VE(t){return t.reduce((n,r)=>{const o=Xl[r].risk;return ax.indexOf(o)>ax.indexOf(n)?o:n},"low")}function KE(t){return ca.filter(n=>t.every(r=>Xl[r].supportedPlatforms.includes(n)))}function ct(t,n,r,o,l,u,f={}){const h=f.description||o,g=l.flatMap(w=>w.split(".")),y=[...new Set([...GE[n],...u,...g])];return{id:t,category:n,title:r,prompt:o,description:h,requiredOperations:l,risk:f.risk||VE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||KE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const LS=[ct("recommended-fleet-health","Recommended","Summarize current target health","Summarize system health, GPU, and disk capacity for the current target Clients.",["system.health","gpu.status","disk.status"],["summary","overview"],{recommended:!0}),ct("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}),ct("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}),ct("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}),ct("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}),ct("recommended-process-services","Recommended","Review processes and services","Review running processes and service state for warnings on the current targets.",["process.list","service.status"],["process","service","warning"],{recommended:!0}),ct("recommended-recover-application","Recommended","Recover a stopped application","Check a named application or service, relaunch its registered entry when stopped, and verify the result.",["process.list","application.launch","service.status"],["recover","start","application"],{targetSupport:"single",recommended:!0}),ct("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}),ct("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","높은 사용량"]),ct("health-uptime","Health & capacity","Review Client uptime","Show uptime, boot time, and current system health for the target Clients.",["system.health"],["uptime","boot","가동시간"]),ct("health-gpu-temperature","Health & capacity","Check GPU temperature","Check GPU temperature and thermal warnings on the current targets.",["gpu.status"],["thermal","temperature","발열"]),ct("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"]),ct("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","디스크"]),ct("health-gpu-compare","Health & capacity","Compare GPU capacity","Compare GPU model, memory, temperature, and utilization across the current targets.",["gpu.status"],["compare","graphics","capacity"]),ct("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","경고"]),ct("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"]),ct("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","실행 중"]),ct("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"]),ct("process-stop-named","Processes & services","Stop a named process","Stop process named [process name] on the target Client after checking its current state.",["process.list","process.control"],["stop","terminate","종료"],{targetSupport:"single"}),ct("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"}),ct("process-launch-app","Processes & services","Launch a registered application","Launch the registered application [application] on the target Client with [arguments].",["application.launch"],["launch","open","실행"],{targetSupport:"single"}),ct("process-close-app","Processes & services","Close an application","Close application [application] on the target Client and report whether it exited cleanly.",["application.close","process.list"],["close","exit","앱 종료"],{targetSupport:"single"}),ct("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","서비스 상태"]),ct("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"}),ct("files-list-directory","Files & configuration","List a directory","List files and folders under [path] on the target Client.",["file.list"],["directory","folder","list","목록"],{targetSupport:"single"}),ct("files-read-config","Files & configuration","Read a configuration file","Read the relevant settings from configuration file [path] on the target Client.",["file.read"],["config","settings","read","구성"]),ct("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"]),ct("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"}),ct("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"}),ct("files-compare-config","Files & configuration","Compare configuration files","Read configuration file [path] on the target Client and compare it with [reference path].",["file.read"],["compare","diff","configuration"]),ct("files-set-environment","Files & configuration","Set an environment variable","Set environment variable [name] to [value] for the target Client and verify the resulting configuration.",["system.configure","file.read"],["environment","variable","env","환경변수"],{targetSupport:"single"}),ct("files-archive-diagnostics","Files & configuration","Write a diagnostic manifest","Collect selected diagnostics and write a manifest file to [path] on the target Client.",["diagnostics.collect","file.write"],["manifest","export","diagnostic file"],{targetSupport:"single"}),ct("software-winget-install","Software & automation","Install software with winget","Install package [package name] with winget on the Windows target Client, then verify it.",["software.install","process.list"],["winget","windows","install","설치"],{targetSupport:"single",supportedPlatforms:["windows"]}),ct("software-apt-install","Software & automation","Install software with apt","Install package [package name] with apt on the Linux target Client, then verify it.",["software.install","process.list"],["apt","linux","package","설치"],{targetSupport:"single",supportedPlatforms:["linux"]}),ct("software-brew-install","Software & automation","Install software with Homebrew","Install package [package name] with brew on the macOS target Client, then verify it.",["software.install","process.list"],["brew","homebrew","macos","설치"],{targetSupport:"single",supportedPlatforms:["macos"]}),ct("software-npm-install","Software & automation","Install an npm package","Install npm package [package name] on the target Client and verify the installed version.",["software.install","command.run"],["npm","node","package"],{targetSupport:"single"}),ct("software-run-script","Software & automation","Run a registered script","Run the registered script [script path] on the target Client and report its result.",["script.run"],["script","automation","registered"],{targetSupport:"single"}),ct("software-run-command","Software & automation","Run a command on one target","Run command [command] on the target Client and return its exit status and output.",["command.run"],["command","shell","terminal"],{targetSupport:"single"}),ct("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"]),ct("software-toolchain-setup","Software & automation","Set up a toolchain","Install the requested package [package name], configure [change], and verify the toolchain on the target Client.",["software.install","system.configure","process.list"],["toolchain","setup","developer"],{targetSupport:"single"}),ct("network-adapter-status","Network & connectivity","Check network adapters","Show adapter state, address, and link information for the current targets.",["network.status"],["adapter","ethernet","wifi","네트워크 상태"]),ct("network-disconnected","Network & connectivity","Find disconnected targets","Find current targets with disconnected or degraded network adapters.",["network.status"],["disconnected","offline","연결 끊김"]),ct("network-link-speed","Network & connectivity","Check link speed","Report network link speed and duplex information for the current targets.",["network.status"],["speed","bandwidth","duplex"]),ct("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"]),ct("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"]),ct("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"]),ct("network-compare","Network & connectivity","Compare target connectivity","Compare adapter state, addresses, and link speed across the current targets.",["network.status"],["compare","inventory","connectivity"]),ct("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"]),ct("power-lock","Power & maintenance","Lock the Client","Lock the target Client and report the resulting power action status.",["system.power"],["lock","security","잠금"],{targetSupport:"single",risk:"critical"}),ct("power-logoff","Power & maintenance","Log off the Client","Log off the target Client after warning that interactive sessions will close.",["system.power"],["logoff","session","로그오프"],{targetSupport:"single",risk:"critical"}),ct("power-sleep","Power & maintenance","Put the Client to sleep","Put the target Client to sleep after confirming the requested delay of [delay].",["system.power"],["sleep","suspend","절전"],{targetSupport:"single",risk:"critical"}),ct("power-restart","Power & maintenance","Restart the Client","Restart the target Client after confirming that active work may be interrupted.",["system.power"],["restart","reboot","재부팅"],{targetSupport:"single",risk:"critical"}),ct("power-shutdown","Power & maintenance","Shut down the Client","Shut down the target Client after confirming that active work may be interrupted.",["system.power"],["shutdown","power off","종료"],{targetSupport:"single",risk:"critical"}),ct("power-maintenance-restart","Power & maintenance","Restart after maintenance","Check the target Client, restart it after maintenance, and verify that it returns online.",["system.health","system.power","network.status"],["maintenance","reboot","verify"],{targetSupport:"single",risk:"critical"}),ct("power-timezone","Power & maintenance","Set the Client timezone","Set the target Client timezone to [timezone] and verify the resulting system configuration.",["system.configure"],["timezone","clock","시간대"],{targetSupport:"single",risk:"critical"}),ct("power-persistent-environment","Power & maintenance","Persist an environment variable","Persist environment variable [name] with value [value] for the target Client and verify it.",["system.configure"],["environment","persistent","환경변수"],{targetSupport:"single",risk:"critical"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("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"}),ct("recovery-network-instability","Troubleshooting & recovery","Recover network instability","Collect network diagnostics, inspect network services, and report the safest recovery action for the target Client.",["network.status","service.status","diagnostics.collect"],["network","unstable","네트워크 복구"],{targetSupport:"single"}),ct("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","장애 보고서"])],Dg={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 QE(t,n){return t==="safe-auto"?Dg:t==="full-access"?{...Dg,processControl:"allow",serviceControl:"allow",applicationControl:"allow",fileDelete:"allow",shell:"allow",script:"allow",softwareInstall:"allow",systemPower:"allow",systemConfiguration:"allow"}:t==="custom"&&n?n:{...Dg,processControl:"ask",serviceControl:"ask",applicationControl:"ask",fileWrite:"ask",network:"ask"}}function YE(t,n,r){const o=QE(n,r),l=t.requiredOperations.map(u=>o[Xl[u].permissionCategory]);if(l.includes("deny")){const u=t.requiredOperations.find(f=>o[Xl[f].permissionCategory]==="deny");return{state:"blocked",label:"Blocked",reason:`This task requires ${Xl[u].label}, which is blocked by the current permission policy.`}}return l.includes("ask")?{state:"approval",label:"Approval required",reason:"This task requires approval before the requested changes can reach a Client."}:t.requiredOperations.every(u=>Xl[u].readOnly)?{state:"read-only",label:"Read only"}:n==="full-access"?{state:"full-access",label:"Full Access"}:{state:"auto",label:"Auto allowed"}}function XE(t){const n=String(t||"").trim().toLowerCase();return n==="windows"||n==="win32"||n==="win32nt"?"windows":n==="macos"||n==="macosx"||n==="darwin"||n==="osx"?"macos":n==="linux"?"linux":null}function ZE(t,n,r){const o=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||o.has(l.deviceId)))}function JE(t,n){const r=XE(t.platform);if(!r||!n.supportedPlatforms.includes(r))return!1;const o=t.capabilities?.agentTools;return!Array.isArray(o)||o.length===0?n.requiredOperations.every(l=>Xl[l].readOnly):n.requiredOperations.every(l=>o.includes(l))}function PS(t,n,r,o,l,u){const f=YE(t,l,u),h=ZE(n,r,o),g=h.map(k=>k.deviceId),y={...f,available:!1,availableDeviceIds:[],unsupportedDeviceIds:g,risk:t.risk,supportedPlatforms:t.supportedPlatforms};if(h.length===0)return{...y,reason:"Select at least one connected Client."};if(t.targetSupport==="single"&&h.length!==1)return{...y,reason:"This task supports one Client at a time."};if(f.state==="blocked")return y;const w=h.filter(k=>JE(k,t)),b=w.map(k=>k.deviceId),S=g.filter(k=>!b.includes(k));return w.length===0?{...y,unsupportedDeviceIds:S,reason:"No current target supports the required platform and client capabilities."}:{...y,available:!0,availableDeviceIds:b,unsupportedDeviceIds:S}}function eD(t,n,r,o,l,u){return t.filter(f=>f.enabled&&PS(f,n,r,o,l,u).available).length}const Ig="livedesk.agentPromptRecent",Lg="livedesk.agentPromptFavorites",tD={Recommended:ec,"Health & capacity":Jl,"Processes & services":Nk,"Files & configuration":Ak,"Software & automation":Kx,"Network & connectivity":kv,"Power & maintenance":ga,"Troubleshooting & recovery":Mk};function rx(t){if(typeof window>"u")return[];try{const n=JSON.parse(window.localStorage.getItem(t)||"[]");return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}catch{return[]}}function Sp(t,n){try{window.localStorage.setItem(t,JSON.stringify(n))}catch{}}function Pg(t){return t==="all"?"All tasks":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto allowed":t==="approval"?"Approval required":t==="full-access"?"Full Access":t==="available"?"Available":t==="unavailable"?"Unavailable":t}function nD(t){return t==="all"?"All":t==="recent"?"Recent":t==="favorites"?"Favorites":t==="read-only"?"Read only":t==="auto"?"Auto":t==="approval"?"Approval":t==="full-access"?"Full access":t==="available"?"Available":t==="unavailable"?"Unavailable":{Recommended:"Recommended","Health & capacity":"Health","Processes & services":"Processes","Files & configuration":"Files","Software & automation":"Software","Network & connectivity":"Network","Power & maintenance":"Power","Troubleshooting & recovery":"Recovery"}[t]}function aD(t,n,r){if(!r.trim())return!0;const o=r.trim().toLowerCase();return[t.title,t.prompt,t.description,t.category,t.risk,n.label,...t.keywords,...t.requiredOperations,...t.supportedPlatforms].join(" ").toLowerCase().includes(o)}function rD(t){return`permission-${t}`}function sD(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function iD(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function oD({devices:t,targetMode:n,selectedIds:r,permissionMode:o,customCategories:l,onSelectPrompt:u,onClose:f}){const[h,g]=d.useState(""),[y,w]=d.useState("all"),[b,S]=d.useState(()=>rx(Ig)),[k,N]=d.useState(()=>rx(Lg)),[A,j]=d.useState(0),[I,T]=d.useState(""),_=d.useRef(null),B=d.useRef(null),F=d.useMemo(()=>LS.filter(J=>J.enabled),[]),H=d.useMemo(()=>new Map(F.map(J=>[J.id,PS(J,t,n,r,o,l)])),[l,t,o,r,n,F]),D=d.useMemo(()=>[...H.values()].filter(J=>J.available).length,[H]),K=d.useMemo(()=>t.filter(J=>J.connected&&(n==="all"||n==="auto"||r.includes(J.deviceId))).length,[t,r,n]),z=d.useMemo(()=>{const J=F.filter($=>aD($,H.get($.id),h));return y==="recent"?b.map($=>J.find(P=>P.id===$)).filter($=>!!$):y==="favorites"?k.map($=>J.find(P=>P.id===$)).filter($=>!!$):y==="all"?J:J.filter($=>{const P=H.get($.id);return y==="read-only"?P.state==="read-only":y==="auto"?P.state==="auto":y==="approval"?P.state==="approval":y==="full-access"?P.state==="full-access":y==="available"?P.available:y==="unavailable"?!P.available:$.category===y})},[H,k,y,b,h,F]),W=d.useMemo(()=>y!=="all"?[{category:Pg(y),templates:z}]:nx.map(J=>({category:J,templates:z.filter($=>$.category===J)})).filter(J=>J.templates.length>0),[y,z]);d.useEffect(()=>{j(J=>Math.min(J,Math.max(0,z.length-1)))},[z.length]),d.useEffect(()=>{Sp(Ig,b)},[b]),d.useEffect(()=>{Sp(Lg,k)},[k]),d.useEffect(()=>{B.current?.focus();const J=P=>{P.target instanceof Node&&!_.current?.contains(P.target)&&f()},$=P=>{P.key==="Escape"&&(P.preventDefault(),f())};return document.addEventListener("pointerdown",J),document.addEventListener("keydown",$),()=>{document.removeEventListener("pointerdown",J),document.removeEventListener("keydown",$)}},[f]);const q=J=>{const $=H.get(J.id);if(!$.available){T($.reason||"This task is not available for the current targets and permission policy.");return}const P=[J.id,...b.filter(se=>se!==J.id)].slice(0,10);S(P),Sp(Ig,P),u(J.prompt),f()},V=J=>{N($=>{const P=$.includes(J)?$.filter(se=>se!==J):[J,...$];return Sp(Lg,P),P})},X=J=>{J.key==="ArrowDown"?(J.preventDefault(),j($=>Math.min($+1,Math.max(0,z.length-1)))):J.key==="ArrowUp"?(J.preventDefault(),j($=>Math.max($-1,0))):J.key==="Enter"&&z[A]&&(J.preventDefault(),q(z[A]))};let ve=-1;return i.jsxs("section",{className:"agents-suggested-tasks",ref:_,"aria-label":"Suggested tasks",children:[i.jsxs("header",{className:"agents-suggested-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"agents-suggested-title",children:[i.jsx(ec,{size:15})," Suggested tasks"]}),i.jsxs("small",{children:[D," available · ",F.length," total. Choose a task, edit it, then run it."]})]}),i.jsx("button",{className:"agents-suggested-close",type:"button","aria-label":"Close suggested tasks",onClick:f,children:i.jsx(rr,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(kk,{size:15,"aria-hidden":"true"}),i.jsx("input",{ref:B,value:h,onChange:J=>g(J.target.value),onKeyDown:X,placeholder:"Search tasks...","aria-label":"Search suggested tasks"})]}),i.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",...nx].map(J=>{const $=J==="recent"?Gx:J==="favorites"?Kg:J==="all"?ec:J==="available"?_a:J==="unavailable"?Jx:J==="read-only"||J==="auto"||J==="approval"||J==="full-access"?ga:tD[J];return i.jsxs("button",{className:y===J?"active":"",type:"button",title:Pg(J),"aria-label":Pg(J),"aria-pressed":y===J,onClick:()=>{w(J),j(0),T("")},children:[i.jsx($,{size:12})," ",nD(J)]},J)})}),I&&i.jsx("div",{className:"agents-suggested-notice",role:"status",children:I}),i.jsxs("div",{className:"agents-suggested-list",role:"listbox","aria-label":"Suggested tasks",children:[W.map(J=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:J.category}),J.templates.map($=>{ve+=1;const P=ve===A,se=k.includes($.id),we=H.get($.id),Z=we.availableDeviceIds.length+we.unsupportedDeviceIds.length||K,Se=we.available?`Available on ${we.availableDeviceIds.length} of ${Z} target${Z===1?"":"s"}`:`Unavailable: ${we.reason||"not supported by the current targets"}`;return i.jsxs("div",{className:`agents-suggested-item ${P?"active":""} ${we.available?"":"unavailable"}`,children:[i.jsxs("button",{className:"agents-suggested-prompt",type:"button",role:"option","aria-selected":P,"aria-disabled":!we.available,onClick:()=>q($),children:[i.jsx("span",{children:$.title}),i.jsx("small",{className:"agents-suggested-description",children:$.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:$.category}),i.jsx("em",{className:rD(we.state),children:we.label}),i.jsx("em",{className:`risk-${$.risk}`,children:sD($.risk)}),i.jsx("em",{children:$.supportedPlatforms.map(iD).join(" · ")}),i.jsx("em",{className:we.available?"availability-ok":"availability-unavailable",children:Se}),we.available&&we.unsupportedDeviceIds.length>0&&i.jsxs("em",{className:"availability-warning",children:["Unsupported on ",we.unsupportedDeviceIds.length]})]})]}),i.jsx("button",{className:`agents-suggested-favorite ${se?"favorite":""}`,type:"button","aria-label":se?`Remove ${$.title} from favorites`:`Add ${$.title} to favorites`,"aria-pressed":se,onClick:()=>V($.id),children:i.jsx(Kg,{size:14,fill:se?"currentColor":"none"})})]},$.id)})]},J.category)),z.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function lD({devices:t,mode:n,selectedIds:r,onModeChange:o,onToggle:l,permissionMode:u,onPermissionModeChange:f}){const h=t.filter(Zp),g=r.filter(y=>h.some(w=>w.deviceId===y)).length;return i.jsxs("section",{className:"agents-target-picker","aria-label":"Agent targets",children:[i.jsxs("div",{className:"agents-target-toolbar",children:[i.jsx("span",{className:"agents-section-label",children:"Targets"}),i.jsxs("div",{className:"agents-target-modes",children:[i.jsxs("button",{className:n==="all"?"active":"",onClick:()=>o("all"),type:"button",children:[i.jsx(nm,{size:14})," All connected ",i.jsx("small",{children:h.length})]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(al,{size:14})," Selected ",g]}),i.jsxs("button",{className:n==="auto"?"active":"",onClick:()=>o("auto"),type:"button",children:[i.jsx(ec,{size:14})," Auto"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(nm,{size:14})," Group ",i.jsx("small",{children:"Soon"})]})]}),i.jsxs("label",{className:`agents-permission-picker permission-${u}`,children:[i.jsx(th,{size:14}),i.jsx("span",{children:"Permission"}),i.jsxs("select",{value:u,onChange:y=>f(y.target.value),"aria-label":"Agent permission mode",children:[i.jsx("option",{value:"ask",children:"Ask"}),i.jsx("option",{value:"safe-auto",children:"Safe Auto"}),i.jsx("option",{value:"full-access",children:"Full Access"}),i.jsx("option",{value:"custom",children:"Custom"})]}),i.jsx(Zx,{size:13,"aria-hidden":"true"})]})]}),i.jsx("div",{className:"agents-target-list",children:t.length===0?i.jsx("span",{className:"agents-target-empty",children:"No Clients discovered."}):t.map(y=>{const w=Zp(y),b=n==="all"||n==="auto"?w:r.includes(y.deviceId);return i.jsxs("label",{className:`agents-target-option ${b?"selected":""} ${w?"":"offline"}`,children:[i.jsx("input",{type:"checkbox",checked:b,disabled:!w||n!=="selected",onChange:()=>l(y.deviceId)}),i.jsx("span",{className:"agents-target-icon",children:i.jsx(Ar,{size:15})}),i.jsxs("span",{children:[i.jsx("strong",{children:Xp(y)}),i.jsx("small",{children:w?"Ready":y.connected?"Agent reconnecting":"Offline"})]}),b&&i.jsx(al,{className:"agents-target-check",size:15,"aria-hidden":"true"})]},y.deviceId)})})]})}const cD=800,sx=5e3;function uD(){return typeof document>"u"||document.visibilityState==="visible"}function dD(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function ix({poll:t,onResult:n,onError:r,intervalMs:o=cD,isVisible:l=uD,subscribeVisibility:u=dD,setTimeoutImpl:f=globalThis.setTimeout.bind(globalThis),clearTimeoutImpl:h=globalThis.clearTimeout.bind(globalThis),createAbortController:g=()=>new AbortController}){if(typeof t!="function")throw new TypeError("Agent polling requires a poll function.");const y={current:null};let w=!0,b=0,S=null,k=null;const N=()=>{S!==null&&(h(S),S=null)},A=()=>{!w||!l()||S!==null||y.current||(S=f(()=>{S=null,j()},o))},j=()=>{if(!w||!l()||y.current)return y.current;const B=++b,F=g();k=F;const H=Up(y,()=>t(F.signal));return H.then(D=>{w&&B===b&&!F.signal.aborted&&n?.(D)},D=>{w&&B===b&&!F.signal.aborted&&r?.(D)}).finally(()=>{k===F&&(k=null),w&&l()&&A()}).catch(()=>{}),H},I=async()=>{if(!w)throw new Error("LiveDesk Agent polling owner is closed.");N(),b+=1;const B=y.current;if(k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling was superseded by an explicit refresh.")),B)try{await B}catch{}if(!(!w||!l()))return N(),j()},_=u(()=>{if(N(),!l()){b+=1,k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling paused while hidden."));return}j()});return j(),{refresh:I,stop(){w&&(w=!1,b+=1,N(),_?.(),k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function fD(t,n){return rt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function mD(t,n,r={}){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function pD(t,n){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function hD(t){return rt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function gD(t,n,r,o){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/approve`,{method:"POST",body:JSON.stringify({scope:o})},t)}async function vD(t,n,r,o="User rejected this action."){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/approvals/${encodeURIComponent(r)}/reject`,{method:"POST",body:JSON.stringify({reason:o})},t)}async function yD(t,n,r){return rt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function bD(t,n,r={}){return rt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function wD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function xD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function Of(t){return`${t}-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}function _g(t,n){const r=new Map(n.map(o=>[o.deviceId,Xp(o)]));return t.results.map(o=>({deviceId:o.deviceId,deviceName:o.deviceName||r.get(o.deviceId)||o.deviceId,status:_E(o.status),stage:o.stage||(o.status==="running"?"Checking processes":void 0),result:o.result,data:o.data,error:o.error,sequence:Number.isSafeInteger(o.sequence)?o.sequence:0}))}function SD(t,n){const r=new Map(n.map(o=>[o.deviceId,o]));return t.map(o=>{const l=r.get(o.deviceId);return!l||l.sequence<=o.sequence?o:l})}const CD={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 kD(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function MD(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function AD(t){const n=t instanceof Error?t.message:String(t);return/agent-disabled/i.test(n)?"Enable Codex Agent in Settings before running commands.":/agent-no-target-devices|agent-target-not-connected|device-not-connected/i.test(n)?"The selected Client is reconnecting. Wait until its Agent status is Ready and try again.":/codex-auth-required/i.test(n)?"Codex sign-in is required on the Hub. Open Settings > Agent and test the Codex connection.":n}function ox({hubUrl:t,devices:n,launchRequest:r,variant:o="page",selectedDeviceIds:l=[]}){const u=o==="dock",[f,h]=d.useState(u?l.length>0?"selected":"auto":"all"),[g,y]=d.useState(l),[w,b]=d.useState("auto"),[S,k]=d.useState(""),[N,A]=d.useState([]),[j,I]=d.useState(""),[T,_]=d.useState(""),[B,F]=d.useState(""),[H,D]=d.useState("safe-auto"),[K]=d.useState("custom-default"),[z,W]=d.useState(CD),[q,V]=d.useState([]),[X,ve]=d.useState(""),[J,$]=d.useState(!1),[P,se]=d.useState(null),[we,Z]=d.useState(!1),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(!1),[de,Qe]=d.useState(null),ue=d.useRef(null),_e=d.useRef(null),Ze=d.useRef(null),at=d.useRef(new Set),Ee=d.useRef(new Set),Ge=d.useMemo(()=>n.filter(Zp).map(fe=>fe.deviceId),[n]),me=d.useMemo(()=>eD(LS,n,f,g,H,z),[z,n,H,g,f]);d.useEffect(()=>{u&&y(l)},[u,l]),d.useEffect(()=>{r?.deviceId&&(h("selected"),y([r.deviceId]),k(r.instruction),Pe(!1),window.requestAnimationFrame(()=>{ue.current?.focus(),ue.current?.setSelectionRange(r.instruction.length,r.instruction.length)}))},[r]);const ke=d.useCallback(fe=>{const te=_g(fe,n);A(ce=>ce.map(Ne=>Ne.type==="task"&&Ne.batchId===fe.batchId?{...Ne,states:SD(Ne.states,te),status:fe.status}:Ne)),["running","queued"].includes(fe.status)||I(ce=>ce===fe.batchId?"":ce)},[n]),et=d.useCallback((fe,te)=>{Ee.current.has(fe.batchId)||(Ee.current.add(fe.batchId),A(ce=>[...ce,{type:"task",id:Of("task"),batchId:fe.batchId,agentRunId:te,operation:fe.operation||"diagnostics.collect",instruction:fe.instructionPreview,states:_g(fe,n),status:fe.status}])),ke(fe)},[n,ke]),Me=d.useCallback((fe,te)=>{for(const Ne of te.taskBatches||[])et(Ne,fe);V(te.approvals||[]);const ce=["running","queued","waiting-approval"].includes(te.status);if(Qe(ce?{runId:fe,stage:te.stage||te.status,message:te.progressMessage||(te.status==="waiting-approval"?"Review the requested action to continue.":"Codex is preparing the answer.")}:Ne=>Ne?.runId===fe?null:Ne),!ce&&!at.current.has(fe)){at.current.add(fe);const Ne=[te.error,te.errorMessage].filter(Boolean).join(" — "),He=te.finalResponse?.trim()||(te.status==="cancelled"?"Codex 작업을 취소했습니다.":Ne?`Codex 작업이 완료되지 않았습니다: ${Ne}`:"Codex 작업이 완료되었습니다.");A(Ie=>[...Ie,{type:te.status==="failed"?"error":"agent",id:Of("agent-run-result"),text:He}])}},[et]),pe=d.useCallback(async fe=>{const te=_e.current;if(!(!te||te.id!==fe))try{return await te.owner.refresh()}catch(ce){if(_e.current!==te)return;throw ce}},[]);d.useEffect(()=>{if(!T){_e.current=null;return}const fe=T,te=ix({poll:Ne=>mD(t,fe,{signal:Ne,timeoutMs:sx}),onResult:Ne=>{Me(fe,Ne),["running","queued","waiting-approval"].includes(Ne.status)||(_(He=>He===fe?"":He),Z(!1))},onError:Ne=>{ae(Ne instanceof Error?Ne.message:String(Ne))}}),ce={id:fe,owner:te};return _e.current=ce,()=>{te.stop(),_e.current===ce&&(_e.current=null)}},[T,t,Me]),d.useEffect(()=>{if(!j){Ze.current=null;return}const fe=j,te=ix({poll:Ne=>bD(t,fe,{signal:Ne,timeoutMs:sx}),onResult:Ne=>{ke(Ne),["running","queued"].includes(Ne.status)||I(He=>He===fe?"":He)},onError:Ne=>{ae(Ne instanceof Error?Ne.message:String(Ne))}}),ce={id:fe,owner:te};return Ze.current=ce,()=>{te.stop(),Ze.current===ce&&(Ze.current=null)}},[j,t,ke]);const qe=async(fe="",te,ce=!1)=>{const Ne=(fe||S).trim();if(!Ne||j||T)return;const He=te||(f==="all"||f==="auto"?Ge:g.filter(ut=>Ge.includes(ut)));if(He.length===0){ae("Select at least one connected Client.");return}if(H==="full-access"&&!we&&!ce){se({instruction:Ne,targetIds:He});return}if(A(ut=>[...ut,{type:"user",id:Of("user"),text:Ne}]),k(""),Pe(!1),ae(""),He.length===0){A(ut=>[...ut,{type:"error",id:Of("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Lt=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
|
|
180
180
|
|
|
181
181
|
${Ne}`:w==="plan"?`Plan only. Produce a safe execution plan, but do not change Client state.
|
|
182
182
|
|
|
@@ -184,5 +184,5 @@ ${Ne}`:w==="execute"?`Execute this request within the configured LiveDesk approv
|
|
|
184
184
|
|
|
185
185
|
${Ne}`:Ne,Xe=f==="auto"?`Auto target selection is enabled. Inspect the allowed Clients and use only the most suitable target or targets for this request.
|
|
186
186
|
|
|
187
|
-
${Lt}`:Lt;try{if(H==="custom"){const yt=await vD(t,K,z);if(!yt.ok)throw new Error(yt.error||"Custom Agent policy could not be saved.")}const ut=await dD(t,{instruction:Xe,deviceIds:He,permissionMode:H,customPolicyId:K});if(!ut.ok||!ut.runId)throw new Error(ut.error||"Codex Agent run could not be started.");V(ut.approvals||[]),Qe({runId:ut.runId,stage:ut.stage||ut.status||"queued",message:ut.progressMessage||"Codex request queued on the Hub."}),_(ut.runId)}catch(ut){A(yt=>[...yt,{type:"error",id:Of("codex-run-error"),text:MD(ut)}])}},Re=async(fe,te)=>{ve(fe.approvalId);try{const ce=await hD(t,fe.runId,fe.approvalId,te);if(!ce.ok)throw new Error(ce.error||"Agent approval could not be applied.");await pe(fe.runId)}catch(ce){ae(ce instanceof Error?ce.message:String(ce))}finally{ve("")}},st=async fe=>{ve(fe.approvalId);try{const te=await gD(t,fe.runId,fe.approvalId);if(!te.ok)throw new Error(te.error||"Agent approval could not be rejected.");await pe(fe.runId)}catch(te){ae(te instanceof Error?te.message:String(te))}finally{ve("")}},jt=async(fe,te)=>{F(fe);try{if(te){const Ne=await mD(t,te);for(const He of Ne.taskBatches||[])ke(He);_(He=>He===te?"":He),Qe(He=>He?.runId===te?null:He);return}const ce=await bD(t,fe);ke(ce),I(Ne=>Ne===fe?"":Ne)}catch(ce){ae(ce instanceof Error?ce.message:String(ce))}finally{F("")}},O=async()=>{if(!(J||!j&&!T)){$(!0);try{const fe=await pD(t);if(!fe.ok)throw new Error(fe.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),_(""),Qe(null),V([]),A(te=>te.map(ce=>ce.type==="task"&&["queued","running"].includes(ce.status)?{...ce,status:"cancelled",states:ce.states.map(Ne=>["queued","running"].includes(Ne.status)?{...Ne,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ne)}:ce))}catch(fe){ae(fe instanceof Error?fe.message:String(fe))}finally{$(!1)}}},ze=async fe=>{F(fe);try{const te=await wD(t,fe);if(!te.ok||!te.batch||!te.batchId)throw new Error(te.error||"재시도하지 못했습니다.");A(ce=>ce.map(Ne=>Ne.type==="task"&&Ne.batchId===fe?{...Ne,batchId:te.batchId,states:_g(te.batch,n),status:te.batch.status}:Ne)),I(te.batchId)}catch(te){ae(te instanceof Error?te.message:String(te))}finally{F("")}},We=fe=>{k(fe),Pe(!1),window.requestAnimationFrame(()=>ue.current?.focus())},Et=d.useMemo(()=>n.filter(Zp),[n]),lt=d.useMemo(()=>Et.filter(fe=>g.includes(fe.deviceId)),[Et,g]),ht=f==="auto"?`Auto · ${Et.length} available`:f==="all"?`All ${Et.length} computers`:lt.length===1?Xp(lt[0]):`${lt.length} selected`,Je=f==="auto"?"LiveDesk chooses the best computer for each task.":f==="all"?"The Agent may coordinate every connected computer.":lt.length>0?lt.map(Xp).join(" · "):"Select one or more computers on the Wall.",be=f==="selected"&<.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:f==="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"],je=f==="selected"?lt.length>0?"What should this computer do?":"Choose a computer or use Auto.":f==="all"?"Use all your computers together.":"What should LiveDesk handle?",Ae=f==="auto"?"The Hub Codex Agent can inspect the available computers and choose the best target.":"Describe the outcome. The Hub Codex Agent will plan approved commands and show progress per computer.";return i.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&i.jsxs("header",{className:"agent-console-header",children:[i.jsxs("div",{className:"agent-console-title",children:[i.jsx("span",{className:"agent-console-mark",children:i.jsx(ec,{size:16})}),i.jsxs("div",{children:[i.jsx("small",{children:"Hub Codex Agent"}),i.jsx("strong",{children:"Command Console"})]}),i.jsx("i",{children:"Ready"})]}),i.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:ht}),i.jsx("small",{children:Je})]}),i.jsxs("div",{className:"agent-console-target-modes",children:[i.jsxs("button",{className:f==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[i.jsx(al,{size:12})," Selected"]}),i.jsxs("button",{className:f==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[i.jsx(nm,{size:12})," All"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(nm,{size:12})," Group"]}),i.jsxs("button",{className:f==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[i.jsx(ec,{size:12})," Auto"]})]})]}),i.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(fe=>i.jsxs("button",{className:w===fe?"active":"",onClick:()=>b(fe),type:"button",children:[fe==="auto"?i.jsx(ec,{size:12}):fe==="execute"?i.jsx(Ar,{size:12}):null,fe[0].toUpperCase()+fe.slice(1)]},fe))})]}),i.jsxs("div",{className:"agents-workspace",children:[(j||T)&&i.jsxs("div",{className:"agents-page-status",children:[i.jsxs("span",{children:[Ge.length," Clients · ",CD(H)]}),i.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{O()},disabled:J,children:J?"Stopping…":"Stop all"})]}),P&&i.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:i.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[i.jsx("span",{className:"agents-permission-modal-icon",children:i.jsx(th,{size:20})}),i.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),i.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),i.jsxs("div",{className:"agents-permission-modal-actions",children:[i.jsx("button",{type:"button",onClick:()=>se(null),children:"Cancel"}),i.jsx("button",{type:"button",className:"danger",onClick:()=>{const fe=P;se(null),Z(!0),qe(fe.instruction,fe.targetIds,!0)},children:"Run with Full Access"})]})]})}),Se&&i.jsx("div",{className:"agents-error",role:"alert",children:Se}),i.jsx(qE,{items:N,onCancel:jt,onRetry:ze,busyBatchId:B,approvals:q,onApprove:Re,onReject:st,busyApprovalId:X,progress:de,emptyTitle:u?je:void 0,emptyBody:u?Ae:void 0}),u&&N.length===0&&!de&&i.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:be.map(fe=>i.jsx("button",{type:"button",onClick:()=>We(fe),children:fe},fe))}),i.jsxs("div",{className:"agents-composer-shell",children:[ye&&i.jsx(iD,{devices:n,targetMode:f,selectedIds:g,permissionMode:H,customCategories:z,onSelectPrompt:We,onClose:()=>Pe(!1)}),i.jsx(IE,{ref:ue,value:S,onChange:k,onSubmit:()=>{qe()},onOpenSuggestedTasks:()=>Pe(fe=>!fe),suggestedOpen:ye,suggestedTaskCount:me,disabled:!!j||!!T,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&i.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[i.jsx(oD,{devices:n,mode:f,selectedIds:g,onModeChange:h,onToggle:fe=>y(te=>te.includes(fe)?te.filter(ce=>ce!==fe):[...te,fe]),permissionMode:H,onPermissionModeChange:fe=>{D(fe),fe!=="full-access"&&Z(!1)}}),H==="custom"&&i.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[i.jsxs("div",{className:"agents-custom-policy-head",children:[i.jsxs("div",{children:[i.jsx("span",{className:"agents-section-label",children:"Custom policy"}),i.jsx("strong",{children:"Choose what Codex may do automatically."})]}),i.jsx("span",{children:"Denied actions never reach a device."})]}),i.jsx("div",{className:"agents-custom-policy-grid",children:LE.map(fe=>i.jsxs("label",{children:[i.jsx("span",{children:kD(fe)}),i.jsxs("select",{value:z[fe],onChange:te=>W(ce=>({...ce,[fe]:te.target.value})),children:[i.jsx("option",{value:"allow",children:"Allow automatically"}),i.jsx("option",{value:"ask",children:"Ask every time"}),i.jsx("option",{value:"deny",children:"Deny"})]})]},fe))})]})]})]})}function _S(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function FS(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function OS(t,n,r){const o=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:_S(n.target)})),l=await Nv(`/api/captures?metadata=${o}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t},r);if(!l.ok)throw new Error(await FS(l));return await l.json()}async function AD(t,n){return await rt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:_S(t.target)})},n)}async function ND(t,n,r,o){const l=await Nv(`/api/capture-sessions/${encodeURIComponent(t)}/chunks/${n}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r},o);if(!l.ok)throw new Error(await FS(l));return await l.json()}async function TD(t,n,r){return await rt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function lx(t,n){await rt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function RD(t){return await rt("/api/captures",void 0,t)}function cx(t,n){return`${cu(n)}/api/captures/${encodeURIComponent(t)}/content`}async function jD(t,n){return await rt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function ED({hubUrl:t,onToast:n}){const[r,o]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{o((await RD(t)).captures||[])}catch(g){n(g instanceof Error?g.message:String(g))}finally{u(!1)}},[t,n]);d.useEffect(()=>{f()},[f]);const h=async g=>{const y=cx(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return i.jsxs("section",{className:"capture-gallery",children:[i.jsxs("header",{children:[i.jsxs("div",{children:[i.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),i.jsx("h2",{children:"Saved captures"})]}),i.jsxs("button",{className:"text-button",onClick:()=>{f()},type:"button",children:[i.jsx(ou,{size:15})," Refresh"]})]}),l?i.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?i.jsx("p",{className:"settings-help",children:"No captures saved yet."}):i.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const y=cx(g.id,t);return i.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?i.jsx("img",{src:y,alt:g.target.label}):i.jsx("video",{src:y,controls:!0,preload:"metadata"}),i.jsxs("div",{className:"capture-gallery-card-body",children:[i.jsx("strong",{children:g.fileName}),i.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),i.jsxs("div",{children:[i.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:i.jsx(Tk,{size:15})}),i.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:i.jsx(Bp,{size:15})}),i.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:i.jsx(e0,{size:15})}),i.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&jD(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:i.jsx(Yx,{size:15})})]})]})]},g.id)})})]})}function Cp(t){if(!t)return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(n/3600),o=Math.floor(n%3600/60),l=n%60;return r>0?`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}:${String(l).padStart(2,"0")}`:`${String(o).padStart(2,"0")}:${String(l).padStart(2,"0")}`}function ux({controller:t,compact:n=!1,onFirstRollingUse:r,onError:o}){const{state:l,settings:u,videoSupported:f}=t,h=async b=>{try{await b()}catch(S){o?.(S instanceof Error?S.message:String(S))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
188
|
-
Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=l.recording?`Stop recording · ${Cp(l.recordingStartedAt)}`:`Start recording · ${l.targetLabel}`,w=l.timelapse?`Stop timelapse · ${Cp(l.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return i.jsxs("div",{className:`capture-toolbar ${n?"compact":""} ${l.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[i.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${l.targetLabel}`,title:`Take screenshot · ${l.targetLabel}`,disabled:l.busy,onClick:()=>{h(t.takeScreenshot)},type:"button",children:i.jsx(Rk,{size:17})}),i.jsx("button",{className:`capture-action ${l.recording?"active":""}`,"aria-label":y,title:y,disabled:!f||l.busy||l.timelapse,onClick:()=>{h(l.recording?t.stopRecording:t.startRecording)},type:"button",children:l.recording?i.jsxs(i.Fragment,{children:[i.jsx(xb,{size:14,fill:"currentColor"}),i.jsx("span",{children:Cp(l.recordingStartedAt)})]}):i.jsx(Xx,{size:18})}),i.jsxs("button",{className:"capture-action","aria-label":l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!f||l.recording||l.timelapse||l.busy||l.bufferEnabled&&l.bufferSeconds<1,onClick:()=>l.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[i.jsx(jk,{size:17}),i.jsx("small",{children:"30s"})]}),i.jsx("button",{className:`capture-action ${l.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!f||l.busy||l.recording,onClick:()=>{h(l.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:l.timelapse?i.jsxs(i.Fragment,{children:[i.jsx(xb,{size:14,fill:"currentColor"}),i.jsx("span",{children:Cp(l.timelapseStartedAt)})]}):i.jsx(Ek,{size:17})})]})}function BS({state:t}){return t==="ok"?i.jsx(_a,{size:15,"aria-hidden":"true"}):i.jsx(Jx,{size:15,"aria-hidden":"true"})}function dx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button ${t?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Dk,{size:18,"aria-hidden":"true"})})}function fx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button debug-status-button ${t?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Ux,{size:18,"aria-hidden":"true"})})}function mx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button hub-status-button ${t?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(mo,{size:18,"aria-hidden":"true"})})}function HS({items:t,mode:n="remote"}){return i.jsx("span",{className:`remote-status-lines mode-${n}`,role:"status","aria-label":n==="debug"?"Debug status":"Remote status",children:t.map(r=>i.jsxs("span",{className:`remote-status-line state-${r.state}`,title:r.detail,children:[i.jsx(BS,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))})}function DD({items:t,collectedAt:n,onClose:r}){return i.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[i.jsxs("header",{children:[i.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:i.jsx(mo,{size:19})}),i.jsxs("span",{children:[i.jsx("small",{children:"Hub measurements"}),i.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),i.jsx("button",{type:"button",onClick:r,title:"Close Hub status","aria-label":"Close Hub status",children:i.jsx(rr,{size:17})})]}),i.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),i.jsx("div",{className:"remote-status-dialog-list",children:t.map(o=>i.jsxs("article",{className:`remote-status-dialog-row state-${o.state}`,children:[i.jsx(BS,{state:o.state}),i.jsxs("span",{children:[i.jsx("strong",{children:o.label}),i.jsx("small",{children:o.detail})]})]},o.id))}),i.jsxs("footer",{children:["Checked ",new Date(n).toLocaleTimeString()]})]})}const ID=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,LD=/(libx264|openh264|software|cpu)/i,xv=2,PD=256,Qc=new Map,It=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,nativeTelemetryStaleMs:3e3,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,runtimeProcessCpuWarningRatio:.65,runtimeProcessMemoryWarningBytes:1.5*1024**3,captureHelperCpuWarningRatio:.55,captureHelperMemoryWarningBytes:1024**3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function mn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Jv(t,n){let r=t;for(const o of String(n).split(".")){if(!r||typeof r!="object")return;r=r[o]}return r}function Mt(t,...n){for(const r of n){const o=Jv(t,r);if(o==null||o==="")continue;const l=Number(o);if(Number.isFinite(l))return l}}function zt(t,...n){for(const r of n){const o=Jv(t,r);if(typeof o=="string"&&o.trim())return o.trim()}return""}function zS(t,...n){for(const r of n){const o=Jv(t,r);if(typeof o=="boolean")return o;if(o===1||o==="1"||String(o).toLowerCase()==="true")return!0;if(o===0||o==="0"||String(o).toLowerCase()==="false")return!1}}function Ci(t,...n){const r=Mt(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Ye(t,n,r,o){return{id:t,state:n,label:r,detail:o}}function $S(t){const n=mn(t),r=Mt(n,"helperCount"),o=Mt(n,"helperOwnedIoTaskCount"),l=Mt(n,"helperUndisposedProcessCount"),u=Mt(n,"helperOwnedExitObserverCount"),f=Mt(n,"helperQuarantineCount"),h=Mt(n,"utilityQuarantineCount"),g=Mt(n,"utilityOwnedIoTaskCount"),y=Mt(n,"utilityUndisposedProcessCount"),w=Number(Mt(n,"helperDisposeFailureCount")||0),b=Number(Mt(n,"utilityDisposeFailureCount")||0),S=Math.max(0,Number(r||0)),k=Number(o||0),N=Number(l||0),A=Number(u||0),j=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),T=Number(g||0),_=Number(y||0),B=[o,l,u,f,h,g,y].every(D=>D!==void 0),F=B&&(k<0||N<0||A<0||N!==S||A!==0||S===0&&k!==0||S>0&&k===0),H=B&&(T<0||_<0||_!==I||T!==I*2);return{telemetryAvailable:B,helperOwnedIoTaskCount:k,helperUndisposedProcessCount:N,helperOwnedExitObserverCount:A,helperQuarantineCount:j,helperDisposeFailureCount:w,helperLastDisposeFailure:zt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:T,utilityUndisposedProcessCount:_,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(D=>Number(D)).filter(D=>Number.isSafeInteger(D)&&D>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(D=>String(D||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(Mt(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(Mt(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:zt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:H,historicalCleanupFailure:w!==0||b!==0,currentProblem:j>0||I>0||F||H}}function US({key:t,sampleId:n,mismatch:r}){if(!t)return{count:0,confirmed:!1};if(!r)return Qc.delete(t),{count:0,confirmed:!1};const o=String(n||"").trim();if(!o)return{count:0,confirmed:!1};const l=em(o),u=Qc.get(t);if(u?.sampleId===o)return{count:u.count,confirmed:u.count>=xv};const f=u&&l!==void 0&&u.sampleEpochMs!==void 0&&l>u.sampleEpochMs,h=u&&f?u.count+1:1;return!Qc.has(t)&&Qc.size>=PD&&Qc.delete(Qc.keys().next().value),Qc.set(t,{sampleId:o,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=xv}}function em(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function px(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function Gl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)/1024**2).toFixed(0)} MB`:"-"}function Vl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)*100).toFixed(1)}%`:"-"}function kp(t){const n=Number(t);return Number.isFinite(n)?`${Math.max(0,n).toFixed(1)}%`:"-"}function _D(t){const n=String(t||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!n||n==="::1"||n==="localhost"||n==="127.0.0.1"||/^10\./.test(n)||/^192\.168\./.test(n))return!0;const r=n.match(/^172\.(\d{1,3})\./);return!!r&&Number(r[1])>=16&&Number(r[1])<=31||n.startsWith("fe80:")||n.startsWith("fc")||n.startsWith("fd")}function qS(t){const n=mn(t),r=zt(n,"controlTransport").toLowerCase();return r==="encrypted-rendezvous-relay"||/relay/.test(r)?"encrypted-rendezvous-relay":r==="direct-tcp"||/direct|tcp/.test(r)?"direct-tcp":""}function hx(t){const n=String(t||"").trim();if(!n)return"";try{return new URL(n.includes("://")?n:`relay://${n}`).host}catch{return n.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function FD(t){const n=qS(t);return n==="encrypted-rendezvous-relay"?Ye("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Ye("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Ye("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function OD(t,n){const r=mn(t),o=mn(n),l=qS(r);if(l==="encrypted-rendezvous-relay"){const u=zt(o,"state")||(o.connected===!0?"registered":"unknown"),f=hx(zt(o,"endpoint"))||hx(zt(r,"relayEndpoint")),h=r.connected!==!0||o.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Ye("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${f||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(o.reconnectCount||0))}`,`handshake ${Math.max(0,Number(o.handshakeCount||0))}`,`peers ${Math.max(0,Number(o.peerCount||0))}`,zt(o,"lastError")].filter(Boolean).join(" · "))}if(l==="direct-tcp"){const u=zt(r,"remoteAddress"),f=Mt(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Ye("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${zt(r,"protocol")||"-"} v${Mt(r,"protocolVersion")??"-"} · input ${mn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Ye("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function WS(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function GS(t,n,r){const o=mn(n?.frameTransport),l=zt(t,"frameTransportChangedAt"),u=zt(o,"changedAt"),f=em(l),h=em(u),g=h!==void 0&&(f===void 0||h>f),y=g?o:t,w=g?t:o,b=zt(t,"transport").toLowerCase(),S=zt(y,g?"active":"frameTransportActive")||zt(w,g?"frameTransportActive":"active"),k=zt(y,g?"protocol":"frameTransportProtocol")||zt(w,g?"frameTransportProtocol":"protocol"),A=(g?zt(o,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")||zt(t,"videoTransport"):zt(t,"videoTransport")||zt(o,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")).toLowerCase(),j=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(A)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),T=/relay/.test(A)||/relay/.test(b)?"encrypted-relay":/p2p|udp/.test(A)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(A)||b==="binary"||j?j?"direct-ws":"direct-tcp":"",_=(zt(y,g?"state":"frameTransportState")||zt(w,g?"frameTransportState":"state")||(T?"active":"")).toLowerCase(),B=zt(y,g?"reason":"frameTransportReason")||zt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,H=em(F),D=H===void 0?void 0:Math.max(0,r-H),K=D===void 0?"":D<1e3?"changed now":D<6e4?`changed ${Math.round(D/1e3)}s ago`:D<36e5?`changed ${Math.round(D/6e4)}m ago`:`changed ${F}`,z=g?o.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??o.switchCount,W=g?o.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??o.tcpFailureCount,q=g?typeof o.p2pReady=="boolean"?o.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:o.p2pReady===!0;return{rawTransport:b,videoTransport:T,state:_,reason:B,changedAt:F,changedLabel:K,switchCount:Math.max(0,Number(z??0)||0),tcpFailureCount:Math.max(0,Number(W??0)||0),p2pReady:q}}function BD(t,n,r){const o=GS(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(o.state);if(o.videoTransport==="encrypted-relay")return Ye("transport",l?"warning":"ok",l?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",l?`End-to-end encrypted TCP relay is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="p2p-udp")return Ye("transport",l?"warning":"ok",l?"P2P video connection needs attention":"P2P video connection",l?`Encrypted UDP P2P is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="direct-tcp"||o.videoTransport==="direct-ws"){const u=o.videoTransport==="direct-ws"?"WebSocket":"TCP";return Ye("transport",l?"warning":"ok",l?"Direct video connection needs attention":"Direct video connection",l?`Direct ${u} to Hub is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Direct ${u} to Hub is active${o.changedLabel?` · ${o.changedLabel}`:""}.`)}return Ye("transport","warning","Video transport is not identified",o.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const HD=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function VS(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),o=Number(t?.nativeCaptureTelemetryVersion)>=5&&HD.every(u=>Mt(t,u)!==void 0)&&typeof t?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t?.nativeCopyTelemetryAvailable===!0,l=t?.nativeCaptureTelemetryAvailable===!0&&t?.nativeCaptureResourceTelemetryAvailable===!0&&o;return{required:r,available:l,pending:Math.max(0,Number(t?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(t?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(t?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(t?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(t?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(t?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(t?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(t?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(t?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(t?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(t?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(t?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(t?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(t?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(t?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(t?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(t?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(t?.pipePayloadCopiedBytes||0))}}function zD(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),o=zS(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||o!==void 0,u=VS(t);return!t||!/h264/.test(n)?Ye("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Ye("encoder","warning","H.264 encoder resource status is unavailable",`${r||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):u.required&&(u.vtActive!==1||u.vtHighWatermark>1||u.timestampOwners>2||u.timestampOwnerHighWatermark>2)?Ye("encoder","warning","VideoToolbox encoder ownership needs attention",`${u.vtActive} active session(s); high-water ${u.vtHighWatermark}; timestamp owners ${u.timestampOwners}/2 (HWM ${u.timestampOwnerHighWatermark})`):u.required&&u.coalesced>0?Ye("encoder","warning","Hardware H.264 encoding is under load",`${u.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):l&&o===!1?Ye("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&o===!0?Ye("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):ID.test(r)?Ye("encoder","ok","Hardware H.264 encoding",r):LD.test(r)?Ye("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Ye("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function $D({device:t,frame:n,receiveStat:r,paintStat:o,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:w=!1,capturePauseConfirmed:b=!0,capturePauseError:S="",clientHeartbeatMs:k=5e3,now:N=Date.now()}={}){const A=mn(t),j=mn(A.status),I=mn(o?.lastInfo),T=[],_=WS(n,N);T.push(FD(A)),T.push(w?b?Ye("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Ye("connection","warning","Video stop needs attention",String(S||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):A.connected===!0&&_<=It.frameAgeWarningMs?Ye("connection","ok","Video connection is current",`${Math.round(_)}ms since the latest frame.`):Ye("connection","warning",A.connected===!0?"Video frame is stale":"Client is offline",A.connected===!0&&Number.isFinite(_)?`${Math.round(_)}ms since the latest frame.`:String(A.lastDisconnectReason||"No current Client session."))),T.push(BD(n,j,N)),T.push(zD(n));const B=$S(j.capture),F=mn(j.capture),H=US({key:`${String(A.deviceId||A.id||"")}:capture-cleanup`,sampleId:zt(F,"sampledAt"),mismatch:B.helperLedgerMismatch||B.utilityLedgerMismatch});(B.helperQuarantineCount>0||B.utilityQuarantineCount>0||H.confirmed)&&T.push(Ye("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${B.helperQuarantineCount} · utility quarantine ${B.utilityQuarantineCount} · owned I/O ${B.helperOwnedIoTaskCount+B.utilityOwnedIoTaskCount} · exit observers ${B.helperOwnedExitObserverCount} · undisposed processes ${B.helperUndisposedProcessCount+B.utilityUndisposedProcessCount}`));const D=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),K=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const z=Math.max(0,Number(n?.nativeCaptureFps||0)),W=Math.max(0,Number(n?.nativeEncodedFps||0)),q=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),V=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),X=Mt(n,"nativeCaptureTelemetryAgeMs"),J=Math.max(0,Number(X||0))+(Number.isFinite(_)?_:0),$=V<2||X!==void 0&&J<=It.nativeTelemetryStaleMs,P=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),se=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),we=n?.nativeCaptureTelemetryAvailable===!0&&q>0&&$,Z=Mt(n,"captureP95Ms","captureAverageMs","captureStageMs"),Se=Math.max(0,Number(Z||0)),ae=n?.captureTimingAvailable===!0&&D>0&&Number(r?.sampleMs||0)>0&&Z!==void 0,ye=ae||we,Pe=Math.max(It.minimumCaptureBudgetMs,D>0?1e3/D*It.captureBudgetMultiplier:0),de=D>0?1e3/D:100,Qe=D>0&&z>=D*It.receiveRatioWarning,ue=W>0&&W<D*It.receiveRatioWarning,_e=we&&Qe&&ue&&W>=1&&se>=Math.max(10,z*.6)&&P===0,Ze=we&&D>0&&(z<D*It.receiveRatioWarning||!_e&&W>0&&W<D*It.receiveRatioWarning),at=we?Ze:ae&&Se>Pe;T.push(ye?at?Ye("capture","warning","Screen capture cannot keep target speed",we?`${z.toFixed(1)} native capture · ${W.toFixed(1)} encoded · ${D||"?"} requested fps`:`${Se?`capture p95 ${Math.round(Se)}ms`:"capture timing unavailable"} · ${K.toFixed(1)}/${D||"?"} fps`):Ye("capture","ok","Screen capture speed is healthy",we?`${z.toFixed(1)} native capture · ${W.toFixed(1)} encoded · ${D||"?"} requested fps${_e?" · idle optimized":""}`:`${Se?`capture p95 ${Math.round(Se)}ms`:"no slow capture reported"}${D?` · ${K.toFixed(1)}/${D} fps`:""}`):Ye("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Ee=Mt(n,"hubPacketTransitAgeMs"),Ge=Math.max(0,Number(Ee||0)),me=Math.max(0,Number(n?.agentSendGapMs||0)),ke=Math.max(0,Number(n?.agentSendDurationMs||0)),et=!_D(A.remoteAddress),Me=Ci(j,"network.usageRatio"),pe=Mt(j,"network.latencyMs"),qe=(Me??0)>=It.networkUsageWarningRatio||(pe??0)>=It.networkLatencyWarningMs,Re=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,st=Re?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,jt=Re?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,O=Re&&jt>0&&st>=jt,ze=Ee!==void 0&&Number(r?.sampleMs||0)>0,We=!_e&&D>0&&Number(r?.sampleMs||0)>0&&K<D*It.deliveryRatioWarning,Et=!_e&&me>Math.max(It.networkDelayWarningMs,de*3),lt=Ge>It.networkDelayWarningMs||Et||ke>It.networkDelayWarningMs||We||_>It.frameAgeWarningMs||qe||O;T.push(ze?lt||et?Ye("network","warning",et?"External network route may add delay":qe?"Client network adapter needs attention":O?"Hub browser video queue needs attention":"Video delivery is uneven",[Ge?`${Math.round(Ge)}ms Hub-to-browser`:"",me?`${Math.round(me)}ms Client send gap`:"",ke?`${Math.round(ke)}ms Client send time`:"",We?`${K.toFixed(1)} of ${D} requested fps`:"",pe!==void 0?`${Math.round(pe)}ms Client network latency`:"",Me!==void 0?`${Math.round(Me*100)}% Client link use`:"",Re&&jt>0?`Hub queue ${st}/${jt}`:"",et?String(A.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Ye("network","ok","Network delivery is healthy",`${Math.round(Ge)}ms Hub-to-browser · ${_e?`idle optimized at ${W.toFixed(1)} fps`:"the current video rate is on target."}`):Ye("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const ht=Ci(j,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),Je=Ci(j,"memory.usedRatio","usedMemRatio"),be=Ci(j,"gpu.usageRatio"),je=Ci(j,"gpu.memory.usedRatio"),Ae=Mt(j,"gpu.temperatureC","thermal.gpuC"),fe=ht!==void 0&&Je!==void 0,te=em(A.lastStatusAt),ce=te===void 0?Number.POSITIVE_INFINITY:Math.max(0,N-te),Ne=Math.max(It.minimumClientStatusFreshMs,Math.max(1e3,Number(k||0))*It.clientStatusFreshMultiplier),He=ce<=Ne,Ie=(ht??0)>=It.cpuWarningRatio||(Je??0)>=It.memoryWarningRatio||(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC;T.push(fe?He?Ie?Ye("computer","warning",(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Je*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:"",je!==void 0?`GPU memory ${Math.round(je*100)}%`:"",Ae!==void 0?`GPU ${Math.round(Ae)}C`:""].filter(Boolean).join(" · ")):Ye("computer","ok","Client computer has working capacity",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Je*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:""].filter(Boolean).join(" · ")):Ye("computer","warning","Client performance snapshot is stale",Number.isFinite(ce)?`The latest CPU and memory report is ${Math.round(ce/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Ye("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Lt=Number(n?.monitorIndex),Xe=Number.isInteger(Lt)&&Lt===Number(u),ut=mn(A.channels),yt=mn(A.capabilities),_t=ut.input!==!1&&yt.remoteInput!==!1&&yt.accessibilityPermission!==!1,mt=yt.screenRecordingPermission!==!1,Vt=mn(g),St=!f||String(n?.sessionId||"")&&String(n?.sessionId||"")===String(Vt.sessionId||"")&&String(n?.commandId||"")&&String(n?.commandId||"")===String(Vt.commandId||"")&&Number(n?.captureGeneration||0)>0&&Number(n?.captureGeneration||0)===Number(Vt.captureGeneration||0)&&Number(n?.monitorIndex)===Number(Vt.monitorIndex),pn=!f||h&&St;T.push(Xe&&pn&&_t&&mt?Ye("display","ok",f?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(u)+1} · generation ${Number(n?.captureGeneration||0)||"current"}.`):Ye("display","warning",mt?_t?f?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(u)+1}; latest frame ${Number.isInteger(Lt)?Lt+1:"not available"}.`));const rn=mn(l),ya=Array.isArray(rn.canvases)?mn(rn.canvases[0]):{},Ct=Math.max(0,Number(o?.decoderInputFps||0)),gn=Math.max(0,Number(o?.decoderOutputFps||0)),en=Ct>0&&Number(o?.sampleMs||r?.sampleMs||0)>0,nt=K>0&&Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0&&Ct<K*It.decoderInputRatioWarning,Dt=Ct>0?gn/Ct:0,vn=zt(ya,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Nr=zt(ya,"softwareFallbackReason"),Ur=!!Nr||vn==="prefer-software";return T.push(nt?Ye("decoder","warning","Browser decoder input is dropping frames",`${K.toFixed(1)} received / ${Ct.toFixed(1)} decoder input / ${gn.toFixed(1)} output fps.`):en?Ur||Dt<It.decoderOutputRatioWarning?Ye("decoder","warning",Ur?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Nr||String(I.decoderLabel||vn||"decoder")} · ${Ct.toFixed(1)} in / ${gn.toFixed(1)} out fps.`):Ye("decoder","ok",vn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Ct.toFixed(1)} in / ${gn.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Ye("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),T}function lo(t){const n=String(t||"").trim();return n?n.length<=14?n:`${n.slice(0,6)}…${n.slice(-5)}`:"-"}function Rn(t,n=1){const r=Number(t);return Number.isFinite(r)?r.toFixed(n):"-"}function UD({device:t,frame:n,receiveStat:r,paintStat:o,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:w=Date.now()}={}){const b=mn(t),S=mn(b.status),k=mn(S.runtimeProcess),N=mn(S.capture),A=$S(N),j=mn(g),I=mn(o?.lastInfo),T=mn(l),_=Array.isArray(T.canvases)?mn(T.canvases[0]):{},B=[],F=Number(u),H=Number(n?.monitorIndex),D=Number.isInteger(H)&&H===F,K=Number(n?.captureGeneration||0),z=Number(j.captureGeneration||0),W=!f||D&&String(n?.sessionId||"")===String(j.sessionId||"")&&String(n?.commandId||"")===String(j.commandId||"")&&K>0&&K===z,q=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),V=Math.max(0,Number(r?.framesPerSecond||0)),X=Math.max(0,Number(o?.framesPerSecond||0)),ve=Math.max(0,Number(o?.decoderInputFps||0)),J=Math.max(0,Number(o?.decoderOutputFps||0)),$=Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0,P=q>0&&$&&Math.min(V,X||V,J||V)<q*It.deliveryRatioWarning,se=Math.max(0,Number(n?.sourceGapMs||0)),we=Math.max(0,Number(n?.agentSendGapMs||0)),Z=Math.max(0,Number(n?.agentSendDurationMs||0)),Se=Math.max(0,Number(n?.agentSendDurationFrameSeq||0)),ae=Math.max(0,Number(n?.agentQueueBeforePaceMs||0)),ye=Math.max(0,Number(n?.agentFrameAgeMs||0)),Pe=Mt(n,"hubPacketTransitAgeMs"),de=Math.max(0,Number(n?.droppedByAgent||0)),Qe=Math.max(0,Number(n?.hubIngressDropped||0)),ue=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,_e=ue?Math.max(0,Number(n?.hubClientDropped||0)):0,Ze=ue?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,at=ue?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,Ee=ue?Math.max(0,Number(n?.hubClientBufferedBytes||0)):0,Ge=Math.max(0,Number(n?.udpIncompleteFrames||0)),me=de+Qe+_e,ke=WS(n,w),et=zt(_,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Me=zt(_,"softwareFallbackReason"),pe=Math.max(0,Number(T.hardwareReleaseGeneration||0)),qe=Math.max(0,Number(T.hardwareRecoveryProbeCount||0)),Re=Number(T.lastHardwareRecoveryProbeAt),st=Number.isFinite(Re)&&Re>0?Math.max(0,w-Re):void 0,jt=`hardware releases ${pe} · recovery probes ${qe} · last probe ${st===void 0?"-":`${Math.round(st)}ms ago`}`,O=$&&V>0&&ve<V*It.decoderInputRatioWarning,ze=GS(n,S,w),We=zt(b,"deviceId")||zt(n,"deviceId"),Et=zt(n,"sessionId")||zt(b,"sessionId"),lt=zt(b,"productVersion")||zt(S,"productVersion","runtime.productVersion"),ht=zt(b,"agentVersion")||zt(S,"agentVersion","runtime.agentVersion"),Je=Mt(b,"pid","runtimePid")??Mt(S,"pid","runtimePid","process.pid"),be=Mt(k,"pid"),je=Ci(k,"cpuUsageRatio"),Ae=Mt(k,"cpuCorePercent"),fe=Mt(k,"workingSetBytes"),te=Mt(k,"privateMemoryBytes"),ce=Math.max(fe||0,te||0),Ne=(be??0)>0&&(fe??0)>0,He=Ne&&(Je??0)>0&&be!==Je,Ie=(je??0)>=It.runtimeProcessCpuWarningRatio||ce>=It.runtimeProcessMemoryWarningBytes,Lt=Ci(S,"cpu.usageRatio"),Xe=Ci(S,"memory.usedRatio","usedMemRatio"),ut=Math.max(0,Number(Mt(N,"videoStreamCount")||0)),yt=Math.max(0,Number(Mt(N,"audioStreamCount")||0)),_t=Mt(N,"helperCount"),mt=Math.max(0,Number(_t||0)),Vt=Mt(N,"helperMaxConcurrent"),St=Math.max(mt,Number(Vt||0)),pn=Array.isArray(N.helperPids)?N.helperPids.map(Aa=>Number(Aa)).filter(Aa=>Number.isSafeInteger(Aa)&&Aa>0):[],rn=Array.isArray(N.helperProfiles)?N.helperProfiles.map(Aa=>String(Aa||"").trim()).filter(Boolean).slice(0,4):[],ya=Ci(N,"helperCpuUsageRatio"),Ct=Mt(N,"helperCpuCorePercent"),gn=Mt(N,"helperWorkingSetBytes"),en=Mt(N,"helperPrivateMemoryBytes"),U=Math.max(gn||0,en||0),nt=Math.max(0,Number(Mt(N,"helperStartCount")||0)),Dt=Math.max(0,Number(Mt(N,"helperStopCount")||0)),vn=_t!==void 0,Nr=vn&&nt>=Dt&&nt-Dt!==mt,Ur=mt>1||St>1||ut>1||Nr||A.currentProblem,Tr=vn&&(ut>0&&mt===0||ut===0&&mt>0),oe=US({key:We&&Et?`${We}:${Et}`:"",sampleId:zt(N,"sampledAt"),mismatch:Tr}),$e=Tr&&!oe.confirmed,tt=Ur||oe.confirmed,Pt=(ya??0)>=It.captureHelperCpuWarningRatio||U>=It.captureHelperMemoryWarningBytes,wn=!!(We&&Et&<&&ht&&(Je??0)>0),Oe=n?.nativeCaptureTelemetryAvailable===!0,it=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),Nt=it>=2,bt=VS(n),Gt=!bt.required||bt.available,ra=Mt(n,"nativeCaptureTelemetryAgeMs"),qn=Math.max(0,Number(ra||0))+(Number.isFinite(ke)?ke:0),Qt=ra===void 0?"-":`${Math.round(qn)}ms`,En=!Nt||ra!==void 0&&qn<=It.nativeTelemetryStaleMs,qr=Oe&&!En,Ht=zS(n,"nativeEncoderHardwareAccelerated"),Pn=n?.nativeEncoderHardwareAccelerationKnown===!0||Ht!==void 0,Ha=zt(n,"nativeEncoderHardwareQueryStatus"),sr=Ha==="0"?"confirmed":Ha,Rr=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),ir=Math.max(0,Number(n?.nativeCaptureFps||0)),Zs=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),Ds=Math.max(0,Number(n?.nativeCompressionFps||0)),Dn=Math.max(0,Number(n?.nativeEncodedFps||0)),ln=Nt||Zs>0?Ds:Dn,il=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Is=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),go=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),Ai=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),or=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Pd=bt.pending,za=bt.timestampOwners,Wr=bt.timestampOwnerHighWatermark,ol=bt.coalesced,wt=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),_n=bt.pendingReplaced,vo=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),sn=bt.vtActive,us=bt.vtHighWatermark,oc=Math.max(0,Number(n?.nativeOutputQueueDepth||0)),Js=Math.max(0,Number(n?.nativeOutputQueueBytes||0)),ll=bt.outputOldestAgeMs,Bt=Math.max(0,Number(n?.nativeOutputQueueHighWatermark||0)),jr=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),yo=n?.nativeOutputQueueAwaitingKeyFrame===!0,ei=bt.nativeAndPipeResidenceAgeMs,lr=bt.handoffDropped,Ni=bt.handoffRecoveryRequests,ti=bt.handoffOldestAgeMs,Hn=or>2||Pd>1||za>2||Wr>2||ol>0||or>=2&&wt>0,cr=bt.required&&bt.available&&(sn!==1||us>1||za>2||Wr>2),ni=oc>=3||Js>=6*1024*1024||ll>120||jr>0||yo||ei>250||lr>0||Ni>0||ti>120,cl=`in-flight ${or}/2 · backpressure skipped ${wt} · idle skipped ${vo} · stdout queue ${oc} AU/${Math.round(Js/1024)} KB/${Math.round(ll)}ms · HWM ${Bt} · dropped ${jr} · awaiting key ${yo?"yes":"no"} · native+pipe ${Math.round(ei)}ms · handoff ${Math.round(ti)}ms/drop ${lr}/recovery ${Ni}`,lc=`pending ${Pd}/1; timestamp owners ${za}/2 (HWM ${Wr}); coalesced ${ol}; pending replaced ${_n}; VideoToolbox ${sn} active/HWM ${us}`,bo=bt.available&&bt.annexBAllocations>0&&bt.annexBPayloadCopies>=bt.annexBAllocations&&bt.annexBPayloadCopiedBytes>0&&bt.pipePayloadAllocations>0&&bt.pipePayloadCopies>=bt.pipePayloadAllocations&&bt.pipePayloadCopiedBytes>0,Gr=`Annex-B allocation/copy ${bt.annexBAllocations}/${bt.annexBPayloadCopies} (${Math.round(bt.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${bt.pipePayloadAllocations}/${bt.pipePayloadCopies} (${Math.round(bt.pipePayloadCopiedBytes/1024)} KB)`,Vr=Oe&&il>0&&En,wo=q>0?1e3/q:100,Ls=q>0&&ir>=q*It.receiveRatioWarning,xo=ln>0&&ln<q*It.receiveRatioWarning,$a=Vr&&Ls&&xo&&ln>=1&&Dn>=1&&vo>=Math.max(10,ir*.6)&&wt===0,cn=P&&!$a,Zn=!$a&&we>Math.max(It.networkDelayWarningMs,wo*3),Ua=Vr&&q>0&&ir<q*It.receiveRatioWarning,kn=Vr&&!$a&&ir>0&&(Nt&&ln<=0||ln>0&&ln<ir*It.receiveRatioWarning),Fn=Vr&&Zs>0&&ln>0&&Dn<ln*It.receiveRatioWarning,qa=qr?"Native capture telemetry is stale":Gt?cr?"VideoToolbox encoder ownership needs attention":Vr?Ua?"Native screen capture is below request":kn||Hn?"VideoToolbox compression is behind capture":Fn||ni?"Native stdout delivery is backpressured":Ht===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";B.push(OD(b,y)),B.push(wn?Ye("debug-runtime","ok",`LiveDesk ${lt} · Agent ${ht}`,`pid ${Je} · session ${lo(Et)} · device ${lo(We)}`):Ye("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${lt||"-"} · Agent ${ht||"-"} · pid ${Je??"-"} · session ${lo(Et)} · device ${lo(We)}`)),B.push(Ne&&!He&&!Ie?Ye("debug-process-load","ok","RemoteFast process load is healthy",`pid ${be} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Xe)}`):Ye("debug-process-load","warning",Ne?He?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${be??"-"} · reported pid ${Je??"-"} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Xe)}`)),B.push(n?Ye("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${lo(n.streamId)} · ${n.width||0}x${n.height||0} · ${Math.round(Number(n.byteLength||0)/1024)} KB · age ${Number.isFinite(ke)?Math.round(ke):"-"}ms`):Ye("debug-frame","warning","No current frame",`Device ${lo(b.deviceId)} has not produced a frame.`));const ur=/(connecting|recovering|failed|error|degraded|unavailable)/.test(ze.state);B.push(ze.videoTransport&&!ur?Ye("debug-transport","ok",`${ze.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":ze.videoTransport==="p2p-udp"?"P2P UDP":ze.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${ze.state||"active"}`,[`raw ${ze.rawTransport||"-"}`,`P2P ${ze.p2pReady?"ready":"standby unavailable"}`,`switch ${ze.switchCount}`,`TCP failure ${ze.tcpFailureCount}`,ze.changedLabel,ze.reason].filter(Boolean).join(" · ")):Ye("debug-transport","warning",ze.videoTransport?`Video transport ${ze.state||"needs attention"}`:"Video transport is not identified",[ze.videoTransport||"no active path",`raw ${ze.rawTransport||"-"}`,`P2P ${ze.p2pReady?"ready":"not ready"}`,ze.changedLabel,ze.reason].filter(Boolean).join(" · "))),B.push(D?Ye("debug-monitor","ok",`Monitor selected ${F+1} · frame ${H+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`):Ye("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger(H)?H+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`)),B.push(W&&(!f||h)?Ye("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${lo(n?.sessionId)} · command ${lo(n?.commandId)} · generation ${K||"-"}`):Ye("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${lo(n?.commandId)}/${K||"-"} · expected ${lo(j.commandId)}/${z||"-"} · input ${h?"ready":"waiting"}`)),B.push($&&!cn?Ye("debug-cadence","ok",`Cadence ${Rn(V)} rx · ${Rn(X)} paint · ${Rn(J)} decode`,`requested ${Rn(q)} · decoder input ${Rn(ve)} fps · receive p95 ${Rn(r?.p95IntervalMs)}ms${$a?" · idle optimized":""}`):Ye("debug-cadence","warning",$?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Rn(q)} · receive ${Rn(V)} · paint ${Rn(X)} · decode ${Rn(J)} fps`)),B.push(Vr&&Gt&&!Ua&&!kn&&!Fn&&!Hn&&!cr&&!ni&&Ht!==!1?Ye("debug-native-capture","ok",`Native capture ${Rn(ir)} fps · compress ${Rn(ln)} fps · stdout ${Rn(Dn)} fps${$a?" · idle optimized":""}`,`telemetry v${it||1} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${sr?` (${sr})`:""} · display ${Rr||"-"} · capture samples ${il} · encodable ${Is} · skipped ${go} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(se)}ms`):Ye("debug-native-capture","warning",qa,`telemetry ${Oe?`v${it||1}`:"no"} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${sr?` (${sr})`:""} · display ${Rr||"-"} · capture ${Rn(ir)} fps · compress ${Rn(ln)} fps · stdout ${Rn(Dn)} fps · capture samples ${il} · encodable ${Is} · skipped ${go} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(se)}ms`)),bt.required&&(B.push(Gt&&!Hn&&!cr?Ye("debug-native-resource","ok","VideoToolbox resource ownership is bounded",lc):Ye("debug-native-resource","warning",Gt?cr?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",lc)),B.push(Gt&&bo?Ye("debug-native-copy","ok","Capture copy accounting is current",Gr):Ye("debug-native-copy","warning",Gt?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Gr))),B.push(vn&&!tt&&!Pt?Ye("debug-capture-ownership","ok",$e?"Capture ownership transition is settling":mt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ut} · audio ${yt} · helpers ${mt} (max ${St||"-"}) · pid ${pn.join(",")||"-"} · profile ${rn.join(", ")||"-"} · CPU ${Vl(ya)} machine / ${kp(Ct)} core · RSS ${Gl(gn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}${$e?` · mismatch samples ${oe.count}/${xv}`:""}`):Ye("debug-capture-ownership","warning",vn?mt>1||St>1?"Duplicate capture helpers detected":tt?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${ut} · audio ${yt} · helpers ${mt} (max ${St||"-"}) · pid ${pn.join(",")||"-"} · profile ${rn.join(", ")||"-"} · CPU ${Vl(ya)} machine / ${kp(Ct)} core · RSS ${Gl(gn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}`));const Wa=`helper I/O ${A.helperOwnedIoTaskCount} | exit observers ${A.helperOwnedExitObserverCount} | undisposed ${A.helperUndisposedProcessCount} | quarantine ${A.helperQuarantineCount} | dispose failures ${A.helperDisposeFailureCount} | utility I/O ${A.utilityOwnedIoTaskCount} | undisposed ${A.utilityUndisposedProcessCount} | quarantine ${A.utilityQuarantineCount} | utility pid ${A.utilityQuarantinePids.join(",")||"-"} | profile ${A.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${A.utilityQuarantineStartCount} / stops ${A.utilityQuarantineStopCount} | dispose failures ${A.utilityDisposeFailureCount}${A.helperLastDisposeFailure?` | helper last ${A.helperLastDisposeFailure}`:""}${A.utilityLastDisposeFailure?` | utility last ${A.utilityLastDisposeFailure}`:""}`;B.push(A.telemetryAvailable&&!A.currentProblem&&!A.historicalCleanupFailure?Ye("debug-capture-cleanup","ok",mt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",Wa):Ye("debug-capture-cleanup","warning",A.telemetryAvailable?A.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",Wa)),B.push(ue?me===0&&Ge===0&&(at<=0||Ze<at)&&!Zn&&Z<=It.networkDelayWarningMs&&ye<=It.networkDelayWarningMs&&(Pe===void 0||Pe<=It.networkDelayWarningMs)?Ye("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Client send time ${Math.round(Z)}ms (frame ${Se||"-"}) · Agent queue ${Math.round(ae)}ms · Agent age ${Math.round(ye)}ms · Agent drop ${de} · Hub transit ${Pe===void 0?"-":Math.round(Pe)}ms · Hub ingress drop ${Qe} · browser queue drop ${_e} (${Ze}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}${$a?" · idle optimized":""}`):Ye("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Client send time ${Math.round(Z)}ms (frame ${Se||"-"}) · Agent queue ${Math.round(ae)}ms · Agent age ${Math.round(ye)}ms · Agent drop ${de} · Hub transit ${Pe===void 0?"-":Math.round(Pe)}ms · Hub ingress drop ${Qe} · browser queue drop ${_e} (${Ze}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}`):Ye("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Agent drop ${de} · Hub ingress drop ${Qe} · per-browser lane counters are intentionally collected outside video packets.`));const ai=Mt(n,"captureP95Ms");return B.push(n?.captureTimingAvailable===!0&&ai!==void 0?Ye("debug-capture","ok",`Capture p95 ${Rn(ai)}ms · avg ${Rn(n?.captureAverageMs)}ms`,`stage ${Rn(n?.captureStageMs)}ms · slow ${Number(n?.slowFrameCount||0)} · helper restart ${Number(n?.captureHelperRestarts||0)} · source skip ${Number(n?.captureSourceSkipped||0)}`):Vr&&Nt?Ye("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Rn(ir)} fps · VideoToolbox ${Rn(ln)} fps · stdout ${Rn(Dn)} fps · telemetry age ${Qt}`):Ye("debug-capture","warning","Capture timing sample is unavailable",`stage ${Rn(n?.captureStageMs)}ms · helper restart ${Number(n?.captureHelperRestarts||0)} · source serial ${Number(n?.captureSourceSerial||0)}`)),B.push(!Me&&et!=="prefer-software"&&!O?Ye("debug-decoder","ok",`Decoder ${et||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${jt}`):Ye("debug-decoder","warning",O?"Decoder input is losing received frames":"Decoder software fallback is active",O?`${Rn(V)} received / ${Rn(ve)} decoder input / ${Rn(J)} output fps · ${jt}`:`${Me||et||"software"} · ${Rn(ve)} in / ${Rn(J)} out fps · ${jt}`)),B}function qD({status:t,deviceDiagnostics:n=[],codec:r,browser:o,frameStats:l}={}){const u=mn(t),f=mn(u.diagnostics),h=mn(f.system),g=mn(f.network),y=mn(r),w=mn(o),b=Array.isArray(n)?n:[],S=b.reduce((ye,Pe)=>ye+(Array.isArray(Pe)&&Pe.some(de=>de?.state==="warning")?1:0),0),k=Ci(h,"cpuUsageRatio","processCpuRatio"),N=Ci(h,"memoryUsedRatio"),A=Mt(h,"totalMemoryBytes"),j=Mt(h,"cpuLogicalCores")??Mt(w,"hardwareConcurrency"),I=Mt(w,"deviceMemory"),T=(j??0)>0&&k!==void 0&&N!==void 0&&(A??0)>0,_=(A??0)>0&&A<It.hubMinimumTotalMemoryBytes,B=(I??0)>0&&I<It.hubMinimumBrowserMemoryGb,F=(j??0)>0&&j<4||(k??0)>=It.cpuWarningRatio||(N??0)>=It.memoryWarningRatio||_||B,H=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),D=Math.max(0,Number(y.activeDecoderCount||0)),K=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),z=Mt(g,"externalDeviceCount"),W=zt(g,"route"),q=z!==void 0&&!!W,V=(z??0)>0||W==="external",X=mn(u.frameLanes),ve=mn(X.packetFanout),J=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(ye=>Mt(ve,ye)!==void 0),$=Array.isArray(X.clients)?X.clients.map(mn):[],P=Mt(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&J,se=$.some(ye=>{const Pe=Math.max(0,Number(ye.queueDepth||0)),de=Math.max(0,Number(ye.queueLimit||0)),Qe=Math.max(0,Number(ye.queuedBytes||0)),ue=Math.max(0,Number(ye.queueByteLimit||0));return Math.max(0,Number(ye.droppedPackets||0))>0||de>0&&Pe>=de||ue>0&&Qe>=ue||Array.isArray(ye.backpressuredDeviceIds)&&ye.backpressuredDeviceIds.length>0}),we=Math.max(0,Number(ve.packetBuilds||0)),Z=Math.max(0,Number(ve.metadataSerializations||0)),Se=Math.max(0,Number(ve.payloadCopyOperations||0)),ae=Math.max(0,Number(ve.fanoutEligibleSubscribers||0));return[u.started&&!u.lastError?Ye("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Ye("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),T?F?Ye("hub-computer","warning",_?"Hub has limited system memory":B?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${j||"?"} logical cores`,`${px(A)} RAM`,I!==void 0?`${I} GB browser memory class`:"",`CPU ${k===void 0?"?":Math.round(k*100)}%`,`memory ${N===void 0?"?":Math.round(N*100)}%`].filter(Boolean).join(" · ")):Ye("hub-computer","ok","Hub computer capacity is healthy",`${j||"?"} logical cores · ${px(A)} RAM · CPU ${k===void 0?"not reported":`${Math.round(k*100)}%`}.`):Ye("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),D<=0?Ye("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):H>0?Ye("hub-codec","warning","Some browser decoders use software fallback",`${D} active H.264 decoders · ${H} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Ye("hub-codec","ok","All active streams request hardware H.264",`${D} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),P?se?Ye("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${$.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Ye("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${$.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Ye("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),S>0?Ye("hub-clients","warning",`${S} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Ye("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Ye("hub-network",!q||V||K>120?"warning":"ok",q?V?`${z} Clients use an external network route`:K>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",q?`${W.toUpperCase()} route · ${K.toFixed(K>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function WD(t,n={}){const r=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),o=Math.max(320,n.maxWidth||1920),l=Math.max(180,n.maxHeight||1080),u=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,f=Math.max(1,Math.ceil(Math.max(1,r.length)/u)),h=Math.floor(o/u),g=Math.floor(l/f),y=document.createElement("canvas");y.width=Math.max(320,h*u),y.height=Math.max(180,g*f);const w=y.getContext("2d",{alpha:!1});if(!w)return y;w.fillStyle="#0b1220",w.fillRect(0,0,y.width,y.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let b=0;b<r.length;b+=1){const S=r[b],k=b%u,N=Math.floor(b/u),A=k*h,j=N*g,I=S.canvas,T=Math.min(h/I.width,g/I.height),_=Math.max(1,Math.floor(I.width*T)),B=Math.max(1,Math.floor(I.height*T)),F=A+Math.floor((h-_)/2),H=j+Math.floor((g-B)/2);w.drawImage(I,F,H,_,B),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,j+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(S.label,A+9,j+g-9))}return y}function GD(t){return t?.signature||"none"}function VD(t){return t?.label||"No capture target"}function gx(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function KD(){const t=new Date,n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}${n(t.getMonth()+1)}${n(t.getDate())}_${n(t.getHours())}${n(t.getMinutes())}${n(t.getSeconds())}`}function QD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function YD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${QD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${KD()}.png`}async function XD(t,n,r){const o=await new Promise((u,f)=>t.toBlob(h=>h?u(h):f(new Error("Screenshot could not be encoded.")),"image/png")),l=await OS(o,{kind:"screenshot",fileName:YD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":o})])}catch{}return l.capture}function KS(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function ZD(t,n){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),o=n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${o}_${r}.webm`:`LiveDesk_Recording_${o}_${r}.webm`}async function QS(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=KS();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",o=await AD({kind:r,fileName:ZD(r,t.target),mimeType:n,target:t.target},t.hubUrl),l=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(l,{mimeType:n,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),f=performance.now();let h=0,g=!1,y=null,w=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const S=h++;w=w.then(()=>ND(o.sessionId,S,b.data,t.hubUrl).then(()=>{})).catch(k=>{y=y||(k instanceof Error?k:new Error(String(k))),t.onError?.(y)})},u.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),t.onError?.(y)},u.start(1e3),{requestFrame:()=>{l.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),l.getTracks().forEach(b=>b.stop()),await w,y)throw await lx(o.sessionId,t.hubUrl).catch(()=>{}),y;await TD(o.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await lx(o.sessionId,t.hubUrl).catch(()=>{}))}}}class JD{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(n,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof n.captureStream!="function")throw new Error("This browser does not support Last 30s.");const o=KS();if(!o)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=n.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:o,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=l=>{if(!l.data.size)return;const u=performance.now();for(this.segments.push({blob:l.data,at:u}),this.totalBytes+=l.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const f=this.segments.shift();this.totalBytes-=f.blob.size}},this.recorder.start(1e3)}stop(){const n=this.recorder;this.recorder=null,n&&n.state!=="inactive"&&(n.ondataavailable=null,n.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(n,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const o=new Blob(this.segments.map(f=>f.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`LiveDesk_Last30s_${n.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 OS(o,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function eI(t,n,r,o,l){const u=await QS({canvas:t,target:n,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:o,onError:l});u.requestFrame?.();const f=window.setInterval(()=>u.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(f),await u.stop()},cancel:async()=>{window.clearInterval(f),await u.cancel()}}}const YS="livedesk.captureSettings";function tI(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(YS)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function nI(t){const[n,r]=d.useState(tI),[o,l]=d.useState(0),[u,f]=d.useState(0),[h,g]=d.useState(0),[y,w]=d.useState(!1),b=d.useRef(void 0),S=d.useRef(!1),k=d.useRef(""),N=d.useRef(null),A=d.useRef(null),j=d.useRef(null),I=d.useRef(null),T=d.useRef(new JD),_=t.sourceRegistry.resolveCurrentTarget(),B=GD(_),F=VD(_),H=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(YS,JSON.stringify(n)),!S.current)return;const se=JSON.stringify(n);se!==k.current&&(k.current=se,rt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:n.rollingEnabled,recordingQuality:n.recordingQuality,timelapseIntervalSeconds:n.timelapseIntervalSeconds,includeRemoteCursor:n.includeRemoteCursor}})},t.hubUrl).then(we=>{b.current=Number(we.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,n]),d.useEffect(()=>{let se=!0;return rt("/api/settings",void 0,t.hubUrl).then(we=>{if(!se)return;const Z=we.settings?.filesAudio||{},Se=typeof Z.rollingBufferEnabled=="boolean"?Z.rollingBufferEnabled:n.rollingEnabled,ae=Z.recordingQuality==="high"?"high":"standard",ye=[5,10,30,60].includes(Number(Z.timelapseIntervalSeconds))?Number(Z.timelapseIntervalSeconds):n.timelapseIntervalSeconds,Pe=typeof Z.includeRemoteCursor=="boolean"?Z.includeRemoteCursor:n.includeRemoteCursor,de={rollingEnabled:Se,recordingQuality:ae,timelapseIntervalSeconds:ye,includeRemoteCursor:Pe};b.current=Number(we.revision||0),k.current=JSON.stringify(de),S.current=!0,r(de)}).catch(()=>{S.current=!0}),()=>{se=!1}},[t.hubUrl]);const D=d.useCallback(async se=>{if(se.sourceCanvas&&se.sourceCanvas.width>0&&se.sourceCanvas.height>0)return{target:gx(se),canvas:se.sourceCanvas,cleanup:()=>{}};const we=await t.sourceRegistry.composeWall(se.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Z=!1;const Se=window.setInterval(async()=>{if(Z)return;const ae=await t.sourceRegistry.composeWall(se.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!ae||Z||((we.width!==ae.width||we.height!==ae.height)&&(we.width=ae.width,we.height=ae.height),we.getContext("2d")?.drawImage(ae,0,0))},100);return{target:gx(se),canvas:we,cleanup:()=>{Z=!0,window.clearInterval(Se)}}},[t.sourceRegistry]);d.useEffect(()=>{const se=T.current;if(!n.rollingEnabled||!_||!H){se.stop(),g(0);return}let we=!1,Z=null;return(async()=>{try{if(Z=await D(_),we)return;await se.start(Z.canvas,Z.target);const ae=window.setInterval(()=>g(Math.round(se.seconds)),500),ye=()=>{window.clearInterval(ae),Z?.cleanup()};se.__cleanup=ye}catch(ae){we||t.onToast(ae instanceof Error?ae.message:String(ae))}})(),()=>{we=!0,se.stop(),se.__cleanup?.(),se.__cleanup=void 0,g(0)}},[D,t.onToast,n.rollingEnabled,B,H]);const K=d.useCallback(se=>r(we=>({...we,rollingEnabled:se})),[]),z=d.useCallback(se=>r(we=>({...we,recordingQuality:se})),[]),W=d.useCallback(se=>r(we=>({...we,timelapseIntervalSeconds:se})),[]),q=d.useCallback(async()=>{const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let we=null;try{we=await D(se),await XD(we.canvas,we.target,t.hubUrl),t.onToast("Screenshot saved")}finally{we?.cleanup(),w(!1)}},[D,t.hubUrl,t.onToast,t.sourceRegistry]),V=d.useCallback(async()=>{if(j.current)throw new Error("Stop the timelapse before recording.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await D(se),Z=await QS({canvas:we.canvas,target:we.target,fps:se.type==="control"?30:15,hubUrl:t.hubUrl,onError:Se=>t.onToast(Se.message)});A.current=we.cleanup,N.current=Z,l(Date.now()),t.onToast("Recording started")},[D,t.hubUrl,t.onToast,t.sourceRegistry]),X=d.useCallback(async()=>{const se=N.current;if(se){w(!0);try{await se.stop(),t.onToast("Recording saved")}finally{N.current=null,A.current?.(),A.current=null,l(0),w(!1)}}},[t.onToast]),ve=d.useCallback(async()=>{if(N.current||j.current)throw new Error("Last 30s is unavailable during a recording.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(se,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{w(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),J=d.useCallback(async()=>{if(N.current)throw new Error("Stop the recording before starting a timelapse.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await D(se),Z=await eI(we.canvas,we.target,n.timelapseIntervalSeconds,t.hubUrl,Se=>t.onToast(Se.message));I.current=we.cleanup,j.current=Z,f(Date.now()),t.onToast("Timelapse started")},[D,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),$=d.useCallback(async()=>{const se=j.current;if(se){w(!0);try{await se.stop(),t.onToast("Timelapse saved")}finally{j.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const se=we=>{!N.current&&!j.current||(we.preventDefault(),we.returnValue="")};return window.addEventListener("beforeunload",se),()=>window.removeEventListener("beforeunload",se)},[]),d.useEffect(()=>()=>{T.current.stop(),N.current?.cancel(),j.current?.cancel(),A.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!N.current,recordingStartedAt:o,timelapse:!!j.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:n.rollingEnabled,busy:y,targetLabel:F}),[h,y,o,n.rollingEnabled,F,u]),settings:n,videoSupported:H,targetKey:B,setRollingEnabled:K,setRecordingQuality:z,setTimelapseInterval:W,takeScreenshot:q,startRecording:V,stopRecording:X,saveLast30Seconds:ve,startTimelapse:J,stopTimelapse:$}}function aI(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const t=window.navigator.userAgent,n=/iPad|iPhone|iPod/i.test(t)||window.navigator.platform==="MacIntel"&&window.navigator.maxTouchPoints>1,r=/Android/i.test(t),o=n&&/CriOS/i.test(t),l=n&&/Safari/i.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(t);return{isIos:n,isAndroid:r,isSafari:l,browserName:o?"Chrome":l?"Safari":"browser"}}const rI=120,sI=999,$f=5,Uf=30,iI=Number.POSITIVE_INFINITY,XS="livedesk.remoteDirectory",Sv="livedesk.localHubAccessEnabled",oI="livedesk.streamSettings",lI=18,cI="livedesk.controlStreamSettings",uI=10,ZS="livedesk.wallCadence",dI=1e3,JS="livedesk.wallMonitorSelections",eC=2,Fg=512*1024,fI=!1;"".trim();"".trim();const mI=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),pI=1e3/60,Og=1500,hI=650,gI=1800,vI=650,yI=2500,Bg=1500,vx=15e3,yx=120,bx=100,wx=20,bI=6e4,wI=6e4,xx=240,xI=1024,SI=640,CI=360,Sx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Mp="LiveDesk is replacing the Hub and verifying the requested version.",Ap=5*6e4,kI=5e3,Cx=2e3,MI=8e3;function kx(t,n){return`${t}:${n.deviceId}:${n.completedAt||n.candidateSessionId||n.commandId||"completed"}`}function Yc({label:t,tooltip:n,disabled:r=!1,active:o=!1,danger:l=!1,pressed:u,onClick:f,children:h}){return i.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":n,children:i.jsx("button",{className:`manual-action ${o?"active":""} ${l?"danger":""}`.trim(),onClick:f,disabled:r,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function AI(t,n){if(n.deviceId!==t.deviceId)return!1;const r=Number(n.browserReceivedEpochMs);if(!Number.isFinite(r)||r<t.startedAtEpochMs)return!1;const o=Number(n.monitorIndex);if(Number.isFinite(o)&&Math.floor(o)!==t.monitorIndex)return!1;const l=String(n.frameMode||n.mode||"").trim().toLowerCase();return!l||l===t.frameMode}const Xc={free:{name:"Free",price:"$0",limit:$f,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Uf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:iI,audience:"Business and studios",note:"Commercial use and larger Client walls."}},NI={"mode3-h264-hw":30};function Mx(t,n){const r=f=>{const g=String(f||"").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 y=g[4]?g[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return y.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},o=r(t),l=r(n);if(!o||!l)return!1;for(let f=0;f<3;f+=1){if(o.core[f]>l.core[f])return!0;if(o.core[f]<l.core[f])return!1}if(o.prerelease.length===0||l.prerelease.length===0)return o.prerelease.length===0;const u=Math.max(o.prerelease.length,l.prerelease.length);for(let f=0;f<u;f+=1){const h=o.prerelease[f],g=l.prerelease[f];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}const TI=512;function la(t,n){return`${t}:${n}`}function co(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const RI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:NI["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},jI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Ax={maxWidth:3840,maxHeight:2160};function Bf(t,n){if(t.length===0)return 0;const r=[...t].sort((l,u)=>l-u),o=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*n)-1));return r[o]}function tC(t,n){t.push(n),t.length>xx&&t.splice(0,t.length-xx)}function Np(t,n){t.sampleFrames=0,t.sampleStartedAt=n,t.intervalCount=0,t.intervalSumMs=0,t.minIntervalMs=Number.POSITIVE_INFINITY,t.maxIntervalMs=0,t.intervalSamplesMs.length=0,t.seqGapCount=0,t.maxSeqGap=0}function Nx(t,n,r){if(t.lastAt!==void 0){const o=Math.max(0,n-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=o,t.minIntervalMs=Math.min(t.minIntervalMs,o),t.maxIntervalMs=Math.max(t.maxIntervalMs,o),tC(t.intervalSamplesMs,o)}if(t.lastFrameSeq!==void 0){const o=r-t.lastFrameSeq;o!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(o)))}t.lastAt=n,t.lastFrameSeq=r}function Tx(t){return!t||t.intervalCount<=0?"waiting":`${Math.round(t.averageIntervalMs)}ms avg / p95 ${Math.round(t.p95IntervalMs)}ms / max ${Math.round(t.maxIntervalMs)}ms`}function Rx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function EI(t){return Number.isFinite(t)?String(t):"30+"}const nC=[1,2,5,8,12,20,30],jx={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},Si={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:Xn.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:Xn.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},Ex=2200,DI=2500,II=8e3,LI=3500,PI=7e3,_I=2,FI=2500,OI=7e3,BI=2600,HI=4200,zI=750,$I=2,Dx=2500,Ix=4200,Lx=2200;function Px(t,n){return Math.min(3e4,t*2**Math.min(3,Math.max(0,n)))}function Op(t,n){const r=t.capabilities?.[n];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Pa(t){return t.deviceName||t.hostname||t.deviceId}function UI(){return"npx -y --prefer-online livedesk@latest client"}function qI(){return"npx -y --prefer-online livedesk@latest"}function WI(){try{return localStorage.getItem(XS)||""}catch{return""}}function GI(){try{return localStorage.getItem(Sv)==="1"}catch{return!1}}function Cd(t){try{t?localStorage.setItem(Sv,"1"):localStorage.removeItem(Sv)}catch{}}function ki(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){const n=ki(t.status),r=ki(n.screens),o=ki(t.capabilities),l=ki(t.latestLiveFrame),u=ki(t.activeLiveStream),h=[n.monitorCount,n.screenCount,r.count,o.monitorCount,o.screenCount,l.monitorCount,u.monitorCount,Array.isArray(r.displays)?r.displays.length:0,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(n.monitors)?n.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function Zl(t){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):0}function aC(t){const n=ki(t.status),o=[ki(n.screens).displays,n.displays,n.monitors];for(const l of o)if(!(!Array.isArray(l)||l.length===0))return l.map(u=>ki(u));return[]}function ey(t,n){const r=aC(t),o=r.find(g=>Number(g.index)===n)||r[n]||r[0]||{},l=Zl(o.width),u=Zl(o.height),f=[o.name,o.displayName,o.deviceName,o.id].find(g=>typeof g=="string"&&g.trim()),h=typeof f=="string"?f.trim():`Display ${n+1}`;return{index:n,name:h,width:l,height:u,primary:o.primary===!0||o.isPrimary===!0}}function VI(t){const n=fo(t);return Array.from({length:n},(r,o)=>ey(t,o))}function KI(t){const n=aC(t);if(n.length===0)return"";const r=n.map((o,l)=>{const u=Number(o.index),f=[o.name,o.displayName,o.deviceName,o.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(u)?Math.floor(u):l,typeof f=="string"?f.trim().toLowerCase():"",h(o.left),h(o.top),h(o.width),h(o.height),o.primary===!0||o.isPrimary===!0]}).sort((o,l)=>o[0]-l[0]);return JSON.stringify(r)}function QI(t){const n=[t.name||`Display ${t.index+1}`];return t.width>0&&t.height>0&&n.push(`${t.width}x${t.height}`),t.primary&&n.push("Primary"),n.join(" - ")}function rC(t,n){const r=ey(t,n);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const o=ki(t.status),l=Zl(o.screenWidth||o.width),u=Zl(o.screenHeight||o.height);return l>0&&u>0?{width:l,height:u}:null}function sC(t){if(!t)return null;const n=Zl(t.sourceWidth)||Zl(t.width),r=Zl(t.sourceHeight)||Zl(t.height);return n>0&&r>0?{width:n,height:r}:null}function YI(t,n,r){const u=((typeof n?.monitorIndex=="number"?qf(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?sC(n):null)||rC(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Tp=16/9;function qf(t,n){const r=Math.max(1,Math.min(64,Math.floor(Number(n)||1))),o=Math.floor(Number(t));return Number.isFinite(o)?Math.max(0,Math.min(r-1,o)):0}function js(t,n){return CN(n,fo(t),t.platform)}function XI(){try{const t=localStorage.getItem(JS);if(!t)return{selections:{},topologyFingerprints:{}};const n=JSON.parse(t),r=n&&typeof n=="object"&&!Array.isArray(n)?n.selections:void 0;if(Number(n?.version)!==eC||!r||typeof r!="object"||Array.isArray(r))return{selections:{},topologyFingerprints:{}};const o={},l={};for(const[u,f]of Object.entries(r)){const h=u.trim(),g=ki(f),y=g.monitorIndex,w=Math.floor(Number(y));if(!h||!Number.isFinite(w))continue;o[h]=Math.max(0,Math.min(63,w));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(l[h]=b)}return{selections:o,topologyFingerprints:l}}catch{return{selections:{},topologyFingerprints:{}}}}function ZI(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([o,l])=>[o,{monitorIndex:l,topologyFingerprint:n[o]||""}]));localStorage.setItem(JS,JSON.stringify({version:eC,selections:r}))}catch{}}function JI(){return{...RI}}function eL(t){try{localStorage.setItem(oI,JSON.stringify({...t,version:lI}))}catch{}}function tL(){return{...jI}}function nL(t){try{localStorage.setItem(cI,JSON.stringify({...t,version:uI}))}catch{}}function aL(){try{return localStorage.getItem(ZS)==="slow"?"slow":"fast"}catch{return"fast"}}function rL(t){try{localStorage.setItem(ZS,t)}catch{}}function Hg(t,n){return t.length!==n.length?!1:t.every((r,o)=>r===n[o])}function zg(t){return[...new Set(t.filter(Boolean))].sort()}function sL(t){return Si.fallbackVisibleCounts[t]||Si.fallbackVisibleCounts.large}function _x(t,n,r){if(t.frameMode==="mode4-h264-atlas")return t.atlasTileSizeMode==="auto"?n==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:t.atlasTileWidth,maxHeight:t.atlasTileHeight};if(!t.adaptiveSizeByWall)return{maxWidth:t.maxWidth,maxHeight:t.maxHeight};const o=jx[n]||jx.large;return{maxWidth:Math.min(t.maxWidth,o.maxWidth),maxHeight:Math.min(t.maxHeight,o.maxHeight)}}function iL(t,n=Si.minFps){const r=[...nC].sort((l,u)=>l-u),o=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||o}function oL(t,n){return[...nC].sort((o,l)=>o-l).find(o=>o>t&&o<=n)||n}function Wf(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;const l=o===0||r>=100?0:1;return`${r.toFixed(l)} ${n[o]}`}function Fx(t){if(!Number.isFinite(t)||!t||t<=0)return"0GB";const n=1024**4,r=1024**3;return t>=n?`${Math.max(1,Math.round(t/n))}TB`:`${Math.max(1,Math.round(t/r))}GB`}function $g(t,n){if(!Number.isFinite(t)||!t||t<=0)return"not reported";const r=Math.max(0,t-Math.max(0,Number(n||0)));return`${Fx(r)} / ${Fx(t)}`}function lL(t){const n=new Uint8Array(t),r=32768;let o="";for(let l=0;l<n.length;l+=r){const u=n.subarray(l,l+r);o+=String.fromCharCode(...u)}return btoa(o)}function Ox(t){return Array.from(t).filter(n=>n.size>=0).map(n=>{const r=n.webkitRelativePath||n.name;return{file:n,relativePath:r,fingerprint:`${n.size}:${n.lastModified}`}})}function cL(t){return t===1?"middle":t===2?"right":"left"}function Bx(t,...n){for(const r of n){const o=t?.[r];if(typeof o=="string"&&o.trim())return o.trim()}return""}function Hx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=sI?n:0}const uL={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function dL(t,n,r){if(t==="online")return"Online";if(t==="busy")return"Busy";if(t==="stale")return"Stale";if(t==="offline")return"Offline";if(r==="failed")return"Task failed";const o=t==="critical"?"critical":"warn",l=n.find(f=>f.state===o)||n.find(f=>f.state==="critical"||f.state==="warn");if(!l)return t==="critical"?"Issue":"Check";const u=uL[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function iC(t,n){const r=n.split(".");let o=t;for(const l of r){if(o==null)return;if(Array.isArray(o)){const u=Number(l);o=Number.isInteger(u)?o[u]:void 0;continue}if(typeof o=="object"){o=o[l];continue}return}return o}function aa(t,...n){for(const r of n){const o=iC(t,r),l=Number(o);if(Number.isFinite(l))return l}}function uo(t,...n){for(const r of n){const o=iC(t,r);if(typeof o=="string"&&o.trim())return o.trim();if(typeof o=="number"&&Number.isFinite(o))return String(o)}return""}function el(t){const n=Number(t);if(Number.isFinite(n))return Math.max(0,Math.min(1,n>1?n/100:n))}function Ug(t,n){if(!(typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)||t<=0))return el((t-Math.max(0,n))/t)}function kd(t){return t===void 0?"-":`${Math.round(t*100)}%`}function qg(t){return t===void 0||!Number.isFinite(t)?"":t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}Gb/s`:`${Math.round(t)}Mb/s`}function Zc(t,n=.92,r=.78){return t===void 0?"unknown":t>=n?"critical":t>=r?"warn":"good"}function fL(t){return!Number.isFinite(t)||!t||t<=0?"-":t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function oC(t){const n=t.status||{},r=aa(n,"cpu.cores","cpuCores","processorCount"),o=aa(n,"loadavg.0","cpu.load1"),l=el(aa(n,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&o!==void 0?o/Math.max(1,r):void 0)),u=aa(n,"memory.totalBytes","totalMem"),f=aa(n,"memory.freeBytes","freeMem"),h=el(aa(n,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ug(u,f),g=aa(n,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=aa(n,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=el(aa(n,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ug(g,y),b=aa(n,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),S=el(aa(n,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),k=uo(n,"gpu.name","gpu.model","accelerators.gpu.name"),N=aa(n,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=aa(n,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),j=el(aa(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ug(N,A),I=aa(n,"gpu.temperatureC","thermal.gpuC"),T=el(aa(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),_=uo(n,"npu.name","npu.model","accelerators.npu.name"),B=aa(n,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=aa(n,"network.rxMbps","network.receiveMbps","network.downMbps"),H=aa(n,"network.txMbps","network.transmitMbps","network.upMbps"),D=aa(n,"network.latencyMs","network.rttMs"),K=el(aa(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),z=uo(n,"network.link","network.interface","network.name"),W=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),q=Number.isFinite(W)?W:void 0,V=q===void 0?void 0:el((q-35)/60),X=b!==void 0&&I!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(I)}°`:b!==void 0?`CPU ${Math.round(b)}°`:I!==void 0?`GPU ${Math.round(I)}°`:"-",ve=uo(n,"workload.role","role","lane")||(Op(t,"taskDispatch")?"Command-ready Client":"Local machine"),J=uo(t.latestTask,"status")||uo(n,"workload.status")||"idle",$=uo(t.latestTask,"title","instructionPreview")||uo(n,"workload.title"),P=uo(t.latestTask,"resultSummary","error","instructionPreview")||uo(n,"workload.summary"),se=Date.parse(t.lastSeenAt||t.connectedAt||""),we=Number.isFinite(se)?Date.now()-se:0;let Z="online";t.connected?we>5*6e4?Z="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(S??0)>=.96||(j??0)>=.96||(T??0)>=.96||(h??0)>=.94||(w??0)>=.94||(D??0)>=200||J==="failed"?Z="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(S??0)>=.86||(j??0)>=.88||(T??0)>=.86||(h??0)>=.82||(w??0)>=.86||(D??0)>=80?Z="warn":["queued","running","targeted"].includes(J)&&(Z="busy"):Z="offline";const Se=[{id:"cpu",label:"CPU",value:kd(l),detail:r?`${r} cores`:o!==void 0?`load ${o.toFixed(1)}`:"not reported",ratio:l,state:Zc(l,.92,.78)},{id:"memory",label:"RAM",value:kd(h),detail:$g(u,f),ratio:h,state:Zc(h,.92,.78)},{id:"disk",label:"DISK",value:kd(w),detail:$g(g,y),ratio:w,state:Zc(w,.92,.82)},{id:"gpu",label:"GPU",value:kd(S),detail:k||(N&&A!==void 0?`${Wf(A)} VRAM free`:I!==void 0?`${Math.round(I)}C`:"not reported"),ratio:S,state:I!==void 0&&I>=88?"critical":I!==void 0&&I>=80?"warn":Zc(S,.96,.86)},{id:"vram",label:"VRAM",value:kd(j),detail:$g(N,A),ratio:j,state:Zc(j,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?kd(T):B!==void 0?`${Math.round(B)} TOPS`:"-",detail:_||(B!==void 0?"neural engine":"not reported"),ratio:T,state:Zc(T,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${fL(aa(n,"uptimeSec"))}`,ratio:V,state:q===void 0?"unknown":q>=86?"critical":q>=78?"warn":"good"},{id:"network",label:"NET",value:qg(F)||(D!==void 0?`${Math.round(D)}ms`:z||"-"),detail:qg(H)?`${qg(H)} up`:z||"not reported",ratio:K,state:D!==void 0&&D>=200?"critical":D!==void 0&&D>=80?"warn":Zc(K,.9,.75)}];return{state:Z,label:dL(Z,Se,J),role:ve,taskLabel:$||(J==="idle"?"idle":J),taskStatus:J,taskSummary:P,metrics:Se}}const mL=[{id:"slow",label:"Slow",fps:pv("slow")},{id:"fast",label:"Fast",fps:pv("fast")}],pL=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],hL=[{id:"sync-server",label:"Hub",icon:mo,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:t0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Hf,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Kf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:jp,accent:"violet",tooltip:"agents"}],gL=[{id:"doc",label:"Doc",icon:Hp,accent:"amber"},{id:"support",label:"Support",icon:Gf,accent:"violet"},{id:"pricing",label:"Pricing",icon:Vf,accent:"green"}];function vL(t){return t.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 Yn(t){return vL(t).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 Jc(t){return t.map(n=>Yn(n))}function kr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:Yn(t.title),intro:Yn(t.intro),sections:[{title:Yn(t.managerTitle),body:Yn(t.managerBody),points:Jc(t.managerPoints)},{title:Yn(t.clientTitle),body:Yn(t.clientBody),points:Jc(t.clientPoints)},{title:Yn(t.syncTitle),body:Yn(t.syncBody),points:Jc(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:Yn(t.agentTitle),body:Yn(t.agentBody),points:Jc(t.agentPoints)}]:[],{title:Yn(t.platformTitle),body:Yn(t.platformBody),points:Jc(t.platformPoints)}],sync:{title:Yn(t.syncTitle),body:Yn(t.syncBody),points:Jc(t.syncPoints)},firewall:{title:Yn(t.firewallTitle),body:Yn(t.firewallBody),points:Jc(t.firewallPoints)},commands:{title:Yn(t.commandsTitle),body:Yn(t.commandsBody),manager:Yn(t.managerCommandLabel),primary:Yn(t.clientCommandLabel),slot:Yn(t.slotCommandLabel),manual:Yn(t.manualCommandLabel)}}}const jd={ko:kr({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 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에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 LiveDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"LiveDesk는 Direct TCP를 먼저 시도하고, 직접 연결이 안 되면 암호화된 rendezvous relay로 제어를 연결하며 가능한 경우 영상은 암호화된 UDP P2P로 전송합니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","Direct TCP가 실패하면 relay 제어와 UDP P2P 영상을 자동으로 시도합니다.","외부망에서도 Direct TCP를 원할 때만 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:kr({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 Clients, mini PCs, Mac minis, and development 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 Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit Client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","The Hub-hosted Codex Agent turns instructions into approved LiveDesk tool calls and shows progress and results for each computer."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"LiveDesk tries Direct TCP first; if direct access fails, control uses the encrypted rendezvous relay and video uses encrypted UDP P2P when available.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server.","Relay control and UDP P2P video are attempted automatically after Direct TCP fails.","Forward TCP 5197 or configure VPN/IP allowlists only when Direct TCP is required across networks.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:kr({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、mini PC、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. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","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、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"LiveDesk は Direct TCP を先に試し、失敗した場合は暗号化 rendezvous relay で制御し、可能なら映像に暗号化 UDP P2P を使います。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は設定済み rendezvous server へ outbound 接続できる必要があります。","Direct TCP 失敗後は relay 制御と UDP P2P 映像を自動的に試します。","ネットワーク越しに Direct TCP が必要な場合だけ TCP 5197 の転送または VPN/IP allowlist を設定します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":kr({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、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. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","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 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"LiveDesk 会先尝试 Direct TCP;直连失败时,控制改用加密 rendezvous relay,视频在可用时使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接。","Direct TCP 失败后会自动尝试 relay 控制和 UDP P2P 视频。","只有跨网络需要 Direct TCP 时才转发 TCP 5197 或配置 VPN/IP 白名单。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":kr({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、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. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","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、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"LiveDesk 會先嘗試 Direct TCP;直連失敗時,控制改用加密 rendezvous relay,影像在可用時使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線。","Direct TCP 失敗後會自動嘗試 relay 控制與 UDP P2P 影像。","只有跨網路需要 Direct TCP 時才轉送 TCP 5197 或設定 VPN/IP allowlist。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:kr({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 equipos de trabajo, mini PC, 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 Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en 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: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"LiveDesk intenta primero Direct TCP; si falla, el control usa el rendezvous relay cifrado y el vídeo usa UDP P2P cifrado cuando está disponible.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado.","Tras fallar Direct TCP se intentan automáticamente control relay y vídeo UDP P2P.","Reenvía TCP 5197 o configura VPN/allowlist de IP solo si necesitas Direct TCP entre redes.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:kr({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, mini PC, 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 Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur 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, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"LiveDesk tente d’abord Direct TCP ; en cas d’échec, le contrôle utilise le relais rendezvous chiffré et la vidéo UDP P2P chiffrée lorsqu’elle est disponible.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent avoir un accès sortant au serveur rendezvous configuré.","Après un échec Direct TCP, le contrôle relay et la vidéo UDP P2P sont tentés automatiquement.","Redirigez TCP 5197 ou configurez VPN/allowlist IP seulement si Direct TCP est requis entre réseaux.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:kr({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte 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. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf 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, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"LiveDesk versucht zuerst Direct TCP; schlägt dies fehl, nutzt die Steuerung das verschlüsselte Rendezvous-Relay und Video nach Möglichkeit verschlüsseltes UDP P2P.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server.","Nach einem Direct-TCP-Fehler werden Relay-Steuerung und UDP-P2P-Video automatisch versucht.","TCP 5197 nur weiterleiten oder VPN/IP-Allowlist einrichten, wenn Direct TCP netzübergreifend nötig ist.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":kr({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, mini PCs, 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 Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em 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 X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"LiveDesk tenta Direct TCP primeiro; se falhar, o controle usa o rendezvous relay criptografado e o vídeo usa UDP P2P criptografado quando disponível.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado.","Após falha no Direct TCP, controle relay e vídeo UDP P2P são tentados automaticamente.","Encaminhe TCP 5197 ou configure VPN/allowlist IP apenas se Direct TCP entre redes for necessário.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:kr({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 Client, mini PC, 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 Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su 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 X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"LiveDesk prova prima Direct TCP; se fallisce, il controllo usa il rendezvous relay cifrato e il video usa UDP P2P cifrato quando disponibile.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono avere accesso in uscita al server rendezvous configurato.","Dopo un errore Direct TCP, controllo relay e video UDP P2P vengono tentati automaticamente.","Inoltra TCP 5197 o configura VPN/allowlist IP solo se serve Direct TCP tra reti.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:kr({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 Client, mini PC, 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 Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di 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 X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"LiveDesk mencoba Direct TCP lebih dulu; jika gagal, kontrol memakai rendezvous relay terenkripsi dan video memakai UDP P2P terenkripsi bila tersedia.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous yang dikonfigurasi.","Setelah Direct TCP gagal, kontrol relay dan video UDP P2P dicoba otomatis.","Forward TCP 5197 atau atur VPN/IP allowlist hanya jika Direct TCP antarjaringan diperlukan.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:kr({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 Client, mini PC, 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 Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên 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 X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"LiveDesk thử Direct TCP trước; nếu thất bại, control dùng rendezvous relay mã hóa và video dùng UDP P2P mã hóa khi khả dụng.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server đã cấu hình.","Sau khi Direct TCP thất bại, relay control và UDP P2P video được thử tự động.","Chỉ forward TCP 5197 hoặc cấu hình VPN/IP allowlist khi cần Direct TCP giữa các mạng.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:kr({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, 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. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน 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 และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"LiveDesk จะลอง Direct TCP ก่อน หากล้มเหลว control จะใช้ rendezvous relay ที่เข้ารหัส และ video จะใช้ UDP P2P ที่เข้ารหัสเมื่อพร้อม",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server ที่ตั้งค่าไว้ได้","หลัง Direct TCP ล้มเหลว ระบบจะลอง relay control และ UDP P2P video อัตโนมัติ","Forward TCP 5197 หรือตั้ง VPN/IP allowlist เฉพาะเมื่อต้องการ Direct TCP ข้าม network","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:kr({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, 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. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","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, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"LiveDesk पहले Direct TCP आज़माता है; विफल होने पर control encrypted rendezvous relay उपयोग करता है और उपलब्ध होने पर video encrypted UDP P2P उपयोग करता है।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Clients और manager को configured rendezvous server तक outbound access चाहिए।","Direct TCP विफल होने के बाद relay control और UDP P2P video अपने आप try होते हैं।","TCP 5197 forward या VPN/IP allowlist तभी सेट करें जब networks के बीच Direct TCP चाहिए।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:kr({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC و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. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على 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 وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يجرب LiveDesk اتصال Direct TCP أولا؛ وإذا فشل يستخدم التحكم rendezvous relay المشفر ويستخدم الفيديو UDP P2P المشفر عند توفره.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous المهيأ.","بعد فشل Direct TCP تتم محاولة relay control وUDP P2P video تلقائيا.","وجه TCP 5197 أو اضبط VPN/IP allowlist فقط عند الحاجة إلى Direct TCP بين الشبكات.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:kr({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 Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda 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. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","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 X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"LiveDesk önce Direct TCP dener; başarısız olursa kontrol şifreli rendezvous relay kullanır ve video mümkün olduğunda şifreli UDP P2P kullanır.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager yapılandırılmış rendezvous servera outbound erişebilmelidir.","Direct TCP başarısız olduktan sonra relay control ve UDP P2P video otomatik denenir.","Ağlar arasında Direct TCP gerekiyorsa TCP 5197 forward et veya VPN/IP allowlist yapılandır.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},yL=Object.entries(jd).map(([t,n])=>({id:t,label:n.languageName}));function bL(){if(typeof navigator>"u")return"en";const t=navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const r=n.toLowerCase();if(jd[n])return n;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const o=r.split("-")[0];if(jd[o])return o}return"en"}function zx({index:t}){const n=t+1;return i.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${n}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"empty-screen",children:[i.jsx(Ar,{size:24}),i.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}const wL=["cpu","gpu","memory","vram","network","disk","temp"];function xL({device:t,slotNumber:n,selected:r,updateIndicator:o,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=oC(t),y=new Map(g.metrics.map(b=>[b.id,b])),w=o?.label||g.label;return i.jsxs("div",{className:`wall-device-list-row state-${g.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:f,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),f())},children:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ar,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:Pa(t)}),i.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),r&&i.jsx(al,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),i.jsxs("span",{className:`wall-device-list-status state-${g.state} ${o?`update-${o.state}`:""}`,role:"gridcell",title:o?.error||w,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:w})]}),wL.map(b=>{const S=y.get(b);return i.jsxs("span",{className:`wall-device-list-metric state-${S?.state||"unknown"}`,role:"gridcell",title:S?`${S.label}: ${S.value} · ${S.detail}`:"Not reported",children:[i.jsx("strong",{children:S?.value||"-"}),i.jsx("small",{children:S?.detail||"not reported"}),S?.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(S.ratio*100)}%`},"aria-hidden":"true"})]},b)}),l&&i.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:i.jsx(HS,{items:l,mode:u})})]})}function SL(t){if(!t)return!1;const n=String(t.platform||"").trim().toLowerCase();return tl(n)&&t.capabilities?.screenRecordingPermission===!1}function tl(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"}function CL(t){const n=String(t||"").trim().toLowerCase();return n==="linux"||n.startsWith("linux ")}function Wg({device:t,frame:n,selected:r,controlEnabled:o,showStatus:l,showDeviceTitle:u=!0,monitorIndex:f,monitorCount:h,onSelect:g,onFocusDevice:y,onOpenControl:w,onCycleMonitor:b,onCanvasReady:S,sendInput:k,remoteModifierState:N,updateIndicator:A,presentationReady:j,showPresentationSpinner:I=!1,remoteDiagnostics:T,diagnosticsMode:_="remote"}){const B=d.useRef(null),F=d.useRef(null),H=d.useRef(0),D=d.useRef(null),K=oC(t),z=["cpu","gpu","memory","vram"].map(ue=>K.metrics.find(_e=>_e.id===ue)).filter(ue=>!!ue),W=Fv(f),q=h>1,V=j??!!n,X=SL(t)&&!V,ve=I&&t.connected&&!V&&!X,J=YI(t,n,W),$=J>=Tp?100:J/Tp*100,P=J>=Tp?Tp/J*100:100,se={"--screen-aspect":J.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,$)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,P)).toFixed(3)}%`},we=d.useCallback(ue=>{B.current=ue,S(t.deviceId,ue)},[t.deviceId,S]),Z=ue=>{const _e=ue.currentTarget.getBoundingClientRect();return pN(ue.clientX,ue.clientY,_e)},Se=ue=>vN(ue,N),ae=d.useCallback(()=>{D.current!==null&&(window.cancelAnimationFrame(D.current),D.current=null)},[]),ye=d.useCallback(()=>{const ue=F.current;if(!ue)return;F.current=null;const _e=Number(ue.input.normalizedX),Ze=Number(ue.input.normalizedY);if(!Number.isFinite(_e)||!Number.isFinite(Ze))return;k(t.deviceId,{...ue.input,normalizedX:_e,normalizedY:Ze})&&(H.current=performance.now())},[t.deviceId,k]),Pe=d.useCallback(()=>{D.current===null&&(D.current=window.requestAnimationFrame(()=>{D.current=null,ye()}))},[ye]);d.useEffect(()=>()=>{ae(),F.current=null},[ae]);const de=(ue,_e)=>{if(!o)return;const Ze={type:_e,monitorIndex:W,...Z(ue),button:cL(ue.button),...Se(ue)};if(_e==="pointermove"){const at=performance.now();F.current={input:Ze},at-H.current>=pI&&(ae(),ye()),Pe();return}F.current&&(ae(),ye()),k(t.deviceId,Ze)},Qe=d.useCallback(ue=>{const _e=document.activeElement;_e instanceof HTMLElement&&ue.contains(_e)&&_e.classList.contains("monitor-cycle-button")&&_e.blur()},[]);return i.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:se,children:i.jsxs("div",{className:`tile-screen ${V?"has-frame":"is-empty"}`,role:"button",tabIndex:o?-1:0,"aria-pressed":r,onClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||g()},onKeyDown:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),g())},onDoubleClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||(ue.preventDefault(),w())},onPointerLeave:ue=>Qe(ue.currentTarget),children:[i.jsx("span",{className:`screen-content ${V?"has-frame":"is-empty"}`,children:i.jsx("canvas",{ref:we,className:`remote-canvas ${V?"has-frame":"is-empty"}`,"data-monitor-index":W,tabIndex:o?0:-1,onPointerDown:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),y(),ue.currentTarget.focus(),ue.currentTarget.setPointerCapture(ue.pointerId),de(ue,"pointerdown"))},onPointerMove:ue=>{o&&ue.preventDefault(),de(ue,"pointermove")},onPointerLeave:ue=>{o&&(de(ue,"pointermove"),ae(),ye())},onPointerUp:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),de(ue,"pointerup"),ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId))},onPointerCancel:ue=>{ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId)},onWheel:ue=>{o&&(ue.preventDefault(),k(t.deviceId,{type:"wheel",monitorIndex:W,...Z(ue),deltaX:ue.deltaX,deltaY:ue.deltaY,...Se(ue)}))},onContextMenu:ue=>o&&ue.preventDefault()},`${t.deviceId}:monitor:${W}`)}),!V&&i.jsx("span",{className:"empty-screen",children:i.jsx(Ar,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:Pa(t),children:Pa(t)}),ve&&i.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Preparing video"})]}),X&&i.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[i.jsx(ga,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"Screen Recording permission required"}),i.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),A&&i.jsxs("span",{className:`wall-update-status state-${A.state}`,role:"status","aria-live":"polite",title:A.error||A.label,children:[A.state==="updated"?i.jsx(_a,{size:20,"aria-hidden":"true"}):A.state==="failed"?i.jsx(rr,{size:22,"aria-hidden":"true"}):A.state==="offline"?i.jsx(eh,{size:22,"aria-hidden":"true"}):i.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),i.jsx("strong",{children:A.label}),A.error?i.jsx("small",{children:A.error}):null]}),l&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`tile-health-pill state-${K.state}`,children:K.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${Pa(t)} status`,children:z.map(ue=>i.jsxs("span",{className:`tile-metric state-${ue.state}`,children:[i.jsx("b",{children:ue.label}),i.jsx("em",{children:ue.value}),ue.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(ue.ratio*100)}%`}})]},ue.id))})]}),T&&i.jsx(HS,{items:T,mode:_}),q&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${Pa(t)} display ${W+1} of ${h}`,onPointerDown:ue=>ue.stopPropagation(),onClick:ue=>ue.stopPropagation(),onDoubleClick:ue=>ue.stopPropagation(),children:[i.jsx("button",{className:"monitor-cycle-button previous",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),b(-1),ue.currentTarget.blur()},title:"Previous display",type:"button",children:i.jsx(n0,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",W+1,"/",h]}),i.jsx("button",{className:"monitor-cycle-button next",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),b(1),ue.currentTarget.blur()},title:"Next display",type:"button",children:i.jsx(Mv,{size:18})})]})]})})}function kL({visible:t}){const n=fI;return d.useEffect(()=>{},[n]),null}function ML({runtimeBaseUrl:t=""}){const{session:n,loading:r}=V1();zM(n?{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}}:null);const{target:o,error:l,refresh:u}=Q1(n),f=d.useMemo(()=>{if(!o?.active)return null;const m=o.expires_at?Date.parse(o.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(m)&&m<=Date.now()?null:o},[o]),h=d.useMemo(()=>Ob(f),[f]),g=Av(),y=t.trim().replace(/\/+$/,""),w=d.useMemo(()=>[...new Set((g?h:[y,...h,Un]).filter(Boolean))],[g,h,y]),[b,S]=d.useState(null),[k]=d.useState(aI),[N,A]=d.useState(!1),[j,I]=d.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[T,_]=d.useState(()=>typeof window<"u"&&vw(window.matchMedia(gw).matches,j,window.matchMedia("(pointer: coarse)").matches));d.useEffect(()=>{if(!g){S(null);return}const m=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),x=()=>I(m.matches||!!window.navigator.standalone),C=E=>{E.preventDefault(),S(E)},R=()=>{S(null),I(!0)};return x(),m.addEventListener("change",x),window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",R),()=>{m.removeEventListener("change",x),window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",R)}},[g]);const B=d.useCallback(async()=>{const m=b;if(!m){k.isIos&&A(!0);return}S(null);try{await m.prompt(),(await m.userChoice).outcome==="accepted"&&I(!0)}catch(x){S(m),console.warn("[LiveDesk] PWA install prompt failed.",x)}},[k.isIos,b]);d.useEffect(()=>{const m=window.matchMedia(gw),x=window.matchMedia("(pointer: coarse)"),C=()=>_(vw(m.matches,j,x.matches));return C(),m.addEventListener("change",C),x.addEventListener("change",C),()=>{m.removeEventListener("change",C),x.removeEventListener("change",C)}},[j]),d.useEffect(()=>{const m=document.documentElement,x=()=>{m.classList.remove("livedesk-mobile-console-active"),m.style.removeProperty("--livedesk-mobile-viewport-height"),m.style.removeProperty("--livedesk-mobile-viewport-top"),m.style.removeProperty("--livedesk-mobile-viewport-width"),m.style.removeProperty("--livedesk-mobile-viewport-left")};if(!T){x();return}m.classList.add("livedesk-mobile-console-active");const C=window.visualViewport;let R=0;const E=()=>{R=0;const Y=DN(C,Math.max(window.innerHeight,document.documentElement.clientHeight),window.innerWidth,j||k.isIos,j||k.isIos||k.isAndroid);m.style.setProperty("--livedesk-mobile-viewport-height",`${Y.height}px`),m.style.setProperty("--livedesk-mobile-viewport-top",`${Y.offsetTop}px`),m.style.setProperty("--livedesk-mobile-viewport-width",`${Y.width}px`),m.style.setProperty("--livedesk-mobile-viewport-left",`${Y.offsetLeft}px`)},G=()=>{R||(R=window.requestAnimationFrame(E))};return E(),C?.addEventListener("resize",G),C?.addEventListener("scroll",G),window.addEventListener("resize",G),window.addEventListener("orientationchange",G),window.addEventListener("pageshow",G),()=>{R&&window.cancelAnimationFrame(R),C?.removeEventListener("resize",G),C?.removeEventListener("scroll",G),window.removeEventListener("resize",G),window.removeEventListener("orientationchange",G),window.removeEventListener("pageshow",G),x()}},[k.isAndroid,k.isIos,T,j]);const[F,H]=d.useState(GI),D=d.useMemo(()=>w.some(m=>!!Yf(m)),[w]),K=g?!!n:!D||F,{status:z,devices:W,error:q,refresh:V,hubBaseUrl:X}=K1(w,K,n?.access_token||""),{entitlement:ve,licensed:J,loading:$,error:P,refresh:se}=Y1(n),[we,Z]=d.useState([]),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(""),[de,Qe]=d.useState(""),[ue,_e]=d.useState(""),[Ze,at]=d.useState(""),[Ee,Ge]=d.useState("idle"),[me,ke]=d.useState(!1),[et,Me]=d.useState(""),[pe,qe]=d.useState(null),Re=d.useRef(null),[st,jt]=d.useState(""),O=d.useRef("");O.current=ue;const[ze,We]=d.useState(!1),[Et,lt]=d.useState([]),ht=d.useRef(null),[Je,be]=d.useState(!1),je=d.useRef(""),Ae=d.useRef(new Map),fe=d.useRef(0),te=d.useRef(!1),ce=d.useRef(""),Ne=d.useRef(null);Ne.current||(Ne.current=LN());const He=d.useRef(document.visibilityState==="visible"),[Ie,Lt]=d.useState({}),Xe=d.useRef({}),ut=d.useRef(new Set),yt=d.useRef(new Map),_t=d.useRef(new Map),[mt,Vt]=d.useState({}),St=d.useMemo(()=>new Set(Object.keys(Ie)),[Ie]),pn=d.useCallback((m,x)=>{if(!m)return;const C={...Xe.current};x?C[m]=x:delete C[m],Xe.current=C,Lt(C)},[]),rn=d.useCallback((m,x)=>{m&&Vt(C=>{if(!!C[m]===x)return C;const R={...C};return x?R[m]=!0:delete R[m],R})},[]),ya=d.useCallback((m,x)=>{m&&_t.current.set(m,{paused:x,expiresAt:Date.now()+MI})},[]),[Ct,gn]=d.useState(""),[en,U]=d.useState(""),[nt,Dt]=d.useState(!1),vn=d.useRef(null),Nr=d.useRef(null);d.useEffect(()=>{Ct==="auth"&&n?.access_token&&gn("")},[Ct,n?.access_token]);const[Ur,Tr]=d.useState(""),[oe,$e]=d.useState(null),tt=d.useRef(null),Pt=d.useRef(0),wn=d.useCallback((m,x,C)=>{const R=String(m||"").trim();if(Tr(R),tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),!R){$e(null);return}const E=++Pt.current;if($e({id:E,message:R,tone:x}),!C)return;const G=window.setTimeout(()=>{$e(Y=>Y?.id===E?null:Y),tt.current===G&&(tt.current=null)},5e3);tt.current=G},[]),Oe=d.useCallback((m,x="info")=>{wn(m,x,!0)},[wn]),it=d.useCallback(m=>{wn(m,"progress",!1)},[wn]);d.useEffect(()=>()=>{tt.current!==null&&window.clearTimeout(tt.current)},[]);const[Nt,bt]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const m=()=>{bt(window.location.pathname.startsWith("/support")?"support":x=>x==="support"?"wall":x)};return window.addEventListener("popstate",m),()=>window.removeEventListener("popstate",m)},[]);const[Gt,ra]=d.useState("large"),[Cn,qn]=d.useState(aL),Qt=pv(Cn),[En,qr]=d.useState(!1),[Ht,Pn]=d.useState(!1),[Ha,sr]=d.useState(!1),[Rr,ir]=d.useState(!1),[Zs,Ds]=d.useState(Date.now),Dn=d.useRef(null);d.useEffect(()=>()=>{Dn.current!==null&&window.clearTimeout(Dn.current)},[]);const[ln,il]=d.useState(bL),[Is,go]=d.useState(!1),[Ai,or]=d.useState(!1),[Pd,za]=d.useState(!1),[Wr,ol]=d.useState(WI),[wt]=d.useState(JI),[_n]=d.useState(tL),[vo]=d.useState(XI),[sn,us]=d.useState(vo.selections),oc=d.useRef({...vo.topologyFingerprints}),Js=d.useRef({}),ll=d.useRef({...vo.selections}),[Bt,jr]=d.useState(null),[yo,ei]=d.useState({}),lr=d.useRef(new Set),[Ni,ti]=d.useState([]),[Hn,cr]=d.useState(Qt),[ni,cl]=d.useState(""),[lc,bo]=d.useState(0),[Gr,Vr]=d.useState(0),[wo,Ls]=d.useState(0),[xo,$a]=d.useState(()=>new Set),cn=d.useRef(new Map),Zn=d.useRef(new Map),Ua=d.useRef(new Map),kn=d.useRef(new Map),Fn=d.useRef(null),qa=d.useRef(new Map),ur=d.useRef(new Set),Wa=d.useRef(new Map),ai=d.useRef(new Map),Aa=d.useRef(new Map),Kr=d.useRef(new Map),Ti=d.useRef(new WeakMap),So=d.useRef(new WeakMap),Ri=d.useRef(""),dr=d.useRef(null),um=d.useRef(Promise.resolve()),uu=d.useRef(0),ji=d.useRef(null),Er=d.useRef(null),cc=d.useRef(""),Na=d.useRef(new Map),ul=d.useRef(null),uc=d.useRef(0),Ps=d.useRef(new Map),du=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),fu=d.useRef(new Map),_d=d.useRef([]),dm=d.useRef(0),[dl,Fd]=d.useState({}),Ei=d.useRef(new Map),[mu,dc]=d.useState({}),pu=d.useRef(null),[Od,Ga]=d.useState(!1),hu=d.useRef(null),hh=d.useRef(0),ri=d.useRef(null),fm=d.useRef(new Map),ds=d.useRef(null),Qr=d.useRef(null),Va=d.useRef(null),si=d.useRef(!1),mm=d.useRef(0),Wn=d.useRef(0),ba=d.useRef(""),Bd=d.useRef(Promise.resolve()),Co=d.useRef(""),At=d.useRef(null),wa=d.useRef(""),ko=d.useRef(null),fl=d.useRef(0),fc=d.useRef(""),ii=d.useRef(new Map),Di=d.useRef(new Map),Ii=d.useRef(performance.now()),_s=d.useRef(new Map),Fs=d.useRef(new Map),Os=d.useRef(new Map),Li=d.useRef(new Map),Mo=d.useRef(new Map),oi=d.useRef(new Map),Dr=d.useRef(document.visibilityState==="visible"),fs=d.useRef(1),gu=d.useRef([]),[Ta,gh]=d.useState(document.visibilityState==="visible"),[ml,vh]=d.useState(0),mc=d.useRef(0),vu=d.useRef(0),Ra=d.useRef(0),Pi=d.useRef(0),yu=d.useRef(0),bu=d.useRef(new Map),pl=d.useRef([]),Hd=d.useRef(new Map),wu=d.useRef(new Map),li=d.useRef(new Map),ci=d.useRef(new Set),_i=d.useCallback(m=>s1(Ti.current,m),[]),Bs=d.useCallback(m=>Dv(So.current,m),[]),ui=d.useCallback((m,x)=>Zb(So.current,m,x),[]),Jn=d.useCallback(m=>{const x=Xb(Ti.current,m);return Xb(So.current,m),x},[]),Yr=d.useCallback((m,x)=>Zb(Ti.current,m,x),[]),Ao=d.useCallback(m=>Er.current===m||Fn.current===m?!0:[cn.current,Zn.current,Ua.current,kn.current,Na.current].some(C=>Array.from(C.values()).some(R=>R===m)),[]),xa=d.useCallback(m=>{m&&(Jn(m),ci.current.add(m),l1(m,{isCurrent:Ao,dispose:bd,schedule:x=>queueMicrotask(()=>{try{x()}finally{ci.current.delete(m)}})}))},[Ao,Jn]),ja=d.useCallback(m=>(Jn(m),lh(m,bd)),[Jn]),Fi=d.useCallback(()=>{const m=Er.current,x=Fn.current,C=[...ci.current];Er.current=null,Fn.current=null,ci.current.clear(),Ti.current=new WeakMap,So.current=new WeakMap,Kr.current.clear(),cc.current="",o1([cn.current,Zn.current,Ua.current,kn.current,Na.current],[m,x,...C],bd),ul.current=null,uc.current=0,qa.current.clear(),ur.current.clear(),Wa.current.clear(),ai.current.clear(),Aa.current.clear(),Ps.current.clear(),fu.current.clear(),_d.current.length=0,Ei.current.clear(),ut.current.clear()},[]);d.useEffect(()=>()=>{Fi()},[Fi]);const ua=d.useCallback((m,x)=>{const C=la(m,x),R=performance.now();ii.current.delete(C),Di.current.delete(C),_s.current.delete(C),Fs.current.delete(C),oi.current.delete(C),li.current.delete(C),Ei.current.delete(C),Ps.current.delete(C),dc(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const G={...E};return delete G[C],G}),Fd(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const G={...E};return delete G[C],G}),m==="control"?(Os.current.delete(C),Li.current.set(C,R)):Mo.current.set(C,R)},[]),[Oi,di]=d.useState(null),[yh,zd]=d.useState(!1),[ty,pm]=d.useState([]),[No,$d]=d.useState("all"),[Ea,hl]=d.useState([]),[ms,pc]=d.useState(!1),[hm,xu]=d.useState(!0),hc=d.useRef(null),Su=d.useRef(null),To=d.useRef(null),gm=d.useRef(null),Cu=d.useRef(!1),Bi=d.useRef(!1),ku=d.useRef(0),Gn=d.useRef(0),ps=d.useRef(0),da=d.useRef(0),gc=d.useRef(0),Ro=d.useRef(""),hs=Nt==="settings",Mu=Nt==="pricing",Ud=Nt==="doc",Au=Nt==="support",Hi=Nt==="share-files",Ka=Nt==="agents",gs=!hs&&!Mu&&!Ud&&!Au&&!Hi&&!Ka,dt=Nt==="control",vc=FN(Nt),Qa=Ta&&Nt==="wall",Ir=d.useRef(Qa);Ir.current=Qa;const Xr=vc&&pl.current.length>0,fr=Ta&&(Nt==="wall"||dt||Xr),Ya=d.useRef(fr);Ya.current=fr;const Lr=Ta&&(dt||Qa),jo=Ta&&(Lr||vc&&(Ee==="connecting"||Ee==="active")),yc=d.useRef({active:fr,epoch:fs.current});yc.current.active!==fr&&(fs.current+=1,yc.current={active:fr,epoch:fs.current}),d.useEffect(()=>{gs||(qr(!1),Pn(!1),sr(!1))},[gs]);const Kt=wt.frameMode==="mode4-h264-atlas",Pr=Ze||_n.frameMode,Vn=Pr!=="mode3-h264-hw"?Math.min(30,_n.fps):_n.fps,un=W.find(m=>m.deviceId===ye),Yt=un?.platform,$i=un?js(un,sn[un.deviceId]):0,Xa=un?ey(un,$i):null,Nu=CL(Yt)?{maxWidth:1280,maxHeight:720}:Ax,fi=Pr!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Ax,bc={maxWidth:Math.min(fi.maxWidth,Nu.maxWidth,_n.maxWidth),maxHeight:Math.min(fi.maxHeight,Nu.maxHeight,_n.maxHeight)},vs={maxWidth:Xa?.width?Math.min(bc.maxWidth,Xa.width):bc.maxWidth,maxHeight:Xa?.height?Math.min(bc.maxHeight,Xa.height):bc.maxHeight};d.useEffect(()=>{if(z?.started){if(!n?.access_token){rt("/api/remote/license",{method:"DELETE"},X).catch(()=>{});return}rt("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},X).catch(m=>{console.warn("[LiveDesk] Hub license sync failed",m)})}},[ve?.updated_at,X,n?.access_token,z?.started]),d.useEffect(()=>{!n?.access_token||!z?.started||z.runtimeRole!=="hub"||!z.deviceId||(async()=>{try{const{data:m,error:x}=await $t.rpc("register_livedesk_device",{p_device_id:z.deviceId,p_device_name:z.deviceName||z.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:z.managerVersion||z.managerPackage||""}),C=Array.isArray(m)?m[0]:m;(x||C?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",x||C?.reason||"unknown-error")}catch(m){console.warn("[LiveDesk] Hub device role registration failed",m)}})()},[n?.access_token,z?.deviceId,z?.deviceName,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started]);const pt=d.useMemo(()=>W.filter(m=>m.connected),[W]);d.useEffect(()=>{const m={...Xe.current},x=Date.now();let C=!1;Vt(R=>{const E={...R};let G=!1;for(const Y of W){const ee=String(Y.liveCapturePause?.token||"").trim(),ie=_t.current.get(Y.deviceId);if(ie)if((ie.paused?!!ee:!ee)||ie.expiresAt<=x)_t.current.delete(Y.deviceId);else continue;const re=!!ee&&(Y.liveCapturePause?.captureStopConfirmed!==!0||Y.liveCapturePause?.phase==="stop-unconfirmed");!!E[Y.deviceId]!==re&&(G=!0,re?E[Y.deviceId]=!0:delete E[Y.deviceId])}return G?E:R});for(const R of W){const E=String(R.liveCapturePause?.token||"").trim(),G=String(m[R.deviceId]||""),Y=_t.current.get(R.deviceId);if(Y)if((Y.paused?!!E:!E)||Y.expiresAt<=x)_t.current.delete(R.deviceId);else continue;E&&E!==G?(m[R.deviceId]=E,C=!0):!E&&G&&(delete m[R.deviceId],yt.current.delete(R.deviceId),C=!0)}C&&(Xe.current=m,Lt(m))},[W]);const Ui=No==="all"?pt.length:Ea.filter(m=>pt.some(x=>x.deviceId===m)).length,qd=d.useMemo(()=>pt.reduce((m,x)=>Math.max(m,Hx(x.slotNumber)),0),[pt]),Eo=Math.max(rI,pt.length,qd),mi=d.useMemo(()=>{const m=Array(Eo).fill(null),x=[];for(const C of pt){const R=Hx(C.slotNumber);R>0&&R<=Eo&&!m[R-1]?m[R-1]=C:x.push(C)}for(const C of x){const R=m.findIndex(E=>!E);R<0?m.push(C):m[R]=C}return m},[pt]),qi=d.useMemo(()=>mi.flatMap((m,x)=>m?[{device:m,slotNumber:x+1}]:[]),[mi]),Zr=d.useMemo(()=>pt.map(m=>m.deviceId),[pt]),mr=d.useMemo(()=>new Set(we),[we]),In=d.useMemo(()=>pt.filter(m=>mr.has(m.deviceId)),[pt,mr]),Wi=d.useMemo(()=>W.find(m=>m.deviceId===Se)||In[0]||null,[W,Se,In]),Sa=d.useMemo(()=>W.find(m=>m.deviceId===ye)||null,[ye,W]),Da=Sa?js(Sa,sn[Sa.deviceId]):0,De=dt?Sa:Wi,Gi=d.useMemo(()=>new Set(Ea),[Ea]),Ca=d.useMemo(()=>No==="all"?pt.map(m=>m.deviceId):pt.filter(m=>Gi.has(m.deviceId)).map(m=>m.deviceId),[pt,Gi,No]),Tu=De?Op(De,"control"):!1,Ru=tl(De?.platform)&&(De?.capabilities?.controlPermission===!1||De?.capabilities?.accessibilityPermission===!1),ys=De?Op(De,"audio")||Op(De,"remoteAudio"):!1,Do=(Array.isArray(De?.capabilities?.agentTools)?De.capabilities.agentTools.map(String):[]).includes("system.power"),Ut=J?ve?.plan==="pro"?"pro":"ltd":"free",ju=Xc[Ut],Io=ju.limit,pr=d.useMemo(()=>new Set(zN(pt,Io)),[Io,pt]),Wd=!De||pr.has(De.deviceId),gl=Ut==="free",Xt=Wd,vl=Ut==="ltd"?`Plus includes up to ${Uf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${$f} Clients. Upgrade to Plus for ${Uf} devices and no ads.`,vm=Ut==="free",bs=Xt&&!!De&&Tu,Eu=Xt&&!!De&&ys,ws=d.useMemo(()=>dt?De?[De]:[]:In.length>0?In:De?[De]:[],[De,In,dt]),Ia=d.useMemo(()=>ws.filter(m=>pr.has(m.deviceId)),[pr,ws]),Lo=Ia.some(m=>String(Ie[m.deviceId]||"").startsWith("pending:")||mt[m.deviceId]===!0),hr=!(Ia.length>0&&Ia.every(m=>{const x=String(Ie[m.deviceId]||"");return!!x&&!x.startsWith("pending:")&&mt[m.deviceId]!==!0}))||Lo,yl=d.useMemo(()=>mi.filter(m=>!!m?.connected).slice(0,sL(Gt)).map(m=>m.deviceId),[mi,Gt]),Po=d.useMemo(()=>fr?Qa?Kt||Gt==="list"?Zr:wt.visibleOnlyLive?Ni.length>0?Ni:yl:Zr:pl.current.length>0?pl.current:Zr:[],[yl,Kt,Ni,wt.visibleOnlyLive,Zr,fr,Qa,Gt]),Za=d.useMemo(()=>zg(Po.filter(m=>pr.has(m))),[pr,Po]);pl.current=Za;const xs=d.useMemo(()=>Za.filter(m=>m!==ni&&!St.has(m)),[St,Za,ni]),wc=d.useMemo(()=>new Map(pt.map(m=>[m.deviceId,m.platform])),[pt]),Ss=d.useMemo(()=>Object.fromEntries(pt.map(m=>[m.deviceId,String(m.sessionId||"").trim()])),[pt]),La=$N(Kt,Za.length),Ja=d.useMemo(()=>Kt?xs.filter(m=>Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(wc.get(m))})==="atlas"):[],[La,Kt,wc,xs]),gr=d.useMemo(()=>xs.filter(m=>Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(wc.get(m))})==="direct"),[La,Kt,wc,xs]),_o=d.useMemo(()=>{const m=wt.autoStartLive?xs.map(x=>la("wall",x)):[];return jo&&Xt&&de&&pr.has(de)&&(Ee==="connecting"||Ee==="active"||Ee==="warm")&&m.push(la("control",de)),[...new Set(m)].sort()},[jo,de,Ee,Xt,pr,wt.autoStartLive,xs]);d.useEffect(()=>{const m=new Set(Za);$a(x=>{let C=!1;const R=new Set;for(const E of x)m.has(E)?R.add(E):C=!0;return C?R:x})},[Za]);const xc=d.useMemo(()=>{const m=E=>pt.find(G=>G.deviceId===E)||null,x=E=>{const G=m(E);return G?js(G,sn[E]):0},C=(E,G=x(E))=>E===de&&(Ee==="connecting"||Ee==="active"||Ee==="warm")?kn.current.get(E)||Zn.current.get(E)||null:Kt?Na.current.get(E)||cn.current.get(E)||null:cn.current.get(E)||null,R=(E,G=x(E))=>{const Y=m(E);return`${Y?Pa(Y):E} · Monitor ${G+1}`};return{resolveCurrentTarget(){if(dt&&Sa){const ie=Da;return{type:"control",deviceIds:[Sa.deviceId],monitorIndex:ie,label:`${Pa(Sa)} · Monitor ${ie+1}`,sourceCanvas:C(Sa.deviceId,ie),signature:`control:${Sa.deviceId}:${ie}:${_n.frameMode}`}}const E=In.map(ie=>ie.deviceId).filter(ie=>xs.includes(ie)),G=Wi&&xs.includes(Wi.deviceId)?Wi.deviceId:"",Y=E.length>0?E:G?[G]:xs,ee=E.length===0&&!G;if(Y.length===0)return null;if(Y.length===1){const ie=Y[0],re=x(ie);return{type:ee?"wall":E.length>1?"selection":"device",deviceIds:Y,monitorIndex:re,label:ee?"Wall":R(ie,re),sourceCanvas:ee?null:C(ie,re),signature:`${ee?"wall":"device"}:${ie}:${re}:${Kt?"atlas":"direct"}`}}return{type:E.length>1?"selection":"wall",deviceIds:Y,label:E.length>1?`${Y.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${E.length>1?"selection":"wall"}:${Y.join(",")}:${Gt}`}},getDeviceCanvas:C,composeWall(E,G={}){return WD(E.map(Y=>{const ee=x(Y);return{deviceId:Y,label:R(Y,ee),canvas:C(Y,ee)}}),G)}}},[pt,Sa,de,Ee,_n.frameMode,cn,Kt,sn,Da,In,dt,xs,Wi,Gt]),Sc=nI({hubUrl:X,sourceRegistry:xc,onToast:Oe}),Hs=d.useMemo(()=>ON({captureOwnershipActive:jo,localFeatureAccess:Xt,controlSessionDeviceId:de,planAllowed:pr.has(de),sessionState:Ee,controlFocusVisible:dt,presentationCanvasMounted:et===de,wallPresentationVisible:Qa,wallPresentationCanvasMounted:cn.current.has(de)||Na.current.has(de),decoderOwnerExists:kn.current.has(de)})?[de]:[],[jo,de,Ee,Xt,et,pr,dt,Qa]),bl=d.useMemo(()=>zg([...Za,...Hs]),[Hs,Za]),Cc=d.useMemo(()=>_x(wt,Gt),[wt,Gt]),Jr=d.useMemo(()=>_x(wt,"large"),[wt]),kc=UN({mode4Enabled:Kt,directMode4WallEnabled:La,adaptiveFps:Hn,directDeviceCount:gr.length,adaptive:wt.adaptiveLoadShedding}),On=jN({fps:kc,maxWidth:Jr.maxWidth,maxHeight:Jr.maxHeight,quality:wt.quality},T),Mc=GN({deviceCount:Ja.length,targetFps:Hn,adaptive:wt.adaptiveLoadShedding});Kt&&Ja.length>0;const Cs=d.useCallback((m,x,C)=>{if(m.width<=0||m.height<=0)return!1;if(m===x)return!0;const R=C?Math.min(1,C.maxWidth/m.width,C.maxHeight/m.height):1,E=Math.max(1,Math.round(m.width*R)),G=Math.max(1,Math.round(m.height*R));(x.width!==E||x.height!==G)&&(x.width=E,x.height=G);const Y=x.getContext("2d",{alpha:!1});return Y?(Y.imageSmoothingEnabled=!0,Y.imageSmoothingQuality="low",Y.drawImage(m,0,0,m.width,m.height,0,0,x.width,x.height),!0):!1},[]),ks=d.useCallback((m,x)=>{const C=Math.max(0,Number(x.clientWidth||0)),R=Math.max(0,Number(x.clientHeight||0)),E=Math.max(1,Number(window.devicePixelRatio||1)),G=C>0&&R>0?{maxWidth:Math.ceil(C*E),maxHeight:Math.ceil(R*E)}:void 0;return Cs(m,x,G)},[Cs]),_r=d.useCallback((m,x,C)=>{if(!du.current)return;const R=`${m}:${x.deviceId}`,E=fu.current.get(R)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};E.bindingKey=co(x),E.totalPaints+=1,E.lastPaintAt=performance.now(),E.lastFrameSeq=Number(x.frameSeq||0),fu.current.set(R,E);const G=++dm.current,Y={sequence:G,scope:m,deviceId:x.deviceId,bindingKey:E.bindingKey,frameSeq:E.lastFrameSeq,paintedAt:E.lastPaintAt,sourceGapMs:Number(x.sourceGapMs||0),agentSendGapMs:Number(x.agentSendGapMs||0),agentSendDurationMs:Number(x.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(x.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(x.agentFrameAgeMs||0),timestampUs:Number(x.timestampUs||0),queuedForMs:Number(C?.queuedForMs||0),decodedForMs:Number(C?.decodedForMs||0),scheduledForMs:Number(C?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(C?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(C?.interactiveBurstTailHoldCount||0)};_d.current[(G-1)%TI]=Y},[]),vr=d.useCallback(m=>{m&&$a(x=>{if(x.has(m))return x;const C=new Set(x);return C.add(m),C})},[]),es=d.useCallback(m=>{m&&$a(x=>{if(!x.has(m))return x;const C=new Set(x);return C.delete(m),C})},[]),pi=d.useCallback((m,x)=>{if(!x||x.width<=0||x.height<=0)return!1;const C=document.createElement("canvas");if(C.width=x.width,C.height=x.height,!Cs(x,C))return xa(C),!1;const R=Ua.current.get(m);return Ua.current.set(m,C),R&&R!==C&&ja(R),vr(m),!0},[vr,Cs,ja,xa]),zn=d.useCallback(m=>{i1(Ua.current,m,bd)},[]),Vi=d.useCallback((m,x)=>{const C=Ua.current.get(m),R=cn.current.get(m)===x||Na.current.get(m)===x;return Xe.current[m]?(zn(m),!1):!C||!R||C.width<=0||C.height<=0?!1:Cs(C,x)?!0:(zn(m),!1)},[Cs,zn]),zs=d.useCallback((m,x=!1,C)=>{if(Xe.current[m]||!ur.current.has(m))return!1;const R=Math.max(1,Math.min(Qt,Xn.controlWallReuseMaxFps,Vn)),E=performance.now(),G=ai.current.get(m)||0,Y=kn.current.get(m)||Zn.current.get(m),ee=cn.current.get(m)||Na.current.get(m);if(!Y||!ee||!ee.isConnected)return!1;const ie=HN({cadenceCredit:Wa.current.get(m)||0,targetFps:R,sourceFps:Vn,elapsedSincePaintMs:G>0?E-G:0,nowMs:E,scheduledPaintAtMs:Aa.current.get(m)||0,force:x});if(!ie.shouldPaint)return Wa.current.set(m,ie.nextCadenceCredit),!1;const re=Math.max(0,Number(ee.clientWidth||0)),Ve=Math.max(0,Number(ee.clientHeight||0)),Be=Math.max(1,Number(window.devicePixelRatio||1)),Ue=re>0&&Ve>0?{maxWidth:Math.min(Cc.maxWidth,Math.ceil(re*Be)),maxHeight:Math.min(Cc.maxHeight,Math.ceil(Ve*Be))}:Cc;return Cs(Y,ee,Ue)?(Wa.current.set(m,ie.nextCadenceCredit),ie.nextScheduledPaintAtMs>0&&Aa.current.set(m,ie.nextScheduledPaintAtMs),ai.current.set(m,performance.now()),ie.sourceCadencePassthrough&&(Wa.current.delete(m),Aa.current.delete(m)),C&&_r("wall-reuse-visible",C),vr(m),zn(m),!0):!1},[Vn,Cc,vr,Cs,_r,zn,Qt]);d.useEffect(()=>{Ri.current=ni},[ni]);const Ac=d.useCallback((m,x)=>{const C=ri.current;if(!C||C.deviceId!==m)return;const R=Date.now();fm.current.set(m,{...C,source:x,completedAtEpochMs:R,durationMs:Math.max(0,performance.now()-C.startedAt)}),ri.current=null},[]),Fo=d.useCallback((m,x)=>{const C=cn.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(cn.current.set(m,x),C&&C!==x&&xa(C),Xe.current[m]){zn(m),ja(x),es(m);return}Ua.current.get(m)&&Vi(m,x)&&vr(m),zs(m,!0);return}if(C&&Ya.current&&pl.current.includes(m)){pi(m,C),cn.current.delete(m),xa(C);return}cn.current.delete(m),zn(m),xa(C),es(m)},[es,vr,zs,Vi,pi,ja,zn,xa]),Du=d.useCallback((m,x)=>{const C=Zn.current.get(m);if(x){Zn.current.set(m,x),Me(m),C&&C!==x&&xa(C);const R=de===m&&me?kn.current.get(m):null;R&&ks(R,x)&&m===ye&&(Ac(m,"warm-reuse"),Ga(!0)),R&&R!==x&&BN({decodeWidth:R.width,decodeHeight:R.height,presentationCssWidth:x.getBoundingClientRect().width,presentationCssHeight:x.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:vs.maxWidth,sourceHeight:vs.maxHeight})&&(kn.current.set(m,x),xa(R));return}Zn.current.delete(m),Me(R=>R===m?"":R),xa(C)},[Ac,ye,de,me,vs.maxHeight,vs.maxWidth,ks,xa]),Nc=d.useCallback((m,x,C)=>{const R=performance.now(),E=la(m,C.deviceId);let G=C;if(m==="control"&&C.visualChanged){const ie=String(x.inputFeedbackEventId||""),re=Number(x.inputFeedbackInputSeq||0),Ve=Number(x.inputFeedbackIssuedAtEpochMs||0),Be=Number(x.browserReceivedEpochMs||0),Ue=Hd.current.get(C.deviceId)||"",gt=Ve>0?Math.max(0,Date.now()-Ve):Number.POSITIVE_INFINITY;if(ie.length>0&&re>0&&ie!==Ue&><=Bg){const Tt=wu.current.get(C.deviceId)||[];Tt.push(gt),Tt.length>yx&&Tt.splice(0,Tt.length-yx),wu.current.set(C.deviceId,Tt),G={...C,inputFeedbackSeq:re,inputFeedbackMs:gt,inputFeedbackAt:R,inputFeedbackExact:!0,inputFeedbackEventId:ie,inputFeedbackInputType:x.inputFeedbackInputType,inputFeedbackInputToFrameMs:Be>0?Math.max(0,Be-Ve):void 0,inputFeedbackFrameToPaintMs:Be>0?Math.max(0,Date.now()-Be):void 0,inputFeedbackAgentApplyMs:x.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:x.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Tt.length,inputFeedbackP50Ms:Bf(Tt,.5),inputFeedbackP95Ms:Bf(Tt,.95)},Hd.current.set(C.deviceId,ie),bu.current.set(C.deviceId,re)}else if(!ie){const Tt=aN(C.deviceId),an=bu.current.get(C.deviceId)||0,Ln=Tt?R-Tt.sentAt:Number.POSITIVE_INFINITY;Tt&&Tt.inputSeq>an&&Ln<=Bg&&(G={...C,inputFeedbackSeq:Tt.inputSeq,inputFeedbackMs:Math.max(0,Ln),inputFeedbackAt:R,inputFeedbackExact:!1},bu.current.set(C.deviceId,Tt.inputSeq))}}Di.current.set(E,R),oi.current.delete(E);const Y=Ps.current.get(E)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:R,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},ee=co(x);Y.bindingKey!==ee&&(Y.bindingKey=ee,Y.lastAt=void 0,Y.lastFrameSeq=void 0,Y.sampleChangedFrames=0,Y.sampleDecoderInputBase=Number(C.decoderInputCount||0),Y.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Np(Y,R)),m==="control"&&G.inputFeedbackMs===void 0&&Y.lastInfo?.inputFeedbackMs!==void 0&&Y.lastInfo.inputFeedbackAt!==void 0&&R-Y.lastInfo.inputFeedbackAt<=Bg&&(G={...G,inputFeedbackSeq:Y.lastInfo.inputFeedbackSeq,inputFeedbackMs:Y.lastInfo.inputFeedbackMs,inputFeedbackAt:Y.lastInfo.inputFeedbackAt,inputFeedbackExact:Y.lastInfo.inputFeedbackExact,inputFeedbackEventId:Y.lastInfo.inputFeedbackEventId,inputFeedbackInputType:Y.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:Y.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:Y.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:Y.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:Y.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Y.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:Y.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:Y.lastInfo.inputFeedbackP95Ms}),Y.totalFrames+=1,Y.sampleFrames+=1,Nx(Y,R,G.frameSeq),G.visualChanged&&(Y.totalChangedFrames+=1,Y.sampleChangedFrames+=1),Y.lastInfo=G,Ps.current.set(E,Y)},[]),wl=d.useCallback((m,x)=>{if(Xe.current[m.deviceId]||Ri.current===m.deviceId)return;Nc("wall",m,x);const C=me&&de===m.deviceId,R=cn.current.get(m.deviceId)||Na.current.get(m.deviceId);du.current&&!dt&&!C&&R?.isConnected&&_r("wall-visible",m,x),m.kind==="live"&&(vr(m.deviceId),zn(m.deviceId)),Ri.current!==m.deviceId&&!C&&(ur.current.delete(m.deviceId),Wa.current.delete(m.deviceId),ai.current.delete(m.deviceId),Aa.current.delete(m.deviceId))},[de,me,vr,Nc,_r,zn,dt]),Iu=d.useCallback((m,x)=>{if(Xe.current[m.deviceId]||Qn(Va.current,At.current)||!kg(m,At.current))return;Nc("control",m,x),jt(Y=>Y&&"");const C=kn.current.get(m.deviceId),R=Zn.current.get(m.deviceId);let E=!1;C&&C.width>0&&C.height>0&&(R&&dt&&m.deviceId===ye&&(E=ks(C,R),E&&_r("control-visible",m,x)),qa.current.set(m.deviceId,tu(m)),ur.current.add(m.deviceId),m.deviceId===de&&(ke(!0),Ge(Y=>Y==="connecting"?"active":Y)),zs(m.deviceId,!1,m));const G=hu.current;!G||!AI(G,m)||!E||(Ac(m.deviceId,"fresh-frame"),Ga(!0))},[Ac,ye,de,zs,ks,Nc,_r,dt]),sa=d.useCallback((m,x)=>{const C=performance.now(),R=la(m,x.deviceId);ii.current.set(R,C),Fs.current.delete(R),li.current.delete(R),m==="control"?Os.current.delete(R):Mo.current.delete(R);const E=Ei.current.get(R)||{totalFrames:0,sampleFrames:0,sampleStartedAt:C,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},G=co(x);if(E.bindingKey!==G&&(E.bindingKey=G,E.lastAt=void 0,E.lastFrameSeq=void 0,E.lastContentHash=void 0,E.sampleBytes=0,E.sampleH264Frames=0,E.sampleTinyFrames=0,E.sampleRepeatedFrames=0,E.sourceSendIntervalsMs.length=0,Np(E,C)),E.totalFrames+=1,E.sampleFrames+=1,E.sampleBytes+=Math.max(0,Number(x.byteLength||0)),String(x.frameMode||x.mode||x.codec||x.mimeType||"").toLowerCase().includes("h264")){E.sampleH264Frames+=1,Number(x.byteLength||0)<=xI&&(E.sampleTinyFrames+=1);const re=String(x.contentHash||"");re&&E.lastContentHash===re&&(E.sampleRepeatedFrames+=1),E.lastContentHash=re}const ie=Number(x.agentSendGapMs||0);ie>0&&ie<1e3&&tC(E.sourceSendIntervalsMs,ie),E.lastFrame=tu(x),Nx(E,C,x.frameSeq),Ei.current.set(R,E)},[]);d.useEffect(()=>{const m=new Set(_o);for(const R of Ps.current.keys())m.has(R)||Ps.current.delete(R);for(const R of Ei.current.keys())m.has(R)||Ei.current.delete(R);const x=R=>{const E=Object.entries(R).filter(([G])=>m.has(G));return E.length===Object.keys(R).length?R:Object.fromEntries(E)};if(Fd(x),dc(x),m.size===0)return;const C=window.setInterval(()=>{const R=performance.now(),E={},G={};for(const Y of m){const ee=Ps.current.get(Y);if(ee){const Be=Math.max(1,R-ee.sampleStartedAt);E[Y]={bindingKey:ee.bindingKey||"",totalFrames:ee.totalFrames,totalChangedFrames:ee.totalChangedFrames,framesPerSecond:ee.sampleFrames*1e3/Be,changedFramesPerSecond:ee.sampleChangedFrames*1e3/Be,averageIntervalMs:ee.intervalCount>0?ee.intervalSumMs/ee.intervalCount:0,minIntervalMs:Number.isFinite(ee.minIntervalMs)?ee.minIntervalMs:0,maxIntervalMs:ee.maxIntervalMs,p95IntervalMs:Bf(ee.intervalSamplesMs,.95),intervalCount:ee.intervalCount,seqGapCount:ee.seqGapCount,maxSeqGap:ee.maxSeqGap,decoderInputFps:Math.max(0,(Number(ee.lastInfo?.decoderInputCount||0)-ee.sampleDecoderInputBase)*1e3/Be),decoderOutputFps:Math.max(0,(Number(ee.lastInfo?.decoderOutputCount||0)-ee.sampleDecoderOutputBase)*1e3/Be),sampleMs:Be,lastInfo:ee.lastInfo},ee.sampleDecoderInputBase=Number(ee.lastInfo?.decoderInputCount||0),ee.sampleDecoderOutputBase=Number(ee.lastInfo?.decoderOutputCount||0),ee.sampleChangedFrames=0,Np(ee,R)}const ie=Ei.current.get(Y);if(!ie)continue;const re=Math.max(1,R-ie.sampleStartedAt),Ve=ie.lastFrame?tu(ie.lastFrame):void 0;ie.lastFrame=Ve,G[Y]={totalFrames:ie.totalFrames,framesPerSecond:ie.sampleFrames*1e3/re,averageIntervalMs:ie.intervalCount>0?ie.intervalSumMs/ie.intervalCount:0,minIntervalMs:Number.isFinite(ie.minIntervalMs)?ie.minIntervalMs:0,maxIntervalMs:ie.maxIntervalMs,p95IntervalMs:Bf(ie.intervalSamplesMs,.95),intervalCount:ie.intervalCount,seqGapCount:ie.seqGapCount,maxSeqGap:ie.maxSeqGap,averageFrameBytes:ie.sampleFrames>0?ie.sampleBytes/ie.sampleFrames:0,tinyFrameRatio:ie.sampleH264Frames>0?ie.sampleTinyFrames/ie.sampleH264Frames:0,repeatedFrameRatio:ie.sampleH264Frames>0?ie.sampleRepeatedFrames/ie.sampleH264Frames:0,sourceSendAverageMs:ie.sourceSendIntervalsMs.length>0?ie.sourceSendIntervalsMs.reduce((Be,Ue)=>Be+Ue,0)/ie.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Bf(ie.sourceSendIntervalsMs,.95),sourceSendSampleCount:ie.sourceSendIntervalsMs.length,sampleMs:re,lastFrame:Ve},ie.sampleBytes=0,ie.sampleH264Frames=0,ie.sampleTinyFrames=0,ie.sampleRepeatedFrames=0,ie.sourceSendIntervalsMs.length=0,Np(ie,R)}Fd(E),dc(G)},1e3);return pu.current=C,()=>{window.clearInterval(C),pu.current===C&&(pu.current=null)}},[_o]);const Fr=d.useCallback(m=>{const x=m.deviceId,C=co(m);if(Xe.current[x]||Ri.current===x||m.currentGenerationVerified!==!0||Kr.current.get(x)!==C)return;sa("wall",m);const R=cn.current.get(x);if(!R)return;const E=_i(R),G=Bs(R),Y=()=>cn.current.get(x)!==R||!Yr(R,E)||!!Xe.current[x]||Ri.current===x||Kr.current.get(x)!==C,ee=()=>Y()||!ui(R,G),ie=VN(Kt,wt.h264DecodeAcceleration);wg(R,m,ee,wl,ie.acceleration,ie.latencyMode,Y).catch(()=>{})},[_i,ui,Yr,Bs,wl,Kt,sa,wt.h264DecodeAcceleration]),hi=d.useCallback(m=>{const x=m.deviceId;if(Xe.current[x]||Qn(Va.current,At.current)||!kg(m,At.current))return;let C=kn.current.get(x);if(!C){const Ue=Zn.current.get(x),gt=Fn.current;C=Ue||gt||document.createElement("canvas"),Ue&>&>!==Ue&&ja(gt),Fn.current=null,C!==Ue&&C.setAttribute("aria-hidden","true"),kn.current.set(x,C)}const R=C,E=m,G=_i(R),Y=Bs(R),ee=()=>kn.current.get(x)!==R||!Yr(R,G)||!!Xe.current[x]||!kg(E,At.current),ie=()=>ee()||!ui(R,Y),re=O.current,Ve=String(m.frameMode||m.mode||m.codec||m.mimeType||"").toLowerCase().includes("h264");Ve||sa("control",m);const Be=wg(R,m,ie,Iu,_n.h264DecodeAcceleration,"interactive",ee);Ve&&sa("control",m),Be.catch(Ue=>{O.current!==re||kn.current.get(x)!==R||!ui(R,Y)||ee()||de!==x||jt(Ue instanceof Error?Ue.message:String(Ue||"Control H.264 decode failed"))})},[_i,ui,Yr,Bs,de,_n.h264DecodeAcceleration,Iu,sa,ja]),Gd=d.useCallback(m=>{const x=Er.current;Er.current=m,x&&x!==m&&xa(x),mc.current=0,vu.current=0,Ra.current=0,Pi.current=0,yu.current=0,uc.current=0},[xa]),Oo=d.useCallback(()=>{const m=new Set,x=Er.current,C=ul.current;if(!x||!C||x.width<=0||x.height<=0||uc.current!==C.layoutVersion)return m;for(const R of C.tiles){if(Xe.current[R.deviceId])continue;const E=Na.current.get(R.deviceId);if(!E||R.width<=0||R.height<=0)continue;const G=Math.max(1,Math.round(R.width)),Y=Math.max(1,Math.round(R.height)),ee=SI,ie=CI;(E.width!==ee||E.height!==ie)&&(E.width=ee,E.height=ie);const re=E.getContext("2d",{alpha:!1});if(re){re.imageSmoothingEnabled=!0,re.imageSmoothingQuality="high";try{re.drawImage(x,Math.round(R.x),Math.round(R.y),G,Y,0,0,ee,ie),m.add(R.deviceId)}catch{}}}return m},[]),Ki=d.useCallback((m,x)=>{const C=Na.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(Na.current.set(m,x),C&&C!==x&&xa(C),Xe.current[m]){zn(m),ja(x),es(m);return}Ua.current.get(m)&&Vi(m,x)&&vr(m),window.requestAnimationFrame(()=>{Oo().has(m)&&zn(m)}),window.requestAnimationFrame(()=>zs(m,!0));return}Na.current.delete(m),zn(m),xa(C),es(m)},[es,vr,Oo,zs,Vi,pi,ja,zn,xa]),yr=d.useCallback((m,x)=>{Ra.current=performance.now(),uc.current=Number(m.layoutVersion||0),Oo();const C=ul.current?.tiles||[],R=C.length>0?Math.round(m.byteLength/C.length):m.byteLength;for(const E of C){if(Xe.current[E.deviceId])continue;const G={...m,deviceId:E.deviceId,width:E.width,height:E.height,sourceWidth:E.width,sourceHeight:E.height,byteLength:R};wl(G,{...x,deviceId:E.deviceId,width:E.width,height:E.height,byteLength:R}),Ri.current===E.deviceId&&zs(E.deviceId,!0)}},[wl,Oo,zs]),Kn=d.useCallback(m=>{const x=performance.now();mc.current<=0&&(mc.current=x),vu.current=x;const C=Er.current;if(!C)return;const R=co(m);cc.current!==R&&(cc.current=R,Jn(C));const E=_i(C),G=Bs(C),Y=()=>Er.current!==C||cc.current!==R||!Yr(C,E),ee=()=>Y()||!ui(C,G),ie=ul.current?.tiles||[],re=ie.length>0?Math.round(m.byteLength/ie.length):m.byteLength;for(const Ve of ie)Xe.current[Ve.deviceId]||sa("wall",{...m,deviceId:Ve.deviceId,width:Ve.width,height:Ve.height,sourceWidth:Ve.width,sourceHeight:Ve.height,byteLength:re});wg(C,m,ee,yr,void 0,"smooth",Y).catch(()=>{})},[_i,ui,Yr,Bs,yr,sa,Jn]),Tc=d.useCallback(m=>{if(m.streamPurpose!=="wall"||Xe.current[m.deviceId])return;const x=co(m);Kr.current.get(m.deviceId)!==x&&(Kr.current.set(m.deviceId,x),Jn(cn.current.get(m.deviceId)))},[Jn]),gi=d.useMemo(()=>({fps:On.fps,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:On.quality,mode:Kt?"mode3-h264-hw":wt.frameMode,frameMode:Kt?"mode3-h264-hw":wt.frameMode,streamPurpose:"wall",configurationRefreshMs:dI,forceRestart:ml>0,forceRestartToken:ml>0?`document-presentation-resume-${ml}`:"",restartReason:ml>0?"document-presentation-resume":"",connectionSessionIds:Ss,monitorSelections:sn,onFrame:Fr,onStreamReady:Tc}),[Ss,ml,Fr,Tc,Kt,sn,wt.frameMode,On.fps,On.maxHeight,On.maxWidth,On.quality]),Ft=d.useCallback(m=>{const x=At.current;if(Xe.current[m.deviceId]||!x||Qn(Va.current,x)||x.deviceId!==m.deviceId||m.deviceId!==de||m.streamPurpose!=="control"||m.monitorIndex!==Da)return;const C=pt.find(E=>E.deviceId===m.deviceId);if(!C?.sessionId||C.sessionId!==m.sessionId)return;const R=Re.current;(!R||co(R)!==co(m))&&Jn(kn.current.get(m.deviceId)),At.current=Cg(x.deviceId,x.transitionGeneration,m),Re.current=m,qe(m),Ge(E=>E==="connecting"?"active":E)},[pt,de,Jn,Da]);d.useEffect(()=>{Jn(kn.current.get(de)),Re.current=null,qe(null)},[de,ue,Pr,Jn,Da]);const on=ue?`${ue}-monitor-${Da}`:"",ea=d.useMemo(()=>({fps:Vn,maxWidth:vs.maxWidth,maxHeight:vs.maxHeight,quality:_n.quality,mode:Pr,frameMode:Pr,streamPurpose:"control",forceRestart:on!=="",forceRestartToken:on,restartReason:on?"control-session-or-monitor-change":"",connectionSessionIds:Ss,monitorSelections:sn,onFrame:hi,onStreamReady:Ft}),[Ss,on,_n.quality,hi,Vn,Pr,vs.maxHeight,vs.maxWidth,Ft,sn]),{frames:Rc,state:$s,error:Qi,stats:Us,restartLive:Yi,reconnectLive:Bo}=iw(gr,wt.autoStartLive&&gr.length>0,X,gi);d.useEffect(()=>{const m=new Set(gr);for(const x of Kr.current.keys())m.has(x)||(Kr.current.delete(x),Jn(cn.current.get(x)))},[gr,Jn]);const{frame:xl,layout:yn,state:jc,stats:Vd,refreshInputs:Kd}=lN(Ja,Kt&&wt.autoStartLive&&Ja.length>0,X,{fps:Xn.atlasOutputFps,inputFps:Mc,width:1920,height:1080,tileWidth:Jr.maxWidth,tileHeight:Jr.maxHeight,captureDeviceIds:Ja,connectionSessionIds:Ss,monitorSelections:sn,onFrame:Kn});d.useEffect(()=>{ul.current=yn,yn&&window.requestAnimationFrame(Oo)},[yn,Oo]),d.useEffect(()=>{if(!Kt||jc!=="open"){mc.current=0,vu.current=0,Ra.current=0;return}const m=window.setInterval(()=>{const x=Er.current,C=performance.now();if(!x||document.visibilityState!=="visible"||C-Ii.current<Og)return;const R=vu.current,E=mc.current;if(R<=0||E<=0||C-R>500)return;const G=Ra.current||E,Y=C-G;if(Y>=gI&&C-yu.current>=yI){wd(x)&&(yu.current=C,Pi.current=C);return}Y>=hI&&C-Pi.current>=vI&&JA(x)&&(Pi.current=C)},250);return()=>window.clearInterval(m)},[jc,Kt]);const{frames:Sl,state:Qd,error:Ho,stats:Yd,restartLive:Cl,reconnectLive:ia}=iw(Hs,Hs.length>0,X,ea);d.useEffect(()=>{const m=ll.current,x=new Set([...Object.keys(m),...Object.keys(sn)]);for(const C of x){const R=Math.max(0,Math.floor(Number(m[C])||0)),E=Math.max(0,Math.floor(Number(sn[C])||0));R!==E&&(Kr.current.delete(C),Jn(cn.current.get(C)),Jn(kn.current.get(C)),Jn(Na.current.get(C)),ua("wall",C),ua("control",C),wd(cn.current.get(C)||null),wd(kn.current.get(C)||null))}x.size>0&&(Jn(Er.current),wd(Er.current)),ll.current={...sn}},[sn,ua,Jn]);const Mn=d.useMemo(()=>{const m=(C,R)=>{const E=pt.find(Y=>Y.deviceId===C),G=E?js(E,sn[C]):0;return!Number.isFinite(Number(R.monitorIndex))||Number(R.monitorIndex)===G},x=new Map;for(const[C,R]of Rc.entries())m(C,R)&&x.set(C,R);if(Kt&&xl&&Ja.length>0){const C=new Map((yn?.tiles||[]).map(E=>[E.deviceId,E])),R=Math.max(1,C.size);for(const E of Ja){const G=C.get(E);G&&x.set(E,{...xl,deviceId:E,width:G.width,height:G.height,sourceWidth:G.width,sourceHeight:G.height,byteLength:Math.round(xl.byteLength/R)})}}for(const[C,R]of Sl.entries())m(C,R)&&x.set(C,R);for(const C of Po){if(!ur.current.has(C)||x.has(C))continue;const R=qa.current.get(C);R&&m(C,R)&&x.set(C,R)}return x},[xl,yn,pt,Sl,Ja,Kt,sn,Rc,Po,wo]),kl=dt&&Hs.length>0?Qd:Ja.length>0?jc:$s,Xi=dt&&Hs.length>0?Yd:Ja.length>0?Vd:Us;d.useCallback((m,x="browser-stale")=>{const C=Yi(m,x),R=Cl(m,x);return C||R},[Cl,Yi]),d.useEffect(()=>{Kt&&Ja.length>0&&!dt&&Kd()},[Ja.length,Kt,Kd,dt]);const vi=d.useCallback((m,x,C)=>{const R=x==="control"?kn.current.get(m)||null:cn.current.get(m)||null;if(!R)return!1;wd(R);const E=performance.now();return oi.current.set(la(x,m),E),!0},[]),Ml=d.useCallback(m=>{if(Pr!=="mode3-h264-hw"||!de||Ze)return!1;const x=pt.find(ee=>ee.deviceId===de)||Sa,C=String(x?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const R="mode5-lzo-delta",E=la("control",de),G=performance.now();Li.current.set(E,G),ii.current.delete(E),Di.current.delete(E),_s.current.delete(E),Os.current.delete(E),li.current.delete(E),wd(kn.current.get(de)||null),ia([de],"control-decode-fallback"),at(R),_e(`control-${R}-fallback-${de}-${Date.now()}`),ke(!1),Ga(!1);const Y=m==="no first frame"||m==="control-first-frame-timeout";return jt(ee=>ee||(Y?`Control frame transport timeout; retrying Control with Mode 5 (${m})`:`H.264 decode failed; retrying Control with Mode 5 (${m})`)),Ge("connecting"),!0},[pt,Sa,de,Ze,Pr,ia]);d.useEffect(()=>{const m=dt?Sa:null;if(m){hu.current={deviceId:m.deviceId,monitorIndex:Da,frameMode:Pr,startedAtEpochMs:Date.now()},Ga(de===m.deviceId&&me);return}hu.current=null,Ga(!1)},[Sa?.sessionId,ye,de,me,Pr,Da,dt]);const qs=d.useCallback(async(m,x)=>{const C=String(x.streamId||"").trim(),R=String(x.streamPurpose||"").trim(),E=String(x.sessionId||"").trim(),G=String(x.commandId||"").trim(),Y=Number(x.captureGeneration||0),ee=Number(x.monitorIndex??-1);if(!C||!["wall","atlas"].includes(R)||!E||!G||!Number.isSafeInteger(Y)||Y<=0||!Number.isSafeInteger(ee)||ee<0)throw new Error("wall-start-owner-incomplete");const ie=performance.now()+3e3;for(;;){const re=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:R,expectedSessionId:E,expectedCommandId:G,expectedCaptureGeneration:Y,expectedMonitorIndex:ee,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},X);if(re?.ok===!1)throw new Error(re.error||"revoked-wall-start-stop-failed");if(re?.captureStopConfirmed===!0||re?.alreadyStopped===!0||re?.staleOwner===!0)return re;if(re?.presentationOwnerActive===!0||re?.retainedForPresentation===!0){if(Dr.current&&Ya.current)return re;if(performance.now()<ie){await new Promise(Ve=>window.setTimeout(Ve,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[X]),Ws=d.useCallback(async m=>{if(Xe.current[m])throw new Error("LIVE_CAPTURE_PAUSED");if(!Dr.current||!Ya.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const x=fs.current,C=W.find(Y=>Y.deviceId===m);Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(C?.platform)});const R=C?js(C,sn[m]):0,E={fps:On.fps,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:On.quality,mode:Kt?"mode3-h264-hw":wt.frameMode,frameMode:Kt?"mode3-h264-hw":wt.frameMode,streamPurpose:"wall",monitorIndex:R},G=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/start`,{method:"POST",body:JSON.stringify(E)},X);if(G?.ok===!1)throw new Error(G.error||"wall-stream-start-failed");return x!==fs.current||!Dr.current||!Ya.current?(await qs(m,G),{...G,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):G},[Mc,W,La,X,Kt,sn,qs,wt.frameMode,Jr.maxHeight,Jr.maxWidth,On.fps,On.maxHeight,On.maxWidth,On.quality]),Lu=d.useCallback(async m=>{const x=W.find(R=>R.deviceId===m);Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(x?.platform)});const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},X);if(C?.ok===!1)throw new Error(C.error||"wall-stream-stop-failed");return C},[W,La,X,Kt]),Pu=d.useCallback(async(m,x="control-session-stop")=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:x})},X);if(C?.ok===!1)throw new Error(C.error||"control-stream-stop-failed");return C},[X]),er=d.useCallback((m,x={})=>{Va.current?.deviceId===m&&(Va.current=null);const C=kn.current.get(m);if(C){const E=Ua.current.has(m)||cn.current.has(m)||Na.current.has(m);x.preservePresentation!==!1&&!E&&pi(m,C),kn.current.delete(m),ja(C),!(Zn.current.get(m)||cn.current.get(m)||Na.current.get(m))&&!Fn.current&&(Fn.current=C)}const R=Zn.current.get(m);R&&bd(R),qa.current.delete(m),ur.current.delete(m),Wa.current.delete(m),ai.current.delete(m),Aa.current.delete(m)},[pi,ja]),Ec=d.useCallback(m=>{const x=[la("wall",m),la("control",m)];for(const C of x){const R=Ei.current.get(C);R?.lastFrame&&(R.lastFrame=tu(R.lastFrame))}dc(C=>{let R=!1;const E={...C};for(const G of x){const Y=C[G];!Y?.lastFrame||Y.lastFrame.payload.byteLength===0||(E[G]={...Y,lastFrame:tu(Y.lastFrame)},R=!0)}return R?E:C})},[]),_u=d.useCallback(m=>{Kr.current.delete(m),zn(m),er(m,{preservePresentation:!1});const x=new Set;for(const C of[Zn.current.get(m),cn.current.get(m),Na.current.get(m)])C&&x.add(C);for(const C of x)ja(C);es(m),de===m&&(hu.current=null,Ga(!1),ke(!1)),ut.current.add(m),Ec(m)},[es,de,ja,er,Ec,zn]);d.useEffect(()=>{const m=new Set(Object.keys(Ie));for(const x of m)ut.current.has(x)||_u(x);for(const x of ut.current)m.has(x)||ut.current.delete(x)},[_u,Ie]);const zo=d.useCallback(m=>{const x=hw(um.current,m);return um.current=x.tail,x.result},[]),Or=d.useCallback(m=>{const x=hw(Bd.current,m);return Bd.current=x.tail,x.result},[]),Br=d.useCallback(m=>{dr.current=m,uu.current=0;const x=m?.deviceId||"";Ri.current=x,cl(x),x&&ur.current.add(x)},[]),Zi=d.useCallback(m=>zo(async()=>{if(Xe.current[m.deviceId])return!1;const x=dr.current;return!Qn(x,m)||!mp(m.deviceId,m,At.current)?!1:(await Ws(m.deviceId),Qn(dr.current,m)&&Br(null),!0)}),[Br,zo,Ws]),Xd=d.useCallback((m,x,C)=>zo(async()=>{const R=dr.current;if(Qn(R,m))return C.stoppedWallDeviceId=m.deviceId,!0;if(R)if(Xe.current[R.deviceId])Qn(dr.current,R)&&Br(null);else{if(!mp(R.deviceId,R,At.current))return!1;await Ws(R.deviceId),Qn(dr.current,R)&&Br(null)}if(!x())return!1;if(await Lu(m.deviceId),C.stoppedWallDeviceId=m.deviceId,!x()){if(mp(C.stoppedWallDeviceId,m,At.current))try{await Ws(C.stoppedWallDeviceId)}catch(E){throw Br(m),E}finally{C.stoppedWallDeviceId=""}return!1}return bd(cn.current.get(m.deviceId)||null),Br(m),!0}),[Br,zo,Ws,Lu]),Fu=d.useCallback(async(m,x)=>{if(x.stoppedWallDeviceId){if(Qn(dr.current,m)){try{await Zi(m)}catch(C){Oe(C instanceof Error?C.message:String(C))}finally{x.stoppedWallDeviceId=""}return}await zo(async()=>{if(!x.stoppedWallDeviceId||!mp(x.stoppedWallDeviceId,m,At.current))return;const C=x.stoppedWallDeviceId;try{await Ws(C)}catch(R){Br(m),Oe(R instanceof Error?R.message:String(R))}finally{x.stoppedWallDeviceId=""}})}},[Br,zo,Zi,Oe,Ws]),Hr=d.useCallback(async(m,x,C={})=>{const R=C.allowStopFailure===!0,E=C.resumeWall!==!1;try{await Pu(m.deviceId,x)}catch(G){if(!R)throw G}if(!Qn(At.current,m))return!1;if(At.current=null,Re.current=null,qe(null),er(m.deviceId),ke(!1),_e(""),at(""),jt(""),Qe(G=>G===m.deviceId?"":G),!E)return Qn(dr.current,m)&&Br(null),!0;try{await Zi(m)}catch(G){Oe(G instanceof Error?G.message:String(G))}return!0},[Br,er,Zi,Oe,Pu]),Zd=(Ta&&dt&&Xt&&ye&&!St.has(ye)&&pt.find(m=>m.deviceId===ye)||null)?.deviceId||"";d.useEffect(()=>{Co.current=Zd},[Zd]),d.useEffect(()=>{const m=ye&&pt.find(G=>G.deviceId===ye)||null;if(!Ta||!dt||!Xt||!m){ba.current&&(++Wn.current,ba.current="");return}if(Xe.current[m.deviceId]){ba.current&&(++Wn.current,ba.current=""),de===m.deviceId&&Ge("paused");return}if(wa.current){if(wa.current===m.deviceId)return;wa.current=""}if(de===m.deviceId&&(Ee==="active"||Ee==="warm"||Ee==="connecting")){Ge(G=>G==="warm"?"active":G);return}if(ba.current===m.deviceId)return;const x=++Wn.current,C=Cg(m.deviceId,x,{sessionId:m.sessionId,monitorIndex:Da});ba.current=m.deviceId;const R={stoppedWallDeviceId:""},E=()=>x===Wn.current&&Co.current===C.deviceId;Or(async()=>{if(!E())return;const G=At.current;if(G){Ge("stopping");try{await Hr(G,"control-session-switch")}catch(ie){E()&&(Ge("error"),Oe(ie instanceof Error?ie.message:String(ie)));return}if(!E()){At.current||Ge("idle");return}}try{if(!await Xd(C,E,R)||!E()){await Fu(C,R),At.current||Ge("idle");return}}catch(ie){await Fu(C,R),E()&&(Ge("error"),Oe(ie instanceof Error?ie.message:String(ie)));return}if(!E()){await Fu(C,R);return}At.current=C,Va.current=null,wa.current="",ko.current=null,fl.current=0,fc.current="",R.stoppedWallDeviceId="";const Y=la("control",C.deviceId),ee=`control-session-${x}-${C.deviceId}`;Li.current.set(Y,performance.now()),ii.current.delete(Y),Di.current.delete(Y),li.current.delete(Y),Os.current.delete(Y),at(""),jt(""),_e(ee),Qe(C.deviceId),ke(!1),Ge("connecting")}).catch(G=>{E()&&(Ge("error"),Oe(G instanceof Error?G.message:String(G)))}).finally(()=>{Wn.current===x&&ba.current===C.deviceId&&(ba.current="")})},[pt,ye,de,Ee,Ta,Or,Xt,Xd,Fu,Da,Oe,dt,Hr,Ie]),d.useEffect(()=>{if(!de||pt.some(C=>C.deviceId===de))return;const m=de;++Wn.current,ba.current="";const x=At.current;Ge("stopping"),Or(async()=>{x&&x.deviceId===m?await Hr(x,"control-device-disconnected",{allowStopFailure:!0}):(er(m),Qe(C=>C===m?"":C)),At.current||Ge("idle")})},[pt,de,Or,er,Hr]),d.useEffect(()=>{if(Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),!Qa||dt||!de||Xe.current[de]||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm")return;const m=de,x=At.current;if(!x||x.deviceId!==m)return;const C=window.setTimeout(()=>{Qr.current===C&&(Qr.current=null);const R=At.current;if(Co.current||Xe.current[m]||!Qn(R,x))return;Va.current=x;const E=++Wn.current;ba.current="",Ge("stopping"),Or(async()=>{if(E!==Wn.current||Co.current||!Qn(At.current,x)){Qn(Va.current,x)&&(Va.current=null),Qn(At.current,x)&&Co.current===m&&Ge("active");return}try{await Hr(x,"control-session-wall-downshift")}catch(G){Qn(Va.current,x)&&(Va.current=null),E===Wn.current&&!Co.current&&Qn(At.current,x)&&(Ge("active"),Oe(G instanceof Error?G.message:String(G)));return}Va.current=null,E===Wn.current&&!At.current&&Ge("idle")})},wI);return Qr.current=C,()=>{Qr.current===C&&(window.clearTimeout(C),Qr.current=null)}},[de,Ee,Or,Oe,dt,Hr,Ie,Qa]);const Al=d.useCallback(m=>{if(mm.current===m)return;mm.current=m;const x=At.current,C=x?.deviceId||de,R=++Wn.current;ba.current="",Re.current=null,si.current=!0,qe(null),ke(!1),Ga(!1),C&&(ua("control",C),er(C,{preservePresentation:!1}),Ge("stopping"),Or(async()=>{if(x&&x.deviceId===C)try{await Hr(x,"control-session-document-hidden",{resumeWall:!1})}catch(E){!Dr.current&&fs.current===m&&(Ge("error"),Oe(E instanceof Error?E.message:String(E)));return}else er(C,{preservePresentation:!1}),Qe(E=>E===C?"":E);!At.current&&Wn.current===R&&Ge("idle")}))},[de,Or,er,ua,Oe,Hr]);d.useEffect(()=>{if(ds.current!==null&&(window.clearTimeout(ds.current),ds.current=null),!de||Ee==="idle"||Ee==="paused"||Ee==="error")return;if(!Ta){Al(fs.current);return}if(Ee==="stopping"||jo){de&&Lr&&Ee==="connecting"&&(si.current=!1),de&&Lr&&si.current&&(Ee==="warm"||Ee==="active")&&(si.current=!1,Re.current=null,qe(null),ke(!1),Ga(!1),ua("control",de),_e(`control-presentation-resume-${Date.now()}-${de}`),Ge("connecting"));return}Re.current=null,si.current=!0,qe(null),ke(!1),Ga(!1),Ge(x=>x==="idle"||x==="stopping"?x:"warm");const m=de;return er(m,{preservePresentation:!1}),ds.current=window.setTimeout(()=>{ds.current=null,++Wn.current,ba.current="";const x=At.current;Ge("stopping"),Or(async()=>{if(x&&x.deviceId===m)try{await Hr(x,"control-session-warm-timeout")}catch(C){Ge("error"),Oe(C instanceof Error?C.message:String(C));return}else er(m),Qe(C=>C===m?"":C);At.current||Ge("idle")})},bI),()=>{ds.current!==null&&(window.clearTimeout(ds.current),ds.current=null)}},[jo,Lr,de,Ee,Ta,Or,er,Al,ua,Oe,Hr]),d.useEffect(()=>()=>{ds.current!==null&&window.clearTimeout(ds.current),Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),Va.current=null},[]);const Dc=d.useCallback(()=>{const m=new Set(gu.current),x=At.current?.deviceId||"";de&&m.add(de),x&&m.add(x),gu.current=[];for(const R of m){Kr.current.delete(R),zn(R),er(R,{preservePresentation:!1});for(const E of[cn.current.get(R),Zn.current.get(R),Na.current.get(R)])E&&ja(E);es(R),ua("wall",R),ua("control",R),Ec(R)}const C=Er.current;C&&ja(C),cc.current="",ul.current=null,uc.current=0},[es,de,ja,er,Ec,zn,ua]);d.useEffect(()=>{if(Ta){gu.current=[...bl];return}Dc()},[Ta,bl,Dc]),d.useEffect(()=>{const m=dr.current,x=At.current;if(!Qa||!m||Xe.current[m.deviceId]||x&&x.deviceId===m.deviceId){uu.current=0;return}const C=uu.current,R=Math.min(5e3,500*2**Math.min(C,4)),E=window.setTimeout(()=>{ji.current===E&&(ji.current=null);const G=dr.current;!Ir.current||!G||Xe.current[G.deviceId]||!Qn(G,m)||(uu.current=C+1,Zi(G).catch(Y=>{Oe(Y instanceof Error?Y.message:String(Y)),Qn(dr.current,G)&&!At.current&&bo(ee=>ee+1)}))},R);return ji.current=E,()=>{window.clearTimeout(E),ji.current===E&&(ji.current=null)}},[Ee,Zi,Oe,Qa,lc,ni]);const Nl=de&&pt.find(m=>m.deviceId===de)||null,Ic=!!(dt&&ze&&Ee==="active"&&me&&Nl?.sessionId&&pe?.deviceId===Nl.deviceId&&pe.sessionId===Nl.sessionId&&pe.streamPurpose==="control"&&pe.commandId&&pe.captureGeneration>0&&pe.monitorIndex===Da),{state:Ou,sendInput:Jd,stats:Gs,error:ef}=cN(Ta&&bs&&Ic,X),Ji=Nl?.deviceId||"",Bu=Nl?.sessionId||"",Tl=pe?.commandId||"",Rl=Number(pe?.captureGeneration||0),tf=Number(pe?.monitorIndex||0),$o=d.useCallback((m,x)=>!Dr.current||!Ic||!Ji||!Bu||!Tl||Rl<=0||m!==Ji?!1:Jd(m,{...x,monitorIndex:tf,controlSessionId:Bu,controlCommandId:Tl,captureGeneration:Rl}),[Ic,Rl,Tl,Ji,tf,Bu,Jd]),Vs=Ta&&Dr.current&&Ic&&Ou==="open",Hu={shiftKey:Et.includes("ShiftLeft"),ctrlKey:Et.includes("ControlLeft"),altKey:Et.includes("AltLeft"),metaKey:Et.includes("MetaLeft")},ts=d.useCallback(m=>Ne.current.enqueueStop(m),[]),eo=d.useCallback(m=>Ne.current.enqueueStart(m),[]),ka=d.useCallback((m,x=ce.current)=>(te.current=m,ce.current=m?String(x||""):"",fe.current+=1,fe.current),[]),ns=d.useCallback((m,x,C)=>PN({generation:m,currentGeneration:fe.current,enabled:te.current,deviceId:x,currentDeviceId:ce.current,documentVisible:Dr.current,presentationVisible:He.current,streamId:C,currentStreamId:Ae.current.get(x)||""}),[]),br=d.useCallback(async(m,x,C)=>{if(!x)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const E=await(Y=>rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({...Y?{streamId:Y}:{},reason:C})},X))(x),G=_N(E);if(G.staleOwner)return E;if(!G.confirmed)throw new Error(E?.error||"Remote audio capture stop was not confirmed.");return E},[X]),zu=d.useCallback(async(m,x)=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:x})},X);if(C?.ok===!1||C?.captureStopConfirmed!==!0&&C?.alreadyStopped!==!0)throw new Error(C?.error||"Remote audio stop-all was not confirmed.");return C},[X]),ym=d.useCallback(m=>{const x=fe.current,C=Ae.current.get(m)||"";return ts(()=>br(m,C,"remote-audio-automatic-restart")).then(()=>eo(async()=>{if(x!==fe.current||!te.current||ce.current!==m||!Dr.current||!He.current||!Xt||!ys||(je.current||De?.deviceId||"")!==m)return"";const R=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(Ae.current.set(m,R),!ns(x,m,R))return Ae.current.delete(m),"";const E=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(E?.ok===!1)throw Ae.current.get(m)===R&&Ae.current.delete(m),new Error(E.error||"Remote audio restart failed.");return ns(x,m,R)?R:(await br(m,R,"remote-audio-stale-restart-compensation"),Ae.current.get(m)===R&&Ae.current.delete(m),"")}))},[eo,ts,Xt,X,ns,ys,De?.deviceId,br]),$u=De?.deviceId&&Ae.current.get(De.deviceId)||"",bm=d.useCallback(async(m,x,C)=>{ka(!1),be(!1),await ts(()=>br(m,x,C)),Ae.current.get(m)===x&&Ae.current.delete(m)},[ts,ka,br]),{state:Uu,lastFrame:nf,stats:An,error:qu}=fN(De?.deviceId||"",Ta&&Eu&&Je,X,ml,En||Ht||du.current,$u,ym,bm),Lc=d.useRef(new Map);d.useEffect(()=>{const m=[["hub",q],["registry",l],["license",P],["wall-stream",Qi],["control-stream",Ho],["control-decode",st],["remote-input",ef],["remote-audio",qu]];for(const[x,C]of m){const R=String(C||"").trim();if(x==="hub"&&Bt?.requiresHubRestart&&Bt.stage==="updating"){Lc.current.delete(x);continue}if(!R){Lc.current.delete(x);continue}Lc.current.get(x)!==R&&(Lc.current.set(x,R),Oe(R))}},[qu,st,Ho,q,ef,P,l,Oe,Qi,Bt]);const jl=De?.deviceId||"",af=De?js(De,sn[jl]):0;d.useEffect(()=>{if(!ze||!bs||!Vs||!jl)return;const m=bN(),x=jl,C=af,R=Be=>{if(!Be)return!1;const Ue=$o(x,{...Be,monitorIndex:C});return!Ue&&Be.type!=="keyboard.reset"&&(m.reset("browser-input-send-rejected"),lt([])),Ue},E=(Be,Ue)=>{const gt=Be.target,bn=gt?.tagName?.toLowerCase(),Tt=gt?.isContentEditable||bn==="input"||bn==="textarea"||bn==="select",an=m.isPressed(Be);if(Tt&&(Ue==="keydown"||!an))return;const Ln=m.event(Be,Ue);Ln&&(Be.preventDefault(),Be.stopPropagation(),R(Ln))},G=Be=>E(Be,"keydown"),Y=Be=>E(Be,"keyup"),ee=(Be,Ue=!1)=>{const gt=m.reset(Be,Ue);gt&&(R(gt),lt([]))};ht.current=Be=>{const Ue=m.snapshot().latchedCodes.includes(Be),gt=m.modifier(Be,!Ue);gt&&(R(gt),lt(bn=>Ue?bn.filter(Tt=>Tt!==Be):[...bn.filter(Tt=>Tt!==Be),Be]))};const ie=()=>ee("browser-window-blur"),re=()=>ee("browser-page-hidden"),Ve=()=>{document.visibilityState==="hidden"&&ee("browser-document-hidden")};return window.addEventListener("keydown",G,!0),window.addEventListener("keyup",Y,!0),window.addEventListener("blur",ie),window.addEventListener("pagehide",re),document.addEventListener("visibilitychange",Ve),()=>{window.removeEventListener("keydown",G,!0),window.removeEventListener("keyup",Y,!0),window.removeEventListener("blur",ie),window.removeEventListener("pagehide",re),document.removeEventListener("visibilitychange",Ve),ht.current=null,ee("control-keyboard-owner-changed",!0)}},[bs,Vs,jl,af,ze,$o]);const rf=d.useCallback(m=>{He.current=m;const x=je.current||De?.deviceId||"";if(!Je||!x)return;const C=ka(te.current,x);if(!m){const E=Ae.current.get(x)||"";ts(async()=>{await br(x,E,"remote-audio-document-hidden")}).catch(G=>{(je.current||De?.deviceId||"")===x&&(ka(!1),Ae.current.delete(x),be(!1),Oe(G instanceof Error?G.message:String(G)))});return}const R=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Ae.current.set(x,R),eo(async()=>{if(!ns(C,x,R)||!Xt||!ys||(je.current||De?.deviceId||"")!==x)return;const E=await rt(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(E?.ok===!1)throw new Error(E.error||"Remote audio presentation resume failed.");ns(C,x,R)||(await br(x,R,"remote-audio-stale-presentation-compensation"),Ae.current.get(x)===R&&Ae.current.delete(x))}).catch(E=>{Dr.current&&C===fe.current&&(ka(!1),Ae.current.delete(x),be(!1),Oe(E instanceof Error?E.message:String(E)))})},[Je,eo,ts,ka,Xt,X,ns,ys,De?.deviceId,Oe,br]);d.useEffect(()=>{const m=E=>{const G=Dr.current;E!==G&&(Dr.current=E,fs.current+=1,yc.current={active:E&&Ya.current,epoch:fs.current},E||(Dc(),Al(fs.current)),rf(E),gh(E),E&&!G&&(vh(Y=>Y+1),Ii.current=performance.now()))},x=()=>{m(document.visibilityState==="visible")},C=()=>m(!1),R=()=>x();return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",C),window.addEventListener("pageshow",R),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",R)}},[Dc,Al,rf]),d.useEffect(()=>{if(!de||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm"||Qd!=="open")return;const m=de,x=la("control",m),C=window.setInterval(()=>{const R=performance.now();if(document.visibilityState!=="visible"||R-Ii.current<Og)return;const E=ii.current.get(x)||0,G=Di.current.get(x)||0,Y=_s.current.get(x)||0,ee=Li.current.get(x)||R;Li.current.has(x)||Li.current.set(x,ee);const ie=E<=0,re=ie?R-ee>II:R-E>Ex,Ve=bw({lastReceivedAt:E,lastPaintedAt:G,now:R,staleAfterMs:Ex}),Be=yw({paintStale:Ve,lastRecoveryAt:oi.current.get(x)||0,now:R,recoveryCooldownMs:Ix,transportRecoveryAfterMs:Lx});if(!re&&Be==="reset-decoder"&&vi(m,"control","decoder-paint-stale")||!re&&Be==="wait")return;if(!(re||Be==="recover-transport")){Ve&&vi(m,"control","decoder-paint-stale"),ie&&R-ee>DI&&!Fs.current.has(x)&&ia([m],"control-frame-socket-recovery")&&Fs.current.set(x,R);return}const gt=Fs.current.get(x)||0;if(gt<=0){ia([m],"control-frame-socket-recovery")&&Fs.current.set(x,R);return}if(R-gt<Dx)return;const bn=Os.current.get(x)||0;if(bn>0){if(R-bn<PI)return;Os.current.delete(x)}const Tt=li.current.get(x)||0;if(Tt>=_I){if(Ml(ie?"no first frame":"stale stream"))return;ke(!1),Ga(!1),wa.current=m,Ge("error");return}if(R-Y<Px(LI,Tt))return;Cl([m],ie?"control-first-frame-timeout":Be==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(Fs.current.delete(x),oi.current.delete(x),_s.current.set(x,R),Os.current.set(x,R),Li.current.set(x,R),li.current.set(x,Tt+1))},650);return()=>window.clearInterval(C)},[Qd,de,Ee,Ml,ia,vi,Cl]),d.useEffect(()=>{!st||de&&Xe.current[de]||Pr!=="mode3-h264-hw"||Ml(st)||(ke(!1),Ga(!1),wa.current=At.current?.deviceId||"",Ge("error"))},[st,de,Pr,Ml]),d.useEffect(()=>{!dt||!de||Xe.current[de]||!Ho||(wa.current=de,Ge(m=>m==="error"?m:"error"))},[Ho,de,dt]),d.useEffect(()=>{if(Ee!=="error")return;const m=At.current;if(!m)return;wa.current=m.deviceId,Qn(ko.current,m)||(ko.current=m,fl.current=0);const x=fl.current,C=x===0?0:Math.min(5e3,500*2**Math.min(x-1,4)),R=window.setTimeout(()=>{Qn(At.current,m)&&(++Wn.current,ba.current="",Ge("stopping"),Or(async()=>{if(Qn(At.current,m))try{if(!await Hr(m,"control-session-terminal-error"))return;ko.current=null,fl.current=0,fc.current===m.deviceId?(fc.current="",wa.current="",Ge("idle")):Ge("error")}catch(E){if(!Qn(At.current,m))return;fl.current+=1,Oe(E instanceof Error?E.message:String(E)),Ge("error"),Vr(G=>G+1)}}))},C);return()=>window.clearTimeout(R)},[Ee,Gr,Or,Oe,Hr]);const Pc=d.useCallback(m=>{if(!m||wa.current!==m)return!1;const x=At.current;return++Wn.current,ba.current="",fl.current=0,x&&x.deviceId===m?(fc.current=m,ko.current=null,Ge("error"),Vr(C=>C+1),!0):(fc.current="",wa.current="",ko.current=null,Ge("idle"),!0)},[]);d.useEffect(()=>{if($s!=="open"||!wt.autoStartLive||gr.length===0)return;const m=window.setInterval(()=>{const x=performance.now();if(document.visibilityState!=="visible"||x-Ii.current<Og)return;const C=1e3/Math.max(1,kc||Qt||1),R=Math.max(BI,Math.ceil(C*4)),E=[],G=[];for(const Y of gr){if(G.length+E.length>=$I)break;const ee=la("wall",Y),ie=ii.current.get(ee)||0,re=ie<=0,Ve=Mo.current.get(ee)||x;Mo.current.has(ee)||Mo.current.set(ee,Ve);const Be=_s.current.get(ee)||0,Ue=Di.current.get(ee)||0,gt=re||x-ie>R,bn=bw({lastReceivedAt:ie,lastPaintedAt:Ue,now:x,staleAfterMs:R}),Tt=yw({paintStale:bn,lastRecoveryAt:oi.current.get(ee)||0,now:x,recoveryCooldownMs:Ix,transportRecoveryAfterMs:Lx});if(!gt&&Tt==="reset-decoder"&&vi(Y,"wall","decoder-paint-stale")||!gt&&Tt==="wait")continue;if(!(gt||Tt==="recover-transport")){bn&&vi(Y,"wall","decoder-paint-stale");continue}const Ln=Fs.current.get(ee)||0;if(Ln<=0&&(!re||x-Ve>FI)){E.push(Y);continue}if(re&&x-Ve<=OI||Ln>0&&x-Ln<Dx)continue;const Ks=li.current.get(ee)||0;x-Be>=Px(HI,Ks)&&G.push(Y)}if(E.length>0&&Bo(E,"wall-frame-socket-recovery"))for(const Y of E)Fs.current.set(la("wall",Y),x);if(G.length>0&&Yi(G,G.some(Y=>(ii.current.get(la("wall",Y))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const Y of G){const ee=la("wall",Y);Fs.current.delete(ee),oi.current.delete(ee),_s.current.set(ee,x),Mo.current.set(ee,x),ii.current.delete(ee),Di.current.delete(ee),li.current.set(ee,(li.current.get(ee)||0)+1)}},zI);return()=>window.clearInterval(m)},[kc,gr,Bo,vi,Yi,wt.autoStartLive,Qt,$s]),d.useEffect(()=>{cr(Qt),ku.current=Date.now(),Gn.current=0,ps.current=0,da.current=0,gc.current=0,Ro.current=""},[Qt,wt.frameMode,wt.adaptiveLoadShedding]),d.useEffect(()=>{PA({h264DecodeAcceleration:wt.h264DecodeAcceleration})},[wt.h264DecodeAcceleration]),d.useEffect(()=>{if(!Xt||dt||Gt==="list"||!wt.visibleOnlyLive){ti([]);return}const m=hc.current;if(!m||typeof IntersectionObserver>"u"){ti(yl);return}const x=Array.from(m.querySelectorAll("[data-live-device-id]"));if(x.length===0){ti([]);return}const C=new Map,R=EN(m,T),E=()=>{const Y=zg(x.map(ee=>String(ee.dataset.liveDeviceId||"")).filter(ee=>(C.get(ee)||0)>0));ti(ee=>Hg(ee,Y)?ee:Y)},G=new IntersectionObserver(Y=>{for(const ee of Y){const ie=String(ee.target.dataset.liveDeviceId||"");ie&&C.set(ie,ee.isIntersecting?ee.intersectionRatio||.01:0)}E()},{root:R,rootMargin:T?AN:Si.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return x.forEach(Y=>G.observe(Y)),E(),()=>G.disconnect()},[yl,Xt,T,dt,mi,wt.visibleOnlyLive,Gt]),d.useEffect(()=>{if(!wt.adaptiveLoadShedding||!wt.autoStartLive||gr.length===0){ps.current=0,da.current=0,gc.current=0,Ro.current="";return}const m=Qt;if($s!=="open"||Us.sampleMs<500||Us.lastUpdatedAt<=0||gc.current===Us.lastUpdatedAt)return;gc.current=Us.lastUpdatedAt;const x=Date.now(),C=gr.map(Be=>({deviceId:Be,receive:mu[la("wall",Be)],paint:dl[la("wall",Be)]}));if(!C.every(({receive:Be,paint:Ue})=>{const gt=Be?.lastFrame,bn=Math.max(0,Number(gt?.requestedFps||0)),Tt=gt?co(gt):"";return WN({receiveSampleMs:Number(Be?.sampleMs||0),paintSampleMs:Number(Ue?.sampleMs||0),currentGenerationVerified:gt?.currentGenerationVerified===!0,frameRequestedFps:bn,adaptiveFps:Hn})&&Ue?.bindingKey===Tt})){ps.current=0,da.current=0,Gn.current=0;return}const E=[Hn,...C.map(({deviceId:Be,receive:Ue})=>`${Be}:${co(Ue.lastFrame)}`).sort()].join("|");if(Ro.current!==E){Ro.current=E,ps.current=x,da.current=0,Gn.current=0;return}if(!ps.current){ps.current=x,da.current=0;return}if(x-ps.current<Si.downshiftStableSampleMs)return;const G=C.reduce((Be,{receive:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0)),0),Y=C.reduce((Be,{receive:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0))*Math.max(0,Number(Ue?.averageFrameBytes||0)),0),ee=C.reduce((Be,{paint:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0)),0),ie=Math.max(0,...C.map(({receive:Be})=>Number(Be?.maxIntervalMs||0))),re=Math.max(0,...C.map(({paint:Be})=>Number(Be?.p95IntervalMs||0))),Ve=qN({directDeviceCount:gr.length,requestedFps:Hn,measuredFramesPerSecond:G,measuredPaintFramesPerSecond:ee,measuredBytesPerSecond:Y,maxBytesPerSecond:Si.maxWallBytesPerSecond,worstReceiveGapMs:ie,worstPaintP95Ms:re,maxFrameGapMs:Si.maxFrameGapMs});if(Ve.overloaded){if(Gn.current=0,da.current+=1,da.current<Si.downshiftConsecutiveSamples)return;const Be=Si.minFps;if(x-ku.current>=Si.downshiftCooldownMs&&Hn>Be){const Ue=Math.max(Be,iL(Hn,Be));Ue<Hn&&(cr(Ue),ku.current=x,ps.current=0,da.current=0)}return}if(da.current=0,!Ve.healthyForRecovery||Hn>=m){Ve.healthyForRecovery||(Gn.current=0);return}if(!Gn.current){Gn.current=x;return}if(x-Gn.current>=Si.recoveryCooldownMs){const Be=Math.min(m,oL(Hn,m));Be>Hn&&(cr(Be),ku.current=x,Gn.current=0,ps.current=0,da.current=0)}},[Hn,gr.length,gr,dl,mu,$s,Us.lastUpdatedAt,Us.sampleMs,wt.adaptiveLoadShedding,wt.autoStartLive,wt.frameMode,Qt]),d.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("checkout");if(m==="success"){Oe("Checkout returned. Waiting for Dodo confirmation."),se();const x=window.setInterval(()=>{se()},4e3),C=window.setTimeout(()=>{window.clearInterval(x)},45e3);return()=>{window.clearInterval(x),window.clearTimeout(C)}}m==="cancelled"&&Oe("Checkout cancelled.")},[se]),d.useEffect(()=>{!Xt&&ze&&We(!1),!Xt&&Je&&(ka(!1),be(!1))},[Je,ze,ka,Xt]),d.useEffect(()=>{Je&&(!De||!ys)&&(ka(!1),be(!1))},[Je,ka,ys,De]),d.useEffect(()=>{const m=De?.deviceId||"",x=je.current;if(je.current=m,!x||x===m)return;const C=ka(Je,m),R=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";m&&Je&&Ae.current.set(m,R);let E=!0;const G=Ae.current.get(x)||"";return(async()=>{try{await ts(async()=>{await br(x,G,"remote-audio-device-switch"),Ae.current.delete(x)}),await eo(async()=>{if(!E||!ns(C,m,R)||!m||!Xt||!ys)return;const Y=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(Y.ok===!1)throw new Error(Y.error||"Remote audio start failed.");ns(C,m,R)||(await br(m,R,"remote-audio-stale-device-switch-compensation"),Ae.current.get(m)===R&&Ae.current.delete(m))})}catch(Y){E&&(ka(!1),Ae.current.delete(m),be(!1),Oe(Y instanceof Error?Y.message:String(Y)))}})(),()=>{E=!1}},[Je,eo,ts,ka,Xt,X,ns,ys,De?.deviceId,br]),d.useEffect(()=>{const m=pt.map(E=>E.deviceId),x=new Set(m),C=new Map(pt.map(E=>[E.deviceId,E])),R=new Map;for(const E of pt){const G=KI(E);if(!G)continue;const Y=ki(E.status),ee=[E.lastStatusAt,Y.capturedAt,Y.collectedAt,Y.timestamp,Y.updatedAt].find(re=>typeof re=="string"&&re.trim()),ie=xN(Js.current[E.deviceId],G,ee);ie&&(Js.current[E.deviceId]=ie,R.set(E.deviceId,ie),Z0({platform:E.platform,topologyFingerprint:G,consecutiveTopologySamples:ie.consecutiveSamples})&&(oc.current[E.deviceId]=G))}for(const E of Object.keys(Js.current))x.has(E)||delete Js.current[E];Z(E=>{const G=E.filter(Y=>x.has(Y));return Hg(E,G)?E:G}),ae(E=>E&&x.has(E)?E:""),Pe(E=>E&&x.has(E)?E:""),us(E=>{let G=!1;const Y={};for(const[ee,ie]of Object.entries(E)){const re=C.get(ee);if(!re){Y[ee]=ie;continue}const Ve=R.get(ee)||Js.current[ee],Be=SN({requestedIndex:ie,monitorCount:fo(re),platform:re.platform,topologyFingerprint:Ve?.fingerprint||"",consecutiveTopologySamples:Ve?.consecutiveSamples||0});Y[ee]=Be,Be!==ie&&(G=!0)}return G?Y:E}),hl(E=>{const G=E.filter(Y=>x.has(Y));return Hg(E,G)?E:G})},[pt,Eo]),d.useEffect(()=>{pm([]),xu(!1)},[zs]),d.useEffect(()=>{!Hi||No!=="selected"||Ea.length>0||In.length===0||hl(In.map(m=>m.deviceId))},[In,Ea.length,No,Hi]),d.useEffect(()=>{try{localStorage.setItem(XS,Wr)}catch{}},[Wr]),d.useEffect(()=>{eL(wt)},[wt]),d.useEffect(()=>{nL(_n)},[_n]),d.useEffect(()=>{ZI(sn,oc.current)},[pt,sn]);const Wu=d.useCallback(async()=>{const m=new Set(w);m.add(Un);try{const G=await rt("/api/remote/status",void 0,Un);Ob({endpoint:G.agentEndpoint,endpoint_candidates:[...G.agentEndpointCandidates||[],...G.hostTargetEndpointCandidates||[]]}).forEach(Y=>m.add(Y))}catch{}const x=[...m].sort((G,Y)=>{const ee=ie=>{const re=Yf(ie);return re==="local"?0:re==="loopback"?1:2};return ee(G)-ee(Y)||G.localeCompare(Y)});let C=!1,R="",E=!1;try{for(const G of x){const Y=Yf(G);try{if(await rt("/api/health",void 0,G),Y==="local")return H(!0),Cd(!0),G;Y==="loopback"&&(C=!0,R=G)}catch{Y==="local"&&(E=!0)}}return C?(E&&Oe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),H(!0),Cd(!0),R||Un):(H(!1),Cd(!1),"")}catch{return H(!1),Cd(!1),""}},[w]),Uo=async()=>{if(gn("auth"),or(!1),window.liveDesk?.auth?.signInWithGoogle){const R=window.liveDesk.auth.signInWithGoogle();Wu();const E=await R;E?.ok===!1&&(Oe(E.error||"LiveDesk could not open the system browser for Google sign-in."),gn(""));return}const m=$t.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});Wu();const{data:x,error:C}=await m;C&&(Oe(C.message),gn(""))},_c=async()=>{gn("auth"),or(!1),window.liveDesk?.auth?.persistSession||await rt("/api/auth/session",{method:"DELETE"},X||Un).catch(()=>{}),await $t.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1&&Oe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),gn("")};d.useEffect(()=>{if(!Ai)return;const m=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||or(!1))},x=C=>{C.key==="Escape"&&or(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Ai]);const Gu=d.useCallback(async(m={})=>{const x=m.silent===!0,C=m.takeover===!0,R=m.requestLocalAccess===!0;if(!n?.user){x||Oe("Sign in before publishing this host.","error");return}if(!Bi.current){Bi.current=!0,x||(gn("host"),it("Hub · 1/4 · Checking the local runtime…"));try{const G=(R?await Wu():"")||X||Un;if(!(z||await rt("/api/remote/status",void 0,G)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");x||it("Hub · 2/4 · Sending the signed-in session to the Hub…");const ee=await rt("/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}})},G);if(!ee.ok||!ee.authenticated)throw new Error(ee.error||"hub-session-sync-failed");x||it("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const ie=await rt("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:C})},G);if(!ie.ok)throw new Error(ie.error||"host-target-failed");if(!x){it("Hub · 4/4 · Verifying the endpoint and lease renewal…");const re=await rt("/api/hub/status",void 0,G);if(!re.hostTargetActive)throw new Error(re.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Ve=re.hostTargetEndpoint||re.agentEndpoint||"endpoint ready",Be=Number(re.connectedDeviceCount||0),Ue=Be>0?`${Be} client${Be===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Oe(`Hub ready · ${Ve} · lease auto-renewal active. ${Ue}`,"success"),(R||D)&&(H(!0),Cd(!0)),V()}u()}catch(E){if(!x){const G=E instanceof Error?E.message:String(E);G.includes("local network access")&&(H(!1),Cd(!1)),Oe(`Hub setup failed · ${G}`,"error")}}finally{Bi.current=!1,x||gn("")}}},[X,D,V,u,Wu,n,Oe,it,z]),to=d.useCallback((m=!0)=>{Ct!=="host"&&(Dt(!1),m&&window.requestAnimationFrame(()=>Nr.current?.focus()))},[Ct]),wm=d.useCallback(()=>{Ct!=="host"&&(Nr.current=document.activeElement instanceof HTMLElement?document.activeElement:null,or(!1),Dt(!0))},[Ct]),xm=d.useCallback(()=>{Dt(!1),Gu({takeover:!0,requestLocalAccess:!0})},[Gu]);d.useEffect(()=>{if(!nt)return;const m=window.requestAnimationFrame(()=>vn.current?.focus()),x=R=>{R.target instanceof Element&&R.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||to(!1)},C=R=>{R.key==="Escape"&&to()};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",C),()=>{window.cancelAnimationFrame(m),window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",C)}},[to,nt]);const El=d.useCallback(async()=>{if(!(!z?.update?.canApply||Ct==="update")){gn("update");try{const m=await rt("/api/update/apply",{method:"POST",body:JSON.stringify({})},X||Un);if(!m.ok)throw new Error(m.error||"LiveDesk update could not be started.");const x=[...new Set((m.targets||[]).map(E=>String(E.deviceId||"").trim()).filter(Boolean))],C=!!(m.managerUpdateAvailable||m.clientPackageUpdateAvailable),R=m.state==="hub-restart-requested"?Date.now():void 0;(x.length>0||C)&&jr({operationId:String(m.operationId||`wall-update-${Date.now()}`),targetIds:x,stage:m.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String(z.hostInstanceId||""),targetManagerVersion:String(m.latestVersion||z.update?.latestVersion||""),targetClientVersion:String(m.latestClientVersion||z.update?.latestClientVersion||""),restartRequestedAt:R,restartDeadlineAt:R?R+Ap:void 0}),it(m.state==="hub-restart-requested"?Mp:Sx),V()}catch(m){Oe(m instanceof Error?m.message:String(m),"error")}finally{gn("")}}},[Ct,X,V,Oe,it,z]);d.useEffect(()=>{const m=Bt,x=z?.update;if(!m||m.stage!=="updating"||!x)return;const C=x.restartResult?.operationId===m.operationId?x.restartResult:null;if(C?.outcome==="restored"){const ie=C.error||`The requested Hub ${C.targetVersion||m.targetManagerVersion||"version"} failed verification.`;jr(re=>re?.operationId===m.operationId?{...re,stage:"restored",error:ie}:re),Oe(`LiveDesk update did not complete. Hub ${C.fallbackVersion||C.appVersion||"the previous version"} was restored. ${ie}`,"error");return}if(C?.outcome==="failed"){const ie=C.error||"No verified LiveDesk Hub replacement could be started.";jr(re=>re?.operationId===m.operationId?{...re,stage:"failed",error:ie}:re),Oe(`LiveDesk Hub update failed. ${ie}`,"error");return}if(x.operationId===m.operationId&&x.state==="failed"){const ie=x.error||"LiveDesk update failed before the Hub replacement completed.";jr(re=>re?.operationId===m.operationId?{...re,stage:"failed",error:ie}:re),Oe(ie,"error");return}if(x.operationId===m.operationId){if(x.state==="hub-restart-requested"&&!m.restartDeadlineAt){const ie=Date.now();jr(re=>re?.operationId===m.operationId?{...re,restartRequestedAt:ie,restartDeadlineAt:ie+Ap}:re),it(Mp)}!m.requiresHubRestart&&x.state==="clients-updated"&&(jr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Oe("LiveDesk clients updated and reconnected successfully.","success"));return}if(!m.requiresHubRestart)return;const R=z.started===!0&&(!m.initialHostInstanceId||z.hostInstanceId&&z.hostInstanceId!==m.initialHostInstanceId),E=!!x.checkedAt,G=Mx(x.currentVersion,m.targetManagerVersion),Y=!m.targetClientVersion||Mx(x.currentClientVersion,m.targetClientVersion),ee=E&&x.state==="idle"&&x.updateAvailable===!1&&G&&Y;R&&ee&&(jr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Oe(`LiveDesk Hub ${x.currentVersion||C?.appVersion||m.targetManagerVersion} restarted and passed version verification.`,"success"))},[Oe,it,z,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||m.restartDeadlineAt)return;const x=()=>{const R=Date.now();jr(E=>E?.operationId===m.operationId&&E.stage==="updating"&&!E.restartDeadlineAt?{...E,restartRequestedAt:R,restartDeadlineAt:R+Ap}:E),it(Mp)};if(z?.update?.state==="hub-restart-requested"){x();return}if(!q)return;const C=window.setTimeout(x,kI);return()=>window.clearTimeout(C)},[q,it,z?.update?.state,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||!m.restartDeadlineAt)return;const x=Math.max(0,m.restartDeadlineAt-Date.now()),C=m.operationId,R=window.setTimeout(()=>{const E=`LiveDesk Hub did not return and verify ${m.targetManagerVersion||"the requested version"} within ${Math.round(Ap/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;jr(G=>G?.operationId===C&&G.stage==="updating"?{...G,stage:"failed",error:E}:G),Oe(E,"error")},x);return()=>window.clearTimeout(R)},[Oe,Bt]),d.useEffect(()=>{if(!Bt||Bt.stage!=="updated")return;const m=Bt.operationId,x=window.setTimeout(()=>{jr(C=>C?.operationId===m?null:C)},Cx);return()=>window.clearTimeout(x)},[Bt]),d.useEffect(()=>{lr.current.clear(),ei({})},[Bt?.operationId]),d.useEffect(()=>{if(!Bt||z?.update?.operationId!==Bt.operationId)return;const m=(z.update.targets||[]).filter(C=>C.state==="completed").map(C=>kx(Bt.operationId,C)).filter(C=>!lr.current.has(C));if(m.length===0)return;const x=Date.now()+Cx;for(const C of m)lr.current.add(C);ei(C=>({...C,...Object.fromEntries(m.map(R=>[R,x]))}))},[z?.update,Bt]),d.useEffect(()=>{const m=Math.min(...Object.values(yo));if(!Number.isFinite(m))return;const x=window.setTimeout(()=>{const C=Date.now();ei(R=>Object.fromEntries(Object.entries(R).filter(([,E])=>E>C)))},Math.max(0,m-Date.now()));return()=>window.clearTimeout(x)},[yo]),d.useEffect(()=>{if(Ur!==Sx&&Ur!==Mp)return;const m=z?.update;if(String(m?.state||"")==="failed"){Oe(m?.error||"LiveDesk update failed.","error");return}Bt?.stage==="updated"&&Oe("")},[Ur,Oe,z?.update?.error,z?.update?.state,Bt?.stage]);const Sm=d.useCallback(async()=>{if(!Ct){gn("pin");try{const x=await rt("/api/remote/pairing-pin",{method:"POST"},X||Un);if(!x.ok)throw new Error(x.error||"pin-rotation-failed");await V(),Oe("New PIN published.")}catch(m){Oe(m instanceof Error?m.message:String(m))}finally{gn("")}}},[Ct,X,V]),Fc=d.useCallback(m=>{m&&(ae(m),Z(x=>x.includes(m)?x:[...x,m]))},[]),Vu=d.useCallback(m=>{if(!m)return;const x=mr.has(m);ae(C=>x?C===m?"":C:m),Z(C=>x?C.filter(R=>R!==m):C.includes(m)?C:[...C,m])},[mr]),qo=d.useCallback(()=>{Z([]),ae("")},[Cs]),Ku=d.useCallback(()=>{Z(pt.map(m=>m.deviceId)),ae("")},[pt]),Qu=d.useCallback((m,x)=>{const C=pt.find(E=>E.deviceId===m);if(!C)return;const R=fo(C);if(!(R<=1)&&(us(E=>{const G=qf(E[m],R),Y=(G+x+R)%R;return Y===G?E:{...E,[m]:Y}}),ua("wall",m),ua("control",m),$a(E=>{if(!E.has(m))return E;const G=new Set(E);return G.delete(m),G}),qa.current.delete(m),ur.current.delete(m),dt)){const E=Pc(m);ke(!1),E||Ge("connecting"),Ga(!1),Pe(m)}},[pt,ua,Pc,dt]);d.useEffect(()=>{const m=x=>{if(ze&&bs&&Vs)return;const C=x.target,R=C?.tagName?.toLowerCase();C?.isContentEditable||R==="input"||R==="textarea"||R==="select"||((x.ctrlKey||x.metaKey)&&x.key.toLowerCase()==="a"&&(x.preventDefault(),Ku()),x.key==="Escape"&&qo())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[bs,qo,Vs,ze,Ku]);const Cm=(m,x)=>{const C=pt.find(Y=>Y.deviceId===m),R=C?fo(C):1,E=qf(sn[m],R),G=qf(x,R);if(E!==G&&(us(Y=>({...Y,[m]:G})),$a(Y=>{if(!Y.has(m))return Y;const ee=new Set(Y);return ee.delete(m),ee}),qa.current.delete(m),ur.current.delete(m),Wa.current.delete(m),ai.current.delete(m),Aa.current.delete(m),ua("wall",m),ua("control",m)),dt){const Y=Pc(m);E!==G&&(ke(!1),Y||Ge("connecting")),Ga(!1),Pe(m)}else Fc(m)},Wo=m=>{const x=je.current||De?.deviceId||"",C=[...new Set([x,m].filter(Boolean))],R=Je||C.some(E=>Ae.current.has(E));ka(!1),be(!1);for(const E of C)Ae.current.delete(E);C.length!==0&&(async()=>{for(const E of C)await ts(()=>zu(E,"remote-audio-control-entry"))})().catch(E=>{R&&Oe("Remote audio was muted locally, but Client capture stop was not confirmed: "+(E instanceof Error?E.message:String(E)),"error")})},no=async m=>{const x={requestId:++hh.current,deviceId:m,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ri.current=x,!pr.has(m)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Oe(vl);return}const C=pt.find(E=>E.deviceId===m);if(tl(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Oe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Wo(m),Pc(m),Ga(!1),Pe(m),bt("control"),We(!0),Oe(`Opening remote control${C?` for ${Pa(C)}`:""}.`,"success")},sf=async()=>{if(!De){Oe("Select a Client before playing audio.");return}if(!Xt){Oe(vl);return}if(!ys){Oe("Selected Client does not report remote audio support yet.");return}if(en)return;const m=!Je,x=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Ae.current.get(De.deviceId),C=ka(m,De.deviceId);m&&x?Ae.current.set(De.deviceId,x):m||Ae.current.delete(De.deviceId),U("audio"),be(m);try{m?(await ts(()=>zu(De.deviceId,"remote-audio-user-enable-reconcile")),await eo(async()=>{if(!x||!ns(C,De.deviceId,x))return;const R=await rt(`/api/remote/devices/${encodeURIComponent(De.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(R?.ok===!1)throw new Error(R.error||"Remote audio start failed.");ns(C,De.deviceId,x)||await br(De.deviceId,x,"remote-audio-stale-user-start-compensation")})):await ts(()=>zu(De.deviceId,"remote-audio-user-disabled")),Oe(`${m?"Audio started":"Audio stopped"} for ${Pa(De)}.`,"success")}catch(R){ka(!1),m&&Ae.current.delete(De.deviceId),be(!1),Oe(R instanceof Error?R.message:String(R),"error")}finally{U("")}},km=async(m,x)=>{const C=m.deviceId,R=Pa(m),E=String(Xe.current[C]||""),G=!!E&&mt[C]===!0;if(x&&E&&!G)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:R};if(!x&&!E)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:R};if(!x&&E.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:R,error:"Pause is still pending confirmation."};if(x){const Ve=E||`pending:${Date.now()}:${C}`,Be=At.current?.deviceId===C?At.current:null,Ue=!!Be||de===C,gt=Ue?++Wn.current:0,bn=()=>pw({deviceId:C,requestTransitionGeneration:gt,currentTransitionGeneration:Wn.current,actualControlOwner:At.current}),Tt=yt.current.get(C);yt.current.set(C,{deviceId:C,monitorIndex:js(m,sn[C]??Tt?.monitorIndex),previousControlOwner:Be||Tt?.previousControlOwner||null}),ya(C,!0),rn(C,!1),pn(C,Ve),_u(C),Ue&&(ba.current="",Ge("paused"));try{const an=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},X);if(!an?.pauseToken)return _t.current.delete(C),pn(C,""),rn(C,!1),yt.current.delete(C),bn()&&(Re.current=null,qe(null),ke(!1),_e(`control-pause-rollback-${Date.now()}-${C}`),Ge("connecting")),{ok:!1,action:"pause",deviceId:C,title:R,error:an?.error||"video-capture-pause-failed"};const Ln=String(Xe.current[C]||"");if(Ln!==Ve&&Ln!==an.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:R,error:"Pause ownership changed before confirmation."};const Ks=bn(),Wc=Ks&&At.current?.deviceId===C?At.current:Be,tr=yt.current.get(C);return tr&&(tr.previousControlOwner=Wc),Ks&&At.current?.deviceId===C&&(At.current=null),Ks&&(Re.current=null,qe(null)),pn(C,an.pauseToken),Ks&&Ge("paused"),an.ok===!1||an.captureStopConfirmed!==!0?(rn(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:an.stopError||an.error||"Client capture shutdown was not confirmed."}):(rn(C,!1),{ok:!0,action:"pause",deviceId:C,title:R})}catch(an){return rn(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:an instanceof Error?an.message:String(an)}}}const Y=yt.current.get(C),ee=Y?.previousControlOwner||null,ie=de===C&&(ee!==null||dr.current?.deviceId===C||Ee==="paused"),re=ie?Wn.current:0;try{ya(C,!1);const Ve=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},X);if(Ve?.ok===!1)throw new Error(Ve.error||"video-capture-resume-failed");if(String(Xe.current[C]||"")!==E)return{ok:!1,action:"resume",deviceId:C,title:R,error:"Resume ownership changed before confirmation."};const Be=yt.current.get(C)||Y,Ue=Be?.previousControlOwner||ee,gt=ie&&pw({deviceId:C,requestTransitionGeneration:re,currentTransitionGeneration:Wn.current,actualControlOwner:At.current});if(pn(C,""),rn(C,!1),yt.current.delete(C),gt){const bn=++Wn.current;ba.current="";const Tt=Cg(C,bn,{sessionId:m.sessionId||Ue?.sessionId,monitorIndex:js(m,sn[C]??Be?.monitorIndex)});At.current=Tt,Br(Tt),wa.current="",ko.current=null,Re.current=null,qe(null),at(""),jt(""),ke(!1),ua("control",C);const an=`control-video-resume-${bn}-${C}`;_e(an),Qe(C),Ge("connecting")}else ua("wall",C);return{ok:!0,action:"resume",deviceId:C,title:R}}catch(Ve){return _t.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:R,error:Ve instanceof Error?Ve.message:String(Ve)}}},Oc=async()=>{if(ws.length===0){Oe("Select one or more Clients before pausing video.");return}if(Ia.length===0){Oe(vl);return}if(en)return;const m=Ia.some(C=>{const R=String(Xe.current[C.deviceId]||"");return!R||R.startsWith("pending:")||mt[C.deviceId]===!0}),x=Ia.filter(C=>{const R=String(Xe.current[C.deviceId]||"");return m?!R||R.startsWith("pending:")||mt[C.deviceId]===!0:!!R});if(x.length===0){Oe(m?"Selected Clients are already paused.":"Selected Clients are already playing.");return}U("video");try{const C=await Promise.all(x.map(re=>km(re,m)));V();const R=C.filter(re=>re.ok&&!re.skipped),E=C.filter(re=>!re.ok&&re.unconfirmed),G=C.filter(re=>!re.ok&&!re.unconfirmed),Y=Ia.length-x.length+C.filter(re=>re.skipped).length,ee=ws.length-Ia.length,ie=m?"pause":"resume";if(G.length>0||E.length>0){const re=G.slice(0,2).map(Ve=>`${Ve.title}: ${Ve.error||"unknown error"}`).join(" · ");Oe([`Video ${ie} completed for ${R.length}/${x.length} Clients.`,E.length>0?`${E.length} Client capture stop${E.length===1?"":"s"} remain unconfirmed.`:"",re,ee>0?`${ee} selected Client${ee===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Oe([`Video ${m?"paused":"resumed"} for ${R.length} Client${R.length===1?"":"s"}.`,Y>0?`${Y} already ${m?"paused":"playing"}.`:"",ee>0?`${ee} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{U("")}},Mm=m=>{const x=m instanceof Error?m.message:String(m);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(x)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(x)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(x)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(x)?"The Client disconnected before the action could be sent.":x},Dl=async m=>{if(!De||en)return;const x=De,R={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[m];if(window.confirm(`${R} ${Pa(x)}? Unsaved work on that computer may be lost.`)){U(m),Oe(`Sending ${R.toLowerCase()} request to ${Pa(x)}...`);try{const E=await rt(`/api/remote/devices/${encodeURIComponent(x.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:m})},X);if(!E.ok)throw new Error(E.error||"The remote action could not be sent.");Oe(`${R} request sent to ${Pa(x)}.`,"success"),V()}catch(E){Oe(Mm(E),"error")}finally{U("")}}},of=async(m,x,C="files")=>{const R=m.filter(ee=>ee.file.size>=0);if(R.length===0)return{files:0,bytes:0};if(!Xt)throw new Error(vl);if(x.length===0)throw new Error("Select at least one connected Client.");const E=crypto.randomUUID(),G=R.reduce((ee,ie)=>ee+ie.file.size,0);let Y=0;di({id:E,status:"reading",progress:1,message:`Preparing ${R.length} ${C}`});try{for(let ee=0;ee<R.length;ee+=1){const ie=R[ee],re=ie.file,Ve=Math.max(1,Math.ceil(re.size/Fg));for(let Be=0;Be<Ve;Be+=1){const Ue=Be*Fg,gt=Math.min(re.size,Ue+Fg),bn=re.size===0?new ArrayBuffer(0):await re.slice(Ue,gt).arrayBuffer(),Tt=Be===Ve-1;di({id:E,status:"sending",progress:Math.max(2,Math.min(98,Math.round(Y/Math.max(1,G)*96))),message:`${ee+1}/${R.length} ${ie.relativePath}`});const an=await rt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:E,deviceIds:x,remoteDirectory:Wr.trim(),name:re.name,relativePath:ie.relativePath,size:re.size,type:re.type,lastModified:re.lastModified,offset:Ue,totalBytes:re.size,final:Tt,dataBase64:lL(bn)})},X);if(!an.ok||an.queued!==x.length)throw new Error(an.error||`file-chunk-not-queued-${an.queued}/${x.length}`);Y+=bn.byteLength,await new Promise(Ln=>window.setTimeout(Ln,0))}}return di({id:E,status:"queued",progress:100,message:`Sent ${R.length} file${R.length===1?"":"s"} to ${x.length} Client${x.length===1?"":"s"}`}),window.setTimeout(()=>{di(ee=>ee?.id===E&&ee.status==="queued"?null:ee)},4500),{files:R.length,bytes:G}}catch(ee){throw di({id:E,status:"failed",progress:100,message:ee instanceof Error?ee.message:String(ee)}),ee}},lf=async m=>{const x=In.length>0?In.map(C=>C.deviceId):De?[De.deviceId]:[];try{await of(Ox(m),x)}catch(C){Oe(C instanceof Error?C.message:String(C))}},Am=async m=>{try{await of(Ox(m),Ca)}catch(x){Oe(x instanceof Error?x.message:String(x))}};d.useEffect(()=>{Cu.current=!1},[]);const cf=m=>{m.preventDefault(),m.stopPropagation(),zd(!1),lf(m.dataTransfer.files)},$n=async(m="ltd")=>{if(!n){Oe("Sign in with Google before checkout.");return}if(J&&m===Ut){Oe("LiveDesk license is already active.");return}if(J&&Ut==="pro"){Oe("LiveDesk Pro is already active.");return}gn("checkout");try{const{data:x,error:C}=await $t.functions.invoke("dodo-checkout",{body:{plan:m}});if(C)throw C;if(!x?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(x.checkout_url)}catch(x){Oe(x instanceof Error?x.message:String(x)),gn("")}},ta=UI(),uf=qI(),Yu=bl.filter(m=>Mn.has(m)).length,Xu=kl==="open"&&Xi.sampleMs>0?`${Xi.framesPerSecond.toFixed(1)} fps`:kl,Ke=De?dt?Sl.get(De.deviceId):Mn.get(De.deviceId):void 0,ao=De?js(De,sn[De.deviceId]):0,Nm=De?VI(De):[],Zu=typeof Ke?.monitorIndex=="number"?qf(Ke.monitorIndex,Math.max(1,Ke.monitorCount||1)):ao,df=(Ke&&Zu===ao?sC(Ke):null)||(De?rC(De,ao):null);df&&`${df.width}${df.height}`;const Go=De?la(dt?"control":"wall",De.deviceId):"",oa=Go?mu[Go]:void 0,wr=Go?dl[Go]:void 0,kt=wr?.lastInfo,Tm=oa&&oa.sampleMs>0?`${oa.framesPerSecond.toFixed(1)} fps`:"waiting";oa&&`${oa.totalFrames}${Tm}`,wr&&wr.sampleMs>0&&`${wr.framesPerSecond.toFixed(1)}`,wr&&wr.sampleMs>0&&`${wr.changedFramesPerSecond.toFixed(1)}`,kt&&(`${kt.frameSeq}${kt.decoderLabel}${kt.queueSize}${kt.renderQueueSize}${kt.droppedForLatency}${kt.decoderFlushCount}${kt.decoderTimestampFallbacks}${kt.decoderInputCount}${kt.decoderOutputCount}`,kt.visualChanged),kt&&`${Math.round(kt.queuedForMs)}${Math.round(kt.decodedForMs)}${Math.round(kt.scheduledForMs)}${kt.drawMs.toFixed(1)}`,kt?.targetPaintIntervalMs&&`${kt.targetPaintIntervalMs.toFixed(1)}${(1e3/kt.targetPaintIntervalMs).toFixed(1)}`,wr&&`${wr.decoderInputFps.toFixed(1)}${wr.decoderOutputFps.toFixed(1)}`,kt?.canvasPresentation,kt&&`${kt.interactiveBufferWaitCount}${Math.round(kt.interactiveBufferWaitMs)}${kt.interactiveQueueDrainCount}`,oa&&(Ke?.frameMode==="mode5-lzo-delta"?`${Wf(oa.averageFrameBytes)}${Ke.deltaVisualTileCount||0}${Ke.deltaRefreshTileCount||0}${Ke.deltaTotalTiles||0}`:`${Wf(oa.averageFrameBytes)}${Math.round(oa.tinyFrameRatio*100)}${Math.round(oa.repeatedFrameRatio*100)}`),oa&&oa.sourceSendSampleCount>0&&`${oa.sourceSendAverageMs.toFixed(1)}${oa.sourceSendP95Ms.toFixed(1)}`,Tx(oa),Tx(wr),oa&&wr&&`${Rx(oa)}${Rx(wr)}`,Ke?Ke.frameMode||Ke.mode||Ke.codec||Ke.mimeType:dt?_n.frameMode:wt.frameMode,dt?_n.frameMode:wt.frameMode,Ke?`${Ke.width}${Ke.height}${Wf(Ke.byteLength)}`:dt?`${vs.maxWidth}${vs.maxHeight}`:`${wt.maxWidth}${wt.maxHeight}`,Ke&&`${Ke.isKeyFrame?"key":String(Ke.chunkType||"delta")}`,Ke&&Ke.monitorCount&&((Ke.monitorIndex??0)+1,`${Ke.monitorCount}`),Ke&&[`src ${Math.round(Ke.sourceGapMs||0)}ms`,`gap ${Math.round(Ke.agentSendGapMs||0)}ms`,`tx ${Math.round(Ke.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ke.agentPaceMs||0)}ms`,`queue ${Math.round(Ke.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ke.agentFrameAgeMs||0)}ms`,Ke.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ke.hubPacketTransitAgeMs))}ms`:"",Ke.droppedByAgent?`drop ${Ke.droppedByAgent}`:"",Ke.hubIngressDropped?`ingress-drop ${Ke.hubIngressDropped}`:"",Ke.hubClientDropped?`ws-drop ${Ke.hubClientDropped}`:"",Ke.captureStageMs?`capture ${Math.round(Ke.captureStageMs)}ms`:"",Ke.requestedFps?`req ${Math.round(Ke.requestedFps)}fps`:"",Ke.effectiveFps?`eff ${Math.round(Ke.effectiveFps)}fps`:"",Ke.captureAverageMs?`avg ${Math.round(Ke.captureAverageMs)}ms`:"",Ke.captureP95Ms?`p95 ${Math.round(Ke.captureP95Ms)}ms`:"",Ke.slowFrameCount?`slow ${Math.round(Ke.slowFrameCount)}`:"",Ke.captureHelperRestarts?`helper ${Math.round(Ke.captureHelperRestarts)}`:"",Ke.convertMs?`rgb565 ${Math.round(Ke.convertMs)}ms`:"",Ke.compressMs?`lzo ${Math.round(Ke.compressMs)}ms`:"",Ke.captureSourceSerial?`cap #${Ke.captureSourceSerial}`:"",Ke.captureSourceSkipped?`cap skip ${Ke.captureSourceSkipped}`:"",Ke.frameMode==="mode5-lzo-delta"?`tiles ${Ke.deltaVisualTileCount||0}+${Ke.deltaRefreshTileCount||0}/${Ke.deltaTotalTiles||0}@${Ke.deltaTileSize||0}`:"",Ke.platformProfile||Ke.hardwareEncoder||"-",Ke.atlasComposeMs?`atlas ${Ke.atlasComposeMs.toFixed(1)}ms`:"",Ke.atlasPoolStarved?`pool ${Ke.atlasPoolStarved}`:"",Ke.atlasTileCount?`tiles ${Ke.atlasReadyTiles||0}/${Ke.atlasTileCount}`:"",Ke.atlasInputRevision?`input #${Ke.atlasInputRevision}`:"",Ke.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ke.atlasSourceMaxAgeMs)}ms`:"",kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=vx?`feedback ${Math.round(kt.inputFeedbackMs)}ms`:"",Ke.contentHash?`enc ${Ke.contentHash.slice(0,6)}`:"",kt?.visualHash?`pix ${kt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Ou==="open"&&[`${Gs.sentPerSecond.toFixed(1)} hz`,Gs.lastInputSeq>0?`rtt ${Math.round(Gs.lastRoundTripMs)}ms`:"",Gs.lastInputSeq>0?`apply ${Gs.lastAgentApplyMs.toFixed(1)}ms`:"",Gs.droppedPerSecond>0?`drop ${Gs.droppedPerSecond.toFixed(1)}/s`:"",Gs.bufferedAmount>0?`buf ${Wf(Gs.bufferedAmount)}`:"",Gs.lastInputType||"ready"].filter(Boolean).join(" / "),kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=vx&&[kt.inputFeedbackExact?"exact":"estimated",kt.inputFeedbackInputType||"",`total ${Math.round(kt.inputFeedbackMs)}ms`,kt.inputFeedbackAgentApplyMs!==void 0?`apply ${kt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",kt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(kt.inputFeedbackApplyToCaptureMs)}ms`:"",kt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(kt.inputFeedbackInputToFrameMs)}ms`:"",kt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(kt.inputFeedbackFrameToPaintMs)}ms`:"",kt.inputFeedbackSampleCount?`p50 ${Math.round(kt.inputFeedbackP50Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`p95 ${Math.round(kt.inputFeedbackP95Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`n=${kt.inputFeedbackSampleCount}`:"",`input #${kt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ke&&`${Ke.frameSeq}${u0(Ke.receivedAt||Ke.capturedAt)}`;const ro=Math.max(0,Xi.bytesPerSecond*8/1e6),Ju={activeTool:Nt,audioError:qu,audioMode:Je,audioState:Uu,audioStats:An,lastAudioFrame:nf,selectedAudioCaptureStreamId:$u,controlFrames:Sl,controlInputReady:Vs,controlMode:ze,controlPresentationReady:Od,controlSessionDeviceId:de,controlSessionFrameReady:me,controlSessionState:Ee,controlStreamBinding:pe,devices:W,documentPresentationVisible:Ta,focusedDeviceId:Se,frames:Mn,localFeatureAccess:Xt,quickActionBusy:en,selectedDeviceId:De?.deviceId||"",selectedIds:we,showControlFocus:dt,videoCaptureStopUnconfirmedByDeviceId:mt,videoCapturePausedDeviceIds:St,wallPresentationReadyDeviceIds:xo},ed=d.useRef(Ju);ed.current=Ju,d.useEffect(()=>{if(!du.current)return;const m=window,x=ee=>{if(!ee)return null;const ie=ee.sourceGapMs,re=ie==null||ie===""?null:Number.isFinite(Number(ie))?Number(ie):null,Ve=ee;return{deviceId:ee.deviceId,sessionId:ee.sessionId||"",streamId:ee.streamId||"",commandId:ee.commandId||"",captureGeneration:Number(ee.captureGeneration||0),monitorIndex:Number(ee.monitorIndex||0),streamPurpose:ee.streamPurpose||"",frameSeq:Number(ee.frameSeq||0),frameMode:ee.frameMode||"",mimeType:ee.mimeType||"",currentGenerationVerified:Ve.currentGenerationVerified===!0,receivedAt:Ve.receivedAt||"",capturedAt:Ve.capturedAt||"",sourceGapMs:re,inputFeedbackEventId:String(ee.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(ee.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(ee.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(ee.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(ee.inputFeedbackApplyToCaptureMs||0)}},C=ee=>{if(!ee)return null;const ie=window.getComputedStyle(ee),re=ee.getBoundingClientRect(),Ve=Math.max(0,Math.min(re.right,window.innerWidth)-Math.max(re.left,0)),Be=Math.max(0,Math.min(re.bottom,window.innerHeight)-Math.max(re.top,0)),Ue=Number(ie.opacity),gt=ee.isConnected&&ie.display!=="none"&&ie.visibility!=="hidden"&&ie.visibility!=="collapse"&&Number.isFinite(Ue)&&Ue>0&&re.width>0&&re.height>0&&Ve>0&&Be>0;return{connected:ee.isConnected,userVisible:gt,width:Math.max(0,Number(ee.width||0)),height:Math.max(0,Number(ee.height||0)),css:{display:ie.display,visibility:ie.visibility,opacity:Number.isFinite(Ue)?Ue:0},rect:{left:re.left,top:re.top,right:re.right,bottom:re.bottom,width:re.width,height:re.height,viewportIntersectionWidth:Ve,viewportIntersectionHeight:Be},codec:up(ee)}},R=(ee,ie)=>{const re=Ps.current.get(la(ee,ie));return re?{bindingKey:re.bindingKey||"",totalFrames:re.totalFrames,totalChangedFrames:re.totalChangedFrames,lastFrameSeq:Number(re.lastFrameSeq||0),lastPaintAgeMs:re.lastAt===void 0?-1:Math.max(0,performance.now()-re.lastAt),lastInfo:re.lastInfo?{frameSeq:Number(re.lastInfo.frameSeq||0),decoderInputCount:Number(re.lastInfo.decoderInputCount||0),decoderOutputCount:Number(re.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(re.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(re.lastInfo.droppedForLatency||0),visualChanged:re.lastInfo.visualChanged===!0,inputFeedbackExact:re.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(re.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(re.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(re.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(re.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:bx,inputFeedbackTargetMinSamples:wx,inputFeedbackOnTarget:re.lastInfo.inputFeedbackExact===!0&&Number(re.lastInfo.inputFeedbackSampleCount||0)>=wx&&Number(re.lastInfo.inputFeedbackP95Ms)<bx}:null}:null},E=(ee,ie)=>{if(!ee)return null;if(ie==="wall-visible"){const Ve=Ps.current.get(la("wall",ee));return Ve?{bindingKey:Ve.bindingKey||"",total:Ve.totalFrames,lastFrameSeq:Number(Ve.lastFrameSeq||0),lastPaintAgeMs:Ve.lastAt===void 0?-1:Math.max(0,performance.now()-Ve.lastAt)}:null}if(ie!=="control-visible"&&ie!=="wall-reuse-visible")return null;const re=fu.current.get(`${ie}:${ee}`);return re?{bindingKey:re.bindingKey,total:re.totalPaints,lastFrameSeq:re.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-re.lastPaintAt)}:null},G=(ee,ie)=>{const re=E(ee,ie);return re?{bindingKey:re.bindingKey,totalPaints:re.total,lastPaintAgeMs:re.lastPaintAgeMs,lastFrameSeq:re.lastFrameSeq}:null},Y={readPresentationCounter(ee,ie){return E(String(ee||""),ie)},snapshot(ee,ie={}){const re=String(ee||""),Ve=ie.includeHistory===!0,Be=Math.max(0,Number(ie.presentationAfterSequence||0)),Ue=ed.current,gt=Ue.devices.find(xr=>xr.deviceId===re)?.liveCapturePause,bn=String(Xe.current[re]||""),Tt=cn.current.get(re)||null,an=kn.current.get(re)||null,Ln=Zn.current.get(re)||null,Ks=q1(),Wc=W1(),tr={frameStats:pu.current===null?0:1,wallRecovery:ji.current===null?0:1,controlWarm:ds.current===null?0:1,controlWallDownshift:Qr.current===null?0:1},od=ri.current?.deviceId===re?ri.current:null,Qo=fm.current.get(re)||null;return{capturedAt:Date.now(),deviceId:re,activeTool:Ue.activeTool,documentPresentationVisible:Ue.documentPresentationVisible,showControlFocus:Ue.showControlFocus,selectedDeviceId:Ue.selectedDeviceId,focusedDeviceId:Ue.focusedDeviceId,selectedDeviceIds:[...Ue.selectedIds],localFeatureAccess:Ue.localFeatureAccess,quickActionBusy:Ue.quickActionBusy,audioMode:Ue.audioMode,audioState:Ue.audioState,audioError:Ue.audioError,audioCaptureStreamId:Ue.selectedAudioCaptureStreamId,audioFrame:Ue.lastAudioFrame?{deviceId:Ue.lastAudioFrame.deviceId,streamId:Ue.lastAudioFrame.streamId,frameSeq:Number(Ue.lastAudioFrame.frameSeq||0),mimeType:Ue.lastAudioFrame.mimeType,sampleRate:Number(Ue.lastAudioFrame.sampleRate||0),channels:Number(Ue.lastAudioFrame.channels||0),byteLength:Number(Ue.lastAudioFrame.byteLength||0)}:null,audioStats:{...Ue.audioStats},videoCapturePausePhase:bn?bn.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:Ue.videoCaptureStopUnconfirmedByDeviceId[re]===!0,authoritativeLiveCapturePause:gt?{phase:gt.phase||"",captureStopConfirmed:gt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(gt.stopAttemptCount||0)),stopError:gt.stopError||""}:null,controlMode:Ue.controlMode,controlSessionDeviceId:Ue.controlSessionDeviceId,controlSessionState:Ue.controlSessionState,controlSessionFrameReady:Ue.controlSessionFrameReady,controlPresentationReady:Ue.controlPresentationReady,controlInputReady:Ue.controlInputReady,controlConnection:Qo?{...Qo}:null,pendingControlConnection:od?{...od,elapsedMs:Math.max(0,performance.now()-od.startedAt)}:null,videoCapturePaused:Ue.videoCapturePausedDeviceIds.has(re),wallPresentationReady:Ue.wallPresentationReadyDeviceIds.has(re),controlBinding:Ue.controlStreamBinding?.deviceId===re?{...Ue.controlStreamBinding}:null,actualControlOwner:At.current?.deviceId===re?{...At.current}:null,wallCapturePauseOwner:dr.current?.deviceId===re?{...dr.current}:null,frameSubscriptions:Ks,audioSubscriptions:Wc,presentationTimers:{...tr,total:Object.values(tr).reduce((xr,Yo)=>xr+Yo,0)},wallFrame:x(Ue.frames.get(re)),controlFrame:x(qa.current.get(re)||Ue.controlFrames.get(re)),wallPaint:R("wall",re),controlPaint:R("control",re),controlVisiblePaint:G(re,"control-visible"),wallReuseVisiblePaint:G(re,"wall-reuse-visible"),presentationPaintSequence:dm.current,presentationPaintEvents:Ve?_d.current.filter(xr=>xr.deviceId===re&&xr.sequence>Be).sort((xr,Yo)=>xr.sequence-Yo.sequence).map(xr=>({...xr})):[],wallCanvas:C(Tt),controlDecodeCanvas:C(an),controlPresentationCanvas:C(Ln),globalCodec:up(void 0,{includeLifecycleEvents:Ve})}}};return m.__liveDeskTransmissionProbe=Y,()=>{m.__liveDeskTransmissionProbe===Y&&delete m.__liveDeskTransmissionProbe}},[]);const Vo=d.useCallback(()=>{ir(!0),Ds(Date.now()),V(),Dn.current!==null&&window.clearTimeout(Dn.current),Dn.current=window.setTimeout(()=>{Dn.current=null,Ds(Date.now()),ir(!1)},650)},[V]),td=d.useCallback(()=>{if(En){qr(!1);return}Pn(!1),qr(!0),Vo()},[Vo,En]),Bc=d.useCallback(()=>{if(Ht){Pn(!1);return}qr(!1),Pn(!0),Vo()},[Ht,Vo]),nd=d.useCallback(()=>{if(Ha){sr(!1);return}sr(!0),Vo()},[Ha,Vo]),ff=En||Ht,ad=JSON.stringify(pt.filter(m=>m.connected).map(m=>m.deviceId).sort());d.useEffect(()=>{if(!ff)return;const m=JSON.parse(ad);if(m.length===0){ir(!1);return}const x=new AbortController,C=[];let R=!1;return Dn.current!==null&&(window.clearTimeout(Dn.current),Dn.current=null),ir(!0),Ds(Date.now()),Promise.allSettled(m.map(E=>rt(`/api/remote/devices/${encodeURIComponent(E)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:x.signal,timeoutMs:1500},X))).then(()=>{R||[500,1800,4500].forEach((E,G,Y)=>{const ee=window.setTimeout(()=>{R||(V(),Ds(Date.now()),G===Y.length-1&&ir(!1))},E);C.push(ee)})}),()=>{R=!0,x.abort();for(const E of C)window.clearTimeout(E)}},[X,V,ad,ff]);const Ko=new Map,zr=new Map;if(En||Ht||Ha)for(const m of pt){const x=m.deviceId,C=dt&&de===x,E=la(C?"control":"wall",x),G=C?Sl.get(x):Mn.get(x),Y=C?kn.current.get(x)||Zn.current.get(x)||null:cn.current.get(x)||(Kt?Er.current:null),ee={device:m,frame:G,receiveStat:mu[E],paintStat:dl[E],codec:Y?up(Y):{},selectedMonitorIndex:js(m,sn[x]),control:C,controlInputReady:C&&Vs,controlBinding:C&&pe?.deviceId===x?pe:void 0,hubRelay:z?.relay,capturePaused:St.has(x),capturePauseConfirmed:m.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:m.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(z?.heartbeatMs||5e3),now:Date.now()},ie=["open","playing","silent"].includes(Uu),re=An.nativeCallbackDiagnosticsAvailable&&(An.nativeRejectedCallbackCount>0||An.nativeCurrentnessDropCount>0),Ve=ie&&!re,Be=x===De?.deviceId&&Je?{id:"browser-remote-audio",state:Ve?"ok":"warning",label:Ve?"Remote audio is healthy":"Remote audio needs attention",detail:An.lastUpdatedAt>0?[Uu,`context ${An.audioContextState}`,`queue ${Math.round(An.queuedMs)}ms`,`packet ${Math.round(An.lastPacketAgeMs)}ms`,`capture ${An.captureHealthy?"healthy":An.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,An.backendKind?`backend ${An.backendKind}`:"backend unknown",An.helperRequired?`helper ${An.helperAlive&&An.helperPid>0?`pid ${An.helperPid}`:"missing"}`:"helper N/A",`drop ${An.drops}`,`restart ${An.automaticRestarts}`,An.nativeCallbackDiagnosticsAvailable?`native reject ${An.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",An.nativeCallbackDiagnosticsAvailable?`native stale ${An.nativeCurrentnessDropCount}`:"",An.nativeLastDropReason?`native reason ${An.nativeLastDropReason}`:"",nf?`frame #${nf.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(En||Ha){const Ue=$D(ee);En&&Be&&Ue.push(Be),Ko.set(x,Ue)}if(Ht){const Ue=UD(ee);Be&&Ue.push(Be),zr.set(x,Ue)}}const mf=Ha?qD({status:z||{},deviceDiagnostics:[...Ko.values()],codec:up(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Xi}):[],Rm=xl?.atlasReadyTiles??Yu,rd=xl?.atlasTileCount??Yu,yi=Rm===rd?`${rd} tiles`:`${Rm}/${rd} tiles`,pf=Ja.length>0;dt?`${Xu}${ro.toFixed(ro>=10?0:1)}`:pf?`${yi}${Xu}${ro.toFixed(ro>=10?0:1)}`:`${Yu}${Xu}${ro.toFixed(ro>=10?0:1)}`;const sd=In.length,Hc=dt?De?Pa(De):"No Client":sd===0?"No Client":sd>1?`${sd} selected`:De?Pa(De):"No Client",zc=dt?[De?.deviceId].filter(m=>!!m):In.map(m=>m.deviceId),qt=jd[ln]||jd.en,id=qt.sync||jd.en.sync,Sh=r||$?"checking":J?Ut==="pro"?"Pro LTD active":`Plus LTD ${pt.length}/${Uf}`:gl?`Free ${pt.length}/${$f}`:`Upgrade ${pt.length}/${$f}`,$c=J?Ut==="pro"?"Pro active":"Upgrade to Pro LTD":n?Ct==="checkout"?"Opening checkout":Ut==="ltd"?"Buy Pro LTD":"Buy Plus LTD":Ct==="auth"?"Opening Google":"Sign in to buy",so=Ut==="pro"||Ct==="checkout"||Ct==="auth"||r||$,hf=n?.user?.user_metadata,Uc=Bx(hf,"avatar_url","picture"),bi=Bx(hf,"full_name","name")||n?.user?.email||"Google",Ms=bi.slice(0,1).toUpperCase(),jm=z?.started?"Local app ready":"Start LiveDesk",gf=o?.active?"Published":n?"Not published":"Sign in required",Em=/^\d{6}$/.test(z?.pairingPin||"")?z?.pairingPin:"------",wi=m=>{if(typeof window<"u"&&(m==="support"?window.history.pushState({},"","/support"):Nt==="support"&&window.history.pushState({},"","/")),m==="control"){const x=Sa||Wi;if(x&&(Pc(x.deviceId),Ga(!1),Pe(x.deviceId)),bt(m),!Xt){We(!1),Oe(vl);return}We(!0);return}m==="wall"&&Ls(x=>x+1),bt(m),We(!1)},as=Ct==="update"||Bt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(z?.update?.state||""),qc=!!(z?.update?.updateAvailable&&z.update.canApply||as||Bt?.error||!z&&Bt),io=GM(ln),As=d.useCallback(m=>{if(!Bt?.targetIds.includes(m))return;const x=z?.update?.operationId===Bt.operationId?z.update.targets?.find(C=>C.deviceId===m):void 0;switch(x?.state){case"completed":return yo[kx(Bt.operationId,x)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:x.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Bt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Bt.stage==="updating"?x.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Bt.stage==="updated"?{state:"updated",label:"Updated"}:Bt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[z?.update,yo,Bt]),Bn=T&&!!n&&K&&!z?.started,vf=r?"checking":z?.started?"online":Bn?q?"retrying":"connecting":"offline",Dm=r?"Checking Hub":z?.started?`${pt.length} online`:Bn?q?"Hub offline":"Connecting Hub":n?"Hub offline":"Sign in required",fa=z?.deviceName||(Bn?q?"Retrying automatically…":"Trying saved Hub routes…":q?"Desktop Hub unavailable":"Remote management"),Im=T&&g&&!n;return i.jsxs("main",{className:`app-shell ${T?"mobile-console-shell":""}`,"data-mobile-auth-required":Im?"true":void 0,"data-mobile-standalone":T&&j?"true":void 0,"data-mobile-ios":T&&k.isIos?"true":void 0,"data-mobile-android":T&&k.isAndroid?"true":void 0,children:[i.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[i.jsx("div",{className:"rail-brand",title:"LiveDesk",children:i.jsx(d0,{size:25})}),i.jsx("nav",{className:"rail-tools",children:hL.map(m=>{const x=m.icon,C=qp(m.tooltip,ln);return i.jsxs("button",{className:`rail-tool ${m.id==="sync-server"?"sync-server hub-sync-trigger":""} ${Nt===m.id?"active":""} accent-${m.accent}`,onClick:()=>m.id==="sync-server"?wm():wi(m.id),"data-tooltip":m.id==="sync-server"&&nt?void 0:Zg(m.label,m.tooltip,ln),"aria-label":`${m.label}. ${C}`,type:"button",disabled:m.id==="sync-server"&&Ct==="host","aria-busy":m.id==="sync-server"&&Ct==="host","aria-expanded":m.id==="sync-server"?nt:void 0,"aria-haspopup":m.id==="sync-server"?"dialog":void 0,"aria-controls":m.id==="sync-server"&&nt?"hub-sync-popover":void 0,children:[m.id==="sync-server"&&Ct==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(x,{size:19}),i.jsx("span",{children:m.id==="sync-server"&&Ct==="host"?"Syncing…":m.label})]},m.id)})}),i.jsxs("div",{className:"rail-footer",children:[gL.map(m=>{const x=m.icon;return i.jsxs("button",{className:`rail-tool compact ${Nt===m.id?"active":""} accent-${m.accent}`,onClick:()=>wi(m.id),title:m.label,type:"button",children:[i.jsx(x,{size:18}),i.jsx("span",{children:m.label})]},m.id)}),i.jsxs("button",{className:`rail-tool compact local-settings ${hs?"active":""}`,onClick:()=>{bt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),or(!1),We(!1),go(!1)},title:"Settings",type:"button",children:[i.jsx(zp,{size:18}),i.jsx("span",{children:"Settings"})]}),i.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{or(m=>!m)},disabled:r||Ct==="auth","aria-expanded":Ai,title:n?`Account: ${n.user?.email||bi}`:"Sign in with Google",type:"button",children:[n?Uc?i.jsx("img",{src:Uc,alt:bi,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Ms}):i.jsx(Ql,{size:18}),i.jsx("span",{children:n?"Account":"Google"})]}),Ai&&i.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[i.jsxs("div",{className:"account-popover-head",children:[i.jsx("div",{className:"account-popover-avatar",children:n&&Uc?i.jsx("img",{src:Uc,alt:bi,referrerPolicy:"no-referrer"}):n?i.jsx("span",{children:Ms}):i.jsx(Ql,{size:18})}),i.jsxs("div",{children:[i.jsx("strong",{children:n?bi:"Account"}),i.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),i.jsxs("dl",{className:"account-popover-facts",children:[i.jsx("dt",{children:"User"}),i.jsx("dd",{children:n?.user?.email||"Not signed in"}),i.jsx("dt",{children:"Network"}),i.jsx("dd",{children:jm}),i.jsx("dt",{children:"Access"}),i.jsx("dd",{children:gf}),i.jsx("dt",{children:"Plan"}),i.jsx("dd",{children:Sh}),i.jsx("dt",{children:"Ads"}),i.jsx("dd",{children:Ut==="free"?"Standard banner":"Removed"})]}),n?i.jsxs("button",{className:"account-popover-action",onClick:_c,disabled:Ct==="auth",type:"button",children:[i.jsx(qx,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:Uo,disabled:Ct==="auth",type:"button",children:[i.jsx(Ql,{size:16}),"Sign in with Google"]})]})]})]}),T&&N&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>A(!1),children:i.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:m=>m.stopPropagation(),children:[i.jsxs("header",{children:[i.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:i.jsx(e0,{size:20})}),i.jsxs("span",{children:[i.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install LiveDesk on iPhone"}),i.jsx("small",{children:"Open without browser bars and tabs"})]}),i.jsx("button",{type:"button",onClick:()=>A(!1),"aria-label":"Close install guide",children:i.jsx(rr,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",k.browserName==="browser"?"the browser":k.browserName,"'s ",i.jsx("strong",{children:"Share"})," button."]}),i.jsxs("li",{children:["Tap ",i.jsx("strong",{children:"Add to Home Screen"}),"."]}),i.jsx("li",{children:k.isSafari?i.jsxs(i.Fragment,{children:["Turn on ",i.jsx("strong",{children:"Open as Web App"}),", then tap ",i.jsx("strong",{children:"Add"}),"."]}):i.jsxs(i.Fragment,{children:["Confirm the app name, then tap ",i.jsx("strong",{children:"Add"}),"."]})})]}),i.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>A(!1),children:"Got it"})]})}),Im&&i.jsxs("section",{className:"mobile-console-auth","aria-labelledby":"mobile-console-auth-title",children:[i.jsx("span",{className:"mobile-console-auth-mark","aria-hidden":"true",children:i.jsx(ga,{size:26})}),i.jsx("h1",{id:"mobile-console-auth-title",children:r?"Checking your account":"Sign in to LiveDesk"}),i.jsx("p",{children:"Use the same Google account as your LiveDesk Hub."}),i.jsxs("button",{type:"button",onClick:()=>{Uo()},disabled:r||Ct==="auth","aria-busy":r||Ct==="auth",children:[r||Ct==="auth"?i.jsx($r,{className:"spin",size:19,"aria-hidden":"true"}):i.jsx(Ql,{size:19,"aria-hidden":"true"}),Ct==="auth"?"Opening Google…":r?"Checking sign-in…":"Sign in with Google"]}),i.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),Bn&&i.jsx("section",{className:"mobile-console-hub-connecting","aria-label":"LiveDesk Hub connection",children:i.jsxs("div",{className:"mobile-console-hub-connecting-card",role:"status","aria-live":"polite",children:[i.jsx($r,{className:"spin",size:34,"aria-hidden":"true"}),i.jsx("strong",{children:q?"LiveDesk Hub is offline":"Connecting to LiveDesk Hub"}),i.jsx("p",{children:q?"LiveDesk is retrying the saved direct and relay routes automatically.":"Trying the saved direct and relay routes…"}),q&&i.jsxs("button",{type:"button",onClick:()=>V(),children:[i.jsx(ou,{size:16,"aria-hidden":"true"}),"Try now"]})]})}),nt&&i.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(mo,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:io.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>to(),"aria-label":io.closeLabel,children:i.jsx(rr,{size:17})})]}),i.jsx("h2",{id:"hub-sync-title",children:io.title}),i.jsx("p",{id:"hub-sync-description",children:io.description}),i.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[i.jsx(ga,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:io.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>to(),children:io.cancel}),i.jsxs("button",{ref:vn,className:"primary",type:"button",onClick:xm,disabled:Ct==="host",children:[i.jsx(mo,{size:16}),io.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${gs&&!Is?"dock-open":""} ${dt?"control-stage":""} ${Ka?"agents-stage":""} ${Hi?"file-share-stage":""}`,children:[T&&i.jsxs("header",{className:"mobile-console-header",children:[i.jsxs("span",{className:"mobile-console-brand","aria-label":"LiveDesk mobile Console",children:[i.jsx("span",{className:"mobile-console-brand-mark",children:i.jsx(Jl,{size:18})}),i.jsxs("span",{children:[i.jsx("strong",{children:"LiveDesk"}),i.jsx("small",{children:"Mobile Console"})]})]}),i.jsxs("span",{className:`mobile-console-hub state-${vf}`,role:"status","aria-live":"polite",children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:Dm}),i.jsx("small",{children:fa})]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[g&&!j&&(b||k.isIos)&&i.jsx("button",{className:"mobile-console-install",onClick:()=>{B()},"aria-label":"Install LiveDesk app",title:"Install LiveDesk app",type:"button",children:i.jsx(Rp,{size:19,"aria-hidden":"true"})}),qc&&i.jsx("button",{className:"mobile-console-update",onClick:()=>{El()},disabled:as||!z?.update?.canApply,"aria-label":as?"LiveDesk update in progress":"Update LiveDesk","aria-busy":as,type:"button",children:as?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:18,"aria-hidden":"true"})})]})]}),i.jsxs("header",{className:"topbar",children:[i.jsxs("div",{className:"brand",children:[i.jsx("span",{className:"brand-mark",children:i.jsx(Jl,{size:18})}),i.jsxs("div",{className:"brand-copy",children:[i.jsx("h1",{children:"LiveDesk"}),i.jsx("p",{children:"Control wall for local machines"})]}),qc?i.jsxs("button",{className:"topbar-update-button",onClick:()=>{El()},title:Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:`Update LiveDesk to ${z?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,"aria-label":Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:as?"LiveDesk update in progress":`Update LiveDesk to ${z?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,type:"button",disabled:as||!z?.update?.canApply,"aria-busy":as,children:[as?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:19,"aria-hidden":"true"}),as&&z?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[z.update.completedCount||0,"/",z.update.targetCount]}):null]}):null]}),i.jsxs("div",{className:"topbar-tray",children:[Hi&&!dt&&i.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[i.jsxs("div",{children:[i.jsx(nu,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Source"}),i.jsx("strong",{children:"LiveDesk Hub"})]})]}),i.jsx(kv,{size:15}),i.jsx(Ik,{size:16}),i.jsxs("div",{children:[i.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),i.jsxs("span",{children:[i.jsx("small",{children:"Destination"}),i.jsxs("strong",{children:[Ui," Client",Ui===1?"":"s"]}),i.jsx("em",{children:Wr.trim()||"Desktop/LiveDeskFiles"})]})]})]}),gs&&!dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mx,{active:Ha,refreshing:Ha&&Rr,onClick:nd}),i.jsx(dx,{active:En,refreshing:En&&Rr,onClick:td}),i.jsx(fx,{active:Ht,refreshing:Ht&&Rr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(ux,{controller:Sc,onError:Oe}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:mL.map(m=>i.jsx("button",{className:Cn===m.id?"active":"",onClick:()=>{qn(m.id),cr(m.fps),rL(m.id)},title:m.label+" Wall streaming ("+m.fps+" fps)","aria-pressed":Cn===m.id,type:"button",children:m.label},m.id))}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:pL.map(m=>i.jsx("button",{className:Gt===m.id?"active":"",onClick:()=>ra(m.id),type:"button",children:m.label},m.id))})]}),dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mx,{active:Ha,refreshing:Ha&&Rr,onClick:nd}),i.jsx(dx,{active:En,refreshing:En&&Rr,onClick:td}),i.jsx(fx,{active:Ht,refreshing:Ht&&Rr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(ux,{controller:Sc,onError:Oe})]})]})]}),Ha&&gs&&i.jsx(DD,{items:mf,collectedAt:Zs,onClose:()=>sr(!1)}),Ud?i.jsxs("section",{className:"doc-page",lang:ln,dir:ln==="ar"?"rtl":"ltr",children:[i.jsxs("section",{className:"doc-hero",children:[i.jsxs("div",{className:"doc-hero-copy",children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Hp,{size:16}),qt.eyebrow]}),i.jsx("h2",{children:qt.title}),i.jsx("p",{children:qt.intro})]}),i.jsxs("label",{className:"doc-language-picker",children:[i.jsxs("span",{children:[i.jsx(Lk,{size:17}),qt.languageLabel]}),i.jsx("select",{value:ln,onChange:m=>il(m.target.value),children:yL.map(m=>i.jsx("option",{value:m.id,children:m.label},m.id))})]})]}),i.jsx("section",{className:"doc-grid",children:qt.sections.map((m,x)=>{const R=[mo,jp,Sb,ga,eh][x]||Hp;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(R,{size:19})}),i.jsxs("div",{children:[i.jsx("h3",{children:m.title}),i.jsx("p",{children:m.body}),i.jsx("ul",{children:m.points.map(E=>i.jsx("li",{children:E},E))})]})]},m.title)})}),id&&i.jsxs("section",{className:"doc-sync",children:[i.jsxs("div",{className:"doc-sync-head",children:[i.jsx(Sb,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:id.title}),i.jsx("p",{children:id.body})]})]}),i.jsx("ul",{children:id.points.map(m=>i.jsx("li",{children:m},m))})]}),i.jsxs("section",{className:"doc-firewall",children:[i.jsxs("div",{className:"doc-firewall-head",children:[i.jsx(ga,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:qt.firewall.title}),i.jsx("p",{children:qt.firewall.body})]})]}),i.jsx("ul",{children:qt.firewall.points.map(m=>i.jsx("li",{children:m},m))})]}),i.jsxs("section",{className:"doc-command-panel",children:[i.jsxs("div",{className:"doc-command-head",children:[i.jsx(jp,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:qt.commands.title}),i.jsx("p",{children:qt.commands.body})]})]}),i.jsxs("div",{className:"doc-command-list",children:[qt.commands.manager&&i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.manager}),i.jsx("code",{children:uf}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(uf),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.primary}),i.jsx("code",{children:ta}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(ta),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.slot}),i.jsx("code",{children:`${ta} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(`${ta} 3`),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]})]})]})]}):Ka?i.jsx(ox,{hubUrl:X,devices:W}):Hi?i.jsx(DE,{hubUrl:X,devices:pt,localFeatureAccess:Xt,upgradeNotice:vl,remoteDirectory:Wr,onRemoteDirectoryChange:ol,targetMode:No,selectedTargetIds:Ea,onTargetModeChange:$d,onTargetToggle:m=>hl(x=>x.includes(m)?x.filter(C=>C!==m):[...x,m]),filePickerRef:To,folderPickerRef:gm,onBrowserFileImport:m=>{Am(m)},onBrowserFolderImport:m=>{Am(m)},onNotice:Oe,onTransferChange:m=>{if(!m){di(null);return}const x=m.state==="failed"||m.state==="partially-failed"||m.state==="cancelled"?"failed":m.state==="completed"?"queued":m.state==="sending"?"sending":"reading";di({id:m.id,status:x,progress:m.progress,message:m.message}),["completed","partially-failed","failed","cancelled"].includes(m.state)&&window.setTimeout(()=>di(C=>C?.id===m.id?null:C),4500)}}):Au?i.jsx(r0,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Uo}):hs?i.jsx(QN,{hubUrl:X,runtimeRole:z?.runtimeRole||"hub",runtimeDeviceId:z?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:i.jsxs(YN,{children:[i.jsx("div",{className:"settings-section-grid",children:i.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Pair a Client"}),i.jsx("h3",{children:"Connect another local PC"})]}),i.jsx(Ar,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Em}),i.jsxs("button",{className:"text-button ghost compact",onClick:Sm,disabled:!z?.started||Ct==="pin",type:"button",children:[i.jsx(nl,{size:15}),Ct==="pin"?"Creating":"New PIN"]})]})]})}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"File transfer"}),i.jsx("h3",{children:"Client destination folder"})]}),i.jsx(Ad,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:Wr,onChange:m=>ol(m.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:i.jsx(ZN,{hubUrl:X,showToast:Oe}),captureGallery:i.jsx(ED,{hubUrl:X,onToast:Oe})}):Mu?i.jsxs("section",{className:"pricing-page",children:[i.jsxs("header",{className:"pricing-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Kg,{size:15})," LiveDesk plans"]}),i.jsx("h2",{children:"Choose the plan that fits your wall"}),i.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),i.jsx("button",{className:"pricing-close",onClick:()=>wi("wall"),title:"Close pricing",type:"button",children:i.jsx(rr,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:ju.name}),i.jsxs("small",{children:[pt.length,"/",EI(Io)," connected devices"]})]}),i.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[i.jsxs("article",{className:`pricing-plan-card ${Ut==="free"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),i.jsx("strong",{children:"$0"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.free.audience}),i.jsx("h3",{children:"Monitor your local wall"}),i.jsx("p",{children:Xc.free.note}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," Up to ",$f," devices"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Standard ad-supported banner"]})]}),i.jsx("span",{className:"pricing-current-label",children:Ut==="free"?"Current plan":"Included for everyone"})]}),i.jsxs("article",{className:`pricing-plan-card featured ${Ut==="ltd"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge plus",children:[i.jsx(Pk,{size:14})," Plus"]}),i.jsx("strong",{children:"$5"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.ltd.audience}),i.jsx("h3",{children:"Ad-free monitoring"}),i.jsx("p",{children:"More room for personal computers without the standard banner."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," Up to ",Uf," devices"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," No standard ad banner"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," ",Xc.ltd.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>$n("ltd"):Uo,disabled:Ut!=="free"||Ct==="checkout"||Ct==="auth"||r||$,type:"button",children:[i.jsx(Vf,{size:16}),Ut==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),i.jsxs("article",{className:`pricing-plan-card pro ${Ut==="pro"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge pro",children:[i.jsx(ga,{size:14})," Pro"]}),i.jsx("strong",{children:"$15"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.pro.audience}),i.jsx("h3",{children:"For serious operations"}),i.jsx("p",{children:"Commercial-ready monitoring for larger studios, offices, and teams."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," 30+ Client walls"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Commercial use included"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," ",Xc.pro.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>$n("pro"):Uo,disabled:Ut==="pro"||Ct==="checkout"||Ct==="auth"||r||$,type:"button",children:[i.jsx(Vf,{size:16}),Ut==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),i.jsxs("section",{className:"pricing-includes",children:[i.jsxs("div",{children:[i.jsx(Ar,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ slots"})]}),i.jsxs("div",{children:[i.jsx(Hf,{size:17}),i.jsx("span",{children:"Focused control"}),i.jsx("strong",{children:"Local-first"})]}),i.jsxs("div",{children:[i.jsx(ig,{size:17}),i.jsx("span",{children:"Remote audio"}),i.jsx("strong",{children:"Available"})]}),i.jsxs("div",{children:[i.jsx(Ad,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(_a,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>$n(Ut==="ltd"?"pro":"ltd"):Uo,disabled:so,type:"button",children:[i.jsx(Vf,{size:18}),$c]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Is?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:hc,className:`screen-wall-panel ${yh?"drop-active":""}`,onClick:m=>{m.currentTarget===m.target&&qo()},onDragEnter:m=>{m.preventDefault(),zd(!0)},onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="copy"},onDragLeave:m=>{m.currentTarget===m.target&&zd(!1)},onDrop:cf,children:[Ja.length>0&&i.jsx("canvas",{ref:Gd,className:"atlas-source-canvas",width:yn?.width||1920,height:yn?.height||1080,"aria-hidden":"true"}),T&&gs&&!dt&&i.jsxs("section",{className:"mobile-console-selection","aria-label":"Selected computer actions",children:[i.jsxs("div",{className:"mobile-console-selection-copy",children:[i.jsx("span",{children:"Selected computer"}),i.jsx("strong",{children:Hc}),i.jsx("small",{children:De?`${De.platform||"Client"} · ${fo(De)} display${fo(De)===1?"":"s"}`:"Tap a computer below, then choose an action."})]}),i.jsxs("div",{className:"mobile-console-actions",role:"toolbar","aria-label":"Selected computer quick actions",children:[i.jsxs("button",{onClick:()=>De&&void no(De.deviceId),disabled:!bs||!!en,type:"button",children:[i.jsx(Hf,{size:17}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Je?"active":"",onClick:()=>{sf()},disabled:!Eu||!!en,"aria-pressed":Je,type:"button",children:[en==="audio"?i.jsx($r,{className:"spin",size:17}):i.jsx(ig,{size:17}),i.jsx("span",{children:"Audio"})]}),i.jsxs("button",{className:hr?"":"active",onClick:()=>{Oc()},disabled:Ia.length===0||!!en,"aria-pressed":!hr,type:"button",children:[en==="video"?i.jsx($r,{className:"spin",size:17}):hr?i.jsx(Cb,{size:17}):i.jsx(kb,{size:17}),i.jsx("span",{children:hr?"Pause":"Resume"})]}),i.jsxs("button",{onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Do,type:"button",children:[en==="restart"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vg,{size:17}),i.jsx("span",{children:"Restart"})]})]})]}),dt?i.jsx("section",{className:"control-focus",children:i.jsxs("div",{className:"control-wall",children:[De&&i.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${Pa(De)}`,children:[i.jsx("strong",{className:"control-computer-name",title:Pa(De),children:Pa(De)}),Nm.map(m=>i.jsxs("button",{className:m.index===ao?"active":"",onClick:()=>Cm(De.deviceId,m.index),title:QI(m),type:"button",children:[i.jsx("span",{children:m.name||`Display ${m.index+1}`}),m.width>0&&m.height>0&&i.jsxs("small",{children:[m.width,"x",m.height]})]},m.index))]}),De&&Vs&&i.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:mI.map(m=>{const x=m.code==="MetaLeft"&&tl(De.platform)?"Cmd":m.label,C=Et.includes(m.code);return i.jsx("button",{className:C?"active":"",type:"button","aria-pressed":C,title:`Hold ${x} on the remote computer`,onClick:()=>ht.current?.(m.code),children:x},m.code)})}),De?i.jsx(Wg,{device:De,frame:Ke,selected:!1,controlEnabled:bs&&ze&&Vs,showStatus:_n.showScreenStatus,showDeviceTitle:!1,monitorIndex:js(De,sn[De.deviceId]),monitorCount:fo(De),onSelect:()=>{},onFocusDevice:()=>Pe(De.deviceId),onOpenControl:()=>no(De.deviceId),onCycleMonitor:m=>Qu(De.deviceId,m),onCanvasReady:Du,sendInput:$o,remoteModifierState:Hu,presentationReady:Od,remoteDiagnostics:Ht?zr.get(De.deviceId):En?Ko.get(De.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},De.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(Ar,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),De&&Ru&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(ga,{size:22,"aria-hidden":"true"}),i.jsx("strong",{children:"Accessibility permission required"}),i.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),De&&!Ru&&!Od&&i.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[Ee!=="error"&&i.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),i.jsx("strong",{children:Ee==="error"?"Connection failed":"Connecting"}),i.jsx("small",{children:Ee==="error"?"See the notification for details. Reopen Control to retry.":Ho||st?"Control stream is recovering. See the notification for details.":kl==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Gt==="list"?i.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[i.jsxs("div",{className:"wall-device-list-head",role:"row",children:[i.jsx("span",{role:"columnheader",children:"Computer"}),i.jsx("span",{role:"columnheader",children:"Status"}),i.jsx("span",{role:"columnheader",children:"CPU"}),i.jsx("span",{role:"columnheader",children:"GPU"}),i.jsx("span",{role:"columnheader",children:"RAM"}),i.jsx("span",{role:"columnheader",children:"VRAM"}),i.jsx("span",{role:"columnheader",children:"Network"}),i.jsx("span",{role:"columnheader",children:"HDD"}),i.jsx("span",{role:"columnheader",children:"Temp"})]}),qi.length>0?qi.map(({device:m,slotNumber:x})=>i.jsx(xL,{device:m,slotNumber:x,selected:mr.has(m.deviceId),updateIndicator:As(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote",onSelect:()=>Vu(m.deviceId),onOpenControl:()=>no(m.deviceId)},m.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(Ar,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"No connected computers"})]})]}):Kt?i.jsx("div",{className:`screen-wall atlas-slot-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&qo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:mr.has(m.deviceId),controlEnabled:!1,showStatus:wt.showScreenStatus,monitorIndex:js(m,sn[m.deviceId]),monitorCount:fo(m),onSelect:()=>Vu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Qu(m.deviceId,C),onCanvasReady:Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(m.platform)})==="direct"?Fo:Ki,sendInput:$o,remoteModifierState:Hu,updateIndicator:As(m.deviceId),presentationReady:wt.autoStartLive&&Za.includes(m.deviceId)?xo.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Za.includes(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(zx,{index:x},`slot-${x}`))}):i.jsx("div",{className:`screen-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&qo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:mr.has(m.deviceId),controlEnabled:bs&&ze&&Vs&&De?.deviceId===m.deviceId,showStatus:wt.showScreenStatus,monitorIndex:js(m,sn[m.deviceId]),monitorCount:fo(m),onSelect:()=>Vu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Qu(m.deviceId,C),onCanvasReady:Fo,sendInput:$o,remoteModifierState:Hu,updateIndicator:As(m.deviceId),presentationReady:wt.autoStartLive&&Za.includes(m.deviceId)?xo.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Za.includes(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(zx,{index:x},`slot-${x}`))}),i.jsx(kL,{visible:vm&&!dt})]}),!hs&&i.jsxs("aside",{className:`right-dock actions-mode ${Is?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>go(m=>!m),"aria-label":Is?"Show control panel":"Hide control panel",title:Is?"Show control panel":"Hide control panel",type:"button",children:Is?i.jsx(n0,{size:18}):i.jsx(Mv,{size:18})}),!Is&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:Su,className:"hidden-file-input",type:"file",multiple:!0,onChange:m=>{m.currentTarget.files&&lf(m.currentTarget.files),m.currentTarget.value=""}}),i.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[i.jsx(Yc,{label:"Control",tooltip:De?Ru?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":bs?Vs?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(De){if(dt&&ze){We(!1),Oe("Remote control paused. Screen viewing stays on.");return}no(De.deviceId)}},disabled:!bs||!!en,active:ze,pressed:dt&&ze,children:i.jsx(Hf,{size:17})}),i.jsx(Yc,{label:"Audio",tooltip:De?ys?Je?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{sf()},disabled:!Eu||!!en,active:Je,pressed:Je,children:en==="audio"?i.jsx($r,{className:"spin",size:17}):i.jsx(ig,{size:17})}),i.jsx(Yc,{label:Lo?"Retry pause":hr?"Pause video":"Resume video",tooltip:ws.length===0?"Select one or more Clients to pause video":Lo?"Retry every selected Client whose capture shutdown is unconfirmed":hr?`Pause video for ${Ia.length} selected Client${Ia.length===1?"":"s"}`:`Resume video for ${Ia.length} selected Client${Ia.length===1?"":"s"}`,onClick:()=>{Oc()},disabled:Ia.length===0||!!en,active:!hr,pressed:!hr,children:en==="video"?i.jsx($r,{className:"spin",size:17}):!hr&&!Lo?i.jsx(kb,{size:17}):i.jsx(Cb,{size:17})}),i.jsx(Yc,{label:"Send files",tooltip:In.length===0&&!dt?"Select one or more Clients to send files":De?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Oe(`Choose files to send to ${Hc}.`),Su.current?.click()},disabled:!!en||!Xt||(dt?!De:In.length===0),children:i.jsx(Ad,{size:17})}),i.jsx(Yc,{label:"Restart",tooltip:De?Do?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Do,children:en==="restart"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vg,{size:17})}),i.jsx(Yc,{label:"Sleep",tooltip:De?Do?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Dl("sleep")},disabled:!De||!Xt||!!en||!Do,children:en==="sleep"?i.jsx($r,{className:"spin",size:17}):i.jsx(_k,{size:17})}),i.jsx(Yc,{label:"Shut down",tooltip:De?Do?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Dl("shutdown")},disabled:!De||!Xt||!!en||!Do,danger:!0,children:en==="shutdown"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vx,{size:17})})]})]}),i.jsx(ox,{hubUrl:X,devices:W,variant:"dock",selectedDeviceIds:zc})]})]})]})})]}),T&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Nt==="wall"?"active":"",onClick:()=>wi("wall"),type:"button",children:[i.jsx(t0,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:dt?"active":"",onClick:()=>De&&void no(De.deviceId),disabled:!De||!bs,type:"button",children:[i.jsx(Hf,{size:19}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Hi?"active":"",onClick:()=>wi("share-files"),type:"button",children:[i.jsx(Kf,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:Ka?"active":"",onClick:()=>wi("agents"),type:"button",children:[i.jsx(jp,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:hs?"active":"",onClick:()=>wi("settings"),type:"button",children:[i.jsx(zp,{size:19}),i.jsx("span",{children:"Settings"})]})]}),Oi&&i.jsxs("aside",{className:`transfer-bar state-${Oi.status}`,"aria-live":"polite",children:[i.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Oi.status==="queued"?i.jsx(_a,{size:18}):Oi.status==="failed"?i.jsx(rr,{size:18}):i.jsx(Qx,{size:18})}),i.jsxs("div",{className:"transfer-bar-copy",children:[i.jsx("p",{children:Oi.message}),i.jsx("div",{className:"transfer-bar-track",children:i.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Oi.progress))}%`}})})]}),i.jsxs("strong",{children:[Math.max(0,Math.min(100,Oi.progress)),"%"]})]}),oe&&i.jsxs("aside",{className:`livedesk-toast tone-${oe.tone}`,role:oe.tone==="error"?"alert":"status","aria-live":oe.tone==="error"?"assertive":"polite","aria-busy":oe.tone==="progress",children:[oe.tone==="progress"&&i.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),i.jsx("span",{children:oe.message}),i.jsx("button",{className:"livedesk-toast-close",onClick:()=>Oe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(rr,{size:15})})]})]})}const AL=1e3,NL=5e3;function TL(){return typeof window>"u"?!1:(!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches)&&window.matchMedia("(pointer: coarse)").matches}function RL(){return typeof window>"u"?[]:[...new Set([window.location.origin,Un].filter(Boolean))]}function jL(){const n=Av(),r=TL(),o=n||r,l=n||typeof window>"u"?Un:window.location.origin,u=o?{role:"hub",baseUrl:l}:null,[f,h]=d.useState(u),g=d.useRef(null);return d.useEffect(()=>{if(o){h(j=>j?.role==="hub"&&j.baseUrl===l?j:{role:"hub",baseUrl:l});return}let y=!1,w=!1,b=null;const S=new AbortController,k=async()=>{for(const j of RL()){if(S.signal.aborted)return;try{const T=(await rt("/api/runtime/status",{signal:S.signal,timeoutMs:900},j)).role==="hub"?"hub":"client";w=!0,y||h(_=>_?.role===T&&_.baseUrl===j?_:{role:T,baseUrl:j});return}catch{if(S.signal.aborted)return}}},N=()=>{Up(g,k).finally(()=>{!y&&!S.signal.aborted&&(b=window.setTimeout(N,w?NL:AL))}).catch(()=>{})};N();const A=window.setTimeout(()=>{!y&&!w&&h(j=>j?.role==="client"&&j.baseUrl===Un?j:{role:"client",baseUrl:Un})},2500);return()=>{y=!0,S.abort(new Error("LiveDesk runtime role probe stopped.")),b!==null&&window.clearTimeout(b),window.clearTimeout(A)}},[null,o,l]),f?f.role==="client"?i.jsx(sA,{runtimeBaseUrl:f.baseUrl}):i.jsx(ML,{runtimeBaseUrl:f.baseUrl}):i.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[i.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),i.jsx("strong",{children:"Starting LiveDesk"}),i.jsx("p",{children:"Loading this computer's assigned role..."})]})}qk.createRoot(document.getElementById("root")).render(i.jsx(d.StrictMode,{children:i.jsx(jL,{})}));"serviceWorker"in navigator&&window.isSecureContext&&window.location.protocol==="https:"&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).then(t=>t.update()).catch(t=>{console.warn("[LiveDesk] PWA service worker registration failed.",t)})},{once:!0});
|
|
187
|
+
${Lt}`:Lt;try{if(H==="custom"){const yt=await yD(t,K,z);if(!yt.ok)throw new Error(yt.error||"Custom Agent policy could not be saved.")}const ut=await fD(t,{instruction:Xe,deviceIds:He,permissionMode:H,customPolicyId:K});if(!ut.ok||!ut.runId)throw new Error(ut.error||"Codex Agent run could not be started.");V(ut.approvals||[]),Qe({runId:ut.runId,stage:ut.stage||ut.status||"queued",message:ut.progressMessage||"Codex request queued on the Hub."}),_(ut.runId)}catch(ut){A(yt=>[...yt,{type:"error",id:Of("codex-run-error"),text:AD(ut)}])}},Re=async(fe,te)=>{ve(fe.approvalId);try{const ce=await gD(t,fe.runId,fe.approvalId,te);if(!ce.ok)throw new Error(ce.error||"Agent approval could not be applied.");await pe(fe.runId)}catch(ce){ae(ce instanceof Error?ce.message:String(ce))}finally{ve("")}},st=async fe=>{ve(fe.approvalId);try{const te=await vD(t,fe.runId,fe.approvalId);if(!te.ok)throw new Error(te.error||"Agent approval could not be rejected.");await pe(fe.runId)}catch(te){ae(te instanceof Error?te.message:String(te))}finally{ve("")}},jt=async(fe,te)=>{F(fe);try{if(te){const Ne=await pD(t,te);for(const He of Ne.taskBatches||[])ke(He);_(He=>He===te?"":He),Qe(He=>He?.runId===te?null:He);return}const ce=await wD(t,fe);ke(ce),I(Ne=>Ne===fe?"":Ne)}catch(ce){ae(ce instanceof Error?ce.message:String(ce))}finally{F("")}},O=async()=>{if(!(J||!j&&!T)){$(!0);try{const fe=await hD(t);if(!fe.ok)throw new Error(fe.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),_(""),Qe(null),V([]),A(te=>te.map(ce=>ce.type==="task"&&["queued","running"].includes(ce.status)?{...ce,status:"cancelled",states:ce.states.map(Ne=>["queued","running"].includes(Ne.status)?{...Ne,status:"cancelled",stage:"Cancelled",error:"Cancelled by user."}:Ne)}:ce))}catch(fe){ae(fe instanceof Error?fe.message:String(fe))}finally{$(!1)}}},ze=async fe=>{F(fe);try{const te=await xD(t,fe);if(!te.ok||!te.batch||!te.batchId)throw new Error(te.error||"재시도하지 못했습니다.");A(ce=>ce.map(Ne=>Ne.type==="task"&&Ne.batchId===fe?{...Ne,batchId:te.batchId,states:_g(te.batch,n),status:te.batch.status}:Ne)),I(te.batchId)}catch(te){ae(te instanceof Error?te.message:String(te))}finally{F("")}},We=fe=>{k(fe),Pe(!1),window.requestAnimationFrame(()=>ue.current?.focus())},Et=d.useMemo(()=>n.filter(Zp),[n]),lt=d.useMemo(()=>Et.filter(fe=>g.includes(fe.deviceId)),[Et,g]),ht=f==="auto"?`Auto · ${Et.length} available`:f==="all"?`All ${Et.length} computers`:lt.length===1?Xp(lt[0]):`${lt.length} selected`,Je=f==="auto"?"LiveDesk chooses the best computer for each task.":f==="all"?"The Agent may coordinate every connected computer.":lt.length>0?lt.map(Xp).join(" · "):"Select one or more computers on the Wall.",be=f==="selected"&<.length===1?["Diagnose this computer","Analyze recent errors","Summarize running applications","Check disk and GPU capacity"]:f==="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"],je=f==="selected"?lt.length>0?"What should this computer do?":"Choose a computer or use Auto.":f==="all"?"Use all your computers together.":"What should LiveDesk handle?",Ae=f==="auto"?"The Hub Codex Agent can inspect the available computers and choose the best target.":"Describe the outcome. The Hub Codex Agent will plan approved commands and show progress per computer.";return i.jsxs("section",{className:`agents-page ${u?"agents-dock-console":""}`,children:[u&&i.jsxs("header",{className:"agent-console-header",children:[i.jsxs("div",{className:"agent-console-title",children:[i.jsx("span",{className:"agent-console-mark",children:i.jsx(ec,{size:16})}),i.jsxs("div",{children:[i.jsx("small",{children:"Hub Codex Agent"}),i.jsx("strong",{children:"Command Console"})]}),i.jsx("i",{children:"Ready"})]}),i.jsxs("section",{className:"agent-console-target","aria-label":"Agent target scope",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Target"}),i.jsx("strong",{children:ht}),i.jsx("small",{children:Je})]}),i.jsxs("div",{className:"agent-console-target-modes",children:[i.jsxs("button",{className:f==="selected"?"active":"",onClick:()=>h("selected"),type:"button",children:[i.jsx(al,{size:12})," Selected"]}),i.jsxs("button",{className:f==="all"?"active":"",onClick:()=>h("all"),type:"button",children:[i.jsx(nm,{size:12})," All"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(nm,{size:12})," Group"]}),i.jsxs("button",{className:f==="auto"?"active":"",onClick:()=>h("auto"),type:"button",children:[i.jsx(ec,{size:12})," Auto"]})]})]}),i.jsx("div",{className:"agent-console-interaction-modes","aria-label":"Agent interaction mode",children:["auto","ask","plan","execute"].map(fe=>i.jsxs("button",{className:w===fe?"active":"",onClick:()=>b(fe),type:"button",children:[fe==="auto"?i.jsx(ec,{size:12}):fe==="execute"?i.jsx(Ar,{size:12}):null,fe[0].toUpperCase()+fe.slice(1)]},fe))})]}),i.jsxs("div",{className:"agents-workspace",children:[(j||T)&&i.jsxs("div",{className:"agents-page-status",children:[i.jsxs("span",{children:[Ge.length," Clients · ",kD(H)]}),i.jsx("button",{type:"button",className:"agents-stop-all",onClick:()=>{O()},disabled:J,children:J?"Stopping…":"Stop all"})]}),P&&i.jsx("div",{className:"agents-permission-modal-backdrop",role:"presentation",children:i.jsxs("section",{className:"agents-permission-modal",role:"dialog","aria-modal":"true","aria-labelledby":"full-access-title",children:[i.jsx("span",{className:"agents-permission-modal-icon",children:i.jsx(th,{size:20})}),i.jsx("h3",{id:"full-access-title",children:"Confirm Full Access"}),i.jsx("p",{children:"Codex may change files, run commands, manage applications, and modify system state on the selected Clients. This run is still limited to the selected devices, the fixed policy, and the tool budget."}),i.jsxs("div",{className:"agents-permission-modal-actions",children:[i.jsx("button",{type:"button",onClick:()=>se(null),children:"Cancel"}),i.jsx("button",{type:"button",className:"danger",onClick:()=>{const fe=P;se(null),Z(!0),qe(fe.instruction,fe.targetIds,!0)},children:"Run with Full Access"})]})]})}),Se&&i.jsx("div",{className:"agents-error",role:"alert",children:Se}),i.jsx(WE,{items:N,onCancel:jt,onRetry:ze,busyBatchId:B,approvals:q,onApprove:Re,onReject:st,busyApprovalId:X,progress:de,emptyTitle:u?je:void 0,emptyBody:u?Ae:void 0}),u&&N.length===0&&!de&&i.jsx("div",{className:"agent-console-suggestions","aria-label":"Suggested Agent commands",children:be.map(fe=>i.jsx("button",{type:"button",onClick:()=>We(fe),children:fe},fe))}),i.jsxs("div",{className:"agents-composer-shell",children:[ye&&i.jsx(oD,{devices:n,targetMode:f,selectedIds:g,permissionMode:H,customCategories:z,onSelectPrompt:We,onClose:()=>Pe(!1)}),i.jsx(LE,{ref:ue,value:S,onChange:k,onSubmit:()=>{qe()},onOpenSuggestedTasks:()=>Pe(fe=>!fe),suggestedOpen:ye,suggestedTaskCount:me,disabled:!!j||!!T,placeholder:u?"Tell LiveDesk what outcome you want...":void 0,compact:u})]})]}),!u&&i.jsxs("aside",{className:"agents-target-sidebar","aria-label":"Agent targets and permissions",children:[i.jsx(lD,{devices:n,mode:f,selectedIds:g,onModeChange:h,onToggle:fe=>y(te=>te.includes(fe)?te.filter(ce=>ce!==fe):[...te,fe]),permissionMode:H,onPermissionModeChange:fe=>{D(fe),fe!=="full-access"&&Z(!1)}}),H==="custom"&&i.jsxs("section",{className:"agents-custom-policy","aria-label":"Custom Agent permissions",children:[i.jsxs("div",{className:"agents-custom-policy-head",children:[i.jsxs("div",{children:[i.jsx("span",{className:"agents-section-label",children:"Custom policy"}),i.jsx("strong",{children:"Choose what Codex may do automatically."})]}),i.jsx("span",{children:"Denied actions never reach a device."})]}),i.jsx("div",{className:"agents-custom-policy-grid",children:PE.map(fe=>i.jsxs("label",{children:[i.jsx("span",{children:MD(fe)}),i.jsxs("select",{value:z[fe],onChange:te=>W(ce=>({...ce,[fe]:te.target.value})),children:[i.jsx("option",{value:"allow",children:"Allow automatically"}),i.jsx("option",{value:"ask",children:"Ask every time"}),i.jsx("option",{value:"deny",children:"Deny"})]})]},fe))})]})]})]})}function _S(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function FS(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function OS(t,n,r){const o=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:_S(n.target)})),l=await Nv(`/api/captures?metadata=${o}`,{method:"POST",headers:{"Content-Type":t.type||"application/octet-stream"},body:t},r);if(!l.ok)throw new Error(await FS(l));return await l.json()}async function ND(t,n){return await rt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:_S(t.target)})},n)}async function TD(t,n,r,o){const l=await Nv(`/api/capture-sessions/${encodeURIComponent(t)}/chunks/${n}`,{method:"PUT",headers:{"Content-Type":r.type||"application/octet-stream"},body:r},o);if(!l.ok)throw new Error(await FS(l));return await l.json()}async function RD(t,n,r){return await rt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function lx(t,n){await rt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function jD(t){return await rt("/api/captures",void 0,t)}function cx(t,n){return`${cu(n)}/api/captures/${encodeURIComponent(t)}/content`}async function ED(t,n){return await rt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function DD({hubUrl:t,onToast:n}){const[r,o]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{o((await jD(t)).captures||[])}catch(g){n(g instanceof Error?g.message:String(g))}finally{u(!1)}},[t,n]);d.useEffect(()=>{f()},[f]);const h=async g=>{const y=cx(g.id,t);if(navigator.share)try{await navigator.share({title:g.fileName,url:y});return}catch{}window.open(y,"_blank","noopener,noreferrer")};return i.jsxs("section",{className:"capture-gallery",children:[i.jsxs("header",{children:[i.jsxs("div",{children:[i.jsx("span",{className:"settings-eyebrow",children:"Capture Gallery"}),i.jsx("h2",{children:"Saved captures"})]}),i.jsxs("button",{className:"text-button",onClick:()=>{f()},type:"button",children:[i.jsx(ou,{size:15})," Refresh"]})]}),l?i.jsx("p",{className:"settings-help",children:"Loading captures..."}):r.length===0?i.jsx("p",{className:"settings-help",children:"No captures saved yet."}):i.jsx("div",{className:"capture-gallery-grid",children:r.map(g=>{const y=cx(g.id,t);return i.jsxs("article",{className:"capture-gallery-card",children:[g.mimeType.startsWith("image/")?i.jsx("img",{src:y,alt:g.target.label}):i.jsx("video",{src:y,controls:!0,preload:"metadata"}),i.jsxs("div",{className:"capture-gallery-card-body",children:[i.jsx("strong",{children:g.fileName}),i.jsxs("small",{children:[g.target.label," · ",new Date(g.createdAt).toLocaleString()," · ",Math.ceil(g.sizeBytes/1024)," KB"]}),i.jsxs("div",{children:[i.jsx("button",{className:"icon-button",title:"Open","aria-label":"Open",onClick:()=>window.open(y,"_blank","noopener,noreferrer"),type:"button",children:i.jsx(Tk,{size:15})}),i.jsx("a",{className:"icon-button",title:"Download","aria-label":"Download",href:`${y}?download=1`,download:g.fileName,children:i.jsx(Bp,{size:15})}),i.jsx("button",{className:"icon-button",title:"Share","aria-label":"Share",onClick:()=>{h(g)},type:"button",children:i.jsx(e0,{size:15})}),i.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&ED(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:i.jsx(Yx,{size:15})})]})]})]},g.id)})})]})}function Cp(t){if(!t)return"";const n=Math.max(0,Math.floor((Date.now()-t)/1e3)),r=Math.floor(n/3600),o=Math.floor(n%3600/60),l=n%60;return r>0?`${String(r).padStart(2,"0")}:${String(o).padStart(2,"0")}:${String(l).padStart(2,"0")}`:`${String(o).padStart(2,"0")}:${String(l).padStart(2,"0")}`}function ux({controller:t,compact:n=!1,onFirstRollingUse:r,onError:o}){const{state:l,settings:u,videoSupported:f}=t,h=async b=>{try{await b()}catch(S){o?.(S instanceof Error?S.message:String(S))}},g=async()=>{if(u.rollingEnabled){t.setRollingEnabled(!1);return}(r?await r():window.confirm(`Keep the most recent 30 seconds in memory temporarily?
|
|
188
|
+
Nothing is saved until you press Save Last 30s.`))&&t.setRollingEnabled(!0)},y=l.recording?`Stop recording · ${Cp(l.recordingStartedAt)}`:`Start recording · ${l.targetLabel}`,w=l.timelapse?`Stop timelapse · ${Cp(l.timelapseStartedAt)}`:`Start timelapse · ${u.timelapseIntervalSeconds}s interval`;return i.jsxs("div",{className:`capture-toolbar ${n?"compact":""} ${l.recording?"recording-active":""}`,"aria-label":"Capture actions",children:[i.jsx("button",{className:"capture-action","aria-label":`Take screenshot · ${l.targetLabel}`,title:`Take screenshot · ${l.targetLabel}`,disabled:l.busy,onClick:()=>{h(t.takeScreenshot)},type:"button",children:i.jsx(Rk,{size:17})}),i.jsx("button",{className:`capture-action ${l.recording?"active":""}`,"aria-label":y,title:y,disabled:!f||l.busy||l.timelapse,onClick:()=>{h(l.recording?t.stopRecording:t.startRecording)},type:"button",children:l.recording?i.jsxs(i.Fragment,{children:[i.jsx(xb,{size:14,fill:"currentColor"}),i.jsx("span",{children:Cp(l.recordingStartedAt)})]}):i.jsx(Xx,{size:18})}),i.jsxs("button",{className:"capture-action","aria-label":l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",title:l.bufferEnabled?`Save last 30 seconds · ${l.bufferSeconds}s ready`:"Enable Last 30s memory buffer",disabled:!f||l.recording||l.timelapse||l.busy||l.bufferEnabled&&l.bufferSeconds<1,onClick:()=>l.bufferEnabled?void h(t.saveLast30Seconds):void g(),type:"button",children:[i.jsx(jk,{size:17}),i.jsx("small",{children:"30s"})]}),i.jsx("button",{className:`capture-action ${l.timelapse?"timelapse-active":""}`,"aria-label":w,title:w,disabled:!f||l.busy||l.recording,onClick:()=>{h(l.timelapse?t.stopTimelapse:t.startTimelapse)},type:"button",children:l.timelapse?i.jsxs(i.Fragment,{children:[i.jsx(xb,{size:14,fill:"currentColor"}),i.jsx("span",{children:Cp(l.timelapseStartedAt)})]}):i.jsx(Ek,{size:17})})]})}function BS({state:t}){return t==="ok"?i.jsx(_a,{size:15,"aria-hidden":"true"}):i.jsx(Jx,{size:15,"aria-hidden":"true"})}function dx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button ${t?"active":""}`,type:"button",title:"Check Remote Status","aria-label":"Check Remote Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Dk,{size:18,"aria-hidden":"true"})})}function fx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button debug-status-button ${t?"active":""}`,type:"button",title:"Check Debug Status","aria-label":"Check Debug Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(Ux,{size:18,"aria-hidden":"true"})})}function mx({active:t,refreshing:n,onClick:r}){return i.jsx("button",{className:`remote-status-button hub-status-button ${t?"active":""}`,type:"button",title:"Check Hub Status","aria-label":"Check Hub Status","aria-pressed":t,"aria-busy":n,onClick:r,children:n?i.jsx("span",{className:"remote-status-spinner","aria-hidden":"true"}):i.jsx(mo,{size:18,"aria-hidden":"true"})})}function HS({items:t,mode:n="remote"}){return i.jsx("span",{className:`remote-status-lines mode-${n}`,role:"status","aria-label":n==="debug"?"Debug status":"Remote status",children:t.map(r=>i.jsxs("span",{className:`remote-status-line state-${r.state}`,title:r.detail,children:[i.jsx(BS,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))})}function ID({items:t,collectedAt:n,onClose:r}){return i.jsxs("section",{className:"remote-status-dialog hub-status-dialog",role:"dialog","aria-modal":"false","aria-labelledby":"hub-status-dialog-title",children:[i.jsxs("header",{children:[i.jsx("span",{className:"remote-status-dialog-mark","aria-hidden":"true",children:i.jsx(mo,{size:19})}),i.jsxs("span",{children:[i.jsx("small",{children:"Hub measurements"}),i.jsx("h2",{id:"hub-status-dialog-title",children:"Hub Status"})]}),i.jsx("button",{type:"button",onClick:r,title:"Close Hub status","aria-label":"Close Hub status",children:i.jsx(rr,{size:17})})]}),i.jsx("p",{children:"LiveDesk collects these Hub and browser signals continuously. This check refreshed the latest snapshot instead of starting a one-time benchmark."}),i.jsx("div",{className:"remote-status-dialog-list",children:t.map(o=>i.jsxs("article",{className:`remote-status-dialog-row state-${o.state}`,children:[i.jsx(BS,{state:o.state}),i.jsxs("span",{children:[i.jsx("strong",{children:o.label}),i.jsx("small",{children:o.detail})]})]},o.id))}),i.jsxs("footer",{children:["Checked ",new Date(n).toLocaleTimeString()]})]})}const LD=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,PD=/(libx264|openh264|software|cpu)/i,xv=2,_D=256,Qc=new Map,It=Object.freeze({frameAgeWarningMs:2500,networkDelayWarningMs:120,receiveRatioWarning:.62,deliveryRatioWarning:.82,decoderInputRatioWarning:.82,decoderOutputRatioWarning:.62,captureBudgetMultiplier:2.5,minimumCaptureBudgetMs:80,cpuWarningRatio:.82,memoryWarningRatio:.86,gpuWarningRatio:.92,gpuMemoryWarningRatio:.92,gpuTemperatureWarningC:85,networkUsageWarningRatio:.85,networkLatencyWarningMs:80,nativeTelemetryStaleMs:3e3,minimumClientStatusFreshMs:15e3,clientStatusFreshMultiplier:3,runtimeProcessCpuWarningRatio:.65,runtimeProcessMemoryWarningBytes:1.5*1024**3,captureHelperCpuWarningRatio:.55,captureHelperMemoryWarningBytes:1024**3,hubMinimumTotalMemoryBytes:8*1024**3,hubMinimumBrowserMemoryGb:4});function mn(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Jv(t,n){let r=t;for(const o of String(n).split(".")){if(!r||typeof r!="object")return;r=r[o]}return r}function Mt(t,...n){for(const r of n){const o=Jv(t,r);if(o==null||o==="")continue;const l=Number(o);if(Number.isFinite(l))return l}}function zt(t,...n){for(const r of n){const o=Jv(t,r);if(typeof o=="string"&&o.trim())return o.trim()}return""}function zS(t,...n){for(const r of n){const o=Jv(t,r);if(typeof o=="boolean")return o;if(o===1||o==="1"||String(o).toLowerCase()==="true")return!0;if(o===0||o==="0"||String(o).toLowerCase()==="false")return!1}}function Ci(t,...n){const r=Mt(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Ye(t,n,r,o){return{id:t,state:n,label:r,detail:o}}function $S(t){const n=mn(t),r=Mt(n,"helperCount"),o=Mt(n,"helperOwnedIoTaskCount"),l=Mt(n,"helperUndisposedProcessCount"),u=Mt(n,"helperOwnedExitObserverCount"),f=Mt(n,"helperQuarantineCount"),h=Mt(n,"utilityQuarantineCount"),g=Mt(n,"utilityOwnedIoTaskCount"),y=Mt(n,"utilityUndisposedProcessCount"),w=Number(Mt(n,"helperDisposeFailureCount")||0),b=Number(Mt(n,"utilityDisposeFailureCount")||0),S=Math.max(0,Number(r||0)),k=Number(o||0),N=Number(l||0),A=Number(u||0),j=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),T=Number(g||0),_=Number(y||0),B=[o,l,u,f,h,g,y].every(D=>D!==void 0),F=B&&(k<0||N<0||A<0||N!==S||A!==0||S===0&&k!==0||S>0&&k===0),H=B&&(T<0||_<0||_!==I||T!==I*2);return{telemetryAvailable:B,helperOwnedIoTaskCount:k,helperUndisposedProcessCount:N,helperOwnedExitObserverCount:A,helperQuarantineCount:j,helperDisposeFailureCount:w,helperLastDisposeFailure:zt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:T,utilityUndisposedProcessCount:_,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(D=>Number(D)).filter(D=>Number.isSafeInteger(D)&&D>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(D=>String(D||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(Mt(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(Mt(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:zt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:H,historicalCleanupFailure:w!==0||b!==0,currentProblem:j>0||I>0||F||H}}function US({key:t,sampleId:n,mismatch:r}){if(!t)return{count:0,confirmed:!1};if(!r)return Qc.delete(t),{count:0,confirmed:!1};const o=String(n||"").trim();if(!o)return{count:0,confirmed:!1};const l=em(o),u=Qc.get(t);if(u?.sampleId===o)return{count:u.count,confirmed:u.count>=xv};const f=u&&l!==void 0&&u.sampleEpochMs!==void 0&&l>u.sampleEpochMs,h=u&&f?u.count+1:1;return!Qc.has(t)&&Qc.size>=_D&&Qc.delete(Qc.keys().next().value),Qc.set(t,{sampleId:o,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=xv}}function em(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function px(t){return`${(Math.max(0,Number(t||0))/1024**3).toFixed(1)} GB`}function Gl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)/1024**2).toFixed(0)} MB`:"-"}function Vl(t){const n=Number(t);return Number.isFinite(n)?`${(Math.max(0,n)*100).toFixed(1)}%`:"-"}function kp(t){const n=Number(t);return Number.isFinite(n)?`${Math.max(0,n).toFixed(1)}%`:"-"}function FD(t){const n=String(t||"").replace(/^::ffff:/,"").trim().toLowerCase();if(!n||n==="::1"||n==="localhost"||n==="127.0.0.1"||/^10\./.test(n)||/^192\.168\./.test(n))return!0;const r=n.match(/^172\.(\d{1,3})\./);return!!r&&Number(r[1])>=16&&Number(r[1])<=31||n.startsWith("fe80:")||n.startsWith("fc")||n.startsWith("fd")}function qS(t){const n=mn(t),r=zt(n,"controlTransport").toLowerCase();return r==="encrypted-rendezvous-relay"||/relay/.test(r)?"encrypted-rendezvous-relay":r==="direct-tcp"||/direct|tcp/.test(r)?"direct-tcp":""}function hx(t){const n=String(t||"").trim();if(!n)return"";try{return new URL(n.includes("://")?n:`relay://${n}`).host}catch{return n.replace(/[?#].*$/,"").replace(/^[a-z][a-z0-9+.-]*:\/\//i,"").split("@").pop().split("/")[0].slice(0,256)}}function OD(t){const n=qS(t);return n==="encrypted-rendezvous-relay"?Ye("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Ye("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Ye("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function BD(t,n){const r=mn(t),o=mn(n),l=qS(r);if(l==="encrypted-rendezvous-relay"){const u=zt(o,"state")||(o.connected===!0?"registered":"unknown"),f=hx(zt(o,"endpoint"))||hx(zt(r,"relayEndpoint")),h=r.connected!==!0||o.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Ye("debug-control-transport",h?"warning":"ok",`Encrypted rendezvous relay control · ${u}`,[`endpoint ${f||"-"}`,`state ${u}`,`reconnect ${Math.max(0,Number(o.reconnectCount||0))}`,`handshake ${Math.max(0,Number(o.handshakeCount||0))}`,`peers ${Math.max(0,Number(o.peerCount||0))}`,zt(o,"lastError")].filter(Boolean).join(" · "))}if(l==="direct-tcp"){const u=zt(r,"remoteAddress"),f=Mt(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Ye("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${zt(r,"protocol")||"-"} v${Mt(r,"protocolVersion")??"-"} · input ${mn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Ye("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function WS(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function GS(t,n,r){const o=mn(n?.frameTransport),l=zt(t,"frameTransportChangedAt"),u=zt(o,"changedAt"),f=em(l),h=em(u),g=h!==void 0&&(f===void 0||h>f),y=g?o:t,w=g?t:o,b=zt(t,"transport").toLowerCase(),S=zt(y,g?"active":"frameTransportActive")||zt(w,g?"frameTransportActive":"active"),k=zt(y,g?"protocol":"frameTransportProtocol")||zt(w,g?"frameTransportProtocol":"protocol"),A=(g?zt(o,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")||zt(t,"videoTransport"):zt(t,"videoTransport")||zt(o,"videoTransport","activeTransport")||[S,k].filter(Boolean).join("-")).toLowerCase(),j=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(A)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),T=/relay/.test(A)||/relay/.test(b)?"encrypted-relay":/p2p|udp/.test(A)||b==="udp-p2p"?"p2p-udp":/direct|tcp|ws|websocket/.test(A)||b==="binary"||j?j?"direct-ws":"direct-tcp":"",_=(zt(y,g?"state":"frameTransportState")||zt(w,g?"frameTransportState":"state")||(T?"active":"")).toLowerCase(),B=zt(y,g?"reason":"frameTransportReason")||zt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,H=em(F),D=H===void 0?void 0:Math.max(0,r-H),K=D===void 0?"":D<1e3?"changed now":D<6e4?`changed ${Math.round(D/1e3)}s ago`:D<36e5?`changed ${Math.round(D/6e4)}m ago`:`changed ${F}`,z=g?o.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??o.switchCount,W=g?o.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??o.tcpFailureCount,q=g?typeof o.p2pReady=="boolean"?o.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:o.p2pReady===!0;return{rawTransport:b,videoTransport:T,state:_,reason:B,changedAt:F,changedLabel:K,switchCount:Math.max(0,Number(z??0)||0),tcpFailureCount:Math.max(0,Number(W??0)||0),p2pReady:q}}function HD(t,n,r){const o=GS(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(o.state);if(o.videoTransport==="encrypted-relay")return Ye("transport",l?"warning":"ok",l?"Encrypted TCP relay fallback needs attention":"Encrypted TCP relay fallback",l?`End-to-end encrypted TCP relay is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`End-to-end encrypted TCP relay fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="p2p-udp")return Ye("transport",l?"warning":"ok",l?"P2P video connection needs attention":"P2P video connection",l?`Encrypted UDP P2P is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Encrypted UDP P2P fallback is active${o.changedLabel?` · ${o.changedLabel}`:""}.`);if(o.videoTransport==="direct-tcp"||o.videoTransport==="direct-ws"){const u=o.videoTransport==="direct-ws"?"WebSocket":"TCP";return Ye("transport",l?"warning":"ok",l?"Direct video connection needs attention":"Direct video connection",l?`Direct ${u} to Hub is ${o.state||"not ready"}; open Debug Status for the technical reason${o.changedLabel?` · ${o.changedLabel}`:""}.`:`Direct ${u} to Hub is active${o.changedLabel?` · ${o.changedLabel}`:""}.`)}return Ye("transport","warning","Video transport is not identified",o.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const zD=Object.freeze(["nativeEncodeFramesInFlight","nativeEncodePendingFrameCount","nativeEncodeTimestampOwnerCount","nativeEncodeTimestampOwnerHighWatermark","nativeBackpressureCoalescedFrameCount","nativeBackpressureSkippedFrameCount","nativeEncodePendingReplacedFrameCount","nativeIdleSkippedFrameCount","nativeVideoToolboxActiveSessionCount","nativeVideoToolboxSessionHighWatermark","nativeOutputQueueDepth","nativeOutputQueueBytes","nativeOutputQueueOldestAgeMs","nativeOutputQueueHighWatermark","nativeOutputQueueDroppedCount","nativeAnnexBAccessUnitAllocationCount","nativeAnnexBPayloadCopyCount","nativeAnnexBPayloadCopiedBytes","nativeAndPipeResidenceAgeMs","pipePayloadAllocationCount","pipePayloadCopyCount","pipePayloadCopiedBytes","handoffDroppedFrameCount","handoffRecoveryKeyFrameRequestCount","handoffOldestFrameAgeMs"]);function VS(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),o=Number(t?.nativeCaptureTelemetryVersion)>=5&&zD.every(u=>Mt(t,u)!==void 0)&&typeof t?.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t?.nativeCopyTelemetryAvailable===!0,l=t?.nativeCaptureTelemetryAvailable===!0&&t?.nativeCaptureResourceTelemetryAvailable===!0&&o;return{required:r,available:l,pending:Math.max(0,Number(t?.nativeEncodePendingFrameCount||0)),timestampOwners:Math.max(0,Number(t?.nativeEncodeTimestampOwnerCount||0)),timestampOwnerHighWatermark:Math.max(0,Number(t?.nativeEncodeTimestampOwnerHighWatermark||0)),coalesced:Math.max(0,Number(t?.nativeBackpressureCoalescedFrameCount||0)),pendingReplaced:Math.max(0,Number(t?.nativeEncodePendingReplacedFrameCount||0)),vtActive:Math.max(0,Number(t?.nativeVideoToolboxActiveSessionCount||0)),vtHighWatermark:Math.max(0,Number(t?.nativeVideoToolboxSessionHighWatermark||0)),outputOldestAgeMs:Math.max(0,Number(t?.nativeOutputQueueOldestAgeMs||0)),nativeAndPipeResidenceAgeMs:Math.max(0,Number(t?.nativeAndPipeResidenceAgeMs||0)),handoffDropped:Math.max(0,Number(t?.handoffDroppedFrameCount||0)),handoffRecoveryRequests:Math.max(0,Number(t?.handoffRecoveryKeyFrameRequestCount||0)),handoffOldestAgeMs:Math.max(0,Number(t?.handoffOldestFrameAgeMs||0)),annexBAllocations:Math.max(0,Number(t?.nativeAnnexBAccessUnitAllocationCount||0)),annexBPayloadCopies:Math.max(0,Number(t?.nativeAnnexBPayloadCopyCount||0)),annexBPayloadCopiedBytes:Math.max(0,Number(t?.nativeAnnexBPayloadCopiedBytes||0)),pipePayloadAllocations:Math.max(0,Number(t?.pipePayloadAllocationCount||0)),pipePayloadCopies:Math.max(0,Number(t?.pipePayloadCopyCount||0)),pipePayloadCopiedBytes:Math.max(0,Number(t?.pipePayloadCopiedBytes||0))}}function $D(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),o=zS(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||o!==void 0,u=VS(t);return!t||!/h264/.test(n)?Ye("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Ye("encoder","warning","H.264 encoder resource status is unavailable",`${r||"Native encoder"} has not provided complete VideoToolbox v5 ownership, queue, and copy telemetry.`):u.required&&(u.vtActive!==1||u.vtHighWatermark>1||u.timestampOwners>2||u.timestampOwnerHighWatermark>2)?Ye("encoder","warning","VideoToolbox encoder ownership needs attention",`${u.vtActive} active session(s); high-water ${u.vtHighWatermark}; timestamp owners ${u.timestampOwners}/2 (HWM ${u.timestampOwnerHighWatermark})`):u.required&&u.coalesced>0?Ye("encoder","warning","Hardware H.264 encoding is under load",`${u.coalesced} current-window frame(s) were coalesced while the encoder was busy.`):l&&o===!1?Ye("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&o===!0?Ye("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):LD.test(r)?Ye("encoder","ok","Hardware H.264 encoding",r):PD.test(r)?Ye("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Ye("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function UD({device:t,frame:n,receiveStat:r,paintStat:o,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,capturePaused:w=!1,capturePauseConfirmed:b=!0,capturePauseError:S="",clientHeartbeatMs:k=5e3,now:N=Date.now()}={}){const A=mn(t),j=mn(A.status),I=mn(o?.lastInfo),T=[],_=WS(n,N);T.push(OD(A)),T.push(w?b?Ye("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Ye("connection","warning","Video stop needs attention",String(S||"The Hub is blocking video restart, but the Client did not confirm screen capture and video encoder shutdown.")):A.connected===!0&&_<=It.frameAgeWarningMs?Ye("connection","ok","Video connection is current",`${Math.round(_)}ms since the latest frame.`):Ye("connection","warning",A.connected===!0?"Video frame is stale":"Client is offline",A.connected===!0&&Number.isFinite(_)?`${Math.round(_)}ms since the latest frame.`:String(A.lastDisconnectReason||"No current Client session."))),T.push(HD(n,j,N)),T.push($D(n));const B=$S(j.capture),F=mn(j.capture),H=US({key:`${String(A.deviceId||A.id||"")}:capture-cleanup`,sampleId:zt(F,"sampledAt"),mismatch:B.helperLedgerMismatch||B.utilityLedgerMismatch});(B.helperQuarantineCount>0||B.utilityQuarantineCount>0||H.confirmed)&&T.push(Ye("capture-cleanup","warning","Video capture cleanup needs attention",`capture quarantine ${B.helperQuarantineCount} · utility quarantine ${B.utilityQuarantineCount} · owned I/O ${B.helperOwnedIoTaskCount+B.utilityOwnedIoTaskCount} · exit observers ${B.helperOwnedExitObserverCount} · undisposed processes ${B.helperUndisposedProcessCount+B.utilityUndisposedProcessCount}`));const D=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),K=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const z=Math.max(0,Number(n?.nativeCaptureFps||0)),W=Math.max(0,Number(n?.nativeEncodedFps||0)),q=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),V=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),X=Mt(n,"nativeCaptureTelemetryAgeMs"),J=Math.max(0,Number(X||0))+(Number.isFinite(_)?_:0),$=V<2||X!==void 0&&J<=It.nativeTelemetryStaleMs,P=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),se=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),we=n?.nativeCaptureTelemetryAvailable===!0&&q>0&&$,Z=Mt(n,"captureP95Ms","captureAverageMs","captureStageMs"),Se=Math.max(0,Number(Z||0)),ae=n?.captureTimingAvailable===!0&&D>0&&Number(r?.sampleMs||0)>0&&Z!==void 0,ye=ae||we,Pe=Math.max(It.minimumCaptureBudgetMs,D>0?1e3/D*It.captureBudgetMultiplier:0),de=D>0?1e3/D:100,Qe=D>0&&z>=D*It.receiveRatioWarning,ue=W>0&&W<D*It.receiveRatioWarning,_e=we&&Qe&&ue&&W>=1&&se>=Math.max(10,z*.6)&&P===0,Ze=we&&D>0&&(z<D*It.receiveRatioWarning||!_e&&W>0&&W<D*It.receiveRatioWarning),at=we?Ze:ae&&Se>Pe;T.push(ye?at?Ye("capture","warning","Screen capture cannot keep target speed",we?`${z.toFixed(1)} native capture · ${W.toFixed(1)} encoded · ${D||"?"} requested fps`:`${Se?`capture p95 ${Math.round(Se)}ms`:"capture timing unavailable"} · ${K.toFixed(1)}/${D||"?"} fps`):Ye("capture","ok","Screen capture speed is healthy",we?`${z.toFixed(1)} native capture · ${W.toFixed(1)} encoded · ${D||"?"} requested fps${_e?" · idle optimized":""}`:`${Se?`capture p95 ${Math.round(Se)}ms`:"no slow capture reported"}${D?` · ${K.toFixed(1)}/${D} fps`:""}`):Ye("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Ee=Mt(n,"hubPacketTransitAgeMs"),Ge=Math.max(0,Number(Ee||0)),me=Math.max(0,Number(n?.agentSendGapMs||0)),ke=Math.max(0,Number(n?.agentSendDurationMs||0)),et=!FD(A.remoteAddress),Me=Ci(j,"network.usageRatio"),pe=Mt(j,"network.latencyMs"),qe=(Me??0)>=It.networkUsageWarningRatio||(pe??0)>=It.networkLatencyWarningMs,Re=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,st=Re?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,jt=Re?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,O=Re&&jt>0&&st>=jt,ze=Ee!==void 0&&Number(r?.sampleMs||0)>0,We=!_e&&D>0&&Number(r?.sampleMs||0)>0&&K<D*It.deliveryRatioWarning,Et=!_e&&me>Math.max(It.networkDelayWarningMs,de*3),lt=Ge>It.networkDelayWarningMs||Et||ke>It.networkDelayWarningMs||We||_>It.frameAgeWarningMs||qe||O;T.push(ze?lt||et?Ye("network","warning",et?"External network route may add delay":qe?"Client network adapter needs attention":O?"Hub browser video queue needs attention":"Video delivery is uneven",[Ge?`${Math.round(Ge)}ms Hub-to-browser`:"",me?`${Math.round(me)}ms Client send gap`:"",ke?`${Math.round(ke)}ms Client send time`:"",We?`${K.toFixed(1)} of ${D} requested fps`:"",pe!==void 0?`${Math.round(pe)}ms Client network latency`:"",Me!==void 0?`${Math.round(Me*100)}% Client link use`:"",Re&&jt>0?`Hub queue ${st}/${jt}`:"",et?String(A.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Ye("network","ok","Network delivery is healthy",`${Math.round(Ge)}ms Hub-to-browser · ${_e?`idle optimized at ${W.toFixed(1)} fps`:"the current video rate is on target."}`):Ye("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const ht=Ci(j,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),Je=Ci(j,"memory.usedRatio","usedMemRatio"),be=Ci(j,"gpu.usageRatio"),je=Ci(j,"gpu.memory.usedRatio"),Ae=Mt(j,"gpu.temperatureC","thermal.gpuC"),fe=ht!==void 0&&Je!==void 0,te=em(A.lastStatusAt),ce=te===void 0?Number.POSITIVE_INFINITY:Math.max(0,N-te),Ne=Math.max(It.minimumClientStatusFreshMs,Math.max(1e3,Number(k||0))*It.clientStatusFreshMultiplier),He=ce<=Ne,Ie=(ht??0)>=It.cpuWarningRatio||(Je??0)>=It.memoryWarningRatio||(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC;T.push(fe?He?Ie?Ye("computer","warning",(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC?"Client GPU is under load":"Client computer is under load",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Je*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:"",je!==void 0?`GPU memory ${Math.round(je*100)}%`:"",Ae!==void 0?`GPU ${Math.round(Ae)}C`:""].filter(Boolean).join(" · ")):Ye("computer","ok","Client computer has working capacity",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Je*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:""].filter(Boolean).join(" · ")):Ye("computer","warning","Client performance snapshot is stale",Number.isFinite(ce)?`The latest CPU and memory report is ${Math.round(ce/1e3)} seconds old.`:"No current Client performance heartbeat has been received."):Ye("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Lt=Number(n?.monitorIndex),Xe=Number.isInteger(Lt)&&Lt===Number(u),ut=mn(A.channels),yt=mn(A.capabilities),_t=ut.input!==!1&&yt.remoteInput!==!1&&yt.accessibilityPermission!==!1,mt=yt.screenRecordingPermission!==!1,Vt=mn(g),St=!f||String(n?.sessionId||"")&&String(n?.sessionId||"")===String(Vt.sessionId||"")&&String(n?.commandId||"")&&String(n?.commandId||"")===String(Vt.commandId||"")&&Number(n?.captureGeneration||0)>0&&Number(n?.captureGeneration||0)===Number(Vt.captureGeneration||0)&&Number(n?.monitorIndex)===Number(Vt.monitorIndex),pn=!f||h&&St;T.push(Xe&&pn&&_t&&mt?Ye("display","ok",f?"Display and remote input are bound":"Display and remote input are available",`Display ${Number(u)+1} · generation ${Number(n?.captureGeneration||0)||"current"}.`):Ye("display","warning",mt?_t?f?"Remote input is not bound to this display":"Waiting for the selected display":"Remote input permission is missing":"Screen capture permission is missing",`Selected display ${Number(u)+1}; latest frame ${Number.isInteger(Lt)?Lt+1:"not available"}.`));const rn=mn(l),ya=Array.isArray(rn.canvases)?mn(rn.canvases[0]):{},Ct=Math.max(0,Number(o?.decoderInputFps||0)),gn=Math.max(0,Number(o?.decoderOutputFps||0)),en=Ct>0&&Number(o?.sampleMs||r?.sampleMs||0)>0,nt=K>0&&Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0&&Ct<K*It.decoderInputRatioWarning,Dt=Ct>0?gn/Ct:0,vn=zt(ya,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Nr=zt(ya,"softwareFallbackReason"),Ur=!!Nr||vn==="prefer-software";return T.push(nt?Ye("decoder","warning","Browser decoder input is dropping frames",`${K.toFixed(1)} received / ${Ct.toFixed(1)} decoder input / ${gn.toFixed(1)} output fps.`):en?Ur||Dt<It.decoderOutputRatioWarning?Ye("decoder","warning",Ur?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Nr||String(I.decoderLabel||vn||"decoder")} · ${Ct.toFixed(1)} in / ${gn.toFixed(1)} out fps.`):Ye("decoder","ok",vn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${Ct.toFixed(1)} in / ${gn.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Ye("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),T}function lo(t){const n=String(t||"").trim();return n?n.length<=14?n:`${n.slice(0,6)}…${n.slice(-5)}`:"-"}function Rn(t,n=1){const r=Number(t);return Number.isFinite(r)?r.toFixed(n):"-"}function qD({device:t,frame:n,receiveStat:r,paintStat:o,codec:l,selectedMonitorIndex:u=0,control:f=!1,controlInputReady:h=!1,controlBinding:g,hubRelay:y,now:w=Date.now()}={}){const b=mn(t),S=mn(b.status),k=mn(S.runtimeProcess),N=mn(S.capture),A=$S(N),j=mn(g),I=mn(o?.lastInfo),T=mn(l),_=Array.isArray(T.canvases)?mn(T.canvases[0]):{},B=[],F=Number(u),H=Number(n?.monitorIndex),D=Number.isInteger(H)&&H===F,K=Number(n?.captureGeneration||0),z=Number(j.captureGeneration||0),W=!f||D&&String(n?.sessionId||"")===String(j.sessionId||"")&&String(n?.commandId||"")===String(j.commandId||"")&&K>0&&K===z,q=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),V=Math.max(0,Number(r?.framesPerSecond||0)),X=Math.max(0,Number(o?.framesPerSecond||0)),ve=Math.max(0,Number(o?.decoderInputFps||0)),J=Math.max(0,Number(o?.decoderOutputFps||0)),$=Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0,P=q>0&&$&&Math.min(V,X||V,J||V)<q*It.deliveryRatioWarning,se=Math.max(0,Number(n?.sourceGapMs||0)),we=Math.max(0,Number(n?.agentSendGapMs||0)),Z=Math.max(0,Number(n?.agentSendDurationMs||0)),Se=Math.max(0,Number(n?.agentSendDurationFrameSeq||0)),ae=Math.max(0,Number(n?.agentQueueBeforePaceMs||0)),ye=Math.max(0,Number(n?.agentFrameAgeMs||0)),Pe=Mt(n,"hubPacketTransitAgeMs"),de=Math.max(0,Number(n?.droppedByAgent||0)),Qe=Math.max(0,Number(n?.hubIngressDropped||0)),ue=n?.hubClientQueueTelemetryAvailable===!0||Mt(n,"hubClientDropped")!==void 0&&Mt(n,"hubClientQueueDepth")!==void 0&&Mt(n,"hubClientQueueLimit")!==void 0&&Mt(n,"hubClientBufferedBytes")!==void 0,_e=ue?Math.max(0,Number(n?.hubClientDropped||0)):0,Ze=ue?Math.max(0,Number(n?.hubClientQueueDepth||0)):0,at=ue?Math.max(0,Number(n?.hubClientQueueLimit||0)):0,Ee=ue?Math.max(0,Number(n?.hubClientBufferedBytes||0)):0,Ge=Math.max(0,Number(n?.udpIncompleteFrames||0)),me=de+Qe+_e,ke=WS(n,w),et=zt(_,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Me=zt(_,"softwareFallbackReason"),pe=Math.max(0,Number(T.hardwareReleaseGeneration||0)),qe=Math.max(0,Number(T.hardwareRecoveryProbeCount||0)),Re=Number(T.lastHardwareRecoveryProbeAt),st=Number.isFinite(Re)&&Re>0?Math.max(0,w-Re):void 0,jt=`hardware releases ${pe} · recovery probes ${qe} · last probe ${st===void 0?"-":`${Math.round(st)}ms ago`}`,O=$&&V>0&&ve<V*It.decoderInputRatioWarning,ze=GS(n,S,w),We=zt(b,"deviceId")||zt(n,"deviceId"),Et=zt(n,"sessionId")||zt(b,"sessionId"),lt=zt(b,"productVersion")||zt(S,"productVersion","runtime.productVersion"),ht=zt(b,"agentVersion")||zt(S,"agentVersion","runtime.agentVersion"),Je=Mt(b,"pid","runtimePid")??Mt(S,"pid","runtimePid","process.pid"),be=Mt(k,"pid"),je=Ci(k,"cpuUsageRatio"),Ae=Mt(k,"cpuCorePercent"),fe=Mt(k,"workingSetBytes"),te=Mt(k,"privateMemoryBytes"),ce=Math.max(fe||0,te||0),Ne=(be??0)>0&&(fe??0)>0,He=Ne&&(Je??0)>0&&be!==Je,Ie=(je??0)>=It.runtimeProcessCpuWarningRatio||ce>=It.runtimeProcessMemoryWarningBytes,Lt=Ci(S,"cpu.usageRatio"),Xe=Ci(S,"memory.usedRatio","usedMemRatio"),ut=Math.max(0,Number(Mt(N,"videoStreamCount")||0)),yt=Math.max(0,Number(Mt(N,"audioStreamCount")||0)),_t=Mt(N,"helperCount"),mt=Math.max(0,Number(_t||0)),Vt=Mt(N,"helperMaxConcurrent"),St=Math.max(mt,Number(Vt||0)),pn=Array.isArray(N.helperPids)?N.helperPids.map(Aa=>Number(Aa)).filter(Aa=>Number.isSafeInteger(Aa)&&Aa>0):[],rn=Array.isArray(N.helperProfiles)?N.helperProfiles.map(Aa=>String(Aa||"").trim()).filter(Boolean).slice(0,4):[],ya=Ci(N,"helperCpuUsageRatio"),Ct=Mt(N,"helperCpuCorePercent"),gn=Mt(N,"helperWorkingSetBytes"),en=Mt(N,"helperPrivateMemoryBytes"),U=Math.max(gn||0,en||0),nt=Math.max(0,Number(Mt(N,"helperStartCount")||0)),Dt=Math.max(0,Number(Mt(N,"helperStopCount")||0)),vn=_t!==void 0,Nr=vn&&nt>=Dt&&nt-Dt!==mt,Ur=mt>1||St>1||ut>1||Nr||A.currentProblem,Tr=vn&&(ut>0&&mt===0||ut===0&&mt>0),oe=US({key:We&&Et?`${We}:${Et}`:"",sampleId:zt(N,"sampledAt"),mismatch:Tr}),$e=Tr&&!oe.confirmed,tt=Ur||oe.confirmed,Pt=(ya??0)>=It.captureHelperCpuWarningRatio||U>=It.captureHelperMemoryWarningBytes,wn=!!(We&&Et&<&&ht&&(Je??0)>0),Oe=n?.nativeCaptureTelemetryAvailable===!0,it=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),Nt=it>=2,bt=VS(n),Gt=!bt.required||bt.available,ra=Mt(n,"nativeCaptureTelemetryAgeMs"),qn=Math.max(0,Number(ra||0))+(Number.isFinite(ke)?ke:0),Qt=ra===void 0?"-":`${Math.round(qn)}ms`,En=!Nt||ra!==void 0&&qn<=It.nativeTelemetryStaleMs,qr=Oe&&!En,Ht=zS(n,"nativeEncoderHardwareAccelerated"),Pn=n?.nativeEncoderHardwareAccelerationKnown===!0||Ht!==void 0,Ha=zt(n,"nativeEncoderHardwareQueryStatus"),sr=Ha==="0"?"confirmed":Ha,Rr=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),ir=Math.max(0,Number(n?.nativeCaptureFps||0)),Zs=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),Ds=Math.max(0,Number(n?.nativeCompressionFps||0)),Dn=Math.max(0,Number(n?.nativeEncodedFps||0)),ln=Nt||Zs>0?Ds:Dn,il=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Is=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),go=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),Ai=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),or=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Pd=bt.pending,za=bt.timestampOwners,Wr=bt.timestampOwnerHighWatermark,ol=bt.coalesced,wt=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),_n=bt.pendingReplaced,vo=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),sn=bt.vtActive,us=bt.vtHighWatermark,oc=Math.max(0,Number(n?.nativeOutputQueueDepth||0)),Js=Math.max(0,Number(n?.nativeOutputQueueBytes||0)),ll=bt.outputOldestAgeMs,Bt=Math.max(0,Number(n?.nativeOutputQueueHighWatermark||0)),jr=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),yo=n?.nativeOutputQueueAwaitingKeyFrame===!0,ei=bt.nativeAndPipeResidenceAgeMs,lr=bt.handoffDropped,Ni=bt.handoffRecoveryRequests,ti=bt.handoffOldestAgeMs,Hn=or>2||Pd>1||za>2||Wr>2||ol>0||or>=2&&wt>0,cr=bt.required&&bt.available&&(sn!==1||us>1||za>2||Wr>2),ni=oc>=3||Js>=6*1024*1024||ll>120||jr>0||yo||ei>250||lr>0||Ni>0||ti>120,cl=`in-flight ${or}/2 · backpressure skipped ${wt} · idle skipped ${vo} · stdout queue ${oc} AU/${Math.round(Js/1024)} KB/${Math.round(ll)}ms · HWM ${Bt} · dropped ${jr} · awaiting key ${yo?"yes":"no"} · native+pipe ${Math.round(ei)}ms · handoff ${Math.round(ti)}ms/drop ${lr}/recovery ${Ni}`,lc=`pending ${Pd}/1; timestamp owners ${za}/2 (HWM ${Wr}); coalesced ${ol}; pending replaced ${_n}; VideoToolbox ${sn} active/HWM ${us}`,bo=bt.available&&bt.annexBAllocations>0&&bt.annexBPayloadCopies>=bt.annexBAllocations&&bt.annexBPayloadCopiedBytes>0&&bt.pipePayloadAllocations>0&&bt.pipePayloadCopies>=bt.pipePayloadAllocations&&bt.pipePayloadCopiedBytes>0,Gr=`Annex-B allocation/copy ${bt.annexBAllocations}/${bt.annexBPayloadCopies} (${Math.round(bt.annexBPayloadCopiedBytes/1024)} KB) · pipe allocation/read ${bt.pipePayloadAllocations}/${bt.pipePayloadCopies} (${Math.round(bt.pipePayloadCopiedBytes/1024)} KB)`,Vr=Oe&&il>0&&En,wo=q>0?1e3/q:100,Ls=q>0&&ir>=q*It.receiveRatioWarning,xo=ln>0&&ln<q*It.receiveRatioWarning,$a=Vr&&Ls&&xo&&ln>=1&&Dn>=1&&vo>=Math.max(10,ir*.6)&&wt===0,cn=P&&!$a,Zn=!$a&&we>Math.max(It.networkDelayWarningMs,wo*3),Ua=Vr&&q>0&&ir<q*It.receiveRatioWarning,kn=Vr&&!$a&&ir>0&&(Nt&&ln<=0||ln>0&&ln<ir*It.receiveRatioWarning),Fn=Vr&&Zs>0&&ln>0&&Dn<ln*It.receiveRatioWarning,qa=qr?"Native capture telemetry is stale":Gt?cr?"VideoToolbox encoder ownership needs attention":Vr?Ua?"Native screen capture is below request":kn||Hn?"VideoToolbox compression is behind capture":Fn||ni?"Native stdout delivery is backpressured":Ht===!1?"Native hardware encoder is unavailable":"Native capture or encoder needs attention":"Native capture telemetry is unavailable":"Native encoder resource telemetry is unavailable";B.push(BD(b,y)),B.push(wn?Ye("debug-runtime","ok",`LiveDesk ${lt} · Agent ${ht}`,`pid ${Je} · session ${lo(Et)} · device ${lo(We)}`):Ye("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${lt||"-"} · Agent ${ht||"-"} · pid ${Je??"-"} · session ${lo(Et)} · device ${lo(We)}`)),B.push(Ne&&!He&&!Ie?Ye("debug-process-load","ok","RemoteFast process load is healthy",`pid ${be} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Xe)}`):Ye("debug-process-load","warning",Ne?He?"RemoteFast process identity does not match":"RemoteFast process load needs attention":"RemoteFast process telemetry is collecting",`runtime pid ${be??"-"} · reported pid ${Je??"-"} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Xe)}`)),B.push(n?Ye("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${lo(n.streamId)} · ${n.width||0}x${n.height||0} · ${Math.round(Number(n.byteLength||0)/1024)} KB · age ${Number.isFinite(ke)?Math.round(ke):"-"}ms`):Ye("debug-frame","warning","No current frame",`Device ${lo(b.deviceId)} has not produced a frame.`));const ur=/(connecting|recovering|failed|error|degraded|unavailable)/.test(ze.state);B.push(ze.videoTransport&&!ur?Ye("debug-transport","ok",`${ze.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":ze.videoTransport==="p2p-udp"?"P2P UDP":ze.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${ze.state||"active"}`,[`raw ${ze.rawTransport||"-"}`,`P2P ${ze.p2pReady?"ready":"standby unavailable"}`,`switch ${ze.switchCount}`,`TCP failure ${ze.tcpFailureCount}`,ze.changedLabel,ze.reason].filter(Boolean).join(" · ")):Ye("debug-transport","warning",ze.videoTransport?`Video transport ${ze.state||"needs attention"}`:"Video transport is not identified",[ze.videoTransport||"no active path",`raw ${ze.rawTransport||"-"}`,`P2P ${ze.p2pReady?"ready":"not ready"}`,ze.changedLabel,ze.reason].filter(Boolean).join(" · "))),B.push(D?Ye("debug-monitor","ok",`Monitor selected ${F+1} · frame ${H+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`):Ye("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger(H)?H+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${K||"-"}`)),B.push(W&&(!f||h)?Ye("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${lo(n?.sessionId)} · command ${lo(n?.commandId)} · generation ${K||"-"}`):Ye("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${lo(n?.commandId)}/${K||"-"} · expected ${lo(j.commandId)}/${z||"-"} · input ${h?"ready":"waiting"}`)),B.push($&&!cn?Ye("debug-cadence","ok",`Cadence ${Rn(V)} rx · ${Rn(X)} paint · ${Rn(J)} decode`,`requested ${Rn(q)} · decoder input ${Rn(ve)} fps · receive p95 ${Rn(r?.p95IntervalMs)}ms${$a?" · idle optimized":""}`):Ye("debug-cadence","warning",$?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Rn(q)} · receive ${Rn(V)} · paint ${Rn(X)} · decode ${Rn(J)} fps`)),B.push(Vr&&Gt&&!Ua&&!kn&&!Fn&&!Hn&&!cr&&!ni&&Ht!==!1?Ye("debug-native-capture","ok",`Native capture ${Rn(ir)} fps · compress ${Rn(ln)} fps · stdout ${Rn(Dn)} fps${$a?" · idle optimized":""}`,`telemetry v${it||1} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${sr?` (${sr})`:""} · display ${Rr||"-"} · capture samples ${il} · encodable ${Is} · skipped ${go} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(se)}ms`):Ye("debug-native-capture","warning",qa,`telemetry ${Oe?`v${it||1}`:"no"} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${sr?` (${sr})`:""} · display ${Rr||"-"} · capture ${Rn(ir)} fps · compress ${Rn(ln)} fps · stdout ${Rn(Dn)} fps · capture samples ${il} · encodable ${Is} · skipped ${go} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(se)}ms`)),bt.required&&(B.push(Gt&&!Hn&&!cr?Ye("debug-native-resource","ok","VideoToolbox resource ownership is bounded",lc):Ye("debug-native-resource","warning",Gt?cr?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",lc)),B.push(Gt&&bo?Ye("debug-native-copy","ok","Capture copy accounting is current",Gr):Ye("debug-native-copy","warning",Gt?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Gr))),B.push(vn&&!tt&&!Pt?Ye("debug-capture-ownership","ok",$e?"Capture ownership transition is settling":mt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ut} · audio ${yt} · helpers ${mt} (max ${St||"-"}) · pid ${pn.join(",")||"-"} · profile ${rn.join(", ")||"-"} · CPU ${Vl(ya)} machine / ${kp(Ct)} core · RSS ${Gl(gn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}${$e?` · mismatch samples ${oe.count}/${xv}`:""}`):Ye("debug-capture-ownership","warning",vn?mt>1||St>1?"Duplicate capture helpers detected":tt?"Capture stream and helper ownership do not match":"Capture helper load needs attention":"Capture process telemetry is collecting",`video ${ut} · audio ${yt} · helpers ${mt} (max ${St||"-"}) · pid ${pn.join(",")||"-"} · profile ${rn.join(", ")||"-"} · CPU ${Vl(ya)} machine / ${kp(Ct)} core · RSS ${Gl(gn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}`));const Wa=`helper I/O ${A.helperOwnedIoTaskCount} | exit observers ${A.helperOwnedExitObserverCount} | undisposed ${A.helperUndisposedProcessCount} | quarantine ${A.helperQuarantineCount} | dispose failures ${A.helperDisposeFailureCount} | utility I/O ${A.utilityOwnedIoTaskCount} | undisposed ${A.utilityUndisposedProcessCount} | quarantine ${A.utilityQuarantineCount} | utility pid ${A.utilityQuarantinePids.join(",")||"-"} | profile ${A.utilityQuarantineProfiles.join(", ")||"-"} | utility starts ${A.utilityQuarantineStartCount} / stops ${A.utilityQuarantineStopCount} | dispose failures ${A.utilityDisposeFailureCount}${A.helperLastDisposeFailure?` | helper last ${A.helperLastDisposeFailure}`:""}${A.utilityLastDisposeFailure?` | utility last ${A.utilityLastDisposeFailure}`:""}`;B.push(A.telemetryAvailable&&!A.currentProblem&&!A.historicalCleanupFailure?Ye("debug-capture-cleanup","ok",mt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",Wa):Ye("debug-capture-cleanup","warning",A.telemetryAvailable?A.currentProblem?"Capture cleanup is quarantined or mismatched":"Capture cleanup recorded a disposal failure":"Capture cleanup telemetry is collecting",Wa)),B.push(ue?me===0&&Ge===0&&(at<=0||Ze<at)&&!Zn&&Z<=It.networkDelayWarningMs&&ye<=It.networkDelayWarningMs&&(Pe===void 0||Pe<=It.networkDelayWarningMs)?Ye("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Client send time ${Math.round(Z)}ms (frame ${Se||"-"}) · Agent queue ${Math.round(ae)}ms · Agent age ${Math.round(ye)}ms · Agent drop ${de} · Hub transit ${Pe===void 0?"-":Math.round(Pe)}ms · Hub ingress drop ${Qe} · browser queue drop ${_e} (${Ze}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}${$a?" · idle optimized":""}`):Ye("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Client send time ${Math.round(Z)}ms (frame ${Se||"-"}) · Agent queue ${Math.round(ae)}ms · Agent age ${Math.round(ye)}ms · Agent drop ${de} · Hub transit ${Pe===void 0?"-":Math.round(Pe)}ms · Hub ingress drop ${Qe} · browser queue drop ${_e} (${Ze}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}`):Ye("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(se)}ms · Client send gap ${Math.round(we)}ms · Agent drop ${de} · Hub ingress drop ${Qe} · per-browser lane counters are intentionally collected outside video packets.`));const ai=Mt(n,"captureP95Ms");return B.push(n?.captureTimingAvailable===!0&&ai!==void 0?Ye("debug-capture","ok",`Capture p95 ${Rn(ai)}ms · avg ${Rn(n?.captureAverageMs)}ms`,`stage ${Rn(n?.captureStageMs)}ms · slow ${Number(n?.slowFrameCount||0)} · helper restart ${Number(n?.captureHelperRestarts||0)} · source skip ${Number(n?.captureSourceSkipped||0)}`):Vr&&Nt?Ye("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Rn(ir)} fps · VideoToolbox ${Rn(ln)} fps · stdout ${Rn(Dn)} fps · telemetry age ${Qt}`):Ye("debug-capture","warning","Capture timing sample is unavailable",`stage ${Rn(n?.captureStageMs)}ms · helper restart ${Number(n?.captureHelperRestarts||0)} · source serial ${Number(n?.captureSourceSerial||0)}`)),B.push(!Me&&et!=="prefer-software"&&!O?Ye("debug-decoder","ok",`Decoder ${et||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${jt}`):Ye("debug-decoder","warning",O?"Decoder input is losing received frames":"Decoder software fallback is active",O?`${Rn(V)} received / ${Rn(ve)} decoder input / ${Rn(J)} output fps · ${jt}`:`${Me||et||"software"} · ${Rn(ve)} in / ${Rn(J)} out fps · ${jt}`)),B}function WD({status:t,deviceDiagnostics:n=[],codec:r,browser:o,frameStats:l}={}){const u=mn(t),f=mn(u.diagnostics),h=mn(f.system),g=mn(f.network),y=mn(r),w=mn(o),b=Array.isArray(n)?n:[],S=b.reduce((ye,Pe)=>ye+(Array.isArray(Pe)&&Pe.some(de=>de?.state==="warning")?1:0),0),k=Ci(h,"cpuUsageRatio","processCpuRatio"),N=Ci(h,"memoryUsedRatio"),A=Mt(h,"totalMemoryBytes"),j=Mt(h,"cpuLogicalCores")??Mt(w,"hardwareConcurrency"),I=Mt(w,"deviceMemory"),T=(j??0)>0&&k!==void 0&&N!==void 0&&(A??0)>0,_=(A??0)>0&&A<It.hubMinimumTotalMemoryBytes,B=(I??0)>0&&I<It.hubMinimumBrowserMemoryGb,F=(j??0)>0&&j<4||(k??0)>=It.cpuWarningRatio||(N??0)>=It.memoryWarningRatio||_||B,H=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),D=Math.max(0,Number(y.activeDecoderCount||0)),K=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),z=Mt(g,"externalDeviceCount"),W=zt(g,"route"),q=z!==void 0&&!!W,V=(z??0)>0||W==="external",X=mn(u.frameLanes),ve=mn(X.packetFanout),J=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(ye=>Mt(ve,ye)!==void 0),$=Array.isArray(X.clients)?X.clients.map(mn):[],P=Mt(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&J,se=$.some(ye=>{const Pe=Math.max(0,Number(ye.queueDepth||0)),de=Math.max(0,Number(ye.queueLimit||0)),Qe=Math.max(0,Number(ye.queuedBytes||0)),ue=Math.max(0,Number(ye.queueByteLimit||0));return Math.max(0,Number(ye.droppedPackets||0))>0||de>0&&Pe>=de||ue>0&&Qe>=ue||Array.isArray(ye.backpressuredDeviceIds)&&ye.backpressuredDeviceIds.length>0}),we=Math.max(0,Number(ve.packetBuilds||0)),Z=Math.max(0,Number(ve.metadataSerializations||0)),Se=Math.max(0,Number(ve.payloadCopyOperations||0)),ae=Math.max(0,Number(ve.fanoutEligibleSubscribers||0));return[u.started&&!u.lastError?Ye("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Ye("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),T?F?Ye("hub-computer","warning",_?"Hub has limited system memory":B?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${j||"?"} logical cores`,`${px(A)} RAM`,I!==void 0?`${I} GB browser memory class`:"",`CPU ${k===void 0?"?":Math.round(k*100)}%`,`memory ${N===void 0?"?":Math.round(N*100)}%`].filter(Boolean).join(" · ")):Ye("hub-computer","ok","Hub computer capacity is healthy",`${j||"?"} logical cores · ${px(A)} RAM · CPU ${k===void 0?"not reported":`${Math.round(k*100)}%`}.`):Ye("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),D<=0?Ye("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):H>0?Ye("hub-codec","warning","Some browser decoders use software fallback",`${D} active H.264 decoders · ${H} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Ye("hub-codec","ok","All active streams request hardware H.264",`${D} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),P?se?Ye("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${$.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Ye("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${$.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Ye("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),S>0?Ye("hub-clients","warning",`${S} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Ye("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Ye("hub-network",!q||V||K>120?"warning":"ok",q?V?`${z} Clients use an external network route`:K>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",q?`${W.toUpperCase()} route · ${K.toFixed(K>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function GD(t,n={}){const r=t.filter(b=>b.canvas&&b.canvas.width>0&&b.canvas.height>0),o=Math.max(320,n.maxWidth||1920),l=Math.max(180,n.maxHeight||1080),u=r.length<=1?1:r.length<=4?2:r.length<=9?3:4,f=Math.max(1,Math.ceil(Math.max(1,r.length)/u)),h=Math.floor(o/u),g=Math.floor(l/f),y=document.createElement("canvas");y.width=Math.max(320,h*u),y.height=Math.max(180,g*f);const w=y.getContext("2d",{alpha:!1});if(!w)return y;w.fillStyle="#0b1220",w.fillRect(0,0,y.width,y.height),w.font="600 14px system-ui, sans-serif",w.textBaseline="bottom";for(let b=0;b<r.length;b+=1){const S=r[b],k=b%u,N=Math.floor(b/u),A=k*h,j=N*g,I=S.canvas,T=Math.min(h/I.width,g/I.height),_=Math.max(1,Math.floor(I.width*T)),B=Math.max(1,Math.floor(I.height*T)),F=A+Math.floor((h-_)/2),H=j+Math.floor((g-B)/2);w.drawImage(I,F,H,_,B),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,j+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(S.label,A+9,j+g-9))}return y}function VD(t){return t?.signature||"none"}function KD(t){return t?.label||"No capture target"}function gx(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function QD(){const t=new Date,n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}${n(t.getMonth()+1)}${n(t.getDate())}_${n(t.getHours())}${n(t.getMinutes())}${n(t.getSeconds())}`}function YD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function XD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${YD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${QD()}.png`}async function ZD(t,n,r){const o=await new Promise((u,f)=>t.toBlob(h=>h?u(h):f(new Error("Screenshot could not be encoded.")),"image/png")),l=await OS(o,{kind:"screenshot",fileName:XD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":o})])}catch{}return l.capture}function KS(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function JD(t,n){const r=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d{3}Z$/,"").replace("T","_"),o=n.label.replace(/[^a-zA-Z0-9._-]+/g,"-").slice(0,70)||"Wall";return t==="timelapse"?`LiveDesk_Timelapse_${o}_${r}.webm`:`LiveDesk_Recording_${o}_${r}.webm`}async function QS(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=KS();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",o=await ND({kind:r,fileName:JD(r,t.target),mimeType:n,target:t.target},t.hubUrl),l=t.canvas.captureStream(t.frameRequests?0:t.fps),u=new MediaRecorder(l,{mimeType:n,videoBitsPerSecond:r==="timelapse"?2e6:4e6}),f=performance.now();let h=0,g=!1,y=null,w=Promise.resolve();return u.ondataavailable=b=>{if(!b.data||b.data.size===0)return;const S=h++;w=w.then(()=>TD(o.sessionId,S,b.data,t.hubUrl).then(()=>{})).catch(k=>{y=y||(k instanceof Error?k:new Error(String(k))),t.onError?.(y)})},u.onerror=()=>{y=new Error("Video recording stopped unexpectedly."),t.onError?.(y)},u.start(1e3),{requestFrame:()=>{l.getVideoTracks()[0]?.requestFrame?.()},stop:async()=>{if(!g){if(g=!0,await new Promise(b=>{u.addEventListener("stop",()=>b(),{once:!0}),u.stop()}),l.getTracks().forEach(b=>b.stop()),await w,y)throw await lx(o.sessionId,t.hubUrl).catch(()=>{}),y;await RD(o.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await lx(o.sessionId,t.hubUrl).catch(()=>{}))}}}class eI{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(n,r){if(this.recorder&&this.targetSignature===r.signature)return;if(this.stop(),typeof MediaRecorder>"u"||typeof n.captureStream!="function")throw new Error("This browser does not support Last 30s.");const o=KS();if(!o)throw new Error("This browser does not support WebM recording.");this.targetSignature=r.signature,this.stream=n.captureStream(20),this.recorder=new MediaRecorder(this.stream,{mimeType:o,videoBitsPerSecond:3e6}),this.startedAt=performance.now(),this.recorder.ondataavailable=l=>{if(!l.data.size)return;const u=performance.now();for(this.segments.push({blob:l.data,at:u}),this.totalBytes+=l.data.size;this.segments.length>1&&(u-this.segments[0].at>this.maxDurationMs||this.totalBytes>this.maxBytes);){const f=this.segments.shift();this.totalBytes-=f.blob.size}},this.recorder.start(1e3)}stop(){const n=this.recorder;this.recorder=null,n&&n.state!=="inactive"&&(n.ondataavailable=null,n.stop()),this.stream?.getTracks().forEach(r=>r.stop()),this.stream=null,this.segments=[],this.totalBytes=0,this.startedAt=0}async save(n,r){if(this.segments.length===0)throw new Error("The Last 30s buffer is not ready yet.");const o=new Blob(this.segments.map(f=>f.blob),{type:this.segments[0].blob.type||"video/webm"}),u=`LiveDesk_Last30s_${n.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 OS(o,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function tI(t,n,r,o,l){const u=await QS({canvas:t,target:n,kind:"timelapse",fps:30,frameRequests:!0,hubUrl:o,onError:l});u.requestFrame?.();const f=window.setInterval(()=>u.requestFrame?.(),Math.max(5,r)*1e3);return{stop:async()=>{window.clearInterval(f),await u.stop()},cancel:async()=>{window.clearInterval(f),await u.cancel()}}}const YS="livedesk.captureSettings";function nI(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(YS)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function aI(t){const[n,r]=d.useState(nI),[o,l]=d.useState(0),[u,f]=d.useState(0),[h,g]=d.useState(0),[y,w]=d.useState(!1),b=d.useRef(void 0),S=d.useRef(!1),k=d.useRef(""),N=d.useRef(null),A=d.useRef(null),j=d.useRef(null),I=d.useRef(null),T=d.useRef(new eI),_=t.sourceRegistry.resolveCurrentTarget(),B=VD(_),F=KD(_),H=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(YS,JSON.stringify(n)),!S.current)return;const se=JSON.stringify(n);se!==k.current&&(k.current=se,rt("/api/settings",{method:"PATCH",body:JSON.stringify({revision:b.current,filesAudio:{rollingBufferEnabled:n.rollingEnabled,recordingQuality:n.recordingQuality,timelapseIntervalSeconds:n.timelapseIntervalSeconds,includeRemoteCursor:n.includeRemoteCursor}})},t.hubUrl).then(we=>{b.current=Number(we.revision||b.current||0)}).catch(()=>{}))},[t.hubUrl,n]),d.useEffect(()=>{let se=!0;return rt("/api/settings",void 0,t.hubUrl).then(we=>{if(!se)return;const Z=we.settings?.filesAudio||{},Se=typeof Z.rollingBufferEnabled=="boolean"?Z.rollingBufferEnabled:n.rollingEnabled,ae=Z.recordingQuality==="high"?"high":"standard",ye=[5,10,30,60].includes(Number(Z.timelapseIntervalSeconds))?Number(Z.timelapseIntervalSeconds):n.timelapseIntervalSeconds,Pe=typeof Z.includeRemoteCursor=="boolean"?Z.includeRemoteCursor:n.includeRemoteCursor,de={rollingEnabled:Se,recordingQuality:ae,timelapseIntervalSeconds:ye,includeRemoteCursor:Pe};b.current=Number(we.revision||0),k.current=JSON.stringify(de),S.current=!0,r(de)}).catch(()=>{S.current=!0}),()=>{se=!1}},[t.hubUrl]);const D=d.useCallback(async se=>{if(se.sourceCanvas&&se.sourceCanvas.width>0&&se.sourceCanvas.height>0)return{target:gx(se),canvas:se.sourceCanvas,cleanup:()=>{}};const we=await t.sourceRegistry.composeWall(se.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Z=!1;const Se=window.setInterval(async()=>{if(Z)return;const ae=await t.sourceRegistry.composeWall(se.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0}).catch(()=>null);!ae||Z||((we.width!==ae.width||we.height!==ae.height)&&(we.width=ae.width,we.height=ae.height),we.getContext("2d")?.drawImage(ae,0,0))},100);return{target:gx(se),canvas:we,cleanup:()=>{Z=!0,window.clearInterval(Se)}}},[t.sourceRegistry]);d.useEffect(()=>{const se=T.current;if(!n.rollingEnabled||!_||!H){se.stop(),g(0);return}let we=!1,Z=null;return(async()=>{try{if(Z=await D(_),we)return;await se.start(Z.canvas,Z.target);const ae=window.setInterval(()=>g(Math.round(se.seconds)),500),ye=()=>{window.clearInterval(ae),Z?.cleanup()};se.__cleanup=ye}catch(ae){we||t.onToast(ae instanceof Error?ae.message:String(ae))}})(),()=>{we=!0,se.stop(),se.__cleanup?.(),se.__cleanup=void 0,g(0)}},[D,t.onToast,n.rollingEnabled,B,H]);const K=d.useCallback(se=>r(we=>({...we,rollingEnabled:se})),[]),z=d.useCallback(se=>r(we=>({...we,recordingQuality:se})),[]),W=d.useCallback(se=>r(we=>({...we,timelapseIntervalSeconds:se})),[]),q=d.useCallback(async()=>{const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let we=null;try{we=await D(se),await ZD(we.canvas,we.target,t.hubUrl),t.onToast("Screenshot saved")}finally{we?.cleanup(),w(!1)}},[D,t.hubUrl,t.onToast,t.sourceRegistry]),V=d.useCallback(async()=>{if(j.current)throw new Error("Stop the timelapse before recording.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await D(se),Z=await QS({canvas:we.canvas,target:we.target,fps:se.type==="control"?30:15,hubUrl:t.hubUrl,onError:Se=>t.onToast(Se.message)});A.current=we.cleanup,N.current=Z,l(Date.now()),t.onToast("Recording started")},[D,t.hubUrl,t.onToast,t.sourceRegistry]),X=d.useCallback(async()=>{const se=N.current;if(se){w(!0);try{await se.stop(),t.onToast("Recording saved")}finally{N.current=null,A.current?.(),A.current=null,l(0),w(!1)}}},[t.onToast]),ve=d.useCallback(async()=>{if(N.current||j.current)throw new Error("Last 30s is unavailable during a recording.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await T.current.save(se,t.hubUrl),t.onToast("Last 30 seconds saved")}finally{w(!1)}},[t.hubUrl,t.onToast,t.sourceRegistry]),J=d.useCallback(async()=>{if(N.current)throw new Error("Stop the recording before starting a timelapse.");const se=t.sourceRegistry.resolveCurrentTarget();if(!se)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await D(se),Z=await tI(we.canvas,we.target,n.timelapseIntervalSeconds,t.hubUrl,Se=>t.onToast(Se.message));I.current=we.cleanup,j.current=Z,f(Date.now()),t.onToast("Timelapse started")},[D,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),$=d.useCallback(async()=>{const se=j.current;if(se){w(!0);try{await se.stop(),t.onToast("Timelapse saved")}finally{j.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const se=we=>{!N.current&&!j.current||(we.preventDefault(),we.returnValue="")};return window.addEventListener("beforeunload",se),()=>window.removeEventListener("beforeunload",se)},[]),d.useEffect(()=>()=>{T.current.stop(),N.current?.cancel(),j.current?.cancel(),A.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!N.current,recordingStartedAt:o,timelapse:!!j.current,timelapseStartedAt:u,bufferSeconds:h,bufferEnabled:n.rollingEnabled,busy:y,targetLabel:F}),[h,y,o,n.rollingEnabled,F,u]),settings:n,videoSupported:H,targetKey:B,setRollingEnabled:K,setRecordingQuality:z,setTimelapseInterval:W,takeScreenshot:q,startRecording:V,stopRecording:X,saveLast30Seconds:ve,startTimelapse:J,stopTimelapse:$}}function rI(){if(typeof window>"u")return{isIos:!1,isAndroid:!1,isSafari:!1,browserName:"browser"};const t=window.navigator.userAgent,n=window.navigator.standalone,r=jN(t,window.navigator.platform,window.navigator.maxTouchPoints,n),o=/Android/i.test(t),l=r&&/CriOS/i.test(t),u=r&&/Safari/i.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(t);return{isIos:r,isAndroid:o,isSafari:u,browserName:l?"Chrome":u?"Safari":"browser"}}const sI=120,iI=999,$f=5,Uf=30,oI=Number.POSITIVE_INFINITY,XS="livedesk.remoteDirectory",Sv="livedesk.localHubAccessEnabled",lI="livedesk.streamSettings",cI=18,uI="livedesk.controlStreamSettings",dI=10,ZS="livedesk.wallCadence",fI=1e3,JS="livedesk.wallMonitorSelections",eC=2,Fg=512*1024,mI=!1;"".trim();"".trim();const pI=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),hI=1e3/60,Og=1500,gI=650,vI=1800,yI=650,bI=2500,Bg=1500,vx=15e3,yx=120,bx=100,wx=20,wI=6e4,xI=6e4,xx=240,SI=1024,CI=640,kI=360,Sx="Connected LiveDesk clients are updating in batches. Hub will restart after every target reconnects on the requested versions.",Mp="LiveDesk is replacing the Hub and verifying the requested version.",Ap=5*6e4,MI=5e3,Cx=2e3,AI=8e3;function kx(t,n){return`${t}:${n.deviceId}:${n.completedAt||n.candidateSessionId||n.commandId||"completed"}`}function Yc({label:t,tooltip:n,disabled:r=!1,active:o=!1,danger:l=!1,pressed:u,onClick:f,children:h}){return i.jsx("span",{className:`manual-action-tooltip ${r?"disabled":""}`.trim(),"data-tooltip":n,children:i.jsx("button",{className:`manual-action ${o?"active":""} ${l?"danger":""}`.trim(),onClick:f,disabled:r,"aria-label":t,"aria-pressed":u,type:"button",children:h})})}function NI(t,n){if(n.deviceId!==t.deviceId)return!1;const r=Number(n.browserReceivedEpochMs);if(!Number.isFinite(r)||r<t.startedAtEpochMs)return!1;const o=Number(n.monitorIndex);if(Number.isFinite(o)&&Math.floor(o)!==t.monitorIndex)return!1;const l=String(n.frameMode||n.mode||"").trim().toLowerCase();return!l||l===t.frameMode}const Xc={free:{name:"Free",price:"$0",limit:$f,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Uf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:oI,audience:"Business and studios",note:"Commercial use and larger Client walls."}},TI={"mode3-h264-hw":30};function Mx(t,n){const r=f=>{const g=String(f||"").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 y=g[4]?g[4].split(".").map(w=>/^\d+$/.test(w)?w.length>1&&w.startsWith("0")?Number.NaN:Number(w):w):[];return y.some(w=>typeof w=="number"&&!Number.isFinite(w))?null:{core:[Number(g[1]),Number(g[2]),Number(g[3])],prerelease:y}},o=r(t),l=r(n);if(!o||!l)return!1;for(let f=0;f<3;f+=1){if(o.core[f]>l.core[f])return!0;if(o.core[f]<l.core[f])return!1}if(o.prerelease.length===0||l.prerelease.length===0)return o.prerelease.length===0;const u=Math.max(o.prerelease.length,l.prerelease.length);for(let f=0;f<u;f+=1){const h=o.prerelease[f],g=l.prerelease[f];if(h===void 0||g===void 0)return g===void 0;if(h!==g){if(typeof h=="number"&&typeof g=="number")return h>g;if(typeof h=="number")return!1;if(typeof g=="number"||h>g)return!0;if(h<g)return!1}}return!0}const RI=512;function la(t,n){return`${t}:${n}`}function co(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const jI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:TI["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},EI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Ax={maxWidth:3840,maxHeight:2160};function Bf(t,n){if(t.length===0)return 0;const r=[...t].sort((l,u)=>l-u),o=Math.max(0,Math.min(r.length-1,Math.ceil(r.length*n)-1));return r[o]}function tC(t,n){t.push(n),t.length>xx&&t.splice(0,t.length-xx)}function Np(t,n){t.sampleFrames=0,t.sampleStartedAt=n,t.intervalCount=0,t.intervalSumMs=0,t.minIntervalMs=Number.POSITIVE_INFINITY,t.maxIntervalMs=0,t.intervalSamplesMs.length=0,t.seqGapCount=0,t.maxSeqGap=0}function Nx(t,n,r){if(t.lastAt!==void 0){const o=Math.max(0,n-t.lastAt);t.intervalCount+=1,t.intervalSumMs+=o,t.minIntervalMs=Math.min(t.minIntervalMs,o),t.maxIntervalMs=Math.max(t.maxIntervalMs,o),tC(t.intervalSamplesMs,o)}if(t.lastFrameSeq!==void 0){const o=r-t.lastFrameSeq;o!==1&&(t.seqGapCount+=1,t.maxSeqGap=Math.max(t.maxSeqGap,Math.abs(o)))}t.lastAt=n,t.lastFrameSeq=r}function Tx(t){return!t||t.intervalCount<=0?"waiting":`${Math.round(t.averageIntervalMs)}ms avg / p95 ${Math.round(t.p95IntervalMs)}ms / max ${Math.round(t.maxIntervalMs)}ms`}function Rx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function DI(t){return Number.isFinite(t)?String(t):"30+"}const nC=[1,2,5,8,12,20,30],jx={large:{maxWidth:1920,maxHeight:1080},medium:{maxWidth:1280,maxHeight:720},list:{maxWidth:960,maxHeight:540}},Si={visibleRootMargin:"520px 0px 760px 0px",fallbackVisibleCounts:{large:12,medium:18,list:32},maxWallBytesPerSecond:80*1024*1024,maxFrameGapMs:280,downshiftCooldownMs:1800,downshiftStableSampleMs:Xn.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:Xn.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},Ex=2200,II=2500,LI=8e3,PI=3500,_I=7e3,FI=2,OI=2500,BI=7e3,HI=2600,zI=4200,$I=750,UI=2,Dx=2500,Ix=4200,Lx=2200;function Px(t,n){return Math.min(3e4,t*2**Math.min(3,Math.max(0,n)))}function Op(t,n){const r=t.capabilities?.[n];return typeof r=="boolean"?r:/^(1|true|yes|on)$/i.test(String(r||"").trim())}function Pa(t){return t.deviceName||t.hostname||t.deviceId}function qI(){return"npx -y --prefer-online livedesk@latest client"}function WI(){return"npx -y --prefer-online livedesk@latest"}function GI(){try{return localStorage.getItem(XS)||""}catch{return""}}function VI(){try{return localStorage.getItem(Sv)==="1"}catch{return!1}}function Cd(t){try{t?localStorage.setItem(Sv,"1"):localStorage.removeItem(Sv)}catch{}}function ki(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function fo(t){const n=ki(t.status),r=ki(n.screens),o=ki(t.capabilities),l=ki(t.latestLiveFrame),u=ki(t.activeLiveStream),h=[n.monitorCount,n.screenCount,r.count,o.monitorCount,o.screenCount,l.monitorCount,u.monitorCount,Array.isArray(r.displays)?r.displays.length:0,Array.isArray(n.displays)?n.displays.length:0,Array.isArray(n.monitors)?n.monitors.length:0].map(Number).filter(g=>Number.isFinite(g)&&g>0).map(g=>Math.max(1,Math.min(64,Math.floor(g))));return h.length>0?Math.max(...h):1}function Zl(t){const n=Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):0}function aC(t){const n=ki(t.status),o=[ki(n.screens).displays,n.displays,n.monitors];for(const l of o)if(!(!Array.isArray(l)||l.length===0))return l.map(u=>ki(u));return[]}function ey(t,n){const r=aC(t),o=r.find(g=>Number(g.index)===n)||r[n]||r[0]||{},l=Zl(o.width),u=Zl(o.height),f=[o.name,o.displayName,o.deviceName,o.id].find(g=>typeof g=="string"&&g.trim()),h=typeof f=="string"?f.trim():`Display ${n+1}`;return{index:n,name:h,width:l,height:u,primary:o.primary===!0||o.isPrimary===!0}}function KI(t){const n=fo(t);return Array.from({length:n},(r,o)=>ey(t,o))}function QI(t){const n=aC(t);if(n.length===0)return"";const r=n.map((o,l)=>{const u=Number(o.index),f=[o.name,o.displayName,o.deviceName,o.id].find(g=>typeof g=="string"&&g.trim()),h=g=>{const y=Number(g);return Number.isFinite(y)?y:null};return[Number.isFinite(u)?Math.floor(u):l,typeof f=="string"?f.trim().toLowerCase():"",h(o.left),h(o.top),h(o.width),h(o.height),o.primary===!0||o.isPrimary===!0]}).sort((o,l)=>o[0]-l[0]);return JSON.stringify(r)}function YI(t){const n=[t.name||`Display ${t.index+1}`];return t.width>0&&t.height>0&&n.push(`${t.width}x${t.height}`),t.primary&&n.push("Primary"),n.join(" - ")}function rC(t,n){const r=ey(t,n);if(r.width>0&&r.height>0)return{width:r.width,height:r.height};const o=ki(t.status),l=Zl(o.screenWidth||o.width),u=Zl(o.screenHeight||o.height);return l>0&&u>0?{width:l,height:u}:null}function sC(t){if(!t)return null;const n=Zl(t.sourceWidth)||Zl(t.width),r=Zl(t.sourceHeight)||Zl(t.height);return n>0&&r>0?{width:n,height:r}:null}function XI(t,n,r){const u=((typeof n?.monitorIndex=="number"?qf(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?sC(n):null)||rC(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Tp=16/9;function qf(t,n){const r=Math.max(1,Math.min(64,Math.floor(Number(n)||1))),o=Math.floor(Number(t));return Number.isFinite(o)?Math.max(0,Math.min(r-1,o)):0}function js(t,n){return CN(n,fo(t),t.platform)}function ZI(){try{const t=localStorage.getItem(JS);if(!t)return{selections:{},topologyFingerprints:{}};const n=JSON.parse(t),r=n&&typeof n=="object"&&!Array.isArray(n)?n.selections:void 0;if(Number(n?.version)!==eC||!r||typeof r!="object"||Array.isArray(r))return{selections:{},topologyFingerprints:{}};const o={},l={};for(const[u,f]of Object.entries(r)){const h=u.trim(),g=ki(f),y=g.monitorIndex,w=Math.floor(Number(y));if(!h||!Number.isFinite(w))continue;o[h]=Math.max(0,Math.min(63,w));const b=typeof g.topologyFingerprint=="string"?g.topologyFingerprint.trim():"";b&&(l[h]=b)}return{selections:o,topologyFingerprints:l}}catch{return{selections:{},topologyFingerprints:{}}}}function JI(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([o,l])=>[o,{monitorIndex:l,topologyFingerprint:n[o]||""}]));localStorage.setItem(JS,JSON.stringify({version:eC,selections:r}))}catch{}}function eL(){return{...jI}}function tL(t){try{localStorage.setItem(lI,JSON.stringify({...t,version:cI}))}catch{}}function nL(){return{...EI}}function aL(t){try{localStorage.setItem(uI,JSON.stringify({...t,version:dI}))}catch{}}function rL(){try{return localStorage.getItem(ZS)==="slow"?"slow":"fast"}catch{return"fast"}}function sL(t){try{localStorage.setItem(ZS,t)}catch{}}function Hg(t,n){return t.length!==n.length?!1:t.every((r,o)=>r===n[o])}function zg(t){return[...new Set(t.filter(Boolean))].sort()}function iL(t){return Si.fallbackVisibleCounts[t]||Si.fallbackVisibleCounts.large}function _x(t,n,r){if(t.frameMode==="mode4-h264-atlas")return t.atlasTileSizeMode==="auto"?n==="large"?{maxWidth:640,maxHeight:360}:{maxWidth:320,maxHeight:180}:{maxWidth:t.atlasTileWidth,maxHeight:t.atlasTileHeight};if(!t.adaptiveSizeByWall)return{maxWidth:t.maxWidth,maxHeight:t.maxHeight};const o=jx[n]||jx.large;return{maxWidth:Math.min(t.maxWidth,o.maxWidth),maxHeight:Math.min(t.maxHeight,o.maxHeight)}}function oL(t,n=Si.minFps){const r=[...nC].sort((l,u)=>l-u),o=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||o}function lL(t,n){return[...nC].sort((o,l)=>o-l).find(o=>o>t&&o<=n)||n}function Wf(t){if(!Number.isFinite(t)||t<=0)return"0 B";const n=["B","KB","MB","GB","TB"];let r=t,o=0;for(;r>=1024&&o<n.length-1;)r/=1024,o+=1;const l=o===0||r>=100?0:1;return`${r.toFixed(l)} ${n[o]}`}function Fx(t){if(!Number.isFinite(t)||!t||t<=0)return"0GB";const n=1024**4,r=1024**3;return t>=n?`${Math.max(1,Math.round(t/n))}TB`:`${Math.max(1,Math.round(t/r))}GB`}function $g(t,n){if(!Number.isFinite(t)||!t||t<=0)return"not reported";const r=Math.max(0,t-Math.max(0,Number(n||0)));return`${Fx(r)} / ${Fx(t)}`}function cL(t){const n=new Uint8Array(t),r=32768;let o="";for(let l=0;l<n.length;l+=r){const u=n.subarray(l,l+r);o+=String.fromCharCode(...u)}return btoa(o)}function Ox(t){return Array.from(t).filter(n=>n.size>=0).map(n=>{const r=n.webkitRelativePath||n.name;return{file:n,relativePath:r,fingerprint:`${n.size}:${n.lastModified}`}})}function uL(t){return t===1?"middle":t===2?"right":"left"}function Bx(t,...n){for(const r of n){const o=t?.[r];if(typeof o=="string"&&o.trim())return o.trim()}return""}function Hx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=iI?n:0}const dL={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function fL(t,n,r){if(t==="online")return"Online";if(t==="busy")return"Busy";if(t==="stale")return"Stale";if(t==="offline")return"Offline";if(r==="failed")return"Task failed";const o=t==="critical"?"critical":"warn",l=n.find(f=>f.state===o)||n.find(f=>f.state==="critical"||f.state==="warn");if(!l)return t==="critical"?"Issue":"Check";const u=dL[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function iC(t,n){const r=n.split(".");let o=t;for(const l of r){if(o==null)return;if(Array.isArray(o)){const u=Number(l);o=Number.isInteger(u)?o[u]:void 0;continue}if(typeof o=="object"){o=o[l];continue}return}return o}function aa(t,...n){for(const r of n){const o=iC(t,r),l=Number(o);if(Number.isFinite(l))return l}}function uo(t,...n){for(const r of n){const o=iC(t,r);if(typeof o=="string"&&o.trim())return o.trim();if(typeof o=="number"&&Number.isFinite(o))return String(o)}return""}function el(t){const n=Number(t);if(Number.isFinite(n))return Math.max(0,Math.min(1,n>1?n/100:n))}function Ug(t,n){if(!(typeof t!="number"||typeof n!="number"||!Number.isFinite(t)||!Number.isFinite(n)||t<=0))return el((t-Math.max(0,n))/t)}function kd(t){return t===void 0?"-":`${Math.round(t*100)}%`}function qg(t){return t===void 0||!Number.isFinite(t)?"":t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}Gb/s`:`${Math.round(t)}Mb/s`}function Zc(t,n=.92,r=.78){return t===void 0?"unknown":t>=n?"critical":t>=r?"warn":"good"}function mL(t){return!Number.isFinite(t)||!t||t<=0?"-":t<3600?`${Math.round(t/60)}m`:t<86400?`${Math.round(t/3600)}h`:`${Math.round(t/86400)}d`}function oC(t){const n=t.status||{},r=aa(n,"cpu.cores","cpuCores","processorCount"),o=aa(n,"loadavg.0","cpu.load1"),l=el(aa(n,"cpu.usedRatio","cpu.usageRatio","cpu.ratio","cpu.usedPct","cpu.usagePct","cpu.percent")??(r&&o!==void 0?o/Math.max(1,r):void 0)),u=aa(n,"memory.totalBytes","totalMem"),f=aa(n,"memory.freeBytes","freeMem"),h=el(aa(n,"memory.usedRatio","memory.usedPct","usedMemRatio"))??Ug(u,f),g=aa(n,"disk.totalBytes","rootDisk.totalBytes","storage.totalBytes"),y=aa(n,"disk.freeBytes","rootDisk.freeBytes","storage.freeBytes"),w=el(aa(n,"disk.usedRatio","disk.usedPct","rootDisk.usedRatio","storage.usedRatio"))??Ug(g,y),b=aa(n,"thermal.cpuC","temperatureC","cpu.temperatureC","gpu.temperatureC"),S=el(aa(n,"gpu.usedRatio","gpu.usageRatio","gpu.usedPct","gpu.usagePct","gpu.percent","accelerators.gpu.usageRatio")),k=uo(n,"gpu.name","gpu.model","accelerators.gpu.name"),N=aa(n,"gpu.memory.totalBytes","gpu.totalMemoryBytes","gpu.vramTotalBytes"),A=aa(n,"gpu.memory.freeBytes","gpu.freeMemoryBytes","gpu.vramFreeBytes"),j=el(aa(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ug(N,A),I=aa(n,"gpu.temperatureC","thermal.gpuC"),T=el(aa(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),_=uo(n,"npu.name","npu.model","accelerators.npu.name"),B=aa(n,"npu.tops","npu.topsInt8","accelerators.npu.tops"),F=aa(n,"network.rxMbps","network.receiveMbps","network.downMbps"),H=aa(n,"network.txMbps","network.transmitMbps","network.upMbps"),D=aa(n,"network.latencyMs","network.rttMs"),K=el(aa(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),z=uo(n,"network.link","network.interface","network.name"),W=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),q=Number.isFinite(W)?W:void 0,V=q===void 0?void 0:el((q-35)/60),X=b!==void 0&&I!==void 0?`CPU ${Math.round(b)}° · GPU ${Math.round(I)}°`:b!==void 0?`CPU ${Math.round(b)}°`:I!==void 0?`GPU ${Math.round(I)}°`:"-",ve=uo(n,"workload.role","role","lane")||(Op(t,"taskDispatch")?"Command-ready Client":"Local machine"),J=uo(t.latestTask,"status")||uo(n,"workload.status")||"idle",$=uo(t.latestTask,"title","instructionPreview")||uo(n,"workload.title"),P=uo(t.latestTask,"resultSummary","error","instructionPreview")||uo(n,"workload.summary"),se=Date.parse(t.lastSeenAt||t.connectedAt||""),we=Number.isFinite(se)?Date.now()-se:0;let Z="online";t.connected?we>5*6e4?Z="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(S??0)>=.96||(j??0)>=.96||(T??0)>=.96||(h??0)>=.94||(w??0)>=.94||(D??0)>=200||J==="failed"?Z="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(S??0)>=.86||(j??0)>=.88||(T??0)>=.86||(h??0)>=.82||(w??0)>=.86||(D??0)>=80?Z="warn":["queued","running","targeted"].includes(J)&&(Z="busy"):Z="offline";const Se=[{id:"cpu",label:"CPU",value:kd(l),detail:r?`${r} cores`:o!==void 0?`load ${o.toFixed(1)}`:"not reported",ratio:l,state:Zc(l,.92,.78)},{id:"memory",label:"RAM",value:kd(h),detail:$g(u,f),ratio:h,state:Zc(h,.92,.78)},{id:"disk",label:"DISK",value:kd(w),detail:$g(g,y),ratio:w,state:Zc(w,.92,.82)},{id:"gpu",label:"GPU",value:kd(S),detail:k||(N&&A!==void 0?`${Wf(A)} VRAM free`:I!==void 0?`${Math.round(I)}C`:"not reported"),ratio:S,state:I!==void 0&&I>=88?"critical":I!==void 0&&I>=80?"warn":Zc(S,.96,.86)},{id:"vram",label:"VRAM",value:kd(j),detail:$g(N,A),ratio:j,state:Zc(j,.96,.88)},{id:"npu",label:"NPU",value:T!==void 0?kd(T):B!==void 0?`${Math.round(B)} TOPS`:"-",detail:_||(B!==void 0?"neural engine":"not reported"),ratio:T,state:Zc(T,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${mL(aa(n,"uptimeSec"))}`,ratio:V,state:q===void 0?"unknown":q>=86?"critical":q>=78?"warn":"good"},{id:"network",label:"NET",value:qg(F)||(D!==void 0?`${Math.round(D)}ms`:z||"-"),detail:qg(H)?`${qg(H)} up`:z||"not reported",ratio:K,state:D!==void 0&&D>=200?"critical":D!==void 0&&D>=80?"warn":Zc(K,.9,.75)}];return{state:Z,label:fL(Z,Se,J),role:ve,taskLabel:$||(J==="idle"?"idle":J),taskStatus:J,taskSummary:P,metrics:Se}}const pL=[{id:"slow",label:"Slow",fps:pv("slow")},{id:"fast",label:"Fast",fps:pv("fast")}],hL=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],gL=[{id:"sync-server",label:"Hub",icon:mo,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:t0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:Hf,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Kf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:jp,accent:"violet",tooltip:"agents"}],vL=[{id:"doc",label:"Doc",icon:Hp,accent:"amber"},{id:"support",label:"Support",icon:Gf,accent:"violet"},{id:"pricing",label:"Pricing",icon:Vf,accent:"green"}];function yL(t){return t.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 Yn(t){return yL(t).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 Jc(t){return t.map(n=>Yn(n))}function kr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:Yn(t.title),intro:Yn(t.intro),sections:[{title:Yn(t.managerTitle),body:Yn(t.managerBody),points:Jc(t.managerPoints)},{title:Yn(t.clientTitle),body:Yn(t.clientBody),points:Jc(t.clientPoints)},{title:Yn(t.syncTitle),body:Yn(t.syncBody),points:Jc(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:Yn(t.agentTitle),body:Yn(t.agentBody),points:Jc(t.agentPoints)}]:[],{title:Yn(t.platformTitle),body:Yn(t.platformBody),points:Jc(t.platformPoints)}],sync:{title:Yn(t.syncTitle),body:Yn(t.syncBody),points:Jc(t.syncPoints)},firewall:{title:Yn(t.firewallTitle),body:Yn(t.firewallBody),points:Jc(t.firewallPoints)},commands:{title:Yn(t.commandsTitle),body:Yn(t.commandsBody),manager:Yn(t.managerCommandLabel),primary:Yn(t.clientCommandLabel),slot:Yn(t.slotCommandLabel),manual:Yn(t.manualCommandLabel)}}}const jd={ko:kr({languageName:"한국어",languageLabel:"문서 언어",eyebrow:"LiveDesk Manual",title:"한 줄로 여는 로컬 Screen Wall",intro:"LiveDesk는 매니저 PC 한 대에서 여러 작업 PC, 미니 PC, 맥미니, 개발 장비를 한 화면에 모니터링하고 필요한 제어를 실행하는 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에는 일반적인 읽기·운영 명령 템플릿이 있으며, 검색과 권한·플랫폼·capability 조건으로 실행 가능 항목을 안내합니다.","Ask, Safe Auto, Full Access, Custom 권한 모드를 선택할 수 있습니다. 위험한 변경 작업은 승인 카드와 장비 capability 검사를 거칩니다.","All connected 또는 Selected로 대상 장비를 제한하고, 결과는 장비별 상태 칩과 실제 RAM·디스크·GPU·프로세스 요약으로 확인합니다.","Hub의 Codex Agent는 지시를 승인된 LiveDesk 도구로 변환하고 컴퓨터별 실행 상태와 결과를 표시합니다."],platformTitle:"5. 현재 플랫폼과 스트림 상태",platformBody:"Windows의 Wall, Control, 파일 전송, 원격 오디오와 RemoteFast 경로를 현재 기준으로 확인했습니다. macOS와 Linux는 같은 npm 명령 경로를 유지하면서 권한과 캡처 백엔드를 확장하고 있습니다.",platformPoints:["자동 Wall과 Control은 모든 Client에서 직접 H.264를 사용합니다. RGB565/LZO Atlas는 내부 진단 실험에만 남고 자동 전송 경로에는 사용되지 않습니다.","원격 오디오는 선택한 장비가 capability를 광고할 때 사용할 수 있으며, 브라우저는 queue·drop·resync·automatic restart 상태를 진단합니다.","macOS: 화면 캡처와 제어에는 Screen Recording/Accessibility 권한이 필요합니다. RemoteFast 로그는 필요한 상태 중심으로 제한됩니다.","Linux: linux-x64 runtime, X11/XTEST 입력과 PipeWire/PulseAudio 기본 출력 오디오 캡처를 지원합니다."],firewallTitle:"방화벽과 외부 장소 연결",firewallBody:"LiveDesk는 Direct TCP를 먼저 시도하고, 직접 연결이 안 되면 암호화된 rendezvous relay로 제어를 연결하며 가능한 경우 영상은 암호화된 UDP P2P로 전송합니다.",firewallPoints:["LAN Direct TCP의 기본 클라이언트 포트는 5197입니다.","클라이언트와 매니저는 설정된 rendezvous 서버로 나가는 연결이 가능해야 합니다.","Direct TCP가 실패하면 relay 제어와 UDP P2P 영상을 자동으로 시도합니다.","외부망에서도 Direct TCP를 원할 때만 TCP 5197 포트포워딩이나 VPN/IP allowlist를 설정합니다.","Screen Wall/API 포트 5179는 외부 브라우저가 Wall을 직접 열 때만 노출합니다."],commandsTitle:"현재 사용 명령",commandsBody:"웹사이트를 찾아가 설치 파일을 받는 방식보다 터미널 한 줄로 모든 운영체제에서 거의 같은 흐름을 쓰는 것이 LiveDesk의 기본 방향입니다.",managerCommandLabel:"매니저 시작",clientCommandLabel:"워크스테이션 연결",slotCommandLabel:"3번 슬롯에 고정",manualCommandLabel:"고급 수동 연결"}),en:kr({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 Clients, mini PCs, Mac minis, and development 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 Client",clientBody:"On each monitored computer, connect with Google sign-in or the 6-digit PIN shown on the Hub screen. If no manager is online yet, the client waits for a live online signal and falls back to adaptive retries.",clientPoints:["Run npx -y livedesk client for first available placement.","Run npx -y livedesk client 3 to pin the machine to slot 3.","The browser connection page lets you choose Google or a 6-digit PIN."],syncTitle:"3. Sync Server and discovery",syncBody:"Sync Server publishes this manager as the active Screen Wall for the signed-in account. Clients read that Supabase record after Google sign-in and try the endpoint candidates in order.",syncPoints:["The record includes host instance, LAN/private addresses, public endpoint candidates, pair token, and a short lease.","LAN candidates are preferred first, then public candidates if needed.","Press Sync Server after manager moves, VPN/firewall/router changes, or when this development machine should take over as active manager.","Chrome Local Network Access on livedesk.pages.dev is no longer the default runtime path. The npm manager app is the real server."],agentTitle:"4. Run multi-Client tasks with Agent",agentBody:"The Agents page runs a Codex-based Agent in the Hub to inspect connected Clients and perform actions within the selected permission scope. Client PCs do not need the Codex app or Codex SDK installed.",agentPoints:["Suggested tasks provide generic read-only and operational command templates with search plus permission, platform, and capability checks.","Choose Ask, Safe Auto, Full Access, or Custom. Risky changes go through approval cards and explicit Client capability checks.","Limit targets with All connected or Selected. Results use compact per-device status chips and show real RAM, disk, GPU, and process summaries.","The Hub-hosted Codex Agent turns instructions into approved LiveDesk tool calls and shows progress and results for each computer."],platformTitle:"5. Current platform and stream state",platformBody:"Windows Wall, Control, file transfer, remote audio, and the RemoteFast path are verified against the current implementation. macOS and Linux keep the same npm command path while capture and permission backends expand.",platformPoints:["Automatic Wall and Control use direct H.264 for every Client. The RGB565/LZO Atlas remains only for internal diagnostic experiments and is never selected automatically.","Remote audio is available when the selected Client advertises the capability, with queue, drop, resync, and automatic-restart diagnostics in the browser.","macOS requires Screen Recording and Accessibility permissions for capture and control. RemoteFast logs focus on actionable state.","Linux includes the linux-x64 runtime, X11/XTEST input, and default-output audio capture through PipeWire or PulseAudio."],firewallTitle:"Firewall and remote locations",firewallBody:"LiveDesk tries Direct TCP first; if direct access fails, control uses the encrypted rendezvous relay and video uses encrypted UDP P2P when available.",firewallPoints:["The default LAN Direct TCP client port is 5197.","Clients and the manager need outbound access to the configured rendezvous server.","Relay control and UDP P2P video are attempted automatically after Direct TCP fails.","Forward TCP 5197 or configure VPN/IP allowlists only when Direct TCP is required across networks.","Expose Screen Wall/API port 5179 only when a remote browser must open the Wall directly."],commandsTitle:"Current commands",commandsBody:"The product direction is one terminal command across operating systems instead of finding a website, downloading, and installing manually.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ja:kr({languageName:"日本語",languageLabel:"ドキュメント言語",eyebrow:"LiveDesk Manual",title:"1行でローカル Screen Wall を開く",intro:"LiveDesk は、複数の作業 PC、mini PC、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. Client を接続",clientBody:"監視される PC で同じ Google アカウントにログインします。manager がまだ無い場合、client はオンライン通知を待ち、適応型の間隔で再確認します。",clientPoints:["空きスロットに入れるには npx -y livedesk client を実行します。","スロットを固定するには npx -y livedesk client 3 のように番号を付けます。","大量の PC でも再ログインなしで待ち続けます。"],syncTitle:"3. Sync Server と自動検出",syncBody:"Sync Server はこの manager を現在の Google アカウントの active Screen Wall として Supabase に登録します。",syncPoints:["host instance、LAN/private アドレス、public 候補、pair token、短い lease を登録します。","client は LAN 候補を優先し、必要なら public 候補も試します。","VPN、firewall、router、manager の場所が変わったら Sync Server を押します。","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、X11/XTEST input backend を追加済み。audio は未対応です。"],firewallTitle:"Firewall と外部拠点",firewallBody:"LiveDesk は Direct TCP を先に試し、失敗した場合は暗号化 rendezvous relay で制御し、可能なら映像に暗号化 UDP P2P を使います。",firewallPoints:["LAN の Direct TCP client 既定ポートは 5197 です。","client と manager は設定済み rendezvous server へ outbound 接続できる必要があります。","Direct TCP 失敗後は relay 制御と UDP P2P 映像を自動的に試します。","ネットワーク越しに Direct TCP が必要な場合だけ TCP 5197 の転送または VPN/IP allowlist を設定します。","5179 は外部ブラウザが Wall を直接開く場合だけ公開します。"],commandsTitle:"現在のコマンド",commandsBody:"Web サイトから installer を探すより、OS をまたいで terminal 1行で動かす方向です。",managerCommandLabel:"manager 起動",clientCommandLabel:"Client 接続",slotCommandLabel:"slot 3 に固定",manualCommandLabel:"高度な手動接続"}),"zh-CN":kr({languageName:"简体中文",languageLabel:"文档语言",eyebrow:"LiveDesk Manual",title:"用一条命令打开本地 Screen Wall",intro:"LiveDesk 是 npm-first 的远程工作台,用一台 manager PC 监控多台工作电脑、迷你主机、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. 连接 Client",clientBody:"在被监控的电脑上使用同一个 Google 账号登录。如果 manager 尚未在线,client 会等待上线通知,并以自适应间隔重新检查。",clientPoints:["自动放入空位: npx -y livedesk client。","固定到 3 号位置: npx -y livedesk client 3。","大量电脑也可以持续等待,不需要反复登录。"],syncTitle:"3. Sync Server 和自动发现",syncBody:"Sync Server 会把当前 manager 作为该账号的 active Screen Wall 写入 Supabase。client 登录后读取记录并依次尝试连接候选地址。",syncPoints:["记录包括 host instance、LAN/private 地址、public 候选、pair token 和短 lease。","优先尝试同一 LAN 地址,需要时再尝试外部地址。","manager 位置、VPN、防火墙或路由变化后请点击 Sync Server。","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 捕获、X11/XTEST 输入后端。音频尚未启用。"],firewallTitle:"防火墙和外部地点",firewallBody:"LiveDesk 会先尝试 Direct TCP;直连失败时,控制改用加密 rendezvous relay,视频在可用时使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的默认 client 端口是 5197。","client 和 manager 必须能向已配置的 rendezvous server 建立出站连接。","Direct TCP 失败后会自动尝试 relay 控制和 UDP P2P 视频。","只有跨网络需要 Direct TCP 时才转发 TCP 5197 或配置 VPN/IP 白名单。","只有远程浏览器需要直接打开 Wall 时才暴露 5179。"],commandsTitle:"当前命令",commandsBody:"产品方向是跨操作系统使用一条终端命令,而不是先找网站、下载、安装。",managerCommandLabel:"启动 manager",clientCommandLabel:"连接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"高级手动连接"}),"zh-TW":kr({languageName:"繁體中文",languageLabel:"文件語言",eyebrow:"LiveDesk Manual",title:"用一行指令開啟本機 Screen Wall",intro:"LiveDesk 是 npm-first 的遠端工作台,用一台 manager PC 監看多台工作電腦、迷你主機、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. 連接 Client",clientBody:"在被監看的電腦上使用同一個 Google 帳號登入。如果 manager 尚未上線,client 會等待上線通知,並以自適應間隔重新檢查。",clientPoints:["自動放入空位: npx -y livedesk client。","固定到 3 號位置: npx -y livedesk client 3。","大量電腦也能持續等待,不需要反覆登入。"],syncTitle:"3. Sync Server 與自動探索",syncBody:"Sync Server 會把目前 manager 登錄為此帳號的 active Screen Wall。client 登入後讀取 Supabase 記錄並依序嘗試連線候選地址。",syncPoints:["記錄包含 host instance、LAN/private 位址、public 候選、pair token 與短 lease。","優先嘗試 LAN 位址,需要時再嘗試外部位址。","manager 位置、VPN、防火牆或路由設定改變後請按 Sync Server。","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、X11/XTEST input backend。音訊尚未啟用。"],firewallTitle:"防火牆與外部地點",firewallBody:"LiveDesk 會先嘗試 Direct TCP;直連失敗時,控制改用加密 rendezvous relay,影像在可用時使用加密 UDP P2P。",firewallPoints:["LAN Direct TCP 的預設 client 連接埠是 5197。","client 與 manager 必須能向已設定的 rendezvous server 建立外送連線。","Direct TCP 失敗後會自動嘗試 relay 控制與 UDP P2P 影像。","只有跨網路需要 Direct TCP 時才轉送 TCP 5197 或設定 VPN/IP allowlist。","只有遠端瀏覽器需要直接開啟 Wall 時才公開 5179。"],commandsTitle:"目前指令",commandsBody:"產品方向是跨作業系統用一行 terminal 指令,而不是先找網站、下載、安裝。",managerCommandLabel:"啟動 manager",clientCommandLabel:"連接 Client",slotCommandLabel:"固定到 slot 3",manualCommandLabel:"進階手動連線"}),es:kr({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 equipos de trabajo, mini PC, 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 Client",clientBody:"En cada equipo monitoreado, inicia sesión con la misma cuenta Google. Si el manager aún no está activo, el client espera una señal en tiempo real y vuelve a comprobar con intervalos adaptativos.",clientPoints:["Usa npx -y livedesk client para el primer slot libre.","Usa npx -y livedesk client 3 para fijar el equipo al slot 3.","Los clients siguen esperando para no repetir login en muchas máquinas."],syncTitle:"3. Sync Server y descubrimiento",syncBody:"Sync Server publica este manager como Screen Wall activo para la cuenta. Los clients leen el registro en Supabase y prueban los endpoints.",syncPoints:["Incluye host instance, direcciones LAN/private, candidatos public, pair token y lease corto.","Primero se prueban candidatos LAN, luego públicos si hace falta.","Pulsa Sync Server después de cambios de manager, VPN, firewall o router.","Chrome Local Network Access en 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: runtime linux-x64, entrada X11/XTEST y audio de salida mediante PipeWire o PulseAudio."],firewallTitle:"Firewall y sedes remotas",firewallBody:"LiveDesk intenta primero Direct TCP; si falla, el control usa el rendezvous relay cifrado y el vídeo usa UDP P2P cifrado cuando está disponible.",firewallPoints:["El puerto client predeterminado para Direct TCP en LAN es 5197.","Clients y manager necesitan acceso saliente al servidor rendezvous configurado.","Tras fallar Direct TCP se intentan automáticamente control relay y vídeo UDP P2P.","Reenvía TCP 5197 o configura VPN/allowlist de IP solo si necesitas Direct TCP entre redes.","Expón 5179 solo si un navegador remoto debe abrir el Wall directamente."],commandsTitle:"Comandos actuales",commandsBody:"La dirección del producto es un comando de terminal común entre sistemas, no descargar e instalar desde una web.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fijar al slot 3",manualCommandLabel:"Conexión manual avanzada"}),fr:kr({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, mini PC, 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 Client",clientBody:"Sur chaque ordinateur surveillé, connectez-vous avec le même compte Google. Si le manager n’est pas encore actif, le client réessaie toutes les 5 secondes.",clientPoints:["Utilisez npx -y livedesk client pour le premier slot libre.","Utilisez npx -y livedesk client 3 pour fixer la machine au slot 3.","Les clients continuent d’attendre pour éviter les reconnexions répétées."],syncTitle:"3. Sync Server et découverte",syncBody:"Sync Server publie ce manager comme Screen Wall actif du compte. Les clients lisent l’enregistrement Supabase et testent les endpoints.",syncPoints:["Il contient host instance, adresses LAN/private, candidats public, pair token et lease court.","Les candidats LAN sont essayés en premier, puis les candidats publics si besoin.","Cliquez Sync Server après un changement de manager, VPN, firewall ou routeur.","Chrome Local Network Access sur 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, entrée X11/XTEST et audio de sortie via PipeWire ou PulseAudio."],firewallTitle:"Firewall et sites distants",firewallBody:"LiveDesk tente d’abord Direct TCP ; en cas d’échec, le contrôle utilise le relais rendezvous chiffré et la vidéo UDP P2P chiffrée lorsqu’elle est disponible.",firewallPoints:["Le port client Direct TCP par défaut sur le LAN est 5197.","Clients et manager doivent avoir un accès sortant au serveur rendezvous configuré.","Après un échec Direct TCP, le contrôle relay et la vidéo UDP P2P sont tentés automatiquement.","Redirigez TCP 5197 ou configurez VPN/allowlist IP seulement si Direct TCP est requis entre réseaux.","Exposez 5179 uniquement si un navigateur distant doit ouvrir directement le Wall."],commandsTitle:"Commandes actuelles",commandsBody:"La direction produit est une commande terminal commune aux OS, plutôt qu’un téléchargement manuel depuis un site.",managerCommandLabel:"Démarrer manager",clientCommandLabel:"Connecter Client",slotCommandLabel:"Fixer au slot 3",manualCommandLabel:"Connexion manuelle avancée"}),de:kr({languageName:"Deutsch",languageLabel:"Dokumentsprache",eyebrow:"LiveDesk Manual",title:"Lokale Screen Wall mit einem Befehl öffnen",intro:"LiveDesk ist ein npm-first Arbeitsdeck, um viele Clients, Mini-PCs, Mac minis und Dev-Rechner von einem Manager-PC zu überwachen.",managerTitle:"1. Manager starten",managerBody:"Starte 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. Client verbinden",clientBody:"Melde dich auf jedem überwachten Computer mit demselben Google-Konto an. Wenn kein Manager online ist, wartet der Client auf ein Live-Signal und prüft mit adaptiven Intervallen erneut.",clientPoints:["npx -y livedesk client nutzt den ersten freien Slot.","npx -y livedesk client 3 fixiert den Rechner auf Slot 3.","Clients warten weiter, damit große Setups kein wiederholtes Login brauchen."],syncTitle:"3. Sync Server und Discovery",syncBody:"Sync Server veröffentlicht diesen Manager als aktive Screen Wall des Kontos. Clients lesen den Supabase-Eintrag und testen Endpoints der Reihe nach.",syncPoints:["Enthält host instance, LAN/private Adressen, public Kandidaten, pair token und kurze lease.","LAN-Kandidaten werden zuerst versucht, danach public Kandidaten.","Nach Änderungen an Manager, VPN, Firewall oder Router Sync Server drücken.","Chrome Local Network Access auf 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, X11/XTEST Eingabe und Ausgangsaudio über PipeWire oder PulseAudio."],firewallTitle:"Firewall und entfernte Standorte",firewallBody:"LiveDesk versucht zuerst Direct TCP; schlägt dies fehl, nutzt die Steuerung das verschlüsselte Rendezvous-Relay und Video nach Möglichkeit verschlüsseltes UDP P2P.",firewallPoints:["Der Standardport für LAN Direct TCP Clients ist 5197.","Clients und Manager benötigen ausgehenden Zugriff auf den konfigurierten Rendezvous-Server.","Nach einem Direct-TCP-Fehler werden Relay-Steuerung und UDP-P2P-Video automatisch versucht.","TCP 5197 nur weiterleiten oder VPN/IP-Allowlist einrichten, wenn Direct TCP netzübergreifend nötig ist.","5179 nur öffnen, wenn ein Remote-Browser die Wall direkt laden muss."],commandsTitle:"Aktuelle Befehle",commandsBody:"Die Produktlinie ist ein Terminalbefehl über Betriebssysteme hinweg, statt Website suchen, herunterladen und installieren.",managerCommandLabel:"Manager starten",clientCommandLabel:"Client verbinden",slotCommandLabel:"An Slot 3 fixieren",manualCommandLabel:"Erweiterte manuelle Verbindung"}),"pt-BR":kr({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, mini PCs, 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 Client",clientBody:"Em cada computador monitorado, entre com a mesma conta Google. Se o manager ainda não estiver online, o client aguarda um sinal em tempo real e verifica novamente em intervalos adaptativos.",clientPoints:["Use npx -y livedesk client para o primeiro slot livre.","Use npx -y livedesk client 3 para fixar no slot 3.","Clients continuam tentando para evitar login repetido em muitos PCs."],syncTitle:"3. Sync Server e descoberta",syncBody:"Sync Server publica este manager como Screen Wall ativo da conta. Clients leem o registro no Supabase e testam endpoints.",syncPoints:["Inclui host instance, endereços LAN/private, candidatos public, pair token e lease curto.","Candidatos LAN vêm primeiro; public depois se necessário.","Clique Sync Server após mudanças de manager, VPN, firewall ou roteador.","Chrome Local Network Access em 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 X11/XTEST adicionados. Áudio ainda desativado."],firewallTitle:"Firewall e locais remotos",firewallBody:"LiveDesk tenta Direct TCP primeiro; se falhar, o controle usa o rendezvous relay criptografado e o vídeo usa UDP P2P criptografado quando disponível.",firewallPoints:["A porta client padrão para Direct TCP na LAN é 5197.","Clients e manager precisam de acesso de saída ao servidor rendezvous configurado.","Após falha no Direct TCP, controle relay e vídeo UDP P2P são tentados automaticamente.","Encaminhe TCP 5197 ou configure VPN/allowlist IP apenas se Direct TCP entre redes for necessário.","Exponha 5179 somente se um navegador remoto precisar abrir o Wall diretamente."],commandsTitle:"Comandos atuais",commandsBody:"A direção do produto é um comando de terminal comum entre sistemas, não baixar e instalar manualmente.",managerCommandLabel:"Iniciar manager",clientCommandLabel:"Conectar Client",slotCommandLabel:"Fixar no slot 3",manualCommandLabel:"Conexão manual avançada"}),it:kr({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 Client, mini PC, 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 Client",clientBody:"Su ogni computer monitorato, accedi con lo stesso account Google. Se il manager non è online, il client riprova ogni 5 secondi.",clientPoints:["npx -y livedesk client usa il primo slot libero.","npx -y livedesk client 3 fissa la macchina allo slot 3.","I client continuano a provare per evitare login ripetuti."],syncTitle:"3. Sync Server e discovery",syncBody:"Sync Server pubblica questo manager come Screen Wall attivo dell’account. I client leggono Supabase e provano gli endpoint.",syncPoints:["Include host instance, indirizzi LAN/private, candidati public, pair token e lease breve.","Prima LAN, poi public se necessario.","Premi Sync Server dopo cambi di manager, VPN, firewall o router.","Chrome Local Network Access su 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 X11/XTEST. Audio disattivato."],firewallTitle:"Firewall e sedi remote",firewallBody:"LiveDesk prova prima Direct TCP; se fallisce, il controllo usa il rendezvous relay cifrato e il video usa UDP P2P cifrato quando disponibile.",firewallPoints:["La porta client predefinita per Direct TCP in LAN è 5197.","Client e manager devono avere accesso in uscita al server rendezvous configurato.","Dopo un errore Direct TCP, controllo relay e video UDP P2P vengono tentati automaticamente.","Inoltra TCP 5197 o configura VPN/allowlist IP solo se serve Direct TCP tra reti.","Esponi 5179 soltanto se un browser remoto deve aprire direttamente la Wall."],commandsTitle:"Comandi attuali",commandsBody:"La direzione è un comando terminale comune tra sistemi operativi, invece di download e install manuale.",managerCommandLabel:"Avvia manager",clientCommandLabel:"Connetti Client",slotCommandLabel:"Fissa allo slot 3",manualCommandLabel:"Connessione manuale avanzata"}),id:kr({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 Client, mini PC, 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 Client",clientBody:"Di komputer yang dipantau, masuk dengan akun Google yang sama. Jika manager belum online, client tetap mencoba tiap 5 detik.",clientPoints:["npx -y livedesk client memakai slot kosong pertama.","npx -y livedesk client 3 mengunci mesin ke slot 3.","Client terus mencoba agar banyak PC tidak perlu login berulang."],syncTitle:"3. Sync Server dan discovery",syncBody:"Sync Server menerbitkan manager ini sebagai Screen Wall aktif untuk akun. Client membaca Supabase dan mencoba endpoint.",syncPoints:["Berisi host instance, alamat LAN/private, kandidat public, pair token, dan lease pendek.","Kandidat LAN dicoba lebih dulu, lalu public jika perlu.","Tekan Sync Server setelah perubahan manager, VPN, firewall, atau router.","Chrome Local Network Access di 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 X11/XTEST sudah ditambahkan. Audio belum aktif."],firewallTitle:"Firewall dan lokasi luar",firewallBody:"LiveDesk mencoba Direct TCP lebih dulu; jika gagal, kontrol memakai rendezvous relay terenkripsi dan video memakai UDP P2P terenkripsi bila tersedia.",firewallPoints:["Port client default untuk Direct TCP di LAN adalah 5197.","Client dan manager memerlukan akses keluar ke server rendezvous yang dikonfigurasi.","Setelah Direct TCP gagal, kontrol relay dan video UDP P2P dicoba otomatis.","Forward TCP 5197 atau atur VPN/IP allowlist hanya jika Direct TCP antarjaringan diperlukan.","Buka 5179 hanya jika browser jarak jauh harus membuka Wall secara langsung."],commandsTitle:"Perintah saat ini",commandsBody:"Arah produk adalah satu perintah terminal lintas OS, bukan download dan instal manual.",managerCommandLabel:"Mulai manager",clientCommandLabel:"Hubungkan Client",slotCommandLabel:"Kunci ke slot 3",manualCommandLabel:"Koneksi manual lanjutan"}),vi:kr({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 Client, mini PC, 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 Client",clientBody:"Trên mỗi máy được giám sát, đăng nhập cùng tài khoản Google. Nếu manager chưa online, client tiếp tục thử mỗi 5 giây.",clientPoints:["npx -y livedesk client dùng slot trống đầu tiên.","npx -y livedesk client 3 ghim máy vào slot 3.","Client tiếp tục chờ để nhiều máy không cần đăng nhập lại."],syncTitle:"3. Sync Server và tự phát hiện",syncBody:"Sync Server đăng manager này là Screen Wall đang hoạt động của tài khoản. Client đọc Supabase và thử các endpoint.",syncPoints:["Bao gồm host instance, địa chỉ LAN/private, public candidate, pair token và lease ngắn.","Ưu tiên LAN trước, sau đó thử public nếu cần.","Bấm Sync Server sau thay đổi manager, VPN, firewall hoặc router.","Chrome Local Network Access trên 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 X11/XTEST. Audio chưa bật."],firewallTitle:"Firewall và địa điểm ngoài",firewallBody:"LiveDesk thử Direct TCP trước; nếu thất bại, control dùng rendezvous relay mã hóa và video dùng UDP P2P mã hóa khi khả dụng.",firewallPoints:["Port client mặc định cho Direct TCP trong LAN là 5197.","Client và manager cần kết nối outbound tới rendezvous server đã cấu hình.","Sau khi Direct TCP thất bại, relay control và UDP P2P video được thử tự động.","Chỉ forward TCP 5197 hoặc cấu hình VPN/IP allowlist khi cần Direct TCP giữa các mạng.","Chỉ mở 5179 khi browser từ xa cần mở Wall trực tiếp."],commandsTitle:"Lệnh hiện tại",commandsBody:"Hướng sản phẩm là một lệnh terminal dùng chung giữa các OS, thay vì tải và cài thủ công.",managerCommandLabel:"Khởi động manager",clientCommandLabel:"Kết nối Client",slotCommandLabel:"Ghim vào slot 3",manualCommandLabel:"Kết nối thủ công nâng cao"}),th:kr({languageName:"ไทย",languageLabel:"ภาษาของเอกสาร",eyebrow:"LiveDesk Manual",title:"เปิด Screen Wall ภายในด้วยคำสั่งเดียว",intro:"LiveDesk คือ deck แบบ npm-first สำหรับดู Client, mini PC, 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. เชื่อม Client",clientBody:"บนเครื่องที่ต้อง monitor ให้ login ด้วย Google account เดียวกัน ถ้า manager ยังไม่ออนไลน์ client จะลองใหม่ทุก 5 วินาที",clientPoints:["npx -y livedesk client จะใช้ slot ว่างแรก","npx -y livedesk client 3 จะตรึงเครื่องไว้ที่ slot 3","Client จะรอต่อเนื่องเพื่อไม่ต้อง login ซ้ำเมื่อมีหลายเครื่อง"],syncTitle:"3. Sync Server และ discovery",syncBody:"Sync Server จะ publish manager นี้เป็น active Screen Wall ของ account แล้ว client อ่านข้อมูลจาก Supabase และลอง endpoint ต่างๆ",syncPoints:["มี host instance, LAN/private address, public candidate, pair token และ short lease","ลอง LAN ก่อน แล้วค่อยลอง public ถ้าจำเป็น","กด Sync Server หลังเปลี่ยน manager, VPN, firewall หรือ router","Chrome Local Network Access บน 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 และ X11/XTEST input แล้ว audio ยังปิดอยู่"],firewallTitle:"Firewall และเครื่องต่างสถานที่",firewallBody:"LiveDesk จะลอง Direct TCP ก่อน หากล้มเหลว control จะใช้ rendezvous relay ที่เข้ารหัส และ video จะใช้ UDP P2P ที่เข้ารหัสเมื่อพร้อม",firewallPoints:["Port client เริ่มต้นสำหรับ Direct TCP ใน LAN คือ 5197","Client และ manager ต้องเชื่อมต่อ outbound ไปยัง rendezvous server ที่ตั้งค่าไว้ได้","หลัง Direct TCP ล้มเหลว ระบบจะลอง relay control และ UDP P2P video อัตโนมัติ","Forward TCP 5197 หรือตั้ง VPN/IP allowlist เฉพาะเมื่อต้องการ Direct TCP ข้าม network","เปิด 5179 เฉพาะเมื่อ browser ระยะไกลต้องเปิด Wall โดยตรง"],commandsTitle:"คำสั่งปัจจุบัน",commandsBody:"ทิศทาง product คือคำสั่ง terminal เดียวข้าม OS ไม่ใช่ download/install จากเว็บไซต์",managerCommandLabel:"เริ่ม manager",clientCommandLabel:"เชื่อม Client",slotCommandLabel:"ตรึง slot 3",manualCommandLabel:"manual connection ขั้นสูง"}),hi:kr({languageName:"हिन्दी",languageLabel:"दस्तावेज़ भाषा",eyebrow:"LiveDesk Manual",title:"एक कमांड से local Screen Wall खोलें",intro:"LiveDesk एक npm-first remote work deck है जिससे एक manager PC से कई Client, mini PC, 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. Client जोड़ें",clientBody:"हर monitored computer पर उसी Google account से sign in करें। Manager online न हो तब भी client बंद नहीं होता और हर 5 सेकंड retry करता है।",clientPoints:["npx -y livedesk client पहला खाली slot लेता है।","npx -y livedesk client 3 machine को slot 3 पर pin करता है।","बहुत सी machines हों तब भी बार-बार login की जरूरत नहीं रहती।"],syncTitle:"3. Sync Server और discovery",syncBody:"Sync Server इस manager को account का active Screen Wall बनाकर Supabase में publish करता है। Clients record पढ़कर endpoints try करते हैं।",syncPoints:["इसमें host instance, LAN/private addresses, public candidates, pair token और short lease होता है।","LAN candidates पहले try होते हैं, जरूरत हो तो public candidates।","Manager, VPN, firewall या router बदलने के बाद Sync Server दबाएं।","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, X11/XTEST input और PipeWire/PulseAudio output audio capture उपलब्ध हैं।"],firewallTitle:"Firewall और remote locations",firewallBody:"LiveDesk पहले Direct TCP आज़माता है; विफल होने पर control encrypted rendezvous relay उपयोग करता है और उपलब्ध होने पर video encrypted UDP P2P उपयोग करता है।",firewallPoints:["LAN Direct TCP का default client port 5197 है।","Clients और manager को configured rendezvous server तक outbound access चाहिए।","Direct TCP विफल होने के बाद relay control और UDP P2P video अपने आप try होते हैं।","TCP 5197 forward या VPN/IP allowlist तभी सेट करें जब networks के बीच Direct TCP चाहिए।","5179 तभी expose करें जब remote browser को Wall सीधे खोलना हो।"],commandsTitle:"Current commands",commandsBody:"Product direction है OS के बीच एक terminal command, website से download/install नहीं।",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),ar:kr({languageName:"العربية",languageLabel:"لغة المستند",eyebrow:"LiveDesk Manual",title:"افتح Screen Wall محلي بأمر واحد",intro:"LiveDesk هو deck بنمط npm-first لمراقبة عدة Clients وأجهزة mini PC و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. وصل Client",clientBody:"على كل كمبيوتر تتم مراقبته، سجل الدخول بنفس حساب Google. إذا لم يكن manager متاحا، يبقى client يعمل ويحاول كل 5 ثوان.",clientPoints:["npx -y livedesk client يختار أول slot فارغ.","npx -y livedesk client 3 يثبت الجهاز في slot 3.","clients تستمر بالمحاولة لتجنب تكرار تسجيل الدخول عند كثرة الأجهزة."],syncTitle:"3. Sync Server والاكتشاف",syncBody:"Sync Server ينشر هذا manager كـ active Screen Wall للحساب. يقرأ clients سجل Supabase ويجربون endpoints بالترتيب.",syncPoints:["السجل يتضمن host instance وعناوين LAN/private وpublic candidates وpair token وlease قصير.","يتم تفضيل LAN أولا، ثم public عند الحاجة.","اضغط Sync Server بعد تغيير manager أو VPN أو firewall أو router.","Chrome Local Network Access على 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 وX11/XTEST input. الصوت ما زال معطلا."],firewallTitle:"Firewall والمواقع البعيدة",firewallBody:"يجرب LiveDesk اتصال Direct TCP أولا؛ وإذا فشل يستخدم التحكم rendezvous relay المشفر ويستخدم الفيديو UDP P2P المشفر عند توفره.",firewallPoints:["منفذ client الافتراضي لاتصال Direct TCP داخل LAN هو 5197.","يحتاج client وmanager إلى اتصال outbound بخادم rendezvous المهيأ.","بعد فشل Direct TCP تتم محاولة relay control وUDP P2P video تلقائيا.","وجه TCP 5197 أو اضبط VPN/IP allowlist فقط عند الحاجة إلى Direct TCP بين الشبكات.","اكشف 5179 فقط إذا كان browser بعيد يحتاج فتح Wall مباشرة."],commandsTitle:"الأوامر الحالية",commandsBody:"اتجاه المنتج هو أمر terminal واحد عبر الأنظمة، وليس تحميل وتثبيت يدوي من موقع.",managerCommandLabel:"Start manager",clientCommandLabel:"Connect Client",slotCommandLabel:"Pin to slot 3",manualCommandLabel:"Advanced manual connection"}),tr:kr({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 Client, mini PC, Mac mini ve dev machine izlemek için npm-first bir çalışma deckidir.",managerTitle:"1. Manager çalıştır",managerBody:"Ekranları izleyecek bilgisayarda 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. Client bağla",clientBody:"İzlenecek bilgisayarda aynı Google hesabıyla giriş yap. Manager henüz online değilse client kapanmaz ve her 5 saniyede tekrar dener.",clientPoints:["npx -y livedesk client ilk boş slota yerleşir.","npx -y livedesk client 3 makineyi slot 3’e sabitler.","Çok makinede tekrar tekrar login gerekmesin diye client beklemeye devam eder."],syncTitle:"3. Sync Server ve discovery",syncBody:"Sync Server bu managerı hesabın active Screen Wall kaydı olarak Supabase’e yazar. Clients bu kaydı okuyup endpoint adaylarını dener.",syncPoints:["Host instance, LAN/private adresler, public adaylar, pair token ve kısa lease içerir.","Önce LAN adayları, gerekirse public adaylar denenir.","Manager, VPN, firewall veya router değişince Sync Server’a bas.","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 X11/XTEST input backend eklendi. Audio kapalı."],firewallTitle:"Firewall ve uzak konumlar",firewallBody:"LiveDesk önce Direct TCP dener; başarısız olursa kontrol şifreli rendezvous relay kullanır ve video mümkün olduğunda şifreli UDP P2P kullanır.",firewallPoints:["LAN Direct TCP için varsayılan client portu 5197dir.","Client ve manager yapılandırılmış rendezvous servera outbound erişebilmelidir.","Direct TCP başarısız olduktan sonra relay control ve UDP P2P video otomatik denenir.","Ağlar arasında Direct TCP gerekiyorsa TCP 5197 forward et veya VPN/IP allowlist yapılandır.","5179u yalnız uzak browser Wallu doğrudan açacaksa expose et."],commandsTitle:"Güncel komutlar",commandsBody:"Ürün yönü, webden indirip kurmak yerine işletim sistemleri arasında ortak tek terminal komutu.",managerCommandLabel:"Manager başlat",clientCommandLabel:"Client bağla",slotCommandLabel:"Slot 3’e sabitle",manualCommandLabel:"Gelişmiş manuel bağlantı"})},bL=Object.entries(jd).map(([t,n])=>({id:t,label:n.languageName}));function wL(){if(typeof navigator>"u")return"en";const t=navigator.languages?.length?navigator.languages:[navigator.language];for(const n of t){const r=n.toLowerCase();if(jd[n])return n;if(r.startsWith("zh-tw")||r.startsWith("zh-hk"))return"zh-TW";if(r.startsWith("pt"))return"pt-BR";const o=r.split("-")[0];if(jd[o])return o}return"en"}function zx({index:t}){const n=t+1;return i.jsx("article",{className:"device-tile placeholder-tile","aria-label":`Empty slot ${n}`,children:i.jsxs("div",{className:"tile-screen","aria-hidden":"true",children:[i.jsx("span",{className:"slot-grid","aria-hidden":"true"}),i.jsxs("span",{className:"empty-screen",children:[i.jsx(Ar,{size:24}),i.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}const xL=["cpu","gpu","memory","vram","network","disk","temp"];function SL({device:t,slotNumber:n,selected:r,updateIndicator:o,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=oC(t),y=new Map(g.metrics.map(b=>[b.id,b])),w=o?.label||g.label;return i.jsxs("div",{className:`wall-device-list-row state-${g.state} ${r?"selected":""}`,role:"row","aria-selected":r,tabIndex:0,onClick:f,onDoubleClick:b=>{b.preventDefault(),h()},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),f())},children:[i.jsxs("span",{className:"wall-device-name",role:"gridcell",children:[i.jsx("span",{className:"wall-device-icon","aria-hidden":"true",children:i.jsx(Ar,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:Pa(t)}),i.jsxs("small",{children:["Slot ",String(n).padStart(3,"0"),t.platform?` · ${t.platform}`:"",t.arch?` · ${t.arch}`:""]})]}),r&&i.jsx(al,{size:16,strokeWidth:3,"aria-label":"Selected"})]}),i.jsxs("span",{className:`wall-device-list-status state-${g.state} ${o?`update-${o.state}`:""}`,role:"gridcell",title:o?.error||w,children:[i.jsx("i",{"aria-hidden":"true"}),i.jsx("strong",{children:w})]}),xL.map(b=>{const S=y.get(b);return i.jsxs("span",{className:`wall-device-list-metric state-${S?.state||"unknown"}`,role:"gridcell",title:S?`${S.label}: ${S.value} · ${S.detail}`:"Not reported",children:[i.jsx("strong",{children:S?.value||"-"}),i.jsx("small",{children:S?.detail||"not reported"}),S?.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(S.ratio*100)}%`},"aria-hidden":"true"})]},b)}),l&&i.jsx("span",{className:"wall-device-list-diagnostics",role:"gridcell",children:i.jsx(HS,{items:l,mode:u})})]})}function CL(t){if(!t)return!1;const n=String(t.platform||"").trim().toLowerCase();return tl(n)&&t.capabilities?.screenRecordingPermission===!1}function tl(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"}function kL(t){const n=String(t||"").trim().toLowerCase();return n==="linux"||n.startsWith("linux ")}function Wg({device:t,frame:n,selected:r,controlEnabled:o,showStatus:l,showDeviceTitle:u=!0,monitorIndex:f,monitorCount:h,onSelect:g,onFocusDevice:y,onOpenControl:w,onCycleMonitor:b,onCanvasReady:S,sendInput:k,remoteModifierState:N,updateIndicator:A,presentationReady:j,showPresentationSpinner:I=!1,remoteDiagnostics:T,diagnosticsMode:_="remote"}){const B=d.useRef(null),F=d.useRef(null),H=d.useRef(0),D=d.useRef(null),K=oC(t),z=["cpu","gpu","memory","vram"].map(ue=>K.metrics.find(_e=>_e.id===ue)).filter(ue=>!!ue),W=Fv(f),q=h>1,V=j??!!n,X=CL(t)&&!V,ve=I&&t.connected&&!V&&!X,J=XI(t,n,W),$=J>=Tp?100:J/Tp*100,P=J>=Tp?Tp/J*100:100,se={"--screen-aspect":J.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,$)).toFixed(3)}%`,"--screen-content-height":`${Math.max(1,Math.min(100,P)).toFixed(3)}%`},we=d.useCallback(ue=>{B.current=ue,S(t.deviceId,ue)},[t.deviceId,S]),Z=ue=>{const _e=ue.currentTarget.getBoundingClientRect();return pN(ue.clientX,ue.clientY,_e)},Se=ue=>vN(ue,N),ae=d.useCallback(()=>{D.current!==null&&(window.cancelAnimationFrame(D.current),D.current=null)},[]),ye=d.useCallback(()=>{const ue=F.current;if(!ue)return;F.current=null;const _e=Number(ue.input.normalizedX),Ze=Number(ue.input.normalizedY);if(!Number.isFinite(_e)||!Number.isFinite(Ze))return;k(t.deviceId,{...ue.input,normalizedX:_e,normalizedY:Ze})&&(H.current=performance.now())},[t.deviceId,k]),Pe=d.useCallback(()=>{D.current===null&&(D.current=window.requestAnimationFrame(()=>{D.current=null,ye()}))},[ye]);d.useEffect(()=>()=>{ae(),F.current=null},[ae]);const de=(ue,_e)=>{if(!o)return;const Ze={type:_e,monitorIndex:W,...Z(ue),button:uL(ue.button),...Se(ue)};if(_e==="pointermove"){const at=performance.now();F.current={input:Ze},at-H.current>=hI&&(ae(),ye()),Pe();return}F.current&&(ae(),ye()),k(t.deviceId,Ze)},Qe=d.useCallback(ue=>{const _e=document.activeElement;_e instanceof HTMLElement&&ue.contains(_e)&&_e.classList.contains("monitor-cycle-button")&&_e.blur()},[]);return i.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:se,children:i.jsxs("div",{className:`tile-screen ${V?"has-frame":"is-empty"}`,role:"button",tabIndex:o?-1:0,"aria-pressed":r,onClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||g()},onKeyDown:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||o||(ue.key==="Enter"||ue.key===" ")&&(ue.preventDefault(),g())},onDoubleClick:ue=>{ue.target instanceof Element&&ue.target.closest(".monitor-cycle")||(ue.preventDefault(),w())},onPointerLeave:ue=>Qe(ue.currentTarget),children:[i.jsx("span",{className:`screen-content ${V?"has-frame":"is-empty"}`,children:i.jsx("canvas",{ref:we,className:`remote-canvas ${V?"has-frame":"is-empty"}`,"data-monitor-index":W,tabIndex:o?0:-1,onPointerDown:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),y(),ue.currentTarget.focus(),ue.currentTarget.setPointerCapture(ue.pointerId),de(ue,"pointerdown"))},onPointerMove:ue=>{o&&ue.preventDefault(),de(ue,"pointermove")},onPointerLeave:ue=>{o&&(de(ue,"pointermove"),ae(),ye())},onPointerUp:ue=>{o&&(ue.preventDefault(),ue.stopPropagation(),de(ue,"pointerup"),ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId))},onPointerCancel:ue=>{ue.currentTarget.hasPointerCapture(ue.pointerId)&&ue.currentTarget.releasePointerCapture(ue.pointerId)},onWheel:ue=>{o&&(ue.preventDefault(),k(t.deviceId,{type:"wheel",monitorIndex:W,...Z(ue),deltaX:ue.deltaX,deltaY:ue.deltaY,...Se(ue)}))},onContextMenu:ue=>o&&ue.preventDefault()},`${t.deviceId}:monitor:${W}`)}),!V&&i.jsx("span",{className:"empty-screen",children:i.jsx(Ar,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:Pa(t),children:Pa(t)}),ve&&i.jsxs("span",{className:"wall-presentation-loading",role:"status","aria-live":"polite",children:[i.jsx("span",{className:"wall-presentation-spinner","aria-hidden":"true"}),i.jsx("strong",{children:"Preparing video"})]}),X&&i.jsxs("span",{className:"wall-presentation-loading permission-required",role:"status","aria-live":"polite",children:[i.jsx(ga,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"Screen Recording permission required"}),i.jsx("small",{children:"Allow the terminal app on this Mac, then restart LiveDesk."})]}),A&&i.jsxs("span",{className:`wall-update-status state-${A.state}`,role:"status","aria-live":"polite",title:A.error||A.label,children:[A.state==="updated"?i.jsx(_a,{size:20,"aria-hidden":"true"}):A.state==="failed"?i.jsx(rr,{size:22,"aria-hidden":"true"}):A.state==="offline"?i.jsx(eh,{size:22,"aria-hidden":"true"}):i.jsx("span",{className:"wall-update-spinner","aria-hidden":"true"}),i.jsx("strong",{children:A.label}),A.error?i.jsx("small",{children:A.error}):null]}),l&&i.jsxs(i.Fragment,{children:[i.jsx("span",{className:`tile-health-pill state-${K.state}`,children:K.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${Pa(t)} status`,children:z.map(ue=>i.jsxs("span",{className:`tile-metric state-${ue.state}`,children:[i.jsx("b",{children:ue.label}),i.jsx("em",{children:ue.value}),ue.ratio!==void 0&&i.jsx("i",{style:{width:`${Math.round(ue.ratio*100)}%`}})]},ue.id))})]}),T&&i.jsx(HS,{items:T,mode:_}),q&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${Pa(t)} display ${W+1} of ${h}`,onPointerDown:ue=>ue.stopPropagation(),onClick:ue=>ue.stopPropagation(),onDoubleClick:ue=>ue.stopPropagation(),children:[i.jsx("button",{className:"monitor-cycle-button previous",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),b(-1),ue.currentTarget.blur()},title:"Previous display",type:"button",children:i.jsx(n0,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",W+1,"/",h]}),i.jsx("button",{className:"monitor-cycle-button next",onClick:ue=>{ue.preventDefault(),ue.stopPropagation(),b(1),ue.currentTarget.blur()},title:"Next display",type:"button",children:i.jsx(Mv,{size:18})})]})]})})}function ML({visible:t}){const n=mI;return d.useEffect(()=>{},[n]),null}function AL({runtimeBaseUrl:t=""}){const{session:n,loading:r}=V1();zM(n?{accessToken:n.access_token,refreshToken:n.refresh_token,expiresAt:n.expires_at,user:{id:n.user.id,email:n.user.email}}:null);const{target:o,error:l,refresh:u}=Q1(n),f=d.useMemo(()=>{if(!o?.active)return null;const m=o.expires_at?Date.parse(o.expires_at):Number.POSITIVE_INFINITY;return Number.isFinite(m)&&m<=Date.now()?null:o},[o]),h=d.useMemo(()=>Ob(f),[f]),g=Av(),y=t.trim().replace(/\/+$/,""),w=d.useMemo(()=>[...new Set((g?h:[y,...h,Un]).filter(Boolean))],[g,h,y]),[b,S]=d.useState(null),[k]=d.useState(rI),[N,A]=d.useState(!1),[j,I]=d.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches),[T,_]=d.useState(()=>typeof window<"u"&&vw(window.matchMedia(gw).matches,j,window.matchMedia("(pointer: coarse)").matches));d.useEffect(()=>{if(!g){S(null);return}const m=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),x=()=>I(m.matches||!!window.navigator.standalone),C=E=>{E.preventDefault(),S(E)},R=()=>{S(null),I(!0)};return x(),m.addEventListener("change",x),window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",R),()=>{m.removeEventListener("change",x),window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",R)}},[g]);const B=d.useCallback(async()=>{const m=b;if(!m){k.isIos&&A(!0);return}S(null);try{await m.prompt(),(await m.userChoice).outcome==="accepted"&&I(!0)}catch(x){S(m),console.warn("[LiveDesk] PWA install prompt failed.",x)}},[k.isIos,b]);d.useEffect(()=>{const m=window.matchMedia(gw),x=window.matchMedia("(pointer: coarse)"),C=()=>_(vw(m.matches,j,x.matches));return C(),m.addEventListener("change",C),x.addEventListener("change",C),()=>{m.removeEventListener("change",C),x.removeEventListener("change",C)}},[j]),d.useEffect(()=>{const m=document.documentElement,x=()=>{m.classList.remove("livedesk-mobile-console-active"),m.style.removeProperty("--livedesk-mobile-viewport-height"),m.style.removeProperty("--livedesk-mobile-viewport-top"),m.style.removeProperty("--livedesk-mobile-viewport-width"),m.style.removeProperty("--livedesk-mobile-viewport-left")};if(!T){x();return}m.classList.add("livedesk-mobile-console-active");const C=window.visualViewport;let R=0;const E=()=>{R=0;const Y=IN(C,Math.max(window.innerHeight,document.documentElement.clientHeight),window.innerWidth,j||k.isIos,j||k.isIos||k.isAndroid);m.style.setProperty("--livedesk-mobile-viewport-height",`${Y.height}px`),m.style.setProperty("--livedesk-mobile-viewport-top",`${Y.offsetTop}px`),m.style.setProperty("--livedesk-mobile-viewport-width",`${Y.width}px`),m.style.setProperty("--livedesk-mobile-viewport-left",`${Y.offsetLeft}px`)},G=()=>{R||(R=window.requestAnimationFrame(E))};return E(),C?.addEventListener("resize",G),C?.addEventListener("scroll",G),window.addEventListener("resize",G),window.addEventListener("orientationchange",G),window.addEventListener("pageshow",G),()=>{R&&window.cancelAnimationFrame(R),C?.removeEventListener("resize",G),C?.removeEventListener("scroll",G),window.removeEventListener("resize",G),window.removeEventListener("orientationchange",G),window.removeEventListener("pageshow",G),x()}},[k.isAndroid,k.isIos,T,j]);const[F,H]=d.useState(VI),D=d.useMemo(()=>w.some(m=>!!Yf(m)),[w]),K=g?!!n:!D||F,{status:z,devices:W,error:q,refresh:V,hubBaseUrl:X}=K1(w,K,n?.access_token||""),{entitlement:ve,licensed:J,loading:$,error:P,refresh:se}=Y1(n),[we,Z]=d.useState([]),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(""),[de,Qe]=d.useState(""),[ue,_e]=d.useState(""),[Ze,at]=d.useState(""),[Ee,Ge]=d.useState("idle"),[me,ke]=d.useState(!1),[et,Me]=d.useState(""),[pe,qe]=d.useState(null),Re=d.useRef(null),[st,jt]=d.useState(""),O=d.useRef("");O.current=ue;const[ze,We]=d.useState(!1),[Et,lt]=d.useState([]),ht=d.useRef(null),[Je,be]=d.useState(!1),je=d.useRef(""),Ae=d.useRef(new Map),fe=d.useRef(0),te=d.useRef(!1),ce=d.useRef(""),Ne=d.useRef(null);Ne.current||(Ne.current=PN());const He=d.useRef(document.visibilityState==="visible"),[Ie,Lt]=d.useState({}),Xe=d.useRef({}),ut=d.useRef(new Set),yt=d.useRef(new Map),_t=d.useRef(new Map),[mt,Vt]=d.useState({}),St=d.useMemo(()=>new Set(Object.keys(Ie)),[Ie]),pn=d.useCallback((m,x)=>{if(!m)return;const C={...Xe.current};x?C[m]=x:delete C[m],Xe.current=C,Lt(C)},[]),rn=d.useCallback((m,x)=>{m&&Vt(C=>{if(!!C[m]===x)return C;const R={...C};return x?R[m]=!0:delete R[m],R})},[]),ya=d.useCallback((m,x)=>{m&&_t.current.set(m,{paused:x,expiresAt:Date.now()+AI})},[]),[Ct,gn]=d.useState(""),[en,U]=d.useState(""),[nt,Dt]=d.useState(!1),vn=d.useRef(null),Nr=d.useRef(null);d.useEffect(()=>{Ct==="auth"&&n?.access_token&&gn("")},[Ct,n?.access_token]);const[Ur,Tr]=d.useState(""),[oe,$e]=d.useState(null),tt=d.useRef(null),Pt=d.useRef(0),wn=d.useCallback((m,x,C)=>{const R=String(m||"").trim();if(Tr(R),tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),!R){$e(null);return}const E=++Pt.current;if($e({id:E,message:R,tone:x}),!C)return;const G=window.setTimeout(()=>{$e(Y=>Y?.id===E?null:Y),tt.current===G&&(tt.current=null)},5e3);tt.current=G},[]),Oe=d.useCallback((m,x="info")=>{wn(m,x,!0)},[wn]),it=d.useCallback(m=>{wn(m,"progress",!1)},[wn]);d.useEffect(()=>()=>{tt.current!==null&&window.clearTimeout(tt.current)},[]);const[Nt,bt]=d.useState(()=>typeof window<"u"&&window.location.pathname.startsWith("/support")?"support":"wall");d.useEffect(()=>{const m=()=>{bt(window.location.pathname.startsWith("/support")?"support":x=>x==="support"?"wall":x)};return window.addEventListener("popstate",m),()=>window.removeEventListener("popstate",m)},[]);const[Gt,ra]=d.useState("large"),[Cn,qn]=d.useState(rL),Qt=pv(Cn),[En,qr]=d.useState(!1),[Ht,Pn]=d.useState(!1),[Ha,sr]=d.useState(!1),[Rr,ir]=d.useState(!1),[Zs,Ds]=d.useState(Date.now),Dn=d.useRef(null);d.useEffect(()=>()=>{Dn.current!==null&&window.clearTimeout(Dn.current)},[]);const[ln,il]=d.useState(wL),[Is,go]=d.useState(!1),[Ai,or]=d.useState(!1),[Pd,za]=d.useState(!1),[Wr,ol]=d.useState(GI),[wt]=d.useState(eL),[_n]=d.useState(nL),[vo]=d.useState(ZI),[sn,us]=d.useState(vo.selections),oc=d.useRef({...vo.topologyFingerprints}),Js=d.useRef({}),ll=d.useRef({...vo.selections}),[Bt,jr]=d.useState(null),[yo,ei]=d.useState({}),lr=d.useRef(new Set),[Ni,ti]=d.useState([]),[Hn,cr]=d.useState(Qt),[ni,cl]=d.useState(""),[lc,bo]=d.useState(0),[Gr,Vr]=d.useState(0),[wo,Ls]=d.useState(0),[xo,$a]=d.useState(()=>new Set),cn=d.useRef(new Map),Zn=d.useRef(new Map),Ua=d.useRef(new Map),kn=d.useRef(new Map),Fn=d.useRef(null),qa=d.useRef(new Map),ur=d.useRef(new Set),Wa=d.useRef(new Map),ai=d.useRef(new Map),Aa=d.useRef(new Map),Kr=d.useRef(new Map),Ti=d.useRef(new WeakMap),So=d.useRef(new WeakMap),Ri=d.useRef(""),dr=d.useRef(null),um=d.useRef(Promise.resolve()),uu=d.useRef(0),ji=d.useRef(null),Er=d.useRef(null),cc=d.useRef(""),Na=d.useRef(new Map),ul=d.useRef(null),uc=d.useRef(0),Ps=d.useRef(new Map),du=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),fu=d.useRef(new Map),_d=d.useRef([]),dm=d.useRef(0),[dl,Fd]=d.useState({}),Ei=d.useRef(new Map),[mu,dc]=d.useState({}),pu=d.useRef(null),[Od,Ga]=d.useState(!1),hu=d.useRef(null),hh=d.useRef(0),ri=d.useRef(null),fm=d.useRef(new Map),ds=d.useRef(null),Qr=d.useRef(null),Va=d.useRef(null),si=d.useRef(!1),mm=d.useRef(0),Wn=d.useRef(0),ba=d.useRef(""),Bd=d.useRef(Promise.resolve()),Co=d.useRef(""),At=d.useRef(null),wa=d.useRef(""),ko=d.useRef(null),fl=d.useRef(0),fc=d.useRef(""),ii=d.useRef(new Map),Di=d.useRef(new Map),Ii=d.useRef(performance.now()),_s=d.useRef(new Map),Fs=d.useRef(new Map),Os=d.useRef(new Map),Li=d.useRef(new Map),Mo=d.useRef(new Map),oi=d.useRef(new Map),Dr=d.useRef(document.visibilityState==="visible"),fs=d.useRef(1),gu=d.useRef([]),[Ta,gh]=d.useState(document.visibilityState==="visible"),[ml,vh]=d.useState(0),mc=d.useRef(0),vu=d.useRef(0),Ra=d.useRef(0),Pi=d.useRef(0),yu=d.useRef(0),bu=d.useRef(new Map),pl=d.useRef([]),Hd=d.useRef(new Map),wu=d.useRef(new Map),li=d.useRef(new Map),ci=d.useRef(new Set),_i=d.useCallback(m=>s1(Ti.current,m),[]),Bs=d.useCallback(m=>Dv(So.current,m),[]),ui=d.useCallback((m,x)=>Zb(So.current,m,x),[]),Jn=d.useCallback(m=>{const x=Xb(Ti.current,m);return Xb(So.current,m),x},[]),Yr=d.useCallback((m,x)=>Zb(Ti.current,m,x),[]),Ao=d.useCallback(m=>Er.current===m||Fn.current===m?!0:[cn.current,Zn.current,Ua.current,kn.current,Na.current].some(C=>Array.from(C.values()).some(R=>R===m)),[]),xa=d.useCallback(m=>{m&&(Jn(m),ci.current.add(m),l1(m,{isCurrent:Ao,dispose:bd,schedule:x=>queueMicrotask(()=>{try{x()}finally{ci.current.delete(m)}})}))},[Ao,Jn]),ja=d.useCallback(m=>(Jn(m),lh(m,bd)),[Jn]),Fi=d.useCallback(()=>{const m=Er.current,x=Fn.current,C=[...ci.current];Er.current=null,Fn.current=null,ci.current.clear(),Ti.current=new WeakMap,So.current=new WeakMap,Kr.current.clear(),cc.current="",o1([cn.current,Zn.current,Ua.current,kn.current,Na.current],[m,x,...C],bd),ul.current=null,uc.current=0,qa.current.clear(),ur.current.clear(),Wa.current.clear(),ai.current.clear(),Aa.current.clear(),Ps.current.clear(),fu.current.clear(),_d.current.length=0,Ei.current.clear(),ut.current.clear()},[]);d.useEffect(()=>()=>{Fi()},[Fi]);const ua=d.useCallback((m,x)=>{const C=la(m,x),R=performance.now();ii.current.delete(C),Di.current.delete(C),_s.current.delete(C),Fs.current.delete(C),oi.current.delete(C),li.current.delete(C),Ei.current.delete(C),Ps.current.delete(C),dc(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const G={...E};return delete G[C],G}),Fd(E=>{if(!Object.prototype.hasOwnProperty.call(E,C))return E;const G={...E};return delete G[C],G}),m==="control"?(Os.current.delete(C),Li.current.set(C,R)):Mo.current.set(C,R)},[]),[Oi,di]=d.useState(null),[yh,zd]=d.useState(!1),[ty,pm]=d.useState([]),[No,$d]=d.useState("all"),[Ea,hl]=d.useState([]),[ms,pc]=d.useState(!1),[hm,xu]=d.useState(!0),hc=d.useRef(null),Su=d.useRef(null),To=d.useRef(null),gm=d.useRef(null),Cu=d.useRef(!1),Bi=d.useRef(!1),ku=d.useRef(0),Gn=d.useRef(0),ps=d.useRef(0),da=d.useRef(0),gc=d.useRef(0),Ro=d.useRef(""),hs=Nt==="settings",Mu=Nt==="pricing",Ud=Nt==="doc",Au=Nt==="support",Hi=Nt==="share-files",Ka=Nt==="agents",gs=!hs&&!Mu&&!Ud&&!Au&&!Hi&&!Ka,dt=Nt==="control",vc=ON(Nt),Qa=Ta&&Nt==="wall",Ir=d.useRef(Qa);Ir.current=Qa;const Xr=vc&&pl.current.length>0,fr=Ta&&(Nt==="wall"||dt||Xr),Ya=d.useRef(fr);Ya.current=fr;const Lr=Ta&&(dt||Qa),jo=Ta&&(Lr||vc&&(Ee==="connecting"||Ee==="active")),yc=d.useRef({active:fr,epoch:fs.current});yc.current.active!==fr&&(fs.current+=1,yc.current={active:fr,epoch:fs.current}),d.useEffect(()=>{gs||(qr(!1),Pn(!1),sr(!1))},[gs]);const Kt=wt.frameMode==="mode4-h264-atlas",Pr=Ze||_n.frameMode,Vn=Pr!=="mode3-h264-hw"?Math.min(30,_n.fps):_n.fps,un=W.find(m=>m.deviceId===ye),Yt=un?.platform,$i=un?js(un,sn[un.deviceId]):0,Xa=un?ey(un,$i):null,Nu=kL(Yt)?{maxWidth:1280,maxHeight:720}:Ax,fi=Pr!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Ax,bc={maxWidth:Math.min(fi.maxWidth,Nu.maxWidth,_n.maxWidth),maxHeight:Math.min(fi.maxHeight,Nu.maxHeight,_n.maxHeight)},vs={maxWidth:Xa?.width?Math.min(bc.maxWidth,Xa.width):bc.maxWidth,maxHeight:Xa?.height?Math.min(bc.maxHeight,Xa.height):bc.maxHeight};d.useEffect(()=>{if(z?.started){if(!n?.access_token){rt("/api/remote/license",{method:"DELETE"},X).catch(()=>{});return}rt("/api/remote/license/sync",{method:"POST",headers:{Authorization:`Bearer ${n.access_token}`}},X).catch(m=>{console.warn("[LiveDesk] Hub license sync failed",m)})}},[ve?.updated_at,X,n?.access_token,z?.started]),d.useEffect(()=>{!n?.access_token||!z?.started||z.runtimeRole!=="hub"||!z.deviceId||(async()=>{try{const{data:m,error:x}=await $t.rpc("register_livedesk_device",{p_device_id:z.deviceId,p_device_name:z.deviceName||z.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:z.managerVersion||z.managerPackage||""}),C=Array.isArray(m)?m[0]:m;(x||C?.ok===!1)&&console.warn("[LiveDesk] Hub device role registration failed",x||C?.reason||"unknown-error")}catch(m){console.warn("[LiveDesk] Hub device role registration failed",m)}})()},[n?.access_token,z?.deviceId,z?.deviceName,z?.managerPackage,z?.managerVersion,z?.runtimeRole,z?.started]);const pt=d.useMemo(()=>W.filter(m=>m.connected),[W]);d.useEffect(()=>{const m={...Xe.current},x=Date.now();let C=!1;Vt(R=>{const E={...R};let G=!1;for(const Y of W){const ee=String(Y.liveCapturePause?.token||"").trim(),ie=_t.current.get(Y.deviceId);if(ie)if((ie.paused?!!ee:!ee)||ie.expiresAt<=x)_t.current.delete(Y.deviceId);else continue;const re=!!ee&&(Y.liveCapturePause?.captureStopConfirmed!==!0||Y.liveCapturePause?.phase==="stop-unconfirmed");!!E[Y.deviceId]!==re&&(G=!0,re?E[Y.deviceId]=!0:delete E[Y.deviceId])}return G?E:R});for(const R of W){const E=String(R.liveCapturePause?.token||"").trim(),G=String(m[R.deviceId]||""),Y=_t.current.get(R.deviceId);if(Y)if((Y.paused?!!E:!E)||Y.expiresAt<=x)_t.current.delete(R.deviceId);else continue;E&&E!==G?(m[R.deviceId]=E,C=!0):!E&&G&&(delete m[R.deviceId],yt.current.delete(R.deviceId),C=!0)}C&&(Xe.current=m,Lt(m))},[W]);const Ui=No==="all"?pt.length:Ea.filter(m=>pt.some(x=>x.deviceId===m)).length,qd=d.useMemo(()=>pt.reduce((m,x)=>Math.max(m,Hx(x.slotNumber)),0),[pt]),Eo=Math.max(sI,pt.length,qd),mi=d.useMemo(()=>{const m=Array(Eo).fill(null),x=[];for(const C of pt){const R=Hx(C.slotNumber);R>0&&R<=Eo&&!m[R-1]?m[R-1]=C:x.push(C)}for(const C of x){const R=m.findIndex(E=>!E);R<0?m.push(C):m[R]=C}return m},[pt]),qi=d.useMemo(()=>mi.flatMap((m,x)=>m?[{device:m,slotNumber:x+1}]:[]),[mi]),Zr=d.useMemo(()=>pt.map(m=>m.deviceId),[pt]),mr=d.useMemo(()=>new Set(we),[we]),In=d.useMemo(()=>pt.filter(m=>mr.has(m.deviceId)),[pt,mr]),Wi=d.useMemo(()=>W.find(m=>m.deviceId===Se)||In[0]||null,[W,Se,In]),Sa=d.useMemo(()=>W.find(m=>m.deviceId===ye)||null,[ye,W]),Da=Sa?js(Sa,sn[Sa.deviceId]):0,De=dt?Sa:Wi,Gi=d.useMemo(()=>new Set(Ea),[Ea]),Ca=d.useMemo(()=>No==="all"?pt.map(m=>m.deviceId):pt.filter(m=>Gi.has(m.deviceId)).map(m=>m.deviceId),[pt,Gi,No]),Tu=De?Op(De,"control"):!1,Ru=tl(De?.platform)&&(De?.capabilities?.controlPermission===!1||De?.capabilities?.accessibilityPermission===!1),ys=De?Op(De,"audio")||Op(De,"remoteAudio"):!1,Do=(Array.isArray(De?.capabilities?.agentTools)?De.capabilities.agentTools.map(String):[]).includes("system.power"),Ut=J?ve?.plan==="pro"?"pro":"ltd":"free",ju=Xc[Ut],Io=ju.limit,pr=d.useMemo(()=>new Set($N(pt,Io)),[Io,pt]),Wd=!De||pr.has(De.deviceId),gl=Ut==="free",Xt=Wd,vl=Ut==="ltd"?`Plus includes up to ${Uf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${$f} Clients. Upgrade to Plus for ${Uf} devices and no ads.`,vm=Ut==="free",bs=Xt&&!!De&&Tu,Eu=Xt&&!!De&&ys,ws=d.useMemo(()=>dt?De?[De]:[]:In.length>0?In:De?[De]:[],[De,In,dt]),Ia=d.useMemo(()=>ws.filter(m=>pr.has(m.deviceId)),[pr,ws]),Lo=Ia.some(m=>String(Ie[m.deviceId]||"").startsWith("pending:")||mt[m.deviceId]===!0),hr=!(Ia.length>0&&Ia.every(m=>{const x=String(Ie[m.deviceId]||"");return!!x&&!x.startsWith("pending:")&&mt[m.deviceId]!==!0}))||Lo,yl=d.useMemo(()=>mi.filter(m=>!!m?.connected).slice(0,iL(Gt)).map(m=>m.deviceId),[mi,Gt]),Po=d.useMemo(()=>fr?Qa?Kt||Gt==="list"?Zr:wt.visibleOnlyLive?Ni.length>0?Ni:yl:Zr:pl.current.length>0?pl.current:Zr:[],[yl,Kt,Ni,wt.visibleOnlyLive,Zr,fr,Qa,Gt]),Za=d.useMemo(()=>zg(Po.filter(m=>pr.has(m))),[pr,Po]);pl.current=Za;const xs=d.useMemo(()=>Za.filter(m=>m!==ni&&!St.has(m)),[St,Za,ni]),wc=d.useMemo(()=>new Map(pt.map(m=>[m.deviceId,m.platform])),[pt]),Ss=d.useMemo(()=>Object.fromEntries(pt.map(m=>[m.deviceId,String(m.sessionId||"").trim()])),[pt]),La=UN(Kt,Za.length),Ja=d.useMemo(()=>Kt?xs.filter(m=>Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(wc.get(m))})==="atlas"):[],[La,Kt,wc,xs]),gr=d.useMemo(()=>xs.filter(m=>Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(wc.get(m))})==="direct"),[La,Kt,wc,xs]),_o=d.useMemo(()=>{const m=wt.autoStartLive?xs.map(x=>la("wall",x)):[];return jo&&Xt&&de&&pr.has(de)&&(Ee==="connecting"||Ee==="active"||Ee==="warm")&&m.push(la("control",de)),[...new Set(m)].sort()},[jo,de,Ee,Xt,pr,wt.autoStartLive,xs]);d.useEffect(()=>{const m=new Set(Za);$a(x=>{let C=!1;const R=new Set;for(const E of x)m.has(E)?R.add(E):C=!0;return C?R:x})},[Za]);const xc=d.useMemo(()=>{const m=E=>pt.find(G=>G.deviceId===E)||null,x=E=>{const G=m(E);return G?js(G,sn[E]):0},C=(E,G=x(E))=>E===de&&(Ee==="connecting"||Ee==="active"||Ee==="warm")?kn.current.get(E)||Zn.current.get(E)||null:Kt?Na.current.get(E)||cn.current.get(E)||null:cn.current.get(E)||null,R=(E,G=x(E))=>{const Y=m(E);return`${Y?Pa(Y):E} · Monitor ${G+1}`};return{resolveCurrentTarget(){if(dt&&Sa){const ie=Da;return{type:"control",deviceIds:[Sa.deviceId],monitorIndex:ie,label:`${Pa(Sa)} · Monitor ${ie+1}`,sourceCanvas:C(Sa.deviceId,ie),signature:`control:${Sa.deviceId}:${ie}:${_n.frameMode}`}}const E=In.map(ie=>ie.deviceId).filter(ie=>xs.includes(ie)),G=Wi&&xs.includes(Wi.deviceId)?Wi.deviceId:"",Y=E.length>0?E:G?[G]:xs,ee=E.length===0&&!G;if(Y.length===0)return null;if(Y.length===1){const ie=Y[0],re=x(ie);return{type:ee?"wall":E.length>1?"selection":"device",deviceIds:Y,monitorIndex:re,label:ee?"Wall":R(ie,re),sourceCanvas:ee?null:C(ie,re),signature:`${ee?"wall":"device"}:${ie}:${re}:${Kt?"atlas":"direct"}`}}return{type:E.length>1?"selection":"wall",deviceIds:Y,label:E.length>1?`${Y.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${E.length>1?"selection":"wall"}:${Y.join(",")}:${Gt}`}},getDeviceCanvas:C,composeWall(E,G={}){return GD(E.map(Y=>{const ee=x(Y);return{deviceId:Y,label:R(Y,ee),canvas:C(Y,ee)}}),G)}}},[pt,Sa,de,Ee,_n.frameMode,cn,Kt,sn,Da,In,dt,xs,Wi,Gt]),Sc=aI({hubUrl:X,sourceRegistry:xc,onToast:Oe}),Hs=d.useMemo(()=>BN({captureOwnershipActive:jo,localFeatureAccess:Xt,controlSessionDeviceId:de,planAllowed:pr.has(de),sessionState:Ee,controlFocusVisible:dt,presentationCanvasMounted:et===de,wallPresentationVisible:Qa,wallPresentationCanvasMounted:cn.current.has(de)||Na.current.has(de),decoderOwnerExists:kn.current.has(de)})?[de]:[],[jo,de,Ee,Xt,et,pr,dt,Qa]),bl=d.useMemo(()=>zg([...Za,...Hs]),[Hs,Za]),Cc=d.useMemo(()=>_x(wt,Gt),[wt,Gt]),Jr=d.useMemo(()=>_x(wt,"large"),[wt]),kc=qN({mode4Enabled:Kt,directMode4WallEnabled:La,adaptiveFps:Hn,directDeviceCount:gr.length,adaptive:wt.adaptiveLoadShedding}),On=EN({fps:kc,maxWidth:Jr.maxWidth,maxHeight:Jr.maxHeight,quality:wt.quality},T),Mc=VN({deviceCount:Ja.length,targetFps:Hn,adaptive:wt.adaptiveLoadShedding});Kt&&Ja.length>0;const Cs=d.useCallback((m,x,C)=>{if(m.width<=0||m.height<=0)return!1;if(m===x)return!0;const R=C?Math.min(1,C.maxWidth/m.width,C.maxHeight/m.height):1,E=Math.max(1,Math.round(m.width*R)),G=Math.max(1,Math.round(m.height*R));(x.width!==E||x.height!==G)&&(x.width=E,x.height=G);const Y=x.getContext("2d",{alpha:!1});return Y?(Y.imageSmoothingEnabled=!0,Y.imageSmoothingQuality="low",Y.drawImage(m,0,0,m.width,m.height,0,0,x.width,x.height),!0):!1},[]),ks=d.useCallback((m,x)=>{const C=Math.max(0,Number(x.clientWidth||0)),R=Math.max(0,Number(x.clientHeight||0)),E=Math.max(1,Number(window.devicePixelRatio||1)),G=C>0&&R>0?{maxWidth:Math.ceil(C*E),maxHeight:Math.ceil(R*E)}:void 0;return Cs(m,x,G)},[Cs]),_r=d.useCallback((m,x,C)=>{if(!du.current)return;const R=`${m}:${x.deviceId}`,E=fu.current.get(R)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};E.bindingKey=co(x),E.totalPaints+=1,E.lastPaintAt=performance.now(),E.lastFrameSeq=Number(x.frameSeq||0),fu.current.set(R,E);const G=++dm.current,Y={sequence:G,scope:m,deviceId:x.deviceId,bindingKey:E.bindingKey,frameSeq:E.lastFrameSeq,paintedAt:E.lastPaintAt,sourceGapMs:Number(x.sourceGapMs||0),agentSendGapMs:Number(x.agentSendGapMs||0),agentSendDurationMs:Number(x.agentSendDurationMs||0),agentSendDurationFrameSeq:Number(x.agentSendDurationFrameSeq||0),agentFrameAgeMs:Number(x.agentFrameAgeMs||0),timestampUs:Number(x.timestampUs||0),queuedForMs:Number(C?.queuedForMs||0),decodedForMs:Number(C?.decodedForMs||0),scheduledForMs:Number(C?.scheduledForMs||0),interactiveBurstOutputWindowMs:Number(C?.interactiveBurstOutputWindowMs||0),interactiveBurstTailHoldCount:Number(C?.interactiveBurstTailHoldCount||0)};_d.current[(G-1)%RI]=Y},[]),vr=d.useCallback(m=>{m&&$a(x=>{if(x.has(m))return x;const C=new Set(x);return C.add(m),C})},[]),es=d.useCallback(m=>{m&&$a(x=>{if(!x.has(m))return x;const C=new Set(x);return C.delete(m),C})},[]),pi=d.useCallback((m,x)=>{if(!x||x.width<=0||x.height<=0)return!1;const C=document.createElement("canvas");if(C.width=x.width,C.height=x.height,!Cs(x,C))return xa(C),!1;const R=Ua.current.get(m);return Ua.current.set(m,C),R&&R!==C&&ja(R),vr(m),!0},[vr,Cs,ja,xa]),zn=d.useCallback(m=>{i1(Ua.current,m,bd)},[]),Vi=d.useCallback((m,x)=>{const C=Ua.current.get(m),R=cn.current.get(m)===x||Na.current.get(m)===x;return Xe.current[m]?(zn(m),!1):!C||!R||C.width<=0||C.height<=0?!1:Cs(C,x)?!0:(zn(m),!1)},[Cs,zn]),zs=d.useCallback((m,x=!1,C)=>{if(Xe.current[m]||!ur.current.has(m))return!1;const R=Math.max(1,Math.min(Qt,Xn.controlWallReuseMaxFps,Vn)),E=performance.now(),G=ai.current.get(m)||0,Y=kn.current.get(m)||Zn.current.get(m),ee=cn.current.get(m)||Na.current.get(m);if(!Y||!ee||!ee.isConnected)return!1;const ie=zN({cadenceCredit:Wa.current.get(m)||0,targetFps:R,sourceFps:Vn,elapsedSincePaintMs:G>0?E-G:0,nowMs:E,scheduledPaintAtMs:Aa.current.get(m)||0,force:x});if(!ie.shouldPaint)return Wa.current.set(m,ie.nextCadenceCredit),!1;const re=Math.max(0,Number(ee.clientWidth||0)),Ve=Math.max(0,Number(ee.clientHeight||0)),Be=Math.max(1,Number(window.devicePixelRatio||1)),Ue=re>0&&Ve>0?{maxWidth:Math.min(Cc.maxWidth,Math.ceil(re*Be)),maxHeight:Math.min(Cc.maxHeight,Math.ceil(Ve*Be))}:Cc;return Cs(Y,ee,Ue)?(Wa.current.set(m,ie.nextCadenceCredit),ie.nextScheduledPaintAtMs>0&&Aa.current.set(m,ie.nextScheduledPaintAtMs),ai.current.set(m,performance.now()),ie.sourceCadencePassthrough&&(Wa.current.delete(m),Aa.current.delete(m)),C&&_r("wall-reuse-visible",C),vr(m),zn(m),!0):!1},[Vn,Cc,vr,Cs,_r,zn,Qt]);d.useEffect(()=>{Ri.current=ni},[ni]);const Ac=d.useCallback((m,x)=>{const C=ri.current;if(!C||C.deviceId!==m)return;const R=Date.now();fm.current.set(m,{...C,source:x,completedAtEpochMs:R,durationMs:Math.max(0,performance.now()-C.startedAt)}),ri.current=null},[]),Fo=d.useCallback((m,x)=>{const C=cn.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(cn.current.set(m,x),C&&C!==x&&xa(C),Xe.current[m]){zn(m),ja(x),es(m);return}Ua.current.get(m)&&Vi(m,x)&&vr(m),zs(m,!0);return}if(C&&Ya.current&&pl.current.includes(m)){pi(m,C),cn.current.delete(m),xa(C);return}cn.current.delete(m),zn(m),xa(C),es(m)},[es,vr,zs,Vi,pi,ja,zn,xa]),Du=d.useCallback((m,x)=>{const C=Zn.current.get(m);if(x){Zn.current.set(m,x),Me(m),C&&C!==x&&xa(C);const R=de===m&&me?kn.current.get(m):null;R&&ks(R,x)&&m===ye&&(Ac(m,"warm-reuse"),Ga(!0)),R&&R!==x&&HN({decodeWidth:R.width,decodeHeight:R.height,presentationCssWidth:x.getBoundingClientRect().width,presentationCssHeight:x.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:vs.maxWidth,sourceHeight:vs.maxHeight})&&(kn.current.set(m,x),xa(R));return}Zn.current.delete(m),Me(R=>R===m?"":R),xa(C)},[Ac,ye,de,me,vs.maxHeight,vs.maxWidth,ks,xa]),Nc=d.useCallback((m,x,C)=>{const R=performance.now(),E=la(m,C.deviceId);let G=C;if(m==="control"&&C.visualChanged){const ie=String(x.inputFeedbackEventId||""),re=Number(x.inputFeedbackInputSeq||0),Ve=Number(x.inputFeedbackIssuedAtEpochMs||0),Be=Number(x.browserReceivedEpochMs||0),Ue=Hd.current.get(C.deviceId)||"",gt=Ve>0?Math.max(0,Date.now()-Ve):Number.POSITIVE_INFINITY;if(ie.length>0&&re>0&&ie!==Ue&><=Bg){const Tt=wu.current.get(C.deviceId)||[];Tt.push(gt),Tt.length>yx&&Tt.splice(0,Tt.length-yx),wu.current.set(C.deviceId,Tt),G={...C,inputFeedbackSeq:re,inputFeedbackMs:gt,inputFeedbackAt:R,inputFeedbackExact:!0,inputFeedbackEventId:ie,inputFeedbackInputType:x.inputFeedbackInputType,inputFeedbackInputToFrameMs:Be>0?Math.max(0,Be-Ve):void 0,inputFeedbackFrameToPaintMs:Be>0?Math.max(0,Date.now()-Be):void 0,inputFeedbackAgentApplyMs:x.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:x.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Tt.length,inputFeedbackP50Ms:Bf(Tt,.5),inputFeedbackP95Ms:Bf(Tt,.95)},Hd.current.set(C.deviceId,ie),bu.current.set(C.deviceId,re)}else if(!ie){const Tt=aN(C.deviceId),an=bu.current.get(C.deviceId)||0,Ln=Tt?R-Tt.sentAt:Number.POSITIVE_INFINITY;Tt&&Tt.inputSeq>an&&Ln<=Bg&&(G={...C,inputFeedbackSeq:Tt.inputSeq,inputFeedbackMs:Math.max(0,Ln),inputFeedbackAt:R,inputFeedbackExact:!1},bu.current.set(C.deviceId,Tt.inputSeq))}}Di.current.set(E,R),oi.current.delete(E);const Y=Ps.current.get(E)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:R,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},ee=co(x);Y.bindingKey!==ee&&(Y.bindingKey=ee,Y.lastAt=void 0,Y.lastFrameSeq=void 0,Y.sampleChangedFrames=0,Y.sampleDecoderInputBase=Number(C.decoderInputCount||0),Y.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Np(Y,R)),m==="control"&&G.inputFeedbackMs===void 0&&Y.lastInfo?.inputFeedbackMs!==void 0&&Y.lastInfo.inputFeedbackAt!==void 0&&R-Y.lastInfo.inputFeedbackAt<=Bg&&(G={...G,inputFeedbackSeq:Y.lastInfo.inputFeedbackSeq,inputFeedbackMs:Y.lastInfo.inputFeedbackMs,inputFeedbackAt:Y.lastInfo.inputFeedbackAt,inputFeedbackExact:Y.lastInfo.inputFeedbackExact,inputFeedbackEventId:Y.lastInfo.inputFeedbackEventId,inputFeedbackInputType:Y.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:Y.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:Y.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:Y.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:Y.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:Y.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:Y.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:Y.lastInfo.inputFeedbackP95Ms}),Y.totalFrames+=1,Y.sampleFrames+=1,Nx(Y,R,G.frameSeq),G.visualChanged&&(Y.totalChangedFrames+=1,Y.sampleChangedFrames+=1),Y.lastInfo=G,Ps.current.set(E,Y)},[]),wl=d.useCallback((m,x)=>{if(Xe.current[m.deviceId]||Ri.current===m.deviceId)return;Nc("wall",m,x);const C=me&&de===m.deviceId,R=cn.current.get(m.deviceId)||Na.current.get(m.deviceId);du.current&&!dt&&!C&&R?.isConnected&&_r("wall-visible",m,x),m.kind==="live"&&(vr(m.deviceId),zn(m.deviceId)),Ri.current!==m.deviceId&&!C&&(ur.current.delete(m.deviceId),Wa.current.delete(m.deviceId),ai.current.delete(m.deviceId),Aa.current.delete(m.deviceId))},[de,me,vr,Nc,_r,zn,dt]),Iu=d.useCallback((m,x)=>{if(Xe.current[m.deviceId]||Qn(Va.current,At.current)||!kg(m,At.current))return;Nc("control",m,x),jt(Y=>Y&&"");const C=kn.current.get(m.deviceId),R=Zn.current.get(m.deviceId);let E=!1;C&&C.width>0&&C.height>0&&(R&&dt&&m.deviceId===ye&&(E=ks(C,R),E&&_r("control-visible",m,x)),qa.current.set(m.deviceId,tu(m)),ur.current.add(m.deviceId),m.deviceId===de&&(ke(!0),Ge(Y=>Y==="connecting"?"active":Y)),zs(m.deviceId,!1,m));const G=hu.current;!G||!NI(G,m)||!E||(Ac(m.deviceId,"fresh-frame"),Ga(!0))},[Ac,ye,de,zs,ks,Nc,_r,dt]),sa=d.useCallback((m,x)=>{const C=performance.now(),R=la(m,x.deviceId);ii.current.set(R,C),Fs.current.delete(R),li.current.delete(R),m==="control"?Os.current.delete(R):Mo.current.delete(R);const E=Ei.current.get(R)||{totalFrames:0,sampleFrames:0,sampleStartedAt:C,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleBytes:0,sampleH264Frames:0,sampleTinyFrames:0,sampleRepeatedFrames:0,sourceSendIntervalsMs:[]},G=co(x);if(E.bindingKey!==G&&(E.bindingKey=G,E.lastAt=void 0,E.lastFrameSeq=void 0,E.lastContentHash=void 0,E.sampleBytes=0,E.sampleH264Frames=0,E.sampleTinyFrames=0,E.sampleRepeatedFrames=0,E.sourceSendIntervalsMs.length=0,Np(E,C)),E.totalFrames+=1,E.sampleFrames+=1,E.sampleBytes+=Math.max(0,Number(x.byteLength||0)),String(x.frameMode||x.mode||x.codec||x.mimeType||"").toLowerCase().includes("h264")){E.sampleH264Frames+=1,Number(x.byteLength||0)<=SI&&(E.sampleTinyFrames+=1);const re=String(x.contentHash||"");re&&E.lastContentHash===re&&(E.sampleRepeatedFrames+=1),E.lastContentHash=re}const ie=Number(x.agentSendGapMs||0);ie>0&&ie<1e3&&tC(E.sourceSendIntervalsMs,ie),E.lastFrame=tu(x),Nx(E,C,x.frameSeq),Ei.current.set(R,E)},[]);d.useEffect(()=>{const m=new Set(_o);for(const R of Ps.current.keys())m.has(R)||Ps.current.delete(R);for(const R of Ei.current.keys())m.has(R)||Ei.current.delete(R);const x=R=>{const E=Object.entries(R).filter(([G])=>m.has(G));return E.length===Object.keys(R).length?R:Object.fromEntries(E)};if(Fd(x),dc(x),m.size===0)return;const C=window.setInterval(()=>{const R=performance.now(),E={},G={};for(const Y of m){const ee=Ps.current.get(Y);if(ee){const Be=Math.max(1,R-ee.sampleStartedAt);E[Y]={bindingKey:ee.bindingKey||"",totalFrames:ee.totalFrames,totalChangedFrames:ee.totalChangedFrames,framesPerSecond:ee.sampleFrames*1e3/Be,changedFramesPerSecond:ee.sampleChangedFrames*1e3/Be,averageIntervalMs:ee.intervalCount>0?ee.intervalSumMs/ee.intervalCount:0,minIntervalMs:Number.isFinite(ee.minIntervalMs)?ee.minIntervalMs:0,maxIntervalMs:ee.maxIntervalMs,p95IntervalMs:Bf(ee.intervalSamplesMs,.95),intervalCount:ee.intervalCount,seqGapCount:ee.seqGapCount,maxSeqGap:ee.maxSeqGap,decoderInputFps:Math.max(0,(Number(ee.lastInfo?.decoderInputCount||0)-ee.sampleDecoderInputBase)*1e3/Be),decoderOutputFps:Math.max(0,(Number(ee.lastInfo?.decoderOutputCount||0)-ee.sampleDecoderOutputBase)*1e3/Be),sampleMs:Be,lastInfo:ee.lastInfo},ee.sampleDecoderInputBase=Number(ee.lastInfo?.decoderInputCount||0),ee.sampleDecoderOutputBase=Number(ee.lastInfo?.decoderOutputCount||0),ee.sampleChangedFrames=0,Np(ee,R)}const ie=Ei.current.get(Y);if(!ie)continue;const re=Math.max(1,R-ie.sampleStartedAt),Ve=ie.lastFrame?tu(ie.lastFrame):void 0;ie.lastFrame=Ve,G[Y]={totalFrames:ie.totalFrames,framesPerSecond:ie.sampleFrames*1e3/re,averageIntervalMs:ie.intervalCount>0?ie.intervalSumMs/ie.intervalCount:0,minIntervalMs:Number.isFinite(ie.minIntervalMs)?ie.minIntervalMs:0,maxIntervalMs:ie.maxIntervalMs,p95IntervalMs:Bf(ie.intervalSamplesMs,.95),intervalCount:ie.intervalCount,seqGapCount:ie.seqGapCount,maxSeqGap:ie.maxSeqGap,averageFrameBytes:ie.sampleFrames>0?ie.sampleBytes/ie.sampleFrames:0,tinyFrameRatio:ie.sampleH264Frames>0?ie.sampleTinyFrames/ie.sampleH264Frames:0,repeatedFrameRatio:ie.sampleH264Frames>0?ie.sampleRepeatedFrames/ie.sampleH264Frames:0,sourceSendAverageMs:ie.sourceSendIntervalsMs.length>0?ie.sourceSendIntervalsMs.reduce((Be,Ue)=>Be+Ue,0)/ie.sourceSendIntervalsMs.length:0,sourceSendP95Ms:Bf(ie.sourceSendIntervalsMs,.95),sourceSendSampleCount:ie.sourceSendIntervalsMs.length,sampleMs:re,lastFrame:Ve},ie.sampleBytes=0,ie.sampleH264Frames=0,ie.sampleTinyFrames=0,ie.sampleRepeatedFrames=0,ie.sourceSendIntervalsMs.length=0,Np(ie,R)}Fd(E),dc(G)},1e3);return pu.current=C,()=>{window.clearInterval(C),pu.current===C&&(pu.current=null)}},[_o]);const Fr=d.useCallback(m=>{const x=m.deviceId,C=co(m);if(Xe.current[x]||Ri.current===x||m.currentGenerationVerified!==!0||Kr.current.get(x)!==C)return;sa("wall",m);const R=cn.current.get(x);if(!R)return;const E=_i(R),G=Bs(R),Y=()=>cn.current.get(x)!==R||!Yr(R,E)||!!Xe.current[x]||Ri.current===x||Kr.current.get(x)!==C,ee=()=>Y()||!ui(R,G),ie=KN(Kt,wt.h264DecodeAcceleration);wg(R,m,ee,wl,ie.acceleration,ie.latencyMode,Y).catch(()=>{})},[_i,ui,Yr,Bs,wl,Kt,sa,wt.h264DecodeAcceleration]),hi=d.useCallback(m=>{const x=m.deviceId;if(Xe.current[x]||Qn(Va.current,At.current)||!kg(m,At.current))return;let C=kn.current.get(x);if(!C){const Ue=Zn.current.get(x),gt=Fn.current;C=Ue||gt||document.createElement("canvas"),Ue&>&>!==Ue&&ja(gt),Fn.current=null,C!==Ue&&C.setAttribute("aria-hidden","true"),kn.current.set(x,C)}const R=C,E=m,G=_i(R),Y=Bs(R),ee=()=>kn.current.get(x)!==R||!Yr(R,G)||!!Xe.current[x]||!kg(E,At.current),ie=()=>ee()||!ui(R,Y),re=O.current,Ve=String(m.frameMode||m.mode||m.codec||m.mimeType||"").toLowerCase().includes("h264");Ve||sa("control",m);const Be=wg(R,m,ie,Iu,_n.h264DecodeAcceleration,"interactive",ee);Ve&&sa("control",m),Be.catch(Ue=>{O.current!==re||kn.current.get(x)!==R||!ui(R,Y)||ee()||de!==x||jt(Ue instanceof Error?Ue.message:String(Ue||"Control H.264 decode failed"))})},[_i,ui,Yr,Bs,de,_n.h264DecodeAcceleration,Iu,sa,ja]),Gd=d.useCallback(m=>{const x=Er.current;Er.current=m,x&&x!==m&&xa(x),mc.current=0,vu.current=0,Ra.current=0,Pi.current=0,yu.current=0,uc.current=0},[xa]),Oo=d.useCallback(()=>{const m=new Set,x=Er.current,C=ul.current;if(!x||!C||x.width<=0||x.height<=0||uc.current!==C.layoutVersion)return m;for(const R of C.tiles){if(Xe.current[R.deviceId])continue;const E=Na.current.get(R.deviceId);if(!E||R.width<=0||R.height<=0)continue;const G=Math.max(1,Math.round(R.width)),Y=Math.max(1,Math.round(R.height)),ee=CI,ie=kI;(E.width!==ee||E.height!==ie)&&(E.width=ee,E.height=ie);const re=E.getContext("2d",{alpha:!1});if(re){re.imageSmoothingEnabled=!0,re.imageSmoothingQuality="high";try{re.drawImage(x,Math.round(R.x),Math.round(R.y),G,Y,0,0,ee,ie),m.add(R.deviceId)}catch{}}}return m},[]),Ki=d.useCallback((m,x)=>{const C=Na.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(Na.current.set(m,x),C&&C!==x&&xa(C),Xe.current[m]){zn(m),ja(x),es(m);return}Ua.current.get(m)&&Vi(m,x)&&vr(m),window.requestAnimationFrame(()=>{Oo().has(m)&&zn(m)}),window.requestAnimationFrame(()=>zs(m,!0));return}Na.current.delete(m),zn(m),xa(C),es(m)},[es,vr,Oo,zs,Vi,pi,ja,zn,xa]),yr=d.useCallback((m,x)=>{Ra.current=performance.now(),uc.current=Number(m.layoutVersion||0),Oo();const C=ul.current?.tiles||[],R=C.length>0?Math.round(m.byteLength/C.length):m.byteLength;for(const E of C){if(Xe.current[E.deviceId])continue;const G={...m,deviceId:E.deviceId,width:E.width,height:E.height,sourceWidth:E.width,sourceHeight:E.height,byteLength:R};wl(G,{...x,deviceId:E.deviceId,width:E.width,height:E.height,byteLength:R}),Ri.current===E.deviceId&&zs(E.deviceId,!0)}},[wl,Oo,zs]),Kn=d.useCallback(m=>{const x=performance.now();mc.current<=0&&(mc.current=x),vu.current=x;const C=Er.current;if(!C)return;const R=co(m);cc.current!==R&&(cc.current=R,Jn(C));const E=_i(C),G=Bs(C),Y=()=>Er.current!==C||cc.current!==R||!Yr(C,E),ee=()=>Y()||!ui(C,G),ie=ul.current?.tiles||[],re=ie.length>0?Math.round(m.byteLength/ie.length):m.byteLength;for(const Ve of ie)Xe.current[Ve.deviceId]||sa("wall",{...m,deviceId:Ve.deviceId,width:Ve.width,height:Ve.height,sourceWidth:Ve.width,sourceHeight:Ve.height,byteLength:re});wg(C,m,ee,yr,void 0,"smooth",Y).catch(()=>{})},[_i,ui,Yr,Bs,yr,sa,Jn]),Tc=d.useCallback(m=>{if(m.streamPurpose!=="wall"||Xe.current[m.deviceId])return;const x=co(m);Kr.current.get(m.deviceId)!==x&&(Kr.current.set(m.deviceId,x),Jn(cn.current.get(m.deviceId)))},[Jn]),gi=d.useMemo(()=>({fps:On.fps,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:On.quality,mode:Kt?"mode3-h264-hw":wt.frameMode,frameMode:Kt?"mode3-h264-hw":wt.frameMode,streamPurpose:"wall",configurationRefreshMs:fI,forceRestart:ml>0,forceRestartToken:ml>0?`document-presentation-resume-${ml}`:"",restartReason:ml>0?"document-presentation-resume":"",connectionSessionIds:Ss,monitorSelections:sn,onFrame:Fr,onStreamReady:Tc}),[Ss,ml,Fr,Tc,Kt,sn,wt.frameMode,On.fps,On.maxHeight,On.maxWidth,On.quality]),Ft=d.useCallback(m=>{const x=At.current;if(Xe.current[m.deviceId]||!x||Qn(Va.current,x)||x.deviceId!==m.deviceId||m.deviceId!==de||m.streamPurpose!=="control"||m.monitorIndex!==Da)return;const C=pt.find(E=>E.deviceId===m.deviceId);if(!C?.sessionId||C.sessionId!==m.sessionId)return;const R=Re.current;(!R||co(R)!==co(m))&&Jn(kn.current.get(m.deviceId)),At.current=Cg(x.deviceId,x.transitionGeneration,m),Re.current=m,qe(m),Ge(E=>E==="connecting"?"active":E)},[pt,de,Jn,Da]);d.useEffect(()=>{Jn(kn.current.get(de)),Re.current=null,qe(null)},[de,ue,Pr,Jn,Da]);const on=ue?`${ue}-monitor-${Da}`:"",ea=d.useMemo(()=>({fps:Vn,maxWidth:vs.maxWidth,maxHeight:vs.maxHeight,quality:_n.quality,mode:Pr,frameMode:Pr,streamPurpose:"control",forceRestart:on!=="",forceRestartToken:on,restartReason:on?"control-session-or-monitor-change":"",connectionSessionIds:Ss,monitorSelections:sn,onFrame:hi,onStreamReady:Ft}),[Ss,on,_n.quality,hi,Vn,Pr,vs.maxHeight,vs.maxWidth,Ft,sn]),{frames:Rc,state:$s,error:Qi,stats:Us,restartLive:Yi,reconnectLive:Bo}=iw(gr,wt.autoStartLive&&gr.length>0,X,gi);d.useEffect(()=>{const m=new Set(gr);for(const x of Kr.current.keys())m.has(x)||(Kr.current.delete(x),Jn(cn.current.get(x)))},[gr,Jn]);const{frame:xl,layout:yn,state:jc,stats:Vd,refreshInputs:Kd}=lN(Ja,Kt&&wt.autoStartLive&&Ja.length>0,X,{fps:Xn.atlasOutputFps,inputFps:Mc,width:1920,height:1080,tileWidth:Jr.maxWidth,tileHeight:Jr.maxHeight,captureDeviceIds:Ja,connectionSessionIds:Ss,monitorSelections:sn,onFrame:Kn});d.useEffect(()=>{ul.current=yn,yn&&window.requestAnimationFrame(Oo)},[yn,Oo]),d.useEffect(()=>{if(!Kt||jc!=="open"){mc.current=0,vu.current=0,Ra.current=0;return}const m=window.setInterval(()=>{const x=Er.current,C=performance.now();if(!x||document.visibilityState!=="visible"||C-Ii.current<Og)return;const R=vu.current,E=mc.current;if(R<=0||E<=0||C-R>500)return;const G=Ra.current||E,Y=C-G;if(Y>=vI&&C-yu.current>=bI){wd(x)&&(yu.current=C,Pi.current=C);return}Y>=gI&&C-Pi.current>=yI&&JA(x)&&(Pi.current=C)},250);return()=>window.clearInterval(m)},[jc,Kt]);const{frames:Sl,state:Qd,error:Ho,stats:Yd,restartLive:Cl,reconnectLive:ia}=iw(Hs,Hs.length>0,X,ea);d.useEffect(()=>{const m=ll.current,x=new Set([...Object.keys(m),...Object.keys(sn)]);for(const C of x){const R=Math.max(0,Math.floor(Number(m[C])||0)),E=Math.max(0,Math.floor(Number(sn[C])||0));R!==E&&(Kr.current.delete(C),Jn(cn.current.get(C)),Jn(kn.current.get(C)),Jn(Na.current.get(C)),ua("wall",C),ua("control",C),wd(cn.current.get(C)||null),wd(kn.current.get(C)||null))}x.size>0&&(Jn(Er.current),wd(Er.current)),ll.current={...sn}},[sn,ua,Jn]);const Mn=d.useMemo(()=>{const m=(C,R)=>{const E=pt.find(Y=>Y.deviceId===C),G=E?js(E,sn[C]):0;return!Number.isFinite(Number(R.monitorIndex))||Number(R.monitorIndex)===G},x=new Map;for(const[C,R]of Rc.entries())m(C,R)&&x.set(C,R);if(Kt&&xl&&Ja.length>0){const C=new Map((yn?.tiles||[]).map(E=>[E.deviceId,E])),R=Math.max(1,C.size);for(const E of Ja){const G=C.get(E);G&&x.set(E,{...xl,deviceId:E,width:G.width,height:G.height,sourceWidth:G.width,sourceHeight:G.height,byteLength:Math.round(xl.byteLength/R)})}}for(const[C,R]of Sl.entries())m(C,R)&&x.set(C,R);for(const C of Po){if(!ur.current.has(C)||x.has(C))continue;const R=qa.current.get(C);R&&m(C,R)&&x.set(C,R)}return x},[xl,yn,pt,Sl,Ja,Kt,sn,Rc,Po,wo]),kl=dt&&Hs.length>0?Qd:Ja.length>0?jc:$s,Xi=dt&&Hs.length>0?Yd:Ja.length>0?Vd:Us;d.useCallback((m,x="browser-stale")=>{const C=Yi(m,x),R=Cl(m,x);return C||R},[Cl,Yi]),d.useEffect(()=>{Kt&&Ja.length>0&&!dt&&Kd()},[Ja.length,Kt,Kd,dt]);const vi=d.useCallback((m,x,C)=>{const R=x==="control"?kn.current.get(m)||null:cn.current.get(m)||null;if(!R)return!1;wd(R);const E=performance.now();return oi.current.set(la(x,m),E),!0},[]),Ml=d.useCallback(m=>{if(Pr!=="mode3-h264-hw"||!de||Ze)return!1;const x=pt.find(ee=>ee.deviceId===de)||Sa,C=String(x?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const R="mode5-lzo-delta",E=la("control",de),G=performance.now();Li.current.set(E,G),ii.current.delete(E),Di.current.delete(E),_s.current.delete(E),Os.current.delete(E),li.current.delete(E),wd(kn.current.get(de)||null),ia([de],"control-decode-fallback"),at(R),_e(`control-${R}-fallback-${de}-${Date.now()}`),ke(!1),Ga(!1);const Y=m==="no first frame"||m==="control-first-frame-timeout";return jt(ee=>ee||(Y?`Control frame transport timeout; retrying Control with Mode 5 (${m})`:`H.264 decode failed; retrying Control with Mode 5 (${m})`)),Ge("connecting"),!0},[pt,Sa,de,Ze,Pr,ia]);d.useEffect(()=>{const m=dt?Sa:null;if(m){hu.current={deviceId:m.deviceId,monitorIndex:Da,frameMode:Pr,startedAtEpochMs:Date.now()},Ga(de===m.deviceId&&me);return}hu.current=null,Ga(!1)},[Sa?.sessionId,ye,de,me,Pr,Da,dt]);const qs=d.useCallback(async(m,x)=>{const C=String(x.streamId||"").trim(),R=String(x.streamPurpose||"").trim(),E=String(x.sessionId||"").trim(),G=String(x.commandId||"").trim(),Y=Number(x.captureGeneration||0),ee=Number(x.monitorIndex??-1);if(!C||!["wall","atlas"].includes(R)||!E||!G||!Number.isSafeInteger(Y)||Y<=0||!Number.isSafeInteger(ee)||ee<0)throw new Error("wall-start-owner-incomplete");const ie=performance.now()+3e3;for(;;){const re=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:R,expectedSessionId:E,expectedCommandId:G,expectedCaptureGeneration:Y,expectedMonitorIndex:ee,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},X);if(re?.ok===!1)throw new Error(re.error||"revoked-wall-start-stop-failed");if(re?.captureStopConfirmed===!0||re?.alreadyStopped===!0||re?.staleOwner===!0)return re;if(re?.presentationOwnerActive===!0||re?.retainedForPresentation===!0){if(Dr.current&&Ya.current)return re;if(performance.now()<ie){await new Promise(Ve=>window.setTimeout(Ve,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[X]),Ws=d.useCallback(async m=>{if(Xe.current[m])throw new Error("LIVE_CAPTURE_PAUSED");if(!Dr.current||!Ya.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const x=fs.current,C=W.find(Y=>Y.deviceId===m);Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(C?.platform)});const R=C?js(C,sn[m]):0,E={fps:On.fps,maxWidth:On.maxWidth,maxHeight:On.maxHeight,quality:On.quality,mode:Kt?"mode3-h264-hw":wt.frameMode,frameMode:Kt?"mode3-h264-hw":wt.frameMode,streamPurpose:"wall",monitorIndex:R},G=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/start`,{method:"POST",body:JSON.stringify(E)},X);if(G?.ok===!1)throw new Error(G.error||"wall-stream-start-failed");return x!==fs.current||!Dr.current||!Ya.current?(await qs(m,G),{...G,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):G},[Mc,W,La,X,Kt,sn,qs,wt.frameMode,Jr.maxHeight,Jr.maxWidth,On.fps,On.maxHeight,On.maxWidth,On.quality]),Lu=d.useCallback(async m=>{const x=W.find(R=>R.deviceId===m);Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(x?.platform)});const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"wall",reason:"control-active"})},X);if(C?.ok===!1)throw new Error(C.error||"wall-stream-stop-failed");return C},[W,La,X,Kt]),Pu=d.useCallback(async(m,x="control-session-stop")=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamPurpose:"control",reason:x})},X);if(C?.ok===!1)throw new Error(C.error||"control-stream-stop-failed");return C},[X]),er=d.useCallback((m,x={})=>{Va.current?.deviceId===m&&(Va.current=null);const C=kn.current.get(m);if(C){const E=Ua.current.has(m)||cn.current.has(m)||Na.current.has(m);x.preservePresentation!==!1&&!E&&pi(m,C),kn.current.delete(m),ja(C),!(Zn.current.get(m)||cn.current.get(m)||Na.current.get(m))&&!Fn.current&&(Fn.current=C)}const R=Zn.current.get(m);R&&bd(R),qa.current.delete(m),ur.current.delete(m),Wa.current.delete(m),ai.current.delete(m),Aa.current.delete(m)},[pi,ja]),Ec=d.useCallback(m=>{const x=[la("wall",m),la("control",m)];for(const C of x){const R=Ei.current.get(C);R?.lastFrame&&(R.lastFrame=tu(R.lastFrame))}dc(C=>{let R=!1;const E={...C};for(const G of x){const Y=C[G];!Y?.lastFrame||Y.lastFrame.payload.byteLength===0||(E[G]={...Y,lastFrame:tu(Y.lastFrame)},R=!0)}return R?E:C})},[]),_u=d.useCallback(m=>{Kr.current.delete(m),zn(m),er(m,{preservePresentation:!1});const x=new Set;for(const C of[Zn.current.get(m),cn.current.get(m),Na.current.get(m)])C&&x.add(C);for(const C of x)ja(C);es(m),de===m&&(hu.current=null,Ga(!1),ke(!1)),ut.current.add(m),Ec(m)},[es,de,ja,er,Ec,zn]);d.useEffect(()=>{const m=new Set(Object.keys(Ie));for(const x of m)ut.current.has(x)||_u(x);for(const x of ut.current)m.has(x)||ut.current.delete(x)},[_u,Ie]);const zo=d.useCallback(m=>{const x=hw(um.current,m);return um.current=x.tail,x.result},[]),Or=d.useCallback(m=>{const x=hw(Bd.current,m);return Bd.current=x.tail,x.result},[]),Br=d.useCallback(m=>{dr.current=m,uu.current=0;const x=m?.deviceId||"";Ri.current=x,cl(x),x&&ur.current.add(x)},[]),Zi=d.useCallback(m=>zo(async()=>{if(Xe.current[m.deviceId])return!1;const x=dr.current;return!Qn(x,m)||!mp(m.deviceId,m,At.current)?!1:(await Ws(m.deviceId),Qn(dr.current,m)&&Br(null),!0)}),[Br,zo,Ws]),Xd=d.useCallback((m,x,C)=>zo(async()=>{const R=dr.current;if(Qn(R,m))return C.stoppedWallDeviceId=m.deviceId,!0;if(R)if(Xe.current[R.deviceId])Qn(dr.current,R)&&Br(null);else{if(!mp(R.deviceId,R,At.current))return!1;await Ws(R.deviceId),Qn(dr.current,R)&&Br(null)}if(!x())return!1;if(await Lu(m.deviceId),C.stoppedWallDeviceId=m.deviceId,!x()){if(mp(C.stoppedWallDeviceId,m,At.current))try{await Ws(C.stoppedWallDeviceId)}catch(E){throw Br(m),E}finally{C.stoppedWallDeviceId=""}return!1}return bd(cn.current.get(m.deviceId)||null),Br(m),!0}),[Br,zo,Ws,Lu]),Fu=d.useCallback(async(m,x)=>{if(x.stoppedWallDeviceId){if(Qn(dr.current,m)){try{await Zi(m)}catch(C){Oe(C instanceof Error?C.message:String(C))}finally{x.stoppedWallDeviceId=""}return}await zo(async()=>{if(!x.stoppedWallDeviceId||!mp(x.stoppedWallDeviceId,m,At.current))return;const C=x.stoppedWallDeviceId;try{await Ws(C)}catch(R){Br(m),Oe(R instanceof Error?R.message:String(R))}finally{x.stoppedWallDeviceId=""}})}},[Br,zo,Zi,Oe,Ws]),Hr=d.useCallback(async(m,x,C={})=>{const R=C.allowStopFailure===!0,E=C.resumeWall!==!1;try{await Pu(m.deviceId,x)}catch(G){if(!R)throw G}if(!Qn(At.current,m))return!1;if(At.current=null,Re.current=null,qe(null),er(m.deviceId),ke(!1),_e(""),at(""),jt(""),Qe(G=>G===m.deviceId?"":G),!E)return Qn(dr.current,m)&&Br(null),!0;try{await Zi(m)}catch(G){Oe(G instanceof Error?G.message:String(G))}return!0},[Br,er,Zi,Oe,Pu]),Zd=(Ta&&dt&&Xt&&ye&&!St.has(ye)&&pt.find(m=>m.deviceId===ye)||null)?.deviceId||"";d.useEffect(()=>{Co.current=Zd},[Zd]),d.useEffect(()=>{const m=ye&&pt.find(G=>G.deviceId===ye)||null;if(!Ta||!dt||!Xt||!m){ba.current&&(++Wn.current,ba.current="");return}if(Xe.current[m.deviceId]){ba.current&&(++Wn.current,ba.current=""),de===m.deviceId&&Ge("paused");return}if(wa.current){if(wa.current===m.deviceId)return;wa.current=""}if(de===m.deviceId&&(Ee==="active"||Ee==="warm"||Ee==="connecting")){Ge(G=>G==="warm"?"active":G);return}if(ba.current===m.deviceId)return;const x=++Wn.current,C=Cg(m.deviceId,x,{sessionId:m.sessionId,monitorIndex:Da});ba.current=m.deviceId;const R={stoppedWallDeviceId:""},E=()=>x===Wn.current&&Co.current===C.deviceId;Or(async()=>{if(!E())return;const G=At.current;if(G){Ge("stopping");try{await Hr(G,"control-session-switch")}catch(ie){E()&&(Ge("error"),Oe(ie instanceof Error?ie.message:String(ie)));return}if(!E()){At.current||Ge("idle");return}}try{if(!await Xd(C,E,R)||!E()){await Fu(C,R),At.current||Ge("idle");return}}catch(ie){await Fu(C,R),E()&&(Ge("error"),Oe(ie instanceof Error?ie.message:String(ie)));return}if(!E()){await Fu(C,R);return}At.current=C,Va.current=null,wa.current="",ko.current=null,fl.current=0,fc.current="",R.stoppedWallDeviceId="";const Y=la("control",C.deviceId),ee=`control-session-${x}-${C.deviceId}`;Li.current.set(Y,performance.now()),ii.current.delete(Y),Di.current.delete(Y),li.current.delete(Y),Os.current.delete(Y),at(""),jt(""),_e(ee),Qe(C.deviceId),ke(!1),Ge("connecting")}).catch(G=>{E()&&(Ge("error"),Oe(G instanceof Error?G.message:String(G)))}).finally(()=>{Wn.current===x&&ba.current===C.deviceId&&(ba.current="")})},[pt,ye,de,Ee,Ta,Or,Xt,Xd,Fu,Da,Oe,dt,Hr,Ie]),d.useEffect(()=>{if(!de||pt.some(C=>C.deviceId===de))return;const m=de;++Wn.current,ba.current="";const x=At.current;Ge("stopping"),Or(async()=>{x&&x.deviceId===m?await Hr(x,"control-device-disconnected",{allowStopFailure:!0}):(er(m),Qe(C=>C===m?"":C)),At.current||Ge("idle")})},[pt,de,Or,er,Hr]),d.useEffect(()=>{if(Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),!Qa||dt||!de||Xe.current[de]||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm")return;const m=de,x=At.current;if(!x||x.deviceId!==m)return;const C=window.setTimeout(()=>{Qr.current===C&&(Qr.current=null);const R=At.current;if(Co.current||Xe.current[m]||!Qn(R,x))return;Va.current=x;const E=++Wn.current;ba.current="",Ge("stopping"),Or(async()=>{if(E!==Wn.current||Co.current||!Qn(At.current,x)){Qn(Va.current,x)&&(Va.current=null),Qn(At.current,x)&&Co.current===m&&Ge("active");return}try{await Hr(x,"control-session-wall-downshift")}catch(G){Qn(Va.current,x)&&(Va.current=null),E===Wn.current&&!Co.current&&Qn(At.current,x)&&(Ge("active"),Oe(G instanceof Error?G.message:String(G)));return}Va.current=null,E===Wn.current&&!At.current&&Ge("idle")})},xI);return Qr.current=C,()=>{Qr.current===C&&(window.clearTimeout(C),Qr.current=null)}},[de,Ee,Or,Oe,dt,Hr,Ie,Qa]);const Al=d.useCallback(m=>{if(mm.current===m)return;mm.current=m;const x=At.current,C=x?.deviceId||de,R=++Wn.current;ba.current="",Re.current=null,si.current=!0,qe(null),ke(!1),Ga(!1),C&&(ua("control",C),er(C,{preservePresentation:!1}),Ge("stopping"),Or(async()=>{if(x&&x.deviceId===C)try{await Hr(x,"control-session-document-hidden",{resumeWall:!1})}catch(E){!Dr.current&&fs.current===m&&(Ge("error"),Oe(E instanceof Error?E.message:String(E)));return}else er(C,{preservePresentation:!1}),Qe(E=>E===C?"":E);!At.current&&Wn.current===R&&Ge("idle")}))},[de,Or,er,ua,Oe,Hr]);d.useEffect(()=>{if(ds.current!==null&&(window.clearTimeout(ds.current),ds.current=null),!de||Ee==="idle"||Ee==="paused"||Ee==="error")return;if(!Ta){Al(fs.current);return}if(Ee==="stopping"||jo){de&&Lr&&Ee==="connecting"&&(si.current=!1),de&&Lr&&si.current&&(Ee==="warm"||Ee==="active")&&(si.current=!1,Re.current=null,qe(null),ke(!1),Ga(!1),ua("control",de),_e(`control-presentation-resume-${Date.now()}-${de}`),Ge("connecting"));return}Re.current=null,si.current=!0,qe(null),ke(!1),Ga(!1),Ge(x=>x==="idle"||x==="stopping"?x:"warm");const m=de;return er(m,{preservePresentation:!1}),ds.current=window.setTimeout(()=>{ds.current=null,++Wn.current,ba.current="";const x=At.current;Ge("stopping"),Or(async()=>{if(x&&x.deviceId===m)try{await Hr(x,"control-session-warm-timeout")}catch(C){Ge("error"),Oe(C instanceof Error?C.message:String(C));return}else er(m),Qe(C=>C===m?"":C);At.current||Ge("idle")})},wI),()=>{ds.current!==null&&(window.clearTimeout(ds.current),ds.current=null)}},[jo,Lr,de,Ee,Ta,Or,er,Al,ua,Oe,Hr]),d.useEffect(()=>()=>{ds.current!==null&&window.clearTimeout(ds.current),Qr.current!==null&&(window.clearTimeout(Qr.current),Qr.current=null),Va.current=null},[]);const Dc=d.useCallback(()=>{const m=new Set(gu.current),x=At.current?.deviceId||"";de&&m.add(de),x&&m.add(x),gu.current=[];for(const R of m){Kr.current.delete(R),zn(R),er(R,{preservePresentation:!1});for(const E of[cn.current.get(R),Zn.current.get(R),Na.current.get(R)])E&&ja(E);es(R),ua("wall",R),ua("control",R),Ec(R)}const C=Er.current;C&&ja(C),cc.current="",ul.current=null,uc.current=0},[es,de,ja,er,Ec,zn,ua]);d.useEffect(()=>{if(Ta){gu.current=[...bl];return}Dc()},[Ta,bl,Dc]),d.useEffect(()=>{const m=dr.current,x=At.current;if(!Qa||!m||Xe.current[m.deviceId]||x&&x.deviceId===m.deviceId){uu.current=0;return}const C=uu.current,R=Math.min(5e3,500*2**Math.min(C,4)),E=window.setTimeout(()=>{ji.current===E&&(ji.current=null);const G=dr.current;!Ir.current||!G||Xe.current[G.deviceId]||!Qn(G,m)||(uu.current=C+1,Zi(G).catch(Y=>{Oe(Y instanceof Error?Y.message:String(Y)),Qn(dr.current,G)&&!At.current&&bo(ee=>ee+1)}))},R);return ji.current=E,()=>{window.clearTimeout(E),ji.current===E&&(ji.current=null)}},[Ee,Zi,Oe,Qa,lc,ni]);const Nl=de&&pt.find(m=>m.deviceId===de)||null,Ic=!!(dt&&ze&&Ee==="active"&&me&&Nl?.sessionId&&pe?.deviceId===Nl.deviceId&&pe.sessionId===Nl.sessionId&&pe.streamPurpose==="control"&&pe.commandId&&pe.captureGeneration>0&&pe.monitorIndex===Da),{state:Ou,sendInput:Jd,stats:Gs,error:ef}=cN(Ta&&bs&&Ic,X),Ji=Nl?.deviceId||"",Bu=Nl?.sessionId||"",Tl=pe?.commandId||"",Rl=Number(pe?.captureGeneration||0),tf=Number(pe?.monitorIndex||0),$o=d.useCallback((m,x)=>!Dr.current||!Ic||!Ji||!Bu||!Tl||Rl<=0||m!==Ji?!1:Jd(m,{...x,monitorIndex:tf,controlSessionId:Bu,controlCommandId:Tl,captureGeneration:Rl}),[Ic,Rl,Tl,Ji,tf,Bu,Jd]),Vs=Ta&&Dr.current&&Ic&&Ou==="open",Hu={shiftKey:Et.includes("ShiftLeft"),ctrlKey:Et.includes("ControlLeft"),altKey:Et.includes("AltLeft"),metaKey:Et.includes("MetaLeft")},ts=d.useCallback(m=>Ne.current.enqueueStop(m),[]),eo=d.useCallback(m=>Ne.current.enqueueStart(m),[]),ka=d.useCallback((m,x=ce.current)=>(te.current=m,ce.current=m?String(x||""):"",fe.current+=1,fe.current),[]),ns=d.useCallback((m,x,C)=>_N({generation:m,currentGeneration:fe.current,enabled:te.current,deviceId:x,currentDeviceId:ce.current,documentVisible:Dr.current,presentationVisible:He.current,streamId:C,currentStreamId:Ae.current.get(x)||""}),[]),br=d.useCallback(async(m,x,C)=>{if(!x)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const E=await(Y=>rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({...Y?{streamId:Y}:{},reason:C})},X))(x),G=FN(E);if(G.staleOwner)return E;if(!G.confirmed)throw new Error(E?.error||"Remote audio capture stop was not confirmed.");return E},[X]),zu=d.useCallback(async(m,x)=>{const C=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({reason:x})},X);if(C?.ok===!1||C?.captureStopConfirmed!==!0&&C?.alreadyStopped!==!0)throw new Error(C?.error||"Remote audio stop-all was not confirmed.");return C},[X]),ym=d.useCallback(m=>{const x=fe.current,C=Ae.current.get(m)||"";return ts(()=>br(m,C,"remote-audio-automatic-restart")).then(()=>eo(async()=>{if(x!==fe.current||!te.current||ce.current!==m||!Dr.current||!He.current||!Xt||!ys||(je.current||De?.deviceId||"")!==m)return"";const R=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(Ae.current.set(m,R),!ns(x,m,R))return Ae.current.delete(m),"";const E=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(E?.ok===!1)throw Ae.current.get(m)===R&&Ae.current.delete(m),new Error(E.error||"Remote audio restart failed.");return ns(x,m,R)?R:(await br(m,R,"remote-audio-stale-restart-compensation"),Ae.current.get(m)===R&&Ae.current.delete(m),"")}))},[eo,ts,Xt,X,ns,ys,De?.deviceId,br]),$u=De?.deviceId&&Ae.current.get(De.deviceId)||"",bm=d.useCallback(async(m,x,C)=>{ka(!1),be(!1),await ts(()=>br(m,x,C)),Ae.current.get(m)===x&&Ae.current.delete(m)},[ts,ka,br]),{state:Uu,lastFrame:nf,stats:An,error:qu}=fN(De?.deviceId||"",Ta&&Eu&&Je,X,ml,En||Ht||du.current,$u,ym,bm),Lc=d.useRef(new Map);d.useEffect(()=>{const m=[["hub",q],["registry",l],["license",P],["wall-stream",Qi],["control-stream",Ho],["control-decode",st],["remote-input",ef],["remote-audio",qu]];for(const[x,C]of m){const R=String(C||"").trim();if(x==="hub"&&Bt?.requiresHubRestart&&Bt.stage==="updating"){Lc.current.delete(x);continue}if(!R){Lc.current.delete(x);continue}Lc.current.get(x)!==R&&(Lc.current.set(x,R),Oe(R))}},[qu,st,Ho,q,ef,P,l,Oe,Qi,Bt]);const jl=De?.deviceId||"",af=De?js(De,sn[jl]):0;d.useEffect(()=>{if(!ze||!bs||!Vs||!jl)return;const m=bN(),x=jl,C=af,R=Be=>{if(!Be)return!1;const Ue=$o(x,{...Be,monitorIndex:C});return!Ue&&Be.type!=="keyboard.reset"&&(m.reset("browser-input-send-rejected"),lt([])),Ue},E=(Be,Ue)=>{const gt=Be.target,bn=gt?.tagName?.toLowerCase(),Tt=gt?.isContentEditable||bn==="input"||bn==="textarea"||bn==="select",an=m.isPressed(Be);if(Tt&&(Ue==="keydown"||!an))return;const Ln=m.event(Be,Ue);Ln&&(Be.preventDefault(),Be.stopPropagation(),R(Ln))},G=Be=>E(Be,"keydown"),Y=Be=>E(Be,"keyup"),ee=(Be,Ue=!1)=>{const gt=m.reset(Be,Ue);gt&&(R(gt),lt([]))};ht.current=Be=>{const Ue=m.snapshot().latchedCodes.includes(Be),gt=m.modifier(Be,!Ue);gt&&(R(gt),lt(bn=>Ue?bn.filter(Tt=>Tt!==Be):[...bn.filter(Tt=>Tt!==Be),Be]))};const ie=()=>ee("browser-window-blur"),re=()=>ee("browser-page-hidden"),Ve=()=>{document.visibilityState==="hidden"&&ee("browser-document-hidden")};return window.addEventListener("keydown",G,!0),window.addEventListener("keyup",Y,!0),window.addEventListener("blur",ie),window.addEventListener("pagehide",re),document.addEventListener("visibilitychange",Ve),()=>{window.removeEventListener("keydown",G,!0),window.removeEventListener("keyup",Y,!0),window.removeEventListener("blur",ie),window.removeEventListener("pagehide",re),document.removeEventListener("visibilitychange",Ve),ht.current=null,ee("control-keyboard-owner-changed",!0)}},[bs,Vs,jl,af,ze,$o]);const rf=d.useCallback(m=>{He.current=m;const x=je.current||De?.deviceId||"";if(!Je||!x)return;const C=ka(te.current,x);if(!m){const E=Ae.current.get(x)||"";ts(async()=>{await br(x,E,"remote-audio-document-hidden")}).catch(G=>{(je.current||De?.deviceId||"")===x&&(ka(!1),Ae.current.delete(x),be(!1),Oe(G instanceof Error?G.message:String(G)))});return}const R=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Ae.current.set(x,R),eo(async()=>{if(!ns(C,x,R)||!Xt||!ys||(je.current||De?.deviceId||"")!==x)return;const E=await rt(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(E?.ok===!1)throw new Error(E.error||"Remote audio presentation resume failed.");ns(C,x,R)||(await br(x,R,"remote-audio-stale-presentation-compensation"),Ae.current.get(x)===R&&Ae.current.delete(x))}).catch(E=>{Dr.current&&C===fe.current&&(ka(!1),Ae.current.delete(x),be(!1),Oe(E instanceof Error?E.message:String(E)))})},[Je,eo,ts,ka,Xt,X,ns,ys,De?.deviceId,Oe,br]);d.useEffect(()=>{const m=E=>{const G=Dr.current;E!==G&&(Dr.current=E,fs.current+=1,yc.current={active:E&&Ya.current,epoch:fs.current},E||(Dc(),Al(fs.current)),rf(E),gh(E),E&&!G&&(vh(Y=>Y+1),Ii.current=performance.now()))},x=()=>{m(document.visibilityState==="visible")},C=()=>m(!1),R=()=>x();return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",C),window.addEventListener("pageshow",R),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",R)}},[Dc,Al,rf]),d.useEffect(()=>{if(!de||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm"||Qd!=="open")return;const m=de,x=la("control",m),C=window.setInterval(()=>{const R=performance.now();if(document.visibilityState!=="visible"||R-Ii.current<Og)return;const E=ii.current.get(x)||0,G=Di.current.get(x)||0,Y=_s.current.get(x)||0,ee=Li.current.get(x)||R;Li.current.has(x)||Li.current.set(x,ee);const ie=E<=0,re=ie?R-ee>LI:R-E>Ex,Ve=bw({lastReceivedAt:E,lastPaintedAt:G,now:R,staleAfterMs:Ex}),Be=yw({paintStale:Ve,lastRecoveryAt:oi.current.get(x)||0,now:R,recoveryCooldownMs:Ix,transportRecoveryAfterMs:Lx});if(!re&&Be==="reset-decoder"&&vi(m,"control","decoder-paint-stale")||!re&&Be==="wait")return;if(!(re||Be==="recover-transport")){Ve&&vi(m,"control","decoder-paint-stale"),ie&&R-ee>II&&!Fs.current.has(x)&&ia([m],"control-frame-socket-recovery")&&Fs.current.set(x,R);return}const gt=Fs.current.get(x)||0;if(gt<=0){ia([m],"control-frame-socket-recovery")&&Fs.current.set(x,R);return}if(R-gt<Dx)return;const bn=Os.current.get(x)||0;if(bn>0){if(R-bn<_I)return;Os.current.delete(x)}const Tt=li.current.get(x)||0;if(Tt>=FI){if(Ml(ie?"no first frame":"stale stream"))return;ke(!1),Ga(!1),wa.current=m,Ge("error");return}if(R-Y<Px(PI,Tt))return;Cl([m],ie?"control-first-frame-timeout":Be==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(Fs.current.delete(x),oi.current.delete(x),_s.current.set(x,R),Os.current.set(x,R),Li.current.set(x,R),li.current.set(x,Tt+1))},650);return()=>window.clearInterval(C)},[Qd,de,Ee,Ml,ia,vi,Cl]),d.useEffect(()=>{!st||de&&Xe.current[de]||Pr!=="mode3-h264-hw"||Ml(st)||(ke(!1),Ga(!1),wa.current=At.current?.deviceId||"",Ge("error"))},[st,de,Pr,Ml]),d.useEffect(()=>{!dt||!de||Xe.current[de]||!Ho||(wa.current=de,Ge(m=>m==="error"?m:"error"))},[Ho,de,dt]),d.useEffect(()=>{if(Ee!=="error")return;const m=At.current;if(!m)return;wa.current=m.deviceId,Qn(ko.current,m)||(ko.current=m,fl.current=0);const x=fl.current,C=x===0?0:Math.min(5e3,500*2**Math.min(x-1,4)),R=window.setTimeout(()=>{Qn(At.current,m)&&(++Wn.current,ba.current="",Ge("stopping"),Or(async()=>{if(Qn(At.current,m))try{if(!await Hr(m,"control-session-terminal-error"))return;ko.current=null,fl.current=0,fc.current===m.deviceId?(fc.current="",wa.current="",Ge("idle")):Ge("error")}catch(E){if(!Qn(At.current,m))return;fl.current+=1,Oe(E instanceof Error?E.message:String(E)),Ge("error"),Vr(G=>G+1)}}))},C);return()=>window.clearTimeout(R)},[Ee,Gr,Or,Oe,Hr]);const Pc=d.useCallback(m=>{if(!m||wa.current!==m)return!1;const x=At.current;return++Wn.current,ba.current="",fl.current=0,x&&x.deviceId===m?(fc.current=m,ko.current=null,Ge("error"),Vr(C=>C+1),!0):(fc.current="",wa.current="",ko.current=null,Ge("idle"),!0)},[]);d.useEffect(()=>{if($s!=="open"||!wt.autoStartLive||gr.length===0)return;const m=window.setInterval(()=>{const x=performance.now();if(document.visibilityState!=="visible"||x-Ii.current<Og)return;const C=1e3/Math.max(1,kc||Qt||1),R=Math.max(HI,Math.ceil(C*4)),E=[],G=[];for(const Y of gr){if(G.length+E.length>=UI)break;const ee=la("wall",Y),ie=ii.current.get(ee)||0,re=ie<=0,Ve=Mo.current.get(ee)||x;Mo.current.has(ee)||Mo.current.set(ee,Ve);const Be=_s.current.get(ee)||0,Ue=Di.current.get(ee)||0,gt=re||x-ie>R,bn=bw({lastReceivedAt:ie,lastPaintedAt:Ue,now:x,staleAfterMs:R}),Tt=yw({paintStale:bn,lastRecoveryAt:oi.current.get(ee)||0,now:x,recoveryCooldownMs:Ix,transportRecoveryAfterMs:Lx});if(!gt&&Tt==="reset-decoder"&&vi(Y,"wall","decoder-paint-stale")||!gt&&Tt==="wait")continue;if(!(gt||Tt==="recover-transport")){bn&&vi(Y,"wall","decoder-paint-stale");continue}const Ln=Fs.current.get(ee)||0;if(Ln<=0&&(!re||x-Ve>OI)){E.push(Y);continue}if(re&&x-Ve<=BI||Ln>0&&x-Ln<Dx)continue;const Ks=li.current.get(ee)||0;x-Be>=Px(zI,Ks)&&G.push(Y)}if(E.length>0&&Bo(E,"wall-frame-socket-recovery"))for(const Y of E)Fs.current.set(la("wall",Y),x);if(G.length>0&&Yi(G,G.some(Y=>(ii.current.get(la("wall",Y))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const Y of G){const ee=la("wall",Y);Fs.current.delete(ee),oi.current.delete(ee),_s.current.set(ee,x),Mo.current.set(ee,x),ii.current.delete(ee),Di.current.delete(ee),li.current.set(ee,(li.current.get(ee)||0)+1)}},$I);return()=>window.clearInterval(m)},[kc,gr,Bo,vi,Yi,wt.autoStartLive,Qt,$s]),d.useEffect(()=>{cr(Qt),ku.current=Date.now(),Gn.current=0,ps.current=0,da.current=0,gc.current=0,Ro.current=""},[Qt,wt.frameMode,wt.adaptiveLoadShedding]),d.useEffect(()=>{PA({h264DecodeAcceleration:wt.h264DecodeAcceleration})},[wt.h264DecodeAcceleration]),d.useEffect(()=>{if(!Xt||dt||Gt==="list"||!wt.visibleOnlyLive){ti([]);return}const m=hc.current;if(!m||typeof IntersectionObserver>"u"){ti(yl);return}const x=Array.from(m.querySelectorAll("[data-live-device-id]"));if(x.length===0){ti([]);return}const C=new Map,R=DN(m,T),E=()=>{const Y=zg(x.map(ee=>String(ee.dataset.liveDeviceId||"")).filter(ee=>(C.get(ee)||0)>0));ti(ee=>Hg(ee,Y)?ee:Y)},G=new IntersectionObserver(Y=>{for(const ee of Y){const ie=String(ee.target.dataset.liveDeviceId||"");ie&&C.set(ie,ee.isIntersecting?ee.intersectionRatio||.01:0)}E()},{root:R,rootMargin:T?AN:Si.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return x.forEach(Y=>G.observe(Y)),E(),()=>G.disconnect()},[yl,Xt,T,dt,mi,wt.visibleOnlyLive,Gt]),d.useEffect(()=>{if(!wt.adaptiveLoadShedding||!wt.autoStartLive||gr.length===0){ps.current=0,da.current=0,gc.current=0,Ro.current="";return}const m=Qt;if($s!=="open"||Us.sampleMs<500||Us.lastUpdatedAt<=0||gc.current===Us.lastUpdatedAt)return;gc.current=Us.lastUpdatedAt;const x=Date.now(),C=gr.map(Be=>({deviceId:Be,receive:mu[la("wall",Be)],paint:dl[la("wall",Be)]}));if(!C.every(({receive:Be,paint:Ue})=>{const gt=Be?.lastFrame,bn=Math.max(0,Number(gt?.requestedFps||0)),Tt=gt?co(gt):"";return GN({receiveSampleMs:Number(Be?.sampleMs||0),paintSampleMs:Number(Ue?.sampleMs||0),currentGenerationVerified:gt?.currentGenerationVerified===!0,frameRequestedFps:bn,adaptiveFps:Hn})&&Ue?.bindingKey===Tt})){ps.current=0,da.current=0,Gn.current=0;return}const E=[Hn,...C.map(({deviceId:Be,receive:Ue})=>`${Be}:${co(Ue.lastFrame)}`).sort()].join("|");if(Ro.current!==E){Ro.current=E,ps.current=x,da.current=0,Gn.current=0;return}if(!ps.current){ps.current=x,da.current=0;return}if(x-ps.current<Si.downshiftStableSampleMs)return;const G=C.reduce((Be,{receive:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0)),0),Y=C.reduce((Be,{receive:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0))*Math.max(0,Number(Ue?.averageFrameBytes||0)),0),ee=C.reduce((Be,{paint:Ue})=>Be+Math.max(0,Number(Ue?.framesPerSecond||0)),0),ie=Math.max(0,...C.map(({receive:Be})=>Number(Be?.maxIntervalMs||0))),re=Math.max(0,...C.map(({paint:Be})=>Number(Be?.p95IntervalMs||0))),Ve=WN({directDeviceCount:gr.length,requestedFps:Hn,measuredFramesPerSecond:G,measuredPaintFramesPerSecond:ee,measuredBytesPerSecond:Y,maxBytesPerSecond:Si.maxWallBytesPerSecond,worstReceiveGapMs:ie,worstPaintP95Ms:re,maxFrameGapMs:Si.maxFrameGapMs});if(Ve.overloaded){if(Gn.current=0,da.current+=1,da.current<Si.downshiftConsecutiveSamples)return;const Be=Si.minFps;if(x-ku.current>=Si.downshiftCooldownMs&&Hn>Be){const Ue=Math.max(Be,oL(Hn,Be));Ue<Hn&&(cr(Ue),ku.current=x,ps.current=0,da.current=0)}return}if(da.current=0,!Ve.healthyForRecovery||Hn>=m){Ve.healthyForRecovery||(Gn.current=0);return}if(!Gn.current){Gn.current=x;return}if(x-Gn.current>=Si.recoveryCooldownMs){const Be=Math.min(m,lL(Hn,m));Be>Hn&&(cr(Be),ku.current=x,Gn.current=0,ps.current=0,da.current=0)}},[Hn,gr.length,gr,dl,mu,$s,Us.lastUpdatedAt,Us.sampleMs,wt.adaptiveLoadShedding,wt.autoStartLive,wt.frameMode,Qt]),d.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("checkout");if(m==="success"){Oe("Checkout returned. Waiting for Dodo confirmation."),se();const x=window.setInterval(()=>{se()},4e3),C=window.setTimeout(()=>{window.clearInterval(x)},45e3);return()=>{window.clearInterval(x),window.clearTimeout(C)}}m==="cancelled"&&Oe("Checkout cancelled.")},[se]),d.useEffect(()=>{!Xt&&ze&&We(!1),!Xt&&Je&&(ka(!1),be(!1))},[Je,ze,ka,Xt]),d.useEffect(()=>{Je&&(!De||!ys)&&(ka(!1),be(!1))},[Je,ka,ys,De]),d.useEffect(()=>{const m=De?.deviceId||"",x=je.current;if(je.current=m,!x||x===m)return;const C=ka(Je,m),R=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";m&&Je&&Ae.current.set(m,R);let E=!0;const G=Ae.current.get(x)||"";return(async()=>{try{await ts(async()=>{await br(x,G,"remote-audio-device-switch"),Ae.current.delete(x)}),await eo(async()=>{if(!E||!ns(C,m,R)||!m||!Xt||!ys)return;const Y=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:R,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(Y.ok===!1)throw new Error(Y.error||"Remote audio start failed.");ns(C,m,R)||(await br(m,R,"remote-audio-stale-device-switch-compensation"),Ae.current.get(m)===R&&Ae.current.delete(m))})}catch(Y){E&&(ka(!1),Ae.current.delete(m),be(!1),Oe(Y instanceof Error?Y.message:String(Y)))}})(),()=>{E=!1}},[Je,eo,ts,ka,Xt,X,ns,ys,De?.deviceId,br]),d.useEffect(()=>{const m=pt.map(E=>E.deviceId),x=new Set(m),C=new Map(pt.map(E=>[E.deviceId,E])),R=new Map;for(const E of pt){const G=QI(E);if(!G)continue;const Y=ki(E.status),ee=[E.lastStatusAt,Y.capturedAt,Y.collectedAt,Y.timestamp,Y.updatedAt].find(re=>typeof re=="string"&&re.trim()),ie=xN(Js.current[E.deviceId],G,ee);ie&&(Js.current[E.deviceId]=ie,R.set(E.deviceId,ie),Z0({platform:E.platform,topologyFingerprint:G,consecutiveTopologySamples:ie.consecutiveSamples})&&(oc.current[E.deviceId]=G))}for(const E of Object.keys(Js.current))x.has(E)||delete Js.current[E];Z(E=>{const G=E.filter(Y=>x.has(Y));return Hg(E,G)?E:G}),ae(E=>E&&x.has(E)?E:""),Pe(E=>E&&x.has(E)?E:""),us(E=>{let G=!1;const Y={};for(const[ee,ie]of Object.entries(E)){const re=C.get(ee);if(!re){Y[ee]=ie;continue}const Ve=R.get(ee)||Js.current[ee],Be=SN({requestedIndex:ie,monitorCount:fo(re),platform:re.platform,topologyFingerprint:Ve?.fingerprint||"",consecutiveTopologySamples:Ve?.consecutiveSamples||0});Y[ee]=Be,Be!==ie&&(G=!0)}return G?Y:E}),hl(E=>{const G=E.filter(Y=>x.has(Y));return Hg(E,G)?E:G})},[pt,Eo]),d.useEffect(()=>{pm([]),xu(!1)},[zs]),d.useEffect(()=>{!Hi||No!=="selected"||Ea.length>0||In.length===0||hl(In.map(m=>m.deviceId))},[In,Ea.length,No,Hi]),d.useEffect(()=>{try{localStorage.setItem(XS,Wr)}catch{}},[Wr]),d.useEffect(()=>{tL(wt)},[wt]),d.useEffect(()=>{aL(_n)},[_n]),d.useEffect(()=>{JI(sn,oc.current)},[pt,sn]);const Wu=d.useCallback(async()=>{const m=new Set(w);m.add(Un);try{const G=await rt("/api/remote/status",void 0,Un);Ob({endpoint:G.agentEndpoint,endpoint_candidates:[...G.agentEndpointCandidates||[],...G.hostTargetEndpointCandidates||[]]}).forEach(Y=>m.add(Y))}catch{}const x=[...m].sort((G,Y)=>{const ee=ie=>{const re=Yf(ie);return re==="local"?0:re==="loopback"?1:2};return ee(G)-ee(Y)||G.localeCompare(Y)});let C=!1,R="",E=!1;try{for(const G of x){const Y=Yf(G);try{if(await rt("/api/health",void 0,G),Y==="local")return H(!0),Cd(!0),G;Y==="loopback"&&(C=!0,R=G)}catch{Y==="local"&&(E=!0)}}return C?(E&&Oe("LiveDesk Hub is reachable on this PC, but not through the LAN address yet. Restart LiveDesk Hub to bind 5179 on the network."),H(!0),Cd(!0),R||Un):(H(!1),Cd(!1),"")}catch{return H(!1),Cd(!1),""}},[w]),Uo=async()=>{if(gn("auth"),or(!1),window.liveDesk?.auth?.signInWithGoogle){const R=window.liveDesk.auth.signInWithGoogle();Wu();const E=await R;E?.ok===!1&&(Oe(E.error||"LiveDesk could not open the system browser for Google sign-in."),gn(""));return}const m=$t.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});Wu();const{data:x,error:C}=await m;C&&(Oe(C.message),gn(""))},_c=async()=>{gn("auth"),or(!1),window.liveDesk?.auth?.persistSession||await rt("/api/auth/session",{method:"DELETE"},X||Un).catch(()=>{}),await $t.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1&&Oe("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),gn("")};d.useEffect(()=>{if(!Ai)return;const m=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||or(!1))},x=C=>{C.key==="Escape"&&or(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Ai]);const Gu=d.useCallback(async(m={})=>{const x=m.silent===!0,C=m.takeover===!0,R=m.requestLocalAccess===!0;if(!n?.user){x||Oe("Sign in before publishing this host.","error");return}if(!Bi.current){Bi.current=!0,x||(gn("host"),it("Hub · 1/4 · Checking the local runtime…"));try{const G=(R?await Wu():"")||X||Un;if(!(z||await rt("/api/remote/status",void 0,G)).started)throw new Error("Start LiveDesk on this computer before syncing the server.");x||it("Hub · 2/4 · Sending the signed-in session to the Hub…");const ee=await rt("/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}})},G);if(!ee.ok||!ee.authenticated)throw new Error(ee.error||"hub-session-sync-failed");x||it("Hub · 3/4 · Claiming the Hub role and publishing its endpoint…");const ie=await rt("/api/hub/sync",{method:"POST",body:JSON.stringify({takeover:C})},G);if(!ie.ok)throw new Error(ie.error||"host-target-failed");if(!x){it("Hub · 4/4 · Verifying the endpoint and lease renewal…");const re=await rt("/api/hub/status",void 0,G);if(!re.hostTargetActive)throw new Error(re.hostTargetLease?.lastError||"host-target-not-active-after-sync");const Ve=re.hostTargetEndpoint||re.agentEndpoint||"endpoint ready",Be=Number(re.connectedDeviceCount||0),Ue=Be>0?`${Be} client${Be===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Oe(`Hub ready · ${Ve} · lease auto-renewal active. ${Ue}`,"success"),(R||D)&&(H(!0),Cd(!0)),V()}u()}catch(E){if(!x){const G=E instanceof Error?E.message:String(E);G.includes("local network access")&&(H(!1),Cd(!1)),Oe(`Hub setup failed · ${G}`,"error")}}finally{Bi.current=!1,x||gn("")}}},[X,D,V,u,Wu,n,Oe,it,z]),to=d.useCallback((m=!0)=>{Ct!=="host"&&(Dt(!1),m&&window.requestAnimationFrame(()=>Nr.current?.focus()))},[Ct]),wm=d.useCallback(()=>{Ct!=="host"&&(Nr.current=document.activeElement instanceof HTMLElement?document.activeElement:null,or(!1),Dt(!0))},[Ct]),xm=d.useCallback(()=>{Dt(!1),Gu({takeover:!0,requestLocalAccess:!0})},[Gu]);d.useEffect(()=>{if(!nt)return;const m=window.requestAnimationFrame(()=>vn.current?.focus()),x=R=>{R.target instanceof Element&&R.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||to(!1)},C=R=>{R.key==="Escape"&&to()};return window.addEventListener("pointerdown",x),window.addEventListener("keydown",C),()=>{window.cancelAnimationFrame(m),window.removeEventListener("pointerdown",x),window.removeEventListener("keydown",C)}},[to,nt]);const El=d.useCallback(async()=>{if(!(!z?.update?.canApply||Ct==="update")){gn("update");try{const m=await rt("/api/update/apply",{method:"POST",body:JSON.stringify({})},X||Un);if(!m.ok)throw new Error(m.error||"LiveDesk update could not be started.");const x=[...new Set((m.targets||[]).map(E=>String(E.deviceId||"").trim()).filter(Boolean))],C=!!(m.managerUpdateAvailable||m.clientPackageUpdateAvailable),R=m.state==="hub-restart-requested"?Date.now():void 0;(x.length>0||C)&&jr({operationId:String(m.operationId||`wall-update-${Date.now()}`),targetIds:x,stage:m.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String(z.hostInstanceId||""),targetManagerVersion:String(m.latestVersion||z.update?.latestVersion||""),targetClientVersion:String(m.latestClientVersion||z.update?.latestClientVersion||""),restartRequestedAt:R,restartDeadlineAt:R?R+Ap:void 0}),it(m.state==="hub-restart-requested"?Mp:Sx),V()}catch(m){Oe(m instanceof Error?m.message:String(m),"error")}finally{gn("")}}},[Ct,X,V,Oe,it,z]);d.useEffect(()=>{const m=Bt,x=z?.update;if(!m||m.stage!=="updating"||!x)return;const C=x.restartResult?.operationId===m.operationId?x.restartResult:null;if(C?.outcome==="restored"){const ie=C.error||`The requested Hub ${C.targetVersion||m.targetManagerVersion||"version"} failed verification.`;jr(re=>re?.operationId===m.operationId?{...re,stage:"restored",error:ie}:re),Oe(`LiveDesk update did not complete. Hub ${C.fallbackVersion||C.appVersion||"the previous version"} was restored. ${ie}`,"error");return}if(C?.outcome==="failed"){const ie=C.error||"No verified LiveDesk Hub replacement could be started.";jr(re=>re?.operationId===m.operationId?{...re,stage:"failed",error:ie}:re),Oe(`LiveDesk Hub update failed. ${ie}`,"error");return}if(x.operationId===m.operationId&&x.state==="failed"){const ie=x.error||"LiveDesk update failed before the Hub replacement completed.";jr(re=>re?.operationId===m.operationId?{...re,stage:"failed",error:ie}:re),Oe(ie,"error");return}if(x.operationId===m.operationId){if(x.state==="hub-restart-requested"&&!m.restartDeadlineAt){const ie=Date.now();jr(re=>re?.operationId===m.operationId?{...re,restartRequestedAt:ie,restartDeadlineAt:ie+Ap}:re),it(Mp)}!m.requiresHubRestart&&x.state==="clients-updated"&&(jr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Oe("LiveDesk clients updated and reconnected successfully.","success"));return}if(!m.requiresHubRestart)return;const R=z.started===!0&&(!m.initialHostInstanceId||z.hostInstanceId&&z.hostInstanceId!==m.initialHostInstanceId),E=!!x.checkedAt,G=Mx(x.currentVersion,m.targetManagerVersion),Y=!m.targetClientVersion||Mx(x.currentClientVersion,m.targetClientVersion),ee=E&&x.state==="idle"&&x.updateAvailable===!1&&G&&Y;R&&ee&&(jr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Oe(`LiveDesk Hub ${x.currentVersion||C?.appVersion||m.targetManagerVersion} restarted and passed version verification.`,"success"))},[Oe,it,z,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||m.restartDeadlineAt)return;const x=()=>{const R=Date.now();jr(E=>E?.operationId===m.operationId&&E.stage==="updating"&&!E.restartDeadlineAt?{...E,restartRequestedAt:R,restartDeadlineAt:R+Ap}:E),it(Mp)};if(z?.update?.state==="hub-restart-requested"){x();return}if(!q)return;const C=window.setTimeout(x,MI);return()=>window.clearTimeout(C)},[q,it,z?.update?.state,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||!m.restartDeadlineAt)return;const x=Math.max(0,m.restartDeadlineAt-Date.now()),C=m.operationId,R=window.setTimeout(()=>{const E=`LiveDesk Hub did not return and verify ${m.targetManagerVersion||"the requested version"} within ${Math.round(Ap/6e4)} minutes. Check the Hub terminal or restart log, then run livedesk@latest manually if the Hub is still offline.`;jr(G=>G?.operationId===C&&G.stage==="updating"?{...G,stage:"failed",error:E}:G),Oe(E,"error")},x);return()=>window.clearTimeout(R)},[Oe,Bt]),d.useEffect(()=>{if(!Bt||Bt.stage!=="updated")return;const m=Bt.operationId,x=window.setTimeout(()=>{jr(C=>C?.operationId===m?null:C)},Cx);return()=>window.clearTimeout(x)},[Bt]),d.useEffect(()=>{lr.current.clear(),ei({})},[Bt?.operationId]),d.useEffect(()=>{if(!Bt||z?.update?.operationId!==Bt.operationId)return;const m=(z.update.targets||[]).filter(C=>C.state==="completed").map(C=>kx(Bt.operationId,C)).filter(C=>!lr.current.has(C));if(m.length===0)return;const x=Date.now()+Cx;for(const C of m)lr.current.add(C);ei(C=>({...C,...Object.fromEntries(m.map(R=>[R,x]))}))},[z?.update,Bt]),d.useEffect(()=>{const m=Math.min(...Object.values(yo));if(!Number.isFinite(m))return;const x=window.setTimeout(()=>{const C=Date.now();ei(R=>Object.fromEntries(Object.entries(R).filter(([,E])=>E>C)))},Math.max(0,m-Date.now()));return()=>window.clearTimeout(x)},[yo]),d.useEffect(()=>{if(Ur!==Sx&&Ur!==Mp)return;const m=z?.update;if(String(m?.state||"")==="failed"){Oe(m?.error||"LiveDesk update failed.","error");return}Bt?.stage==="updated"&&Oe("")},[Ur,Oe,z?.update?.error,z?.update?.state,Bt?.stage]);const Sm=d.useCallback(async()=>{if(!Ct){gn("pin");try{const x=await rt("/api/remote/pairing-pin",{method:"POST"},X||Un);if(!x.ok)throw new Error(x.error||"pin-rotation-failed");await V(),Oe("New PIN published.")}catch(m){Oe(m instanceof Error?m.message:String(m))}finally{gn("")}}},[Ct,X,V]),Fc=d.useCallback(m=>{m&&(ae(m),Z(x=>x.includes(m)?x:[...x,m]))},[]),Vu=d.useCallback(m=>{if(!m)return;const x=mr.has(m);ae(C=>x?C===m?"":C:m),Z(C=>x?C.filter(R=>R!==m):C.includes(m)?C:[...C,m])},[mr]),qo=d.useCallback(()=>{Z([]),ae("")},[Cs]),Ku=d.useCallback(()=>{Z(pt.map(m=>m.deviceId)),ae("")},[pt]),Qu=d.useCallback((m,x)=>{const C=pt.find(E=>E.deviceId===m);if(!C)return;const R=fo(C);if(!(R<=1)&&(us(E=>{const G=qf(E[m],R),Y=(G+x+R)%R;return Y===G?E:{...E,[m]:Y}}),ua("wall",m),ua("control",m),$a(E=>{if(!E.has(m))return E;const G=new Set(E);return G.delete(m),G}),qa.current.delete(m),ur.current.delete(m),dt)){const E=Pc(m);ke(!1),E||Ge("connecting"),Ga(!1),Pe(m)}},[pt,ua,Pc,dt]);d.useEffect(()=>{const m=x=>{if(ze&&bs&&Vs)return;const C=x.target,R=C?.tagName?.toLowerCase();C?.isContentEditable||R==="input"||R==="textarea"||R==="select"||((x.ctrlKey||x.metaKey)&&x.key.toLowerCase()==="a"&&(x.preventDefault(),Ku()),x.key==="Escape"&&qo())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[bs,qo,Vs,ze,Ku]);const Cm=(m,x)=>{const C=pt.find(Y=>Y.deviceId===m),R=C?fo(C):1,E=qf(sn[m],R),G=qf(x,R);if(E!==G&&(us(Y=>({...Y,[m]:G})),$a(Y=>{if(!Y.has(m))return Y;const ee=new Set(Y);return ee.delete(m),ee}),qa.current.delete(m),ur.current.delete(m),Wa.current.delete(m),ai.current.delete(m),Aa.current.delete(m),ua("wall",m),ua("control",m)),dt){const Y=Pc(m);E!==G&&(ke(!1),Y||Ge("connecting")),Ga(!1),Pe(m)}else Fc(m)},Wo=m=>{const x=je.current||De?.deviceId||"",C=[...new Set([x,m].filter(Boolean))],R=Je||C.some(E=>Ae.current.has(E));ka(!1),be(!1);for(const E of C)Ae.current.delete(E);C.length!==0&&(async()=>{for(const E of C)await ts(()=>zu(E,"remote-audio-control-entry"))})().catch(E=>{R&&Oe("Remote audio was muted locally, but Client capture stop was not confirmed: "+(E instanceof Error?E.message:String(E)),"error")})},no=async m=>{const x={requestId:++hh.current,deviceId:m,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ri.current=x,!pr.has(m)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Oe(vl);return}const C=pt.find(E=>E.deviceId===m);if(tl(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Oe("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Wo(m),Pc(m),Ga(!1),Pe(m),bt("control"),We(!0),Oe(`Opening remote control${C?` for ${Pa(C)}`:""}.`,"success")},sf=async()=>{if(!De){Oe("Select a Client before playing audio.");return}if(!Xt){Oe(vl);return}if(!ys){Oe("Selected Client does not report remote audio support yet.");return}if(en)return;const m=!Je,x=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Ae.current.get(De.deviceId),C=ka(m,De.deviceId);m&&x?Ae.current.set(De.deviceId,x):m||Ae.current.delete(De.deviceId),U("audio"),be(m);try{m?(await ts(()=>zu(De.deviceId,"remote-audio-user-enable-reconcile")),await eo(async()=>{if(!x||!ns(C,De.deviceId,x))return;const R=await rt(`/api/remote/devices/${encodeURIComponent(De.deviceId)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:x,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(R?.ok===!1)throw new Error(R.error||"Remote audio start failed.");ns(C,De.deviceId,x)||await br(De.deviceId,x,"remote-audio-stale-user-start-compensation")})):await ts(()=>zu(De.deviceId,"remote-audio-user-disabled")),Oe(`${m?"Audio started":"Audio stopped"} for ${Pa(De)}.`,"success")}catch(R){ka(!1),m&&Ae.current.delete(De.deviceId),be(!1),Oe(R instanceof Error?R.message:String(R),"error")}finally{U("")}},km=async(m,x)=>{const C=m.deviceId,R=Pa(m),E=String(Xe.current[C]||""),G=!!E&&mt[C]===!0;if(x&&E&&!G)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:R};if(!x&&!E)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:R};if(!x&&E.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:R,error:"Pause is still pending confirmation."};if(x){const Ve=E||`pending:${Date.now()}:${C}`,Be=At.current?.deviceId===C?At.current:null,Ue=!!Be||de===C,gt=Ue?++Wn.current:0,bn=()=>pw({deviceId:C,requestTransitionGeneration:gt,currentTransitionGeneration:Wn.current,actualControlOwner:At.current}),Tt=yt.current.get(C);yt.current.set(C,{deviceId:C,monitorIndex:js(m,sn[C]??Tt?.monitorIndex),previousControlOwner:Be||Tt?.previousControlOwner||null}),ya(C,!0),rn(C,!1),pn(C,Ve),_u(C),Ue&&(ba.current="",Ge("paused"));try{const an=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},X);if(!an?.pauseToken)return _t.current.delete(C),pn(C,""),rn(C,!1),yt.current.delete(C),bn()&&(Re.current=null,qe(null),ke(!1),_e(`control-pause-rollback-${Date.now()}-${C}`),Ge("connecting")),{ok:!1,action:"pause",deviceId:C,title:R,error:an?.error||"video-capture-pause-failed"};const Ln=String(Xe.current[C]||"");if(Ln!==Ve&&Ln!==an.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:R,error:"Pause ownership changed before confirmation."};const Ks=bn(),Wc=Ks&&At.current?.deviceId===C?At.current:Be,tr=yt.current.get(C);return tr&&(tr.previousControlOwner=Wc),Ks&&At.current?.deviceId===C&&(At.current=null),Ks&&(Re.current=null,qe(null)),pn(C,an.pauseToken),Ks&&Ge("paused"),an.ok===!1||an.captureStopConfirmed!==!0?(rn(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:an.stopError||an.error||"Client capture shutdown was not confirmed."}):(rn(C,!1),{ok:!0,action:"pause",deviceId:C,title:R})}catch(an){return rn(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:R,error:an instanceof Error?an.message:String(an)}}}const Y=yt.current.get(C),ee=Y?.previousControlOwner||null,ie=de===C&&(ee!==null||dr.current?.deviceId===C||Ee==="paused"),re=ie?Wn.current:0;try{ya(C,!1);const Ve=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:E})},X);if(Ve?.ok===!1)throw new Error(Ve.error||"video-capture-resume-failed");if(String(Xe.current[C]||"")!==E)return{ok:!1,action:"resume",deviceId:C,title:R,error:"Resume ownership changed before confirmation."};const Be=yt.current.get(C)||Y,Ue=Be?.previousControlOwner||ee,gt=ie&&pw({deviceId:C,requestTransitionGeneration:re,currentTransitionGeneration:Wn.current,actualControlOwner:At.current});if(pn(C,""),rn(C,!1),yt.current.delete(C),gt){const bn=++Wn.current;ba.current="";const Tt=Cg(C,bn,{sessionId:m.sessionId||Ue?.sessionId,monitorIndex:js(m,sn[C]??Be?.monitorIndex)});At.current=Tt,Br(Tt),wa.current="",ko.current=null,Re.current=null,qe(null),at(""),jt(""),ke(!1),ua("control",C);const an=`control-video-resume-${bn}-${C}`;_e(an),Qe(C),Ge("connecting")}else ua("wall",C);return{ok:!0,action:"resume",deviceId:C,title:R}}catch(Ve){return _t.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:R,error:Ve instanceof Error?Ve.message:String(Ve)}}},Oc=async()=>{if(ws.length===0){Oe("Select one or more Clients before pausing video.");return}if(Ia.length===0){Oe(vl);return}if(en)return;const m=Ia.some(C=>{const R=String(Xe.current[C.deviceId]||"");return!R||R.startsWith("pending:")||mt[C.deviceId]===!0}),x=Ia.filter(C=>{const R=String(Xe.current[C.deviceId]||"");return m?!R||R.startsWith("pending:")||mt[C.deviceId]===!0:!!R});if(x.length===0){Oe(m?"Selected Clients are already paused.":"Selected Clients are already playing.");return}U("video");try{const C=await Promise.all(x.map(re=>km(re,m)));V();const R=C.filter(re=>re.ok&&!re.skipped),E=C.filter(re=>!re.ok&&re.unconfirmed),G=C.filter(re=>!re.ok&&!re.unconfirmed),Y=Ia.length-x.length+C.filter(re=>re.skipped).length,ee=ws.length-Ia.length,ie=m?"pause":"resume";if(G.length>0||E.length>0){const re=G.slice(0,2).map(Ve=>`${Ve.title}: ${Ve.error||"unknown error"}`).join(" · ");Oe([`Video ${ie} completed for ${R.length}/${x.length} Clients.`,E.length>0?`${E.length} Client capture stop${E.length===1?"":"s"} remain unconfirmed.`:"",re,ee>0?`${ee} selected Client${ee===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Oe([`Video ${m?"paused":"resumed"} for ${R.length} Client${R.length===1?"":"s"}.`,Y>0?`${Y} already ${m?"paused":"playing"}.`:"",ee>0?`${ee} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{U("")}},Mm=m=>{const x=m instanceof Error?m.message:String(m);return/remote-actions-disabled|remote-access-blocked-by-settings/i.test(x)?"Remote access is blocked. Change Settings > Remote Access > Access mode first.":/power-actions-disabled|allowPowerActions-blocked-by-settings/i.test(x)?"Power actions are off. Turn on Settings > Remote Access > Power actions first.":/agent-tool-capability-unavailable|unsupported-agent-operation/i.test(x)?"This Client needs a newer LiveDesk Client for power actions.":/device-not-connected|404 device-not-found/i.test(x)?"The Client disconnected before the action could be sent.":x},Dl=async m=>{if(!De||en)return;const x=De,R={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[m];if(window.confirm(`${R} ${Pa(x)}? Unsaved work on that computer may be lost.`)){U(m),Oe(`Sending ${R.toLowerCase()} request to ${Pa(x)}...`);try{const E=await rt(`/api/remote/devices/${encodeURIComponent(x.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:m})},X);if(!E.ok)throw new Error(E.error||"The remote action could not be sent.");Oe(`${R} request sent to ${Pa(x)}.`,"success"),V()}catch(E){Oe(Mm(E),"error")}finally{U("")}}},of=async(m,x,C="files")=>{const R=m.filter(ee=>ee.file.size>=0);if(R.length===0)return{files:0,bytes:0};if(!Xt)throw new Error(vl);if(x.length===0)throw new Error("Select at least one connected Client.");const E=crypto.randomUUID(),G=R.reduce((ee,ie)=>ee+ie.file.size,0);let Y=0;di({id:E,status:"reading",progress:1,message:`Preparing ${R.length} ${C}`});try{for(let ee=0;ee<R.length;ee+=1){const ie=R[ee],re=ie.file,Ve=Math.max(1,Math.ceil(re.size/Fg));for(let Be=0;Be<Ve;Be+=1){const Ue=Be*Fg,gt=Math.min(re.size,Ue+Fg),bn=re.size===0?new ArrayBuffer(0):await re.slice(Ue,gt).arrayBuffer(),Tt=Be===Ve-1;di({id:E,status:"sending",progress:Math.max(2,Math.min(98,Math.round(Y/Math.max(1,G)*96))),message:`${ee+1}/${R.length} ${ie.relativePath}`});const an=await rt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:E,deviceIds:x,remoteDirectory:Wr.trim(),name:re.name,relativePath:ie.relativePath,size:re.size,type:re.type,lastModified:re.lastModified,offset:Ue,totalBytes:re.size,final:Tt,dataBase64:cL(bn)})},X);if(!an.ok||an.queued!==x.length)throw new Error(an.error||`file-chunk-not-queued-${an.queued}/${x.length}`);Y+=bn.byteLength,await new Promise(Ln=>window.setTimeout(Ln,0))}}return di({id:E,status:"queued",progress:100,message:`Sent ${R.length} file${R.length===1?"":"s"} to ${x.length} Client${x.length===1?"":"s"}`}),window.setTimeout(()=>{di(ee=>ee?.id===E&&ee.status==="queued"?null:ee)},4500),{files:R.length,bytes:G}}catch(ee){throw di({id:E,status:"failed",progress:100,message:ee instanceof Error?ee.message:String(ee)}),ee}},lf=async m=>{const x=In.length>0?In.map(C=>C.deviceId):De?[De.deviceId]:[];try{await of(Ox(m),x)}catch(C){Oe(C instanceof Error?C.message:String(C))}},Am=async m=>{try{await of(Ox(m),Ca)}catch(x){Oe(x instanceof Error?x.message:String(x))}};d.useEffect(()=>{Cu.current=!1},[]);const cf=m=>{m.preventDefault(),m.stopPropagation(),zd(!1),lf(m.dataTransfer.files)},$n=async(m="ltd")=>{if(!n){Oe("Sign in with Google before checkout.");return}if(J&&m===Ut){Oe("LiveDesk license is already active.");return}if(J&&Ut==="pro"){Oe("LiveDesk Pro is already active.");return}gn("checkout");try{const{data:x,error:C}=await $t.functions.invoke("dodo-checkout",{body:{plan:m}});if(C)throw C;if(!x?.checkout_url)throw new Error("Checkout function did not return a checkout URL.");window.location.assign(x.checkout_url)}catch(x){Oe(x instanceof Error?x.message:String(x)),gn("")}},ta=qI(),uf=WI(),Yu=bl.filter(m=>Mn.has(m)).length,Xu=kl==="open"&&Xi.sampleMs>0?`${Xi.framesPerSecond.toFixed(1)} fps`:kl,Ke=De?dt?Sl.get(De.deviceId):Mn.get(De.deviceId):void 0,ao=De?js(De,sn[De.deviceId]):0,Nm=De?KI(De):[],Zu=typeof Ke?.monitorIndex=="number"?qf(Ke.monitorIndex,Math.max(1,Ke.monitorCount||1)):ao,df=(Ke&&Zu===ao?sC(Ke):null)||(De?rC(De,ao):null);df&&`${df.width}${df.height}`;const Go=De?la(dt?"control":"wall",De.deviceId):"",oa=Go?mu[Go]:void 0,wr=Go?dl[Go]:void 0,kt=wr?.lastInfo,Tm=oa&&oa.sampleMs>0?`${oa.framesPerSecond.toFixed(1)} fps`:"waiting";oa&&`${oa.totalFrames}${Tm}`,wr&&wr.sampleMs>0&&`${wr.framesPerSecond.toFixed(1)}`,wr&&wr.sampleMs>0&&`${wr.changedFramesPerSecond.toFixed(1)}`,kt&&(`${kt.frameSeq}${kt.decoderLabel}${kt.queueSize}${kt.renderQueueSize}${kt.droppedForLatency}${kt.decoderFlushCount}${kt.decoderTimestampFallbacks}${kt.decoderInputCount}${kt.decoderOutputCount}`,kt.visualChanged),kt&&`${Math.round(kt.queuedForMs)}${Math.round(kt.decodedForMs)}${Math.round(kt.scheduledForMs)}${kt.drawMs.toFixed(1)}`,kt?.targetPaintIntervalMs&&`${kt.targetPaintIntervalMs.toFixed(1)}${(1e3/kt.targetPaintIntervalMs).toFixed(1)}`,wr&&`${wr.decoderInputFps.toFixed(1)}${wr.decoderOutputFps.toFixed(1)}`,kt?.canvasPresentation,kt&&`${kt.interactiveBufferWaitCount}${Math.round(kt.interactiveBufferWaitMs)}${kt.interactiveQueueDrainCount}`,oa&&(Ke?.frameMode==="mode5-lzo-delta"?`${Wf(oa.averageFrameBytes)}${Ke.deltaVisualTileCount||0}${Ke.deltaRefreshTileCount||0}${Ke.deltaTotalTiles||0}`:`${Wf(oa.averageFrameBytes)}${Math.round(oa.tinyFrameRatio*100)}${Math.round(oa.repeatedFrameRatio*100)}`),oa&&oa.sourceSendSampleCount>0&&`${oa.sourceSendAverageMs.toFixed(1)}${oa.sourceSendP95Ms.toFixed(1)}`,Tx(oa),Tx(wr),oa&&wr&&`${Rx(oa)}${Rx(wr)}`,Ke?Ke.frameMode||Ke.mode||Ke.codec||Ke.mimeType:dt?_n.frameMode:wt.frameMode,dt?_n.frameMode:wt.frameMode,Ke?`${Ke.width}${Ke.height}${Wf(Ke.byteLength)}`:dt?`${vs.maxWidth}${vs.maxHeight}`:`${wt.maxWidth}${wt.maxHeight}`,Ke&&`${Ke.isKeyFrame?"key":String(Ke.chunkType||"delta")}`,Ke&&Ke.monitorCount&&((Ke.monitorIndex??0)+1,`${Ke.monitorCount}`),Ke&&[`src ${Math.round(Ke.sourceGapMs||0)}ms`,`gap ${Math.round(Ke.agentSendGapMs||0)}ms`,`tx ${Math.round(Ke.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ke.agentPaceMs||0)}ms`,`queue ${Math.round(Ke.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ke.agentFrameAgeMs||0)}ms`,Ke.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ke.hubPacketTransitAgeMs))}ms`:"",Ke.droppedByAgent?`drop ${Ke.droppedByAgent}`:"",Ke.hubIngressDropped?`ingress-drop ${Ke.hubIngressDropped}`:"",Ke.hubClientDropped?`ws-drop ${Ke.hubClientDropped}`:"",Ke.captureStageMs?`capture ${Math.round(Ke.captureStageMs)}ms`:"",Ke.requestedFps?`req ${Math.round(Ke.requestedFps)}fps`:"",Ke.effectiveFps?`eff ${Math.round(Ke.effectiveFps)}fps`:"",Ke.captureAverageMs?`avg ${Math.round(Ke.captureAverageMs)}ms`:"",Ke.captureP95Ms?`p95 ${Math.round(Ke.captureP95Ms)}ms`:"",Ke.slowFrameCount?`slow ${Math.round(Ke.slowFrameCount)}`:"",Ke.captureHelperRestarts?`helper ${Math.round(Ke.captureHelperRestarts)}`:"",Ke.convertMs?`rgb565 ${Math.round(Ke.convertMs)}ms`:"",Ke.compressMs?`lzo ${Math.round(Ke.compressMs)}ms`:"",Ke.captureSourceSerial?`cap #${Ke.captureSourceSerial}`:"",Ke.captureSourceSkipped?`cap skip ${Ke.captureSourceSkipped}`:"",Ke.frameMode==="mode5-lzo-delta"?`tiles ${Ke.deltaVisualTileCount||0}+${Ke.deltaRefreshTileCount||0}/${Ke.deltaTotalTiles||0}@${Ke.deltaTileSize||0}`:"",Ke.platformProfile||Ke.hardwareEncoder||"-",Ke.atlasComposeMs?`atlas ${Ke.atlasComposeMs.toFixed(1)}ms`:"",Ke.atlasPoolStarved?`pool ${Ke.atlasPoolStarved}`:"",Ke.atlasTileCount?`tiles ${Ke.atlasReadyTiles||0}/${Ke.atlasTileCount}`:"",Ke.atlasInputRevision?`input #${Ke.atlasInputRevision}`:"",Ke.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ke.atlasSourceMaxAgeMs)}ms`:"",kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=vx?`feedback ${Math.round(kt.inputFeedbackMs)}ms`:"",Ke.contentHash?`enc ${Ke.contentHash.slice(0,6)}`:"",kt?.visualHash?`pix ${kt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Ou==="open"&&[`${Gs.sentPerSecond.toFixed(1)} hz`,Gs.lastInputSeq>0?`rtt ${Math.round(Gs.lastRoundTripMs)}ms`:"",Gs.lastInputSeq>0?`apply ${Gs.lastAgentApplyMs.toFixed(1)}ms`:"",Gs.droppedPerSecond>0?`drop ${Gs.droppedPerSecond.toFixed(1)}/s`:"",Gs.bufferedAmount>0?`buf ${Wf(Gs.bufferedAmount)}`:"",Gs.lastInputType||"ready"].filter(Boolean).join(" / "),kt?.inputFeedbackMs!==void 0&&kt.inputFeedbackAt!==void 0&&performance.now()-kt.inputFeedbackAt<=vx&&[kt.inputFeedbackExact?"exact":"estimated",kt.inputFeedbackInputType||"",`total ${Math.round(kt.inputFeedbackMs)}ms`,kt.inputFeedbackAgentApplyMs!==void 0?`apply ${kt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",kt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(kt.inputFeedbackApplyToCaptureMs)}ms`:"",kt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(kt.inputFeedbackInputToFrameMs)}ms`:"",kt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(kt.inputFeedbackFrameToPaintMs)}ms`:"",kt.inputFeedbackSampleCount?`p50 ${Math.round(kt.inputFeedbackP50Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`p95 ${Math.round(kt.inputFeedbackP95Ms||0)}ms`:"",kt.inputFeedbackSampleCount?`n=${kt.inputFeedbackSampleCount}`:"",`input #${kt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ke&&`${Ke.frameSeq}${u0(Ke.receivedAt||Ke.capturedAt)}`;const ro=Math.max(0,Xi.bytesPerSecond*8/1e6),Ju={activeTool:Nt,audioError:qu,audioMode:Je,audioState:Uu,audioStats:An,lastAudioFrame:nf,selectedAudioCaptureStreamId:$u,controlFrames:Sl,controlInputReady:Vs,controlMode:ze,controlPresentationReady:Od,controlSessionDeviceId:de,controlSessionFrameReady:me,controlSessionState:Ee,controlStreamBinding:pe,devices:W,documentPresentationVisible:Ta,focusedDeviceId:Se,frames:Mn,localFeatureAccess:Xt,quickActionBusy:en,selectedDeviceId:De?.deviceId||"",selectedIds:we,showControlFocus:dt,videoCaptureStopUnconfirmedByDeviceId:mt,videoCapturePausedDeviceIds:St,wallPresentationReadyDeviceIds:xo},ed=d.useRef(Ju);ed.current=Ju,d.useEffect(()=>{if(!du.current)return;const m=window,x=ee=>{if(!ee)return null;const ie=ee.sourceGapMs,re=ie==null||ie===""?null:Number.isFinite(Number(ie))?Number(ie):null,Ve=ee;return{deviceId:ee.deviceId,sessionId:ee.sessionId||"",streamId:ee.streamId||"",commandId:ee.commandId||"",captureGeneration:Number(ee.captureGeneration||0),monitorIndex:Number(ee.monitorIndex||0),streamPurpose:ee.streamPurpose||"",frameSeq:Number(ee.frameSeq||0),frameMode:ee.frameMode||"",mimeType:ee.mimeType||"",currentGenerationVerified:Ve.currentGenerationVerified===!0,receivedAt:Ve.receivedAt||"",capturedAt:Ve.capturedAt||"",sourceGapMs:re,inputFeedbackEventId:String(ee.inputFeedbackEventId||""),inputFeedbackInputSeq:Number(ee.inputFeedbackInputSeq||0),inputFeedbackIssuedAtEpochMs:Number(ee.inputFeedbackIssuedAtEpochMs||0),inputFeedbackAgentApplyMs:Number(ee.inputFeedbackAgentApplyMs||0),inputFeedbackApplyToCaptureMs:Number(ee.inputFeedbackApplyToCaptureMs||0)}},C=ee=>{if(!ee)return null;const ie=window.getComputedStyle(ee),re=ee.getBoundingClientRect(),Ve=Math.max(0,Math.min(re.right,window.innerWidth)-Math.max(re.left,0)),Be=Math.max(0,Math.min(re.bottom,window.innerHeight)-Math.max(re.top,0)),Ue=Number(ie.opacity),gt=ee.isConnected&&ie.display!=="none"&&ie.visibility!=="hidden"&&ie.visibility!=="collapse"&&Number.isFinite(Ue)&&Ue>0&&re.width>0&&re.height>0&&Ve>0&&Be>0;return{connected:ee.isConnected,userVisible:gt,width:Math.max(0,Number(ee.width||0)),height:Math.max(0,Number(ee.height||0)),css:{display:ie.display,visibility:ie.visibility,opacity:Number.isFinite(Ue)?Ue:0},rect:{left:re.left,top:re.top,right:re.right,bottom:re.bottom,width:re.width,height:re.height,viewportIntersectionWidth:Ve,viewportIntersectionHeight:Be},codec:up(ee)}},R=(ee,ie)=>{const re=Ps.current.get(la(ee,ie));return re?{bindingKey:re.bindingKey||"",totalFrames:re.totalFrames,totalChangedFrames:re.totalChangedFrames,lastFrameSeq:Number(re.lastFrameSeq||0),lastPaintAgeMs:re.lastAt===void 0?-1:Math.max(0,performance.now()-re.lastAt),lastInfo:re.lastInfo?{frameSeq:Number(re.lastInfo.frameSeq||0),decoderInputCount:Number(re.lastInfo.decoderInputCount||0),decoderOutputCount:Number(re.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(re.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(re.lastInfo.droppedForLatency||0),visualChanged:re.lastInfo.visualChanged===!0,inputFeedbackExact:re.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(re.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(re.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(re.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(re.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:bx,inputFeedbackTargetMinSamples:wx,inputFeedbackOnTarget:re.lastInfo.inputFeedbackExact===!0&&Number(re.lastInfo.inputFeedbackSampleCount||0)>=wx&&Number(re.lastInfo.inputFeedbackP95Ms)<bx}:null}:null},E=(ee,ie)=>{if(!ee)return null;if(ie==="wall-visible"){const Ve=Ps.current.get(la("wall",ee));return Ve?{bindingKey:Ve.bindingKey||"",total:Ve.totalFrames,lastFrameSeq:Number(Ve.lastFrameSeq||0),lastPaintAgeMs:Ve.lastAt===void 0?-1:Math.max(0,performance.now()-Ve.lastAt)}:null}if(ie!=="control-visible"&&ie!=="wall-reuse-visible")return null;const re=fu.current.get(`${ie}:${ee}`);return re?{bindingKey:re.bindingKey,total:re.totalPaints,lastFrameSeq:re.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-re.lastPaintAt)}:null},G=(ee,ie)=>{const re=E(ee,ie);return re?{bindingKey:re.bindingKey,totalPaints:re.total,lastPaintAgeMs:re.lastPaintAgeMs,lastFrameSeq:re.lastFrameSeq}:null},Y={readPresentationCounter(ee,ie){return E(String(ee||""),ie)},snapshot(ee,ie={}){const re=String(ee||""),Ve=ie.includeHistory===!0,Be=Math.max(0,Number(ie.presentationAfterSequence||0)),Ue=ed.current,gt=Ue.devices.find(xr=>xr.deviceId===re)?.liveCapturePause,bn=String(Xe.current[re]||""),Tt=cn.current.get(re)||null,an=kn.current.get(re)||null,Ln=Zn.current.get(re)||null,Ks=q1(),Wc=W1(),tr={frameStats:pu.current===null?0:1,wallRecovery:ji.current===null?0:1,controlWarm:ds.current===null?0:1,controlWallDownshift:Qr.current===null?0:1},od=ri.current?.deviceId===re?ri.current:null,Qo=fm.current.get(re)||null;return{capturedAt:Date.now(),deviceId:re,activeTool:Ue.activeTool,documentPresentationVisible:Ue.documentPresentationVisible,showControlFocus:Ue.showControlFocus,selectedDeviceId:Ue.selectedDeviceId,focusedDeviceId:Ue.focusedDeviceId,selectedDeviceIds:[...Ue.selectedIds],localFeatureAccess:Ue.localFeatureAccess,quickActionBusy:Ue.quickActionBusy,audioMode:Ue.audioMode,audioState:Ue.audioState,audioError:Ue.audioError,audioCaptureStreamId:Ue.selectedAudioCaptureStreamId,audioFrame:Ue.lastAudioFrame?{deviceId:Ue.lastAudioFrame.deviceId,streamId:Ue.lastAudioFrame.streamId,frameSeq:Number(Ue.lastAudioFrame.frameSeq||0),mimeType:Ue.lastAudioFrame.mimeType,sampleRate:Number(Ue.lastAudioFrame.sampleRate||0),channels:Number(Ue.lastAudioFrame.channels||0),byteLength:Number(Ue.lastAudioFrame.byteLength||0)}:null,audioStats:{...Ue.audioStats},videoCapturePausePhase:bn?bn.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:Ue.videoCaptureStopUnconfirmedByDeviceId[re]===!0,authoritativeLiveCapturePause:gt?{phase:gt.phase||"",captureStopConfirmed:gt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(gt.stopAttemptCount||0)),stopError:gt.stopError||""}:null,controlMode:Ue.controlMode,controlSessionDeviceId:Ue.controlSessionDeviceId,controlSessionState:Ue.controlSessionState,controlSessionFrameReady:Ue.controlSessionFrameReady,controlPresentationReady:Ue.controlPresentationReady,controlInputReady:Ue.controlInputReady,controlConnection:Qo?{...Qo}:null,pendingControlConnection:od?{...od,elapsedMs:Math.max(0,performance.now()-od.startedAt)}:null,videoCapturePaused:Ue.videoCapturePausedDeviceIds.has(re),wallPresentationReady:Ue.wallPresentationReadyDeviceIds.has(re),controlBinding:Ue.controlStreamBinding?.deviceId===re?{...Ue.controlStreamBinding}:null,actualControlOwner:At.current?.deviceId===re?{...At.current}:null,wallCapturePauseOwner:dr.current?.deviceId===re?{...dr.current}:null,frameSubscriptions:Ks,audioSubscriptions:Wc,presentationTimers:{...tr,total:Object.values(tr).reduce((xr,Yo)=>xr+Yo,0)},wallFrame:x(Ue.frames.get(re)),controlFrame:x(qa.current.get(re)||Ue.controlFrames.get(re)),wallPaint:R("wall",re),controlPaint:R("control",re),controlVisiblePaint:G(re,"control-visible"),wallReuseVisiblePaint:G(re,"wall-reuse-visible"),presentationPaintSequence:dm.current,presentationPaintEvents:Ve?_d.current.filter(xr=>xr.deviceId===re&&xr.sequence>Be).sort((xr,Yo)=>xr.sequence-Yo.sequence).map(xr=>({...xr})):[],wallCanvas:C(Tt),controlDecodeCanvas:C(an),controlPresentationCanvas:C(Ln),globalCodec:up(void 0,{includeLifecycleEvents:Ve})}}};return m.__liveDeskTransmissionProbe=Y,()=>{m.__liveDeskTransmissionProbe===Y&&delete m.__liveDeskTransmissionProbe}},[]);const Vo=d.useCallback(()=>{ir(!0),Ds(Date.now()),V(),Dn.current!==null&&window.clearTimeout(Dn.current),Dn.current=window.setTimeout(()=>{Dn.current=null,Ds(Date.now()),ir(!1)},650)},[V]),td=d.useCallback(()=>{if(En){qr(!1);return}Pn(!1),qr(!0),Vo()},[Vo,En]),Bc=d.useCallback(()=>{if(Ht){Pn(!1);return}qr(!1),Pn(!0),Vo()},[Ht,Vo]),nd=d.useCallback(()=>{if(Ha){sr(!1);return}sr(!0),Vo()},[Ha,Vo]),ff=En||Ht,ad=JSON.stringify(pt.filter(m=>m.connected).map(m=>m.deviceId).sort());d.useEffect(()=>{if(!ff)return;const m=JSON.parse(ad);if(m.length===0){ir(!1);return}const x=new AbortController,C=[];let R=!1;return Dn.current!==null&&(window.clearTimeout(Dn.current),Dn.current=null),ir(!0),Ds(Date.now()),Promise.allSettled(m.map(E=>rt(`/api/remote/devices/${encodeURIComponent(E)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:x.signal,timeoutMs:1500},X))).then(()=>{R||[500,1800,4500].forEach((E,G,Y)=>{const ee=window.setTimeout(()=>{R||(V(),Ds(Date.now()),G===Y.length-1&&ir(!1))},E);C.push(ee)})}),()=>{R=!0,x.abort();for(const E of C)window.clearTimeout(E)}},[X,V,ad,ff]);const Ko=new Map,zr=new Map;if(En||Ht||Ha)for(const m of pt){const x=m.deviceId,C=dt&&de===x,E=la(C?"control":"wall",x),G=C?Sl.get(x):Mn.get(x),Y=C?kn.current.get(x)||Zn.current.get(x)||null:cn.current.get(x)||(Kt?Er.current:null),ee={device:m,frame:G,receiveStat:mu[E],paintStat:dl[E],codec:Y?up(Y):{},selectedMonitorIndex:js(m,sn[x]),control:C,controlInputReady:C&&Vs,controlBinding:C&&pe?.deviceId===x?pe:void 0,hubRelay:z?.relay,capturePaused:St.has(x),capturePauseConfirmed:m.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:m.liveCapturePause?.stopError||"",clientHeartbeatMs:Number(z?.heartbeatMs||5e3),now:Date.now()},ie=["open","playing","silent"].includes(Uu),re=An.nativeCallbackDiagnosticsAvailable&&(An.nativeRejectedCallbackCount>0||An.nativeCurrentnessDropCount>0),Ve=ie&&!re,Be=x===De?.deviceId&&Je?{id:"browser-remote-audio",state:Ve?"ok":"warning",label:Ve?"Remote audio is healthy":"Remote audio needs attention",detail:An.lastUpdatedAt>0?[Uu,`context ${An.audioContextState}`,`queue ${Math.round(An.queuedMs)}ms`,`packet ${Math.round(An.lastPacketAgeMs)}ms`,`capture ${An.captureHealthy?"healthy":An.captureAwaitingCurrentPcm?"awaiting PCM":"down"}`,An.backendKind?`backend ${An.backendKind}`:"backend unknown",An.helperRequired?`helper ${An.helperAlive&&An.helperPid>0?`pid ${An.helperPid}`:"missing"}`:"helper N/A",`drop ${An.drops}`,`restart ${An.automaticRestarts}`,An.nativeCallbackDiagnosticsAvailable?`native reject ${An.nativeRejectedCallbackCount}`:"native callback diagnostics unknown",An.nativeCallbackDiagnosticsAvailable?`native stale ${An.nativeCurrentnessDropCount}`:"",An.nativeLastDropReason?`native reason ${An.nativeLastDropReason}`:"",nf?`frame #${nf.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(En||Ha){const Ue=UD(ee);En&&Be&&Ue.push(Be),Ko.set(x,Ue)}if(Ht){const Ue=qD(ee);Be&&Ue.push(Be),zr.set(x,Ue)}}const mf=Ha?WD({status:z||{},deviceDiagnostics:[...Ko.values()],codec:up(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Xi}):[],Rm=xl?.atlasReadyTiles??Yu,rd=xl?.atlasTileCount??Yu,yi=Rm===rd?`${rd} tiles`:`${Rm}/${rd} tiles`,pf=Ja.length>0;dt?`${Xu}${ro.toFixed(ro>=10?0:1)}`:pf?`${yi}${Xu}${ro.toFixed(ro>=10?0:1)}`:`${Yu}${Xu}${ro.toFixed(ro>=10?0:1)}`;const sd=In.length,Hc=dt?De?Pa(De):"No Client":sd===0?"No Client":sd>1?`${sd} selected`:De?Pa(De):"No Client",zc=dt?[De?.deviceId].filter(m=>!!m):In.map(m=>m.deviceId),qt=jd[ln]||jd.en,id=qt.sync||jd.en.sync,Sh=r||$?"checking":J?Ut==="pro"?"Pro LTD active":`Plus LTD ${pt.length}/${Uf}`:gl?`Free ${pt.length}/${$f}`:`Upgrade ${pt.length}/${$f}`,$c=J?Ut==="pro"?"Pro active":"Upgrade to Pro LTD":n?Ct==="checkout"?"Opening checkout":Ut==="ltd"?"Buy Pro LTD":"Buy Plus LTD":Ct==="auth"?"Opening Google":"Sign in to buy",so=Ut==="pro"||Ct==="checkout"||Ct==="auth"||r||$,hf=n?.user?.user_metadata,Uc=Bx(hf,"avatar_url","picture"),bi=Bx(hf,"full_name","name")||n?.user?.email||"Google",Ms=bi.slice(0,1).toUpperCase(),jm=z?.started?"Local app ready":"Start LiveDesk",gf=o?.active?"Published":n?"Not published":"Sign in required",Em=/^\d{6}$/.test(z?.pairingPin||"")?z?.pairingPin:"------",wi=m=>{if(typeof window<"u"&&(m==="support"?window.history.pushState({},"","/support"):Nt==="support"&&window.history.pushState({},"","/")),m==="control"){const x=Sa||Wi;if(x&&(Pc(x.deviceId),Ga(!1),Pe(x.deviceId)),bt(m),!Xt){We(!1),Oe(vl);return}We(!0);return}m==="wall"&&Ls(x=>x+1),bt(m),We(!1)},as=Ct==="update"||Bt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes(z?.update?.state||""),qc=!!(z?.update?.updateAvailable&&z.update.canApply||as||Bt?.error||!z&&Bt),io=GM(ln),As=d.useCallback(m=>{if(!Bt?.targetIds.includes(m))return;const x=z?.update?.operationId===Bt.operationId?z.update.targets?.find(C=>C.deviceId===m):void 0;switch(x?.state){case"completed":return yo[kx(Bt.operationId,x)]?{state:"updated",label:"Updated"}:void 0;case"failed":return{state:"failed",label:"Update failed",error:x.error};case"pending-offline":return{state:"offline",label:"Waiting for reconnect"};case"queued":return Bt.stage==="updating"?{state:"queued",label:"Queued"}:void 0;case"waiting":return Bt.stage==="updating"?x.candidateSince?{state:"updating",label:"Verifying restart..."}:{state:"updating",label:"Restarting..."}:void 0;default:return Bt.stage==="updated"?{state:"updated",label:"Updated"}:Bt.stage==="updating"?{state:"updating",label:"Verifying..."}:void 0}},[z?.update,yo,Bt]),Bn=T&&!!n&&K&&!z?.started,vf=r?"checking":z?.started?"online":Bn?q?"retrying":"connecting":"offline",Dm=r?"Checking Hub":z?.started?`${pt.length} online`:Bn?q?"Hub offline":"Connecting Hub":n?"Hub offline":"Sign in required",fa=z?.deviceName||(Bn?q?"Retrying automatically…":"Trying saved Hub routes…":q?"Desktop Hub unavailable":"Remote management"),Im=T&&g&&!n;return i.jsxs("main",{className:`app-shell ${T?"mobile-console-shell":""}`,"data-mobile-auth-required":Im?"true":void 0,"data-mobile-standalone":T&&j?"true":void 0,"data-mobile-ios":T&&k.isIos?"true":void 0,"data-mobile-android":T&&k.isAndroid?"true":void 0,children:[i.jsxs("aside",{className:"tool-rail","aria-label":"LiveDesk tools",children:[i.jsx("div",{className:"rail-brand",title:"LiveDesk",children:i.jsx(d0,{size:25})}),i.jsx("nav",{className:"rail-tools",children:gL.map(m=>{const x=m.icon,C=qp(m.tooltip,ln);return i.jsxs("button",{className:`rail-tool ${m.id==="sync-server"?"sync-server hub-sync-trigger":""} ${Nt===m.id?"active":""} accent-${m.accent}`,onClick:()=>m.id==="sync-server"?wm():wi(m.id),"data-tooltip":m.id==="sync-server"&&nt?void 0:Zg(m.label,m.tooltip,ln),"aria-label":`${m.label}. ${C}`,type:"button",disabled:m.id==="sync-server"&&Ct==="host","aria-busy":m.id==="sync-server"&&Ct==="host","aria-expanded":m.id==="sync-server"?nt:void 0,"aria-haspopup":m.id==="sync-server"?"dialog":void 0,"aria-controls":m.id==="sync-server"&&nt?"hub-sync-popover":void 0,children:[m.id==="sync-server"&&Ct==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(x,{size:19}),i.jsx("span",{children:m.id==="sync-server"&&Ct==="host"?"Syncing…":m.label})]},m.id)})}),i.jsxs("div",{className:"rail-footer",children:[vL.map(m=>{const x=m.icon;return i.jsxs("button",{className:`rail-tool compact ${Nt===m.id?"active":""} accent-${m.accent}`,onClick:()=>wi(m.id),title:m.label,type:"button",children:[i.jsx(x,{size:18}),i.jsx("span",{children:m.label})]},m.id)}),i.jsxs("button",{className:`rail-tool compact local-settings ${hs?"active":""}`,onClick:()=>{bt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),or(!1),We(!1),go(!1)},title:"Settings",type:"button",children:[i.jsx(zp,{size:18}),i.jsx("span",{children:"Settings"})]}),i.jsxs("button",{className:`rail-account ${n?"signed-in":""}`,onClick:()=>{or(m=>!m)},disabled:r||Ct==="auth","aria-expanded":Ai,title:n?`Account: ${n.user?.email||bi}`:"Sign in with Google",type:"button",children:[n?Uc?i.jsx("img",{src:Uc,alt:bi,referrerPolicy:"no-referrer"}):i.jsx("span",{className:"avatar-fallback",children:Ms}):i.jsx(Ql,{size:18}),i.jsx("span",{children:n?"Account":"Google"})]}),Ai&&i.jsxs("section",{className:"account-popover",role:"dialog","aria-label":"LiveDesk account",children:[i.jsxs("div",{className:"account-popover-head",children:[i.jsx("div",{className:"account-popover-avatar",children:n&&Uc?i.jsx("img",{src:Uc,alt:bi,referrerPolicy:"no-referrer"}):n?i.jsx("span",{children:Ms}):i.jsx(Ql,{size:18})}),i.jsxs("div",{children:[i.jsx("strong",{children:n?bi:"Account"}),i.jsx("p",{children:n?.user?.email||"Not signed in"})]})]}),i.jsxs("dl",{className:"account-popover-facts",children:[i.jsx("dt",{children:"User"}),i.jsx("dd",{children:n?.user?.email||"Not signed in"}),i.jsx("dt",{children:"Network"}),i.jsx("dd",{children:jm}),i.jsx("dt",{children:"Access"}),i.jsx("dd",{children:gf}),i.jsx("dt",{children:"Plan"}),i.jsx("dd",{children:Sh}),i.jsx("dt",{children:"Ads"}),i.jsx("dd",{children:Ut==="free"?"Standard banner":"Removed"})]}),n?i.jsxs("button",{className:"account-popover-action",onClick:_c,disabled:Ct==="auth",type:"button",children:[i.jsx(qx,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:Uo,disabled:Ct==="auth",type:"button",children:[i.jsx(Ql,{size:16}),"Sign in with Google"]})]})]})]}),T&&N&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>A(!1),children:i.jsxs("section",{className:"mobile-pwa-guide",role:"dialog","aria-modal":"true","aria-labelledby":"mobile-pwa-guide-title",onClick:m=>m.stopPropagation(),children:[i.jsxs("header",{children:[i.jsx("span",{className:"mobile-pwa-guide-mark","aria-hidden":"true",children:i.jsx(e0,{size:20})}),i.jsxs("span",{children:[i.jsx("strong",{id:"mobile-pwa-guide-title",children:"Install LiveDesk on iPhone"}),i.jsx("small",{children:"Open without browser bars and tabs"})]}),i.jsx("button",{type:"button",onClick:()=>A(!1),"aria-label":"Close install guide",children:i.jsx(rr,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",k.browserName==="browser"?"the browser":k.browserName,"'s ",i.jsx("strong",{children:"Share"})," button."]}),i.jsxs("li",{children:["Tap ",i.jsx("strong",{children:"Add to Home Screen"}),"."]}),i.jsx("li",{children:k.isSafari?i.jsxs(i.Fragment,{children:["Turn on ",i.jsx("strong",{children:"Open as Web App"}),", then tap ",i.jsx("strong",{children:"Add"}),"."]}):i.jsxs(i.Fragment,{children:["Confirm the app name, then tap ",i.jsx("strong",{children:"Add"}),"."]})})]}),i.jsx("button",{className:"mobile-pwa-guide-done",type:"button",onClick:()=>A(!1),children:"Got it"})]})}),Im&&i.jsxs("section",{className:"mobile-console-auth","aria-labelledby":"mobile-console-auth-title",children:[i.jsx("span",{className:"mobile-console-auth-mark","aria-hidden":"true",children:i.jsx(ga,{size:26})}),i.jsx("h1",{id:"mobile-console-auth-title",children:r?"Checking your account":"Sign in to LiveDesk"}),i.jsx("p",{children:"Use the same Google account as your LiveDesk Hub."}),i.jsxs("button",{type:"button",onClick:()=>{Uo()},disabled:r||Ct==="auth","aria-busy":r||Ct==="auth",children:[r||Ct==="auth"?i.jsx($r,{className:"spin",size:19,"aria-hidden":"true"}):i.jsx(Ql,{size:19,"aria-hidden":"true"}),Ct==="auth"?"Opening Google…":r?"Checking sign-in…":"Sign in with Google"]}),i.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),Bn&&i.jsx("section",{className:"mobile-console-hub-connecting","aria-label":"LiveDesk Hub connection",children:i.jsxs("div",{className:"mobile-console-hub-connecting-card",role:"status","aria-live":"polite",children:[i.jsx($r,{className:"spin",size:34,"aria-hidden":"true"}),i.jsx("strong",{children:q?"LiveDesk Hub is offline":"Connecting to LiveDesk Hub"}),i.jsx("p",{children:q?"LiveDesk is retrying the saved direct and relay routes automatically.":"Trying the saved direct and relay routes…"}),q&&i.jsxs("button",{type:"button",onClick:()=>V(),children:[i.jsx(ou,{size:16,"aria-hidden":"true"}),"Try now"]})]})}),nt&&i.jsxs("section",{id:"hub-sync-popover",className:"client-hub-switch-popover hub-sync-popover",role:"dialog","aria-modal":"false","aria-labelledby":"hub-sync-title","aria-describedby":"hub-sync-description hub-sync-notice",children:[i.jsxs("header",{className:"client-hub-switch-head",children:[i.jsx("span",{className:"client-hub-switch-mark","aria-hidden":"true",children:i.jsx(mo,{size:19})}),i.jsx("span",{className:"client-hub-switch-eyebrow",children:io.eyebrow}),i.jsx("button",{className:"client-hub-switch-close",type:"button",onClick:()=>to(),"aria-label":io.closeLabel,children:i.jsx(rr,{size:17})})]}),i.jsx("h2",{id:"hub-sync-title",children:io.title}),i.jsx("p",{id:"hub-sync-description",children:io.description}),i.jsxs("p",{id:"hub-sync-notice",className:"client-hub-switch-notice",children:[i.jsx(ga,{size:16,"aria-hidden":"true"}),i.jsx("span",{children:io.restartNotice})]}),i.jsxs("div",{className:"client-hub-switch-actions",children:[i.jsx("button",{type:"button",onClick:()=>to(),children:io.cancel}),i.jsxs("button",{ref:vn,className:"primary",type:"button",onClick:xm,disabled:Ct==="host",children:[i.jsx(mo,{size:16}),io.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${gs&&!Is?"dock-open":""} ${dt?"control-stage":""} ${Ka?"agents-stage":""} ${Hi?"file-share-stage":""}`,children:[T&&i.jsxs("header",{className:"mobile-console-header",children:[i.jsxs("span",{className:"mobile-console-brand","aria-label":"LiveDesk mobile Console",children:[i.jsx("span",{className:"mobile-console-brand-mark",children:i.jsx(Jl,{size:18})}),i.jsxs("span",{children:[i.jsx("strong",{children:"LiveDesk"}),i.jsx("small",{children:"Mobile Console"})]})]}),i.jsxs("span",{className:`mobile-console-hub state-${vf}`,role:"status","aria-live":"polite",children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:Dm}),i.jsx("small",{children:fa})]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[g&&!j&&(b||k.isIos)&&i.jsx("button",{className:"mobile-console-install",onClick:()=>{B()},"aria-label":"Install LiveDesk app",title:"Install LiveDesk app",type:"button",children:i.jsx(Rp,{size:19,"aria-hidden":"true"})}),qc&&i.jsx("button",{className:"mobile-console-update",onClick:()=>{El()},disabled:as||!z?.update?.canApply,"aria-label":as?"LiveDesk update in progress":"Update LiveDesk","aria-busy":as,type:"button",children:as?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:18,"aria-hidden":"true"})})]})]}),i.jsxs("header",{className:"topbar",children:[i.jsxs("div",{className:"brand",children:[i.jsx("span",{className:"brand-mark",children:i.jsx(Jl,{size:18})}),i.jsxs("div",{className:"brand-copy",children:[i.jsx("h1",{children:"LiveDesk"}),i.jsx("p",{children:"Control wall for local machines"})]}),qc?i.jsxs("button",{className:"topbar-update-button",onClick:()=>{El()},title:Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:`Update LiveDesk to ${z?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,"aria-label":Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:as?"LiveDesk update in progress":`Update LiveDesk to ${z?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,type:"button",disabled:as||!z?.update?.canApply,"aria-busy":as,children:[as?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:19,"aria-hidden":"true"}),as&&z?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[z.update.completedCount||0,"/",z.update.targetCount]}):null]}):null]}),i.jsxs("div",{className:"topbar-tray",children:[Hi&&!dt&&i.jsxs("div",{className:"file-share-top-route","aria-label":"File distribution route",children:[i.jsxs("div",{children:[i.jsx(nu,{size:17}),i.jsxs("span",{children:[i.jsx("small",{children:"Source"}),i.jsx("strong",{children:"LiveDesk Hub"})]})]}),i.jsx(kv,{size:15}),i.jsx(Ik,{size:16}),i.jsxs("div",{children:[i.jsx("span",{className:"file-share-top-route-laptops",children:"▣ ▣ ▣"}),i.jsxs("span",{children:[i.jsx("small",{children:"Destination"}),i.jsxs("strong",{children:[Ui," Client",Ui===1?"":"s"]}),i.jsx("em",{children:Wr.trim()||"Desktop/LiveDeskFiles"})]})]})]}),gs&&!dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mx,{active:Ha,refreshing:Ha&&Rr,onClick:nd}),i.jsx(dx,{active:En,refreshing:En&&Rr,onClick:td}),i.jsx(fx,{active:Ht,refreshing:Ht&&Rr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(ux,{controller:Sc,onError:Oe}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control wall-cadence-control","aria-label":"Wall frame speed",children:pL.map(m=>i.jsx("button",{className:Cn===m.id?"active":"",onClick:()=>{qn(m.id),cr(m.fps),sL(m.id)},title:m.label+" Wall streaming ("+m.fps+" fps)","aria-pressed":Cn===m.id,type:"button",children:m.label},m.id))}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx("div",{className:"segmented-control","aria-label":"Wall view",children:hL.map(m=>i.jsx("button",{className:Gt===m.id?"active":"",onClick:()=>ra(m.id),type:"button",children:m.label},m.id))})]}),dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(mx,{active:Ha,refreshing:Ha&&Rr,onClick:nd}),i.jsx(dx,{active:En,refreshing:En&&Rr,onClick:td}),i.jsx(fx,{active:Ht,refreshing:Ht&&Rr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(ux,{controller:Sc,onError:Oe})]})]})]}),Ha&&gs&&i.jsx(ID,{items:mf,collectedAt:Zs,onClose:()=>sr(!1)}),Ud?i.jsxs("section",{className:"doc-page",lang:ln,dir:ln==="ar"?"rtl":"ltr",children:[i.jsxs("section",{className:"doc-hero",children:[i.jsxs("div",{className:"doc-hero-copy",children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Hp,{size:16}),qt.eyebrow]}),i.jsx("h2",{children:qt.title}),i.jsx("p",{children:qt.intro})]}),i.jsxs("label",{className:"doc-language-picker",children:[i.jsxs("span",{children:[i.jsx(Lk,{size:17}),qt.languageLabel]}),i.jsx("select",{value:ln,onChange:m=>il(m.target.value),children:bL.map(m=>i.jsx("option",{value:m.id,children:m.label},m.id))})]})]}),i.jsx("section",{className:"doc-grid",children:qt.sections.map((m,x)=>{const R=[mo,jp,Sb,ga,eh][x]||Hp;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(R,{size:19})}),i.jsxs("div",{children:[i.jsx("h3",{children:m.title}),i.jsx("p",{children:m.body}),i.jsx("ul",{children:m.points.map(E=>i.jsx("li",{children:E},E))})]})]},m.title)})}),id&&i.jsxs("section",{className:"doc-sync",children:[i.jsxs("div",{className:"doc-sync-head",children:[i.jsx(Sb,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:id.title}),i.jsx("p",{children:id.body})]})]}),i.jsx("ul",{children:id.points.map(m=>i.jsx("li",{children:m},m))})]}),i.jsxs("section",{className:"doc-firewall",children:[i.jsxs("div",{className:"doc-firewall-head",children:[i.jsx(ga,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:qt.firewall.title}),i.jsx("p",{children:qt.firewall.body})]})]}),i.jsx("ul",{children:qt.firewall.points.map(m=>i.jsx("li",{children:m},m))})]}),i.jsxs("section",{className:"doc-command-panel",children:[i.jsxs("div",{className:"doc-command-head",children:[i.jsx(jp,{size:20}),i.jsxs("div",{children:[i.jsx("h3",{children:qt.commands.title}),i.jsx("p",{children:qt.commands.body})]})]}),i.jsxs("div",{className:"doc-command-list",children:[qt.commands.manager&&i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.manager}),i.jsx("code",{children:uf}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(uf),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.primary}),i.jsx("code",{children:ta}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(ta),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]}),i.jsxs("div",{className:"doc-command-row",children:[i.jsx("span",{children:qt.commands.slot}),i.jsx("code",{children:`${ta} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(`${ta} 3`),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]})]})]})]}):Ka?i.jsx(ox,{hubUrl:X,devices:W}):Hi?i.jsx(IE,{hubUrl:X,devices:pt,localFeatureAccess:Xt,upgradeNotice:vl,remoteDirectory:Wr,onRemoteDirectoryChange:ol,targetMode:No,selectedTargetIds:Ea,onTargetModeChange:$d,onTargetToggle:m=>hl(x=>x.includes(m)?x.filter(C=>C!==m):[...x,m]),filePickerRef:To,folderPickerRef:gm,onBrowserFileImport:m=>{Am(m)},onBrowserFolderImport:m=>{Am(m)},onNotice:Oe,onTransferChange:m=>{if(!m){di(null);return}const x=m.state==="failed"||m.state==="partially-failed"||m.state==="cancelled"?"failed":m.state==="completed"?"queued":m.state==="sending"?"sending":"reading";di({id:m.id,status:x,progress:m.progress,message:m.message}),["completed","partially-failed","failed","cancelled"].includes(m.state)&&window.setTimeout(()=>di(C=>C?.id===m.id?null:C),4500)}}):Au?i.jsx(r0,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:Uo}):hs?i.jsx(YN,{hubUrl:X,runtimeRole:z?.runtimeRole||"hub",runtimeDeviceId:z?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:i.jsxs(XN,{children:[i.jsx("div",{className:"settings-section-grid",children:i.jsxs("section",{className:"settings-section-card settings-pairing-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"Pair a Client"}),i.jsx("h3",{children:"Connect another local PC"})]}),i.jsx(Ar,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Em}),i.jsxs("button",{className:"text-button ghost compact",onClick:Sm,disabled:!z?.started||Ct==="pin",type:"button",children:[i.jsx(nl,{size:15}),Ct==="pin"?"Creating":"New PIN"]})]})]})}),i.jsxs("section",{className:"settings-section-card",children:[i.jsxs("div",{className:"settings-section-heading",children:[i.jsxs("div",{children:[i.jsx("span",{children:"File transfer"}),i.jsx("h3",{children:"Client destination folder"})]}),i.jsx(Ad,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:Wr,onChange:m=>ol(m.target.value),placeholder:"Desktop/LiveDeskFiles"})]}),i.jsx("p",{className:"settings-help",children:"Blank uses Desktop/LiveDeskFiles on each Client."})]})]}),agent:i.jsx(JN,{hubUrl:X,showToast:Oe}),captureGallery:i.jsx(DD,{hubUrl:X,onToast:Oe})}):Mu?i.jsxs("section",{className:"pricing-page",children:[i.jsxs("header",{className:"pricing-header",children:[i.jsxs("div",{children:[i.jsxs("span",{className:"pricing-eyebrow",children:[i.jsx(Kg,{size:15})," LiveDesk plans"]}),i.jsx("h2",{children:"Choose the plan that fits your wall"}),i.jsx("p",{children:"Start free with a local screen wall. Upgrade when you need ad-free monitoring, more Clients, or commercial controls."})]}),i.jsx("button",{className:"pricing-close",onClick:()=>wi("wall"),title:"Close pricing",type:"button",children:i.jsx(rr,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:ju.name}),i.jsxs("small",{children:[pt.length,"/",DI(Io)," connected devices"]})]}),i.jsxs("div",{className:"pricing-cards","aria-label":"LiveDesk plans",children:[i.jsxs("article",{className:`pricing-plan-card ${Ut==="free"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsx("span",{className:"pricing-plan-badge free",children:"Free"}),i.jsx("strong",{children:"$0"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.free.audience}),i.jsx("h3",{children:"Monitor your local wall"}),i.jsx("p",{children:Xc.free.note}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," Up to ",$f," devices"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Standard ad-supported banner"]})]}),i.jsx("span",{className:"pricing-current-label",children:Ut==="free"?"Current plan":"Included for everyone"})]}),i.jsxs("article",{className:`pricing-plan-card featured ${Ut==="ltd"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge plus",children:[i.jsx(Pk,{size:14})," Plus"]}),i.jsx("strong",{children:"$5"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.ltd.audience}),i.jsx("h3",{children:"Ad-free monitoring"}),i.jsx("p",{children:"More room for personal computers without the standard banner."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," Up to ",Uf," devices"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," No standard ad banner"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," ",Xc.ltd.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>$n("ltd"):Uo,disabled:Ut!=="free"||Ct==="checkout"||Ct==="auth"||r||$,type:"button",children:[i.jsx(Vf,{size:16}),Ut==="free"?n?"Choose Plus":"Sign in for Plus":"Plus active"]})]}),i.jsxs("article",{className:`pricing-plan-card pro ${Ut==="pro"?"current":""}`,children:[i.jsxs("div",{className:"pricing-plan-topline",children:[i.jsxs("span",{className:"pricing-plan-badge pro",children:[i.jsx(ga,{size:14})," Pro"]}),i.jsx("strong",{children:"$15"})]}),i.jsx("p",{className:"pricing-plan-audience",children:Xc.pro.audience}),i.jsx("h3",{children:"For serious operations"}),i.jsx("p",{children:"Commercial-ready monitoring for larger studios, offices, and teams."}),i.jsxs("ul",{children:[i.jsxs("li",{children:[i.jsx(_a,{size:16})," 30+ Client walls"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," Commercial use included"]}),i.jsxs("li",{children:[i.jsx(_a,{size:16})," ",Xc.pro.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>$n("pro"):Uo,disabled:Ut==="pro"||Ct==="checkout"||Ct==="auth"||r||$,type:"button",children:[i.jsx(Vf,{size:16}),Ut==="pro"?"Pro active":n?"Choose Pro":"Sign in for Pro"]})]})]}),i.jsxs("section",{className:"pricing-includes",children:[i.jsxs("div",{children:[i.jsx(Ar,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ slots"})]}),i.jsxs("div",{children:[i.jsx(Hf,{size:17}),i.jsx("span",{children:"Focused control"}),i.jsx("strong",{children:"Local-first"})]}),i.jsxs("div",{children:[i.jsx(ig,{size:17}),i.jsx("span",{children:"Remote audio"}),i.jsx("strong",{children:"Available"})]}),i.jsxs("div",{children:[i.jsx(Ad,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(_a,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>$n(Ut==="ltd"?"pro":"ltd"):Uo,disabled:so,type:"button",children:[i.jsx(Vf,{size:18}),$c]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Is?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:hc,className:`screen-wall-panel ${yh?"drop-active":""}`,onClick:m=>{m.currentTarget===m.target&&qo()},onDragEnter:m=>{m.preventDefault(),zd(!0)},onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="copy"},onDragLeave:m=>{m.currentTarget===m.target&&zd(!1)},onDrop:cf,children:[Ja.length>0&&i.jsx("canvas",{ref:Gd,className:"atlas-source-canvas",width:yn?.width||1920,height:yn?.height||1080,"aria-hidden":"true"}),T&&gs&&!dt&&i.jsxs("section",{className:"mobile-console-selection","aria-label":"Selected computer actions",children:[i.jsxs("div",{className:"mobile-console-selection-copy",children:[i.jsx("span",{children:"Selected computer"}),i.jsx("strong",{children:Hc}),i.jsx("small",{children:De?`${De.platform||"Client"} · ${fo(De)} display${fo(De)===1?"":"s"}`:"Tap a computer below, then choose an action."})]}),i.jsxs("div",{className:"mobile-console-actions",role:"toolbar","aria-label":"Selected computer quick actions",children:[i.jsxs("button",{onClick:()=>De&&void no(De.deviceId),disabled:!bs||!!en,type:"button",children:[i.jsx(Hf,{size:17}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Je?"active":"",onClick:()=>{sf()},disabled:!Eu||!!en,"aria-pressed":Je,type:"button",children:[en==="audio"?i.jsx($r,{className:"spin",size:17}):i.jsx(ig,{size:17}),i.jsx("span",{children:"Audio"})]}),i.jsxs("button",{className:hr?"":"active",onClick:()=>{Oc()},disabled:Ia.length===0||!!en,"aria-pressed":!hr,type:"button",children:[en==="video"?i.jsx($r,{className:"spin",size:17}):hr?i.jsx(Cb,{size:17}):i.jsx(kb,{size:17}),i.jsx("span",{children:hr?"Pause":"Resume"})]}),i.jsxs("button",{onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Do,type:"button",children:[en==="restart"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vg,{size:17}),i.jsx("span",{children:"Restart"})]})]})]}),dt?i.jsx("section",{className:"control-focus",children:i.jsxs("div",{className:"control-wall",children:[De&&i.jsxs("div",{className:"control-monitor-tabs","aria-label":`Select monitor for ${Pa(De)}`,children:[i.jsx("strong",{className:"control-computer-name",title:Pa(De),children:Pa(De)}),Nm.map(m=>i.jsxs("button",{className:m.index===ao?"active":"",onClick:()=>Cm(De.deviceId,m.index),title:YI(m),type:"button",children:[i.jsx("span",{children:m.name||`Display ${m.index+1}`}),m.width>0&&m.height>0&&i.jsxs("small",{children:[m.width,"x",m.height]})]},m.index))]}),De&&Vs&&i.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:pI.map(m=>{const x=m.code==="MetaLeft"&&tl(De.platform)?"Cmd":m.label,C=Et.includes(m.code);return i.jsx("button",{className:C?"active":"",type:"button","aria-pressed":C,title:`Hold ${x} on the remote computer`,onClick:()=>ht.current?.(m.code),children:x},m.code)})}),De?i.jsx(Wg,{device:De,frame:Ke,selected:!1,controlEnabled:bs&&ze&&Vs,showStatus:_n.showScreenStatus,showDeviceTitle:!1,monitorIndex:js(De,sn[De.deviceId]),monitorCount:fo(De),onSelect:()=>{},onFocusDevice:()=>Pe(De.deviceId),onOpenControl:()=>no(De.deviceId),onCycleMonitor:m=>Qu(De.deviceId,m),onCanvasReady:Du,sendInput:$o,remoteModifierState:Hu,presentationReady:Od,remoteDiagnostics:Ht?zr.get(De.deviceId):En?Ko.get(De.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},De.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(Ar,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),De&&Ru&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(ga,{size:22,"aria-hidden":"true"}),i.jsx("strong",{children:"Accessibility permission required"}),i.jsx("small",{children:"On the Mac, allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client."})]}),De&&!Ru&&!Od&&i.jsxs("div",{className:"control-connection-overlay",role:"status","aria-live":"polite",children:[Ee!=="error"&&i.jsx("span",{className:"control-connection-spinner","aria-hidden":"true"}),i.jsx("strong",{children:Ee==="error"?"Connection failed":"Connecting"}),i.jsx("small",{children:Ee==="error"?"See the notification for details. Reopen Control to retry.":Ho||st?"Control stream is recovering. See the notification for details.":kl==="open"?"Preparing the first control frame":"Opening the Control stream"})]})]})}):Gt==="list"?i.jsxs("div",{className:"wall-device-list",role:"grid","aria-label":"Computer status list",children:[i.jsxs("div",{className:"wall-device-list-head",role:"row",children:[i.jsx("span",{role:"columnheader",children:"Computer"}),i.jsx("span",{role:"columnheader",children:"Status"}),i.jsx("span",{role:"columnheader",children:"CPU"}),i.jsx("span",{role:"columnheader",children:"GPU"}),i.jsx("span",{role:"columnheader",children:"RAM"}),i.jsx("span",{role:"columnheader",children:"VRAM"}),i.jsx("span",{role:"columnheader",children:"Network"}),i.jsx("span",{role:"columnheader",children:"HDD"}),i.jsx("span",{role:"columnheader",children:"Temp"})]}),qi.length>0?qi.map(({device:m,slotNumber:x})=>i.jsx(SL,{device:m,slotNumber:x,selected:mr.has(m.deviceId),updateIndicator:As(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote",onSelect:()=>Vu(m.deviceId),onOpenControl:()=>no(m.deviceId)},m.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(Ar,{size:24,"aria-hidden":"true"}),i.jsx("strong",{children:"No connected computers"})]})]}):Kt?i.jsx("div",{className:`screen-wall atlas-slot-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&qo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:mr.has(m.deviceId),controlEnabled:!1,showStatus:wt.showScreenStatus,monitorIndex:js(m,sn[m.deviceId]),monitorCount:fo(m),onSelect:()=>Vu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Qu(m.deviceId,C),onCanvasReady:Lf({mode4Enabled:Kt,directMode4WallEnabled:La,isMac:tl(m.platform)})==="direct"?Fo:Ki,sendInput:$o,remoteModifierState:Hu,updateIndicator:As(m.deviceId),presentationReady:wt.autoStartLive&&Za.includes(m.deviceId)?xo.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Za.includes(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(zx,{index:x},`slot-${x}`))}):i.jsx("div",{className:`screen-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&qo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:mr.has(m.deviceId),controlEnabled:bs&&ze&&Vs&&De?.deviceId===m.deviceId,showStatus:wt.showScreenStatus,monitorIndex:js(m,sn[m.deviceId]),monitorCount:fo(m),onSelect:()=>Vu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Qu(m.deviceId,C),onCanvasReady:Fo,sendInput:$o,remoteModifierState:Hu,updateIndicator:As(m.deviceId),presentationReady:wt.autoStartLive&&Za.includes(m.deviceId)?xo.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Za.includes(m.deviceId),remoteDiagnostics:Ht?zr.get(m.deviceId):En?Ko.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(zx,{index:x},`slot-${x}`))}),i.jsx(ML,{visible:vm&&!dt})]}),!hs&&i.jsxs("aside",{className:`right-dock actions-mode ${Is?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>go(m=>!m),"aria-label":Is?"Show control panel":"Hide control panel",title:Is?"Show control panel":"Hide control panel",type:"button",children:Is?i.jsx(n0,{size:18}):i.jsx(Mv,{size:18})}),!Is&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:Su,className:"hidden-file-input",type:"file",multiple:!0,onChange:m=>{m.currentTarget.files&&lf(m.currentTarget.files),m.currentTarget.value=""}}),i.jsxs("div",{className:"manual-action-bar",role:"toolbar","aria-label":"Manual Client controls",children:[i.jsx(Yc,{label:"Control",tooltip:De?Ru?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":bs?Vs?"Keyboard and mouse control is ready":"Waiting for the current Control capture session":"Remote control is not available on this Client":"Select a Client to use Control",onClick:()=>{if(De){if(dt&&ze){We(!1),Oe("Remote control paused. Screen viewing stays on.");return}no(De.deviceId)}},disabled:!bs||!!en,active:ze,pressed:dt&&ze,children:i.jsx(Hf,{size:17})}),i.jsx(Yc,{label:"Audio",tooltip:De?ys?Je?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{sf()},disabled:!Eu||!!en,active:Je,pressed:Je,children:en==="audio"?i.jsx($r,{className:"spin",size:17}):i.jsx(ig,{size:17})}),i.jsx(Yc,{label:Lo?"Retry pause":hr?"Pause video":"Resume video",tooltip:ws.length===0?"Select one or more Clients to pause video":Lo?"Retry every selected Client whose capture shutdown is unconfirmed":hr?`Pause video for ${Ia.length} selected Client${Ia.length===1?"":"s"}`:`Resume video for ${Ia.length} selected Client${Ia.length===1?"":"s"}`,onClick:()=>{Oc()},disabled:Ia.length===0||!!en,active:!hr,pressed:!hr,children:en==="video"?i.jsx($r,{className:"spin",size:17}):!hr&&!Lo?i.jsx(kb,{size:17}):i.jsx(Cb,{size:17})}),i.jsx(Yc,{label:"Send files",tooltip:In.length===0&&!dt?"Select one or more Clients to send files":De?"Choose files and send them to the selected Client":"Select a Client to send files",onClick:()=>{Oe(`Choose files to send to ${Hc}.`),Su.current?.click()},disabled:!!en||!Xt||(dt?!De:In.length===0),children:i.jsx(Ad,{size:17})}),i.jsx(Yc,{label:"Restart",tooltip:De?Do?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Do,children:en==="restart"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vg,{size:17})}),i.jsx(Yc,{label:"Sleep",tooltip:De?Do?"Put Client to sleep":"Sleep is not available on this Client":"Select a Client to put to sleep",onClick:()=>{Dl("sleep")},disabled:!De||!Xt||!!en||!Do,children:en==="sleep"?i.jsx($r,{className:"spin",size:17}):i.jsx(_k,{size:17})}),i.jsx(Yc,{label:"Shut down",tooltip:De?Do?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Dl("shutdown")},disabled:!De||!Xt||!!en||!Do,danger:!0,children:en==="shutdown"?i.jsx($r,{className:"spin",size:17}):i.jsx(Vx,{size:17})})]})]}),i.jsx(ox,{hubUrl:X,devices:W,variant:"dock",selectedDeviceIds:zc})]})]})]})})]}),T&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Nt==="wall"?"active":"",onClick:()=>wi("wall"),type:"button",children:[i.jsx(t0,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:dt?"active":"",onClick:()=>De&&void no(De.deviceId),disabled:!De||!bs,type:"button",children:[i.jsx(Hf,{size:19}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Hi?"active":"",onClick:()=>wi("share-files"),type:"button",children:[i.jsx(Kf,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:Ka?"active":"",onClick:()=>wi("agents"),type:"button",children:[i.jsx(jp,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:hs?"active":"",onClick:()=>wi("settings"),type:"button",children:[i.jsx(zp,{size:19}),i.jsx("span",{children:"Settings"})]})]}),Oi&&i.jsxs("aside",{className:`transfer-bar state-${Oi.status}`,"aria-live":"polite",children:[i.jsx("span",{className:"transfer-bar-icon","aria-hidden":"true",children:Oi.status==="queued"?i.jsx(_a,{size:18}):Oi.status==="failed"?i.jsx(rr,{size:18}):i.jsx(Qx,{size:18})}),i.jsxs("div",{className:"transfer-bar-copy",children:[i.jsx("p",{children:Oi.message}),i.jsx("div",{className:"transfer-bar-track",children:i.jsx("span",{style:{width:`${Math.max(0,Math.min(100,Oi.progress))}%`}})})]}),i.jsxs("strong",{children:[Math.max(0,Math.min(100,Oi.progress)),"%"]})]}),oe&&i.jsxs("aside",{className:`livedesk-toast tone-${oe.tone}`,role:oe.tone==="error"?"alert":"status","aria-live":oe.tone==="error"?"assertive":"polite","aria-busy":oe.tone==="progress",children:[oe.tone==="progress"&&i.jsx("span",{className:"livedesk-toast-spinner","aria-hidden":"true"}),i.jsx("span",{children:oe.message}),i.jsx("button",{className:"livedesk-toast-close",onClick:()=>Oe(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(rr,{size:15})})]})]})}const NL=1e3,TL=5e3;function RL(){return typeof window>"u"?!1:(!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches)&&window.matchMedia("(pointer: coarse)").matches}function jL(){return typeof window>"u"?[]:[...new Set([window.location.origin,Un].filter(Boolean))]}function EL(){const n=Av(),r=RL(),o=n||r,l=n||typeof window>"u"?Un:window.location.origin,u=o?{role:"hub",baseUrl:l}:null,[f,h]=d.useState(u),g=d.useRef(null);return d.useEffect(()=>{if(o){h(j=>j?.role==="hub"&&j.baseUrl===l?j:{role:"hub",baseUrl:l});return}let y=!1,w=!1,b=null;const S=new AbortController,k=async()=>{for(const j of jL()){if(S.signal.aborted)return;try{const T=(await rt("/api/runtime/status",{signal:S.signal,timeoutMs:900},j)).role==="hub"?"hub":"client";w=!0,y||h(_=>_?.role===T&&_.baseUrl===j?_:{role:T,baseUrl:j});return}catch{if(S.signal.aborted)return}}},N=()=>{Up(g,k).finally(()=>{!y&&!S.signal.aborted&&(b=window.setTimeout(N,w?TL:NL))}).catch(()=>{})};N();const A=window.setTimeout(()=>{!y&&!w&&h(j=>j?.role==="client"&&j.baseUrl===Un?j:{role:"client",baseUrl:Un})},2500);return()=>{y=!0,S.abort(new Error("LiveDesk runtime role probe stopped.")),b!==null&&window.clearTimeout(b),window.clearTimeout(A)}},[null,o,l]),f?f.role==="client"?i.jsx(sA,{runtimeBaseUrl:f.baseUrl}):i.jsx(AL,{runtimeBaseUrl:f.baseUrl}):i.jsxs("main",{className:"runtime-role-boot","aria-busy":"true","aria-label":"Starting LiveDesk",children:[i.jsx("span",{className:"runtime-role-boot-mark","aria-hidden":"true"}),i.jsx("strong",{children:"Starting LiveDesk"}),i.jsx("p",{children:"Loading this computer's assigned role..."})]})}qk.createRoot(document.getElementById("root")).render(i.jsx(d.StrictMode,{children:i.jsx(EL,{})}));"serviceWorker"in navigator&&window.isSecureContext&&window.location.protocol==="https:"&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).then(t=>t.update()).catch(t=>{console.warn("[LiveDesk] PWA service worker registration failed.",t)})},{once:!0});
|