livedesk 0.1.521 → 0.1.522

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 H1({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",z1="livedesk_entitlements",rw=4e3,$1=2500,Pv=new TextDecoder,cv=new Set;function U1(){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 q1(){return ma.snapshot()}function W1(t){const r=(Array.isArray(t)?t:[t||$n]).map(o=>lu(o||$n));return[...new Set(r.filter(Boolean))]}function G1(){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(r0(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 V1(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(()=>W1(t),[k]),A=d.useMemo(()=>N.find(R=>Zf(R)==="loopback")||N[0]||$n,[N]),D=d.useCallback(async R=>{if(!n){l(null),f([]),w(""),g("");return}let _=null;const B=Date.now(),F=N.filter(j=>(b.current.get(j)||0)<=B),H=H1({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 j of H.candidates)try{const[Q,$]=await Promise.all([rt("/api/remote/status",{signal:R,timeoutMs:rw,transport:H.transport},j),rt("/api/remote/devices",{signal:R,timeoutMs:rw,transport:H.transport},j)]);if(R?.aborted)throw R.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray($.devices))throw new Error("Invalid Hub devices response.");b.current.delete(j),l(Q),f($.devices),w(j),g("");return}catch(Q){if(R?.aborted)throw Q;_=Q,H.transport==="auto"&&b.current.set(j,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,()=>D()).catch(R=>{g(R instanceof Error?R.message:String(R))})},[D]);return d.useEffect(()=>{if(b.current.clear(),!n){l(null),f([]),w(""),g("");return}let R=!0,_=null;const B=new AbortController,F=()=>{Up(S,()=>D(B.signal)).catch(j=>{R&&!B.signal.aborted&&g(j instanceof Error?j.message:String(j))}).finally(()=>{R&&!B.signal.aborted&&(_=window.setTimeout(F,$1))})};return F(),()=>{R=!1,B.abort(new Error("LiveDesk Hub snapshot polling stopped.")),_!==null&&window.clearTimeout(_)}},[n,D]),{status:o,devices:u,error:h,refresh:I,hubBaseUrl:y||A,hubCandidates:N}}function K1(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 Q1(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(z1).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 em={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},Y1=2500,X1=3e4,Z1=64*1024,J1=64*1024,eN=6,tN=eN,G0=new Map;function nN(t){return G0.get(t)}const sw={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function aN(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>X1?(t.minimumHubClockOffsetMs=l,0):f}function gt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const rN=["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 sN(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&rN.every(n=>gt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function iN(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=$n,o={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(em),S=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(new Map),A=d.useRef(null);A.current===null&&(A.current=f1());const D=d.useRef(0),I=d.useRef(new Map),R=d.useRef({enabled:!1,token:"",reason:""}),_=d.useRef(new Map),B=d.useRef(null),F=d.useRef(new Map),[H,j]=d.useState(0),Q=d.useRef(o.onFrame),$=d.useRef(o.onStreamReady),G=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),W=d.useMemo(()=>[...t].sort().join(","),[t]),V=n&&W.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,z=Number.isFinite(o.maxHeight)?Number(o.maxHeight):360,P=Number.isFinite(o.quality)?Number(o.quality):45,re=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();R.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(()=>{Q.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{$.current=o.onStreamReady},[o.onStreamReady]);const Ke=d.useCallback((Me,pe="livedesk-frame-socket-release")=>{m1(Me,pe,A.current)},[]),ue=d.useCallback(Me=>{const pe=_.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),_.current.delete(Me))},[]),Fe=d.useCallback(Me=>{const pe=F.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),F.current.delete(Me))},[]),Xe=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,Ke(qe,Me);N.current.clear(),I.current.clear(),S.current=new Map,k.current.clear(),G.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(em),h("idle"))},[Ke]),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));y1(O,pe.sparseTelemetry,pe.expectedBinding);const $e=gt(O.hubPacketEpochMs),We=$e!==void 0&&$e>0?$e:void 0,Et=aN(pe,We,qe);if(Et>Y1)return;const lt=new Uint8Array(Me,4+st),ht=gt(O.nativeCaptureTelemetryVersion),Ze=gt(O.nativeCaptureTelemetryAgeMs),be=gt(O.hubClientDropped),je=gt(O.hubClientQueueDepth),Ae=gt(O.hubClientQueueLimit),fe=gt(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:gt(O.inputFeedbackInputSeq),inputFeedbackInputType:O.inputFeedbackInputType?String(O.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:gt(O.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:gt(O.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:gt(O.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:gt(O.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:gt(O.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:gt(O.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:gt(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:Ze===void 0?void 0:Math.max(0,Ze),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:gt(O.nativeCaptureDisplayId),nativeCaptureFps:gt(O.nativeCaptureFps),nativeCompressionFps:gt(O.nativeCompressionFps),nativeEncodedFps:gt(O.nativeEncodedFps),nativeCaptureSampleCount:gt(O.nativeCaptureSampleCount),nativeEncodableFrameCount:gt(O.nativeEncodableFrameCount),nativeSkippedFrameCount:gt(O.nativeSkippedFrameCount),nativeCompressionOutputCount:gt(O.nativeCompressionOutputCount),nativeEncodedFrameCount:gt(O.nativeEncodedFrameCount),nativeEncodeFramesInFlight:gt(O.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:gt(O.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:gt(O.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:gt(O.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:gt(O.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:gt(O.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:gt(O.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:gt(O.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:gt(O.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:gt(O.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:gt(O.nativeOutputQueueDepth),nativeOutputQueueBytes:gt(O.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:gt(O.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:gt(O.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:gt(O.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof O.nativeOutputQueueAwaitingKeyFrame=="boolean"?O.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof O.nativeCopyTelemetryAvailable=="boolean"?O.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:gt(O.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:gt(O.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:gt(O.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:gt(O.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:gt(O.pipePayloadAllocationCount),pipePayloadCopyCount:gt(O.pipePayloadCopyCount),pipePayloadCopiedBytes:gt(O.pipePayloadCopiedBytes),handoffDroppedFrameCount:gt(O.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:gt(O.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:gt(O.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:O.nativeCaptureResourceTelemetryAvailable===!0?sN(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:gt(O.captureAverageMs),captureP95Ms:gt(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:gt(O.captureMs),captureStageMs:gt(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},Ye=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>=Ye&&(_t===Ye||ut))return;pe.lastFrameStreamId=ce.streamId,pe.lastFrameCommandId=ce.commandId||"",pe.lastFrameOrder=Ye;const mt=G.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),Ct=c1(k.current,ce);Vt&&(S.current.set(ce.deviceId,Ct),k.current.delete(ce.deviceId),u(new Map(S.current))),Q.current?.(ce)},[]);d.useEffect(()=>{if(!n||!W)return;G.current.sampleStartedAt=performance.now();const Me=window.setInterval(()=>{if(!X.current)return;const pe=performance.now(),qe=G.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(u1(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,W]),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:W,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,$e)=>O+Math.max(0,Number($e.payload?.byteLength||0)),0)}};return cv.add(Me),()=>{cv.delete(Me)}},[W]),d.useEffect(()=>{const Me=W?W.split(",").filter(Boolean):[];if(!V){Xe(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)||Fe(Re);for(const[Re,st]of N.current.entries())pe.has(Re)||(ue(Re),Ke(st,"livedesk-device-unsubscribed"),N.current.delete(Re),I.current.delete(Re),S.current.delete(Re),k.current.delete(Re));G.current.sampleStartedAt<=0&&(G.current.sampleStartedAt=qe,b({...em,lastUpdatedAt:Date.now()}));for(const Re of Me){ue(Re),Fe(Re);const st=Number(o.monitorSelections?.[Re]),jt=Number.isInteger(st)&&st>=0?st:0,O={[Re]:jt},$e={type:"subscribe",deviceIds:[Re],autoStartLive:n,fps:ve,maxWidth:J,maxHeight:z,quality:P,mode:we,frameMode:we,streamPurpose:Z,monitorSelections:O},We=String(o.connectionSessionIds?.[Re]||"").trim(),Et=JSON.stringify({subscribePayload:$e,connectionSessionId:We}),lt=N.current.get(Re),ht=Number(lt?.payload.monitorSelections?.[Re]),Ze=Number(O[Re]),be=!!lt&&Number.isFinite(ht)&&Number.isFinite(Ze)&&ht!==Ze,je=!!lt&&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&&lt!==Ae?lt:void 0,te=`/api/remote/frames/ws?devices=${encodeURIComponent(Re)}`,ce=nh(ah(te,r),te);ce.binaryType="arraybuffer";const Ne=v1(),He={socket:ce,payload:$e,payloadKey:Et,connectionSessionId:We,generation:D.current+1,monitorRestartToken:be?`monitor-${Re}-${Ze}-${D.current+1}`:"",disposed:!1,handoffFrom:Ae,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Ne,releaseOwnedState:()=>ew(Ne)};D.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,Ke(fe,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||He.disposed||N.current.get(Re)!==He){Ke(He,"livedesk-stale-frame-socket");return}ue(Re),y("");const yt=R.current,_t=yt.enabled&&(!yt.token||I.current.get(Re)!==yt.token),mt=_t||He.monitorRestartToken!=="",Vt=_t?yt.token:He.monitorRestartToken,Ct=_t?yt.reason:He.monitorRestartToken?"monitor-selection-change":"";if(ce.send(JSON.stringify({...He.payload,forceRestart:mt,restartReason:mt?Ct:"",restartToken:mt?Vt:""})),re>0){const an=window.setTimeout(()=>{F.current.get(Re)===an&&F.current.delete(Re),X.current&&Ge(Re,He)},Math.max(1e3,re));F.current.set(Re,an)}_t&&yt.token&&I.current.set(Re,yt.token);const mn=He.handoffFrom;He.handoffFrom=void 0,He.handoffCompleted=!0,mn&&!mn.disposed&&Ke(mn,"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=(Ct,mn=!0)=>{const an=iN(Ct,Re,Z);return an?(He.expectedBinding=an,mn&&$.current?.(an),!0):!1};if(mt?.type==="RemoteFrameSubscriptionError")y(String(mt.error||"control-stream-start-failed"));else if(mt?.type==="RemoteFrameLiveAutoStart"){const mn=(Array.isArray(mt.skipped)?mt.skipped:[]).find(an=>an?.deviceId===Re);if(mn)mn.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&mn.retryScheduled===!0?y(""):y(String(mn.reason||"control-stream-start-failed"));else if(Array.isArray(mt.started)){const an=mt.started.find(va=>va?.deviceId===Re);an&&(y(""),Vt(an,an.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))},Ye=()=>{!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&&Fe(Re);let Vt=!1;if(mt===He){const Ct=He.handoffFrom;He.handoffFrom=void 0,Ct&&!Ct.disposed&&(Ct.socket.readyState===WebSocket.CONNECTING||Ct.socket.readyState===WebSocket.OPEN)?(N.current.set(Re,Ct),Vt=!0):N.current.delete(Re)}if(at(),yt&&X.current&&mt===He&&!Vt){const Ct=window.setTimeout(()=>{_.current.get(Re)===Ct&&_.current.delete(Re),X.current&&j(mn=>mn+1)},750);ue(Re),_.current.set(Re,Ct)}};He.detachListeners=()=>{ce.removeEventListener("open",Ie),ce.removeEventListener("message",Lt),ce.removeEventListener("error",Ye),ce.removeEventListener("close",ut)},ce.addEventListener("open",Ie),ce.addEventListener("message",Lt),ce.addEventListener("error",Ye),ce.addEventListener("close",ut)}at()},[n,Fe,ue,Ke,re,de,W,ve,we,me,r,z,J,Pe,o.monitorSelections,P,H,Xe,Ge,Z,V,at]),d.useEffect(()=>{if(!V||!Se||!ae)return;const Me=W?W.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)}},[W,Se,ae,ye,Ee,V]),d.useEffect(()=>()=>{Xe("livedesk-hook-unmount",!1)},[Xe]);const ke=d.useCallback((Me,pe="browser-stale")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:W.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},[W,Ee,V]),Je=d.useCallback((Me,pe="browser-reconnect")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:W.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),Ke(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)),j(st=>st+1),at(),!0},[ue,Ke,W,V,at]);return{frames:l,state:f,error:g,stats:w,restartLive:ke,reconnectLive:Je}}function oN(t,n,r=$n,o={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(em),S=d.useRef(null),k=d.useRef(o.onFrame),N=d.useRef(null),A=d.useRef(0),D=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),R=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 W=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(W))},[o.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:R.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||{}}),[R,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]),j=d.useRef(F);j.current=F;const Q=n&&F.deviceIds.length>0,$=d.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...j.current})),!0),[]);d.useEffect(()=>{k.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{if(!Q)return;D.current.sampleStartedAt=performance.now();const W=window.setInterval(()=>{const V=D.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(W)},[Q]),d.useEffect(()=>{if(!Q){S.current?.close(),S.current=null,u(null),N.current=null,A.current=0,h(null),y("idle"),b(em);return}let W=!1,V=0;const X=()=>{if(W)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",()=>{D.current.sampleStartedAt=performance.now(),y("open"),$(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 z=J.data instanceof ArrayBuffer?J.data:null;if(!(!z||z.byteLength<5))try{const P=Date.now(),we=new DataView(z).getUint32(0,!1);if(we<=0||we+4>z.byteLength)return;const Z=JSON.parse(Pv.decode(new Uint8Array(z,4,we))),Se=new Uint8Array(z,4+we),ae=gt(Z.hubClientDropped),ye=gt(Z.hubClientQueueDepth),Pe=gt(Z.hubClientQueueLimit),de=gt(Z.hubClientBufferedBytes),Ke={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=D.current;ue.totalFrames+=1,ue.totalBytes+=Se.byteLength,ue.sampleFrames+=1,ue.sampleBytes+=Se.byteLength,N.current=Ke,A.current===0&&(A.current=Ke.frameSeq,u(Ke)),k.current?.(Ke)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{S.current===ve&&(S.current=null),!W&&(y("closed"),V=window.setTimeout(X,1200))})};return X(),()=>{W=!0,window.clearTimeout(V),S.current?.close(),S.current=null}},[Q,r,$]),d.useEffect(()=>{if(!Q)return;const W=S.current;W&&$(W)},[H,Q,$]);const G=d.useCallback(()=>{const W=S.current;return W?$(W):!1},[$]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:G}}function lN(t,n=$n){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,D=0;const I=()=>{if(A)return;const R=nh(ah("/api/remote/input/ws",n),"/api/remote/input/ws");r.current=R,k.current.sampleStartedAt=performance.now(),g("connecting"),w(""),R.addEventListener("open",()=>{A||r.current!==R||(w(""),g("open"))}),R.addEventListener("message",_=>{if(!(A||r.current!==R||typeof _.data!="string"))try{const B=JSON.parse(_.data),F=Number(B.inputSeq||B.result?.inputSeq||0),H=String(B.deviceId||B.result?.deviceId||""),j=String(B.inputEventId||B.result?.inputEventId||""),Q=u.current.get(F);if(H&&(Q&&Q.deviceId!==H||!Q&&f.current&&f.current!==H)||Q?.inputEventId&&j&&Q.inputEventId!==j)return;if(B?.type==="RemoteInputError"){F>0&&u.current.delete(F),w(String(B.error||B.result?.error||"Remote input failed.")),R.readyState===WebSocket.OPEN&&g("open");return}if(B?.type!=="RemoteInputApplied")return;Q&&(k.current.lastRoundTripMs=Math.max(0,performance.now()-Q.sentAt),u.current.delete(F)),k.current.lastInputSeq=F,k.current.lastAgentApplyMs=Math.max(0,Number(B.agentApplyMs||0)),w(""),g("open")}catch{}}),R.addEventListener("close",()=>{A||r.current!==R||(r.current=null,g("closed"),D=window.setTimeout(I,1200))}),R.addEventListener("error",()=>{!A&&r.current===R&&g("error")})};return I(),()=>{A=!0,window.clearTimeout(D);const R=r.current;r.current=null,R?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const A=window.setInterval(()=>{const D=performance.now(),I=k.current,R=Math.max(1,D-I.sampleStartedAt);S({totalSent:I.totalSent,totalDropped:I.totalDropped,sentPerSecond:I.sampleSent*1e3/R,droppedPerSecond:I.sampleDropped*1e3/R,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=D},1e3);return()=>window.clearInterval(A)},[t]);const N=d.useCallback((A,D)=>{const I=r.current;if(!I||I.readyState!==WebSocket.OPEN||!A)return!1;const R=String(D.type||"").toLowerCase(),F=R==="pointermove"||R==="wheel",H=k.current;if(F&&I.bufferedAmount>Z1)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${R}-coalescible-drop`,!1;if(!F&&I.bufferedAmount>J1){H.lastInputType=`${R||"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 j=o.current+1;o.current=j;const Q=`${j}-${crypto.randomUUID()}`,$=Date.now(),G=!F||j-l.current>=tN;for(G&&(u.current.set(j,{sentAt:performance.now(),deviceId:A,inputEventId:Q}),F&&(l.current=j)),f.current=A,G0.set(A,{inputSeq:j,inputType:R||"input",sentAt:performance.now()});u.current.size>256;){const W=u.current.keys().next().value;if(W===void 0)break;u.current.delete(W)}try{I.send(JSON.stringify({type:"input",requestId:F?"":crypto.randomUUID(),fireAndForget:F,deviceId:A,input:{...D,inputEventId:Q,inputSeq:j,requestAck:G,issuedAtEpochMs:$,issuedAt:new Date($).toISOString()}}))}catch{u.current.delete(j),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=R||"input",!0},[]);return{state:h,sendInput:N,stats:b,error:y}}const bd={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},cN=.25,ow=300,lw=2,dp=1500,xg=5e3,uN=2e3,cw=1e4,Pf=[0,1e3,3e3];function uw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function dN(t,n,r=$n,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(bd),[A,D]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(S(R=>R===null?R:null),N(R=>R===bd?R:bd))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),S(null),N(bd),D("");return}w("connecting"),S(null),N(bd),D("");const R=window.AudioContext||window.webkitAudioContext;if(!R){w("unsupported"),N(bd),D("Audio playback is not supported in this browser.");return}let _=!1,B=null;const F=A1.acquire(({release:H})=>{if(_){H();return}const j=new R({latencyHint:"interactive"});g.current=j;let Q=String(u||"").trim();const $="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(Q?"&streamId="+encodeURIComponent(Q):""),G=nh(ah($,r),$);G.binaryType="arraybuffer";const W=ma.createOwner({deviceId:t,socket:G,audioContext:j,statsTimer:null});let V=!1;const X=()=>{const te=ma.releaseIfDrained(W);return(te||!ma.hasOwner(W))&&!V&&(V=!0,H()),te},ve=Lv({sampleRate:192e3,channels:8}).capacityBytes,J=L1({maxPendingPackets:ov,maxPendingBytes:ve}),z=x1(),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(j.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:Q,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let re=!1,we=!1,Z=null,Se=0,ae=0,ye="",Pe=!1,de=()=>{},Ke="connecting",ue="";const Fe=te=>{re||te===Ke||(Ke=te,w(te))},Xe=te=>{re||te===ue||(ue=te,D(te))};let at=0,Ee=!1,Ge=0,me=0,ke=0,Je=!1;const Me=()=>{ma.setPendingWorkletPackets(W,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(cN*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),ma.setPcmRing(W,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,ma.setPcmRing(W,0,0),ma.setWorkletNode(W,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=()=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:Q?{[t]:Q}:{}}))},O=()=>{P.audioContextState=String(j.state),!re&&(P.audioContextState==="suspended"||P.audioContextState==="interrupted"?Fe("suspended"):P.audioContextState==="closed"&&(Fe("error"),Xe("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},$e=async()=>{if(re||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),P.audioContextState=String(j.state),!re&&!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;Fe(te?"playing":ce?"silent":"open")}return P.audioContextState==="running"}catch(te){return re||(Fe("suspended"),Xe(te instanceof Error?"Audio playback is suspended: "+te.message:"Audio playback is suspended.")),!1}},We=async()=>{if(!j.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const te=new Blob([B1],{type:"text/javascript"});ye=URL.createObjectURL(te);try{await j.audioWorklet.addModule(ye)}finally{URL.revokeObjectURL(ye),ye=""}if(re||String(j.state)==="closed")return;const ce=new AudioWorkletNode(j,W0,{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(j.destination),Pe=!0,ma.setWorkletNode(W,1,1,Se)},Et=(te,ce,Ne,He)=>{const Ie=Z;if(re||!Pe||!Ie||ce.byteLength<=0)return!1;const Lt=Iv({sampleRate:te.sampleRate,channels:te.channels,mimeType:te.mimeType}),Ye=++ae;if(!J.claim(Ye,ce.byteLength))return Me(),!1;Me();try{return Ie.port.postMessage({type:"pcm",packetId:Ye,buffer:ce,byteOffset:Ne,byteLength:He,sampleRate:Lt.sampleRate,channels:Lt.channels,mimeType:te.mimeType,sampleFormat:Lt.sampleFormat},[ce]),!0}catch{return J.acknowledge(Ye),Me(),!1}},lt=async()=>{if(re||Ee||G.readyState!==WebSocket.OPEN)return;if(Ge>=Pf.length){Fe("error"),Xe("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,Fe("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ce=await f(t);if(re||!ce)return;Q=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=Q,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st(),me=Ne+(Pf[te+1]??3e3),Xe(""),re||Fe("open")}catch(ce){re||(me=performance.now()+(Pf[te+1]??3e3),Fe("error"),Xe(ce instanceof Error?"Remote audio restart failed: "+ce.message:"Remote audio restart failed."))}finally{Ee=!1}},ht=()=>{P.drops+=1},Ze=window.setInterval(()=>{if(re)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=G.readyState===WebSocket.OPEN,Lt=P.lastCaptureStatusAt>0,Ye=Lt&&He<=xg&&P.captureHealthy,ut=Lt&&P.captureStatusFailed&&He>uN,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>=Pf.length&&!Ee?(Fe("error"),Xe("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Ee&&te>=me?lt():Ee||Fe("stalled"):Ie&&Vt&&!Ee&&P.audioContextState!=="suspended"&&P.audioContextState!=="interrupted"&&Fe(Ye?"silent":"open"),N1({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 Ct=z.publish();Ct&&(Je=!0,ma.setRetainedFrame(W,1,Ct.payload.byteLength),S(Ct))}else!I.current&&Je&&(Je=!1,z.clear(),ma.setRetainedFrame(W,0,0))},250);ma.setStatsTimer(W,Ze);const be=()=>{O(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&$e()},je=()=>{document.visibilityState==="visible"&&$e()},Ae=()=>{$e()};j.addEventListener("statechange",be),document.addEventListener("visibilitychange",je),window.addEventListener("pageshow",Ae),window.addEventListener("pointerdown",Ae),window.addEventListener("keydown",Ae),Fe("connecting"),Xe(""),O();const fe=(te,ce,Ne,He,Ie)=>{if(P.localProcessingAgeMs=Math.max(0,performance.now()-Ie),re||P.localProcessingAgeMs>ow||!lv(te,{deviceId:t,streamId:Q}))return ht(),!1;P.activeStreamId!==Q&&(P.activeStreamId=Q,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st());const Lt=E1(te,{deviceId:t,streamId:Q,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 Ye=performance.now();P.lastAcceptedAt>0&&(P.maximumAcceptedGapMs=Math.max(P.maximumAcceptedGapMs,Ye-P.lastAcceptedAt)),P.lastAcceptedAt=Ye,P.framesReceived+=1,P.lastFrameSeq=Lt.nextFrameSeq,Ge=0,me=0,I.current&&(z.accept(te),Je=!0,ma.setRetainedFrame(W,1,0)),String(j.state)!=="running"&&$e();const ut=String(j.state)==="running";return ut&&Xe(""),Fe(ut?"playing":"suspended"),!0};de=(te="")=>{if(!we){if(we=!0,te&&(ma.recordTerminalFailure(W,te,te.includes("setup failed")?"setup":"processor"),Fe(te.includes("AudioWorklet is unavailable")?"unsupported":"error"),Xe(te),h?.(t,Q,"browser-audio-playback-failed").catch(()=>{})),re=!0,ma.deactivate(W),window.clearInterval(Ze),ma.setStatsTimer(W,null),j.removeEventListener("statechange",be),document.removeEventListener("visibilitychange",je),window.removeEventListener("pageshow",Ae),window.removeEventListener("pointerdown",Ae),window.removeEventListener("keydown",Ae),z.clear(),ma.setRetainedFrame(W,0,0),Z)try{Z.port.postMessage({type:"dispose"})}catch{}try{G.close()}catch{}G.readyState===WebSocket.CLOSED&&ma.setSocket(W,null),j.close().catch(()=>{}).finally(()=>{qe(),String(j.state)==="closed"&&ma.setAudioContext(W,null),X()}),g.current===j&&(g.current=null),X()}},We().catch(te=>{de(te instanceof Error?`Remote audio worklet setup failed: ${te.message}`:"Remote audio worklet setup failed.")}),G.addEventListener("open",()=>{re||(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,Fe("open"),jt(),$e())}),G.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),Ye=JSON.parse(Pv.decode(Lt)),ut=new Uint8Array(ce,4+Ie),yt=String(Ye.deviceId||""),_t=String(Ye.streamId||"");if(!lv({deviceId:yt,streamId:_t},{deviceId:t,streamId:Q})){ht();return}const mt=String(Ye.frameKind||Ye.kind||"").toLowerCase();if(Ye.type==="remote.audio.status"||mt==="audio-status"){P.lastCaptureStatusAt=Ne;const Ct=D1(Ye);if(P.captureAlive=Ct.captureAlive,P.helperAlive=Ct.helperAlive,P.helperReady=Ct.helperReady,P.captureHealthy=Ct.healthy,P.captureStatusFailed=Ct.failed,P.captureAwaitingCurrentPcm=Ct.awaitingCurrentPcm,Ct.awaitingCurrentPcm?P.captureAwaitingSinceAt||=Ne:P.captureAwaitingSinceAt=0,P.capturePhase=Ct.capturePhase,P.backendKind=Ct.backendKind,P.helperRequired=Ct.helperRequired===!0,P.helperPid=Ct.helperPid,P.captureRestartCount=Math.max(0,Number(Ye.restartCount||0)||0),P.nativeCallbackDiagnosticsAvailable=Ye.callbackDiagnosticsAvailable===!0,P.nativeRejectedCallbackCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.rejectedCallbackCount||0)||0):0,P.nativeCurrentnessDropCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.currentnessDropCount||0)||0):0,P.nativeLastDropReason=P.nativeCallbackDiagnosticsAvailable?String(Ye.lastDropReason||""):"",P.lastPcmAtEpochMs=Math.max(0,Number(Ye.lastPcmAtEpochMs||0)||0),P.silentForMs=Math.max(0,Number(Ye.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){Xe("");const mn=String(j.state)==="running",an=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp;Fe(mn?an?"playing":"silent":"suspended")}}else P.captureAwaitingCurrentPcm&&!Ee?Fe("open"):P.captureStatusFailed&&!Ee&&Fe("stalled");return}const Vt={deviceId:yt,frameSeq:Number(Ye.frameSeq||0),streamId:_t,mimeType:String(Ye.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ye.sampleRate||48e3),channels:Number(Ye.channels||2),capturedAt:String(Ye.capturedAt||""),receivedAt:String(Ye.receivedAt||""),byteLength:Number(Ye.byteLength||ut.byteLength),payload:q0};if(!Vt.deviceId||re)return;if(performance.now()-Ne>ow){ht();return}if(j1(Vt.mimeType)){fe(Vt,ce,ut.byteOffset,ut.byteLength,Ne);return}ht(),Fe("error"),Xe(`Unsupported remote audio format "${Vt.mimeType}". Requesting a bounded PCM restart.`),!Ee&&Ge<Pf.length&&(me=0,lt());return}catch(He){re||(Fe("error"),Xe(He instanceof Error?He.message:String(He)))}}),G.addEventListener("error",()=>{re||(Fe("error"),Xe("Remote audio WebSocket error."))}),G.addEventListener("close",()=>{ma.setSocket(W,null),X(),re||Fe("closed")}),B=()=>{de()}});return F.ready.catch(H=>{_||(w("error"),D(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 fN=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,fN);return l<=u?0:l>=o-u?1:l/o}function mN(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"])}),pN=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 V0(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=V0(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(pN[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function hN(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 gN(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 vN(t,n,r){const o=fv(t),l=V0(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 yN(){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&&hN(g,t)?null:vN(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 K0=64,bN=2;function Q0(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(K0,n)):1}function Fv(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(K0-1,n)):0}function Y0(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function wN(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 X0({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return Y0(t)?!!String(n||"").trim()&&Number(r)>=bN:!0}function xN({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:o,consecutiveTopologySamples:l}){const u=Fv(t),f=Q0(n);return u<f||!X0({platform:r,topologyFingerprint:o,consecutiveTopologySamples:l})?u:f-1}function SN(t,n,r){const o=Fv(t),l=Q0(n);return o<l||Y0(r)?o:l-1}function sc(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function pa(t){return String(t||"").trim()}function Cg(t,n,r={}){return{deviceId:pa(t),transitionGeneration:sc(n),sessionId:pa(r.sessionId),streamId:pa(r.streamId),commandId:pa(r.commandId),captureGeneration:sc(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Kn(t,n){return!!t&&!!n&&pa(t.deviceId)===pa(n.deviceId)&&sc(t.transitionGeneration)===sc(n.transitionGeneration)}function pw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:o}){const l=pa(t),u=sc(n),f=sc(r);return!!l&&u>0&&u===f&&(!o||pa(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=pa(t);return!o||!n||pa(n.deviceId)!==o?!1:!r||pa(r.deviceId)!==o}function kg(t,n){if(!t||!n)return!1;const r=sc(n.captureGeneration),o=pa(n.commandId),l=pa(n.sessionId),u=pa(n.streamId),f=Number(t.monitorIndex);return!r||!o||!l||!u||!Number.isInteger(f)||f<0?!1:pa(t.deviceId)===pa(n.deviceId)&&pa(t.sessionId)===l&&pa(t.streamId)===u&&pa(t.commandId)===o&&sc(t.captureGeneration)===r&&pa(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}const CN=820,gw=`(max-width: ${CN}px)`,kN="1200px 0px 1800px 0px",MN=960,AN=540,NN=68;function TN(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,MN),maxHeight:Math.min(o.maxHeight,AN),quality:Math.min(o.quality,NN)}:o}function RN(t,n){return!n||!t||typeof t.closest!="function"?null:t.closest(".desk-stage")}function jN(t,n){const r=Number(t?.height),o=Number(n),l=Number.isFinite(r)&&r>0?r:Number.isFinite(o)&&o>0?o:1,u=Number(t?.offsetTop);return{height:Math.max(1,Math.round(l)),offsetTop:Number.isFinite(u)?Math.max(0,Math.round(u)):0}}function EN(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function DN(){let t=Promise.resolve(),n=Promise.resolve();const r=o=>{const l=EN(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 IN(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 LN(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 Yn=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"?Yn.slowWallFps:Yn.fastWallFps}function vw({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 yw({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 PN(t){return t==="share-files"||t==="agents"}function _N({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 FN({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,D=Math.min(1,N/S,A/k),I=Math.max(1,Math.round(S*D)),R=Math.max(1,Math.round(k*D));return h<I*.9||g<R*.9}function ON({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,D=A>=g,I=1e3/h*Yn.controlWallReuseStarvationFactor,R=!D&&Number(o)>=I,_=b&&y+k>=w,B=b?_||R:D||R;let F=w;return B&&y>0&&(!b||R?F=y+S:(F=w+S,F<=y-S&&(F=y+S))),{shouldPaint:B,nextCadenceCredit:R?0:D&&B?A-g:Math.min(g-Number.EPSILON,A),sourceCadencePassthrough:!1,deadlineForced:R,scheduleSelected:_,nextScheduledPaintAtMs:F}}function BN(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 HN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function _f({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function zN({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:o,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function $N({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),D=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),R=y*w,_=R>8&&b<R*Yn.missingDeliveryRatio,B=R>8&&S<R*Yn.missingDeliveryRatio,F=k>N||A>I||_||B,H=b>=R*Yn.recoveryDeliveryRatio&&S>=R*Yn.recoveryDeliveryRatio&&k<N*Yn.recoveryByteRatio&&A<I*Yn.recoveryGapRatio&&D<I*Yn.recoveryGapRatio;return{expectedFramesPerSecond:R,estimatedMissingFrames:_,estimatedMissingPaints:B,overloaded:F,healthyForRecovery:H}}function UN({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>=Yn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Yn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function qN({deviceCount:t,targetFps:n,adaptive:r=!0}){const o=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Yn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Yn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Yn.scalableAtlasMinInputFps,Math.min(Yn.scalableAtlasMaxInputFps,Math.floor(Yn.scalableAtlasAggregateInputFps/o)));return Math.min(l,u)}function WN(t,n){return{acceleration:Yn.directDecodeAcceleration,latencyMode:Yn.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}}},GN=[{id:"connection",label:"Connection",icon:eh},{id:"remote-access",label:"Remote Access",icon:ha},{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 bw(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 Ff({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 ww({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 VN({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(""),[D,I]=d.useState("idle"),[R,_]=d.useState(""),B=d.useRef(null),F=d.useRef(null),H=d.useRef([]),j=d.useRef(Promise.resolve()),Q=d.useRef(0),$=d.useRef(0);d.useEffect(()=>{const Se=++$.current;let ae=!0;return H.current=[],F.current=null,B.current=null,j.current=Promise.resolve(),k("loading"),rt("/api/settings",void 0,t).then(ye=>{if(!ae||Se!==$.current)return;const Pe=Mg(ye);F.current=Pe,B.current=Pe,b(Pe),k("saved")}).catch(ye=>{!ae||Se!==$.current||(A(ye instanceof Error?ye.message:String(ye)),F.current=eu,B.current=eu,b(eu),k("failed"))}),()=>{ae=!1}},[t]);const G=async(Se,ae,ye)=>{const Pe={id:++Q.current,section:Se,key:ae,value:ye},de=$.current;H.current.push(Pe);const Ke=bw(B.current||F.current||eu,Pe);B.current=Ke,b(Ke),k("saving"),A(""),j.current=j.current.then(async()=>{if(de!==$.current)return;let ue=null,Fe=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(Fe=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!==$.current)return;F.current=Mg(ke)}catch(ke){Fe=ke;break}}}if(de!==$.current)return;H.current=H.current.filter(Ee=>Ee.id!==Pe.id),ue&&(F.current=ue);const Xe=F.current||eu,at=H.current.reduce(bw,Xe);B.current=at,b(at),ue?(A(""),k(H.current.length>0?"saving":"saved")):(k(H.current.length>0?"saving":"failed"),A(Fe instanceof Error?Fe.message:String(Fe||"Settings could not be saved.")))}),await j.current},W=(Se,ae)=>ye=>{G(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 l0({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),zM(5179)}catch(Se){I("failed"),_(Se instanceof Error?Se.message:String(Se))}},X=Pp(w,"security"),ve=Pp(w,"control"),J=Pp(w,"filesAudio"),z=`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(Vx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),D==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):R?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:R}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{V()},disabled:D==="changing"||n!=="hub",type:"button",children:D==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),re=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:ha,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(ww,{value:String(X.accessMode),onChange:W("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(kr,{size:20})]}),i.jsx(Kc,{icon:kr,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(Ff,{checked:!!ve.allowKeyboardMouse,onChange:W("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(Kc,{icon:Gx,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:i.jsx(Ff,{checked:!!ve.allowRemoteRestart,onChange:W("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(Ff,{checked:!!J.allowFileTransfer,onChange:W("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(Kc,{icon:Jl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(Ff,{checked:!!J.allowRemoteAudio,onChange:W("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(Ff,{checked:!!J.rollingBufferEnabled,onChange:W("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(ww,{value:Number(J.timelapseIntervalSeconds),onChange:Se=>W("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"?re: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:GN.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:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Z})]})}function KN({children:t}){return i.jsx("div",{className:"settings-tab-content",children:t})}const xw={enabled:!1};function Sw(t){return{enabled:t?.enabled===!0}}async function QN(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 YN({hubUrl:t,showToast:n}){const[r,o]=d.useState(xw),[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 j=new AbortController;k.current=j;const Q=++S.current;return u(null),o(xw),h(""),b(""),y(""),rt("/api/settings/agent",{signal:j.signal},t).then($=>{!H||j.signal.aborted||Q!==S.current||(u($.settings),o(Sw($.settings)))}).catch($=>{H&&!j.signal.aborted&&Q===S.current&&b($ instanceof Error?$.message:String($))}),()=>{H=!1,j.abort(),k.current===j&&(k.current=null)}},[t]);const N=(H,j)=>o(Q=>({...Q,[H]:j})),A=H=>{u(H),o(Sw(H))},D=()=>({generation:S.current,controller:k.current}),I=H=>H.generation===S.current&&H.controller!==null&&H.controller===k.current&&!H.controller.signal.aborted,R=async()=>{if(!l){b("Agent settings are not available yet.");return}const H=D();if(I(H)){h("save"),b(""),y("");try{if(await QN(r.enabled,t,H.controller.signal),!I(H))return;const j=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(j.settings),y("Codex Agent settings saved.")}catch(j){I(H)&&b(j instanceof Error?j.message:String(j))}finally{I(H)&&h("")}}},_=async()=>{const H=D();if(I(H)){h("test"),b(""),y("");try{const j=await rt("/api/settings/agent/test",{method:"POST",signal:H.controller.signal,body:JSON.stringify({})},t);if(!I(H))return;const Q=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(Q.settings);const $=Number.isFinite(j.connection?.latencyMs)?Math.max(0,Math.round(j.connection.latencyMs)):null;n(`Codex Agent connection verified${$!==null?` in ${$} ms.`:"."}`,"success")}catch(j){I(H)&&b(j instanceof Error?j.message:String(j))}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(ha,{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(hk,{size:15})," ",f==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(gk,{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:()=>{R()},disabled:!F||f!=="",type:"button",children:[i.jsx(vk,{size:15})," ",f==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function ho(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 Dd(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 XN(t,n="data-id"){const r=Dd(t,n);return r?r.getAttribute(n):null}function im(t,n="data-id"){const r=Dd(t,n);return r?uh(r,n):null}function uh(t,n="data-id"){const r=t.getAttribute(n);return r?ZN(r):null}function _a(t){return typeof t=="string"?":"+t:t}function ZN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function JN(){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 ls=JN();function Bv(t){Object.assign(ls,t)}function Cw(t,n,r){function o(l){const u=Dd(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)}ls.addEvent(t,r,o)}function Id(t,n){Cw(t,n,"click"),n.dblclick&&Cw(t,n.dblclick,"dblclick")}function eT(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function tT(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 Z0=new Date,Qp=!1,pp=[],rl=[],kw=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>Z0)&&!o.contains(n)&&o!==n&&(tT(o,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},nT=t=>{Z0=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 go(t,n){pp.length||(pp=[ls.addGlobalEvent("click",kw,t),ls.addGlobalEvent("contextmenu",kw,t),ls.addGlobalEvent("mousedown",nT,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return rl.push(r),{destroy(){eT(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,Mw=t=>t.indexOf("fit")!==-1,Of=t=>t.indexOf("overlap")!==-1,aT=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),rT=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function sT(t,n){let r=0;const o=ls.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 fa,xr,Bf,tr;function J0(t,n,r="bottom",o=0,l=0){if(!t)return null;fa=o,xr=l,Bf="auto";let u=0,f=0,h=r;const g=eS(t),y=Of(r)?ls.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=sT(n,g);u=Math.max(B+1,20)}if(n){if(tr=n.getBoundingClientRect(),Mw(r)&&(Bf=tr.width+"px"),r!=="point")if(aT(r))Mw(r)?fa=0:(fa=S.width/2,f=1),xr=(S.height-b.height)/2;else{const B=Of(r)?0:1;fa=vp(r)?tr.right+B:tr.left-B,xr=hp(r)?tr.bottom+1:tr.top;const F=rT(r);F&&(vp(r)||gp(r)?F==="center"?xr-=(b.height-tr.height)/2:F==="end"&&(xr-=b.height-tr.height):(hp(r)||Ag(r))&&(F==="center"?fa-=(b.width-tr.width)/2:F==="end"&&(fa-=b.width-tr.width),Of(r)||(fa+=1)))}}else tr={left:o,right:o,top:l,bottom:l};const A=(gp(r)||vp(r))&&(hp(r)||Ag(r));gp(r)&&(f=2);const D=fa-b.width-S.left;n&&gp(r)&&!A&&D<0&&(fa=tr.right,f=0,h=h.replace("left","right"));const I=fa+b.width*(1-f/2)-S.right;if(I>0)if(!vp(r))fa=S.right-N.right-b.width;else{const B=tr.left-S.x-b.width;n&&!A&&B>=0?(fa=tr.left-b.width,h=h.replace("right","left")):fa-=I+N.right}f&&(fa=Math.round(fa-b.width*f/2));const R=D<0||I>0||!A;Ag(r)&&(xr=tr.top-b.height,n&&xr<S.y&&R&&(xr=tr.bottom,h=h.replace("top","bottom")));const _=xr+b.height-S.bottom;return _>0&&(n&&hp(r)&&R?(xr-=b.height+tr.height+1,h=h.replace("bottom","top")):xr-=_+N.bottom),fa-=w.left+N.left,xr-=w.top+N.top,fa=(Of(r)?fa:Math.max(fa,0))+y.scrollLeft,xr=(Of(r)?xr:Math.max(xr,0))+y.scrollTop,Bf=Bf||"auto",{at:h,x:fa,y:xr,z:u,width:Bf}}function eS(t){const n=ls.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 iT(t){const n=[];let r=t;const o=ls.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 Aw=new Date().valueOf();function Hv(){return Aw+=1,Aw}function Cr(t){return t<10?"0"+t:t.toString()}function oT(t){const n=Cr(t);return n.length==2?"0"+n:n}function tS(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 Nw=["",""];function lT(t,n,r){switch(t){case"%d":return Cr(n.getDate());case"%m":return Cr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return Cr(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 Cr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return Cr(n.getHours());case"%i":return Cr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||Nw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||Nw)[1];case"%s":return Cr(n.getSeconds());case"%S":return oT(n.getMilliseconds());case"%W":return Cr(Ng(n));case"%w":{const o=r.weekStart??1;if(o===1)return Cr(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)),Cr(Ng(f))}case"%c":{let o=n.getFullYear()+"";return o+="-"+Cr(n.getMonth()+1),o+="-"+Cr(n.getDate()),o+="T",o+=Cr(n.getHours()),o+=":"+Cr(n.getMinutes()),o+=":"+Cr(n.getSeconds()),o}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var cT=/%[a-zA-Z]/g;function Ad(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(cT,o=>lT(o,r,n))):""}}function Tw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function hv(t,n){for(const r in n){const o=n[r];Tw(t[r])&&Tw(o)?t[r]=hv({...t[r]},n[r]):t[r]=n[r]}return t}function um(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),um(o)}}}var uT=n0();const dT="en-US",fT={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},mT={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},pT={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},nS={core:mT,calendar:fT,formats:pT,lang:dT},zv=d.createContext(""),aS=d.createContext({}),Mi=d.createContext(null),rS=d.createContext(null),Oa=Object.freeze(Object.defineProperty({__proto__:null,fieldId:rS,helpers:aS,i18n:Mi,theme:zv},Symbol.toStringTag,{value:"Module"}));function sS(t){const n=d.useContext(rS),[r]=d.useState(()=>t||n||Hv());return r}function tm({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 hT({id:t,label:n="",inputValue:r="",value:o=!1,onChange:l,disabled:u=!1,css:f=""}){const h=sS(t),[g,y]=ho(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||gT(l.current)||ls.getTopNode(l.current))},[l.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?uT.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function gT(t){const n=ls.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function vT({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,D]=d.useState(!1),I=d.useRef(null),R=d.useRef(null),_=d.useRef(f);d.useEffect(()=>{_.current=f},[f]);function B(H){return o&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(j,Q)=>(Q=Q*o.offsetWidth/100+"px",l.replace(j,Q))):l&&l!=="auto"?l:H}const F=d.useCallback(()=>{if(!I.current)return;const H=J0(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=Q=>{_.current&&Q.target!==R.current&&I.current&&!I.current.contains(Q.target)&&_.current(Q)};let j;return requestAnimationFrame(()=>{F(),D(!0),g&&I.current&&(R.current=eS(I.current),R.current&&R.current.addEventListener("scroll",H,!0)),o&&(j=new ResizeObserver(F),j.observe(o))}),()=>{g&&R.current&&R.current.removeEventListener("scroll",H,!0),j?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[o,r,t,n]),d.useEffect(()=>{const H=j=>{_.current&&_.current(j)};if(I.current)return go(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 yT({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 go(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(yT,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):i.jsx($v,{children:i.jsx(vT,{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 um(nS)}function bT(){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=im(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 Rw=10,wT=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:o}){return i.jsxs(i.Fragment,{children:[n&&i.jsx(hT,{id:t.id,css:"wx-list-checkbox",value:o&&o.includes(t.id)}),r?Ov(r,{option:t}):t.label]})});function jw({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(wT,{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(bT()),[S,k]=d.useState(null),N=d.useRef(S),[A,D]=d.useState(0),[I,R]=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 j=d.useRef(0);d.useEffect(()=>{j.current=I},[I]);const Q=d.useCallback(ae=>{ae&&ae.stopPropagation();const ye=F.current,Pe=H.current,de=N.current;let Ke;const ue=ye[de]?.id;f?Pe&&Pe.includes(ue)?Ke=Pe.filter(Fe=>Fe!==ue):Ke=[...Pe||[],ue]:Ke=ue,r&&r({id:Ke})},[f,r]),$=d.useRef(Q);d.useEffect(()=>{$.current=Q},[Q]);const G=d.useCallback(ae=>{if(y.current){let ye=ae*j.current-y.current.clientHeight+j.current;D(ye),y.current.scrollTop=ye}},[j.current]),W=d.useCallback(ae=>{y.current=ae,l&&(ae&&!w.current&&N.current!==null&&requestAnimationFrame(()=>{y.current&&(G(N.current),w.current=!0)}),ae||(w.current=!1))},[G]),V=d.useCallback(ae=>{if(!ae||_.current)return;const ye=ae.getBoundingClientRect().height;ye&&(R(ye),j.current=ye,_.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ae=>{k(ae),N.current=ae},ae=>$.current(ae),l)},[t,y.current,l]),d.useEffect(()=>{const ae=(Pe,de)=>{b.current.navigate(Pe,de),G(N.current)},ye=(Pe,de)=>{const Ke=N.current,ue=F.current;if(Ke!==0&&Ke!==ue.length-1&&(Pe.key==="ArrowDown"||Pe.key==="ArrowUp")&&Pe.preventDefault(),b.current.keydown(Pe,de),y.current){const Fe=y.current.scrollTop<=N.current*j.current,Xe=y.current.scrollTop+y.current.clientHeight>=N.current*j.current+j.current;Fe?Xe||G(N.current):(y.current.scrollTop=N.current*j.current,D(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]),z=d.useCallback(ae=>{l&&D(ae.target.scrollTop)},[l]),P=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,A]),re=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-Rw),end:Math.min(t.length,ye+Rw)}},[l,t,A,I,P]),we=d.useMemo(()=>{if(!l)return t;const{start:ae,end:ye}=re;return t.slice(ae,ye).map(Pe=>({...Pe}))},[l,t,re]),Z=re.start*I,Se=t.length*I;return d.useEffect(()=>{l&&D(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:W,onClick:Q,onMouseMove:b.current.move,onScroll:z,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(jw,{visibleRange:re,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h})})}):i.jsx(jw,{visibleRange:re,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=sS(n),[D,I]=ho(t),R=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 $=setTimeout(()=>{o&&R.current&&R.current.focus(),l&&R.current&&R.current.select()},1);return()=>clearTimeout($)},[o,l]);const F=d.useCallback($=>{const G=$.target.value;I(G),N&&N({value:G,input:!0})},[N]),H=d.useCallback($=>N&&N({value:$.target.value}),[N]);function j($){$.stopPropagation(),I(""),N&&N({value:""})}let Q=u;return u!=="password"&&u!=="number"&&(Q="text"),d.useEffect(()=>{const $=H,G=R.current;return G.addEventListener("change",$),()=>{G&&G.removeEventListener("change",$)}},[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:R,id:A,readOnly:r,disabled:h,placeholder:f,type:Q,title:y,value:D,onInput:F}),k&&!h&&D?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:j}),B&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`})]}):S?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`}):null]})}function xT({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 Ad(u.monthYearFormat,l)(t);case"year":return Ad(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=tS(f),b=Ad(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 ST({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,j)=>new Date(F.getFullYear(),F.getMonth()+(H||0),F.getDate()+(j||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 D(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]),R=d.useMemo(()=>{const F=k(),H=N(),j=n.getMonth();let Q=[];for(let $=F;$<=H;$.setDate($.getDate()+1)){const G={day:$.getDate(),in:$.getMonth()===j,date:$.valueOf()};let W="";if(W+=G.in?"":" wx-inactive",W+=I.indexOf(G.date)>-1?" wx-selected":"",b){const V=G.date==I[0],X=G.date==I[1];V&&!X?W+=" wx-left":X&&!V&&(W+=" wx-right"),G.date>I[0]&&G.date<I[1]&&(W+=" wx-inrange")}if(W+=S($)?" wx-weekend":"",o){const V=o($);V&&(W+=" "+V)}Q.push({...G,css:W})}return Q},[n,I,b,o]),_=d.useRef(null);let B=d.useRef({});return B.current.click=D,d.useEffect(()=>{Id(_.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:R.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 CT({value:t,current:n,part:r,onCancel:o,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=ho(t||f.current),[y,w]=ho(n||f.current),b=d.useContext(Mi).getRaw().calendar,S=b.monthShort||[],k=d.useMemo(()=>y.getMonth(),[y]),N=d.useCallback((I,R)=>{if(I!=null){R.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(iS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),D=d.useCallback(I=>{const R=I.target.closest("[data-id]");if(R){const _=parseInt(R.getAttribute("data-id"),10);N(_,I)}},[N]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:D,children:S.map((I,R)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(k===R?" wx-current":""),"data-id":R,children:I},R))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx(Wv,{onClick:A,children:b.done})})]})}const Tg="wx-1XEF33",kT=({value:t,current:n,onCancel:r,onChange:o,onShift:l,part:u})=>{const f=d.useContext(Mi).getRaw().calendar,[h,g]=ho(n),[y,w]=ho(t),b=d.useMemo(()=>h.getFullYear(),[h]),S=d.useMemo(()=>{const{start:I,end:R}=tS(b),_=[];for(let B=I;B<=R;++B)_.push(B);return _},[b]),k={click:N};function N(I,R){if(I){R.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(iS(y,u)||h);I.setFullYear(h.getFullYear()),o&&o(I)}const D=d.useRef(null);return d.useEffect(()=>{D.current&&Id(D.current,k)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Tg+" wx-years",ref:D,children:S.map((I,R)=>i.jsx("div",{className:Tg+` wx-year ${b==I?"wx-current":""} ${R===0?"wx-prev-decade":""} ${R===11?"wx-next-decade":""}`,"data-id":I,children:I},R))}),i.jsx("div",{className:Tg+" wx-buttons",children:i.jsx(Wv,{onClick:A,children:f.done})})]})},Ew={month:{component:ST,next:AT,prev:MT},year:{component:CT,next:TT,prev:NT},duodecade:{component:kT,next:jT,prev:RT}};function MT(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function AT(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function NT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-1),t}function TT(t){return t=new Date(t),t.setFullYear(t.getFullYear()+1),t}function RT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-10),t}function jT(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function iS(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 ET=["clear","today"];function DT(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function IT({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?ET:[],k=(R,_)=>{R.preventDefault(),g&&g({value:_})},N=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},A=R=>{const{diff:_,current:B}=R;if(_===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(_){const F=Ew[w];r(_>0?F.next(n):F.prev(n))}else B&&r(B);h&&h()},D=R=>{b("month"),g&&g({select:!0,value:R})},I=d.useMemo(()=>Ew[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(xT,{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:D,onShift:A}),w==="month"&&S.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:S.map(R=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx(Wv,{onClick:_=>k(_,DT(R)),children:y(R)})},R))})]})]})})}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=um(nS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return i.jsx(Mi.Provider,{value:u,children:o})}function Dw(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 LT=["clear","today"];function oS({value:t,current:n,markers:r=null,buttons:o=LT,css:l="",onChange:u}){const[f,h]=ho(t),[g,y]=ho(n);d.useEffect(()=>{Dw(g,f,y,!1)},[f,g]);const w=d.useCallback(S=>{const k=S.value;k?(h(new Date(k)),Dw(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(IT,{value:f,current:g,markers:r,buttons:o,css:l,onChange:w,onCurrentChange:b})}):null}function PT(t){return t||(t={}),t.width||(t.width="unset"),t}const _T=["clear","today"];function FT({value:t,id:n,disabled:r=!1,error:o=!1,placeholder:l="",format:u="",buttons:f=_T,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(),D=u||A?.dateFormat;let I=typeof D=="function"?D:Ad(D,N);const[R,_]=d.useState(t),[B,F]=d.useState(!1);d.useEffect(()=>{_(t)},[t]);function H(){F(!1)}function j(G){const W=G===R||G&&R&&G.valueOf()===R.valueOf()||!G&&!R;_(G),W||S&&S({value:G}),setTimeout(H,1)}const Q=d.useMemo(()=>R?I(R):"",[R,I]);function $({value:G,input:W}){if(!w&&!b||W)return;let V=typeof w=="function"?w(G):G?new Date(G):null;V=isNaN(V)?R||null:V||null,j(V)}return d.useEffect(()=>{const G=H;return window.addEventListener("scroll",G),()=>window.removeEventListener("scroll",G)},[]),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:Q,id:n,readonly:!w,disabled:r,error:o,placeholder:l,onInput:H,onChange:$,icon:"wxi-calendar",clear:b}),B&&!r&&i.jsx(Uv,{onCancel:H,...PT(k),children:i.jsx(oS,{buttons:f,value:R,onChange:G=>j(G.value)})})]})}function OT({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[D,I]=ho(t);function R(j){N.current=j.navigate,A.current=j.keydown}const _=d.useMemo(()=>D||D===0?(r||n).find(j=>j.id===D):null,[D,r,n]),B=d.useCallback(({id:j})=>{(j||j===0)&&(I(j),N.current(null),S&&S({value:j}))},[I,S]),F=d.useCallback(j=>{j.stopPropagation(),I(""),S&&S({value:""})},[I,S]),H=d.useCallback(()=>n.findIndex(j=>j.id===D),[n,D]);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:j=>A.current(j,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&&D?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:R,onSelect:B,...k,children:({option:j})=>b?b(j):j[g]})]})}const BT=({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 HT({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 zT({data:t=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>i.jsx(HT,{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(tm,{type:`block ${S==="ok"?"primary":"secondary"}`,onClick:k=>b(k,S),children:g(S)})},S))})]})})}function $T({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(zT,{data:l})]})}const UT=d.forwardRef($T);function qT(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(aS.Provider,{value:o,children:i.jsx(UT,{ref:r,children:n})})}const WT=({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]=ho(t),D=d.useMemo(()=>(N?"pressed":"")+(n?" "+n:""),[N,n]),I=d.useCallback(R=>{let _=!N;u&&u(R),R.defaultPrevented||(A(_),k&&k({value:_}))},[N,u,k]);return N&&S?i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o,children:Ov(S,{value:N})}):b?i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o,children:b}):i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o})};function GT(){return i.jsx(i.Fragment,{})}function Iw(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(GT,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Bv(ls);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 lS=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 VT=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]:Lw(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);KT(h,y);const w=l?g.data.length:yp(g,u.id)+(n==="after"?1:0);if(Lw(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&&cS(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 cS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&cS(r.data,n)})}function KT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Lw(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 uS=2,QT=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&uS?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 Pw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var YT=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=>dS(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,uS);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 dS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>dS(u,n,r+1));return Math.max(...l)}var XT=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 wd=1024;function om(t){return t<wd?`${t} B`:t<wd**2?`${(t/wd).toFixed(1)} KB`:t<wd**3?`${(t/wd**2).toFixed(1)} MB`:`${(t/wd**3).toFixed(1)} GB`}function _w(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(Fw(n)),u=o.sort(Fw(n));return[...l,...u]}function ZT(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 JT(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 Fw({key:t,order:n}){const r=n==="asc"?ZT:JT;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 eR(t){return t.length>1?t[t.length-2].id:null}let tR=class extends VT{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()}}},nR=class extends QT{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=_w(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=_w(y,b[w]),k=[];k[u]={_selected:S},this.setState({panels:k},f)}});this._router=new YT(super.setState.bind(this),r,{data:u=>new tR(u)});const o=this.in=new XT;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(R=>R.id==w[g]._lastSelected),D=N.findIndex(R=>R.id==u);D<A&&([A,D]=[D,A]);const I=N.slice(A,D+1).map(R=>R.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]=Pw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[o]});const r={panels:Pw(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 aR(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 rR(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 sR(t,n="data-id"){const r=rR(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function iR(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(D=>D.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:D,_selectNavigation:I}=h;if(I){const R=eR(D);if(R){const _=Kv(R,D);r.exec("set-path",{id:R,selected:[_]})}}else if(g.length===1){const R=r.getFile(g[0]);R&&r.exec(R.type==="folder"?"set-path":"open-file",{id:R.id})}break}case"arrowup":case"arrowleft":{const{_files:D,_selected:I,path:R,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(0).id,H=D.findIndex(j=>j.id===F);if(H!==-1){const j=H-1;D[j]?B=D[j].id:R!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(_)break;if(R!=="/"){r.exec("select-file",{type:"navigation"});break}B=D.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:D,_selected:I,path:R,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(-1).id,H=D.findIndex(j=>j.id===F);if(H!==-1){const j=H+1;D[j]&&(B=D[j].id)}}else{if(R!=="/"&&!_){r.exec("select-file",{type:"navigation"});break}B=D.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:+sR(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}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=t.getAttribute(n);return r?cR(r):null}function cR(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function uR(){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 dR=uR();new Date().valueOf();function fS(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 fR(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 fR(o[n],r[n],n)}function mR(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 mR(o[n],r[n])}function mS(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 pS(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 Ow(t,n,r){function o(l){const u=oR(l);if(!u)return;const f=lR(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 dR.addEvent(t,r,o)}function pR(t,n){const r=[Ow(t,n,"click")];return n.dblclick&&r.push(Ow(t,n.dblclick,"dblclick")),()=>{r.forEach(o=>o())}}function hS(t,n){return t.map((r,o)=>{const l=n(r,o);return r.data&&r.data.length&&(l.data=hS(r.data,n)),l}).filter(Boolean)}function gS(t,n){const r=[];return t.forEach(o=>{if(o.data){const l=gS(o.data,n);l.length&&r.push({...o,data:l})}else n(o)&&r.push(o)}),r}function hR(t){return hS(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 vS={};function gR(t){return vS[t]||t}function vR(t,n){vS[t]=n}function yR({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?gR(r.comp):null,[r]);return i.jsxs("div",{ref:o,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":_a(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),[D,I]=d.useState(),R=d.useRef(null),[_,B]=d.useState(!1),[F,H]=d.useState(null),j=d.useCallback(()=>{const ve=J0(R.current,l,o,n,r);ve&&(b(ve.x),k(ve.y),I(ve.width));let J=ve?.z??20;const z=l?iT(l):[];let P=0;for(const re of z){const we=parseInt(getComputedStyle(re).zIndex,10);we>P&&(P=we)}P>=J&&(J=P+1),A(J)},[l,o,n,r]);d.useEffect(()=>{u&&u(j)},[]);const Q=d.useCallback(()=>{B(!1)},[]),$=d.useCallback((ve,J)=>{B(ve),H(J)},[]),G=d.useMemo(()=>hR(t),[t]);d.useEffect(()=>{j()},[l,j]);const W=d.useRef(g),V=d.useRef(y),X=d.useRef(l);return d.useEffect(()=>{W.current=g},[g]),d.useEffect(()=>{V.current=y},[y]),d.useEffect(()=>{X.current=l},[l]),d.useEffect(()=>{if(!R.current)return;function ve(J){V.current?V.current(J):W.current&&W.current({action:null,option:null})}return go(R.current,{callback:ve,modal:!0,parent:()=>X.current}).destroy},[]),i.jsx("div",{ref:R,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:S+"px",left:w+"px",width:D,zIndex:N},onMouseLeave:Q,children:G.map(ve=>i.jsxs(d.Fragment,{children:[ve.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(yR,{option:ve,onShow:$,onClick:J=>{if(!ve.data&&!J.defaultPrevented){const z={context:f,action:ve,option:ve,event:J};ve.handler&&ve.handler(z),g&&g(z),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 yS=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),[D,I]=d.useState(0),R=d.useRef(null),_=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),B=d.useMemo(()=>w!==null&&f?gS(r,Q=>f(Q,w)):r,[w,f,r]);function F(Q){k(null),y&&y(Q)}function H(Q){if(R.current===Q){R.current=null;return}k(null),y&&y({action:null,option:null})}const j=d.useCallback((Q,$)=>{if(!Q){k(null);return}if(Q.defaultPrevented)return;const G=Q.target;if(G&&G.dataset&&G.dataset.menuIgnore)return;if(S&&S===G){k(null),Q.preventDefault();return}A(Q.clientX+1),I(Q.clientY+1);let W=typeof $<"u"?$:im(G,_);l&&(W=l(W,Q),!W)||(b(W),k(G),R.current=Q.nativeEvent||Q,Q.preventDefault())},[S,_,l]);return d.useImperativeHandle(n,()=>({show:j}),[j]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:j,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,S?i.jsx($v,{children:i.jsx(Qv,{css:h,at:o,top:D,left:N,parent:S,context:w,onClick:F,onCancel:H,options:B},S)}):null]})}),bR=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]})}),wR=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(yS,{css:h,at:o,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),xR={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 SR=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 bS(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 SR(r,l,f,g,t)),y.current.files=n,y.current.ready=o,y.current.signal=u,y.current.drag=h,y.current}function CR(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return um(xR).getGroup(n)}}const kR=()=>Math.random().toString(36).substr(2,9),MR=({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=bS(),A=t||N,D=d.useContext(Oa.i18n),I=CR(D,"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 R=G=>{const W=new FormData;return W.append("upload",G.file),fetch(l,{method:"POST",body:W}).then(V=>V.json()).then(V=>({id:G.id,...V}),()=>({id:G.id,status:"error"})).catch(V=>(console.log(V),{id:G.id,status:"error"}))},_=(G,W)=>{const V=A.updateFile(G,W),X={...V,status:A.getState()};V&&V.uploaded&&V.uploaded(X),y&&y(X),V.temp&&A.deleteFile(V.id)},B=G=>{if(!G)return;const W=typeof l=="function"?l(G):R(G);A.setReady(W.then(V=>{V.status=V.status||"server",_(G.id,V)}).catch(V=>{_(G.id,{status:"error",error:V})}))},F=(G,W)=>{const V={...W||S,id:kR(),status:"client",name:G.name,file:G};V.selected&&V.selected(V),g&&g(V),A.addFile(V,r),B(V),w.current&&(w.current.value="")},H=(G,W,V)=>{G.isFile?G.file(X=>{F(X,V)}):G.isDirectory&&G.createReader().readEntries(X=>{X.forEach(ve=>{H(ve,W+ve.name+"/",V)})})},j=G=>{Array.from(G.target.files).forEach(W=>F(W))},Q=(G,W)=>{Array.from(G.dataTransfer.items).forEach(V=>{const X=V.webkitGetAsEntry();X&&H(X,"",W)})},$=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(A.signal){const[G,W,V]=A.signal;k(W),G==="click"?$():G==="drop"&&Q(V,W),A.setSignal(null)}},[A.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:j,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:j,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:$,children:I("select files")})]})})]})};new Date().valueOf();function AR(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 AR(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 wS=2,NR=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&wS?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}}}},TR=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=>xS(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,wS);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 xS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>xS(u,n,r+1));return Math.max(...l)}var RR=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 jR(t){return n=>n[t]}function ER(t){return(n,r)=>n[t]=r}function ic(t,n){return(n.getter||jR(n.id))(t)}function Rg(t,n,r){return(n.setter||ER(n.id))(t,r)}function DR(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 IR(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=Bw("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=Bw("footer",f,o,u,l)),o}function Bw(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 LR="portrait",PR=100,_R="a4",FR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function OR(t,n){const r=[];let o=[],l=0;const u=t.filter(h=>!h.hidden),f=BR(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 Hw(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 BR(t){const{mode:n,ppi:r,paper:o}=t,{width:l,height:u}=FR[o];return HR(n==="portrait"?l:u,r)}function HR(t,n){return t*n}function zR(t={}){const{mode:n,ppi:r,paper:o}=t;return{mode:n||LR,ppi:r||PR,paper:o||_R}}function SS(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 $R(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 zw=["resize-column","hide-column","update-cell"],UR=["delete-row","update-row","update-cell"],qR=["move-item"],WR=["resize-column","move-item"];class GR{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(WR.includes(r)){(o.inProgress&&!this.progress[r]||typeof o.inProgress!="boolean")&&(qR.includes(r)&&this.setPrev("flatData"),zw.includes(r)&&this.setPrev("columns")),this.progress[r]=o.inProgress;return}UR.includes(r)&&this.setPrev("data"),zw.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 CS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function VR(t,n){return-CS(t,n)}function KR(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"?CS:VR;return function(o,l){return r(ic(o,n),ic(l,n))}}function QR(t,n){if(!t||!t.length)return;const r=t.map(o=>{const l=n.find(u=>u.id==o.key);return KR(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,YR=20;function XR(){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 $w(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 D=`wx-measure-cell-${n}`;if(D+=N?` ${N}`:"",A=Yp(w,D,l).width,(k>1||!h[y+1])&&r>y+1){const I=k||r-y,R=u.slice(y,y+I).reduce((_,B)=>_+B,0);if(R<A){const _=Math.ceil((A-R)/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 ZR(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 JR(t,n){const r="wx-measure-cell-header",o=t.sort?YR: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 ej={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&&nj(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 kS(t){return ej[t]}function tj(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):kS(f)(y,h)})}return o=>{for(let l=0;l<r.length;l++)if(!r[l](o))return!1;return!0}}function nj(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let aj=class extends NR{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 TR(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 RR;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(D=>D.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(D=>D.id===S[S.length-1]),A=k.findIndex(D=>D.id===l);N>A&&([N,A]=[A,N]),k.slice(N,A+1).forEach(D=>{this.isSelected(D.id)||S.push(D.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=ZR(b,A,k)}if(f==="header"||f===!0){const{_skin:S}=this.getState();y=Math.max(JR(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 R=[...w];R.sort(h),this.setState({data:R});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 D=Object.keys(k).sort((R,_)=>k[R].index-k[_].index).map(R=>({key:R,order:k[R].order}));this.setState({sortMarks:k});const I=QR(D,y);if(I){const R=[...w];b?this.sortTree(R,I):R.sort(I),this.setState({data:R})}}),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??tj(S,b);let A=[];w?A=this.filterTree(y,N,A):y.forEach(D=>{N(D)&&A.push(D.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(D=>D.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=IR(this.getState(),l.csv||{});l.download!==!1?DR(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(D=>D.id===l.column);k=u[A].width;for(let D=f.left??0;D<A;D++){const I=u[D];I.hidden||(b+=I.width)}}if(l.row&&!y){const A=g.findIndex(D=>D.id===l.row);A>=0&&(w?(S=g.slice(0,A).reduce((D,I)=>D+(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=zR(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=XR()),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 GR(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):kS(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=$w(n,"header",o,r.headerHeight,u),h=$w(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}}},rj=new Date().valueOf();function wp(){return"temp://"+rj++}function sj(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 ij=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)}}},Nd=[],oj={subscribe:t=>{lj();const n=new ij;return Nd.push(n),t(n),()=>{const r=Nd.findIndex(o=>o===n);r>=0&&Nd.splice(r,1)}}},Uw=!1;function lj(){Uw||(Uw=!0,document.addEventListener("keydown",t=>{if(Nd.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=Nd.length-1;l>=0;l--){const u=Nd[l],f=u.store.get(o)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:o,evKey:r})}}}))}const cj={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 uj(t,{keys:n,exec:r}){if(!n)return;function o(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||sj(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=oj.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function dj(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 Ds=d.createContext(null);function fj(t,n){const r=new ResizeObserver(o=>{requestAnimationFrame(()=>n(o[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const qw=5,mj=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 pj(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(j){const Q=Dd(j);Q&&(o={container:g,sourceNode:j.target,from:uh(Q),pos:yv(j,t)},u=o.pos,b(j))}function b(j){if(!o)return;const Q=o.pos=yv(j,t);if(!f){if(!h&&!j?.target?.getAttribute("draggable-data")&&Math.abs(u.x-Q.x)<qw&&Math.abs(u.y-Q.y)<qw)return;if(F(j)===!1)return H()}if(h){const $=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,G=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;o.targetNode=document.elementFromPoint(j.pageX-$,j.pageY-G)}else o.targetNode=j.target;r.move&&r.move(j,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(j){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(j,o),o=u=null,H()}function k(j){r.getReorder&&!r.getReorder()||j.button===0&&(B(j),window.addEventListener("mousemove",N),window.addEventListener("mouseup",A),w(j))}function N(j){b(j)}function A(j){S(j)}function D(j){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(j.touches[0])},mj),B(j);function Q(){l&&y(),j.target.removeEventListener("touchmove",I),j.target.removeEventListener("touchend",Q),S(j)}j.target.addEventListener("touchmove",I),j.target.addEventListener("touchend",Q),t.addEventListener("contextmenu",R)}function I(j){f?(j.preventDefault(),b(j.touches[0])):l&&y()}function R(j){if(f||l)return j.preventDefault(),!1}function _(j){j.preventDefault()}function B(j){if(!r.getDraggableInfo)return;const{hasDraggable:Q}=r.getDraggableInfo();(!Q||j.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(j){if(f=!0,r.start){if(r.start(j,o)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function H(j){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",A),j&&(t.removeEventListener("mousedown",k),t.removeEventListener("touchstart",D),t.removeEventListener("dragstart",_))}return t.addEventListener("mousedown",k),t.addEventListener("touchstart",D),t.addEventListener("dragstart",_),{destroy(){H(!0)}}}const hj=.004;function gj(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function vj(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=gj());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)&&(MS(r),r.scrollState.dirX=S,r.scrollState.dirY=k),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&yj(r,o,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function yj(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(bj,15,t,n,r)},250))}function MS(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function bj(t,n,r){const{x:o,y:l}=r;t.scrollSpeedFactor+=hj,o!==0&&xj(t,n,o),l!==0&&wj(t,n,l)}function wj(t,n,r){const o=n.node.scrollTop;AS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function xj(t,n,r){const o=n.node.scrollLeft;AS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function AS(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 NS(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 Sj(t){const{row:n,column:r,cellStyle:o=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(Ds),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 j="wx-cell";return j+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",j+=F?" "+F(r):"",j+=H?" "+H(n,r):"",j+=r.treetoggle?" wx-tree-cell":"",j}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]),D=d.useRef(null);d.useEffect(()=>{D.current&&f&&g?.row===n.id&&g?.column===r.id&&D.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 R(F){const H=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(H).map(j=>({text:j,highlight:H.test(j)}))}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:D,onFocus:I,style:S,"data-row-id":_a(n.id),"data-col-id":_a(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:R(tc(n,r)).map(({highlight:F,text:H},j)=>F?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:H},j):i.jsx("span",{children:H},j))}):tc(n,r)]})}function Ww(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 Cj({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 kj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Ds),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(OT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:o,onChange:y,children:b=>h?h(b):b.label})})}function Mj({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(FT,{placeholder:"",clear:!0,...t?.config??{},value:o,onChange:l})})}function TS(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]=fS(n||[]),N=d.useMemo(()=>(S||[]).map(G=>r.find(W=>W.id===G)).filter(Boolean),[S,r]),A=d.useRef(null),D=d.useRef(null),[I,R]=d.useState(null),_=()=>{const G=S||[];if(!G.length)return 0;const W=r.find(V=>G.includes(V.id));return W?r.indexOf(W):0};function B(G){D.current=G.navigate,R(()=>G.keydown),y&&G.navigate(_())}d.useEffect(()=>{y&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:G}){k(G),w&&w({value:G})}function H(G){G.stopPropagation(),k([]),w&&w({value:[]})}function j(){D.current?.(_())}function Q(){D.current?.(null)}function $(G){I?.(G,_())}return i.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:j,onKeyDown:$,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(G=>G.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:Q,...g,children:({option:G})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(G):h?i.jsx(h,{data:G,onAction:b}):G.label})})]})}function Aj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Oa.i18n)?.getGroup("grid")||um(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(TS,{placeholder:"",...u,options:f,value:o||[],text:h,onChange:g})})}const Nj={text:Cj,richselect:kj,datepicker:Mj,multiselect:Aj};function Tj({filter:t,column:n}){const r=d.useContext(Ds),o=Ot(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>Nj[t.type],[t.type]);return i.jsx(u,{filter:t,column:n,action:l,filterValue:o[n.id]})}function Rj(t){const{cell:n,column:r,row:o,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(Ds),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]),D=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]),R=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"&&R()},[R]),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]),j=d.useMemo(()=>H?{top:-h/2,position:"absolute"}:{},[H,h]),Q=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]),$=d.useMemo(()=>NS(r,n,f),[r,n,f]),G=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([ve])=>ve!=="cell")),[n]),W=`wx-cell ${$} ${n.css||""} wx-collapsed`,V=["wx-cell",$,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=Ww(ve,{down:k,move:A,up:D});return()=>{typeof J=="function"&&J()}},[k,A,D,Ww]),F?i.jsx("div",{className:"wx-RsQD74qC "+W,style:Q,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:R,"data-header-id":_a(r.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:j,children:n.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+V,style:Q,onClick:I,"data-header-id":_a(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:R,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:G(),column:r,row:o,onAction:({action:J,data:z})=>y.exec(J,z)})})():n.filter?i.jsx(Tj,{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 jj({cell:t,column:n,row:r,columnStyle:o}){const l=d.useContext(Ds),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(()=>NS(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 Gw({deltaLeft:t,contentWidth:n,columns:r,type:o="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(Ds),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 D=r[0][o].length;for(let I=0;I<D;I++){let R=0;A.push([]),r.forEach((_,B)=>{const F={..._[o][I]};R||A[I].push(F),F.colspan>1?R=F.colspan-1:R&&R--})}}return A},[r,o]),b=d.useMemo(()=>g?.left||g?.right,[g]);function S(A){return r.find(D=>D.id===A)}function k(A,D){let I=D;return A.rowspan&&(I+=A.rowspan-1),I===w.length-1}function N(A,D,I){if(!I.sort)return!1;for(let R=w.length-1;R>=0;R--){const _=I.header[R];if(!_.filter&&!_._hidden)return D===R}return k(A,D)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${o}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((A,D)=>i.jsx("div",{className:o==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[D]}px`,display:"flex"},role:"row",children:A.map(I=>{const R=S(I.id);return o==="header"?i.jsx(Rj,{cell:I,columnStyle:l,column:R,row:D,lastRow:k(I,D),bodyHeight:u,sortRow:N(I,D,R),hasSplit:b},I.id):i.jsx(jj,{cell:I,columnStyle:l,column:S(I.id),row:D},I.id)})},D))})}function Ej({overlay:t}){const n=d.useContext(Ds);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 Dj(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=go(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 Ij({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(j=>j.id===u),[y,u]),D=d.useRef(null),I=d.useRef(null),R=d.useCallback(j=>{D.current=j.navigate,I.current=j.keydown,D.current(A)},[A,D]),_=d.useCallback(j=>{const Q=j?.target?.value??"";g(Q);const $=Q?(t?.options||[]).filter(G=>(G.label||"").toLowerCase().includes(Q.toLowerCase())):t?.options||[];w($),$.length?D.current(-1/0):D.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 j=go(B.current,()=>F.current(!0));return()=>j.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const H=d.useCallback(({id:j})=>{o(j),r()},[o,r]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:B,value:h??"",onChange:_,onKeyDown:j=>I.current?I.current(j,A):void 0}),i.jsx(fh,{items:y,onReady:R,onSelect:H,...N,onCancel:l,children:({option:j})=>b?b(j):S?i.jsx(S,{data:j,onAction:n}):j.label})]})}function Lj({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=go(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(oS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function Pj(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,D]=d.useState();function I(_){N=_.navigate,D(()=>_.keydown),N(S)}const R=d.useRef(null);return d.useEffect(()=>{R.current&&R.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!R.current)return;const _=go(R.current,()=>o(!0));return()=>_.destroy()},[o]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:R,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 _j(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=go(b.current,()=>o(!0));return()=>S.destroy()},[o]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>o(!0),children:i.jsx(TS,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const Fj={text:Dj,combo:Ij,datepicker:Lj,richselect:Pj,multiselect:_j};function Oj({column:t,row:n}){const r=d.useContext(Ds),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 Fj[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 Vw(t){const{columns:n,type:r,columnStyle:o}=t,l=d.useContext(Ds),{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:mS(SS(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:$R(u,f,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function Bj(t){const{columns:n,rowStyle:r,columnStyle:o,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(Ds),{flatData:y,_sizes:w}=g.getState(),b=u&&Hw(n,"header",w.headerRowHeights),S=f&&Hw(n,"footer",w.footerRowHeights);function k(A,D){let I="";return I+=o?" "+o(D):"",I+=l?" "+l(A,D):"",I}function N(A,D){return typeof D.draggable=="function"?D.draggable(A,D)!==!1:D.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(Vw,{columns:b,type:"header",columnStyle:o})}):null,i.jsx("tbody",{children:y.map((A,D)=>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:mS(SS(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 R=I.cell;return i.jsx(R,{api:g,row:A,column:I})})():i.jsx("span",{children:tc(A,I)})]},I.id))},D))}),f?i.jsx("tfoot",{children:i.jsx(Vw,{columns:S,type:"footer",columnStyle:o})}):null]})}function Hj(t){const{config:n,...r}=t,o=d.useContext(Ds),{_skin:l,_columns:u}=o.getState(),f=d.useMemo(()=>OR(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(Bj,{columns:g,...r})},y))})}function zj(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(Ds),D=Ot(A,"dynamic"),I=Ot(A,"_columns"),R=Ot(A,"flatData"),_=Ot(A,"split"),B=Ot(A,"_sizes"),[F,H]=Xs(A,"selectedRows"),j=Ot(A,"select"),Q=Ot(A,"editor"),$=Ot(A,"scrollLeft"),G=Ot(A,"scrollTop"),W=Ot(A,"tree"),V=Ot(A,"focusCell"),X=Ot(A,"_print"),ve=Ot(A,"undo"),J=Ot(A,"reorder"),z=Ot(A,"_rowHeightFromData"),[P,re]=d.useState(0);d.useEffect(()=>{re(va())},[]);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),[Ke,ue]=d.useState(null),Fe=d.useMemo(()=>{let oe=[],Ue=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=Ue,Ue+=tt.width}),oe.length&&(oe[oe.length-1].fixed.left=-1)),{columns:oe,width:Ue}},[_,I]),Xe=d.useMemo(()=>{let oe=[],Ue=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=Ue,Ue+=Pt.width}oe.length&&(oe[0].fixed={right:-1})}return{columns:oe,width:Ue}},[_,I]),at=d.useMemo(()=>{const oe=(I||[]).slice(_?.left||0,(I||[]).length-(_?.right??0)).filter(Ue=>!Ue.hidden);return oe.forEach(Ue=>{Ue.fixed=0}),oe},[I,_]),Ee=d.useMemo(()=>(I||[]).reduce((oe,Ue)=>(Ue.hidden||(oe+=Ue.width),oe),0),[I]),Ge=1;function me(oe,Ue,tt){let Pt=Ue,wn=oe;if(at.length){let Be=at.length;for(let it=oe;it>=0;it--)at[it][tt].forEach(Tt=>{Tt.colspan>1&&it>oe-Tt.colspan&&it<Be&&(Be=it)});if(Be!==at.length&&Be<oe){for(let it=Be;it<oe;it++)Pt-=at[it].width;wn=Be}}return{index:wn,delta:Pt}}const ke=d.useMemo(()=>{let oe,Ue,tt;const Pt=$||0,wn=($||0)+(b||0);let Be=0,it=0,Tt=0,bt=0;at.forEach((Ht,Pn)=>{Pt>Tt&&(Be=Pn,bt=Tt),Tt=Tt+Ht.width,wn>Tt&&(it=Pn+Ge)});const Gt={header:0,footer:0};for(let Ht=it;Ht>=Be;Ht--)["header","footer"].forEach(Pn=>{at[Ht]&&at[Ht][Pn].forEach(Ba=>{const ar=Ba.colspan;if(ar&&ar>1){const Nr=ar-(it-Ht+1);Nr>0&&(Gt[Pn]=Math.max(Gt[Pn],Nr))}})});const ra=me(Be,bt,"header"),Cn=me(Be,bt,"footer"),Un=ra.delta,Qt=ra.index,En=Cn.delta,zr=Cn.index;return Se&&Ee>(b||0)?oe=Ue=tt=[...Fe.columns,...at,...Xe.columns]:(oe=[...Fe.columns,...at.slice(Be,it+1),...Xe.columns],Ue=[...Fe.columns,...at.slice(Qt,it+Gt.header+1),...Xe.columns],tt=[...Fe.columns,...at.slice(zr,it+Gt.footer+1),...Xe.columns]),{data:oe||[],header:Ue||[],footer:tt||[],d:bt,df:En,dh:Un}},[at,Fe,Xe,$,b,Se,Ee]),Je=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)-Je-Me-(pe?P:0),[S,Je,Me,pe,P]),jt=d.useMemo(()=>Math.ceil((st||0)/(ae||1))+1,[st,ae]),O=d.useRef([]),[$e,We]=d.useState(0),[Et,lt]=d.useState(void 0),ht=d.useMemo(()=>{let oe=0,Ue=0;const tt=2,Pt=G||0;if(y){let it=Pt;for(;it>0;)it-=O.current[oe]||ae,oe++;Ue=Pt-it;for(let Tt=Math.max(0,oe-tt-1);Tt<oe;Tt++)Ue-=O.current[oe-Tt]||ae;oe=Math.max(0,oe-tt)}else{if(z){let it=0,Tt=0;for(let Cn=0;Cn<(R||[]).length;Cn++){const Un=R[Cn].rowHeight||ae;if(Tt+Un>Pt){it=Cn;break}Tt+=Un}oe=Math.max(0,it-tt);for(let Cn=0;Cn<oe;Cn++)Ue+=R[Cn].rowHeight||ae;let bt=0,Gt=0;for(let Cn=it+1;Cn<(R||[]).length;Cn++){const Un=R[Cn].rowHeight||ae;if(bt++,Gt+Un>st)break;Gt+=Un}const ra=Math.min(D?D.rowCount:(R||[]).length,it+bt+tt);return{d:Ue,start:oe,end:ra}}oe=Math.floor(Pt/(ae||1)),oe=Math.max(0,oe-tt),Ue=oe*(ae||0)}const wn=D?D.rowCount:(R||[]).length,Be=Math.min(wn,oe+(jt||0)+tt);return{d:Ue,start:oe,end:Be}},[y,z,G,ae,D,R,jt,st]),Ze=d.useMemo(()=>{const oe=D?D.rowCount:(R||[]).length;if(y)return $e+ht.d+(oe-(Et||0))*(ae||0);if(!z)return oe*(ae||0);let Ue=0;for(let tt=0;tt<oe;tt++)Ue+=R[tt]?.rowHeight||ae;return Ue},[D,R,ae,y,z,$e,ht.d,Et]),be=d.useRef({});be.current={clientWidth:b,clientHeight:S,fullHeight:Ze,headerHeight:Je,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(D&&(te.current.start!==ht.start||te.current.end!==ht.end)){const{start:oe,end:Ue}=ht;te.current={start:oe,end:Ue},A&&A.exec&&A.exec("request-data",{row:{start:oe,end:Ue}})}},[D,ht,A]);const ce=d.useMemo(()=>D?R||[]:(R||[]).slice(ht.start,ht.end),[D,R,ht]),Ne=d.useMemo(()=>(F||[]).filter(oe=>(ce||[]).some(Ue=>Ue.id===oe)),[H,ce]),He=d.useMemo(()=>ht.start,[ht.start]),Ie=d.useRef({top:G,left:$});Ie.current={top:G,left:$};const Lt=d.useCallback(oe=>{const Ue=oe.target.scrollTop,tt=oe.target.scrollLeft,Pt=Ie.current;(Ue!==Pt.top||tt!==Pt.left)&&A.exec("scroll-to",{top:Ue,left:tt})},[A]),Ye=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,Ue)=>{const tt={id:oe,column:im(Ue,"data-col-id")};A.exec("open-editor",tt)},click:(oe,Ue)=>{if(Ue.target.closest("input")||yt.current)return;const tt=im(Ue,"data-col-id");if(V?.id!==oe&&A.exec("focus-cell",{row:oe,column:tt,eventSource:"click"}),j===!1)return;const Pt=l&&(Ue.ctrlKey||Ue.metaKey),wn=l&&Ue.shiftKey;(Pt||F.length>1||!F.includes(oe))&&A.exec("select-row",{id:oe,toggle:Pt,range:wn})},"toggle-row":oe=>{const Ue=A.getRow(oe);A.exec(Ue.open!==!1?"close-row":"open-row",{id:oe})},"ignore-click":()=>!1}),Vt=d.useMemo(()=>({top:Je,bottom:Me,left:Fe.width,xScroll:pe,yScroll:qe,sense:y&&Ke?Ke.offsetHeight:Math.max(B?.rowHeight||0,40),node:ye.current&&ye.current.firstElementChild}),[Je,Me,Fe.width,pe,qe,y,Ke,B]);function Ct(oe,Ue){const{container:tt,sourceNode:Pt,from:wn}=Ue;if(ut()&&!Pt.getAttribute("draggable-data"))return!1;de(wn),W&&A.getRow(wn).open&&A.exec("close-row",{id:wn,nested:!0});const Be=Dd(Pt),it=Be.cloneNode(!0);it.classList.remove("wx-selected"),it.querySelectorAll("[tabindex]").forEach(ra=>ra.setAttribute("tabindex","-1")),tt.appendChild(it),ue(it);const Tt=($||0)-ke.d,bt=qe?P:0;tt.style.width=Math.min((b||0)-bt,Se&&Ee<=(b||0)?Ae:Ae-bt)+Tt+"px";const Gt=_p(Be);Ue.offset={x:Tt,y:-Math.round(Gt.height/2)},_t.current||(_t.current=oe.clientY)}function mn(oe,Ue){const{from:tt}=Ue,Pt=Ue.pos,wn=_p(ye.current);Pt.x=wn.x;const Be=Vt.top;if(Pt.y<Be)Pt.y=Be;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(Ue.targetNode)){const it=Dd(Ue.targetNode),Tt=it&&uh(it);if(Tt&&Tt!==tt){Ue.to=Tt;const bt=y?Ke?.offsetHeight:B?.rowHeight;if(Ke&&((G||0)===0||Pt.y>Be+bt-1)){const Gt=it.getBoundingClientRect(),ra=_p(Ke).y,Cn=Gt.y,Un=ra>Cn?-1:1,Qt=Un===1?"after":"before",En=A.getState().flatData,zr=Math.abs(En.findIndex(Pn=>Pn.id===tt)-En.findIndex(Pn=>Pn.id===Tt)),Ht=zr!==1?Qt==="before"?"after":"before":Qt;if(zr===1&&(Un===-1&&oe.clientY>_t.current||Un===1&&oe.clientY<_t.current))return;_t.current=oe.clientY,A.exec("move-item",{id:tt,target:Tt,mode:Ht,inProgress:!0})}}u&&u({event:oe,context:Ue})}vj(oe,wn,Ue,Vt)}function an(oe,Ue){const{from:tt,to:Pt}=Ue;A.exec("move-item",{id:tt,target:Pt,inProgress:!1}),yt.current=setTimeout(()=>{yt.current=0},1),de(null),ue(null),_t.current=null,MS(Ue)}function va(){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 Ue=oe.offsetWidth-oe.clientWidth;return document.body.removeChild(oe),Ue}const kt=d.useMemo(()=>fe>0?{width:`${fe}px`}:void 0,[fe]),hn=d.useRef(null);function en(){Promise.resolve().then(()=>{let oe=0,Ue=He;const tt=hn.current;tt&&(Array.from(tt.children).forEach((Pt,wn)=>{O.current[He+wn]=Pt.offsetHeight,oe+=Pt.offsetHeight,Ue++}),We(oe),lt(Ue))})}d.useEffect(()=>{ce&&y&&en()},[ce,y,He]);let[q,nt]=d.useState();d.useEffect(()=>{if(V&&(!j||!Ne.length||Ne.includes(V.row)))nt({...V});else if(ce.length&&ke.data.length){if(!q||Ne.length&&!Ne.includes(q.row)||ce.findIndex(oe=>oe.id===q.row)===-1||ke.data.findIndex(oe=>oe.id===q.column&&!oe.collapsed)===-1){const oe=Ne[0]||ce[0].id,Ue=ke.data.findIndex(tt=>!tt.collapsed);nt(Ue!==-1?{row:oe,column:ke.data[Ue].id}:null)}}else nt(null)},[V]);const Dt=d.useRef(null);d.useEffect(()=>{const oe=ye.current;if(!oe)return;const Ue=fj(oe,w);return()=>{typeof Ue=="function"&&Ue()}},[w]);const gn=d.useRef({});Object.assign(gn.current,{start:Ct,move:mn,end:an,getReorder:()=>J,getDraggableInfo:()=>({hasDraggable:ut()})}),d.useEffect(()=>{const oe=ye.current;return oe?pj(oe,gn).destroy:void 0},[J,ye.current]),d.useEffect(()=>{const oe=ye.current;return oe?uj(oe,{keys:N!==!1&&{...cj,"ctrl+z":ve,"ctrl+y":ve,...N},exec:Ue=>A.exec("hotkey",Ue)}).destroy:void 0},[A,ve,N]);const Mr=d.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});Mr.current.getWidth=()=>(b||0)-(qe?P:0),Mr.current.getHeight=()=>st,Mr.current.getScrollMargin=()=>Fe.width+Xe.width,d.useEffect(()=>{dj(Dt.current,Mr.current)},[]);const Hr=d.useRef(null);d.useEffect(()=>{const oe=Hr.current;if(!oe)return;const Ue=[];Ue.push(go(oe,()=>V&&A.exec("focus-cell",{eventSource:"click"})).destroy),Ue.push(pR(oe,mt.current)),Z(oe.clientHeight);const tt=new ResizeObserver(()=>{Z(oe.clientHeight)});return tt.observe(oe),Ue.push(()=>tt.disconnect()),()=>Ue.forEach(Pt=>Pt())},[]);const Ar=`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 "+Ar,style:{"--header-height":`${Je}px`,"--footer-height":`${Me}px`,"--split-left-width":`${Fe.width}px`,"--split-right-width":`${Xe.width}px`},children:i.jsx("div",{ref:ye,className:"wx-4VuBwK2D wx-table-box",style:kt,role:W?"treegrid":"grid","aria-colcount":ke.data.length,"aria-rowcount":ce.length,"aria-multiselectable":W&&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(Gw,{contentWidth:Ae,deltaLeft:ke.dh,columns:ke.header,columnStyle:h,bodyHeight:st-+r})}):null,i.jsxs("div",{ref:Hr,className:"wx-4VuBwK2D wx-body",style:{width:`${Ae}px`,height:`${Ze}px`},onMouseDown:oe=>Ye(oe),children:[o?i.jsx(Ej,{overlay:o}):null,i.jsx("div",{ref:hn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${ht.d}px`,paddingLeft:`${ke.d}px`},children:ce.map((oe,Ue)=>{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":""),Be=y?{minHeight:`${oe.rowHeight||ae}px`}:{height:`${oe.rowHeight||ae}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+wn,"data-id":_a(oe.id),"data-context-id":_a(oe.id),style:Be,role:"row","aria-rowindex":Ue,"aria-expanded":oe.open,"aria-level":W?oe.$level+1:void 0,"aria-selected":W?tt:void 0,tabIndex:-1,children:ke.data.map(it=>it.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},it.id):Q?.id===oe.id&&Q.column===it.id?i.jsx(Oj,{row:oe,column:it},it.id):i.jsx(Sj,{row:oe,column:it,columnStyle:h,cellStyle:g,reorder:J,focusable:q?.row===oe.id&&q?.column===it.id},it.id))},oe.id)})})]}),r&&(R||[]).length?i.jsx(Gw,{type:"footer",contentWidth:Ae,deltaLeft:ke.df,columns:ke.footer,columnStyle:h}):null]})})}),X?i.jsx(Hj,{config:X,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:J}):null]})}const $j=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),Uj=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:D,tree:I=!1,autoConfig:R=!1,init:_=null,responsive:B=null,sortMarks:F,undo:H=!1,hotkeys:j=null,filterValues:Q,...$},G){const W=d.useRef();W.current=$;const V=d.useMemo(()=>new aj(pS),[]),X=d.useMemo(()=>V.in,[V]),ve=d.useRef(null);ve.current===null&&(ve.current=new lS((Xe,at)=>{const Ee="on"+$j(Xe);W.current&&W.current[Ee]&&W.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:Xe=>(ve.current=ve.current.setNext(Xe),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]),[z,P]=d.useState(0),[re,we]=d.useState(0),[Z,Se]=d.useState(null),[ae,ye]=d.useState(null),Pe=d.useMemo(()=>{if(R&&!n.length&&t.length){const Xe=t[0],at=[];for(let Ee in Xe)if(Ee!=="id"&&Ee[0]!=="$"){let Ge={id:Ee,header:Ee[0].toUpperCase()+Ee.slice(1)};typeof R=="object"&&(Ge={...Ge,...R}),at.push(Ge)}return at}return(ae&&ae.columns)??n},[R,n,t,ae]),de=d.useMemo(()=>(ae&&ae.sizes)??A,[ae,A]),Ke=d.useCallback(Xe=>{if(P(Xe.width),we(Xe.height),B){const at=Object.keys(B).map(Number).sort((Ee,Ge)=>Ee-Ge).find(Ee=>Xe.width<=Ee)??null;at!==Z&&(ye(B[at]),Se(at))}},[B,Z]),ue=d.useContext(Oa.theme),Fe=d.useRef(0);return d.useEffect(()=>{if(!Fe.current)_&&_(J);else{const Xe=V.getState();V.init({data:t,columns:Pe,split:D||Xe.split,sizes:de||Xe.sizes,selectedRows:u||Xe.selectedRows,dynamic:w,tree:I,sortMarks:F||Xe.sortMarks,filterValues:Q||Xe.filterValues,undo:H,reorder:S,_skin:ue,_select:f})}Fe.current++},[V,t,Pe,D,de,u,w,I,F,Q,H,S,ue,f,_,J]),Fe.current===0&&V.init({data:t,columns:Pe,split:D||{left:0},sizes:de||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:Q||{},undo:H,reorder:S,_skin:ue,select:f}),d.useImperativeHandle(G,()=>({...J}),[J]),i.jsx(Ds.Provider,{value:J,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(zj,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:o,cellStyle:l,onReorder:k,multiselect:h,autoRowHeight:N,clientWidth:z,clientHeight:re,responsiveLevel:Z,resize:Ke,hotkeys:j})})})});Bv(ls);const Fa=d.createContext(null),Yv=d.createContext(null),Xv=d.createContext(null);function qj({children:t}){const n=d.useContext(Oa.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=d.useContext(Fa),[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,D]=d.useState(!1);function I(){const F=b.trim();if(!F){D(!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}),R()}function R(){g(null),D(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(qT,{children:t}),h?i.jsx(gv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:R,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 Kw={"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 Wj(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 Gj({item:t}){const n=d.useContext(Fa),r=d.useContext(Oa.i18n).getGroup("filemanager"),o=d.useContext(Fa).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(()=>Wj(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":_a("/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":_a(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":_a(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":_a(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function RS(){const t=d.useContext(Fa),n=d.useContext(Oa.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((R,_)=>{const B=_&&(_.ctrlKey||_.metaKey),F=_&&_.shiftKey;if(R==="/wx-filemanager-parent-link"){if(h.length&&(B||F))return;t.exec("select-file",{type:"navigation"});return}let H=R==="body"&&_?null:R;const j=_.target.className.indexOf("wx-more")!==-1||_.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:H,toggle:B&&!j,range:F&&!j,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(R=>{if(R==="/wx-filemanager-parent-link")return S();u==="search"&&t.exec("filter-files",{text:""});const _=f.find(B=>B.id===R);_&&(_.type=="folder"?t.exec("set-path",{id:_.id,panel:l}):t.exec("open-file",{id:_.id}))},[t,S,u,f,l]),N=d.useCallback((R,_)=>{(!h?.length||!h.filter(B=>B?.id===R).length>0)&&b(R,_)},[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]),D=d.useRef(null),I=d.useRef();return d.useEffect(()=>{D.current&&(I.current?(I.current.click=b,I.current._dblclick=k,I.current.context=N):(I.current={click:b,dblclick:R=>I.current._dblclick(R),_dblclick:k,context:N},Id(D.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":_a("body"),ref:D,children:A.map(R=>i.jsx(Gj,{item:R},R.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 Vj(){const t=d.useContext(Oa.i18n).getGroup("filemanager"),n=d.useContext(Fa),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(RS,{})]})}function jg({narrowMode:t,extraInfo:n}){const r=d.useContext(Fa),{preview:o,icon:l}=r.templates,u=d.useContext(Oa.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Ad("%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 j=g&&w!=null&&g[w]?._selected?.length||0;return S&&!j},[S,y,w]),N=d.useMemo(()=>{const j=g&&w!=null?g[w]:null;return j?k?j._files:j._selected:[]},[k,y,w]),A=d.useCallback((j,Q)=>(j?`${j} ${f(j>1?"folders":"folder")} `:"")+(Q?`${Q} ${f(Q>1?"files":"file")}`:""),[f]),D=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(j=>j.type==="folder"?f("Folder"):j.ext||f("Unknown file"),[f]),R=d.useMemo(()=>{let j,Q,$,G,W,V,X,ve;if(N.length===1&&!k){Q=N[0],j=Q.name;const J=o(Q,400,500);J?($=J,G=""):(G=l(Q,"big"),$=""),W=Q.type!=="folder"}else{if(Q=W=null,j="",N.length){let J=0,z=0,P=0,re=[],we;N.forEach(Se=>{typeof Se.size>"u"&&(we=!0,J=void 0),we||(J+=Se.size),re.push(I(Se)),Se.type==="folder"?z++:P++});const Z=new Set(re);V=Z.size>1?f("multiple"):[...Z][0],X=A(z,P),ve=J,k||(j=f("Multiple files"))}G=l({type:k?"search":N.length?"multiple":"none"},"big"),$=""}return{name:j,item:Q,previewSrc:$,iconSrc:G,showDownloadIcon:W,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 j=>{if(!n||!j)return null;try{return await n(j)}catch(Q){return console.log(Q),null}},[n]),[F,H]=d.useState(null);return d.useEffect(()=>{let j=!1;return H(null),Promise.resolve(B(R.item)).then(Q=>{j||H(Q)}).catch(()=>{j||H(null)}),()=>{j=!0}},[B,R.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:R.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[R.showDownloadIcon?i.jsx(iu,{name:"download",onClick:_}):null,t?i.jsx(iu,{name:"close",onClick:D}):null]})]}),R.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:R.previewSrc,alt:f("A miniature file preview")})}):R.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:R.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:R.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${R.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:[R.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(R.item)}),typeof R.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:om(R.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(R.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:R.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:R.type}),typeof R.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:om(R.totalSize)})]}):null]}),F?Object.entries(F).map(([j,Q])=>i.jsxs(Cv.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:j}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Q})]},j)):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:R.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?i.jsx(iu,{name:"close",onClick:D}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[R.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:R.previewSrc,alt:f("A miniature file preview")})}):R.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:R.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 jS({panel:t}){const n=d.useContext(Fa),r=d.useContext(Oa.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},Id(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":_a(N.id),"data-menu-ignore":"true",children:N.id=="/"?o(N.name):N.name})]},A))]})}function Kj({row:t}){const n=d.useContext(Oa.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),o=d.useContext(Fa).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 ES({children:t}){const n=d.useContext(Fa),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=XN(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(Fa),u=d.useContext(Oa.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Ad("%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:Kj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:V=>typeof V=="number"?om(V):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:V=>V?h(V):""}],[f,h]),D=d.useRef(null),I=d.useRef(null),R=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 z=V==="body"&&X?null:V;!D.current&&!I.current?l.exec("select-file",{id:z,toggle:ve,range:J,panel:t}):(D.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 j(V){V.intercept("sort-rows",X=>(D.current=!0,H(X),!1)),V.intercept("select-row",()=>!1),V.on("resize-column",()=>I.current=!0),V.intercept("hotkey",()=>!1)}const Q=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...N]:N,[w,N,f]),$=d.useMemo(()=>{if(Q&&S&&S[w]){const{key:V,order:X}=S[w];return{[V]:{order:X}}}},[Q,S,w]),G=d.useRef(null),W=d.useRef();return d.useEffect(()=>{W.current?(W.current.click=_,W.current._dblclick=F):(W.current={click:_,dblclick:V=>W.current._dblclick(V),_dblclick:F},Id(G.current,W.current))},[_,F]),i.jsxs("div",{onClick:r,onContextMenu:o,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(jS,{panel:t}),i.jsx("div",{"data-id":_a("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:G,children:i.jsx(ES,{children:i.jsx(Uj,{init:j,data:Q,columns:A,selectedRows:R,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:$})})})]})}function Qj(){const t=d.useContext(Fa),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":_a("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 DS({folderIcon:t=!1,folder:n={}}){const r=d.useContext(Fa),[o,l]=Xs(r,"panels"),u=Ot(r,"activePanel"),f=d.useMemo(()=>o[u].path,[l,u]),h=d.useContext(Oa.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":_a(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(DS,{folder:k},k.id):null)}):null]})}function Yj(){const t=d.useContext(Fa),[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},Id(b.current,S.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(k=>k.type==="folder"?i.jsx(DS,{folder:k},k.id):null)})}function Xj(){const t=d.useContext(Fa),n=d.useContext(Oa.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:[om(l)," ",r("of")," ",om(u)," ",r("used")]})]}):null}function Zj({option:t}){const n=d.useContext(Oa.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 Jj({readonly:t,menuOptions:n}){const r=d.useContext(Oa.i18n).getGroup("filemanager"),{showPrompt:o}=d.useContext(Yv);d.useEffect(()=>{vR("upload",Zj)},[]);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(bR,{options:u,at:"bottom-fit",onClick:l,children:i.jsx(tm,{type:"primary block",children:r("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(Yj,{})}),i.jsx(Xj,{})]})}function eE({value:t="",onSearch:n}){const[r,o]=fS(t),l=d.useContext(Oa.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 tE({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(Fa),o=d.useContext(Oa.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":_a("toggle-tree"),children:i.jsx(iu,{onClick:()=>n&&n(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:o("Files")}),i.jsx(eE,{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(WT,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx(BT,{value:l,options:h,onChange:g})})]})]})}function nE(){const t=d.useContext(Fa),n=Ot(t,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(jS,{panel:n}),i.jsx(ES,{children:i.jsx(RS,{})})]})}function aE({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=bS(),S=d.useContext(Fa),{showPrompt:k,showConfirm:N}=d.useContext(Yv),A=d.useContext(Oa.i18n),D=d.useMemo(()=>A.getGroup("filemanager"),[A]),I=Ot(S,"mode"),R=Ot(S,"preview"),_=Ot(S,"activePanel"),[B,F]=Xs(S,"panels"),H=d.useMemo(()=>(B&&_!=null?B[_]:null)?.selected??[],[F,_]),j=d.useMemo(()=>(B&&_!=null?B[_]:null)?.path,[F,_]),[Q,$]=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 G=d.useCallback(()=>{w(Z=>!Z)},[]),W=d.useCallback(Z=>{h&&im(Z)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const Z=l.current;if(Z)return go(Z,W).destroy},[W]),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:j});break;case"rename":k({item:Se});break;case"delete":N({selected:ye});break;case"preview":S.exec("show-preview",{mode:!R});break}},[S,H,j,k,N,R]),z=d.useCallback(()=>B?.[_],[B,_]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=iR(Z,{api:S,menuOptions:t?X:n,performAction:J,getPanel:z});return()=>{typeof Se=="function"?Se():Se&&typeof Se.destroy=="function"&&Se.destroy()}},[S,t,X,n,J,z]);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=D(de.text)),de.hotkey&&(de.subtext=de.hotkey)}),$(Pe),ae||{}},[S,t,X,n,H,h,V,I,D]),re=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:j})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:o,"data-menu-ignore":"false",children:h&&R?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(jg,{narrowMode:h,extraInfo:r})}):i.jsxs(i.Fragment,{children:[i.jsx(tE,{narrowMode:h,onShowTree:G}),i.jsx(wR,{dataKey:"id",at:"point",options:Q,resolver:P,onClick:re,children:i.jsxs(yS,{dataKey:"actionId",options:Q,resolver:P,onClick:re,children:[i.jsx(MR,{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(Jj,{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${R?"":"-fit"}`,"data-id":_a("body"),children:I==="table"?i.jsx(bv,{panel:_}):i.jsx(nE,{})}),R?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${R?"":"-fit"}`,children:I==="panels"?i.jsx(Qj,{}):i.jsx(Vj,{})}),R?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})})})]})})]})})}const rE=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function sE(t,n){const{type:r,ext:o}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Kw[r]?l=r:o?l=Kw[o]?o:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const iE=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=aR,extraInfo:w=null,init:b=null,icons:S=sE,previews:k=null,...N}=t,A=d.useRef();A.current=N;const D=d.useMemo(()=>new nR(pS),[]),I=d.useMemo(()=>D.in,[D]),R=d.useRef(null);R.current===null&&(R.current=new lS((F,H)=>{const j="on"+rE(F);A.current&&A.current[j]&&A.current[j](H)}),I.setNext(R.current));const _=d.useMemo(()=>({getState:D.getState.bind(D),getReactiveState:D.getReactive.bind(D),getStores:()=>({data:D}),exec:I.exec,setNext:F=>(R.current=R.current.setNext(F),R.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:D.getFile.bind(D),serialize:D.serialize.bind(D),templates:{preview:k||(()=>null),icon:S==="simple"?(()=>null):S}}),[D,I]),B=d.useRef(0);return d.useEffect(()=>{if(!B.current)b&&b(_);else{const F=D.getState();D.init({data:r,mode:o,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}B.current++},[D,r,o,l,u,f,h,b,_]),B.current===0&&D.init({data:r,mode:o,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({..._}),[_]),i.jsx(Fa.Provider,{value:_,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(qj,{children:i.jsx(aE,{readonly:g,menuOptions:y,extraInfo:w})})})})});function oE({fonts:t=!0,children:n}){return n?i.jsx(Iw,{fonts:t,children:n}):i.jsx(Iw,{fonts:t})}Bv(ls);function Zv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function dm(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 lE(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 cE(t,n=!1){return dm(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:lE(r,"folder","filesystem entries"),entries:dm(r,"entries","filesystem entries")}}async function uE(t,n){return rt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function dE(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 fE(t,n=!1){const r=await rt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:dm(r,"jobs","file transfer jobs")}}async function mE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function pE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function Qw(t){return dm(await rt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function hE(t,n){return rt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function gE(t,n,r){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function vE(t,n){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function yE(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:dm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function bE(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 Yw(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 wE(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 xE(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 SE({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),[D,I]=d.useState(null),[R,_]=d.useState([]),[B,F]=d.useState([]),[H,j]=d.useState(0),[Q,$]=d.useState(null),[G,W]=d.useState(!1),[V,X]=d.useState(""),[ve,J]=d.useState(new Set),z=n.find(me=>me.id===D)||null,P=R[R.length-1]||null,re=z?P?.svarPath||`/${z.name}`:null,we=re;d.useEffect(()=>{N.current=R,S.current=we||"/"},[we,R]);const Z=d.useMemo(()=>(A.current.clear(),!z||!we||R.length===0?[]:(R.forEach(me=>A.current.set(me.svarPath,me.hubId)),[...R.map((me,ke)=>({id:me.svarPath,parent:ke===0?"/":R[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}})])),[z,B,we,R]),Se=me=>A.current.get(String(me))||String(me),ae=me=>bE({...me,id:Se(String(me.id)),parent:Se(String(me.parent))}),ye=async(me,ke)=>{const Je=me[me.length-1];if(!Je)return;const Me=++k.current;W(!0),X("");try{const pe=await Eg(Je.hubId,t);if(Me!==k.current)return;if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe={...Je,displayPath:pe.folder.displayPath||Je.displayPath,modifiedAt:pe.folder.modifiedAt||Je.modifiedAt},Re=[...me.slice(0,-1),qe];N.current=Re,_(Re),F(pe.entries),j(st=>st+1)}catch(pe){if(Me!==k.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Je.hubId,error:pe}),X(pe instanceof Error?`${ke}: ${pe.message}`:`${ke}: Unable to read this folder.`)}finally{Me===k.current&&W(!1)}},Pe=async me=>{const ke={svarPath:`/${me.name}`,hubId:me.id,name:me.name,pathLabel:xE(me),displayPath:me.displayPath,modifiedAt:me.modifiedAt},Je=++k.current;I(me.id),N.current=[ke],_([ke]),S.current=ke.svarPath,F([]),X(""),W(!0),$(me.id),J(Me=>{const pe=new Set(Me);return pe.delete(me.id),pe});try{const Me=await Eg(me.id,t);if(Je!==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),j(qe=>qe+1)}catch(Me){if(Je!==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{Je===k.current&&($(null),W(!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)},Ke=(me,ke)=>{if(me.type!=="folder")return;const Je=N.current,Me=Je.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([...Je.slice(0,Me+1),pe],me.name)},ue=()=>de(N.current.length-2),Fe=me=>{if(me.key!=="Enter"&&me.code!=="Enter"&&me.code!=="NumpadEnter"||me.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Je=b.current;if(!Je)return;const Me=Je.getState().panels?.flatMap(qe=>qe.selected||[])||[];if(Me.length!==1)return;const pe=Je.getFile(String(Me[0]));pe?.type==="folder"&&(me.preventDefault(),me.stopPropagation(),Ke(ae(pe),String(pe.parent||S.current)))};d.useEffect(()=>{const me=n.find(ke=>ke.id===D)||wE(n);if(J(ke=>new Set([...ke].filter(Je=>n.some(Me=>Me.id===Je)))),!me){I(null),N.current=[],_([]),F([]);return}Pe(me)},[n]);const Xe=me=>{b.current=me,me.on("request-data",async({id:ke})=>{const Je=String(ke),Me=Se(Je);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=`${Je}/${Re.name}`;return A.current.set(st,Re.id),{id:st,parent:Je,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:Je,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 Je=String(ke),Me=N.current.findIndex(qe=>qe.svarPath===Je);if(Me>=0)return de(Me),!1;const pe=me.getFile(Je);if(pe?.type==="folder")return Ke(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 Je=ke?ae(ke):null,Me=()=>{const pe=Je?.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}]:Je?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Je)},...Je.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Je)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Dp(Je.displayPath||Je.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${Je.name}
179
- ${Je.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:yk,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(Kx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:i.jsx(bk,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ee()},title:"Refresh drives",type:"button",children:i.jsx(Rd,{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 Je=me.icon,Me=ve.has(ke.id)||ke.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${D===ke.id?"active":""} ${Me?"unavailable":""}`,onClick:()=>{Pe(ke)},"aria-pressed":D===ke.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(Je,{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:[Yw(ke.freeBytes||0)," free / ",Yw(ke.totalBytes||0)]})]}),Q===ke.id?i.jsx(is,{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:R.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===R.length-1?"current":""}`,onClick:()=>de(ke),title:me.displayPath||me.pathLabel,"data-hub-folder-id":me.hubId,"aria-current":ke===R.length-1?"location":void 0,type:"button",children:me.pathLabel})]},me.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[G&&i.jsx(is,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:ue,disabled:R.length<=1||G,title:"Back to parent folder",type:"button",children:i.jsx(zx,{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:Fe,children:i.jsx(oE,{fonts:!1,children:i.jsx(iE,{data:Z,panels:re?[{path:re,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Xe,icons:"simple",menuOptions:at},`${z?.id||"no-root"}:${H}`)})})]})]})]})}class CE 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(Rd,{size:15})," Retry"]})]}):this.props.children}}function kE(t){return t.deviceName||t.hostname||t.deviceId}function ME({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(rm,{size:14})," All connected"]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(kr,{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(kr,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:kE(f)}),i.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),i.jsx(Pa,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function AE(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 NE({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(Yf,{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(Yf,{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(Yf,{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 / ",AE(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${c0(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(Rd,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(Qx,{size:15})})]},y.id))})]})}function TE(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(am,{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(ME,{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(kd,{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(am,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[i.jsx(kd,{size:16})," Add selected folder to Sync"]})]}):i.jsx(NE,{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 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 Xw(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 Zw(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 jE({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 D=Array.isArray(n)?n:[],[I,R]=d.useState([]),[_,B]=d.useState(!0),[F,H]=d.useState(""),[j,Q]=d.useState([]),[$,G]=d.useState([]),[W,V]=d.useState(null),[X,ve]=d.useState(!1),[J,z]=d.useState([]),[P,re]=d.useState(!0),[we,Z]=d.useState(!1),[Se,ae]=d.useState("send"),[ye,Pe]=d.useState([]),de=d.useRef(new Set),Ke=d.useRef(!1),ue=d.useMemo(()=>f==="all"?D.map(O=>O.deviceId):h.filter(O=>D.some($e=>$e.deviceId===O)),[D,h,f]),Fe=ye.find(O=>!wv(O.state)),Xe=$.length===1&&$[0].type==="folder"?$[0]:null,at=$.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":W?`${W.files} files, ${W.folders} folders · ${RE(W.totalBytes)}`:`${$.length} item${$.length===1?"":"s"} selected`,Ee=O=>{A({id:O.jobId,state:O.state,progress:Xw(O),message:Zw(O)})},Ge=d.useCallback(async()=>{const O=await cE(t,!0);return R(O),H(""),O},[t]),me=async()=>{if(!Ke.current){Ke.current=!0;try{const $e=(await fE(t,!0)).jobs||[],We=await Promise.all([...de.current].map(async ht=>{try{return await mE(ht,t)}catch{return null}})),Et=[...$e,...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{Ke.current=!1}}};d.useEffect(()=>{let O=!0;B(!0),H(""),Promise.all([Ge(),Qw(t).then(We=>{O&&z(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),re(!1))}),me();const $e=window.setInterval(()=>{me()},800);return()=>{O=!1,window.clearInterval($e)}},[t,Ge]),d.useEffect(()=>{if(j.length===0){V(null);return}let O=!1;return ve(!0),uE(j,t).then($e=>{O||V($e)}).catch($e=>{O||N($e instanceof Error?$e.message:"Unable to calculate selected size.")}).finally(()=>{O||ve(!1)}),()=>{O=!0}},[t,j.join("|")]);const ke=(O,$e)=>{Q(O),G($e)},Je=O=>{O.forEach($e=>de.current.add($e.jobId)),Pe($e=>[...new Map([...$e,...O].map(We=>[We.jobId,We])).values()]),O.forEach(Ee)},Me=async()=>{if(!r){N(o);return}if(j.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(Fe){N("A Hub transfer is already running.");return}try{const O=await dE(j,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 $e=O||Xe;if(!$e||$e.type!=="folder"){N("Select one folder to add it to Sync.");return}try{const We=await hE($e.id,t);z(Et=>[...Et.filter(lt=>lt.id!==We.folder.id),We.folder]),ae("sync"),N(`${$e.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),z($e=>$e.map(We=>We.id===O.id?{...We,status:"syncing"}:We));try{const $e=await yE(O.id,ue,l.trim(),t);Je($e.jobs||[]),N($e.jobs?.length?"Hub sync queued.":"No changed files to sync.");const We=await Qw(t);z(We)}catch($e){N($e instanceof Error?$e.message:"Unable to sync the Hub folder."),z(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 $e=await gE(O.id,{autoSync:!O.autoSync},t);z(We=>We.map(Et=>Et.id===O.id?$e.folder:Et))}catch($e){N($e instanceof Error?$e.message:"Unable to update auto sync.")}},jt=async O=>{try{await vE(O.id,t),z($e=>$e.filter(We=>We.id!==O.id))}catch($e){N($e instanceof Error?$e.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(CE,{onRetry:()=>window.location.reload(),children:[i.jsx(SE,{hubUrl:t,roots:I,loading:_,error:F,onRefreshRoots:Ge,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ke,onShareItem:O=>{Q([O.id]),G([O]),ae("send")},onAddSyncFolder:O=>{Q([O.id]),G([O]),pe(O)},onNotice:N}),i.jsx(TE,{devices:D,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:$,selectedSummary:at,canShare:r&&!Fe&&j.length>0&&ue.length>0&&!X,onShare:()=>{Me()},canAddSync:!!Xe,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()}})]})}),Fe&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Zw(Fe)," · ",Xw(Fe),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{pE(Fe.jobId,t).then(O=>{Pe($e=>$e.map(We=>We.jobId===O.jobId?O:We)),Ee(O)})},title:"Cancel transfer",type:"button",children:i.jsx(nr,{size:14})})]})})]})}const EE=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(wk,{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(is,{className:"spin",size:16}):i.jsx(am,{size:16}),h?"Running":"Run"]})]})}),DE=["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 IE(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function LE(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 PE(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ss(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function xp(t){const n=ss(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 Jw(t){const n=ss(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function _E(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Jp(t,n){if(n.error)return n.error;const r=PE(n.data),o=_E(n.result||"");if(!r)return o||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=Jw(r.cpuUsageRatio),f=ss(r.cores),h=xp(r.freeMemoryBytes),g=xp(r.totalMemoryBytes),y=ss(r.totalMemoryBytes)&&ss(r.freeMemoryBytes)!==null?`${Math.round(ss(r.freeMemoryBytes)/ss(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=ss(r.totalBytes)&&ss(r.freeBytes)!==null?`${Math.round(ss(r.freeBytes)/ss(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=Jw(r.usageRatio),f=ss(r.temperatureC)!==null?`${Math.round(ss(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=ss(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 ex(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 FE({state:t,operation:n}){const r=t.status==="completed"?al:t.status==="failed"||t.status==="cancelled"?nr:t.status==="running"?is:Yx,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 OE({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(_=>ex(t,_)),k=S.filter(_=>_.status==="completed").length,N=b.failed>0,A=S.length>0,D=n.filter(_=>y==="issues"?ex(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),R=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:LE(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"]})]}),R.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:R.join(" · "),children:[i.jsx("span",{children:"Result"}),R.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(xk,{size:14}):i.jsx(Xx,{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:D.length>0?D.map(_=>i.jsx(FE,{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(Sk,{size:14})," Cancel"]}),!f&&N&&l&&i.jsxs("button",{onClick:l,disabled:u,type:"button",children:[i.jsx(Vg,{size:14})," Retry failed"]})]})]})}function BE(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function HE({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:BE(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(nr,{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 zE(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 $E({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 D=A.currentTarget;S.current=D.scrollHeight-D.scrollTop-D.clientHeight<72},children:[l.filter(A=>A.status==="pending").map(A=>i.jsx(HE,{approval:A,busy:h===A.approvalId,onApprove:D=>u(A,D),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 D=A;return i.jsx(OE,{operation:D.operation,states:D.states,status:D.status,onCancel:()=>n(D.batchId,D.agentRunId),onRetry:()=>r(D.batchId),busy:o===D.batchId},D.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(is,{"aria-hidden":"true",size:15}),zE(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const tx=["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 UE={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","문제해결","복구","장애"]},nx=["low","medium","high","critical"];function qE(t){return t.reduce((n,r)=>{const o=Xl[r].risk;return nx.indexOf(o)>nx.indexOf(n)?o:n},"low")}function WE(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([...UE[n],...u,...g])];return{id:t,category:n,title:r,prompt:o,description:h,requiredOperations:l,risk:f.risk||qE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||WE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const IS=[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 GE(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 VE(t,n,r){const o=GE(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 KE(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 QE(t,n,r){const o=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||o.has(l.deviceId)))}function YE(t,n){const r=KE(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 LS(t,n,r,o,l,u){const f=VE(t,l,u),h=QE(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=>YE(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 XE(t,n,r,o,l,u){return t.filter(f=>f.enabled&&LS(f,n,r,o,l,u).available).length}const Ig="livedesk.agentPromptRecent",Lg="livedesk.agentPromptFavorites",ZE={Recommended:ec,"Health & capacity":Jl,"Processes & services":Ak,"Files & configuration":Mk,"Software & automation":Vx,"Network & connectivity":kv,"Power & maintenance":ha,"Troubleshooting & recovery":kk};function ax(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 JE(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 eD(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 tD(t){return`permission-${t}`}function nD(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function aD(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function rD({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(()=>ax(Ig)),[k,N]=d.useState(()=>ax(Lg)),[A,D]=d.useState(0),[I,R]=d.useState(""),_=d.useRef(null),B=d.useRef(null),F=d.useMemo(()=>IS.filter(J=>J.enabled),[]),H=d.useMemo(()=>new Map(F.map(J=>[J.id,LS(J,t,n,r,o,l)])),[l,t,o,r,n,F]),j=d.useMemo(()=>[...H.values()].filter(J=>J.available).length,[H]),Q=d.useMemo(()=>t.filter(J=>J.connected&&(n==="all"||n==="auto"||r.includes(J.deviceId))).length,[t,r,n]),$=d.useMemo(()=>{const J=F.filter(z=>eD(z,H.get(z.id),h));return y==="recent"?b.map(z=>J.find(P=>P.id===z)).filter(z=>!!z):y==="favorites"?k.map(z=>J.find(P=>P.id===z)).filter(z=>!!z):y==="all"?J:J.filter(z=>{const P=H.get(z.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:z.category===y})},[H,k,y,b,h,F]),G=d.useMemo(()=>y!=="all"?[{category:Pg(y),templates:$}]:tx.map(J=>({category:J,templates:$.filter(z=>z.category===J)})).filter(J=>J.templates.length>0),[y,$]);d.useEffect(()=>{D(J=>Math.min(J,Math.max(0,$.length-1)))},[$.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()},z=P=>{P.key==="Escape"&&(P.preventDefault(),f())};return document.addEventListener("pointerdown",J),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",J),document.removeEventListener("keydown",z)}},[f]);const W=J=>{const z=H.get(J.id);if(!z.available){R(z.reason||"This task is not available for the current targets and permission policy.");return}const P=[J.id,...b.filter(re=>re!==J.id)].slice(0,10);S(P),Sp(Ig,P),u(J.prompt),f()},V=J=>{N(z=>{const P=z.includes(J)?z.filter(re=>re!==J):[J,...z];return Sp(Lg,P),P})},X=J=>{J.key==="ArrowDown"?(J.preventDefault(),D(z=>Math.min(z+1,Math.max(0,$.length-1)))):J.key==="ArrowUp"?(J.preventDefault(),D(z=>Math.max(z-1,0))):J.key==="Enter"&&$[A]&&(J.preventDefault(),W($[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:[j," 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(nr,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(Ck,{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",...tx].map(J=>{const z=J==="recent"?Wx:J==="favorites"?Kg:J==="all"?ec:J==="available"?Pa:J==="unavailable"?Zx:J==="read-only"||J==="auto"||J==="approval"||J==="full-access"?ha:ZE[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),D(0),R("")},children:[i.jsx(z,{size:12})," ",JE(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:[G.map(J=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:J.category}),J.templates.map(z=>{ve+=1;const P=ve===A,re=k.includes(z.id),we=H.get(z.id),Z=we.availableDeviceIds.length+we.unsupportedDeviceIds.length||Q,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:()=>W(z),children:[i.jsx("span",{children:z.title}),i.jsx("small",{className:"agents-suggested-description",children:z.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:z.category}),i.jsx("em",{className:tD(we.state),children:we.label}),i.jsx("em",{className:`risk-${z.risk}`,children:nD(z.risk)}),i.jsx("em",{children:z.supportedPlatforms.map(aD).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 ${re?"favorite":""}`,type:"button","aria-label":re?`Remove ${z.title} from favorites`:`Add ${z.title} to favorites`,"aria-pressed":re,onClick:()=>V(z.id),children:i.jsx(Kg,{size:14,fill:re?"currentColor":"none"})})]},z.id)})]},J.category)),$.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function sD({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(rm,{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(rm,{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(Xx,{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(kr,{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 iD=800,rx=5e3;function oD(){return typeof document>"u"||document.visibilityState==="visible"}function lD(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function sx({poll:t,onResult:n,onError:r,intervalMs:o=iD,isVisible:l=oD,subscribeVisibility:u=lD,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,D()},o))},D=()=>{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(j=>{w&&B===b&&!F.signal.aborted&&n?.(j)},j=>{w&&B===b&&!F.signal.aborted&&r?.(j)}).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(),D()},_=u(()=>{if(N(),!l()){b+=1,k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling paused while hidden."));return}D()});return D(),{refresh:I,stop(){w&&(w=!1,b+=1,N(),_?.(),k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function cD(t,n){return rt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function uD(t,n,r={}){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function dD(t,n){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function fD(t){return rt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function mD(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 pD(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 hD(t,n,r){return rt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function gD(t,n,r={}){return rt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function vD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function yD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function Hf(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:IE(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 bD(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 wD={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 xD(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function SD(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function CD(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 ix({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([]),[D,I]=d.useState(""),[R,_]=d.useState(""),[B,F]=d.useState(""),[H,j]=d.useState("safe-auto"),[Q]=d.useState("custom-default"),[$,G]=d.useState(wD),[W,V]=d.useState([]),[X,ve]=d.useState(""),[J,z]=d.useState(!1),[P,re]=d.useState(null),[we,Z]=d.useState(!1),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(!1),[de,Ke]=d.useState(null),ue=d.useRef(null),Fe=d.useRef(null),Xe=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(()=>XE(IS,n,f,g,H,$),[$,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:bD(Ne.states,te),status:fe.status}:Ne)),["running","queued"].includes(fe.status)||I(ce=>ce===fe.batchId?"":ce)},[n]),Je=d.useCallback((fe,te)=>{Ee.current.has(fe.batchId)||(Ee.current.add(fe.batchId),A(ce=>[...ce,{type:"task",id:Hf("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||[])Je(Ne,fe);V(te.approvals||[]);const ce=["running","queued","waiting-approval"].includes(te.status);if(Ke(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:Hf("agent-run-result"),text:He}])}},[Je]),pe=d.useCallback(async fe=>{const te=Fe.current;if(!(!te||te.id!==fe))try{return await te.owner.refresh()}catch(ce){if(Fe.current!==te)return;throw ce}},[]);d.useEffect(()=>{if(!R){Fe.current=null;return}const fe=R,te=sx({poll:Ne=>uD(t,fe,{signal:Ne,timeoutMs:rx}),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 Fe.current=ce,()=>{te.stop(),Fe.current===ce&&(Fe.current=null)}},[R,t,Me]),d.useEffect(()=>{if(!D){Xe.current=null;return}const fe=D,te=sx({poll:Ne=>gD(t,fe,{signal:Ne,timeoutMs:rx}),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 Xe.current=ce,()=>{te.stop(),Xe.current===ce&&(Xe.current=null)}},[D,t,ke]);const qe=async(fe="",te,ce=!1)=>{const Ne=(fe||S).trim();if(!Ne||D||R)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){re({instruction:Ne,targetIds:He});return}if(A(ut=>[...ut,{type:"user",id:Hf("user"),text:Ne}]),k(""),Pe(!1),ae(""),He.length===0){A(ut=>[...ut,{type:"error",id:Hf("no-targets"),text:"연결된 대상 장비를 하나 이상 선택해 주세요."}]);return}const Lt=w==="ask"?`Read-only request. Inspect and answer without changing Client state.
177
+ `):String(t||""),N=d.useMemo(()=>W1(t),[k]),A=d.useMemo(()=>N.find(R=>Zf(R)==="loopback")||N[0]||$n,[N]),D=d.useCallback(async R=>{if(!n){l(null),f([]),w(""),g("");return}let _=null;const B=Date.now(),F=N.filter(j=>(b.current.get(j)||0)<=B),H=H1({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 j of H.candidates)try{const[Q,$]=await Promise.all([rt("/api/remote/status",{signal:R,timeoutMs:rw,transport:H.transport},j),rt("/api/remote/devices",{signal:R,timeoutMs:rw,transport:H.transport},j)]);if(R?.aborted)throw R.reason||new Error("LiveDesk Hub snapshot cancelled.");if(!Array.isArray($.devices))throw new Error("Invalid Hub devices response.");b.current.delete(j),l(Q),f($.devices),w(j),g("");return}catch(Q){if(R?.aborted)throw Q;_=Q,H.transport==="auto"&&b.current.set(j,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,()=>D()).catch(R=>{g(R instanceof Error?R.message:String(R))})},[D]);return d.useEffect(()=>{if(b.current.clear(),!n){l(null),f([]),w(""),g("");return}let R=!0,_=null;const B=new AbortController,F=()=>{Up(S,()=>D(B.signal)).catch(j=>{R&&!B.signal.aborted&&g(j instanceof Error?j.message:String(j))}).finally(()=>{R&&!B.signal.aborted&&(_=window.setTimeout(F,$1))})};return F(),()=>{R=!1,B.abort(new Error("LiveDesk Hub snapshot polling stopped.")),_!==null&&window.clearTimeout(_)}},[n,D]),{status:o,devices:u,error:h,refresh:I,hubBaseUrl:y||A,hubCandidates:N}}function K1(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 Q1(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(z1).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 em={totalFrames:0,totalBytes:0,framesPerSecond:0,bytesPerSecond:0,sampleMs:0,lastUpdatedAt:0},Y1=2500,X1=3e4,Z1=64*1024,J1=64*1024,eN=6,tN=eN,G0=new Map;function nN(t){return G0.get(t)}const sw={totalSent:0,totalDropped:0,sentPerSecond:0,droppedPerSecond:0,bufferedAmount:0,lastInputType:"",lastInputSeq:0,lastRoundTripMs:0,lastAgentApplyMs:0,lastUpdatedAt:0};function aN(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>X1?(t.minimumHubClockOffsetMs=l,0):f}function gt(t){if(t==null||t==="")return;const n=Number(t);return Number.isFinite(n)?n:void 0}const rN=["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 sN(t){return Number(t.nativeCaptureTelemetryVersion)>=5&&rN.every(n=>gt(t[n])!==void 0)&&typeof t.nativeOutputQueueAwaitingKeyFrame=="boolean"&&t.nativeCopyTelemetryAvailable===!0}function iN(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=$n,o={}){const[l,u]=d.useState(new Map),[f,h]=d.useState("idle"),[g,y]=d.useState(""),[w,b]=d.useState(em),S=d.useRef(new Map),k=d.useRef(new Map),N=d.useRef(new Map),A=d.useRef(null);A.current===null&&(A.current=f1());const D=d.useRef(0),I=d.useRef(new Map),R=d.useRef({enabled:!1,token:"",reason:""}),_=d.useRef(new Map),B=d.useRef(null),F=d.useRef(new Map),[H,j]=d.useState(0),Q=d.useRef(o.onFrame),$=d.useRef(o.onStreamReady),G=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),W=d.useMemo(()=>[...t].sort().join(","),[t]),V=n&&W.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,z=Number.isFinite(o.maxHeight)?Number(o.maxHeight):360,P=Number.isFinite(o.quality)?Number(o.quality):45,re=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();R.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(()=>{Q.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{$.current=o.onStreamReady},[o.onStreamReady]);const Ke=d.useCallback((Me,pe="livedesk-frame-socket-release")=>{m1(Me,pe,A.current)},[]),ue=d.useCallback(Me=>{const pe=_.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),_.current.delete(Me))},[]),Fe=d.useCallback(Me=>{const pe=F.current.get(Me);pe!==void 0&&(window.clearTimeout(pe),F.current.delete(Me))},[]),Xe=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,Ke(qe,Me);N.current.clear(),I.current.clear(),S.current=new Map,k.current.clear(),G.current={totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0},pe&&(u(new Map),y(""),b(em),h("idle"))},[Ke]),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));y1(O,pe.sparseTelemetry,pe.expectedBinding);const $e=gt(O.hubPacketEpochMs),We=$e!==void 0&&$e>0?$e:void 0,Et=aN(pe,We,qe);if(Et>Y1)return;const lt=new Uint8Array(Me,4+st),ht=gt(O.nativeCaptureTelemetryVersion),Ze=gt(O.nativeCaptureTelemetryAgeMs),be=gt(O.hubClientDropped),je=gt(O.hubClientQueueDepth),Ae=gt(O.hubClientQueueLimit),fe=gt(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:gt(O.inputFeedbackInputSeq),inputFeedbackInputType:O.inputFeedbackInputType?String(O.inputFeedbackInputType):void 0,inputFeedbackIssuedAtEpochMs:gt(O.inputFeedbackIssuedAtEpochMs),inputFeedbackHubReceivedAtEpochMs:gt(O.inputFeedbackHubReceivedAtEpochMs),inputFeedbackHubForwardedAtEpochMs:gt(O.inputFeedbackHubForwardedAtEpochMs),inputFeedbackAgentReceivedAtEpochMs:gt(O.inputFeedbackAgentReceivedAtEpochMs),inputFeedbackAppliedAtEpochMs:gt(O.inputFeedbackAppliedAtEpochMs),inputFeedbackAgentApplyMs:gt(O.inputFeedbackAgentApplyMs),inputFeedbackApplyToCaptureMs:gt(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:Ze===void 0?void 0:Math.max(0,Ze),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:gt(O.nativeCaptureDisplayId),nativeCaptureFps:gt(O.nativeCaptureFps),nativeCompressionFps:gt(O.nativeCompressionFps),nativeEncodedFps:gt(O.nativeEncodedFps),nativeCaptureSampleCount:gt(O.nativeCaptureSampleCount),nativeEncodableFrameCount:gt(O.nativeEncodableFrameCount),nativeSkippedFrameCount:gt(O.nativeSkippedFrameCount),nativeCompressionOutputCount:gt(O.nativeCompressionOutputCount),nativeEncodedFrameCount:gt(O.nativeEncodedFrameCount),nativeEncodeFramesInFlight:gt(O.nativeEncodeFramesInFlight),nativeEncodePendingFrameCount:gt(O.nativeEncodePendingFrameCount),nativeEncodeTimestampOwnerCount:gt(O.nativeEncodeTimestampOwnerCount),nativeEncodeTimestampOwnerHighWatermark:gt(O.nativeEncodeTimestampOwnerHighWatermark),nativeBackpressureCoalescedFrameCount:gt(O.nativeBackpressureCoalescedFrameCount),nativeBackpressureSkippedFrameCount:gt(O.nativeBackpressureSkippedFrameCount),nativeEncodePendingReplacedFrameCount:gt(O.nativeEncodePendingReplacedFrameCount),nativeIdleSkippedFrameCount:gt(O.nativeIdleSkippedFrameCount),nativeVideoToolboxActiveSessionCount:gt(O.nativeVideoToolboxActiveSessionCount),nativeVideoToolboxSessionHighWatermark:gt(O.nativeVideoToolboxSessionHighWatermark),nativeOutputQueueDepth:gt(O.nativeOutputQueueDepth),nativeOutputQueueBytes:gt(O.nativeOutputQueueBytes),nativeOutputQueueOldestAgeMs:gt(O.nativeOutputQueueOldestAgeMs),nativeOutputQueueHighWatermark:gt(O.nativeOutputQueueHighWatermark),nativeOutputQueueDroppedCount:gt(O.nativeOutputQueueDroppedCount),nativeOutputQueueAwaitingKeyFrame:typeof O.nativeOutputQueueAwaitingKeyFrame=="boolean"?O.nativeOutputQueueAwaitingKeyFrame:void 0,nativeCopyTelemetryAvailable:typeof O.nativeCopyTelemetryAvailable=="boolean"?O.nativeCopyTelemetryAvailable:void 0,nativeAnnexBAccessUnitAllocationCount:gt(O.nativeAnnexBAccessUnitAllocationCount),nativeAnnexBPayloadCopyCount:gt(O.nativeAnnexBPayloadCopyCount),nativeAnnexBPayloadCopiedBytes:gt(O.nativeAnnexBPayloadCopiedBytes),nativeAndPipeResidenceAgeMs:gt(O.nativeAndPipeResidenceAgeMs),pipePayloadAllocationCount:gt(O.pipePayloadAllocationCount),pipePayloadCopyCount:gt(O.pipePayloadCopyCount),pipePayloadCopiedBytes:gt(O.pipePayloadCopiedBytes),handoffDroppedFrameCount:gt(O.handoffDroppedFrameCount),handoffRecoveryKeyFrameRequestCount:gt(O.handoffRecoveryKeyFrameRequestCount),handoffOldestFrameAgeMs:gt(O.handoffOldestFrameAgeMs),nativeCaptureResourceTelemetryAvailable:O.nativeCaptureResourceTelemetryAvailable===!0?sN(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:gt(O.captureAverageMs),captureP95Ms:gt(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:gt(O.captureMs),captureStageMs:gt(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},Ye=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>=Ye&&(_t===Ye||ut))return;pe.lastFrameStreamId=ce.streamId,pe.lastFrameCommandId=ce.commandId||"",pe.lastFrameOrder=Ye;const mt=G.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),Ct=c1(k.current,ce);Vt&&(S.current.set(ce.deviceId,Ct),k.current.delete(ce.deviceId),u(new Map(S.current))),Q.current?.(ce)},[]);d.useEffect(()=>{if(!n||!W)return;G.current.sampleStartedAt=performance.now();const Me=window.setInterval(()=>{if(!X.current)return;const pe=performance.now(),qe=G.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(u1(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,W]),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:W,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,$e)=>O+Math.max(0,Number($e.payload?.byteLength||0)),0)}};return cv.add(Me),()=>{cv.delete(Me)}},[W]),d.useEffect(()=>{const Me=W?W.split(",").filter(Boolean):[];if(!V){Xe(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)||Fe(Re);for(const[Re,st]of N.current.entries())pe.has(Re)||(ue(Re),Ke(st,"livedesk-device-unsubscribed"),N.current.delete(Re),I.current.delete(Re),S.current.delete(Re),k.current.delete(Re));G.current.sampleStartedAt<=0&&(G.current.sampleStartedAt=qe,b({...em,lastUpdatedAt:Date.now()}));for(const Re of Me){ue(Re),Fe(Re);const st=Number(o.monitorSelections?.[Re]),jt=Number.isInteger(st)&&st>=0?st:0,O={[Re]:jt},$e={type:"subscribe",deviceIds:[Re],autoStartLive:n,fps:ve,maxWidth:J,maxHeight:z,quality:P,mode:we,frameMode:we,streamPurpose:Z,monitorSelections:O},We=String(o.connectionSessionIds?.[Re]||"").trim(),Et=JSON.stringify({subscribePayload:$e,connectionSessionId:We}),lt=N.current.get(Re),ht=Number(lt?.payload.monitorSelections?.[Re]),Ze=Number(O[Re]),be=!!lt&&Number.isFinite(ht)&&Number.isFinite(Ze)&&ht!==Ze,je=!!lt&&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&&lt!==Ae?lt:void 0,te=`/api/remote/frames/ws?devices=${encodeURIComponent(Re)}`,ce=nh(ah(te,r),te);ce.binaryType="arraybuffer";const Ne=v1(),He={socket:ce,payload:$e,payloadKey:Et,connectionSessionId:We,generation:D.current+1,monitorRestartToken:be?`monitor-${Re}-${Ze}-${D.current+1}`:"",disposed:!1,handoffFrom:Ae,handoffCompleted:!1,lastFrameStreamId:"",lastFrameCommandId:"",lastFrameOrder:-1,sparseTelemetry:Ne,releaseOwnedState:()=>ew(Ne)};D.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,Ke(fe,"livedesk-subscription-superseded"));const Ie=()=>{if(!X.current||He.disposed||N.current.get(Re)!==He){Ke(He,"livedesk-stale-frame-socket");return}ue(Re),y("");const yt=R.current,_t=yt.enabled&&(!yt.token||I.current.get(Re)!==yt.token),mt=_t||He.monitorRestartToken!=="",Vt=_t?yt.token:He.monitorRestartToken,Ct=_t?yt.reason:He.monitorRestartToken?"monitor-selection-change":"";if(ce.send(JSON.stringify({...He.payload,forceRestart:mt,restartReason:mt?Ct:"",restartToken:mt?Vt:""})),re>0){const an=window.setTimeout(()=>{F.current.get(Re)===an&&F.current.delete(Re),X.current&&Ge(Re,He)},Math.max(1e3,re));F.current.set(Re,an)}_t&&yt.token&&I.current.set(Re,yt.token);const mn=He.handoffFrom;He.handoffFrom=void 0,He.handoffCompleted=!0,mn&&!mn.disposed&&Ke(mn,"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=(Ct,mn=!0)=>{const an=iN(Ct,Re,Z);return an?(He.expectedBinding=an,mn&&$.current?.(an),!0):!1};if(mt?.type==="RemoteFrameSubscriptionError")y(String(mt.error||"control-stream-start-failed"));else if(mt?.type==="RemoteFrameLiveAutoStart"){const mn=(Array.isArray(mt.skipped)?mt.skipped:[]).find(an=>an?.deviceId===Re);if(mn)mn.reason==="CAPTURE_TRANSITION_IN_PROGRESS"&&mn.retryScheduled===!0?y(""):y(String(mn.reason||"control-stream-start-failed"));else if(Array.isArray(mt.started)){const an=mt.started.find(va=>va?.deviceId===Re);an&&(y(""),Vt(an,an.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))},Ye=()=>{!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&&Fe(Re);let Vt=!1;if(mt===He){const Ct=He.handoffFrom;He.handoffFrom=void 0,Ct&&!Ct.disposed&&(Ct.socket.readyState===WebSocket.CONNECTING||Ct.socket.readyState===WebSocket.OPEN)?(N.current.set(Re,Ct),Vt=!0):N.current.delete(Re)}if(at(),yt&&X.current&&mt===He&&!Vt){const Ct=window.setTimeout(()=>{_.current.get(Re)===Ct&&_.current.delete(Re),X.current&&j(mn=>mn+1)},750);ue(Re),_.current.set(Re,Ct)}};He.detachListeners=()=>{ce.removeEventListener("open",Ie),ce.removeEventListener("message",Lt),ce.removeEventListener("error",Ye),ce.removeEventListener("close",ut)},ce.addEventListener("open",Ie),ce.addEventListener("message",Lt),ce.addEventListener("error",Ye),ce.addEventListener("close",ut)}at()},[n,Fe,ue,Ke,re,de,W,ve,we,me,r,z,J,Pe,o.monitorSelections,P,H,Xe,Ge,Z,V,at]),d.useEffect(()=>{if(!V||!Se||!ae)return;const Me=W?W.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)}},[W,Se,ae,ye,Ee,V]),d.useEffect(()=>()=>{Xe("livedesk-hook-unmount",!1)},[Xe]);const ke=d.useCallback((Me,pe="browser-stale")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:W.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},[W,Ee,V]),Je=d.useCallback((Me,pe="browser-reconnect")=>{if(!V)return!1;const qe=Array.isArray(Me)&&Me.length>0?Me:W.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),Ke(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)),j(st=>st+1),at(),!0},[ue,Ke,W,V,at]);return{frames:l,state:f,error:g,stats:w,restartLive:ke,reconnectLive:Je}}function oN(t,n,r=$n,o={}){const[l,u]=d.useState(null),[f,h]=d.useState(null),[g,y]=d.useState("idle"),[w,b]=d.useState(em),S=d.useRef(null),k=d.useRef(o.onFrame),N=d.useRef(null),A=d.useRef(0),D=d.useRef({totalFrames:0,totalBytes:0,sampleFrames:0,sampleBytes:0,sampleStartedAt:0}),I=d.useMemo(()=>[...new Set(t.filter(Boolean))].join(","),[t]),R=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 W=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(W))},[o.connectionSessionIds]),F=d.useMemo(()=>({deviceIds:I.split(",").filter(Boolean),captureDeviceIds:R.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||{}}),[R,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]),j=d.useRef(F);j.current=F;const Q=n&&F.deviceIds.length>0,$=d.useCallback(W=>W.readyState!==WebSocket.OPEN?!1:(W.send(JSON.stringify({type:"configure",...j.current})),!0),[]);d.useEffect(()=>{k.current=o.onFrame},[o.onFrame]),d.useEffect(()=>{if(!Q)return;D.current.sampleStartedAt=performance.now();const W=window.setInterval(()=>{const V=D.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(W)},[Q]),d.useEffect(()=>{if(!Q){S.current?.close(),S.current=null,u(null),N.current=null,A.current=0,h(null),y("idle"),b(em);return}let W=!1,V=0;const X=()=>{if(W)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",()=>{D.current.sampleStartedAt=performance.now(),y("open"),$(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 z=J.data instanceof ArrayBuffer?J.data:null;if(!(!z||z.byteLength<5))try{const P=Date.now(),we=new DataView(z).getUint32(0,!1);if(we<=0||we+4>z.byteLength)return;const Z=JSON.parse(Pv.decode(new Uint8Array(z,4,we))),Se=new Uint8Array(z,4+we),ae=gt(Z.hubClientDropped),ye=gt(Z.hubClientQueueDepth),Pe=gt(Z.hubClientQueueLimit),de=gt(Z.hubClientBufferedBytes),Ke={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=D.current;ue.totalFrames+=1,ue.totalBytes+=Se.byteLength,ue.sampleFrames+=1,ue.sampleBytes+=Se.byteLength,N.current=Ke,A.current===0&&(A.current=Ke.frameSeq,u(Ke)),k.current?.(Ke)}catch{}}),ve.addEventListener("error",()=>y("error")),ve.addEventListener("close",()=>{S.current===ve&&(S.current=null),!W&&(y("closed"),V=window.setTimeout(X,1200))})};return X(),()=>{W=!0,window.clearTimeout(V),S.current?.close(),S.current=null}},[Q,r,$]),d.useEffect(()=>{if(!Q)return;const W=S.current;W&&$(W)},[H,Q,$]);const G=d.useCallback(()=>{const W=S.current;return W?$(W):!1},[$]);return{frame:l,layout:f,state:g,stats:w,refreshInputs:G}}function lN(t,n=$n){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,D=0;const I=()=>{if(A)return;const R=nh(ah("/api/remote/input/ws",n),"/api/remote/input/ws");r.current=R,k.current.sampleStartedAt=performance.now(),g("connecting"),w(""),R.addEventListener("open",()=>{A||r.current!==R||(w(""),g("open"))}),R.addEventListener("message",_=>{if(!(A||r.current!==R||typeof _.data!="string"))try{const B=JSON.parse(_.data),F=Number(B.inputSeq||B.result?.inputSeq||0),H=String(B.deviceId||B.result?.deviceId||""),j=String(B.inputEventId||B.result?.inputEventId||""),Q=u.current.get(F);if(H&&(Q&&Q.deviceId!==H||!Q&&f.current&&f.current!==H)||Q?.inputEventId&&j&&Q.inputEventId!==j)return;if(B?.type==="RemoteInputError"){F>0&&u.current.delete(F),w(String(B.error||B.result?.error||"Remote input failed.")),R.readyState===WebSocket.OPEN&&g("open");return}if(B?.type!=="RemoteInputApplied")return;Q&&(k.current.lastRoundTripMs=Math.max(0,performance.now()-Q.sentAt),u.current.delete(F)),k.current.lastInputSeq=F,k.current.lastAgentApplyMs=Math.max(0,Number(B.agentApplyMs||0)),w(""),g("open")}catch{}}),R.addEventListener("close",()=>{A||r.current!==R||(r.current=null,g("closed"),D=window.setTimeout(I,1200))}),R.addEventListener("error",()=>{!A&&r.current===R&&g("error")})};return I(),()=>{A=!0,window.clearTimeout(D);const R=r.current;r.current=null,R?.close(),u.current.clear()}},[t,n]),d.useEffect(()=>{if(!t)return;const A=window.setInterval(()=>{const D=performance.now(),I=k.current,R=Math.max(1,D-I.sampleStartedAt);S({totalSent:I.totalSent,totalDropped:I.totalDropped,sentPerSecond:I.sampleSent*1e3/R,droppedPerSecond:I.sampleDropped*1e3/R,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=D},1e3);return()=>window.clearInterval(A)},[t]);const N=d.useCallback((A,D)=>{const I=r.current;if(!I||I.readyState!==WebSocket.OPEN||!A)return!1;const R=String(D.type||"").toLowerCase(),F=R==="pointermove"||R==="wheel",H=k.current;if(F&&I.bufferedAmount>Z1)return H.totalDropped+=1,H.sampleDropped+=1,H.lastInputType=`${R}-coalescible-drop`,!1;if(!F&&I.bufferedAmount>J1){H.lastInputType=`${R||"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 j=o.current+1;o.current=j;const Q=`${j}-${crypto.randomUUID()}`,$=Date.now(),G=!F||j-l.current>=tN;for(G&&(u.current.set(j,{sentAt:performance.now(),deviceId:A,inputEventId:Q}),F&&(l.current=j)),f.current=A,G0.set(A,{inputSeq:j,inputType:R||"input",sentAt:performance.now()});u.current.size>256;){const W=u.current.keys().next().value;if(W===void 0)break;u.current.delete(W)}try{I.send(JSON.stringify({type:"input",requestId:F?"":crypto.randomUUID(),fireAndForget:F,deviceId:A,input:{...D,inputEventId:Q,inputSeq:j,requestAck:G,issuedAtEpochMs:$,issuedAt:new Date($).toISOString()}}))}catch{u.current.delete(j),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=R||"input",!0},[]);return{state:h,sendInput:N,stats:b,error:y}}const bd={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},cN=.25,ow=300,lw=2,dp=1500,xg=5e3,uN=2e3,cw=1e4,Pf=[0,1e3,3e3];function uw(t){const n=Date.parse(String(t||""));return Number.isFinite(n)?Math.max(0,Date.now()-n):0}function dN(t,n,r=$n,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(bd),[A,D]=d.useState(""),I=d.useRef(l);return I.current=l,d.useEffect(()=>{l||(S(R=>R===null?R:null),N(R=>R===bd?R:bd))},[l]),d.useEffect(()=>{if(!n||!t){w("idle"),S(null),N(bd),D("");return}w("connecting"),S(null),N(bd),D("");const R=window.AudioContext||window.webkitAudioContext;if(!R){w("unsupported"),N(bd),D("Audio playback is not supported in this browser.");return}let _=!1,B=null;const F=A1.acquire(({release:H})=>{if(_){H();return}const j=new R({latencyHint:"interactive"});g.current=j;let Q=String(u||"").trim();const $="/api/remote/audio/ws?devices="+encodeURIComponent(t)+(Q?"&streamId="+encodeURIComponent(Q):""),G=nh(ah($,r),$);G.binaryType="arraybuffer";const W=ma.createOwner({deviceId:t,socket:G,audioContext:j,statsTimer:null});let V=!1;const X=()=>{const te=ma.releaseIfDrained(W);return(te||!ma.hasOwner(W))&&!V&&(V=!0,H()),te},ve=Lv({sampleRate:192e3,channels:8}).capacityBytes,J=L1({maxPendingPackets:ov,maxPendingBytes:ve}),z=x1(),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(j.state),stalledCount:0,automaticRestarts:0,maximumAcceptedGapMs:0,activeStreamId:Q,lastCaptureStatusAt:0,lastPcmAtEpochMs:0,workletRingCapacityBytes:0,workletRingBufferedBytes:0,workletRingBufferedMs:0,workletRingDroppedFrames:0,workletRingUnderflowCount:0};let re=!1,we=!1,Z=null,Se=0,ae=0,ye="",Pe=!1,de=()=>{},Ke="connecting",ue="";const Fe=te=>{re||te===Ke||(Ke=te,w(te))},Xe=te=>{re||te===ue||(ue=te,D(te))};let at=0,Ee=!1,Ge=0,me=0,ke=0,Je=!1;const Me=()=>{ma.setPendingWorkletPackets(W,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(cN*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),ma.setPcmRing(W,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,ma.setPcmRing(W,0,0),ma.setWorkletNode(W,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=()=>{G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"subscribe",deviceIds:[t],streamIdsByDeviceId:Q?{[t]:Q}:{}}))},O=()=>{P.audioContextState=String(j.state),!re&&(P.audioContextState==="suspended"||P.audioContextState==="interrupted"?Fe("suspended"):P.audioContextState==="closed"&&(Fe("error"),Xe("The browser audio context is closed. Toggle Remote Audio off and on to recover.")))},$e=async()=>{if(re||String(j.state)==="closed")return!1;try{if(String(j.state)!=="running"&&await j.resume(),P.audioContextState=String(j.state),!re&&!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;Fe(te?"playing":ce?"silent":"open")}return P.audioContextState==="running"}catch(te){return re||(Fe("suspended"),Xe(te instanceof Error?"Audio playback is suspended: "+te.message:"Audio playback is suspended.")),!1}},We=async()=>{if(!j.audioWorklet||typeof AudioWorkletNode>"u")throw new Error("AudioWorklet is unavailable in this browser.");const te=new Blob([B1],{type:"text/javascript"});ye=URL.createObjectURL(te);try{await j.audioWorklet.addModule(ye)}finally{URL.revokeObjectURL(ye),ye=""}if(re||String(j.state)==="closed")return;const ce=new AudioWorkletNode(j,W0,{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(j.destination),Pe=!0,ma.setWorkletNode(W,1,1,Se)},Et=(te,ce,Ne,He)=>{const Ie=Z;if(re||!Pe||!Ie||ce.byteLength<=0)return!1;const Lt=Iv({sampleRate:te.sampleRate,channels:te.channels,mimeType:te.mimeType}),Ye=++ae;if(!J.claim(Ye,ce.byteLength))return Me(),!1;Me();try{return Ie.port.postMessage({type:"pcm",packetId:Ye,buffer:ce,byteOffset:Ne,byteLength:He,sampleRate:Lt.sampleRate,channels:Lt.channels,mimeType:te.mimeType,sampleFormat:Lt.sampleFormat},[ce]),!0}catch{return J.acknowledge(Ye),Me(),!1}},lt=async()=>{if(re||Ee||G.readyState!==WebSocket.OPEN)return;if(Ge>=Pf.length){Fe("error"),Xe("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,Fe("reconnecting");try{if(!f)throw new Error("Remote audio restart owner is unavailable.");const ce=await f(t);if(re||!ce)return;Q=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=Q,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st(),me=Ne+(Pf[te+1]??3e3),Xe(""),re||Fe("open")}catch(ce){re||(me=performance.now()+(Pf[te+1]??3e3),Fe("error"),Xe(ce instanceof Error?"Remote audio restart failed: "+ce.message:"Remote audio restart failed."))}finally{Ee=!1}},ht=()=>{P.drops+=1},Ze=window.setInterval(()=>{if(re)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=G.readyState===WebSocket.OPEN,Lt=P.lastCaptureStatusAt>0,Ye=Lt&&He<=xg&&P.captureHealthy,ut=Lt&&P.captureStatusFailed&&He>uN,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>=Pf.length&&!Ee?(Fe("error"),Xe("Remote audio capture heartbeat stopped. Toggle Audio off and on to retry.")):!Ee&&te>=me?lt():Ee||Fe("stalled"):Ie&&Vt&&!Ee&&P.audioContextState!=="suspended"&&P.audioContextState!=="interrupted"&&Fe(Ye?"silent":"open"),N1({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 Ct=z.publish();Ct&&(Je=!0,ma.setRetainedFrame(W,1,Ct.payload.byteLength),S(Ct))}else!I.current&&Je&&(Je=!1,z.clear(),ma.setRetainedFrame(W,0,0))},250);ma.setStatsTimer(W,Ze);const be=()=>{O(),(String(j.state)==="suspended"||String(j.state)==="interrupted")&&$e()},je=()=>{document.visibilityState==="visible"&&$e()},Ae=()=>{$e()};j.addEventListener("statechange",be),document.addEventListener("visibilitychange",je),window.addEventListener("pageshow",Ae),window.addEventListener("pointerdown",Ae),window.addEventListener("keydown",Ae),Fe("connecting"),Xe(""),O();const fe=(te,ce,Ne,He,Ie)=>{if(P.localProcessingAgeMs=Math.max(0,performance.now()-Ie),re||P.localProcessingAgeMs>ow||!lv(te,{deviceId:t,streamId:Q}))return ht(),!1;P.activeStreamId!==Q&&(P.activeStreamId=Q,P.lastFrameSeq=0,P.maximumAcceptedGapMs=0,st());const Lt=E1(te,{deviceId:t,streamId:Q,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 Ye=performance.now();P.lastAcceptedAt>0&&(P.maximumAcceptedGapMs=Math.max(P.maximumAcceptedGapMs,Ye-P.lastAcceptedAt)),P.lastAcceptedAt=Ye,P.framesReceived+=1,P.lastFrameSeq=Lt.nextFrameSeq,Ge=0,me=0,I.current&&(z.accept(te),Je=!0,ma.setRetainedFrame(W,1,0)),String(j.state)!=="running"&&$e();const ut=String(j.state)==="running";return ut&&Xe(""),Fe(ut?"playing":"suspended"),!0};de=(te="")=>{if(!we){if(we=!0,te&&(ma.recordTerminalFailure(W,te,te.includes("setup failed")?"setup":"processor"),Fe(te.includes("AudioWorklet is unavailable")?"unsupported":"error"),Xe(te),h?.(t,Q,"browser-audio-playback-failed").catch(()=>{})),re=!0,ma.deactivate(W),window.clearInterval(Ze),ma.setStatsTimer(W,null),j.removeEventListener("statechange",be),document.removeEventListener("visibilitychange",je),window.removeEventListener("pageshow",Ae),window.removeEventListener("pointerdown",Ae),window.removeEventListener("keydown",Ae),z.clear(),ma.setRetainedFrame(W,0,0),Z)try{Z.port.postMessage({type:"dispose"})}catch{}try{G.close()}catch{}G.readyState===WebSocket.CLOSED&&ma.setSocket(W,null),j.close().catch(()=>{}).finally(()=>{qe(),String(j.state)==="closed"&&ma.setAudioContext(W,null),X()}),g.current===j&&(g.current=null),X()}},We().catch(te=>{de(te instanceof Error?`Remote audio worklet setup failed: ${te.message}`:"Remote audio worklet setup failed.")}),G.addEventListener("open",()=>{re||(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,Fe("open"),jt(),$e())}),G.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),Ye=JSON.parse(Pv.decode(Lt)),ut=new Uint8Array(ce,4+Ie),yt=String(Ye.deviceId||""),_t=String(Ye.streamId||"");if(!lv({deviceId:yt,streamId:_t},{deviceId:t,streamId:Q})){ht();return}const mt=String(Ye.frameKind||Ye.kind||"").toLowerCase();if(Ye.type==="remote.audio.status"||mt==="audio-status"){P.lastCaptureStatusAt=Ne;const Ct=D1(Ye);if(P.captureAlive=Ct.captureAlive,P.helperAlive=Ct.helperAlive,P.helperReady=Ct.helperReady,P.captureHealthy=Ct.healthy,P.captureStatusFailed=Ct.failed,P.captureAwaitingCurrentPcm=Ct.awaitingCurrentPcm,Ct.awaitingCurrentPcm?P.captureAwaitingSinceAt||=Ne:P.captureAwaitingSinceAt=0,P.capturePhase=Ct.capturePhase,P.backendKind=Ct.backendKind,P.helperRequired=Ct.helperRequired===!0,P.helperPid=Ct.helperPid,P.captureRestartCount=Math.max(0,Number(Ye.restartCount||0)||0),P.nativeCallbackDiagnosticsAvailable=Ye.callbackDiagnosticsAvailable===!0,P.nativeRejectedCallbackCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.rejectedCallbackCount||0)||0):0,P.nativeCurrentnessDropCount=P.nativeCallbackDiagnosticsAvailable?Math.max(0,Number(Ye.currentnessDropCount||0)||0):0,P.nativeLastDropReason=P.nativeCallbackDiagnosticsAvailable?String(Ye.lastDropReason||""):"",P.lastPcmAtEpochMs=Math.max(0,Number(Ye.lastPcmAtEpochMs||0)||0),P.silentForMs=Math.max(0,Number(Ye.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){Xe("");const mn=String(j.state)==="running",an=P.lastAcceptedAt>0&&performance.now()-P.lastAcceptedAt<=dp;Fe(mn?an?"playing":"silent":"suspended")}}else P.captureAwaitingCurrentPcm&&!Ee?Fe("open"):P.captureStatusFailed&&!Ee&&Fe("stalled");return}const Vt={deviceId:yt,frameSeq:Number(Ye.frameSeq||0),streamId:_t,mimeType:String(Ye.mimeType||"audio/webm;codecs=opus"),sampleRate:Number(Ye.sampleRate||48e3),channels:Number(Ye.channels||2),capturedAt:String(Ye.capturedAt||""),receivedAt:String(Ye.receivedAt||""),byteLength:Number(Ye.byteLength||ut.byteLength),payload:q0};if(!Vt.deviceId||re)return;if(performance.now()-Ne>ow){ht();return}if(j1(Vt.mimeType)){fe(Vt,ce,ut.byteOffset,ut.byteLength,Ne);return}ht(),Fe("error"),Xe(`Unsupported remote audio format "${Vt.mimeType}". Requesting a bounded PCM restart.`),!Ee&&Ge<Pf.length&&(me=0,lt());return}catch(He){re||(Fe("error"),Xe(He instanceof Error?He.message:String(He)))}}),G.addEventListener("error",()=>{re||(Fe("error"),Xe("Remote audio WebSocket error."))}),G.addEventListener("close",()=>{ma.setSocket(W,null),X(),re||Fe("closed")}),B=()=>{de()}});return F.ready.catch(H=>{_||(w("error"),D(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 fN=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,fN);return l<=u?0:l>=o-u?1:l/o}function mN(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"])}),pN=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 V0(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=V0(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(pN[u]);continue}for(const g of h)n.has(g)||t.delete(g)}}function hN(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 gN(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 vN(t,n,r){const o=fv(t),l=V0(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 yN(){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&&hN(g,t)?null:vN(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 K0=64,bN=2;function Q0(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(1,Math.min(K0,n)):1}function Fv(t){const n=Math.floor(Number(t));return Number.isFinite(n)?Math.max(0,Math.min(K0-1,n)):0}function Y0(t){const n=String(t||"").trim().toLowerCase();return n==="macos"||n==="darwin"||n==="mac"||n==="macosx"||n==="linux"||n.startsWith("linux ")}function wN(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 X0({platform:t,topologyFingerprint:n,consecutiveTopologySamples:r}){return Y0(t)?!!String(n||"").trim()&&Number(r)>=bN:!0}function xN({requestedIndex:t,monitorCount:n,platform:r,topologyFingerprint:o,consecutiveTopologySamples:l}){const u=Fv(t),f=Q0(n);return u<f||!X0({platform:r,topologyFingerprint:o,consecutiveTopologySamples:l})?u:f-1}function SN(t,n,r){const o=Fv(t),l=Q0(n);return o<l||Y0(r)?o:l-1}function sc(t){const n=Number(t);return Number.isSafeInteger(n)&&n>0?n:0}function pa(t){return String(t||"").trim()}function Cg(t,n,r={}){return{deviceId:pa(t),transitionGeneration:sc(n),sessionId:pa(r.sessionId),streamId:pa(r.streamId),commandId:pa(r.commandId),captureGeneration:sc(r.captureGeneration),monitorIndex:Math.max(0,Math.floor(Number(r.monitorIndex)||0))}}function Kn(t,n){return!!t&&!!n&&pa(t.deviceId)===pa(n.deviceId)&&sc(t.transitionGeneration)===sc(n.transitionGeneration)}function pw({deviceId:t,requestTransitionGeneration:n,currentTransitionGeneration:r,actualControlOwner:o}){const l=pa(t),u=sc(n),f=sc(r);return!!l&&u>0&&u===f&&(!o||pa(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=pa(t);return!o||!n||pa(n.deviceId)!==o?!1:!r||pa(r.deviceId)!==o}function kg(t,n){if(!t||!n)return!1;const r=sc(n.captureGeneration),o=pa(n.commandId),l=pa(n.sessionId),u=pa(n.streamId),f=Number(t.monitorIndex);return!r||!o||!l||!u||!Number.isInteger(f)||f<0?!1:pa(t.deviceId)===pa(n.deviceId)&&pa(t.sessionId)===l&&pa(t.streamId)===u&&pa(t.commandId)===o&&sc(t.captureGeneration)===r&&pa(t.streamPurpose).toLowerCase()==="control"&&f===n.monitorIndex}const CN=820,kN=500,gw=`(max-width: ${CN}px), (orientation: landscape) and (max-height: ${kN}px) and (pointer: coarse)`,MN="1200px 0px 1800px 0px",AN=960,NN=540,TN=68;function RN(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,AN),maxHeight:Math.min(o.maxHeight,NN),quality:Math.min(o.quality,TN)}:o}function jN(t,n){return!n||!t||typeof t.closest!="function"?null:t.closest(".desk-stage")}function EN(t,n,r){const o=Number(t?.height),l=Number(n),u=Number.isFinite(o)&&o>0?o:Number.isFinite(l)&&l>0?l:1,f=Number(t?.width),h=Number(r),g=Number.isFinite(f)&&f>0?f:Number.isFinite(h)&&h>0?h:1,y=Number(t?.offsetTop),w=Number(t?.offsetLeft);return{height:Math.max(1,Math.round(u)),width:Math.max(1,Math.round(g)),offsetTop:Number.isFinite(y)?Math.max(0,Math.round(y)):0,offsetLeft:Number.isFinite(w)?Math.max(0,Math.round(w)):0}}function DN(t,n){const r=Promise.resolve(t).catch(()=>{}).then(n);return{result:r,tail:r.then(()=>{},()=>{})}}function IN(){let t=Promise.resolve(),n=Promise.resolve();const r=o=>{const l=DN(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 LN(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 PN(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 Yn=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"?Yn.slowWallFps:Yn.fastWallFps}function vw({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 yw({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 _N(t){return t==="share-files"||t==="agents"}function FN({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 ON({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,D=Math.min(1,N/S,A/k),I=Math.max(1,Math.round(S*D)),R=Math.max(1,Math.round(k*D));return h<I*.9||g<R*.9}function BN({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,D=A>=g,I=1e3/h*Yn.controlWallReuseStarvationFactor,R=!D&&Number(o)>=I,_=b&&y+k>=w,B=b?_||R:D||R;let F=w;return B&&y>0&&(!b||R?F=y+S:(F=w+S,F<=y-S&&(F=y+S))),{shouldPaint:B,nextCadenceCredit:R?0:D&&B?A-g:Math.min(g-Number.EPSILON,A),sourceCadencePassthrough:!1,deadlineForced:R,scheduleSelected:_,nextScheduledPaintAtMs:F}}function HN(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 zN(t,n){const r=Math.max(0,Math.floor(Number(n)||0));return t===!0&&r>0}function _f({mode4Enabled:t,directMode4WallEnabled:n,isMac:r}){return"direct"}function $N({mode4Enabled:t,directMode4WallEnabled:n,adaptiveFps:r,directDeviceCount:o,adaptive:l=!0}){return Math.max(1,Math.floor(Number(r)||1))}function UN({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),D=Math.max(0,Number(h)||0),I=Math.max(1,Number(g)||1),R=y*w,_=R>8&&b<R*Yn.missingDeliveryRatio,B=R>8&&S<R*Yn.missingDeliveryRatio,F=k>N||A>I||_||B,H=b>=R*Yn.recoveryDeliveryRatio&&S>=R*Yn.recoveryDeliveryRatio&&k<N*Yn.recoveryByteRatio&&A<I*Yn.recoveryGapRatio&&D<I*Yn.recoveryGapRatio;return{expectedFramesPerSecond:R,estimatedMissingFrames:_,estimatedMissingPaints:B,overloaded:F,healthyForRecovery:H}}function qN({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>=Yn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(f)&&f>=Yn.adaptiveMinimumCurrentSampleMs&&Number.isFinite(h)&&h>0&&h===g}function WN({deviceCount:t,targetFps:n,adaptive:r=!0}){const o=Math.max(1,Math.floor(Number(t)||1)),l=Math.max(1,Math.min(Yn.scalableAtlasMaxInputFps,Math.floor(Number(n)||Yn.scalableAtlasMaxInputFps)));if(!r)return l;const u=Math.max(Yn.scalableAtlasMinInputFps,Math.min(Yn.scalableAtlasMaxInputFps,Math.floor(Yn.scalableAtlasAggregateInputFps/o)));return Math.min(l,u)}function GN(t,n){return{acceleration:Yn.directDecodeAcceleration,latencyMode:Yn.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}}},VN=[{id:"connection",label:"Connection",icon:eh},{id:"remote-access",label:"Remote Access",icon:ha},{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 bw(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 Ff({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 ww({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 KN({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(""),[D,I]=d.useState("idle"),[R,_]=d.useState(""),B=d.useRef(null),F=d.useRef(null),H=d.useRef([]),j=d.useRef(Promise.resolve()),Q=d.useRef(0),$=d.useRef(0);d.useEffect(()=>{const Se=++$.current;let ae=!0;return H.current=[],F.current=null,B.current=null,j.current=Promise.resolve(),k("loading"),rt("/api/settings",void 0,t).then(ye=>{if(!ae||Se!==$.current)return;const Pe=Mg(ye);F.current=Pe,B.current=Pe,b(Pe),k("saved")}).catch(ye=>{!ae||Se!==$.current||(A(ye instanceof Error?ye.message:String(ye)),F.current=eu,B.current=eu,b(eu),k("failed"))}),()=>{ae=!1}},[t]);const G=async(Se,ae,ye)=>{const Pe={id:++Q.current,section:Se,key:ae,value:ye},de=$.current;H.current.push(Pe);const Ke=bw(B.current||F.current||eu,Pe);B.current=Ke,b(Ke),k("saving"),A(""),j.current=j.current.then(async()=>{if(de!==$.current)return;let ue=null,Fe=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(Fe=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!==$.current)return;F.current=Mg(ke)}catch(ke){Fe=ke;break}}}if(de!==$.current)return;H.current=H.current.filter(Ee=>Ee.id!==Pe.id),ue&&(F.current=ue);const Xe=F.current||eu,at=H.current.reduce(bw,Xe);B.current=at,b(at),ue?(A(""),k(H.current.length>0?"saving":"saved")):(k(H.current.length>0?"saving":"failed"),A(Fe instanceof Error?Fe.message:String(Fe||"Settings could not be saved.")))}),await j.current},W=(Se,ae)=>ye=>{G(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 l0({baseUrl:t,targetRole:"client",previousRuntimePid:Number(Se.runtimePid||0),allowedStates:["running","waiting-auth"]}),zM(5179)}catch(Se){I("failed"),_(Se instanceof Error?Se.message:String(Se))}},X=Pp(w,"security"),ve=Pp(w,"control"),J=Pp(w,"filesAudio"),z=`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(Vx,{size:20})]}),i.jsx("p",{className:"settings-help",children:"Stop hosting from this computer and reconnect it to the selected Hub."}),D==="accepted"?i.jsx("p",{className:"settings-help runtime-role-success",children:"LiveDesk is restarting as Client."}):R?i.jsx("p",{className:"settings-help runtime-role-error",role:"alert",children:R}):null,i.jsx("button",{className:"settings-reset",onClick:()=>{V()},disabled:D==="changing"||n!=="hub",type:"button",children:D==="changing"?"Switching role...":"Switch this computer to Client"})]})]}),re=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:ha,title:"Access mode",description:"Choose the default permission boundary for remote sessions.",recommended:!0,children:i.jsx(ww,{value:String(X.accessMode),onChange:W("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(kr,{size:20})]}),i.jsx(Kc,{icon:kr,title:"Keyboard and mouse control",description:"Allow Control to send keyboard and pointer input.",recommended:!0,children:i.jsx(Ff,{checked:!!ve.allowKeyboardMouse,onChange:W("control","allowKeyboardMouse"),label:"Keyboard and mouse control"})}),i.jsx(Kc,{icon:Gx,title:"Power actions",description:"Allow confirmed sleep, restart, and shut down commands from the Hub.",children:i.jsx(Ff,{checked:!!ve.allowRemoteRestart,onChange:W("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(Ff,{checked:!!J.allowFileTransfer,onChange:W("filesAudio","allowFileTransfer"),label:"File transfer"})}),i.jsx(Kc,{icon:Jl,title:"Remote audio",description:"Allow sound capture from connected computers.",children:i.jsx(Ff,{checked:!!J.allowRemoteAudio,onChange:W("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(Ff,{checked:!!J.rollingBufferEnabled,onChange:W("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(ww,{value:Number(J.timelapseIntervalSeconds),onChange:Se=>W("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"?re: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:VN.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:z,role:"tabpanel","aria-labelledby":`settings-tab-${g}`,tabIndex:0,children:Z})]})}function QN({children:t}){return i.jsx("div",{className:"settings-tab-content",children:t})}const xw={enabled:!1};function Sw(t){return{enabled:t?.enabled===!0}}async function YN(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 XN({hubUrl:t,showToast:n}){const[r,o]=d.useState(xw),[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 j=new AbortController;k.current=j;const Q=++S.current;return u(null),o(xw),h(""),b(""),y(""),rt("/api/settings/agent",{signal:j.signal},t).then($=>{!H||j.signal.aborted||Q!==S.current||(u($.settings),o(Sw($.settings)))}).catch($=>{H&&!j.signal.aborted&&Q===S.current&&b($ instanceof Error?$.message:String($))}),()=>{H=!1,j.abort(),k.current===j&&(k.current=null)}},[t]);const N=(H,j)=>o(Q=>({...Q,[H]:j})),A=H=>{u(H),o(Sw(H))},D=()=>({generation:S.current,controller:k.current}),I=H=>H.generation===S.current&&H.controller!==null&&H.controller===k.current&&!H.controller.signal.aborted,R=async()=>{if(!l){b("Agent settings are not available yet.");return}const H=D();if(I(H)){h("save"),b(""),y("");try{if(await YN(r.enabled,t,H.controller.signal),!I(H))return;const j=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(j.settings),y("Codex Agent settings saved.")}catch(j){I(H)&&b(j instanceof Error?j.message:String(j))}finally{I(H)&&h("")}}},_=async()=>{const H=D();if(I(H)){h("test"),b(""),y("");try{const j=await rt("/api/settings/agent/test",{method:"POST",signal:H.controller.signal,body:JSON.stringify({})},t);if(!I(H))return;const Q=await rt("/api/settings/agent",{signal:H.controller.signal},t);if(!I(H))return;A(Q.settings);const $=Number.isFinite(j.connection?.latencyMs)?Math.max(0,Math.round(j.connection.latencyMs)):null;n(`Codex Agent connection verified${$!==null?` in ${$} ms.`:"."}`,"success")}catch(j){I(H)&&b(j instanceof Error?j.message:String(j))}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(ha,{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(hk,{size:15})," ",f==="test"?"Testing":"Test connection"]})]}),i.jsxs("p",{className:"settings-help",children:[i.jsx(gk,{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:()=>{R()},disabled:!F||f!=="",type:"button",children:[i.jsx(vk,{size:15})," ",f==="save"?"Saving":"Save Agent settings"]})})]})}new Date().valueOf();function ho(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 Dd(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 ZN(t,n="data-id"){const r=Dd(t,n);return r?r.getAttribute(n):null}function im(t,n="data-id"){const r=Dd(t,n);return r?uh(r,n):null}function uh(t,n="data-id"){const r=t.getAttribute(n);return r?JN(r):null}function _a(t){return typeof t=="string"?":"+t:t}function JN(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function eT(){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 ls=eT();function Bv(t){Object.assign(ls,t)}function Cw(t,n,r){function o(l){const u=Dd(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)}ls.addEvent(t,r,o)}function Id(t,n){Cw(t,n,"click"),n.dblclick&&Cw(t,n.dblclick,"dblclick")}function tT(t,n){for(let r=t.length-1;r>=0;r--)if(t[r]===n){t.splice(r,1);break}}function nT(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 Z0=new Date,Qp=!1,pp=[],rl=[],kw=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>Z0)&&!o.contains(n)&&o!==n&&(nT(o,n,r)||(u.callback&&u.callback(t),u.modal||t.defaultPrevented)))break}},aT=t=>{Z0=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 go(t,n){pp.length||(pp=[ls.addGlobalEvent("click",kw,t),ls.addGlobalEvent("contextmenu",kw,t),ls.addGlobalEvent("mousedown",aT,t)]),typeof n!="object"&&(n={callback:n});const r={node:t,date:new Date,props:n};return rl.push(r),{destroy(){tT(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,Mw=t=>t.indexOf("fit")!==-1,Of=t=>t.indexOf("overlap")!==-1,rT=t=>t.split("-").every(n=>["center","fit"].indexOf(n)>-1),sT=t=>{const n=t.match(/(start|center|end)/);return n?n[0]:null};function iT(t,n){let r=0;const o=ls.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 fa,xr,Bf,tr;function J0(t,n,r="bottom",o=0,l=0){if(!t)return null;fa=o,xr=l,Bf="auto";let u=0,f=0,h=r;const g=eS(t),y=Of(r)?ls.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=iT(n,g);u=Math.max(B+1,20)}if(n){if(tr=n.getBoundingClientRect(),Mw(r)&&(Bf=tr.width+"px"),r!=="point")if(rT(r))Mw(r)?fa=0:(fa=S.width/2,f=1),xr=(S.height-b.height)/2;else{const B=Of(r)?0:1;fa=vp(r)?tr.right+B:tr.left-B,xr=hp(r)?tr.bottom+1:tr.top;const F=sT(r);F&&(vp(r)||gp(r)?F==="center"?xr-=(b.height-tr.height)/2:F==="end"&&(xr-=b.height-tr.height):(hp(r)||Ag(r))&&(F==="center"?fa-=(b.width-tr.width)/2:F==="end"&&(fa-=b.width-tr.width),Of(r)||(fa+=1)))}}else tr={left:o,right:o,top:l,bottom:l};const A=(gp(r)||vp(r))&&(hp(r)||Ag(r));gp(r)&&(f=2);const D=fa-b.width-S.left;n&&gp(r)&&!A&&D<0&&(fa=tr.right,f=0,h=h.replace("left","right"));const I=fa+b.width*(1-f/2)-S.right;if(I>0)if(!vp(r))fa=S.right-N.right-b.width;else{const B=tr.left-S.x-b.width;n&&!A&&B>=0?(fa=tr.left-b.width,h=h.replace("right","left")):fa-=I+N.right}f&&(fa=Math.round(fa-b.width*f/2));const R=D<0||I>0||!A;Ag(r)&&(xr=tr.top-b.height,n&&xr<S.y&&R&&(xr=tr.bottom,h=h.replace("top","bottom")));const _=xr+b.height-S.bottom;return _>0&&(n&&hp(r)&&R?(xr-=b.height+tr.height+1,h=h.replace("bottom","top")):xr-=_+N.bottom),fa-=w.left+N.left,xr-=w.top+N.top,fa=(Of(r)?fa:Math.max(fa,0))+y.scrollLeft,xr=(Of(r)?xr:Math.max(xr,0))+y.scrollTop,Bf=Bf||"auto",{at:h,x:fa,y:xr,z:u,width:Bf}}function eS(t){const n=ls.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 oT(t){const n=[];let r=t;const o=ls.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 Aw=new Date().valueOf();function Hv(){return Aw+=1,Aw}function Cr(t){return t<10?"0"+t:t.toString()}function lT(t){const n=Cr(t);return n.length==2?"0"+n:n}function tS(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 Nw=["",""];function cT(t,n,r){switch(t){case"%d":return Cr(n.getDate());case"%m":return Cr(n.getMonth()+1);case"%j":return n.getDate();case"%n":return n.getMonth()+1;case"%y":return Cr(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 Cr((n.getHours()+11)%12+1);case"%g":return(n.getHours()+11)%12+1;case"%G":return n.getHours();case"%H":return Cr(n.getHours());case"%i":return Cr(n.getMinutes());case"%a":return((n.getHours()>11?r.pm:r.am)||Nw)[0];case"%A":return((n.getHours()>11?r.pm:r.am)||Nw)[1];case"%s":return Cr(n.getSeconds());case"%S":return lT(n.getMilliseconds());case"%W":return Cr(Ng(n));case"%w":{const o=r.weekStart??1;if(o===1)return Cr(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)),Cr(Ng(f))}case"%c":{let o=n.getFullYear()+"";return o+="-"+Cr(n.getMonth()+1),o+="-"+Cr(n.getDate()),o+="T",o+=Cr(n.getHours()),o+=":"+Cr(n.getMinutes()),o+=":"+Cr(n.getSeconds()),o}case"%Q":return Math.floor(n.getMonth()/3)+1;default:return t}}var uT=/%[a-zA-Z]/g;function Ad(t,n){return typeof t=="function"?t:function(r){return r?(r.getMonth||(r=new Date(r)),t.replace(uT,o=>cT(o,r,n))):""}}function Tw(t){return t&&typeof t=="object"&&!Array.isArray(t)}function hv(t,n){for(const r in n){const o=n[r];Tw(t[r])&&Tw(o)?t[r]=hv({...t[r]},n[r]):t[r]=n[r]}return t}function um(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),um(o)}}}var dT=n0();const fT="en-US",mT={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},pT={ok:"OK",cancel:"Cancel",select:"Select","No data":"No data","Rows per page":"Rows per page","Total pages":"Total pages"},hT={timeFormat:"%H:%i",dateFormat:"%m/%d/%Y",monthYearFormat:"%F %Y",yearFormat:"%Y"},nS={core:pT,calendar:mT,formats:hT,lang:fT},zv=d.createContext(""),aS=d.createContext({}),Mi=d.createContext(null),rS=d.createContext(null),Oa=Object.freeze(Object.defineProperty({__proto__:null,fieldId:rS,helpers:aS,i18n:Mi,theme:zv},Symbol.toStringTag,{value:"Module"}));function sS(t){const n=d.useContext(rS),[r]=d.useState(()=>t||n||Hv());return r}function tm({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 gT({id:t,label:n="",inputValue:r="",value:o=!1,onChange:l,disabled:u=!1,css:f=""}){const h=sS(t),[g,y]=ho(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||vT(l.current)||ls.getTopNode(l.current))},[l.current]),i.jsxs(i.Fragment,{children:[i.jsx("span",{ref:l,style:{display:"none"}}),l.current&&u?dT.createPortal(i.jsx("div",{className:`wx-3ZWsT0 wx-${t||h}-theme`,children:r}),u):null]})}function vT(t){const n=ls.getTopNode(t);for(;t&&t!==n&&!t.getAttribute("data-wx-portal-root");)t=t.parentNode;return t}function yT({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,D]=d.useState(!1),I=d.useRef(null),R=d.useRef(null),_=d.useRef(f);d.useEffect(()=>{_.current=f},[f]);function B(H){return o&&(l+"").indexOf("%")>-1?l.replace(/(\d+)%/,(j,Q)=>(Q=Q*o.offsetWidth/100+"px",l.replace(j,Q))):l&&l!=="auto"?l:H}const F=d.useCallback(()=>{if(!I.current)return;const H=J0(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=Q=>{_.current&&Q.target!==R.current&&I.current&&!I.current.contains(Q.target)&&_.current(Q)};let j;return requestAnimationFrame(()=>{F(),D(!0),g&&I.current&&(R.current=eS(I.current),R.current&&R.current.addEventListener("scroll",H,!0)),o&&(j=new ResizeObserver(F),j.observe(o))}),()=>{g&&R.current&&R.current.removeEventListener("scroll",H,!0),j?.disconnect()}},[]),d.useLayoutEffect(()=>{F()},[o,r,t,n]),d.useEffect(()=>{const H=j=>{_.current&&_.current(j)};if(I.current)return go(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 bT({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 go(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(bT,{onCancel:l,position:t,align:n,autoFit:r,width:u,...h,children:f}):i.jsx($v,{children:i.jsx(yT,{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 um(nS)}function wT(){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=im(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 Rw=10,xT=d.memo(function({data:t,checkboxes:n,itemTemplate:r,value:o}){return i.jsxs(i.Fragment,{children:[n&&i.jsx(gT,{id:t.id,css:"wx-list-checkbox",value:o&&o.includes(t.id)}),r?Ov(r,{option:t}):t.label]})});function jw({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(xT,{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(wT()),[S,k]=d.useState(null),N=d.useRef(S),[A,D]=d.useState(0),[I,R]=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 j=d.useRef(0);d.useEffect(()=>{j.current=I},[I]);const Q=d.useCallback(ae=>{ae&&ae.stopPropagation();const ye=F.current,Pe=H.current,de=N.current;let Ke;const ue=ye[de]?.id;f?Pe&&Pe.includes(ue)?Ke=Pe.filter(Fe=>Fe!==ue):Ke=[...Pe||[],ue]:Ke=ue,r&&r({id:Ke})},[f,r]),$=d.useRef(Q);d.useEffect(()=>{$.current=Q},[Q]);const G=d.useCallback(ae=>{if(y.current){let ye=ae*j.current-y.current.clientHeight+j.current;D(ye),y.current.scrollTop=ye}},[j.current]),W=d.useCallback(ae=>{y.current=ae,l&&(ae&&!w.current&&N.current!==null&&requestAnimationFrame(()=>{y.current&&(G(N.current),w.current=!0)}),ae||(w.current=!1))},[G]),V=d.useCallback(ae=>{if(!ae||_.current)return;const ye=ae.getBoundingClientRect().height;ye&&(R(ye),j.current=ye,_.current=!0)},[]);d.useEffect(()=>{b.current.init(y.current,t,ae=>{k(ae),N.current=ae},ae=>$.current(ae),l)},[t,y.current,l]),d.useEffect(()=>{const ae=(Pe,de)=>{b.current.navigate(Pe,de),G(N.current)},ye=(Pe,de)=>{const Ke=N.current,ue=F.current;if(Ke!==0&&Ke!==ue.length-1&&(Pe.key==="ArrowDown"||Pe.key==="ArrowUp")&&Pe.preventDefault(),b.current.keydown(Pe,de),y.current){const Fe=y.current.scrollTop<=N.current*j.current,Xe=y.current.scrollTop+y.current.clientHeight>=N.current*j.current+j.current;Fe?Xe||G(N.current):(y.current.scrollTop=N.current*j.current,D(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]),z=d.useCallback(ae=>{l&&D(ae.target.scrollTop)},[l]),P=d.useMemo(()=>Math.ceil((y.current?.clientHeight||0)/I),[I,A]),re=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-Rw),end:Math.min(t.length,ye+Rw)}},[l,t,A,I,P]),we=d.useMemo(()=>{if(!l)return t;const{start:ae,end:ye}=re;return t.slice(ae,ye).map(Pe=>({...Pe}))},[l,t,re]),Z=re.start*I,Se=t.length*I;return d.useEffect(()=>{l&&D(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:W,onClick:Q,onMouseMove:b.current.move,onScroll:z,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(jw,{visibleRange:re,visibleItems:we,navIndex:S,measureRefCallback:V,checkboxes:u,itemTemplate:n,value:h})})}):i.jsx(jw,{visibleRange:re,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=sS(n),[D,I]=ho(t),R=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 $=setTimeout(()=>{o&&R.current&&R.current.focus(),l&&R.current&&R.current.select()},1);return()=>clearTimeout($)},[o,l]);const F=d.useCallback($=>{const G=$.target.value;I(G),N&&N({value:G,input:!0})},[N]),H=d.useCallback($=>N&&N({value:$.target.value}),[N]);function j($){$.stopPropagation(),I(""),N&&N({value:""})}let Q=u;return u!=="password"&&u!=="number"&&(Q="text"),d.useEffect(()=>{const $=H,G=R.current;return G.addEventListener("change",$),()=>{G&&G.removeEventListener("change",$)}},[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:R,id:A,readOnly:r,disabled:h,placeholder:f,type:Q,title:y,value:D,onInput:F}),k&&!h&&D?i.jsxs(i.Fragment,{children:[i.jsx("i",{className:"wx-hQ64J4 wx-icon wxi-close",onClick:j}),B&&i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`})]}):S?i.jsx("i",{className:`wx-hQ64J4 wx-icon ${S}`}):null]})}function ST({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 Ad(u.monthYearFormat,l)(t);case"year":return Ad(u.yearFormat,l)(t);case"duodecade":{const{start:y,end:w}=tS(f),b=Ad(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 CT({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,j)=>new Date(F.getFullYear(),F.getMonth()+(H||0),F.getDate()+(j||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 D(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]),R=d.useMemo(()=>{const F=k(),H=N(),j=n.getMonth();let Q=[];for(let $=F;$<=H;$.setDate($.getDate()+1)){const G={day:$.getDate(),in:$.getMonth()===j,date:$.valueOf()};let W="";if(W+=G.in?"":" wx-inactive",W+=I.indexOf(G.date)>-1?" wx-selected":"",b){const V=G.date==I[0],X=G.date==I[1];V&&!X?W+=" wx-left":X&&!V&&(W+=" wx-right"),G.date>I[0]&&G.date<I[1]&&(W+=" wx-inrange")}if(W+=S($)?" wx-weekend":"",o){const V=o($);V&&(W+=" "+V)}Q.push({...G,css:W})}return Q},[n,I,b,o]),_=d.useRef(null);let B=d.useRef({});return B.current.click=D,d.useEffect(()=>{Id(_.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:R.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 kT({value:t,current:n,part:r,onCancel:o,onChange:l,onShift:u}){const f=d.useRef(new Date),[h,g]=ho(t||f.current),[y,w]=ho(n||f.current),b=d.useContext(Mi).getRaw().calendar,S=b.monthShort||[],k=d.useMemo(()=>y.getMonth(),[y]),N=d.useCallback((I,R)=>{if(I!=null){R.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(iS(h,r)||y);I.setMonth(y.getMonth()),I.setFullYear(y.getFullYear()),l&&l(I)},[h,y,r,l]),D=d.useCallback(I=>{const R=I.target.closest("[data-id]");if(R){const _=parseInt(R.getAttribute("data-id"),10);N(_,I)}},[N]);return i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"wx-34U8T8 wx-months",onClick:D,children:S.map((I,R)=>i.jsx("div",{className:"wx-34U8T8 wx-month"+(k===R?" wx-current":""),"data-id":R,children:I},R))}),i.jsx("div",{className:"wx-34U8T8 wx-buttons",children:i.jsx(Wv,{onClick:A,children:b.done})})]})}const Tg="wx-1XEF33",MT=({value:t,current:n,onCancel:r,onChange:o,onShift:l,part:u})=>{const f=d.useContext(Mi).getRaw().calendar,[h,g]=ho(n),[y,w]=ho(t),b=d.useMemo(()=>h.getFullYear(),[h]),S=d.useMemo(()=>{const{start:I,end:R}=tS(b),_=[];for(let B=I;B<=R;++B)_.push(B);return _},[b]),k={click:N};function N(I,R){if(I){R.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(iS(y,u)||h);I.setFullYear(h.getFullYear()),o&&o(I)}const D=d.useRef(null);return d.useEffect(()=>{D.current&&Id(D.current,k)},[]),i.jsxs(i.Fragment,{children:[i.jsx("div",{className:Tg+" wx-years",ref:D,children:S.map((I,R)=>i.jsx("div",{className:Tg+` wx-year ${b==I?"wx-current":""} ${R===0?"wx-prev-decade":""} ${R===11?"wx-next-decade":""}`,"data-id":I,children:I},R))}),i.jsx("div",{className:Tg+" wx-buttons",children:i.jsx(Wv,{onClick:A,children:f.done})})]})},Ew={month:{component:CT,next:NT,prev:AT},year:{component:kT,next:RT,prev:TT},duodecade:{component:MT,next:ET,prev:jT}};function AT(t){return t=new Date(t),t.setMonth(t.getMonth()-1),t}function NT(t){return t=new Date(t),t.setMonth(t.getMonth()+1),t}function TT(t){return t=new Date(t),t.setFullYear(t.getFullYear()-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()-10),t}function ET(t){return t=new Date(t),t.setFullYear(t.getFullYear()+10),t}function iS(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 DT=["clear","today"];function IT(t){if(t==="done")return-1;if(t==="clear")return null;if(t==="today")return new Date}function LT({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?DT:[],k=(R,_)=>{R.preventDefault(),g&&g({value:_})},N=()=>{w==="duodecade"?b("year"):w==="year"&&b("month")},A=R=>{const{diff:_,current:B}=R;if(_===0){w==="month"?b("year"):w==="year"&&b("duodecade");return}if(_){const F=Ew[w];r(_>0?F.next(n):F.prev(n))}else B&&r(B);h&&h()},D=R=>{b("month"),g&&g({select:!0,value:R})},I=d.useMemo(()=>Ew[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(ST,{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:D,onShift:A}),w==="month"&&S.length>0&&i.jsx("div",{className:"wx-2Gr4AS wx-buttons",children:S.map(R=>i.jsx("div",{className:"wx-2Gr4AS wx-button-item",children:i.jsx(Wv,{onClick:_=>k(_,IT(R)),children:y(R)})},R))})]})]})})}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=um(nS)),n!==null&&(f=f.extend(n,r)),f},[n,r,l]);return i.jsx(Mi.Provider,{value:u,children:o})}function Dw(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 PT=["clear","today"];function oS({value:t,current:n,markers:r=null,buttons:o=PT,css:l="",onChange:u}){const[f,h]=ho(t),[g,y]=ho(n);d.useEffect(()=>{Dw(g,f,y,!1)},[f,g]);const w=d.useCallback(S=>{const k=S.value;k?(h(new Date(k)),Dw(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(LT,{value:f,current:g,markers:r,buttons:o,css:l,onChange:w,onCurrentChange:b})}):null}function _T(t){return t||(t={}),t.width||(t.width="unset"),t}const FT=["clear","today"];function OT({value:t,id:n,disabled:r=!1,error:o=!1,placeholder:l="",format:u="",buttons:f=FT,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(),D=u||A?.dateFormat;let I=typeof D=="function"?D:Ad(D,N);const[R,_]=d.useState(t),[B,F]=d.useState(!1);d.useEffect(()=>{_(t)},[t]);function H(){F(!1)}function j(G){const W=G===R||G&&R&&G.valueOf()===R.valueOf()||!G&&!R;_(G),W||S&&S({value:G}),setTimeout(H,1)}const Q=d.useMemo(()=>R?I(R):"",[R,I]);function $({value:G,input:W}){if(!w&&!b||W)return;let V=typeof w=="function"?w(G):G?new Date(G):null;V=isNaN(V)?R||null:V||null,j(V)}return d.useEffect(()=>{const G=H;return window.addEventListener("scroll",G),()=>window.removeEventListener("scroll",G)},[]),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:Q,id:n,readonly:!w,disabled:r,error:o,placeholder:l,onInput:H,onChange:$,icon:"wxi-calendar",clear:b}),B&&!r&&i.jsx(Uv,{onCancel:H,..._T(k),children:i.jsx(oS,{buttons:f,value:R,onChange:G=>j(G.value)})})]})}function BT({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[D,I]=ho(t);function R(j){N.current=j.navigate,A.current=j.keydown}const _=d.useMemo(()=>D||D===0?(r||n).find(j=>j.id===D):null,[D,r,n]),B=d.useCallback(({id:j})=>{(j||j===0)&&(I(j),N.current(null),S&&S({value:j}))},[I,S]),F=d.useCallback(j=>{j.stopPropagation(),I(""),S&&S({value:""})},[I,S]),H=d.useCallback(()=>n.findIndex(j=>j.id===D),[n,D]);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:j=>A.current(j,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&&D?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:R,onSelect:B,...k,children:({option:j})=>b?b(j):j[g]})]})}const HT=({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 zT({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 $T({data:t=[]}){return i.jsx("div",{className:"wx-3nwoO9 wx-notices",children:t.map(n=>i.jsx(zT,{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(tm,{type:`block ${S==="ok"?"primary":"secondary"}`,onClick:k=>b(k,S),children:g(S)})},S))})]})})}function UT({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($T,{data:l})]})}const qT=d.forwardRef(UT);function WT(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(aS.Provider,{value:o,children:i.jsx(qT,{ref:r,children:n})})}const GT=({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]=ho(t),D=d.useMemo(()=>(N?"pressed":"")+(n?" "+n:""),[N,n]),I=d.useCallback(R=>{let _=!N;u&&u(R),R.defaultPrevented||(A(_),k&&k({value:_}))},[N,u,k]);return N&&S?i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o,children:Ov(S,{value:N})}):b?i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o,children:b}):i.jsx(tm,{title:f,tooltip:h,text:N&&w||y,css:g,type:D,icon:N&&l||r,onClick:I,disabled:o})};function VT(){return i.jsx(i.Fragment,{})}function Iw(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(VT,{}),i.jsx("link",{rel:"stylesheet",href:"https://cdn.svar.dev/fonts/wxi/wx-icons.css"})]})]})})}Bv(ls);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 lS=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 KT=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]:Lw(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);QT(h,y);const w=l?g.data.length:yp(g,u.id)+(n==="after"?1:0);if(Lw(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&&cS(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 cS(t,n){t.forEach(r=>{n.push(r),r.open===!0&&cS(r.data,n)})}function QT(t,n){const r=[...t.data];r.splice(n,1),t.data=r}function Lw(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 uS=2,YT=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&uS?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 Pw(t,n){return Object.defineProperty(t,"__reactive",{value:!0,enumerable:!1,writable:!1}),t}var XT=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=>dS(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,uS);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 dS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>dS(u,n,r+1));return Math.max(...l)}var ZT=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 wd=1024;function om(t){return t<wd?`${t} B`:t<wd**2?`${(t/wd).toFixed(1)} KB`:t<wd**3?`${(t/wd**2).toFixed(1)} MB`:`${(t/wd**3).toFixed(1)} GB`}function _w(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(Fw(n)),u=o.sort(Fw(n));return[...l,...u]}function JT(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 eR(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 Fw({key:t,order:n}){const r=n==="asc"?JT:eR;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 tR(t){return t.length>1?t[t.length-2].id:null}let nR=class extends KT{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()}}},aR=class extends YT{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=_w(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=_w(y,b[w]),k=[];k[u]={_selected:S},this.setState({panels:k},f)}});this._router=new XT(super.setState.bind(this),r,{data:u=>new nR(u)});const o=this.in=new ZT;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(R=>R.id==w[g]._lastSelected),D=N.findIndex(R=>R.id==u);D<A&&([A,D]=[D,A]);const I=N.slice(A,D+1).map(R=>R.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]=Pw({_crumbs:[],_files:[],_selected:[],_sorts:{},path:"/",selected:[],...n[o]});const r={panels:Pw(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 rR(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 sR(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 iR(t,n="data-id"){const r=sR(t,n);return r?r.getAttribute(n):null}new Date().valueOf();function oR(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(D=>D.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:D,_selectNavigation:I}=h;if(I){const R=tR(D);if(R){const _=Kv(R,D);r.exec("set-path",{id:R,selected:[_]})}}else if(g.length===1){const R=r.getFile(g[0]);R&&r.exec(R.type==="folder"?"set-path":"open-file",{id:R.id})}break}case"arrowup":case"arrowleft":{const{_files:D,_selected:I,path:R,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(0).id,H=D.findIndex(j=>j.id===F);if(H!==-1){const j=H-1;D[j]?B=D[j].id:R!=="/"&&!(y||w)&&r.exec("select-file",{type:"navigation"})}}else{if(_)break;if(R!=="/"){r.exec("select-file",{type:"navigation"});break}B=D.at(0)?.id}B&&r.exec("select-file",{id:B,toggle:y,range:w});break}case"arrowdown":case"arrowright":{const{_files:D,_selected:I,path:R,_selectNavigation:_}=h;let B;if(I.length){const F=I.at(-1).id,H=D.findIndex(j=>j.id===F);if(H!==-1){const j=H+1;D[j]&&(B=D[j].id)}}else{if(R!=="/"&&!_){r.exec("select-file",{type:"navigation"});break}B=D.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:+iR(h,"data-panel")})})}return t.addEventListener("keydown",l),{destroy:()=>{t.removeEventListener("keydown",l)}}}function lR(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 cR(t,n="data-id"){const r=t.getAttribute(n);return r?uR(r):null}function uR(t){if(t.startsWith(":"))return t.substring(1);const n=t*1;return isNaN(n)?t:n}function dR(){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 fR=dR();new Date().valueOf();function fS(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 mR(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 mR(o[n],r[n],n)}function pR(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 pR(o[n],r[n])}function mS(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 pS(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 Ow(t,n,r){function o(l){const u=lR(l);if(!u)return;const f=cR(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 fR.addEvent(t,r,o)}function hR(t,n){const r=[Ow(t,n,"click")];return n.dblclick&&r.push(Ow(t,n.dblclick,"dblclick")),()=>{r.forEach(o=>o())}}function hS(t,n){return t.map((r,o)=>{const l=n(r,o);return r.data&&r.data.length&&(l.data=hS(r.data,n)),l}).filter(Boolean)}function gS(t,n){const r=[];return t.forEach(o=>{if(o.data){const l=gS(o.data,n);l.length&&r.push({...o,data:l})}else n(o)&&r.push(o)}),r}function gR(t){return hS(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 vS={};function vR(t){return vS[t]||t}function yR(t,n){vS[t]=n}function bR({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?vR(r.comp):null,[r]);return i.jsxs("div",{ref:o,className:`wx-cDCz9rZQ wx-option ${r.css||""} ${r.disabled?"wx-disabled":""}`,"data-id":_a(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),[D,I]=d.useState(),R=d.useRef(null),[_,B]=d.useState(!1),[F,H]=d.useState(null),j=d.useCallback(()=>{const ve=J0(R.current,l,o,n,r);ve&&(b(ve.x),k(ve.y),I(ve.width));let J=ve?.z??20;const z=l?oT(l):[];let P=0;for(const re of z){const we=parseInt(getComputedStyle(re).zIndex,10);we>P&&(P=we)}P>=J&&(J=P+1),A(J)},[l,o,n,r]);d.useEffect(()=>{u&&u(j)},[]);const Q=d.useCallback(()=>{B(!1)},[]),$=d.useCallback((ve,J)=>{B(ve),H(J)},[]),G=d.useMemo(()=>gR(t),[t]);d.useEffect(()=>{j()},[l,j]);const W=d.useRef(g),V=d.useRef(y),X=d.useRef(l);return d.useEffect(()=>{W.current=g},[g]),d.useEffect(()=>{V.current=y},[y]),d.useEffect(()=>{X.current=l},[l]),d.useEffect(()=>{if(!R.current)return;function ve(J){V.current?V.current(J):W.current&&W.current({action:null,option:null})}return go(R.current,{callback:ve,modal:!0,parent:()=>X.current}).destroy},[]),i.jsx("div",{ref:R,"data-wx-menu":"true",className:`wx-XMmAGqVx wx-menu ${h}`,style:{position:"absolute",top:S+"px",left:w+"px",width:D,zIndex:N},onMouseLeave:Q,children:G.map(ve=>i.jsxs(d.Fragment,{children:[ve.comp==="separator"?i.jsx("div",{className:"wx-XMmAGqVx wx-separator"}):i.jsx(bR,{option:ve,onShow:$,onClick:J=>{if(!ve.data&&!J.defaultPrevented){const z={context:f,action:ve,option:ve,event:J};ve.handler&&ve.handler(z),g&&g(z),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 yS=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),[D,I]=d.useState(0),R=d.useRef(null),_=d.useMemo(()=>`data-${u.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}`,[u]),B=d.useMemo(()=>w!==null&&f?gS(r,Q=>f(Q,w)):r,[w,f,r]);function F(Q){k(null),y&&y(Q)}function H(Q){if(R.current===Q){R.current=null;return}k(null),y&&y({action:null,option:null})}const j=d.useCallback((Q,$)=>{if(!Q){k(null);return}if(Q.defaultPrevented)return;const G=Q.target;if(G&&G.dataset&&G.dataset.menuIgnore)return;if(S&&S===G){k(null),Q.preventDefault();return}A(Q.clientX+1),I(Q.clientY+1);let W=typeof $<"u"?$:im(G,_);l&&(W=l(W,Q),!W)||(b(W),k(G),R.current=Q.nativeEvent||Q,Q.preventDefault())},[S,_,l]);return d.useImperativeHandle(n,()=>({show:j}),[j]),i.jsxs(i.Fragment,{children:[g?i.jsx("span",{onClick:j,"data-menu-ignore":"true",children:typeof g=="function"?g():g}):null,S?i.jsx($v,{children:i.jsx(Qv,{css:h,at:o,top:D,left:N,parent:S,context:w,onClick:F,onCancel:H,options:B},S)}):null]})}),wR=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]})}),xR=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(yS,{css:h,at:o,options:r,resolver:l,dataKey:u,filter:f,ref:w,onClick:y})]})}),SR={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 CR=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 bS(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 CR(r,l,f,g,t)),y.current.files=n,y.current.ready=o,y.current.signal=u,y.current.drag=h,y.current}function kR(t,n){{if(t){const r=t.getGroup(n);if(r)return r}return um(SR).getGroup(n)}}const MR=()=>Math.random().toString(36).substr(2,9),AR=({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=bS(),A=t||N,D=d.useContext(Oa.i18n),I=kR(D,"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 R=G=>{const W=new FormData;return W.append("upload",G.file),fetch(l,{method:"POST",body:W}).then(V=>V.json()).then(V=>({id:G.id,...V}),()=>({id:G.id,status:"error"})).catch(V=>(console.log(V),{id:G.id,status:"error"}))},_=(G,W)=>{const V=A.updateFile(G,W),X={...V,status:A.getState()};V&&V.uploaded&&V.uploaded(X),y&&y(X),V.temp&&A.deleteFile(V.id)},B=G=>{if(!G)return;const W=typeof l=="function"?l(G):R(G);A.setReady(W.then(V=>{V.status=V.status||"server",_(G.id,V)}).catch(V=>{_(G.id,{status:"error",error:V})}))},F=(G,W)=>{const V={...W||S,id:MR(),status:"client",name:G.name,file:G};V.selected&&V.selected(V),g&&g(V),A.addFile(V,r),B(V),w.current&&(w.current.value="")},H=(G,W,V)=>{G.isFile?G.file(X=>{F(X,V)}):G.isDirectory&&G.createReader().readEntries(X=>{X.forEach(ve=>{H(ve,W+ve.name+"/",V)})})},j=G=>{Array.from(G.target.files).forEach(W=>F(W))},Q=(G,W)=>{Array.from(G.dataTransfer.items).forEach(V=>{const X=V.webkitGetAsEntry();X&&H(X,"",W)})},$=()=>{w.current&&w.current.click()};return d.useEffect(()=>{if(A.signal){const[G,W,V]=A.signal;k(W),G==="click"?$():G==="drop"&&Q(V,W),A.setSignal(null)}},[A.signal]),u?i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"file",className:"wx-at1A8tb8 wx-input",ref:w,onChange:j,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:j,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:$,children:I("select files")})]})})]})};new Date().valueOf();function NR(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 NR(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 wS=2,TR=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&wS?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}}}},RR=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=>xS(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,wS);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 xS(t,n,r){const o=n.get(t);if(!o)return r;const l=Object.keys(o).map(u=>xS(u,n,r+1));return Math.max(...l)}var jR=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 ER(t){return n=>n[t]}function DR(t){return(n,r)=>n[t]=r}function ic(t,n){return(n.getter||ER(n.id))(t)}function Rg(t,n,r){return(n.setter||DR(n.id))(t,r)}function IR(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 LR(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=Bw("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=Bw("footer",f,o,u,l)),o}function Bw(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 PR="portrait",_R=100,FR="a4",OR={a3:{width:11.7,height:16.5},a4:{width:8.27,height:11.7},letter:{width:8.5,height:11}};function BR(t,n){const r=[];let o=[],l=0;const u=t.filter(h=>!h.hidden),f=HR(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 Hw(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 HR(t){const{mode:n,ppi:r,paper:o}=t,{width:l,height:u}=OR[o];return zR(n==="portrait"?l:u,r)}function zR(t,n){return t*n}function $R(t={}){const{mode:n,ppi:r,paper:o}=t;return{mode:n||PR,ppi:r||_R,paper:o||FR}}function SS(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 UR(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 zw=["resize-column","hide-column","update-cell"],qR=["delete-row","update-row","update-cell"],WR=["move-item"],GR=["resize-column","move-item"];class VR{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(GR.includes(r)){(o.inProgress&&!this.progress[r]||typeof o.inProgress!="boolean")&&(WR.includes(r)&&this.setPrev("flatData"),zw.includes(r)&&this.setPrev("columns")),this.progress[r]=o.inProgress;return}qR.includes(r)&&this.setPrev("data"),zw.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 CS(t,n){return typeof t>"u"||t===null?-1:typeof n>"u"||n===null?1:t===n?0:t>n?1:-1}function KR(t,n){return-CS(t,n)}function QR(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"?CS:KR;return function(o,l){return r(ic(o,n),ic(l,n))}}function YR(t,n){if(!t||!t.length)return;const r=t.map(o=>{const l=n.find(u=>u.id==o.key);return QR(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,XR=20;function ZR(){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 $w(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 D=`wx-measure-cell-${n}`;if(D+=N?` ${N}`:"",A=Yp(w,D,l).width,(k>1||!h[y+1])&&r>y+1){const I=k||r-y,R=u.slice(y,y+I).reduce((_,B)=>_+B,0);if(R<A){const _=Math.ceil((A-R)/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 JR(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 ej(t,n){const r="wx-measure-cell-header",o=t.sort?XR: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 tj={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&&aj(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 kS(t){return tj[t]}function nj(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):kS(f)(y,h)})}return o=>{for(let l=0;l<r.length;l++)if(!r[l](o))return!1;return!0}}function aj(t,n){return t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate()}let rj=class extends TR{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 RR(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 jR;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(D=>D.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(D=>D.id===S[S.length-1]),A=k.findIndex(D=>D.id===l);N>A&&([N,A]=[A,N]),k.slice(N,A+1).forEach(D=>{this.isSelected(D.id)||S.push(D.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=JR(b,A,k)}if(f==="header"||f===!0){const{_skin:S}=this.getState();y=Math.max(ej(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 R=[...w];R.sort(h),this.setState({data:R});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 D=Object.keys(k).sort((R,_)=>k[R].index-k[_].index).map(R=>({key:R,order:k[R].order}));this.setState({sortMarks:k});const I=YR(D,y);if(I){const R=[...w];b?this.sortTree(R,I):R.sort(I),this.setState({data:R})}}),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??nj(S,b);let A=[];w?A=this.filterTree(y,N,A):y.forEach(D=>{N(D)&&A.push(D.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(D=>D.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=LR(this.getState(),l.csv||{});l.download!==!1?IR(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(D=>D.id===l.column);k=u[A].width;for(let D=f.left??0;D<A;D++){const I=u[D];I.hidden||(b+=I.width)}}if(l.row&&!y){const A=g.findIndex(D=>D.id===l.row);A>=0&&(w?(S=g.slice(0,A).reduce((D,I)=>D+(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=$R(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=ZR()),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 VR(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):kS(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=$w(n,"header",o,r.headerHeight,u),h=$w(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}}},sj=new Date().valueOf();function wp(){return"temp://"+sj++}function ij(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 oj=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)}}},Nd=[],lj={subscribe:t=>{cj();const n=new oj;return Nd.push(n),t(n),()=>{const r=Nd.findIndex(o=>o===n);r>=0&&Nd.splice(r,1)}}},Uw=!1;function cj(){Uw||(Uw=!0,document.addEventListener("keydown",t=>{if(Nd.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=Nd.length-1;l>=0;l--){const u=Nd[l],f=u.store.get(o)||u.store.get(r);f&&u.node.contains(t.target)&&f(t,{key:o,evKey:r})}}}))}const uj={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 dj(t,{keys:n,exec:r}){if(!n)return;function o(f){const h=f.target;return h.tagName==="INPUT"||h.tagName==="TEXTAREA"||ij(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=lj.subscribe(f=>{f.configure(l,t)});return{destroy:()=>{u()}}}function fj(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 Ds=d.createContext(null);function mj(t,n){const r=new ResizeObserver(o=>{requestAnimationFrame(()=>n(o[0].contentRect))});return r.observe(t.parentNode),{destroy(){r.disconnect()}}}const qw=5,pj=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 hj(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(j){const Q=Dd(j);Q&&(o={container:g,sourceNode:j.target,from:uh(Q),pos:yv(j,t)},u=o.pos,b(j))}function b(j){if(!o)return;const Q=o.pos=yv(j,t);if(!f){if(!h&&!j?.target?.getAttribute("draggable-data")&&Math.abs(u.x-Q.x)<qw&&Math.abs(u.y-Q.y)<qw)return;if(F(j)===!1)return H()}if(h){const $=window.scrollX||document.documentElement.scrollLeft||document.body.scrollLeft,G=window.scrollY||document.documentElement.scrollTop||document.body.scrollTop;o.targetNode=document.elementFromPoint(j.pageX-$,j.pageY-G)}else o.targetNode=j.target;r.move&&r.move(j,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(j){g.parentNode&&g.parentNode.removeChild(g),g.innerHTML="",f&&r.end&&r.end(j,o),o=u=null,H()}function k(j){r.getReorder&&!r.getReorder()||j.button===0&&(B(j),window.addEventListener("mousemove",N),window.addEventListener("mouseup",A),w(j))}function N(j){b(j)}function A(j){S(j)}function D(j){if(r.getReorder&&!r.getReorder())return;l=setTimeout(()=>{h=!0,w(j.touches[0])},pj),B(j);function Q(){l&&y(),j.target.removeEventListener("touchmove",I),j.target.removeEventListener("touchend",Q),S(j)}j.target.addEventListener("touchmove",I),j.target.addEventListener("touchend",Q),t.addEventListener("contextmenu",R)}function I(j){f?(j.preventDefault(),b(j.touches[0])):l&&y()}function R(j){if(f||l)return j.preventDefault(),!1}function _(j){j.preventDefault()}function B(j){if(!r.getDraggableInfo)return;const{hasDraggable:Q}=r.getDraggableInfo();(!Q||j.target.getAttribute("draggable-data"))&&(document.body.style.userSelect="none",document.body.style.webkitUserSelect="none")}function F(j){if(f=!0,r.start){if(r.start(j,o)===!1)return!1;t.appendChild(g),document.body.style.cursor="move"}}function H(j){f=h=!1,document.body.style.cursor="",document.body.style.userSelect="",document.body.style.webkitUserSelect="",window.removeEventListener("mousemove",N),window.removeEventListener("mouseup",A),j&&(t.removeEventListener("mousedown",k),t.removeEventListener("touchstart",D),t.removeEventListener("dragstart",_))}return t.addEventListener("mousedown",k),t.addEventListener("touchstart",D),t.addEventListener("dragstart",_),{destroy(){H(!0)}}}const gj=.004;function vj(){return{dirX:0,dirY:0,scrollSpeedFactor:1}}function yj(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=vj());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)&&(MS(r),r.scrollState.dirX=S,r.scrollState.dirY=k),(y&&r.scrollState.dirX!==0||w&&r.scrollState.dirY!==0)&&bj(r,o,{x:r.scrollState.dirX,y:r.scrollState.dirY})}function bj(t,n,r){t.autoScrollTimer||(t.autoScrollTimer=setTimeout(()=>{t.activeAutoScroll=setInterval(wj,15,t,n,r)},250))}function MS(t){t.scrollSpeedFactor=1,t.autoScrollTimer&&(t.autoScrollTimer=clearTimeout(t.autoScrollTimer),t.activeAutoScroll=clearInterval(t.activeAutoScroll))}function wj(t,n,r){const{x:o,y:l}=r;t.scrollSpeedFactor+=gj,o!==0&&Sj(t,n,o),l!==0&&xj(t,n,l)}function xj(t,n,r){const o=n.node.scrollTop;AS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollTop",n)}function Sj(t,n,r){const o=n.node.scrollLeft;AS(o+Math.round(n.sense/3)*t.scrollSpeedFactor*r,"scrollLeft",n)}function AS(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 NS(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 Cj(t){const{row:n,column:r,cellStyle:o=null,columnStyle:l=null,children:u,focusable:f}=t,h=d.useContext(Ds),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 j="wx-cell";return j+=r.fixed?" "+(r.fixed===-1?"wx-shadow":"wx-fixed"):"",j+=F?" "+F(r):"",j+=H?" "+H(n,r):"",j+=r.treetoggle?" wx-tree-cell":"",j}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]),D=d.useRef(null);d.useEffect(()=>{D.current&&f&&g?.row===n.id&&g?.column===r.id&&D.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 R(F){const H=new RegExp(`(${y.value.trim()})`,"gi");return String(F).split(H).map(j=>({text:j,highlight:H.test(j)}))}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:D,onFocus:I,style:S,"data-row-id":_a(n.id),"data-col-id":_a(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:R(tc(n,r)).map(({highlight:F,text:H},j)=>F?i.jsx("mark",{className:"wx-TSCaXsGV wx-search",children:H},j):i.jsx("span",{children:H},j))}):tc(n,r)]})}function Ww(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 kj({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 Mj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Ds),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(BT,{placeholder:"",clear:!0,...t?.config??{},options:f,value:o,onChange:y,children:b=>h?h(b):b.label})})}function Aj({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(OT,{placeholder:"",clear:!0,...t?.config??{},value:o,onChange:l})})}function TS(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]=fS(n||[]),N=d.useMemo(()=>(S||[]).map(G=>r.find(W=>W.id===G)).filter(Boolean),[S,r]),A=d.useRef(null),D=d.useRef(null),[I,R]=d.useState(null),_=()=>{const G=S||[];if(!G.length)return 0;const W=r.find(V=>G.includes(V.id));return W?r.indexOf(W):0};function B(G){D.current=G.navigate,R(()=>G.keydown),y&&G.navigate(_())}d.useEffect(()=>{y&&(A.current?.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges())},[]);function F({id:G}){k(G),w&&w({value:G})}function H(G){G.stopPropagation(),k([]),w&&w({value:[]})}function j(){D.current?.(_())}function Q(){D.current?.(null)}function $(G){I?.(G,_())}return i.jsxs("div",{ref:A,className:"wx-multiselect wx-aadNNOwy",onClick:j,onKeyDown:$,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(G=>G.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:Q,...g,children:({option:G})=>i.jsx("div",{className:"wx-option wx-aadNNOwy",children:f?f(G):h?i.jsx(h,{data:G,onAction:b}):G.label})})]})}function Nj({filter:t,column:n,action:r,filterValue:o}){const l=d.useContext(Oa.i18n)?.getGroup("grid")||um(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(TS,{placeholder:"",...u,options:f,value:o||[],text:h,onChange:g})})}const Tj={text:kj,richselect:Mj,datepicker:Aj,multiselect:Nj};function Rj({filter:t,column:n}){const r=d.useContext(Ds),o=Ot(r,"filterValues");function l(f){r.exec("filter-rows",f)}const u=d.useMemo(()=>Tj[t.type],[t.type]);return i.jsx(u,{filter:t,column:n,action:l,filterValue:o[n.id]})}function jj(t){const{cell:n,column:r,row:o,lastRow:l,sortRow:u,columnStyle:f,bodyHeight:h,hasSplit:g}=t,y=d.useContext(Ds),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]),D=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]),R=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"&&R()},[R]),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]),j=d.useMemo(()=>H?{top:-h/2,position:"absolute"}:{},[H,h]),Q=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]),$=d.useMemo(()=>NS(r,n,f),[r,n,f]),G=d.useCallback(()=>Object.fromEntries(Object.entries(n).filter(([ve])=>ve!=="cell")),[n]),W=`wx-cell ${$} ${n.css||""} wx-collapsed`,V=["wx-cell",$,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=Ww(ve,{down:k,move:A,up:D});return()=>{typeof J=="function"&&J()}},[k,A,D,Ww]),F?i.jsx("div",{className:"wx-RsQD74qC "+W,style:Q,role:"button","aria-label":`Expand column ${n.text||""}`,"aria-expanded":!n.collapsed,tabIndex:0,onKeyDown:_,onClick:R,"data-header-id":_a(r.id),children:i.jsx("div",{className:"wx-RsQD74qC wx-text",style:j,children:n.text||""})}):i.jsxs("div",{className:"wx-RsQD74qC "+V,style:Q,onClick:I,"data-header-id":_a(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:R,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:G(),column:r,row:o,onAction:({action:J,data:z})=>y.exec(J,z)})})():n.filter?i.jsx(Rj,{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 Ej({cell:t,column:n,row:r,columnStyle:o}){const l=d.useContext(Ds),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(()=>NS(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 Gw({deltaLeft:t,contentWidth:n,columns:r,type:o="header",columnStyle:l,bodyHeight:u}){const f=d.useContext(Ds),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 D=r[0][o].length;for(let I=0;I<D;I++){let R=0;A.push([]),r.forEach((_,B)=>{const F={..._[o][I]};R||A[I].push(F),F.colspan>1?R=F.colspan-1:R&&R--})}}return A},[r,o]),b=d.useMemo(()=>g?.left||g?.right,[g]);function S(A){return r.find(D=>D.id===A)}function k(A,D){let I=D;return A.rowspan&&(I+=A.rowspan-1),I===w.length-1}function N(A,D,I){if(!I.sort)return!1;for(let R=w.length-1;R>=0;R--){const _=I.header[R];if(!_.filter&&!_._hidden)return D===R}return k(A,D)}return i.jsx("div",{className:`wx-sAsPVaUK wx-${o}`,style:{paddingLeft:`${t}px`,width:`${n}px`},role:"rowgroup",children:w.map((A,D)=>i.jsx("div",{className:o==="header"?"wx-sAsPVaUK wx-h-row":"wx-sAsPVaUK wx-f-row",style:{height:`${y?.[D]}px`,display:"flex"},role:"row",children:A.map(I=>{const R=S(I.id);return o==="header"?i.jsx(jj,{cell:I,columnStyle:l,column:R,row:D,lastRow:k(I,D),bodyHeight:u,sortRow:N(I,D,R),hasSplit:b},I.id):i.jsx(Ej,{cell:I,columnStyle:l,column:S(I.id),row:D},I.id)})},D))})}function Dj({overlay:t}){const n=d.useContext(Ds);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 Ij(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=go(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 Lj({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(j=>j.id===u),[y,u]),D=d.useRef(null),I=d.useRef(null),R=d.useCallback(j=>{D.current=j.navigate,I.current=j.keydown,D.current(A)},[A,D]),_=d.useCallback(j=>{const Q=j?.target?.value??"";g(Q);const $=Q?(t?.options||[]).filter(G=>(G.label||"").toLowerCase().includes(Q.toLowerCase())):t?.options||[];w($),$.length?D.current(-1/0):D.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 j=go(B.current,()=>F.current(!0));return()=>j.destroy()},[]),d.useEffect(()=>{f(t?.value),g(t?.renderedValue),w(t?.options||[])},[t]);const H=d.useCallback(({id:j})=>{o(j),r()},[o,r]);return i.jsxs(i.Fragment,{children:[i.jsx("input",{className:"wx-0UYfSd1x wx-input",ref:B,value:h??"",onChange:_,onKeyDown:j=>I.current?I.current(j,A):void 0}),i.jsx(fh,{items:y,onReady:R,onSelect:H,...N,onCancel:l,children:({option:j})=>b?b(j):S?i.jsx(S,{data:j,onAction:n}):j.label})]})}function Pj({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=go(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(oS,{value:u,onChange:w,buttons:t.config?.buttons})})})]})}function _j(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,D]=d.useState();function I(_){N=_.navigate,D(()=>_.keydown),N(S)}const R=d.useRef(null);return d.useEffect(()=>{R.current&&R.current.focus(),typeof window<"u"&&window.getSelection&&window.getSelection().removeAllRanges()},[]),d.useEffect(()=>{if(!R.current)return;const _=go(R.current,()=>o(!0));return()=>_.destroy()},[o]),i.jsxs(i.Fragment,{children:[i.jsx("div",{ref:R,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 Fj(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=go(b.current,()=>o(!0));return()=>S.destroy()},[o]),i.jsx("div",{ref:b,className:"wx-value wx-aacZ4gNU",onClick:()=>o(!0),children:i.jsx(TS,{value:h,options:f,text:g,template:u.template,cell:u.cell,clear:u.clear,dropdown:y,autoOpen:!0,onChange:w,onAction:r})})}const Oj={text:Ij,combo:Lj,datepicker:Pj,richselect:_j,multiselect:Fj};function Bj({column:t,row:n}){const r=d.useContext(Ds),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 Oj[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 Vw(t){const{columns:n,type:r,columnStyle:o}=t,l=d.useContext(Ds),{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:mS(SS(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:UR(u,f,b)}):i.jsx("div",{className:"wx-Gy81xq2u wx-text",children:b.text??""})},b.id)})},w))})}function Hj(t){const{columns:n,rowStyle:r,columnStyle:o,cellStyle:l,header:u,footer:f,reorder:h}=t,g=d.useContext(Ds),{flatData:y,_sizes:w}=g.getState(),b=u&&Hw(n,"header",w.headerRowHeights),S=f&&Hw(n,"footer",w.footerRowHeights);function k(A,D){let I="";return I+=o?" "+o(D):"",I+=l?" "+l(A,D):"",I}function N(A,D){return typeof D.draggable=="function"?D.draggable(A,D)!==!1:D.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(Vw,{columns:b,type:"header",columnStyle:o})}):null,i.jsx("tbody",{children:y.map((A,D)=>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:mS(SS(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 R=I.cell;return i.jsx(R,{api:g,row:A,column:I})})():i.jsx("span",{children:tc(A,I)})]},I.id))},D))}),f?i.jsx("tfoot",{children:i.jsx(Vw,{columns:S,type:"footer",columnStyle:o})}):null]})}function zj(t){const{config:n,...r}=t,o=d.useContext(Ds),{_skin:l,_columns:u}=o.getState(),f=d.useMemo(()=>BR(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(Hj,{columns:g,...r})},y))})}function $j(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(Ds),D=Ot(A,"dynamic"),I=Ot(A,"_columns"),R=Ot(A,"flatData"),_=Ot(A,"split"),B=Ot(A,"_sizes"),[F,H]=Xs(A,"selectedRows"),j=Ot(A,"select"),Q=Ot(A,"editor"),$=Ot(A,"scrollLeft"),G=Ot(A,"scrollTop"),W=Ot(A,"tree"),V=Ot(A,"focusCell"),X=Ot(A,"_print"),ve=Ot(A,"undo"),J=Ot(A,"reorder"),z=Ot(A,"_rowHeightFromData"),[P,re]=d.useState(0);d.useEffect(()=>{re(va())},[]);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),[Ke,ue]=d.useState(null),Fe=d.useMemo(()=>{let oe=[],Ue=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=Ue,Ue+=tt.width}),oe.length&&(oe[oe.length-1].fixed.left=-1)),{columns:oe,width:Ue}},[_,I]),Xe=d.useMemo(()=>{let oe=[],Ue=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=Ue,Ue+=Pt.width}oe.length&&(oe[0].fixed={right:-1})}return{columns:oe,width:Ue}},[_,I]),at=d.useMemo(()=>{const oe=(I||[]).slice(_?.left||0,(I||[]).length-(_?.right??0)).filter(Ue=>!Ue.hidden);return oe.forEach(Ue=>{Ue.fixed=0}),oe},[I,_]),Ee=d.useMemo(()=>(I||[]).reduce((oe,Ue)=>(Ue.hidden||(oe+=Ue.width),oe),0),[I]),Ge=1;function me(oe,Ue,tt){let Pt=Ue,wn=oe;if(at.length){let Be=at.length;for(let it=oe;it>=0;it--)at[it][tt].forEach(Tt=>{Tt.colspan>1&&it>oe-Tt.colspan&&it<Be&&(Be=it)});if(Be!==at.length&&Be<oe){for(let it=Be;it<oe;it++)Pt-=at[it].width;wn=Be}}return{index:wn,delta:Pt}}const ke=d.useMemo(()=>{let oe,Ue,tt;const Pt=$||0,wn=($||0)+(b||0);let Be=0,it=0,Tt=0,bt=0;at.forEach((Ht,Pn)=>{Pt>Tt&&(Be=Pn,bt=Tt),Tt=Tt+Ht.width,wn>Tt&&(it=Pn+Ge)});const Gt={header:0,footer:0};for(let Ht=it;Ht>=Be;Ht--)["header","footer"].forEach(Pn=>{at[Ht]&&at[Ht][Pn].forEach(Ba=>{const ar=Ba.colspan;if(ar&&ar>1){const Nr=ar-(it-Ht+1);Nr>0&&(Gt[Pn]=Math.max(Gt[Pn],Nr))}})});const ra=me(Be,bt,"header"),Cn=me(Be,bt,"footer"),Un=ra.delta,Qt=ra.index,En=Cn.delta,zr=Cn.index;return Se&&Ee>(b||0)?oe=Ue=tt=[...Fe.columns,...at,...Xe.columns]:(oe=[...Fe.columns,...at.slice(Be,it+1),...Xe.columns],Ue=[...Fe.columns,...at.slice(Qt,it+Gt.header+1),...Xe.columns],tt=[...Fe.columns,...at.slice(zr,it+Gt.footer+1),...Xe.columns]),{data:oe||[],header:Ue||[],footer:tt||[],d:bt,df:En,dh:Un}},[at,Fe,Xe,$,b,Se,Ee]),Je=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)-Je-Me-(pe?P:0),[S,Je,Me,pe,P]),jt=d.useMemo(()=>Math.ceil((st||0)/(ae||1))+1,[st,ae]),O=d.useRef([]),[$e,We]=d.useState(0),[Et,lt]=d.useState(void 0),ht=d.useMemo(()=>{let oe=0,Ue=0;const tt=2,Pt=G||0;if(y){let it=Pt;for(;it>0;)it-=O.current[oe]||ae,oe++;Ue=Pt-it;for(let Tt=Math.max(0,oe-tt-1);Tt<oe;Tt++)Ue-=O.current[oe-Tt]||ae;oe=Math.max(0,oe-tt)}else{if(z){let it=0,Tt=0;for(let Cn=0;Cn<(R||[]).length;Cn++){const Un=R[Cn].rowHeight||ae;if(Tt+Un>Pt){it=Cn;break}Tt+=Un}oe=Math.max(0,it-tt);for(let Cn=0;Cn<oe;Cn++)Ue+=R[Cn].rowHeight||ae;let bt=0,Gt=0;for(let Cn=it+1;Cn<(R||[]).length;Cn++){const Un=R[Cn].rowHeight||ae;if(bt++,Gt+Un>st)break;Gt+=Un}const ra=Math.min(D?D.rowCount:(R||[]).length,it+bt+tt);return{d:Ue,start:oe,end:ra}}oe=Math.floor(Pt/(ae||1)),oe=Math.max(0,oe-tt),Ue=oe*(ae||0)}const wn=D?D.rowCount:(R||[]).length,Be=Math.min(wn,oe+(jt||0)+tt);return{d:Ue,start:oe,end:Be}},[y,z,G,ae,D,R,jt,st]),Ze=d.useMemo(()=>{const oe=D?D.rowCount:(R||[]).length;if(y)return $e+ht.d+(oe-(Et||0))*(ae||0);if(!z)return oe*(ae||0);let Ue=0;for(let tt=0;tt<oe;tt++)Ue+=R[tt]?.rowHeight||ae;return Ue},[D,R,ae,y,z,$e,ht.d,Et]),be=d.useRef({});be.current={clientWidth:b,clientHeight:S,fullHeight:Ze,headerHeight:Je,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(D&&(te.current.start!==ht.start||te.current.end!==ht.end)){const{start:oe,end:Ue}=ht;te.current={start:oe,end:Ue},A&&A.exec&&A.exec("request-data",{row:{start:oe,end:Ue}})}},[D,ht,A]);const ce=d.useMemo(()=>D?R||[]:(R||[]).slice(ht.start,ht.end),[D,R,ht]),Ne=d.useMemo(()=>(F||[]).filter(oe=>(ce||[]).some(Ue=>Ue.id===oe)),[H,ce]),He=d.useMemo(()=>ht.start,[ht.start]),Ie=d.useRef({top:G,left:$});Ie.current={top:G,left:$};const Lt=d.useCallback(oe=>{const Ue=oe.target.scrollTop,tt=oe.target.scrollLeft,Pt=Ie.current;(Ue!==Pt.top||tt!==Pt.left)&&A.exec("scroll-to",{top:Ue,left:tt})},[A]),Ye=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,Ue)=>{const tt={id:oe,column:im(Ue,"data-col-id")};A.exec("open-editor",tt)},click:(oe,Ue)=>{if(Ue.target.closest("input")||yt.current)return;const tt=im(Ue,"data-col-id");if(V?.id!==oe&&A.exec("focus-cell",{row:oe,column:tt,eventSource:"click"}),j===!1)return;const Pt=l&&(Ue.ctrlKey||Ue.metaKey),wn=l&&Ue.shiftKey;(Pt||F.length>1||!F.includes(oe))&&A.exec("select-row",{id:oe,toggle:Pt,range:wn})},"toggle-row":oe=>{const Ue=A.getRow(oe);A.exec(Ue.open!==!1?"close-row":"open-row",{id:oe})},"ignore-click":()=>!1}),Vt=d.useMemo(()=>({top:Je,bottom:Me,left:Fe.width,xScroll:pe,yScroll:qe,sense:y&&Ke?Ke.offsetHeight:Math.max(B?.rowHeight||0,40),node:ye.current&&ye.current.firstElementChild}),[Je,Me,Fe.width,pe,qe,y,Ke,B]);function Ct(oe,Ue){const{container:tt,sourceNode:Pt,from:wn}=Ue;if(ut()&&!Pt.getAttribute("draggable-data"))return!1;de(wn),W&&A.getRow(wn).open&&A.exec("close-row",{id:wn,nested:!0});const Be=Dd(Pt),it=Be.cloneNode(!0);it.classList.remove("wx-selected"),it.querySelectorAll("[tabindex]").forEach(ra=>ra.setAttribute("tabindex","-1")),tt.appendChild(it),ue(it);const Tt=($||0)-ke.d,bt=qe?P:0;tt.style.width=Math.min((b||0)-bt,Se&&Ee<=(b||0)?Ae:Ae-bt)+Tt+"px";const Gt=_p(Be);Ue.offset={x:Tt,y:-Math.round(Gt.height/2)},_t.current||(_t.current=oe.clientY)}function mn(oe,Ue){const{from:tt}=Ue,Pt=Ue.pos,wn=_p(ye.current);Pt.x=wn.x;const Be=Vt.top;if(Pt.y<Be)Pt.y=Be;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(Ue.targetNode)){const it=Dd(Ue.targetNode),Tt=it&&uh(it);if(Tt&&Tt!==tt){Ue.to=Tt;const bt=y?Ke?.offsetHeight:B?.rowHeight;if(Ke&&((G||0)===0||Pt.y>Be+bt-1)){const Gt=it.getBoundingClientRect(),ra=_p(Ke).y,Cn=Gt.y,Un=ra>Cn?-1:1,Qt=Un===1?"after":"before",En=A.getState().flatData,zr=Math.abs(En.findIndex(Pn=>Pn.id===tt)-En.findIndex(Pn=>Pn.id===Tt)),Ht=zr!==1?Qt==="before"?"after":"before":Qt;if(zr===1&&(Un===-1&&oe.clientY>_t.current||Un===1&&oe.clientY<_t.current))return;_t.current=oe.clientY,A.exec("move-item",{id:tt,target:Tt,mode:Ht,inProgress:!0})}}u&&u({event:oe,context:Ue})}yj(oe,wn,Ue,Vt)}function an(oe,Ue){const{from:tt,to:Pt}=Ue;A.exec("move-item",{id:tt,target:Pt,inProgress:!1}),yt.current=setTimeout(()=>{yt.current=0},1),de(null),ue(null),_t.current=null,MS(Ue)}function va(){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 Ue=oe.offsetWidth-oe.clientWidth;return document.body.removeChild(oe),Ue}const kt=d.useMemo(()=>fe>0?{width:`${fe}px`}:void 0,[fe]),hn=d.useRef(null);function en(){Promise.resolve().then(()=>{let oe=0,Ue=He;const tt=hn.current;tt&&(Array.from(tt.children).forEach((Pt,wn)=>{O.current[He+wn]=Pt.offsetHeight,oe+=Pt.offsetHeight,Ue++}),We(oe),lt(Ue))})}d.useEffect(()=>{ce&&y&&en()},[ce,y,He]);let[q,nt]=d.useState();d.useEffect(()=>{if(V&&(!j||!Ne.length||Ne.includes(V.row)))nt({...V});else if(ce.length&&ke.data.length){if(!q||Ne.length&&!Ne.includes(q.row)||ce.findIndex(oe=>oe.id===q.row)===-1||ke.data.findIndex(oe=>oe.id===q.column&&!oe.collapsed)===-1){const oe=Ne[0]||ce[0].id,Ue=ke.data.findIndex(tt=>!tt.collapsed);nt(Ue!==-1?{row:oe,column:ke.data[Ue].id}:null)}}else nt(null)},[V]);const Dt=d.useRef(null);d.useEffect(()=>{const oe=ye.current;if(!oe)return;const Ue=mj(oe,w);return()=>{typeof Ue=="function"&&Ue()}},[w]);const gn=d.useRef({});Object.assign(gn.current,{start:Ct,move:mn,end:an,getReorder:()=>J,getDraggableInfo:()=>({hasDraggable:ut()})}),d.useEffect(()=>{const oe=ye.current;return oe?hj(oe,gn).destroy:void 0},[J,ye.current]),d.useEffect(()=>{const oe=ye.current;return oe?dj(oe,{keys:N!==!1&&{...uj,"ctrl+z":ve,"ctrl+y":ve,...N},exec:Ue=>A.exec("hotkey",Ue)}).destroy:void 0},[A,ve,N]);const Mr=d.useRef({scroll:A.getReactiveState().scroll,scrollLeft:A.getReactiveState().scrollLeft,scrollTop:A.getReactiveState().scrollTop});Mr.current.getWidth=()=>(b||0)-(qe?P:0),Mr.current.getHeight=()=>st,Mr.current.getScrollMargin=()=>Fe.width+Xe.width,d.useEffect(()=>{fj(Dt.current,Mr.current)},[]);const Hr=d.useRef(null);d.useEffect(()=>{const oe=Hr.current;if(!oe)return;const Ue=[];Ue.push(go(oe,()=>V&&A.exec("focus-cell",{eventSource:"click"})).destroy),Ue.push(hR(oe,mt.current)),Z(oe.clientHeight);const tt=new ResizeObserver(()=>{Z(oe.clientHeight)});return tt.observe(oe),Ue.push(()=>tt.disconnect()),()=>Ue.forEach(Pt=>Pt())},[]);const Ar=`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 "+Ar,style:{"--header-height":`${Je}px`,"--footer-height":`${Me}px`,"--split-left-width":`${Fe.width}px`,"--split-right-width":`${Xe.width}px`},children:i.jsx("div",{ref:ye,className:"wx-4VuBwK2D wx-table-box",style:kt,role:W?"treegrid":"grid","aria-colcount":ke.data.length,"aria-rowcount":ce.length,"aria-multiselectable":W&&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(Gw,{contentWidth:Ae,deltaLeft:ke.dh,columns:ke.header,columnStyle:h,bodyHeight:st-+r})}):null,i.jsxs("div",{ref:Hr,className:"wx-4VuBwK2D wx-body",style:{width:`${Ae}px`,height:`${Ze}px`},onMouseDown:oe=>Ye(oe),children:[o?i.jsx(Dj,{overlay:o}):null,i.jsx("div",{ref:hn,className:"wx-4VuBwK2D wx-data",style:{paddingTop:`${ht.d}px`,paddingLeft:`${ke.d}px`},children:ce.map((oe,Ue)=>{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":""),Be=y?{minHeight:`${oe.rowHeight||ae}px`}:{height:`${oe.rowHeight||ae}px`};return i.jsx("div",{className:"wx-4VuBwK2D "+wn,"data-id":_a(oe.id),"data-context-id":_a(oe.id),style:Be,role:"row","aria-rowindex":Ue,"aria-expanded":oe.open,"aria-level":W?oe.$level+1:void 0,"aria-selected":W?tt:void 0,tabIndex:-1,children:ke.data.map(it=>it.collapsed?i.jsx("div",{className:"wx-4VuBwK2D wx-cell wx-collapsed"},it.id):Q?.id===oe.id&&Q.column===it.id?i.jsx(Bj,{row:oe,column:it},it.id):i.jsx(Cj,{row:oe,column:it,columnStyle:h,cellStyle:g,reorder:J,focusable:q?.row===oe.id&&q?.column===it.id},it.id))},oe.id)})})]}),r&&(R||[]).length?i.jsx(Gw,{type:"footer",contentWidth:Ae,deltaLeft:ke.df,columns:ke.footer,columnStyle:h}):null]})})}),X?i.jsx(zj,{config:X,rowStyle:f,columnStyle:h,cellStyle:g,header:n,footer:r,reorder:J}):null]})}const Uj=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join(""),qj=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:D,tree:I=!1,autoConfig:R=!1,init:_=null,responsive:B=null,sortMarks:F,undo:H=!1,hotkeys:j=null,filterValues:Q,...$},G){const W=d.useRef();W.current=$;const V=d.useMemo(()=>new rj(pS),[]),X=d.useMemo(()=>V.in,[V]),ve=d.useRef(null);ve.current===null&&(ve.current=new lS((Xe,at)=>{const Ee="on"+Uj(Xe);W.current&&W.current[Ee]&&W.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:Xe=>(ve.current=ve.current.setNext(Xe),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]),[z,P]=d.useState(0),[re,we]=d.useState(0),[Z,Se]=d.useState(null),[ae,ye]=d.useState(null),Pe=d.useMemo(()=>{if(R&&!n.length&&t.length){const Xe=t[0],at=[];for(let Ee in Xe)if(Ee!=="id"&&Ee[0]!=="$"){let Ge={id:Ee,header:Ee[0].toUpperCase()+Ee.slice(1)};typeof R=="object"&&(Ge={...Ge,...R}),at.push(Ge)}return at}return(ae&&ae.columns)??n},[R,n,t,ae]),de=d.useMemo(()=>(ae&&ae.sizes)??A,[ae,A]),Ke=d.useCallback(Xe=>{if(P(Xe.width),we(Xe.height),B){const at=Object.keys(B).map(Number).sort((Ee,Ge)=>Ee-Ge).find(Ee=>Xe.width<=Ee)??null;at!==Z&&(ye(B[at]),Se(at))}},[B,Z]),ue=d.useContext(Oa.theme),Fe=d.useRef(0);return d.useEffect(()=>{if(!Fe.current)_&&_(J);else{const Xe=V.getState();V.init({data:t,columns:Pe,split:D||Xe.split,sizes:de||Xe.sizes,selectedRows:u||Xe.selectedRows,dynamic:w,tree:I,sortMarks:F||Xe.sortMarks,filterValues:Q||Xe.filterValues,undo:H,reorder:S,_skin:ue,_select:f})}Fe.current++},[V,t,Pe,D,de,u,w,I,F,Q,H,S,ue,f,_,J]),Fe.current===0&&V.init({data:t,columns:Pe,split:D||{left:0},sizes:de||{},selectedRows:u||[],dynamic:w,tree:I,sortMarks:F||{},filterValues:Q||{},undo:H,reorder:S,_skin:ue,select:f}),d.useImperativeHandle(G,()=>({...J}),[J]),i.jsx(Ds.Provider,{value:J,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx($j,{header:g,footer:y,overlay:b,rowStyle:r,columnStyle:o,cellStyle:l,onReorder:k,multiselect:h,autoRowHeight:N,clientWidth:z,clientHeight:re,responsiveLevel:Z,resize:Ke,hotkeys:j})})})});Bv(ls);const Fa=d.createContext(null),Yv=d.createContext(null),Xv=d.createContext(null);function Wj({children:t}){const n=d.useContext(Oa.i18n),r=d.useMemo(()=>n.getGroup("filemanager"),[n]),o=d.useContext(Fa),[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,D]=d.useState(!1);function I(){const F=b.trim();if(!F){D(!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}),R()}function R(){g(null),D(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(WT,{children:t}),h?i.jsx(gv,{title:r(`Enter ${h.item.type} name`),onConfirm:I,onCancel:R,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 Kw={"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 Gj(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 Vj({item:t}){const n=d.useContext(Fa),r=d.useContext(Oa.i18n).getGroup("filemanager"),o=d.useContext(Fa).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(()=>Gj(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":_a("/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":_a(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":_a(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":_a(t.id),className:"wx-GAOa4kDV wx-more",children:i.jsx("i",{className:"wx-GAOa4kDV wxi-dots-v"})})]})]})})}function RS(){const t=d.useContext(Fa),n=d.useContext(Oa.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((R,_)=>{const B=_&&(_.ctrlKey||_.metaKey),F=_&&_.shiftKey;if(R==="/wx-filemanager-parent-link"){if(h.length&&(B||F))return;t.exec("select-file",{type:"navigation"});return}let H=R==="body"&&_?null:R;const j=_.target.className.indexOf("wx-more")!==-1||_.target.className.indexOf("wxi-dots-v")!==-1;setTimeout(()=>{t.exec("select-file",{id:H,toggle:B&&!j,range:F&&!j,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(R=>{if(R==="/wx-filemanager-parent-link")return S();u==="search"&&t.exec("filter-files",{text:""});const _=f.find(B=>B.id===R);_&&(_.type=="folder"?t.exec("set-path",{id:_.id,panel:l}):t.exec("open-file",{id:_.id}))},[t,S,u,f,l]),N=d.useCallback((R,_)=>{(!h?.length||!h.filter(B=>B?.id===R).length>0)&&b(R,_)},[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]),D=d.useRef(null),I=d.useRef();return d.useEffect(()=>{D.current&&(I.current?(I.current.click=b,I.current._dblclick=k,I.current.context=N):(I.current={click:b,dblclick:R=>I.current._dblclick(R),_dblclick:k,context:N},Id(D.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":_a("body"),ref:D,children:A.map(R=>i.jsx(Vj,{item:R},R.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 Kj(){const t=d.useContext(Oa.i18n).getGroup("filemanager"),n=d.useContext(Fa),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(RS,{})]})}function jg({narrowMode:t,extraInfo:n}){const r=d.useContext(Fa),{preview:o,icon:l}=r.templates,u=d.useContext(Oa.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Ad("%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 j=g&&w!=null&&g[w]?._selected?.length||0;return S&&!j},[S,y,w]),N=d.useMemo(()=>{const j=g&&w!=null?g[w]:null;return j?k?j._files:j._selected:[]},[k,y,w]),A=d.useCallback((j,Q)=>(j?`${j} ${f(j>1?"folders":"folder")} `:"")+(Q?`${Q} ${f(Q>1?"files":"file")}`:""),[f]),D=d.useCallback(()=>{r.exec("show-preview",{mode:!b})},[r,b]),I=d.useCallback(j=>j.type==="folder"?f("Folder"):j.ext||f("Unknown file"),[f]),R=d.useMemo(()=>{let j,Q,$,G,W,V,X,ve;if(N.length===1&&!k){Q=N[0],j=Q.name;const J=o(Q,400,500);J?($=J,G=""):(G=l(Q,"big"),$=""),W=Q.type!=="folder"}else{if(Q=W=null,j="",N.length){let J=0,z=0,P=0,re=[],we;N.forEach(Se=>{typeof Se.size>"u"&&(we=!0,J=void 0),we||(J+=Se.size),re.push(I(Se)),Se.type==="folder"?z++:P++});const Z=new Set(re);V=Z.size>1?f("multiple"):[...Z][0],X=A(z,P),ve=J,k||(j=f("Multiple files"))}G=l({type:k?"search":N.length?"multiple":"none"},"big"),$=""}return{name:j,item:Q,previewSrc:$,iconSrc:G,showDownloadIcon:W,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 j=>{if(!n||!j)return null;try{return await n(j)}catch(Q){return console.log(Q),null}},[n]),[F,H]=d.useState(null);return d.useEffect(()=>{let j=!1;return H(null),Promise.resolve(B(R.item)).then(Q=>{j||H(Q)}).catch(()=>{j||H(null)}),()=>{j=!0}},[B,R.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:R.name}),i.jsxs("div",{className:"wx-O0BTtRrH wx-icons",children:[R.showDownloadIcon?i.jsx(iu,{name:"download",onClick:_}):null,t?i.jsx(iu,{name:"close",onClick:D}):null]})]}),R.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:R.previewSrc,alt:f("A miniature file preview")})}):R.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:R.iconSrc,alt:f("A miniature file preview")})}):i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:R.item?i.jsx("i",{className:`wx-O0BTtRrH wx-icon wxi-${R.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:[R.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(R.item)}),typeof R.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:om(R.item.size)})]}):null,i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Date")}),i.jsxs("span",{className:"wx-O0BTtRrH wx-value",children:[h(R.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:R.totalCount}),i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:f("Type")}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:R.type}),typeof R.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:om(R.totalSize)})]}):null]}),F?Object.entries(F).map(([j,Q])=>i.jsxs(Cv.Fragment,{children:[i.jsx("span",{className:"wx-O0BTtRrH wx-name",children:j}),i.jsx("span",{className:"wx-O0BTtRrH wx-value",children:Q})]},j)):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:R.name}),i.jsx("div",{className:"wx-O0BTtRrH wx-icons",children:t?i.jsx(iu,{name:"close",onClick:D}):null})]}),i.jsx("div",{className:"wx-O0BTtRrH wx-no-info-wrapper",children:i.jsxs("div",{className:"wx-O0BTtRrH wx-no-info",children:[R.previewSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-img-wrapper",children:i.jsx("img",{src:R.previewSrc,alt:f("A miniature file preview")})}):R.iconSrc?i.jsx("div",{className:"wx-O0BTtRrH wx-icon-wrapper",children:i.jsx("img",{src:R.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 jS({panel:t}){const n=d.useContext(Fa),r=d.useContext(Oa.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},Id(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":_a(N.id),"data-menu-ignore":"true",children:N.id=="/"?o(N.name):N.name})]},A))]})}function Qj({row:t}){const n=d.useContext(Oa.i18n),[r]=d.useState(()=>n.getGroup("filemanager")),o=d.useContext(Fa).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 ES({children:t}){const n=d.useContext(Fa),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=ZN(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(Fa),u=d.useContext(Oa.i18n),f=d.useMemo(()=>u.getGroup("filemanager"),[u]),h=d.useMemo(()=>Ad("%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:Qj},{id:"size",header:f("Size"),width:100,sort:!0,resize:!0,template:V=>typeof V=="number"?om(V):""},{id:"date",header:f("Date"),width:120,sort:!0,resize:!0,template:V=>V?h(V):""}],[f,h]),D=d.useRef(null),I=d.useRef(null),R=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 z=V==="body"&&X?null:V;!D.current&&!I.current?l.exec("select-file",{id:z,toggle:ve,range:J,panel:t}):(D.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 j(V){V.intercept("sort-rows",X=>(D.current=!0,H(X),!1)),V.intercept("select-row",()=>!1),V.on("resize-column",()=>I.current=!0),V.intercept("hotkey",()=>!1)}const Q=d.useMemo(()=>w!=="/"?[{id:"/wx-filemanager-parent-link",name:f("Back to parent folder")},...N]:N,[w,N,f]),$=d.useMemo(()=>{if(Q&&S&&S[w]){const{key:V,order:X}=S[w];return{[V]:{order:X}}}},[Q,S,w]),G=d.useRef(null),W=d.useRef();return d.useEffect(()=>{W.current?(W.current.click=_,W.current._dblclick=F):(W.current={click:_,dblclick:V=>W.current._dblclick(V),_dblclick:F},Id(G.current,W.current))},[_,F]),i.jsxs("div",{onClick:r,onContextMenu:o,className:"wx-SSaVhET7 wx-wrapper",children:[i.jsx(jS,{panel:t}),i.jsx("div",{"data-id":_a("body"),className:`wx-SSaVhET7 wx-list ${n?"wx-active":""}`,ref:G,children:i.jsx(ES,{children:i.jsx(qj,{init:j,data:Q,columns:A,selectedRows:R,columnStyle:()=>"wx-SSaVhET7 wx-each-cell",sizes:{rowHeight:42,headerHeight:42},sortMarks:$})})})]})}function Yj(){const t=d.useContext(Fa),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":_a("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 DS({folderIcon:t=!1,folder:n={}}){const r=d.useContext(Fa),[o,l]=Xs(r,"panels"),u=Ot(r,"activePanel"),f=d.useMemo(()=>o[u].path,[l,u]),h=d.useContext(Oa.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":_a(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(DS,{folder:k},k.id):null)}):null]})}function Xj(){const t=d.useContext(Fa),[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},Id(b.current,S.current))},[g,h]),i.jsx("ul",{ref:b,className:"wx-LyHJ6R6A",children:y.map(k=>k.type==="folder"?i.jsx(DS,{folder:k},k.id):null)})}function Zj(){const t=d.useContext(Fa),n=d.useContext(Oa.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:[om(l)," ",r("of")," ",om(u)," ",r("used")]})]}):null}function Jj({option:t}){const n=d.useContext(Oa.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 eE({readonly:t,menuOptions:n}){const r=d.useContext(Oa.i18n).getGroup("filemanager"),{showPrompt:o}=d.useContext(Yv);d.useEffect(()=>{yR("upload",Jj)},[]);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(wR,{options:u,at:"bottom-fit",onClick:l,children:i.jsx(tm,{type:"primary block",children:r("Add New")})})}),i.jsx("div",{className:"wx-FlucfALM wx-tree",children:i.jsx(Xj,{})}),i.jsx(Zj,{})]})}function tE({value:t="",onSearch:n}){const[r,o]=fS(t),l=d.useContext(Oa.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 nE({narrowMode:t=!1,onShowTree:n}){const r=d.useContext(Fa),o=d.useContext(Oa.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":_a("toggle-tree"),children:i.jsx(iu,{onClick:()=>n&&n(),name:"subtask"})}):i.jsx("div",{className:"wx-5PZQQztG wx-name",children:o("Files")}),i.jsx(tE,{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(GT,{onClick:y,value:u,children:i.jsx("i",{className:"wx-5PZQQztG wxi-eye"})})}),i.jsx("div",{className:"wx-5PZQQztG wx-modes",children:i.jsx(HT,{value:l,options:h,onChange:g})})]})]})}function aE(){const t=d.useContext(Fa),n=Ot(t,"activePanel");return i.jsxs("div",{className:"wx-NwohNJzN wx-wrapper",children:[i.jsx(jS,{panel:n}),i.jsx(ES,{children:i.jsx(RS,{})})]})}function rE({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=bS(),S=d.useContext(Fa),{showPrompt:k,showConfirm:N}=d.useContext(Yv),A=d.useContext(Oa.i18n),D=d.useMemo(()=>A.getGroup("filemanager"),[A]),I=Ot(S,"mode"),R=Ot(S,"preview"),_=Ot(S,"activePanel"),[B,F]=Xs(S,"panels"),H=d.useMemo(()=>(B&&_!=null?B[_]:null)?.selected??[],[F,_]),j=d.useMemo(()=>(B&&_!=null?B[_]:null)?.path,[F,_]),[Q,$]=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 G=d.useCallback(()=>{w(Z=>!Z)},[]),W=d.useCallback(Z=>{h&&im(Z)!=="toggle-tree"&&w(!1)},[h]);d.useEffect(()=>{const Z=l.current;if(Z)return go(Z,W).destroy},[W]),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:j});break;case"rename":k({item:Se});break;case"delete":N({selected:ye});break;case"preview":S.exec("show-preview",{mode:!R});break}},[S,H,j,k,N,R]),z=d.useCallback(()=>B?.[_],[B,_]);d.useEffect(()=>{const Z=o.current;if(!Z)return;const Se=oR(Z,{api:S,menuOptions:t?X:n,performAction:J,getPanel:z});return()=>{typeof Se=="function"?Se():Se&&typeof Se.destroy=="function"&&Se.destroy()}},[S,t,X,n,J,z]);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=D(de.text)),de.hotkey&&(de.subtext=de.hotkey)}),$(Pe),ae||{}},[S,t,X,n,H,h,V,I,D]),re=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:j})}return i.jsx("div",{className:"wx-RJbNonjJ wx-filemanager wx-flex",ref:o,"data-menu-ignore":"false",children:h&&R?i.jsx("div",{className:"wx-RJbNonjJ wx-info-narrow",children:i.jsx(jg,{narrowMode:h,extraInfo:r})}):i.jsxs(i.Fragment,{children:[i.jsx(nE,{narrowMode:h,onShowTree:G}),i.jsx(xR,{dataKey:"id",at:"point",options:Q,resolver:P,onClick:re,children:i.jsxs(yS,{dataKey:"actionId",options:Q,resolver:P,onClick:re,children:[i.jsx(AR,{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(eE,{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${R?"":"-fit"}`,"data-id":_a("body"),children:I==="table"?i.jsx(bv,{panel:_}):i.jsx(aE,{})}),R?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${R?"":"-fit"}`,children:I==="panels"?i.jsx(Yj,{}):i.jsx(Kj,{})}),R?i.jsx("div",{className:"wx-RJbNonjJ wx-info",children:i.jsx(jg,{extraInfo:r})}):null]})})})]})})]})})}const sE=t=>t.split("-").map(n=>n?n.charAt(0).toUpperCase()+n.slice(1):"").join("");function iE(t,n){const{type:r,ext:o}=t;if(r==="folder")return!1;let l;return r&&r!=="file"&&Kw[r]?l=r:o?l=Kw[o]?o:"file":l="unknown",`https://cdn.svar.dev/icons/filemanager/vivid/${n}/${l}.svg`}const oE=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=rR,extraInfo:w=null,init:b=null,icons:S=iE,previews:k=null,...N}=t,A=d.useRef();A.current=N;const D=d.useMemo(()=>new aR(pS),[]),I=d.useMemo(()=>D.in,[D]),R=d.useRef(null);R.current===null&&(R.current=new lS((F,H)=>{const j="on"+sE(F);A.current&&A.current[j]&&A.current[j](H)}),I.setNext(R.current));const _=d.useMemo(()=>({getState:D.getState.bind(D),getReactiveState:D.getReactive.bind(D),getStores:()=>({data:D}),exec:I.exec,setNext:F=>(R.current=R.current.setNext(F),R.current),intercept:I.intercept.bind(I),on:I.on.bind(I),detach:I.detach.bind(I),getFile:D.getFile.bind(D),serialize:D.serialize.bind(D),templates:{preview:k||(()=>null),icon:S==="simple"?(()=>null):S}}),[D,I]),B=d.useRef(0);return d.useEffect(()=>{if(!B.current)b&&b(_);else{const F=D.getState();D.init({data:r,mode:o,drive:l,preview:u,panels:f||F.panels||[],activePanel:h})}B.current++},[D,r,o,l,u,f,h,b,_]),B.current===0&&D.init({data:r,mode:o,drive:l,preview:u,panels:f||[],activePanel:h}),d.useImperativeHandle(n,()=>({..._}),[_]),i.jsx(Fa.Provider,{value:_,children:i.jsx(Gv,{words:Vv,optional:!0,children:i.jsx(Wj,{children:i.jsx(rE,{readonly:g,menuOptions:y,extraInfo:w})})})})});function lE({fonts:t=!0,children:n}){return n?i.jsx(Iw,{fonts:t,children:n}):i.jsx(Iw,{fonts:t})}Bv(ls);function Zv(t,n){if(!t||typeof t!="object"||Array.isArray(t))throw new Error(`Invalid Hub ${n} response.`);return t}function dm(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 cE(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 uE(t,n=!1){return dm(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:cE(r,"folder","filesystem entries"),entries:dm(r,"entries","filesystem entries")}}async function dE(t,n){return rt("/api/remote/filesystem/selection/scan",{method:"POST",body:JSON.stringify({itemIds:t})},n)}async function fE(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 mE(t,n=!1){const r=await rt(`/api/remote/files/jobs?active=${n?"1":"0"}`,void 0,t);return{jobs:dm(r,"jobs","file transfer jobs")}}async function pE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}`,void 0,n)}async function hE(t,n){return rt(`/api/remote/files/jobs/${encodeURIComponent(t)}/cancel`,{method:"POST"},n)}async function Qw(t){return dm(await rt("/api/remote/filesystem/shared-folders",void 0,t),"folders","shared folders")}async function gE(t,n){return rt("/api/remote/filesystem/shared-folders",{method:"POST",body:JSON.stringify({sourceId:t})},n)}async function vE(t,n,r){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)},r)}async function yE(t,n){return rt(`/api/remote/filesystem/shared-folders/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function bE(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:dm(l,"jobs","shared folder sync"),files:Number(u.files||0),totalBytes:Number(u.totalBytes||0)}}function wE(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 Yw(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 xE(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 SE(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 CE({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),[D,I]=d.useState(null),[R,_]=d.useState([]),[B,F]=d.useState([]),[H,j]=d.useState(0),[Q,$]=d.useState(null),[G,W]=d.useState(!1),[V,X]=d.useState(""),[ve,J]=d.useState(new Set),z=n.find(me=>me.id===D)||null,P=R[R.length-1]||null,re=z?P?.svarPath||`/${z.name}`:null,we=re;d.useEffect(()=>{N.current=R,S.current=we||"/"},[we,R]);const Z=d.useMemo(()=>(A.current.clear(),!z||!we||R.length===0?[]:(R.forEach(me=>A.current.set(me.svarPath,me.hubId)),[...R.map((me,ke)=>({id:me.svarPath,parent:ke===0?"/":R[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}})])),[z,B,we,R]),Se=me=>A.current.get(String(me))||String(me),ae=me=>wE({...me,id:Se(String(me.id)),parent:Se(String(me.parent))}),ye=async(me,ke)=>{const Je=me[me.length-1];if(!Je)return;const Me=++k.current;W(!0),X("");try{const pe=await Eg(Je.hubId,t);if(Me!==k.current)return;if(!Array.isArray(pe.entries))throw new Error("Invalid Hub filesystem entries response.");const qe={...Je,displayPath:pe.folder.displayPath||Je.displayPath,modifiedAt:pe.folder.modifiedAt||Je.modifiedAt},Re=[...me.slice(0,-1),qe];N.current=Re,_(Re),F(pe.entries),j(st=>st+1)}catch(pe){if(Me!==k.current)return;console.error("[LiveDesk FS] folder navigation failed",{folderId:Je.hubId,error:pe}),X(pe instanceof Error?`${ke}: ${pe.message}`:`${ke}: Unable to read this folder.`)}finally{Me===k.current&&W(!1)}},Pe=async me=>{const ke={svarPath:`/${me.name}`,hubId:me.id,name:me.name,pathLabel:SE(me),displayPath:me.displayPath,modifiedAt:me.modifiedAt},Je=++k.current;I(me.id),N.current=[ke],_([ke]),S.current=ke.svarPath,F([]),X(""),W(!0),$(me.id),J(Me=>{const pe=new Set(Me);return pe.delete(me.id),pe});try{const Me=await Eg(me.id,t);if(Je!==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),j(qe=>qe+1)}catch(Me){if(Je!==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{Je===k.current&&($(null),W(!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)},Ke=(me,ke)=>{if(me.type!=="folder")return;const Je=N.current,Me=Je.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([...Je.slice(0,Me+1),pe],me.name)},ue=()=>de(N.current.length-2),Fe=me=>{if(me.key!=="Enter"&&me.code!=="Enter"&&me.code!=="NumpadEnter"||me.target?.closest('button, input, textarea, [contenteditable="true"]'))return;const Je=b.current;if(!Je)return;const Me=Je.getState().panels?.flatMap(qe=>qe.selected||[])||[];if(Me.length!==1)return;const pe=Je.getFile(String(Me[0]));pe?.type==="folder"&&(me.preventDefault(),me.stopPropagation(),Ke(ae(pe),String(pe.parent||S.current)))};d.useEffect(()=>{const me=n.find(ke=>ke.id===D)||xE(n);if(J(ke=>new Set([...ke].filter(Je=>n.some(Me=>Me.id===Je)))),!me){I(null),N.current=[],_([]),F([]);return}Pe(me)},[n]);const Xe=me=>{b.current=me,me.on("request-data",async({id:ke})=>{const Je=String(ke),Me=Se(Je);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=`${Je}/${Re.name}`;return A.current.set(st,Re.id),{id:st,parent:Je,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:Je,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 Je=String(ke),Me=N.current.findIndex(qe=>qe.svarPath===Je);if(Me>=0)return de(Me),!1;const pe=me.getFile(Je);if(pe?.type==="folder")return Ke(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 Je=ke?ae(ke):null,Me=()=>{const pe=Je?.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}]:Je?[{id:"share",text:"Share to Clients",icon:"mdi mdi-share-variant",handler:()=>g(Je)},...Je.type==="folder"?[{id:"sync",text:"Add folder to Sync",icon:"mdi mdi-folder-sync-outline",handler:()=>y(Je)}]:[],{id:"copy-path",text:"Copy path",icon:"mdi mdi-content-copy",handler:()=>{Dp(Je.displayPath||Je.name)}},{id:"refresh",text:"Refresh",icon:"mdi mdi-refresh",handler:Me},{id:"properties",text:"Properties",icon:"mdi mdi-information-outline",handler:()=>w(`${Je.name}
179
+ ${Je.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:yk,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(Kx,{size:16})}),i.jsx("button",{className:"icon-button",onClick:f,title:"Import folder from this browser",type:"button",children:i.jsx(bk,{size:16})}),i.jsx("button",{className:"icon-button",onClick:()=>{Ee()},title:"Refresh drives",type:"button",children:i.jsx(Rd,{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 Je=me.icon,Me=ve.has(ke.id)||ke.locked===!0;return i.jsxs("button",{className:`hub-drive-item ${D===ke.id?"active":""} ${Me?"unavailable":""}`,onClick:()=>{Pe(ke)},"aria-pressed":D===ke.id,type:"button",children:[i.jsx("span",{className:"hub-drive-item-icon",children:i.jsx(Je,{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:[Yw(ke.freeBytes||0)," free / ",Yw(ke.totalBytes||0)]})]}),Q===ke.id?i.jsx(is,{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:R.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===R.length-1?"current":""}`,onClick:()=>de(ke),title:me.displayPath||me.pathLabel,"data-hub-folder-id":me.hubId,"aria-current":ke===R.length-1?"location":void 0,type:"button",children:me.pathLabel})]},me.svarPath))}),i.jsxs("div",{className:"hub-file-explorer-navigation-actions",children:[G&&i.jsx(is,{className:"hub-file-explorer-loading-icon spin",size:15,"aria-label":"Loading folder"}),i.jsx("button",{className:"icon-button",onClick:ue,disabled:R.length<=1||G,title:"Back to parent folder",type:"button",children:i.jsx(zx,{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:Fe,children:i.jsx(lE,{fonts:!1,children:i.jsx(oE,{data:Z,panels:re?[{path:re,selected:[]}]:void 0,readonly:!0,mode:"table",preview:!1,init:Xe,icons:"simple",menuOptions:at},`${z?.id||"no-root"}:${H}`)})})]})]})]})}class kE 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(Rd,{size:15})," Retry"]})]}):this.props.children}}function ME(t){return t.deviceName||t.hostname||t.deviceId}function AE({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(rm,{size:14})," All connected"]}),i.jsxs("button",{className:n==="selected"?"active":"",onClick:()=>o("selected"),type:"button",children:[i.jsx(kr,{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(kr,{size:20,"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:ME(f)}),i.jsxs("small",{children:["Slot ",f.slotNumber?String(f.slotNumber).padStart(3,"0"):"-"," / ",f.platform||"unknown OS"]})]}),i.jsx(Pa,{size:17,"aria-hidden":"true"})]},f.deviceId)})})]})}function NE(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 TE({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(Yf,{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(Yf,{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(Yf,{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 / ",NE(y.totalBytes)," · ",y.lastSyncedAt?`Last sync ${c0(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(Rd,{size:14})," Sync now"]}),i.jsx("button",{className:"icon-button",onClick:()=>h(y),title:"Remove sync folder",type:"button",children:i.jsx(Qx,{size:15})})]},y.id))})]})}function RE(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(am,{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(AE,{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(kd,{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(am,{size:17})," Share selected"]}),i.jsxs("button",{className:"file-share-secondary-button",onClick:t.onAddSync,disabled:!t.canAddSync,type:"button",children:[i.jsx(kd,{size:16})," Add selected folder to Sync"]})]}):i.jsx(TE,{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 jE(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 Xw(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 Zw(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 EE({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 D=Array.isArray(n)?n:[],[I,R]=d.useState([]),[_,B]=d.useState(!0),[F,H]=d.useState(""),[j,Q]=d.useState([]),[$,G]=d.useState([]),[W,V]=d.useState(null),[X,ve]=d.useState(!1),[J,z]=d.useState([]),[P,re]=d.useState(!0),[we,Z]=d.useState(!1),[Se,ae]=d.useState("send"),[ye,Pe]=d.useState([]),de=d.useRef(new Set),Ke=d.useRef(!1),ue=d.useMemo(()=>f==="all"?D.map(O=>O.deviceId):h.filter(O=>D.some($e=>$e.deviceId===O)),[D,h,f]),Fe=ye.find(O=>!wv(O.state)),Xe=$.length===1&&$[0].type==="folder"?$[0]:null,at=$.length===0?"Select files or folders from the Hub explorer.":X?"Calculating selection size...":W?`${W.files} files, ${W.folders} folders · ${jE(W.totalBytes)}`:`${$.length} item${$.length===1?"":"s"} selected`,Ee=O=>{A({id:O.jobId,state:O.state,progress:Xw(O),message:Zw(O)})},Ge=d.useCallback(async()=>{const O=await uE(t,!0);return R(O),H(""),O},[t]),me=async()=>{if(!Ke.current){Ke.current=!0;try{const $e=(await mE(t,!0)).jobs||[],We=await Promise.all([...de.current].map(async ht=>{try{return await pE(ht,t)}catch{return null}})),Et=[...$e,...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{Ke.current=!1}}};d.useEffect(()=>{let O=!0;B(!0),H(""),Promise.all([Ge(),Qw(t).then(We=>{O&&z(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),re(!1))}),me();const $e=window.setInterval(()=>{me()},800);return()=>{O=!1,window.clearInterval($e)}},[t,Ge]),d.useEffect(()=>{if(j.length===0){V(null);return}let O=!1;return ve(!0),dE(j,t).then($e=>{O||V($e)}).catch($e=>{O||N($e instanceof Error?$e.message:"Unable to calculate selected size.")}).finally(()=>{O||ve(!1)}),()=>{O=!0}},[t,j.join("|")]);const ke=(O,$e)=>{Q(O),G($e)},Je=O=>{O.forEach($e=>de.current.add($e.jobId)),Pe($e=>[...new Map([...$e,...O].map(We=>[We.jobId,We])).values()]),O.forEach(Ee)},Me=async()=>{if(!r){N(o);return}if(j.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(Fe){N("A Hub transfer is already running.");return}try{const O=await fE(j,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 $e=O||Xe;if(!$e||$e.type!=="folder"){N("Select one folder to add it to Sync.");return}try{const We=await gE($e.id,t);z(Et=>[...Et.filter(lt=>lt.id!==We.folder.id),We.folder]),ae("sync"),N(`${$e.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),z($e=>$e.map(We=>We.id===O.id?{...We,status:"syncing"}:We));try{const $e=await bE(O.id,ue,l.trim(),t);Je($e.jobs||[]),N($e.jobs?.length?"Hub sync queued.":"No changed files to sync.");const We=await Qw(t);z(We)}catch($e){N($e instanceof Error?$e.message:"Unable to sync the Hub folder."),z(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 $e=await vE(O.id,{autoSync:!O.autoSync},t);z(We=>We.map(Et=>Et.id===O.id?$e.folder:Et))}catch($e){N($e instanceof Error?$e.message:"Unable to update auto sync.")}},jt=async O=>{try{await yE(O.id,t),z($e=>$e.filter(We=>We.id!==O.id))}catch($e){N($e instanceof Error?$e.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(kE,{onRetry:()=>window.location.reload(),children:[i.jsx(CE,{hubUrl:t,roots:I,loading:_,error:F,onRefreshRoots:Ge,onImportFiles:()=>w.current?.click(),onImportFolder:()=>b.current?.click(),onSelectionChange:ke,onShareItem:O=>{Q([O.id]),G([O]),ae("send")},onAddSyncFolder:O=>{Q([O.id]),G([O]),pe(O)},onNotice:N}),i.jsx(RE,{devices:D,targetMode:f,selectedTargetIds:h,onTargetModeChange:g,onTargetToggle:y,remoteDirectory:l,onRemoteDirectoryChange:u,selectedEntries:$,selectedSummary:at,canShare:r&&!Fe&&j.length>0&&ue.length>0&&!X,onShare:()=>{Me()},canAddSync:!!Xe,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()}})]})}),Fe&&i.jsx("footer",{className:"file-share-workspace-footer",children:i.jsxs("span",{children:[Zw(Fe)," · ",Xw(Fe),"% ",i.jsx("button",{className:"icon-button",onClick:()=>{hE(Fe.jobId,t).then(O=>{Pe($e=>$e.map(We=>We.jobId===O.jobId?O:We)),Ee(O)})},title:"Cancel transfer",type:"button",children:i.jsx(nr,{size:14})})]})})]})}const DE=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(wk,{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(is,{className:"spin",size:16}):i.jsx(am,{size:16}),h?"Running":"Run"]})]})}),IE=["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 LE(t){return t==="running"||t==="completed"||t==="failed"||t==="cancelled"?t:"queued"}function PE(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 _E(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function ss(t){return typeof t=="number"&&Number.isFinite(t)?t:null}function xp(t){const n=ss(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 Jw(t){const n=ss(t);return n===null?"":`${Math.round((n<=1?n:n/100)*100)}%`}function FE(t){return!t||/^(?:[\w .-]+ )?collected(?:\.)?$/i.test(t.trim())?"":t.trim()}function Jp(t,n){if(n.error)return n.error;const r=_E(n.data),o=FE(n.result||"");if(!r)return o||n.stage||n.status;if(t==="system.health"){const l=typeof r.machine=="string"?r.machine:"",u=Jw(r.cpuUsageRatio),f=ss(r.cores),h=xp(r.freeMemoryBytes),g=xp(r.totalMemoryBytes),y=ss(r.totalMemoryBytes)&&ss(r.freeMemoryBytes)!==null?`${Math.round(ss(r.freeMemoryBytes)/ss(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=ss(r.totalBytes)&&ss(r.freeBytes)!==null?`${Math.round(ss(r.freeBytes)/ss(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=Jw(r.usageRatio),f=ss(r.temperatureC)!==null?`${Math.round(ss(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=ss(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 ex(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 OE({state:t,operation:n}){const r=t.status==="completed"?al:t.status==="failed"||t.status==="cancelled"?nr:t.status==="running"?is:Yx,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 BE({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(_=>ex(t,_)),k=S.filter(_=>_.status==="completed").length,N=b.failed>0,A=S.length>0,D=n.filter(_=>y==="issues"?ex(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),R=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:PE(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"]})]}),R.length>0&&i.jsxs("div",{className:"agent-task-result-preview",title:R.join(" · "),children:[i.jsx("span",{children:"Result"}),R.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(xk,{size:14}):i.jsx(Xx,{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:D.length>0?D.map(_=>i.jsx(OE,{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(Sk,{size:14})," Cancel"]}),!f&&N&&l&&i.jsxs("button",{onClick:l,disabled:u,type:"button",children:[i.jsx(Vg,{size:14})," Retry failed"]})]})]})}function HE(t){try{return JSON.stringify(t,null,2).slice(0,6e3)}catch{return"{}"}}function zE({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:HE(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(nr,{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 $E(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 UE({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 D=A.currentTarget;S.current=D.scrollHeight-D.scrollTop-D.clientHeight<72},children:[l.filter(A=>A.status==="pending").map(A=>i.jsx(zE,{approval:A,busy:h===A.approvalId,onApprove:D=>u(A,D),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 D=A;return i.jsx(BE,{operation:D.operation,states:D.states,status:D.status,onCancel:()=>n(D.batchId,D.agentRunId),onRetry:()=>r(D.batchId),busy:o===D.batchId},D.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(is,{"aria-hidden":"true",size:15}),$E(g.stage)]}),i.jsx("p",{children:g.message})]})]})}const tx=["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 qE={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","문제해결","복구","장애"]},nx=["low","medium","high","critical"];function WE(t){return t.reduce((n,r)=>{const o=Xl[r].risk;return nx.indexOf(o)>nx.indexOf(n)?o:n},"low")}function GE(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([...qE[n],...u,...g])];return{id:t,category:n,title:r,prompt:o,description:h,requiredOperations:l,risk:f.risk||WE(l),targetSupport:f.targetSupport||"single-or-multiple",supportedPlatforms:f.supportedPlatforms||GE(l),keywords:y,recommended:f.recommended??!1,enabled:!0}}const IS=[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 VE(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 KE(t,n,r){const o=VE(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 QE(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 YE(t,n,r){const o=new Set(r);return t.filter(l=>l.connected&&(n==="all"||n==="auto"||o.has(l.deviceId)))}function XE(t,n){const r=QE(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 LS(t,n,r,o,l,u){const f=KE(t,l,u),h=YE(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=>XE(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 ZE(t,n,r,o,l,u){return t.filter(f=>f.enabled&&LS(f,n,r,o,l,u).available).length}const Ig="livedesk.agentPromptRecent",Lg="livedesk.agentPromptFavorites",JE={Recommended:ec,"Health & capacity":Jl,"Processes & services":Ak,"Files & configuration":Mk,"Software & automation":Vx,"Network & connectivity":kv,"Power & maintenance":ha,"Troubleshooting & recovery":kk};function ax(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 eD(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 tD(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 nD(t){return`permission-${t}`}function aD(t){return t==="low"?"Low risk":t==="medium"?"Medium risk":t==="high"?"High risk":"Critical risk"}function rD(t){return t==="windows"?"Windows":t==="macos"?"macOS":"Linux"}function sD({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(()=>ax(Ig)),[k,N]=d.useState(()=>ax(Lg)),[A,D]=d.useState(0),[I,R]=d.useState(""),_=d.useRef(null),B=d.useRef(null),F=d.useMemo(()=>IS.filter(J=>J.enabled),[]),H=d.useMemo(()=>new Map(F.map(J=>[J.id,LS(J,t,n,r,o,l)])),[l,t,o,r,n,F]),j=d.useMemo(()=>[...H.values()].filter(J=>J.available).length,[H]),Q=d.useMemo(()=>t.filter(J=>J.connected&&(n==="all"||n==="auto"||r.includes(J.deviceId))).length,[t,r,n]),$=d.useMemo(()=>{const J=F.filter(z=>tD(z,H.get(z.id),h));return y==="recent"?b.map(z=>J.find(P=>P.id===z)).filter(z=>!!z):y==="favorites"?k.map(z=>J.find(P=>P.id===z)).filter(z=>!!z):y==="all"?J:J.filter(z=>{const P=H.get(z.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:z.category===y})},[H,k,y,b,h,F]),G=d.useMemo(()=>y!=="all"?[{category:Pg(y),templates:$}]:tx.map(J=>({category:J,templates:$.filter(z=>z.category===J)})).filter(J=>J.templates.length>0),[y,$]);d.useEffect(()=>{D(J=>Math.min(J,Math.max(0,$.length-1)))},[$.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()},z=P=>{P.key==="Escape"&&(P.preventDefault(),f())};return document.addEventListener("pointerdown",J),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",J),document.removeEventListener("keydown",z)}},[f]);const W=J=>{const z=H.get(J.id);if(!z.available){R(z.reason||"This task is not available for the current targets and permission policy.");return}const P=[J.id,...b.filter(re=>re!==J.id)].slice(0,10);S(P),Sp(Ig,P),u(J.prompt),f()},V=J=>{N(z=>{const P=z.includes(J)?z.filter(re=>re!==J):[J,...z];return Sp(Lg,P),P})},X=J=>{J.key==="ArrowDown"?(J.preventDefault(),D(z=>Math.min(z+1,Math.max(0,$.length-1)))):J.key==="ArrowUp"?(J.preventDefault(),D(z=>Math.max(z-1,0))):J.key==="Enter"&&$[A]&&(J.preventDefault(),W($[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:[j," 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(nr,{size:16})})]}),i.jsxs("label",{className:"agents-suggested-search",children:[i.jsx(Ck,{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",...tx].map(J=>{const z=J==="recent"?Wx:J==="favorites"?Kg:J==="all"?ec:J==="available"?Pa:J==="unavailable"?Zx:J==="read-only"||J==="auto"||J==="approval"||J==="full-access"?ha:JE[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),D(0),R("")},children:[i.jsx(z,{size:12})," ",eD(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:[G.map(J=>i.jsxs("div",{className:"agents-suggested-group",children:[i.jsx("strong",{children:J.category}),J.templates.map(z=>{ve+=1;const P=ve===A,re=k.includes(z.id),we=H.get(z.id),Z=we.availableDeviceIds.length+we.unsupportedDeviceIds.length||Q,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:()=>W(z),children:[i.jsx("span",{children:z.title}),i.jsx("small",{className:"agents-suggested-description",children:z.description}),i.jsxs("span",{className:"agents-suggested-meta",children:[i.jsx("em",{children:z.category}),i.jsx("em",{className:nD(we.state),children:we.label}),i.jsx("em",{className:`risk-${z.risk}`,children:aD(z.risk)}),i.jsx("em",{children:z.supportedPlatforms.map(rD).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 ${re?"favorite":""}`,type:"button","aria-label":re?`Remove ${z.title} from favorites`:`Add ${z.title} to favorites`,"aria-pressed":re,onClick:()=>V(z.id),children:i.jsx(Kg,{size:14,fill:re?"currentColor":"none"})})]},z.id)})]},J.category)),$.length===0&&i.jsx("p",{className:"agents-suggested-empty",children:"No tasks match this search or current filter."})]})]})}function iD({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(rm,{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(rm,{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(Xx,{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(kr,{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 oD=800,rx=5e3;function lD(){return typeof document>"u"||document.visibilityState==="visible"}function cD(t){return typeof document>"u"?()=>{}:(document.addEventListener("visibilitychange",t),()=>document.removeEventListener("visibilitychange",t))}function sx({poll:t,onResult:n,onError:r,intervalMs:o=oD,isVisible:l=lD,subscribeVisibility:u=cD,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,D()},o))},D=()=>{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(j=>{w&&B===b&&!F.signal.aborted&&n?.(j)},j=>{w&&B===b&&!F.signal.aborted&&r?.(j)}).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(),D()},_=u(()=>{if(N(),!l()){b+=1,k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling paused while hidden."));return}D()});return D(),{refresh:I,stop(){w&&(w=!1,b+=1,N(),_?.(),k&&!k.signal.aborted&&k.abort(new Error("LiveDesk Agent polling owner closed.")))}}}async function uD(t,n){return rt("/api/settings/agent/run",{method:"POST",body:JSON.stringify(n)},t)}async function dD(t,n,r={}){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}`,r,t)}async function fD(t,n){return rt(`/api/settings/agent/runs/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function mD(t){return rt("/api/settings/agent/runs/cancel-all",{method:"POST",body:JSON.stringify({})},t)}async function pD(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 hD(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 gD(t,n,r){return rt(`/api/settings/agent/policies/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({categories:r})},t)}async function vD(t,n,r={}){return rt(`/api/remote/tasks/${encodeURIComponent(n)}`,r,t)}async function yD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/cancel`,{method:"POST",body:JSON.stringify({})},t)}async function bD(t,n){return rt(`/api/remote/tasks/${encodeURIComponent(n)}/retry`,{method:"POST",body:JSON.stringify({failedOnly:!0})},t)}function Hf(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:LE(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 wD(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 xD={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 SD(t){return t==="safe-auto"?"Safe Auto":t==="full-access"?"Full Access":t==="custom"?"Custom":"Ask"}function CD(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase())}function kD(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 ix({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([]),[D,I]=d.useState(""),[R,_]=d.useState(""),[B,F]=d.useState(""),[H,j]=d.useState("safe-auto"),[Q]=d.useState("custom-default"),[$,G]=d.useState(xD),[W,V]=d.useState([]),[X,ve]=d.useState(""),[J,z]=d.useState(!1),[P,re]=d.useState(null),[we,Z]=d.useState(!1),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(!1),[de,Ke]=d.useState(null),ue=d.useRef(null),Fe=d.useRef(null),Xe=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(()=>ZE(IS,n,f,g,H,$),[$,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:wD(Ne.states,te),status:fe.status}:Ne)),["running","queued"].includes(fe.status)||I(ce=>ce===fe.batchId?"":ce)},[n]),Je=d.useCallback((fe,te)=>{Ee.current.has(fe.batchId)||(Ee.current.add(fe.batchId),A(ce=>[...ce,{type:"task",id:Hf("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||[])Je(Ne,fe);V(te.approvals||[]);const ce=["running","queued","waiting-approval"].includes(te.status);if(Ke(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:Hf("agent-run-result"),text:He}])}},[Je]),pe=d.useCallback(async fe=>{const te=Fe.current;if(!(!te||te.id!==fe))try{return await te.owner.refresh()}catch(ce){if(Fe.current!==te)return;throw ce}},[]);d.useEffect(()=>{if(!R){Fe.current=null;return}const fe=R,te=sx({poll:Ne=>dD(t,fe,{signal:Ne,timeoutMs:rx}),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 Fe.current=ce,()=>{te.stop(),Fe.current===ce&&(Fe.current=null)}},[R,t,Me]),d.useEffect(()=>{if(!D){Xe.current=null;return}const fe=D,te=sx({poll:Ne=>vD(t,fe,{signal:Ne,timeoutMs:rx}),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 Xe.current=ce,()=>{te.stop(),Xe.current===ce&&(Xe.current=null)}},[D,t,ke]);const qe=async(fe="",te,ce=!1)=>{const Ne=(fe||S).trim();if(!Ne||D||R)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){re({instruction:Ne,targetIds:He});return}if(A(ut=>[...ut,{type:"user",id:Hf("user"),text:Ne}]),k(""),Pe(!1),ae(""),He.length===0){A(ut=>[...ut,{type:"error",id:Hf("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,Ye=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 hD(t,Q,$);if(!yt.ok)throw new Error(yt.error||"Custom Agent policy could not be saved.")}const ut=await cD(t,{instruction:Ye,deviceIds:He,permissionMode:H,customPolicyId:Q});if(!ut.ok||!ut.runId)throw new Error(ut.error||"Codex Agent run could not be started.");V(ut.approvals||[]),Ke({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:Hf("codex-run-error"),text:CD(ut)}])}},Re=async(fe,te)=>{ve(fe.approvalId);try{const ce=await mD(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 pD(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 dD(t,te);for(const He of Ne.taskBatches||[])ke(He);_(He=>He===te?"":He),Ke(He=>He?.runId===te?null:He);return}const ce=await vD(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||!D&&!R)){z(!0);try{const fe=await fD(t);if(!fe.ok)throw new Error(fe.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),_(""),Ke(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{z(!1)}}},$e=async fe=>{F(fe);try{const te=await yD(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`,Ze=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"&&lt.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:Ze})]}),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(rm,{size:12})," All"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(rm,{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(kr,{size:12}):null,fe[0].toUpperCase()+fe.slice(1)]},fe))})]}),i.jsxs("div",{className:"agents-workspace",children:[(D||R)&&i.jsxs("div",{className:"agents-page-status",children:[i.jsxs("span",{children:[Ge.length," Clients · ",xD(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:()=>re(null),children:"Cancel"}),i.jsx("button",{type:"button",className:"danger",onClick:()=>{const fe=P;re(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($E,{items:N,onCancel:jt,onRetry:$e,busyBatchId:B,approvals:W,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(rD,{devices:n,targetMode:f,selectedIds:g,permissionMode:H,customCategories:$,onSelectPrompt:We,onClose:()=>Pe(!1)}),i.jsx(EE,{ref:ue,value:S,onChange:k,onSubmit:()=>{qe()},onOpenSuggestedTasks:()=>Pe(fe=>!fe),suggestedOpen:ye,suggestedTaskCount:me,disabled:!!D||!!R,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(sD,{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=>{j(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:DE.map(fe=>i.jsxs("label",{children:[i.jsx("span",{children:SD(fe)}),i.jsxs("select",{value:$[fe],onChange:te=>G(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 PS(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function _S(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function FS(t,n,r){const o=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:PS(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 _S(l));return await l.json()}async function kD(t,n){return await rt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:PS(t.target)})},n)}async function MD(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 _S(l));return await l.json()}async function AD(t,n,r){return await rt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function ox(t,n){await rt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function ND(t){return await rt("/api/captures",void 0,t)}function lx(t,n){return`${lu(n)}/api/captures/${encodeURIComponent(t)}/content`}async function TD(t,n){return await rt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function RD({hubUrl:t,onToast:n}){const[r,o]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{o((await ND(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=lx(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(Rd,{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=lx(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(Nk,{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(Jx,{size:15})}),i.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&TD(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:i.jsx(Qx,{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 cx({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(Tk,{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(Yx,{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(Rk,{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(jk,{size:17})})]})}function OS({state:t}){return t==="ok"?i.jsx(Pa,{size:15,"aria-hidden":"true"}):i.jsx(Zx,{size:15,"aria-hidden":"true"})}function ux({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(Ek,{size:18,"aria-hidden":"true"})})}function dx({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($x,{size:18,"aria-hidden":"true"})})}function fx({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(po,{size:18,"aria-hidden":"true"})})}function BS({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(OS,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))})}function jD({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(po,{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(nr,{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(OS,{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 ED=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,DD=/(libx264|openh264|software|cpu)/i,xv=2,ID=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 fn(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 At(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 HS(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=At(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Qe(t,n,r,o){return{id:t,state:n,label:r,detail:o}}function zS(t){const n=fn(t),r=At(n,"helperCount"),o=At(n,"helperOwnedIoTaskCount"),l=At(n,"helperUndisposedProcessCount"),u=At(n,"helperOwnedExitObserverCount"),f=At(n,"helperQuarantineCount"),h=At(n,"utilityQuarantineCount"),g=At(n,"utilityOwnedIoTaskCount"),y=At(n,"utilityUndisposedProcessCount"),w=Number(At(n,"helperDisposeFailureCount")||0),b=Number(At(n,"utilityDisposeFailureCount")||0),S=Math.max(0,Number(r||0)),k=Number(o||0),N=Number(l||0),A=Number(u||0),D=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),R=Number(g||0),_=Number(y||0),B=[o,l,u,f,h,g,y].every(j=>j!==void 0),F=B&&(k<0||N<0||A<0||N!==S||A!==0||S===0&&k!==0||S>0&&k===0),H=B&&(R<0||_<0||_!==I||R!==I*2);return{telemetryAvailable:B,helperOwnedIoTaskCount:k,helperUndisposedProcessCount:N,helperOwnedExitObserverCount:A,helperQuarantineCount:D,helperDisposeFailureCount:w,helperLastDisposeFailure:zt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:R,utilityUndisposedProcessCount:_,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(j=>Number(j)).filter(j=>Number.isSafeInteger(j)&&j>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(j=>String(j||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(At(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(At(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:zt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:H,historicalCleanupFailure:w!==0||b!==0,currentProblem:D>0||I>0||F||H}}function $S({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=nm(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>=ID&&Qc.delete(Qc.keys().next().value),Qc.set(t,{sampleId:o,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=xv}}function nm(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function mx(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 LD(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 US(t){const n=fn(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 px(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 PD(t){const n=US(t);return n==="encrypted-rendezvous-relay"?Qe("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Qe("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Qe("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function _D(t,n){const r=fn(t),o=fn(n),l=US(r);if(l==="encrypted-rendezvous-relay"){const u=zt(o,"state")||(o.connected===!0?"registered":"unknown"),f=px(zt(o,"endpoint"))||px(zt(r,"relayEndpoint")),h=r.connected!==!0||o.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Qe("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=At(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Qe("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${zt(r,"protocol")||"-"} v${At(r,"protocolVersion")??"-"} · input ${fn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Qe("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function qS(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function WS(t,n,r){const o=fn(n?.frameTransport),l=zt(t,"frameTransportChangedAt"),u=zt(o,"changedAt"),f=nm(l),h=nm(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(),D=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(A)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),R=/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"||D?D?"direct-ws":"direct-tcp":"",_=(zt(y,g?"state":"frameTransportState")||zt(w,g?"frameTransportState":"state")||(R?"active":"")).toLowerCase(),B=zt(y,g?"reason":"frameTransportReason")||zt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,H=nm(F),j=H===void 0?void 0:Math.max(0,r-H),Q=j===void 0?"":j<1e3?"changed now":j<6e4?`changed ${Math.round(j/1e3)}s ago`:j<36e5?`changed ${Math.round(j/6e4)}m ago`:`changed ${F}`,$=g?o.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??o.switchCount,G=g?o.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??o.tcpFailureCount,W=g?typeof o.p2pReady=="boolean"?o.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:o.p2pReady===!0;return{rawTransport:b,videoTransport:R,state:_,reason:B,changedAt:F,changedLabel:Q,switchCount:Math.max(0,Number($??0)||0),tcpFailureCount:Math.max(0,Number(G??0)||0),p2pReady:W}}function FD(t,n,r){const o=WS(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(o.state);if(o.videoTransport==="encrypted-relay")return Qe("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 Qe("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 Qe("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 Qe("transport","warning","Video transport is not identified",o.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const OD=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 GS(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),o=Number(t?.nativeCaptureTelemetryVersion)>=5&&OD.every(u=>At(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 BD(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),o=HS(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||o!==void 0,u=GS(t);return!t||!/h264/.test(n)?Qe("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Qe("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)?Qe("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?Qe("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?Qe("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&o===!0?Qe("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):ED.test(r)?Qe("encoder","ok","Hardware H.264 encoding",r):DD.test(r)?Qe("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Qe("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function HD({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=fn(t),D=fn(A.status),I=fn(o?.lastInfo),R=[],_=qS(n,N);R.push(PD(A)),R.push(w?b?Qe("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Qe("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?Qe("connection","ok","Video connection is current",`${Math.round(_)}ms since the latest frame.`):Qe("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."))),R.push(FD(n,D,N)),R.push(BD(n));const B=zS(D.capture),F=fn(D.capture),H=$S({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)&&R.push(Qe("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 j=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),Q=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const $=Math.max(0,Number(n?.nativeCaptureFps||0)),G=Math.max(0,Number(n?.nativeEncodedFps||0)),W=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),V=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),X=At(n,"nativeCaptureTelemetryAgeMs"),J=Math.max(0,Number(X||0))+(Number.isFinite(_)?_:0),z=V<2||X!==void 0&&J<=It.nativeTelemetryStaleMs,P=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),re=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),we=n?.nativeCaptureTelemetryAvailable===!0&&W>0&&z,Z=At(n,"captureP95Ms","captureAverageMs","captureStageMs"),Se=Math.max(0,Number(Z||0)),ae=n?.captureTimingAvailable===!0&&j>0&&Number(r?.sampleMs||0)>0&&Z!==void 0,ye=ae||we,Pe=Math.max(It.minimumCaptureBudgetMs,j>0?1e3/j*It.captureBudgetMultiplier:0),de=j>0?1e3/j:100,Ke=j>0&&$>=j*It.receiveRatioWarning,ue=G>0&&G<j*It.receiveRatioWarning,Fe=we&&Ke&&ue&&G>=1&&re>=Math.max(10,$*.6)&&P===0,Xe=we&&j>0&&($<j*It.receiveRatioWarning||!Fe&&G>0&&G<j*It.receiveRatioWarning),at=we?Xe:ae&&Se>Pe;R.push(ye?at?Qe("capture","warning","Screen capture cannot keep target speed",we?`${$.toFixed(1)} native capture · ${G.toFixed(1)} encoded · ${j||"?"} requested fps`:`${Se?`capture p95 ${Math.round(Se)}ms`:"capture timing unavailable"} · ${Q.toFixed(1)}/${j||"?"} fps`):Qe("capture","ok","Screen capture speed is healthy",we?`${$.toFixed(1)} native capture · ${G.toFixed(1)} encoded · ${j||"?"} requested fps${Fe?" · idle optimized":""}`:`${Se?`capture p95 ${Math.round(Se)}ms`:"no slow capture reported"}${j?` · ${Q.toFixed(1)}/${j} fps`:""}`):Qe("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Ee=At(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)),Je=!LD(A.remoteAddress),Me=Ci(D,"network.usageRatio"),pe=At(D,"network.latencyMs"),qe=(Me??0)>=It.networkUsageWarningRatio||(pe??0)>=It.networkLatencyWarningMs,Re=n?.hubClientQueueTelemetryAvailable===!0||At(n,"hubClientDropped")!==void 0&&At(n,"hubClientQueueDepth")!==void 0&&At(n,"hubClientQueueLimit")!==void 0&&At(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,$e=Ee!==void 0&&Number(r?.sampleMs||0)>0,We=!Fe&&j>0&&Number(r?.sampleMs||0)>0&&Q<j*It.deliveryRatioWarning,Et=!Fe&&me>Math.max(It.networkDelayWarningMs,de*3),lt=Ge>It.networkDelayWarningMs||Et||ke>It.networkDelayWarningMs||We||_>It.frameAgeWarningMs||qe||O;R.push($e?lt||Je?Qe("network","warning",Je?"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?`${Q.toFixed(1)} of ${j} 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}`:"",Je?String(A.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Qe("network","ok","Network delivery is healthy",`${Math.round(Ge)}ms Hub-to-browser · ${Fe?`idle optimized at ${G.toFixed(1)} fps`:"the current video rate is on target."}`):Qe("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const ht=Ci(D,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),Ze=Ci(D,"memory.usedRatio","usedMemRatio"),be=Ci(D,"gpu.usageRatio"),je=Ci(D,"gpu.memory.usedRatio"),Ae=At(D,"gpu.temperatureC","thermal.gpuC"),fe=ht!==void 0&&Ze!==void 0,te=nm(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||(Ze??0)>=It.memoryWarningRatio||(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC;R.push(fe?He?Ie?Qe("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(Ze*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(" · ")):Qe("computer","ok","Client computer has working capacity",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Ze*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:""].filter(Boolean).join(" · ")):Qe("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."):Qe("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Lt=Number(n?.monitorIndex),Ye=Number.isInteger(Lt)&&Lt===Number(u),ut=fn(A.channels),yt=fn(A.capabilities),_t=ut.input!==!1&&yt.remoteInput!==!1&&yt.accessibilityPermission!==!1,mt=yt.screenRecordingPermission!==!1,Vt=fn(g),Ct=!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),mn=!f||h&&Ct;R.push(Ye&&mn&&_t&&mt?Qe("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"}.`):Qe("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 an=fn(l),va=Array.isArray(an.canvases)?fn(an.canvases[0]):{},kt=Math.max(0,Number(o?.decoderInputFps||0)),hn=Math.max(0,Number(o?.decoderOutputFps||0)),en=kt>0&&Number(o?.sampleMs||r?.sampleMs||0)>0,nt=Q>0&&Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0&&kt<Q*It.decoderInputRatioWarning,Dt=kt>0?hn/kt:0,gn=zt(va,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Mr=zt(va,"softwareFallbackReason"),Hr=!!Mr||gn==="prefer-software";return R.push(nt?Qe("decoder","warning","Browser decoder input is dropping frames",`${Q.toFixed(1)} received / ${kt.toFixed(1)} decoder input / ${hn.toFixed(1)} output fps.`):en?Hr||Dt<It.decoderOutputRatioWarning?Qe("decoder","warning",Hr?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Mr||String(I.decoderLabel||gn||"decoder")} · ${kt.toFixed(1)} in / ${hn.toFixed(1)} out fps.`):Qe("decoder","ok",gn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${kt.toFixed(1)} in / ${hn.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Qe("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),R}function co(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 zD({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=fn(t),S=fn(b.status),k=fn(S.runtimeProcess),N=fn(S.capture),A=zS(N),D=fn(g),I=fn(o?.lastInfo),R=fn(l),_=Array.isArray(R.canvases)?fn(R.canvases[0]):{},B=[],F=Number(u),H=Number(n?.monitorIndex),j=Number.isInteger(H)&&H===F,Q=Number(n?.captureGeneration||0),$=Number(D.captureGeneration||0),G=!f||j&&String(n?.sessionId||"")===String(D.sessionId||"")&&String(n?.commandId||"")===String(D.commandId||"")&&Q>0&&Q===$,W=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)),z=Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0,P=W>0&&z&&Math.min(V,X||V,J||V)<W*It.deliveryRatioWarning,re=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=At(n,"hubPacketTransitAgeMs"),de=Math.max(0,Number(n?.droppedByAgent||0)),Ke=Math.max(0,Number(n?.hubIngressDropped||0)),ue=n?.hubClientQueueTelemetryAvailable===!0||At(n,"hubClientDropped")!==void 0&&At(n,"hubClientQueueDepth")!==void 0&&At(n,"hubClientQueueLimit")!==void 0&&At(n,"hubClientBufferedBytes")!==void 0,Fe=ue?Math.max(0,Number(n?.hubClientDropped||0)):0,Xe=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+Ke+Fe,ke=qS(n,w),Je=zt(_,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Me=zt(_,"softwareFallbackReason"),pe=Math.max(0,Number(R.hardwareReleaseGeneration||0)),qe=Math.max(0,Number(R.hardwareRecoveryProbeCount||0)),Re=Number(R.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=z&&V>0&&ve<V*It.decoderInputRatioWarning,$e=WS(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"),Ze=At(b,"pid","runtimePid")??At(S,"pid","runtimePid","process.pid"),be=At(k,"pid"),je=Ci(k,"cpuUsageRatio"),Ae=At(k,"cpuCorePercent"),fe=At(k,"workingSetBytes"),te=At(k,"privateMemoryBytes"),ce=Math.max(fe||0,te||0),Ne=(be??0)>0&&(fe??0)>0,He=Ne&&(Ze??0)>0&&be!==Ze,Ie=(je??0)>=It.runtimeProcessCpuWarningRatio||ce>=It.runtimeProcessMemoryWarningBytes,Lt=Ci(S,"cpu.usageRatio"),Ye=Ci(S,"memory.usedRatio","usedMemRatio"),ut=Math.max(0,Number(At(N,"videoStreamCount")||0)),yt=Math.max(0,Number(At(N,"audioStreamCount")||0)),_t=At(N,"helperCount"),mt=Math.max(0,Number(_t||0)),Vt=At(N,"helperMaxConcurrent"),Ct=Math.max(mt,Number(Vt||0)),mn=Array.isArray(N.helperPids)?N.helperPids.map(Ma=>Number(Ma)).filter(Ma=>Number.isSafeInteger(Ma)&&Ma>0):[],an=Array.isArray(N.helperProfiles)?N.helperProfiles.map(Ma=>String(Ma||"").trim()).filter(Boolean).slice(0,4):[],va=Ci(N,"helperCpuUsageRatio"),kt=At(N,"helperCpuCorePercent"),hn=At(N,"helperWorkingSetBytes"),en=At(N,"helperPrivateMemoryBytes"),q=Math.max(hn||0,en||0),nt=Math.max(0,Number(At(N,"helperStartCount")||0)),Dt=Math.max(0,Number(At(N,"helperStopCount")||0)),gn=_t!==void 0,Mr=gn&&nt>=Dt&&nt-Dt!==mt,Hr=mt>1||Ct>1||ut>1||Mr||A.currentProblem,Ar=gn&&(ut>0&&mt===0||ut===0&&mt>0),oe=$S({key:We&&Et?`${We}:${Et}`:"",sampleId:zt(N,"sampledAt"),mismatch:Ar}),Ue=Ar&&!oe.confirmed,tt=Hr||oe.confirmed,Pt=(va??0)>=It.captureHelperCpuWarningRatio||q>=It.captureHelperMemoryWarningBytes,wn=!!(We&&Et&&lt&&ht&&(Ze??0)>0),Be=n?.nativeCaptureTelemetryAvailable===!0,it=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),Tt=it>=2,bt=GS(n),Gt=!bt.required||bt.available,ra=At(n,"nativeCaptureTelemetryAgeMs"),Un=Math.max(0,Number(ra||0))+(Number.isFinite(ke)?ke:0),Qt=ra===void 0?"-":`${Math.round(Un)}ms`,En=!Tt||ra!==void 0&&Un<=It.nativeTelemetryStaleMs,zr=Be&&!En,Ht=HS(n,"nativeEncoderHardwareAccelerated"),Pn=n?.nativeEncoderHardwareAccelerationKnown===!0||Ht!==void 0,Ba=zt(n,"nativeEncoderHardwareQueryStatus"),ar=Ba==="0"?"confirmed":Ba,Nr=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),rr=Math.max(0,Number(n?.nativeCaptureFps||0)),Zs=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),Is=Math.max(0,Number(n?.nativeCompressionFps||0)),Dn=Math.max(0,Number(n?.nativeEncodedFps||0)),on=Tt||Zs>0?Is:Dn,il=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Ls=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),vo=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),Ai=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),sr=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Ld=bt.pending,Ha=bt.timestampOwners,$r=bt.timestampOwnerHighWatermark,ol=bt.coalesced,wt=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),_n=bt.pendingReplaced,yo=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),rn=bt.vtActive,cs=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)),Tr=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),bo=n?.nativeOutputQueueAwaitingKeyFrame===!0,ei=bt.nativeAndPipeResidenceAgeMs,ir=bt.handoffDropped,Ni=bt.handoffRecoveryRequests,ti=bt.handoffOldestAgeMs,Bn=sr>2||Ld>1||Ha>2||$r>2||ol>0||sr>=2&&wt>0,or=bt.required&&bt.available&&(rn!==1||cs>1||Ha>2||$r>2),ni=oc>=3||Js>=6*1024*1024||ll>120||Tr>0||bo||ei>250||ir>0||Ni>0||ti>120,cl=`in-flight ${sr}/2 · backpressure skipped ${wt} · idle skipped ${yo} · stdout queue ${oc} AU/${Math.round(Js/1024)} KB/${Math.round(ll)}ms · HWM ${Bt} · dropped ${Tr} · awaiting key ${bo?"yes":"no"} · native+pipe ${Math.round(ei)}ms · handoff ${Math.round(ti)}ms/drop ${ir}/recovery ${Ni}`,lc=`pending ${Ld}/1; timestamp owners ${Ha}/2 (HWM ${$r}); coalesced ${ol}; pending replaced ${_n}; VideoToolbox ${rn} active/HWM ${cs}`,wo=bt.available&&bt.annexBAllocations>0&&bt.annexBPayloadCopies>=bt.annexBAllocations&&bt.annexBPayloadCopiedBytes>0&&bt.pipePayloadAllocations>0&&bt.pipePayloadCopies>=bt.pipePayloadAllocations&&bt.pipePayloadCopiedBytes>0,Ur=`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)`,qr=Be&&il>0&&En,xo=W>0?1e3/W:100,Ps=W>0&&rr>=W*It.receiveRatioWarning,So=on>0&&on<W*It.receiveRatioWarning,za=qr&&Ps&&So&&on>=1&&Dn>=1&&yo>=Math.max(10,rr*.6)&&wt===0,ln=P&&!za,Xn=!za&&we>Math.max(It.networkDelayWarningMs,xo*3),$a=qr&&W>0&&rr<W*It.receiveRatioWarning,kn=qr&&!za&&rr>0&&(Tt&&on<=0||on>0&&on<rr*It.receiveRatioWarning),Fn=qr&&Zs>0&&on>0&&Dn<on*It.receiveRatioWarning,Ua=zr?"Native capture telemetry is stale":Gt?or?"VideoToolbox encoder ownership needs attention":qr?$a?"Native screen capture is below request":kn||Bn?"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(_D(b,y)),B.push(wn?Qe("debug-runtime","ok",`LiveDesk ${lt} · Agent ${ht}`,`pid ${Ze} · session ${co(Et)} · device ${co(We)}`):Qe("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${lt||"-"} · Agent ${ht||"-"} · pid ${Ze??"-"} · session ${co(Et)} · device ${co(We)}`)),B.push(Ne&&!He&&!Ie?Qe("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(Ye)}`):Qe("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 ${Ze??"-"} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Ye)}`)),B.push(n?Qe("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${co(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`):Qe("debug-frame","warning","No current frame",`Device ${co(b.deviceId)} has not produced a frame.`));const lr=/(connecting|recovering|failed|error|degraded|unavailable)/.test($e.state);B.push($e.videoTransport&&!lr?Qe("debug-transport","ok",`${$e.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":$e.videoTransport==="p2p-udp"?"P2P UDP":$e.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${$e.state||"active"}`,[`raw ${$e.rawTransport||"-"}`,`P2P ${$e.p2pReady?"ready":"standby unavailable"}`,`switch ${$e.switchCount}`,`TCP failure ${$e.tcpFailureCount}`,$e.changedLabel,$e.reason].filter(Boolean).join(" · ")):Qe("debug-transport","warning",$e.videoTransport?`Video transport ${$e.state||"needs attention"}`:"Video transport is not identified",[$e.videoTransport||"no active path",`raw ${$e.rawTransport||"-"}`,`P2P ${$e.p2pReady?"ready":"not ready"}`,$e.changedLabel,$e.reason].filter(Boolean).join(" · "))),B.push(j?Qe("debug-monitor","ok",`Monitor selected ${F+1} · frame ${H+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${Q||"-"}`):Qe("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger(H)?H+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${Q||"-"}`)),B.push(G&&(!f||h)?Qe("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${co(n?.sessionId)} · command ${co(n?.commandId)} · generation ${Q||"-"}`):Qe("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${co(n?.commandId)}/${Q||"-"} · expected ${co(D.commandId)}/${$||"-"} · input ${h?"ready":"waiting"}`)),B.push(z&&!ln?Qe("debug-cadence","ok",`Cadence ${Rn(V)} rx · ${Rn(X)} paint · ${Rn(J)} decode`,`requested ${Rn(W)} · decoder input ${Rn(ve)} fps · receive p95 ${Rn(r?.p95IntervalMs)}ms${za?" · idle optimized":""}`):Qe("debug-cadence","warning",z?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Rn(W)} · receive ${Rn(V)} · paint ${Rn(X)} · decode ${Rn(J)} fps`)),B.push(qr&&Gt&&!$a&&!kn&&!Fn&&!Bn&&!or&&!ni&&Ht!==!1?Qe("debug-native-capture","ok",`Native capture ${Rn(rr)} fps · compress ${Rn(on)} fps · stdout ${Rn(Dn)} fps${za?" · idle optimized":""}`,`telemetry v${it||1} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${ar?` (${ar})`:""} · display ${Nr||"-"} · capture samples ${il} · encodable ${Ls} · skipped ${vo} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(re)}ms`):Qe("debug-native-capture","warning",Ua,`telemetry ${Be?`v${it||1}`:"no"} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${ar?` (${ar})`:""} · display ${Nr||"-"} · capture ${Rn(rr)} fps · compress ${Rn(on)} fps · stdout ${Rn(Dn)} fps · capture samples ${il} · encodable ${Ls} · skipped ${vo} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(re)}ms`)),bt.required&&(B.push(Gt&&!Bn&&!or?Qe("debug-native-resource","ok","VideoToolbox resource ownership is bounded",lc):Qe("debug-native-resource","warning",Gt?or?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",lc)),B.push(Gt&&wo?Qe("debug-native-copy","ok","Capture copy accounting is current",Ur):Qe("debug-native-copy","warning",Gt?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Ur))),B.push(gn&&!tt&&!Pt?Qe("debug-capture-ownership","ok",Ue?"Capture ownership transition is settling":mt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ut} · audio ${yt} · helpers ${mt} (max ${Ct||"-"}) · pid ${mn.join(",")||"-"} · profile ${an.join(", ")||"-"} · CPU ${Vl(va)} machine / ${kp(kt)} core · RSS ${Gl(hn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}${Ue?` · mismatch samples ${oe.count}/${xv}`:""}`):Qe("debug-capture-ownership","warning",gn?mt>1||Ct>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 ${Ct||"-"}) · pid ${mn.join(",")||"-"} · profile ${an.join(", ")||"-"} · CPU ${Vl(va)} machine / ${kp(kt)} core · RSS ${Gl(hn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}`));const qa=`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?Qe("debug-capture-cleanup","ok",mt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",qa):Qe("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",qa)),B.push(ue?me===0&&Ge===0&&(at<=0||Xe<at)&&!Xn&&Z<=It.networkDelayWarningMs&&ye<=It.networkDelayWarningMs&&(Pe===void 0||Pe<=It.networkDelayWarningMs)?Qe("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(re)}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 ${Ke} · browser queue drop ${Fe} (${Xe}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}${za?" · idle optimized":""}`):Qe("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(re)}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 ${Ke} · browser queue drop ${Fe} (${Xe}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}`):Qe("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(we)}ms · Agent drop ${de} · Hub ingress drop ${Ke} · per-browser lane counters are intentionally collected outside video packets.`));const ai=At(n,"captureP95Ms");return B.push(n?.captureTimingAvailable===!0&&ai!==void 0?Qe("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)}`):qr&&Tt?Qe("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Rn(rr)} fps · VideoToolbox ${Rn(on)} fps · stdout ${Rn(Dn)} fps · telemetry age ${Qt}`):Qe("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&&Je!=="prefer-software"&&!O?Qe("debug-decoder","ok",`Decoder ${Je||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${jt}`):Qe("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||Je||"software"} · ${Rn(ve)} in / ${Rn(J)} out fps · ${jt}`)),B}function $D({status:t,deviceDiagnostics:n=[],codec:r,browser:o,frameStats:l}={}){const u=fn(t),f=fn(u.diagnostics),h=fn(f.system),g=fn(f.network),y=fn(r),w=fn(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=At(h,"totalMemoryBytes"),D=At(h,"cpuLogicalCores")??At(w,"hardwareConcurrency"),I=At(w,"deviceMemory"),R=(D??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=(D??0)>0&&D<4||(k??0)>=It.cpuWarningRatio||(N??0)>=It.memoryWarningRatio||_||B,H=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),j=Math.max(0,Number(y.activeDecoderCount||0)),Q=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),$=At(g,"externalDeviceCount"),G=zt(g,"route"),W=$!==void 0&&!!G,V=($??0)>0||G==="external",X=fn(u.frameLanes),ve=fn(X.packetFanout),J=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(ye=>At(ve,ye)!==void 0),z=Array.isArray(X.clients)?X.clients.map(fn):[],P=At(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&J,re=z.some(ye=>{const Pe=Math.max(0,Number(ye.queueDepth||0)),de=Math.max(0,Number(ye.queueLimit||0)),Ke=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&&Ke>=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?Qe("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Qe("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),R?F?Qe("hub-computer","warning",_?"Hub has limited system memory":B?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${D||"?"} logical cores`,`${mx(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(" · ")):Qe("hub-computer","ok","Hub computer capacity is healthy",`${D||"?"} logical cores · ${mx(A)} RAM · CPU ${k===void 0?"not reported":`${Math.round(k*100)}%`}.`):Qe("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),j<=0?Qe("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):H>0?Qe("hub-codec","warning","Some browser decoders use software fallback",`${j} active H.264 decoders · ${H} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Qe("hub-codec","ok","All active streams request hardware H.264",`${j} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),P?re?Qe("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${z.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Qe("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${z.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Qe("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),S>0?Qe("hub-clients","warning",`${S} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Qe("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Qe("hub-network",!W||V||Q>120?"warning":"ok",W?V?`${$} Clients use an external network route`:Q>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",W?`${G.toUpperCase()} route · ${Q.toFixed(Q>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function UD(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,D=N*g,I=S.canvas,R=Math.min(h/I.width,g/I.height),_=Math.max(1,Math.floor(I.width*R)),B=Math.max(1,Math.floor(I.height*R)),F=A+Math.floor((h-_)/2),H=D+Math.floor((g-B)/2);w.drawImage(I,F,H,_,B),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,D+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(S.label,A+9,D+g-9))}return y}function qD(t){return t?.signature||"none"}function WD(t){return t?.label||"No capture target"}function hx(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function GD(){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 VD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function KD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${VD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${GD()}.png`}async function QD(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 FS(o,{kind:"screenshot",fileName:KD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":o})])}catch{}return l.capture}function VS(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function YD(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 KS(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=VS();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",o=await kD({kind:r,fileName:YD(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(()=>MD(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 ox(o.sessionId,t.hubUrl).catch(()=>{}),y;await AD(o.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await ox(o.sessionId,t.hubUrl).catch(()=>{}))}}}class XD{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=VS();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 FS(o,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function ZD(t,n,r,o,l){const u=await KS({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 QS="livedesk.captureSettings";function JD(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(QS)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function eI(t){const[n,r]=d.useState(JD),[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),D=d.useRef(null),I=d.useRef(null),R=d.useRef(new XD),_=t.sourceRegistry.resolveCurrentTarget(),B=qD(_),F=WD(_),H=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(QS,JSON.stringify(n)),!S.current)return;const re=JSON.stringify(n);re!==k.current&&(k.current=re,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 re=!0;return rt("/api/settings",void 0,t.hubUrl).then(we=>{if(!re)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}),()=>{re=!1}},[t.hubUrl]);const j=d.useCallback(async re=>{if(re.sourceCanvas&&re.sourceCanvas.width>0&&re.sourceCanvas.height>0)return{target:hx(re),canvas:re.sourceCanvas,cleanup:()=>{}};const we=await t.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Z=!1;const Se=window.setInterval(async()=>{if(Z)return;const ae=await t.sourceRegistry.composeWall(re.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:hx(re),canvas:we,cleanup:()=>{Z=!0,window.clearInterval(Se)}}},[t.sourceRegistry]);d.useEffect(()=>{const re=R.current;if(!n.rollingEnabled||!_||!H){re.stop(),g(0);return}let we=!1,Z=null;return(async()=>{try{if(Z=await j(_),we)return;await re.start(Z.canvas,Z.target);const ae=window.setInterval(()=>g(Math.round(re.seconds)),500),ye=()=>{window.clearInterval(ae),Z?.cleanup()};re.__cleanup=ye}catch(ae){we||t.onToast(ae instanceof Error?ae.message:String(ae))}})(),()=>{we=!0,re.stop(),re.__cleanup?.(),re.__cleanup=void 0,g(0)}},[j,t.onToast,n.rollingEnabled,B,H]);const Q=d.useCallback(re=>r(we=>({...we,rollingEnabled:re})),[]),$=d.useCallback(re=>r(we=>({...we,recordingQuality:re})),[]),G=d.useCallback(re=>r(we=>({...we,timelapseIntervalSeconds:re})),[]),W=d.useCallback(async()=>{const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let we=null;try{we=await j(re),await QD(we.canvas,we.target,t.hubUrl),t.onToast("Screenshot saved")}finally{we?.cleanup(),w(!1)}},[j,t.hubUrl,t.onToast,t.sourceRegistry]),V=d.useCallback(async()=>{if(D.current)throw new Error("Stop the timelapse before recording.");const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await j(re),Z=await KS({canvas:we.canvas,target:we.target,fps:re.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")},[j,t.hubUrl,t.onToast,t.sourceRegistry]),X=d.useCallback(async()=>{const re=N.current;if(re){w(!0);try{await re.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||D.current)throw new Error("Last 30s is unavailable during a recording.");const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await R.current.save(re,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 re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await j(re),Z=await ZD(we.canvas,we.target,n.timelapseIntervalSeconds,t.hubUrl,Se=>t.onToast(Se.message));I.current=we.cleanup,D.current=Z,f(Date.now()),t.onToast("Timelapse started")},[j,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),z=d.useCallback(async()=>{const re=D.current;if(re){w(!0);try{await re.stop(),t.onToast("Timelapse saved")}finally{D.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const re=we=>{!N.current&&!D.current||(we.preventDefault(),we.returnValue="")};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[]),d.useEffect(()=>()=>{R.current.stop(),N.current?.cancel(),D.current?.cancel(),A.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!N.current,recordingStartedAt:o,timelapse:!!D.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:Q,setRecordingQuality:$,setTimelapseInterval:G,takeScreenshot:W,startRecording:V,stopRecording:X,saveLast30Seconds:ve,startTimelapse:J,stopTimelapse:z}}function tI(){if(typeof window>"u")return{isIos:!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=n&&/CriOS/i.test(t),o=n&&/Safari/i.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(t);return{isIos:n,isSafari:o,browserName:r?"Chrome":o?"Safari":"browser"}}const nI=120,aI=999,qf=5,Wf=30,rI=Number.POSITIVE_INFINITY,YS="livedesk.remoteDirectory",Sv="livedesk.localHubAccessEnabled",sI="livedesk.streamSettings",iI=18,oI="livedesk.controlStreamSettings",lI=10,XS="livedesk.wallCadence",cI=1e3,ZS="livedesk.wallMonitorSelections",JS=2,Fg=512*1024,uI=!1;"".trim();"".trim();const dI=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),fI=1e3/60,Og=1500,mI=650,pI=1800,hI=650,gI=2500,Bg=1500,gx=15e3,vx=120,yx=100,bx=20,vI=6e4,yI=6e4,wx=240,bI=1024,wI=640,xI=360,xx="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,SI=5e3,Sx=2e3,CI=8e3;function Cx(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 kI(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:qf,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Wf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:rI,audience:"Business and studios",note:"Commercial use and larger Client walls."}},MI={"mode3-h264-hw":30};function kx(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 AI=512;function la(t,n){return`${t}:${n}`}function uo(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const NI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:MI["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},TI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Mx={maxWidth:3840,maxHeight:2160};function zf(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 eC(t,n){t.push(n),t.length>wx&&t.splice(0,t.length-wx)}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 Ax(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),eC(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 Nx(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 Tx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function RI(t){return Number.isFinite(t)?String(t):"30+"}const tC=[1,2,5,8,12,20,30],Rx={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:Yn.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:Yn.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},jx=2200,jI=2500,EI=8e3,DI=3500,II=7e3,LI=2,PI=2500,_I=7e3,FI=2600,OI=4200,BI=750,HI=2,Ex=2500,Dx=4200,Ix=2200;function Lx(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 La(t){return t.deviceName||t.hostname||t.deviceId}function zI(){return"npx -y --prefer-online livedesk@latest client"}function $I(){return"npx -y --prefer-online livedesk@latest"}function UI(){try{return localStorage.getItem(YS)||""}catch{return""}}function qI(){try{return localStorage.getItem(Sv)==="1"}catch{return!1}}function xd(t){try{t?localStorage.setItem(Sv,"1"):localStorage.removeItem(Sv)}catch{}}function ki(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function mo(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 nC(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=nC(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 WI(t){const n=mo(t);return Array.from({length:n},(r,o)=>ey(t,o))}function GI(t){const n=nC(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 VI(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 aC(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 rC(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 KI(t,n,r){const u=((typeof n?.monitorIndex=="number"?Gf(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?rC(n):null)||aC(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Tp=16/9;function Gf(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 Es(t,n){return SN(n,mo(t),t.platform)}function QI(){try{const t=localStorage.getItem(ZS);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)!==JS||!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 YI(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([o,l])=>[o,{monitorIndex:l,topologyFingerprint:n[o]||""}]));localStorage.setItem(ZS,JSON.stringify({version:JS,selections:r}))}catch{}}function XI(){return{...NI}}function ZI(t){try{localStorage.setItem(sI,JSON.stringify({...t,version:iI}))}catch{}}function JI(){return{...TI}}function eL(t){try{localStorage.setItem(oI,JSON.stringify({...t,version:lI}))}catch{}}function tL(){try{return localStorage.getItem(XS)==="slow"?"slow":"fast"}catch{return"fast"}}function nL(t){try{localStorage.setItem(XS,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 aL(t){return Si.fallbackVisibleCounts[t]||Si.fallbackVisibleCounts.large}function Px(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=Rx[n]||Rx.large;return{maxWidth:Math.min(t.maxWidth,o.maxWidth),maxHeight:Math.min(t.maxHeight,o.maxHeight)}}function rL(t,n=Si.minFps){const r=[...tC].sort((l,u)=>l-u),o=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||o}function sL(t,n){return[...tC].sort((o,l)=>o-l).find(o=>o>t&&o<=n)||n}function Vf(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 _x(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`${_x(r)} / ${_x(t)}`}function iL(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 Fx(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 oL(t){return t===1?"middle":t===2?"right":"left"}function Ox(t,...n){for(const r of n){const o=t?.[r];if(typeof o=="string"&&o.trim())return o.trim()}return""}function Bx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=aI?n:0}const lL={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function cL(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=lL[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function sC(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=sC(t,r),l=Number(o);if(Number.isFinite(l))return l}}function fo(t,...n){for(const r of n){const o=sC(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 Sd(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 uL(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 iC(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=fo(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"),D=el(aa(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ug(N,A),I=aa(n,"gpu.temperatureC","thermal.gpuC"),R=el(aa(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),_=fo(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"),j=aa(n,"network.latencyMs","network.rttMs"),Q=el(aa(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),$=fo(n,"network.link","network.interface","network.name"),G=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),W=Number.isFinite(G)?G:void 0,V=W===void 0?void 0:el((W-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=fo(n,"workload.role","role","lane")||(Op(t,"taskDispatch")?"Command-ready Client":"Local machine"),J=fo(t.latestTask,"status")||fo(n,"workload.status")||"idle",z=fo(t.latestTask,"title","instructionPreview")||fo(n,"workload.title"),P=fo(t.latestTask,"resultSummary","error","instructionPreview")||fo(n,"workload.summary"),re=Date.parse(t.lastSeenAt||t.connectedAt||""),we=Number.isFinite(re)?Date.now()-re:0;let Z="online";t.connected?we>5*6e4?Z="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(S??0)>=.96||(D??0)>=.96||(R??0)>=.96||(h??0)>=.94||(w??0)>=.94||(j??0)>=200||J==="failed"?Z="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(S??0)>=.86||(D??0)>=.88||(R??0)>=.86||(h??0)>=.82||(w??0)>=.86||(j??0)>=80?Z="warn":["queued","running","targeted"].includes(J)&&(Z="busy"):Z="offline";const Se=[{id:"cpu",label:"CPU",value:Sd(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:Sd(h),detail:$g(u,f),ratio:h,state:Zc(h,.92,.78)},{id:"disk",label:"DISK",value:Sd(w),detail:$g(g,y),ratio:w,state:Zc(w,.92,.82)},{id:"gpu",label:"GPU",value:Sd(S),detail:k||(N&&A!==void 0?`${Vf(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:Sd(D),detail:$g(N,A),ratio:D,state:Zc(D,.96,.88)},{id:"npu",label:"NPU",value:R!==void 0?Sd(R):B!==void 0?`${Math.round(B)} TOPS`:"-",detail:_||(B!==void 0?"neural engine":"not reported"),ratio:R,state:Zc(R,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${uL(aa(n,"uptimeSec"))}`,ratio:V,state:W===void 0?"unknown":W>=86?"critical":W>=78?"warn":"good"},{id:"network",label:"NET",value:qg(F)||(j!==void 0?`${Math.round(j)}ms`:$||"-"),detail:qg(H)?`${qg(H)} up`:$||"not reported",ratio:Q,state:j!==void 0&&j>=200?"critical":j!==void 0&&j>=80?"warn":Zc(Q,.9,.75)}];return{state:Z,label:cL(Z,Se,J),role:ve,taskLabel:z||(J==="idle"?"idle":J),taskStatus:J,taskSummary:P,metrics:Se}}const dL=[{id:"slow",label:"Slow",fps:pv("slow")},{id:"fast",label:"Fast",fps:pv("fast")}],fL=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],mL=[{id:"sync-server",label:"Hub",icon:po,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:e0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:$f,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Yf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:jp,accent:"violet",tooltip:"agents"}],pL=[{id:"doc",label:"Doc",icon:Hp,accent:"amber"},{id:"support",label:"Support",icon:Kf,accent:"violet"},{id:"pricing",label:"Pricing",icon:Qf,accent:"green"}];function hL(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 Qn(t){return hL(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=>Qn(n))}function Sr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:Qn(t.title),intro:Qn(t.intro),sections:[{title:Qn(t.managerTitle),body:Qn(t.managerBody),points:Jc(t.managerPoints)},{title:Qn(t.clientTitle),body:Qn(t.clientBody),points:Jc(t.clientPoints)},{title:Qn(t.syncTitle),body:Qn(t.syncBody),points:Jc(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:Qn(t.agentTitle),body:Qn(t.agentBody),points:Jc(t.agentPoints)}]:[],{title:Qn(t.platformTitle),body:Qn(t.platformBody),points:Jc(t.platformPoints)}],sync:{title:Qn(t.syncTitle),body:Qn(t.syncBody),points:Jc(t.syncPoints)},firewall:{title:Qn(t.firewallTitle),body:Qn(t.firewallBody),points:Jc(t.firewallPoints)},commands:{title:Qn(t.commandsTitle),body:Qn(t.commandsBody),manager:Qn(t.managerCommandLabel),primary:Qn(t.clientCommandLabel),slot:Qn(t.slotCommandLabel),manual:Qn(t.manualCommandLabel)}}}const Td={ko:Sr({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:Sr({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:Sr({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":Sr({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":Sr({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:Sr({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:Sr({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:Sr({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":Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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ı"})},gL=Object.entries(Td).map(([t,n])=>({id:t,label:n.languageName}));function vL(){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(Td[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(Td[o])return o}return"en"}function Hx({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(kr,{size:24}),i.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}const yL=["cpu","gpu","memory","vram","network","disk","temp"];function bL({device:t,slotNumber:n,selected:r,updateIndicator:o,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=iC(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(kr,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:La(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})]}),yL.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(BS,{items:l,mode:u})})]})}function wL(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 xL(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:D,showPresentationSpinner:I=!1,remoteDiagnostics:R,diagnosticsMode:_="remote"}){const B=d.useRef(null),F=d.useRef(null),H=d.useRef(0),j=d.useRef(null),Q=iC(t),$=["cpu","gpu","memory","vram"].map(ue=>Q.metrics.find(Fe=>Fe.id===ue)).filter(ue=>!!ue),G=Fv(f),W=h>1,V=D??!!n,X=wL(t)&&!V,ve=I&&t.connected&&!V&&!X,J=KI(t,n,G),z=J>=Tp?100:J/Tp*100,P=J>=Tp?Tp/J*100:100,re={"--screen-aspect":J.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,z)).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 Fe=ue.currentTarget.getBoundingClientRect();return mN(ue.clientX,ue.clientY,Fe)},Se=ue=>gN(ue,N),ae=d.useCallback(()=>{j.current!==null&&(window.cancelAnimationFrame(j.current),j.current=null)},[]),ye=d.useCallback(()=>{const ue=F.current;if(!ue)return;F.current=null;const Fe=Number(ue.input.normalizedX),Xe=Number(ue.input.normalizedY);if(!Number.isFinite(Fe)||!Number.isFinite(Xe))return;k(t.deviceId,{...ue.input,normalizedX:Fe,normalizedY:Xe})&&(H.current=performance.now())},[t.deviceId,k]),Pe=d.useCallback(()=>{j.current===null&&(j.current=window.requestAnimationFrame(()=>{j.current=null,ye()}))},[ye]);d.useEffect(()=>()=>{ae(),F.current=null},[ae]);const de=(ue,Fe)=>{if(!o)return;const Xe={type:Fe,monitorIndex:G,...Z(ue),button:oL(ue.button),...Se(ue)};if(Fe==="pointermove"){const at=performance.now();F.current={input:Xe},at-H.current>=fI&&(ae(),ye()),Pe();return}F.current&&(ae(),ye()),k(t.deviceId,Xe)},Ke=d.useCallback(ue=>{const Fe=document.activeElement;Fe instanceof HTMLElement&&ue.contains(Fe)&&Fe.classList.contains("monitor-cycle-button")&&Fe.blur()},[]);return i.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:re,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=>Ke(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":G,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:G,...Z(ue),deltaX:ue.deltaX,deltaY:ue.deltaY,...Se(ue)}))},onContextMenu:ue=>o&&ue.preventDefault()},`${t.deviceId}:monitor:${G}`)}),!V&&i.jsx("span",{className:"empty-screen",children:i.jsx(kr,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:La(t),children:La(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(ha,{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(Pa,{size:20,"aria-hidden":"true"}):A.state==="failed"?i.jsx(nr,{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-${Q.state}`,children:Q.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${La(t)} status`,children:$.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))})]}),R&&i.jsx(BS,{items:R,mode:_}),W&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${La(t)} display ${G+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(t0,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",G+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 SL({visible:t}){const n=uI;return d.useEffect(()=>{},[n]),null}function CL({runtimeBaseUrl:t=""}){const{session:n,loading:r}=G1();HM(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}=K1(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,$n]).filter(Boolean))],[g,h,y]),[b,S]=d.useState(()=>typeof window<"u"&&window.matchMedia(gw).matches),[k,N]=d.useState(null),[A]=d.useState(tI),[D,I]=d.useState(!1),[R,_]=d.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches);d.useEffect(()=>{if(!g){N(null);return}const m=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),x=()=>_(m.matches||!!window.navigator.standalone),C=T=>{T.preventDefault(),N(T)},E=()=>{N(null),_(!0)};return x(),m.addEventListener("change",x),window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",E),()=>{m.removeEventListener("change",x),window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",E)}},[g]);const B=d.useCallback(async()=>{const m=k;if(!m){A.isIos&&I(!0);return}N(null);try{await m.prompt(),(await m.userChoice).outcome==="accepted"&&_(!0)}catch(x){N(m),console.warn("[LiveDesk] PWA install prompt failed.",x)}},[A.isIos,k]);d.useEffect(()=>{const m=window.matchMedia(gw),x=()=>S(m.matches);return x(),m.addEventListener("change",x),()=>m.removeEventListener("change",x)},[]),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")};if(!b){x();return}m.classList.add("livedesk-mobile-console-active");const C=window.visualViewport;let E=0;const T=()=>{E=0;const K=jN(C,window.innerHeight);m.style.setProperty("--livedesk-mobile-viewport-height",`${K.height}px`),m.style.setProperty("--livedesk-mobile-viewport-top",`${K.offsetTop}px`)},U=()=>{E||(E=window.requestAnimationFrame(T))};return T(),C?.addEventListener("resize",U),C?.addEventListener("scroll",U),window.addEventListener("resize",U),window.addEventListener("orientationchange",U),window.addEventListener("pageshow",U),()=>{E&&window.cancelAnimationFrame(E),C?.removeEventListener("resize",U),C?.removeEventListener("scroll",U),window.removeEventListener("resize",U),window.removeEventListener("orientationchange",U),window.removeEventListener("pageshow",U),x()}},[b]);const[F,H]=d.useState(qI),j=d.useMemo(()=>w.some(m=>!!Zf(m)),[w]),Q=g?!!n:!j||F,{status:$,devices:G,error:W,refresh:V,hubBaseUrl:X}=V1(w,Q,n?.access_token||""),{entitlement:ve,licensed:J,loading:z,error:P,refresh:re}=Q1(n),[we,Z]=d.useState([]),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(""),[de,Ke]=d.useState(""),[ue,Fe]=d.useState(""),[Xe,at]=d.useState(""),[Ee,Ge]=d.useState("idle"),[me,ke]=d.useState(!1),[Je,Me]=d.useState(""),[pe,qe]=d.useState(null),Re=d.useRef(null),[st,jt]=d.useState(""),O=d.useRef("");O.current=ue;const[$e,We]=d.useState(!1),[Et,lt]=d.useState([]),ht=d.useRef(null),[Ze,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=DN());const He=d.useRef(document.visibilityState==="visible"),[Ie,Lt]=d.useState({}),Ye=d.useRef({}),ut=d.useRef(new Set),yt=d.useRef(new Map),_t=d.useRef(new Map),[mt,Vt]=d.useState({}),Ct=d.useMemo(()=>new Set(Object.keys(Ie)),[Ie]),mn=d.useCallback((m,x)=>{if(!m)return;const C={...Ye.current};x?C[m]=x:delete C[m],Ye.current=C,Lt(C)},[]),an=d.useCallback((m,x)=>{m&&Vt(C=>{if(!!C[m]===x)return C;const E={...C};return x?E[m]=!0:delete E[m],E})},[]),va=d.useCallback((m,x)=>{m&&_t.current.set(m,{paused:x,expiresAt:Date.now()+CI})},[]),[kt,hn]=d.useState(""),[en,q]=d.useState(""),[nt,Dt]=d.useState(!1),gn=d.useRef(null),Mr=d.useRef(null);d.useEffect(()=>{kt==="auth"&&n?.access_token&&hn("")},[kt,n?.access_token]);const[Hr,Ar]=d.useState(""),[oe,Ue]=d.useState(null),tt=d.useRef(null),Pt=d.useRef(0),wn=d.useCallback((m,x,C)=>{const E=String(m||"").trim();if(Ar(E),tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),!E){Ue(null);return}const T=++Pt.current;if(Ue({id:T,message:E,tone:x}),!C)return;const U=window.setTimeout(()=>{Ue(K=>K?.id===T?null:K),tt.current===U&&(tt.current=null)},5e3);tt.current=U},[]),Be=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[Tt,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,Un]=d.useState(tL),Qt=pv(Cn),[En,zr]=d.useState(!1),[Ht,Pn]=d.useState(!1),[Ba,ar]=d.useState(!1),[Nr,rr]=d.useState(!1),[Zs,Is]=d.useState(Date.now),Dn=d.useRef(null);d.useEffect(()=>()=>{Dn.current!==null&&window.clearTimeout(Dn.current)},[]);const[on,il]=d.useState(vL),[Ls,vo]=d.useState(!1),[Ai,sr]=d.useState(!1),[Ld,Ha]=d.useState(!1),[$r,ol]=d.useState(UI),[wt]=d.useState(XI),[_n]=d.useState(JI),[yo]=d.useState(QI),[rn,cs]=d.useState(yo.selections),oc=d.useRef({...yo.topologyFingerprints}),Js=d.useRef({}),ll=d.useRef({...yo.selections}),[Bt,Tr]=d.useState(null),[bo,ei]=d.useState({}),ir=d.useRef(new Set),[Ni,ti]=d.useState([]),[Bn,or]=d.useState(Qt),[ni,cl]=d.useState(""),[lc,wo]=d.useState(0),[Ur,qr]=d.useState(0),[xo,Ps]=d.useState(0),[So,za]=d.useState(()=>new Set),ln=d.useRef(new Map),Xn=d.useRef(new Map),$a=d.useRef(new Map),kn=d.useRef(new Map),Fn=d.useRef(null),Ua=d.useRef(new Map),lr=d.useRef(new Set),qa=d.useRef(new Map),ai=d.useRef(new Map),Ma=d.useRef(new Map),Wr=d.useRef(new Map),Ti=d.useRef(new WeakMap),Co=d.useRef(new WeakMap),Ri=d.useRef(""),cr=d.useRef(null),fm=d.useRef(Promise.resolve()),cu=d.useRef(0),ji=d.useRef(null),Rr=d.useRef(null),cc=d.useRef(""),Aa=d.useRef(new Map),ul=d.useRef(null),uc=d.useRef(0),_s=d.useRef(new Map),uu=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),du=d.useRef(new Map),Pd=d.useRef([]),mm=d.useRef(0),[dl,_d]=d.useState({}),Ei=d.useRef(new Map),[fu,dc]=d.useState({}),mu=d.useRef(null),[Fd,Wa]=d.useState(!1),pu=d.useRef(null),hh=d.useRef(0),ri=d.useRef(null),pm=d.useRef(new Map),us=d.useRef(null),Gr=d.useRef(null),Ga=d.useRef(null),si=d.useRef(!1),hm=d.useRef(0),qn=d.useRef(0),ya=d.useRef(""),Od=d.useRef(Promise.resolve()),ko=d.useRef(""),Nt=d.useRef(null),ba=d.useRef(""),Mo=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()),Fs=d.useRef(new Map),Os=d.useRef(new Map),Bs=d.useRef(new Map),Li=d.useRef(new Map),Ao=d.useRef(new Map),oi=d.useRef(new Map),jr=d.useRef(document.visibilityState==="visible"),ds=d.useRef(1),hu=d.useRef([]),[Na,gh]=d.useState(document.visibilityState==="visible"),[ml,vh]=d.useState(0),mc=d.useRef(0),gu=d.useRef(0),Ta=d.useRef(0),Pi=d.useRef(0),vu=d.useRef(0),yu=d.useRef(new Map),pl=d.useRef([]),Bd=d.useRef(new Map),bu=d.useRef(new Map),li=d.useRef(new Map),ci=d.useRef(new Set),_i=d.useCallback(m=>r1(Ti.current,m),[]),Hs=d.useCallback(m=>Dv(Co.current,m),[]),ui=d.useCallback((m,x)=>Zb(Co.current,m,x),[]),Zn=d.useCallback(m=>{const x=Xb(Ti.current,m);return Xb(Co.current,m),x},[]),Vr=d.useCallback((m,x)=>Zb(Ti.current,m,x),[]),No=d.useCallback(m=>Rr.current===m||Fn.current===m?!0:[ln.current,Xn.current,$a.current,kn.current,Aa.current].some(C=>Array.from(C.values()).some(E=>E===m)),[]),wa=d.useCallback(m=>{m&&(Zn(m),ci.current.add(m),o1(m,{isCurrent:No,dispose:vd,schedule:x=>queueMicrotask(()=>{try{x()}finally{ci.current.delete(m)}})}))},[No,Zn]),Ra=d.useCallback(m=>(Zn(m),lh(m,vd)),[Zn]),Fi=d.useCallback(()=>{const m=Rr.current,x=Fn.current,C=[...ci.current];Rr.current=null,Fn.current=null,ci.current.clear(),Ti.current=new WeakMap,Co.current=new WeakMap,Wr.current.clear(),cc.current="",i1([ln.current,Xn.current,$a.current,kn.current,Aa.current],[m,x,...C],vd),ul.current=null,uc.current=0,Ua.current.clear(),lr.current.clear(),qa.current.clear(),ai.current.clear(),Ma.current.clear(),_s.current.clear(),du.current.clear(),Pd.current.length=0,Ei.current.clear(),ut.current.clear()},[]);d.useEffect(()=>()=>{Fi()},[Fi]);const ua=d.useCallback((m,x)=>{const C=la(m,x),E=performance.now();ii.current.delete(C),Di.current.delete(C),Fs.current.delete(C),Os.current.delete(C),oi.current.delete(C),li.current.delete(C),Ei.current.delete(C),_s.current.delete(C),dc(T=>{if(!Object.prototype.hasOwnProperty.call(T,C))return T;const U={...T};return delete U[C],U}),_d(T=>{if(!Object.prototype.hasOwnProperty.call(T,C))return T;const U={...T};return delete U[C],U}),m==="control"?(Bs.current.delete(C),Li.current.set(C,E)):Ao.current.set(C,E)},[]),[Oi,di]=d.useState(null),[yh,Hd]=d.useState(!1),[ty,gm]=d.useState([]),[To,zd]=d.useState("all"),[ja,hl]=d.useState([]),[fs,pc]=d.useState(!1),[vm,wu]=d.useState(!0),hc=d.useRef(null),xu=d.useRef(null),Ro=d.useRef(null),ym=d.useRef(null),Su=d.useRef(!1),Bi=d.useRef(!1),Cu=d.useRef(0),Wn=d.useRef(0),ms=d.useRef(0),da=d.useRef(0),gc=d.useRef(0),jo=d.useRef(""),ps=Tt==="settings",ku=Tt==="pricing",$d=Tt==="doc",Mu=Tt==="support",Hi=Tt==="share-files",Va=Tt==="agents",hs=!ps&&!ku&&!$d&&!Mu&&!Hi&&!Va,dt=Tt==="control",vc=PN(Tt),Ka=Na&&Tt==="wall",Er=d.useRef(Ka);Er.current=Ka;const Kr=vc&&pl.current.length>0,ur=Na&&(Tt==="wall"||dt||Kr),Qa=d.useRef(ur);Qa.current=ur;const Dr=Na&&(dt||Ka),Eo=Na&&(Dr||vc&&(Ee==="connecting"||Ee==="active")),yc=d.useRef({active:ur,epoch:ds.current});yc.current.active!==ur&&(ds.current+=1,yc.current={active:ur,epoch:ds.current}),d.useEffect(()=>{hs||(zr(!1),Pn(!1),ar(!1))},[hs]);const Kt=wt.frameMode==="mode4-h264-atlas",Ir=Xe||_n.frameMode,Gn=Ir!=="mode3-h264-hw"?Math.min(30,_n.fps):_n.fps,cn=G.find(m=>m.deviceId===ye),Yt=cn?.platform,$i=cn?Es(cn,rn[cn.deviceId]):0,Ya=cn?ey(cn,$i):null,Au=xL(Yt)?{maxWidth:1280,maxHeight:720}:Mx,fi=Ir!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Mx,bc={maxWidth:Math.min(fi.maxWidth,Au.maxWidth,_n.maxWidth),maxHeight:Math.min(fi.maxHeight,Au.maxHeight,_n.maxHeight)},gs={maxWidth:Ya?.width?Math.min(bc.maxWidth,Ya.width):bc.maxWidth,maxHeight:Ya?.height?Math.min(bc.maxHeight,Ya.height):bc.maxHeight};d.useEffect(()=>{if($?.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,$?.started]),d.useEffect(()=>{!n?.access_token||!$?.started||$.runtimeRole!=="hub"||!$.deviceId||(async()=>{try{const{data:m,error:x}=await $t.rpc("register_livedesk_device",{p_device_id:$.deviceId,p_device_name:$.deviceName||$.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:$.managerVersion||$.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,$?.deviceId,$?.deviceName,$?.managerPackage,$?.managerVersion,$?.runtimeRole,$?.started]);const pt=d.useMemo(()=>G.filter(m=>m.connected),[G]);d.useEffect(()=>{const m={...Ye.current},x=Date.now();let C=!1;Vt(E=>{const T={...E};let U=!1;for(const K of G){const ee=String(K.liveCapturePause?.token||"").trim(),ie=_t.current.get(K.deviceId);if(ie)if((ie.paused?!!ee:!ee)||ie.expiresAt<=x)_t.current.delete(K.deviceId);else continue;const se=!!ee&&(K.liveCapturePause?.captureStopConfirmed!==!0||K.liveCapturePause?.phase==="stop-unconfirmed");!!T[K.deviceId]!==se&&(U=!0,se?T[K.deviceId]=!0:delete T[K.deviceId])}return U?T:E});for(const E of G){const T=String(E.liveCapturePause?.token||"").trim(),U=String(m[E.deviceId]||""),K=_t.current.get(E.deviceId);if(K)if((K.paused?!!T:!T)||K.expiresAt<=x)_t.current.delete(E.deviceId);else continue;T&&T!==U?(m[E.deviceId]=T,C=!0):!T&&U&&(delete m[E.deviceId],yt.current.delete(E.deviceId),C=!0)}C&&(Ye.current=m,Lt(m))},[G]);const Ui=To==="all"?pt.length:ja.filter(m=>pt.some(x=>x.deviceId===m)).length,Ud=d.useMemo(()=>pt.reduce((m,x)=>Math.max(m,Bx(x.slotNumber)),0),[pt]),Do=Math.max(nI,pt.length,Ud),mi=d.useMemo(()=>{const m=Array(Do).fill(null),x=[];for(const C of pt){const E=Bx(C.slotNumber);E>0&&E<=Do&&!m[E-1]?m[E-1]=C:x.push(C)}for(const C of x){const E=m.findIndex(T=>!T);E<0?m.push(C):m[E]=C}return m},[pt]),qi=d.useMemo(()=>mi.flatMap((m,x)=>m?[{device:m,slotNumber:x+1}]:[]),[mi]),Qr=d.useMemo(()=>pt.map(m=>m.deviceId),[pt]),dr=d.useMemo(()=>new Set(we),[we]),In=d.useMemo(()=>pt.filter(m=>dr.has(m.deviceId)),[pt,dr]),Wi=d.useMemo(()=>G.find(m=>m.deviceId===Se)||In[0]||null,[G,Se,In]),xa=d.useMemo(()=>G.find(m=>m.deviceId===ye)||null,[ye,G]),Ea=xa?Es(xa,rn[xa.deviceId]):0,De=dt?xa:Wi,Gi=d.useMemo(()=>new Set(ja),[ja]),Sa=d.useMemo(()=>To==="all"?pt.map(m=>m.deviceId):pt.filter(m=>Gi.has(m.deviceId)).map(m=>m.deviceId),[pt,Gi,To]),Nu=De?Op(De,"control"):!1,Tu=tl(De?.platform)&&(De?.capabilities?.controlPermission===!1||De?.capabilities?.accessibilityPermission===!1),vs=De?Op(De,"audio")||Op(De,"remoteAudio"):!1,Io=(Array.isArray(De?.capabilities?.agentTools)?De.capabilities.agentTools.map(String):[]).includes("system.power"),Ut=J?ve?.plan==="pro"?"pro":"ltd":"free",Ru=Xc[Ut],Lo=Ru.limit,fr=d.useMemo(()=>new Set(BN(pt,Lo)),[Lo,pt]),qd=!De||fr.has(De.deviceId),gl=Ut==="free",Xt=qd,vl=Ut==="ltd"?`Plus includes up to ${Wf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${qf} Clients. Upgrade to Plus for ${Wf} devices and no ads.`,bm=Ut==="free",ys=Xt&&!!De&&Nu,ju=Xt&&!!De&&vs,bs=d.useMemo(()=>dt?De?[De]:[]:In.length>0?In:De?[De]:[],[De,In,dt]),Da=d.useMemo(()=>bs.filter(m=>fr.has(m.deviceId)),[fr,bs]),Po=Da.some(m=>String(Ie[m.deviceId]||"").startsWith("pending:")||mt[m.deviceId]===!0),mr=!(Da.length>0&&Da.every(m=>{const x=String(Ie[m.deviceId]||"");return!!x&&!x.startsWith("pending:")&&mt[m.deviceId]!==!0}))||Po,yl=d.useMemo(()=>mi.filter(m=>!!m?.connected).slice(0,aL(Gt)).map(m=>m.deviceId),[mi,Gt]),_o=d.useMemo(()=>ur?Ka?Kt||Gt==="list"?Qr:wt.visibleOnlyLive?Ni.length>0?Ni:yl:Qr:pl.current.length>0?pl.current:Qr:[],[yl,Kt,Ni,wt.visibleOnlyLive,Qr,ur,Ka,Gt]),Xa=d.useMemo(()=>zg(_o.filter(m=>fr.has(m))),[fr,_o]);pl.current=Xa;const ws=d.useMemo(()=>Xa.filter(m=>m!==ni&&!Ct.has(m)),[Ct,Xa,ni]),wc=d.useMemo(()=>new Map(pt.map(m=>[m.deviceId,m.platform])),[pt]),xs=d.useMemo(()=>Object.fromEntries(pt.map(m=>[m.deviceId,String(m.sessionId||"").trim()])),[pt]),Ia=HN(Kt,Xa.length),Za=d.useMemo(()=>Kt?ws.filter(m=>_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(wc.get(m))})==="atlas"):[],[Ia,Kt,wc,ws]),pr=d.useMemo(()=>ws.filter(m=>_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(wc.get(m))})==="direct"),[Ia,Kt,wc,ws]),Fo=d.useMemo(()=>{const m=wt.autoStartLive?ws.map(x=>la("wall",x)):[];return Eo&&Xt&&de&&fr.has(de)&&(Ee==="connecting"||Ee==="active"||Ee==="warm")&&m.push(la("control",de)),[...new Set(m)].sort()},[Eo,de,Ee,Xt,fr,wt.autoStartLive,ws]);d.useEffect(()=>{const m=new Set(Xa);za(x=>{let C=!1;const E=new Set;for(const T of x)m.has(T)?E.add(T):C=!0;return C?E:x})},[Xa]);const xc=d.useMemo(()=>{const m=T=>pt.find(U=>U.deviceId===T)||null,x=T=>{const U=m(T);return U?Es(U,rn[T]):0},C=(T,U=x(T))=>T===de&&(Ee==="connecting"||Ee==="active"||Ee==="warm")?kn.current.get(T)||Xn.current.get(T)||null:Kt?Aa.current.get(T)||ln.current.get(T)||null:ln.current.get(T)||null,E=(T,U=x(T))=>{const K=m(T);return`${K?La(K):T} · Monitor ${U+1}`};return{resolveCurrentTarget(){if(dt&&xa){const ie=Ea;return{type:"control",deviceIds:[xa.deviceId],monitorIndex:ie,label:`${La(xa)} · Monitor ${ie+1}`,sourceCanvas:C(xa.deviceId,ie),signature:`control:${xa.deviceId}:${ie}:${_n.frameMode}`}}const T=In.map(ie=>ie.deviceId).filter(ie=>ws.includes(ie)),U=Wi&&ws.includes(Wi.deviceId)?Wi.deviceId:"",K=T.length>0?T:U?[U]:ws,ee=T.length===0&&!U;if(K.length===0)return null;if(K.length===1){const ie=K[0],se=x(ie);return{type:ee?"wall":T.length>1?"selection":"device",deviceIds:K,monitorIndex:se,label:ee?"Wall":E(ie,se),sourceCanvas:ee?null:C(ie,se),signature:`${ee?"wall":"device"}:${ie}:${se}:${Kt?"atlas":"direct"}`}}return{type:T.length>1?"selection":"wall",deviceIds:K,label:T.length>1?`${K.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${T.length>1?"selection":"wall"}:${K.join(",")}:${Gt}`}},getDeviceCanvas:C,composeWall(T,U={}){return UD(T.map(K=>{const ee=x(K);return{deviceId:K,label:E(K,ee),canvas:C(K,ee)}}),U)}}},[pt,xa,de,Ee,_n.frameMode,ln,Kt,rn,Ea,In,dt,ws,Wi,Gt]),Sc=eI({hubUrl:X,sourceRegistry:xc,onToast:Be}),zs=d.useMemo(()=>_N({captureOwnershipActive:Eo,localFeatureAccess:Xt,controlSessionDeviceId:de,planAllowed:fr.has(de),sessionState:Ee,controlFocusVisible:dt,presentationCanvasMounted:Je===de,wallPresentationVisible:Ka,wallPresentationCanvasMounted:ln.current.has(de)||Aa.current.has(de),decoderOwnerExists:kn.current.has(de)})?[de]:[],[Eo,de,Ee,Xt,Je,fr,dt,Ka]),bl=d.useMemo(()=>zg([...Xa,...zs]),[zs,Xa]),Cc=d.useMemo(()=>Px(wt,Gt),[wt,Gt]),Yr=d.useMemo(()=>Px(wt,"large"),[wt]),kc=zN({mode4Enabled:Kt,directMode4WallEnabled:Ia,adaptiveFps:Bn,directDeviceCount:pr.length,adaptive:wt.adaptiveLoadShedding}),On=TN({fps:kc,maxWidth:Yr.maxWidth,maxHeight:Yr.maxHeight,quality:wt.quality},b),Mc=qN({deviceCount:Za.length,targetFps:Bn,adaptive:wt.adaptiveLoadShedding});Kt&&Za.length>0;const Ss=d.useCallback((m,x,C)=>{if(m.width<=0||m.height<=0)return!1;if(m===x)return!0;const E=C?Math.min(1,C.maxWidth/m.width,C.maxHeight/m.height):1,T=Math.max(1,Math.round(m.width*E)),U=Math.max(1,Math.round(m.height*E));(x.width!==T||x.height!==U)&&(x.width=T,x.height=U);const K=x.getContext("2d",{alpha:!1});return K?(K.imageSmoothingEnabled=!0,K.imageSmoothingQuality="low",K.drawImage(m,0,0,m.width,m.height,0,0,x.width,x.height),!0):!1},[]),Cs=d.useCallback((m,x)=>{const C=Math.max(0,Number(x.clientWidth||0)),E=Math.max(0,Number(x.clientHeight||0)),T=Math.max(1,Number(window.devicePixelRatio||1)),U=C>0&&E>0?{maxWidth:Math.ceil(C*T),maxHeight:Math.ceil(E*T)}:void 0;return Ss(m,x,U)},[Ss]),Lr=d.useCallback((m,x,C)=>{if(!uu.current)return;const E=`${m}:${x.deviceId}`,T=du.current.get(E)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};T.bindingKey=uo(x),T.totalPaints+=1,T.lastPaintAt=performance.now(),T.lastFrameSeq=Number(x.frameSeq||0),du.current.set(E,T);const U=++mm.current,K={sequence:U,scope:m,deviceId:x.deviceId,bindingKey:T.bindingKey,frameSeq:T.lastFrameSeq,paintedAt:T.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)};Pd.current[(U-1)%AI]=K},[]),hr=d.useCallback(m=>{m&&za(x=>{if(x.has(m))return x;const C=new Set(x);return C.add(m),C})},[]),Xr=d.useCallback(m=>{m&&za(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,!Ss(x,C))return wa(C),!1;const E=$a.current.get(m);return $a.current.set(m,C),E&&E!==C&&Ra(E),hr(m),!0},[hr,Ss,Ra,wa]),Hn=d.useCallback(m=>{s1($a.current,m,vd)},[]),Vi=d.useCallback((m,x)=>{const C=$a.current.get(m),E=ln.current.get(m)===x||Aa.current.get(m)===x;return Ye.current[m]?(Hn(m),!1):!C||!E||C.width<=0||C.height<=0?!1:Ss(C,x)?!0:(Hn(m),!1)},[Ss,Hn]),$s=d.useCallback((m,x=!1,C)=>{if(Ye.current[m]||!lr.current.has(m))return!1;const E=Math.max(1,Math.min(Qt,Yn.controlWallReuseMaxFps,Gn)),T=performance.now(),U=ai.current.get(m)||0,K=kn.current.get(m)||Xn.current.get(m),ee=ln.current.get(m)||Aa.current.get(m);if(!K||!ee||!ee.isConnected)return!1;const ie=ON({cadenceCredit:qa.current.get(m)||0,targetFps:E,sourceFps:Gn,elapsedSincePaintMs:U>0?T-U:0,nowMs:T,scheduledPaintAtMs:Ma.current.get(m)||0,force:x});if(!ie.shouldPaint)return qa.current.set(m,ie.nextCadenceCredit),!1;const se=Math.max(0,Number(ee.clientWidth||0)),et=Math.max(0,Number(ee.clientHeight||0)),ze=Math.max(1,Number(window.devicePixelRatio||1)),_e=se>0&&et>0?{maxWidth:Math.min(Cc.maxWidth,Math.ceil(se*ze)),maxHeight:Math.min(Cc.maxHeight,Math.ceil(et*ze))}:Cc;return Ss(K,ee,_e)?(qa.current.set(m,ie.nextCadenceCredit),ie.nextScheduledPaintAtMs>0&&Ma.current.set(m,ie.nextScheduledPaintAtMs),ai.current.set(m,performance.now()),ie.sourceCadencePassthrough&&(qa.current.delete(m),Ma.current.delete(m)),C&&Lr("wall-reuse-visible",C),hr(m),Hn(m),!0):!1},[Gn,Cc,hr,Ss,Lr,Hn,Qt]);d.useEffect(()=>{Ri.current=ni},[ni]);const Ac=d.useCallback((m,x)=>{const C=ri.current;if(!C||C.deviceId!==m)return;const E=Date.now();pm.current.set(m,{...C,source:x,completedAtEpochMs:E,durationMs:Math.max(0,performance.now()-C.startedAt)}),ri.current=null},[]),Oo=d.useCallback((m,x)=>{const C=ln.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(ln.current.set(m,x),C&&C!==x&&wa(C),Ye.current[m]){Hn(m),Ra(x),Xr(m);return}$a.current.get(m)&&Vi(m,x)&&hr(m),$s(m,!0);return}if(C&&Qa.current&&pl.current.includes(m)){pi(m,C),ln.current.delete(m),wa(C);return}ln.current.delete(m),Hn(m),wa(C),Xr(m)},[Xr,hr,$s,Vi,pi,Ra,Hn,wa]),Eu=d.useCallback((m,x)=>{const C=Xn.current.get(m);if(x){Xn.current.set(m,x),Me(m),C&&C!==x&&wa(C);const E=de===m&&me?kn.current.get(m):null;E&&Cs(E,x)&&m===ye&&(Ac(m,"warm-reuse"),Wa(!0)),E&&E!==x&&FN({decodeWidth:E.width,decodeHeight:E.height,presentationCssWidth:x.getBoundingClientRect().width,presentationCssHeight:x.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:gs.maxWidth,sourceHeight:gs.maxHeight})&&(kn.current.set(m,x),wa(E));return}Xn.current.delete(m),Me(E=>E===m?"":E),wa(C)},[Ac,ye,de,me,gs.maxHeight,gs.maxWidth,Cs,wa]),Nc=d.useCallback((m,x,C)=>{const E=performance.now(),T=la(m,C.deviceId);let U=C;if(m==="control"&&C.visualChanged){const ie=String(x.inputFeedbackEventId||""),se=Number(x.inputFeedbackInputSeq||0),et=Number(x.inputFeedbackIssuedAtEpochMs||0),ze=Number(x.browserReceivedEpochMs||0),_e=Bd.current.get(C.deviceId)||"",xt=et>0?Math.max(0,Date.now()-et):Number.POSITIVE_INFINITY;if(ie.length>0&&se>0&&ie!==_e&&xt<=Bg){const vt=bu.current.get(C.deviceId)||[];vt.push(xt),vt.length>vx&&vt.splice(0,vt.length-vx),bu.current.set(C.deviceId,vt),U={...C,inputFeedbackSeq:se,inputFeedbackMs:xt,inputFeedbackAt:E,inputFeedbackExact:!0,inputFeedbackEventId:ie,inputFeedbackInputType:x.inputFeedbackInputType,inputFeedbackInputToFrameMs:ze>0?Math.max(0,ze-et):void 0,inputFeedbackFrameToPaintMs:ze>0?Math.max(0,Date.now()-ze):void 0,inputFeedbackAgentApplyMs:x.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:x.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:vt.length,inputFeedbackP50Ms:zf(vt,.5),inputFeedbackP95Ms:zf(vt,.95)},Bd.current.set(C.deviceId,ie),yu.current.set(C.deviceId,se)}else if(!ie){const vt=nN(C.deviceId),bn=yu.current.get(C.deviceId)||0,Ln=vt?E-vt.sentAt:Number.POSITIVE_INFINITY;vt&&vt.inputSeq>bn&&Ln<=Bg&&(U={...C,inputFeedbackSeq:vt.inputSeq,inputFeedbackMs:Math.max(0,Ln),inputFeedbackAt:E,inputFeedbackExact:!1},yu.current.set(C.deviceId,vt.inputSeq))}}Di.current.set(T,E),oi.current.delete(T);const K=_s.current.get(T)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:E,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},ee=uo(x);K.bindingKey!==ee&&(K.bindingKey=ee,K.lastAt=void 0,K.lastFrameSeq=void 0,K.sampleChangedFrames=0,K.sampleDecoderInputBase=Number(C.decoderInputCount||0),K.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Np(K,E)),m==="control"&&U.inputFeedbackMs===void 0&&K.lastInfo?.inputFeedbackMs!==void 0&&K.lastInfo.inputFeedbackAt!==void 0&&E-K.lastInfo.inputFeedbackAt<=Bg&&(U={...U,inputFeedbackSeq:K.lastInfo.inputFeedbackSeq,inputFeedbackMs:K.lastInfo.inputFeedbackMs,inputFeedbackAt:K.lastInfo.inputFeedbackAt,inputFeedbackExact:K.lastInfo.inputFeedbackExact,inputFeedbackEventId:K.lastInfo.inputFeedbackEventId,inputFeedbackInputType:K.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:K.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:K.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:K.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:K.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:K.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:K.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:K.lastInfo.inputFeedbackP95Ms}),K.totalFrames+=1,K.sampleFrames+=1,Ax(K,E,U.frameSeq),U.visualChanged&&(K.totalChangedFrames+=1,K.sampleChangedFrames+=1),K.lastInfo=U,_s.current.set(T,K)},[]),wl=d.useCallback((m,x)=>{if(Ye.current[m.deviceId]||Ri.current===m.deviceId)return;Nc("wall",m,x);const C=me&&de===m.deviceId,E=ln.current.get(m.deviceId)||Aa.current.get(m.deviceId);uu.current&&!dt&&!C&&E?.isConnected&&Lr("wall-visible",m,x),m.kind==="live"&&(hr(m.deviceId),Hn(m.deviceId)),Ri.current!==m.deviceId&&!C&&(lr.current.delete(m.deviceId),qa.current.delete(m.deviceId),ai.current.delete(m.deviceId),Ma.current.delete(m.deviceId))},[de,me,hr,Nc,Lr,Hn,dt]),Du=d.useCallback((m,x)=>{if(Ye.current[m.deviceId]||Kn(Ga.current,Nt.current)||!kg(m,Nt.current))return;Nc("control",m,x),jt(K=>K&&"");const C=kn.current.get(m.deviceId),E=Xn.current.get(m.deviceId);let T=!1;C&&C.width>0&&C.height>0&&(E&&dt&&m.deviceId===ye&&(T=Cs(C,E),T&&Lr("control-visible",m,x)),Ua.current.set(m.deviceId,tu(m)),lr.current.add(m.deviceId),m.deviceId===de&&(ke(!0),Ge(K=>K==="connecting"?"active":K)),$s(m.deviceId,!1,m));const U=pu.current;!U||!kI(U,m)||!T||(Ac(m.deviceId,"fresh-frame"),Wa(!0))},[Ac,ye,de,$s,Cs,Nc,Lr,dt]),sa=d.useCallback((m,x)=>{const C=performance.now(),E=la(m,x.deviceId);ii.current.set(E,C),Os.current.delete(E),li.current.delete(E),m==="control"?Bs.current.delete(E):Ao.current.delete(E);const T=Ei.current.get(E)||{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:[]},U=uo(x);if(T.bindingKey!==U&&(T.bindingKey=U,T.lastAt=void 0,T.lastFrameSeq=void 0,T.lastContentHash=void 0,T.sampleBytes=0,T.sampleH264Frames=0,T.sampleTinyFrames=0,T.sampleRepeatedFrames=0,T.sourceSendIntervalsMs.length=0,Np(T,C)),T.totalFrames+=1,T.sampleFrames+=1,T.sampleBytes+=Math.max(0,Number(x.byteLength||0)),String(x.frameMode||x.mode||x.codec||x.mimeType||"").toLowerCase().includes("h264")){T.sampleH264Frames+=1,Number(x.byteLength||0)<=bI&&(T.sampleTinyFrames+=1);const se=String(x.contentHash||"");se&&T.lastContentHash===se&&(T.sampleRepeatedFrames+=1),T.lastContentHash=se}const ie=Number(x.agentSendGapMs||0);ie>0&&ie<1e3&&eC(T.sourceSendIntervalsMs,ie),T.lastFrame=tu(x),Ax(T,C,x.frameSeq),Ei.current.set(E,T)},[]);d.useEffect(()=>{const m=new Set(Fo);for(const E of _s.current.keys())m.has(E)||_s.current.delete(E);for(const E of Ei.current.keys())m.has(E)||Ei.current.delete(E);const x=E=>{const T=Object.entries(E).filter(([U])=>m.has(U));return T.length===Object.keys(E).length?E:Object.fromEntries(T)};if(_d(x),dc(x),m.size===0)return;const C=window.setInterval(()=>{const E=performance.now(),T={},U={};for(const K of m){const ee=_s.current.get(K);if(ee){const ze=Math.max(1,E-ee.sampleStartedAt);T[K]={bindingKey:ee.bindingKey||"",totalFrames:ee.totalFrames,totalChangedFrames:ee.totalChangedFrames,framesPerSecond:ee.sampleFrames*1e3/ze,changedFramesPerSecond:ee.sampleChangedFrames*1e3/ze,averageIntervalMs:ee.intervalCount>0?ee.intervalSumMs/ee.intervalCount:0,minIntervalMs:Number.isFinite(ee.minIntervalMs)?ee.minIntervalMs:0,maxIntervalMs:ee.maxIntervalMs,p95IntervalMs:zf(ee.intervalSamplesMs,.95),intervalCount:ee.intervalCount,seqGapCount:ee.seqGapCount,maxSeqGap:ee.maxSeqGap,decoderInputFps:Math.max(0,(Number(ee.lastInfo?.decoderInputCount||0)-ee.sampleDecoderInputBase)*1e3/ze),decoderOutputFps:Math.max(0,(Number(ee.lastInfo?.decoderOutputCount||0)-ee.sampleDecoderOutputBase)*1e3/ze),sampleMs:ze,lastInfo:ee.lastInfo},ee.sampleDecoderInputBase=Number(ee.lastInfo?.decoderInputCount||0),ee.sampleDecoderOutputBase=Number(ee.lastInfo?.decoderOutputCount||0),ee.sampleChangedFrames=0,Np(ee,E)}const ie=Ei.current.get(K);if(!ie)continue;const se=Math.max(1,E-ie.sampleStartedAt),et=ie.lastFrame?tu(ie.lastFrame):void 0;ie.lastFrame=et,U[K]={totalFrames:ie.totalFrames,framesPerSecond:ie.sampleFrames*1e3/se,averageIntervalMs:ie.intervalCount>0?ie.intervalSumMs/ie.intervalCount:0,minIntervalMs:Number.isFinite(ie.minIntervalMs)?ie.minIntervalMs:0,maxIntervalMs:ie.maxIntervalMs,p95IntervalMs:zf(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((ze,_e)=>ze+_e,0)/ie.sourceSendIntervalsMs.length:0,sourceSendP95Ms:zf(ie.sourceSendIntervalsMs,.95),sourceSendSampleCount:ie.sourceSendIntervalsMs.length,sampleMs:se,lastFrame:et},ie.sampleBytes=0,ie.sampleH264Frames=0,ie.sampleTinyFrames=0,ie.sampleRepeatedFrames=0,ie.sourceSendIntervalsMs.length=0,Np(ie,E)}_d(T),dc(U)},1e3);return mu.current=C,()=>{window.clearInterval(C),mu.current===C&&(mu.current=null)}},[Fo]);const Pr=d.useCallback(m=>{const x=m.deviceId,C=uo(m);if(Ye.current[x]||Ri.current===x||m.currentGenerationVerified!==!0||Wr.current.get(x)!==C)return;sa("wall",m);const E=ln.current.get(x);if(!E)return;const T=_i(E),U=Hs(E),K=()=>ln.current.get(x)!==E||!Vr(E,T)||!!Ye.current[x]||Ri.current===x||Wr.current.get(x)!==C,ee=()=>K()||!ui(E,U),ie=WN(Kt,wt.h264DecodeAcceleration);wg(E,m,ee,wl,ie.acceleration,ie.latencyMode,K).catch(()=>{})},[_i,ui,Vr,Hs,wl,Kt,sa,wt.h264DecodeAcceleration]),hi=d.useCallback(m=>{const x=m.deviceId;if(Ye.current[x]||Kn(Ga.current,Nt.current)||!kg(m,Nt.current))return;let C=kn.current.get(x);if(!C){const _e=Xn.current.get(x),xt=Fn.current;C=_e||xt||document.createElement("canvas"),_e&&xt&&xt!==_e&&Ra(xt),Fn.current=null,C!==_e&&C.setAttribute("aria-hidden","true"),kn.current.set(x,C)}const E=C,T=m,U=_i(E),K=Hs(E),ee=()=>kn.current.get(x)!==E||!Vr(E,U)||!!Ye.current[x]||!kg(T,Nt.current),ie=()=>ee()||!ui(E,K),se=O.current,et=String(m.frameMode||m.mode||m.codec||m.mimeType||"").toLowerCase().includes("h264");et||sa("control",m);const ze=wg(E,m,ie,Du,_n.h264DecodeAcceleration,"interactive",ee);et&&sa("control",m),ze.catch(_e=>{O.current!==se||kn.current.get(x)!==E||!ui(E,K)||ee()||de!==x||jt(_e instanceof Error?_e.message:String(_e||"Control H.264 decode failed"))})},[_i,ui,Vr,Hs,de,_n.h264DecodeAcceleration,Du,sa,Ra]),Wd=d.useCallback(m=>{const x=Rr.current;Rr.current=m,x&&x!==m&&wa(x),mc.current=0,gu.current=0,Ta.current=0,Pi.current=0,vu.current=0,uc.current=0},[wa]),Bo=d.useCallback(()=>{const m=new Set,x=Rr.current,C=ul.current;if(!x||!C||x.width<=0||x.height<=0||uc.current!==C.layoutVersion)return m;for(const E of C.tiles){if(Ye.current[E.deviceId])continue;const T=Aa.current.get(E.deviceId);if(!T||E.width<=0||E.height<=0)continue;const U=Math.max(1,Math.round(E.width)),K=Math.max(1,Math.round(E.height)),ee=wI,ie=xI;(T.width!==ee||T.height!==ie)&&(T.width=ee,T.height=ie);const se=T.getContext("2d",{alpha:!1});if(se){se.imageSmoothingEnabled=!0,se.imageSmoothingQuality="high";try{se.drawImage(x,Math.round(E.x),Math.round(E.y),U,K,0,0,ee,ie),m.add(E.deviceId)}catch{}}}return m},[]),Ki=d.useCallback((m,x)=>{const C=Aa.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(Aa.current.set(m,x),C&&C!==x&&wa(C),Ye.current[m]){Hn(m),Ra(x),Xr(m);return}$a.current.get(m)&&Vi(m,x)&&hr(m),window.requestAnimationFrame(()=>{Bo().has(m)&&Hn(m)}),window.requestAnimationFrame(()=>$s(m,!0));return}Aa.current.delete(m),Hn(m),wa(C),Xr(m)},[Xr,hr,Bo,$s,Vi,pi,Ra,Hn,wa]),gr=d.useCallback((m,x)=>{Ta.current=performance.now(),uc.current=Number(m.layoutVersion||0),Bo();const C=ul.current?.tiles||[],E=C.length>0?Math.round(m.byteLength/C.length):m.byteLength;for(const T of C){if(Ye.current[T.deviceId])continue;const U={...m,deviceId:T.deviceId,width:T.width,height:T.height,sourceWidth:T.width,sourceHeight:T.height,byteLength:E};wl(U,{...x,deviceId:T.deviceId,width:T.width,height:T.height,byteLength:E}),Ri.current===T.deviceId&&$s(T.deviceId,!0)}},[wl,Bo,$s]),Vn=d.useCallback(m=>{const x=performance.now();mc.current<=0&&(mc.current=x),gu.current=x;const C=Rr.current;if(!C)return;const E=uo(m);cc.current!==E&&(cc.current=E,Zn(C));const T=_i(C),U=Hs(C),K=()=>Rr.current!==C||cc.current!==E||!Vr(C,T),ee=()=>K()||!ui(C,U),ie=ul.current?.tiles||[],se=ie.length>0?Math.round(m.byteLength/ie.length):m.byteLength;for(const et of ie)Ye.current[et.deviceId]||sa("wall",{...m,deviceId:et.deviceId,width:et.width,height:et.height,sourceWidth:et.width,sourceHeight:et.height,byteLength:se});wg(C,m,ee,gr,void 0,"smooth",K).catch(()=>{})},[_i,ui,Vr,Hs,gr,sa,Zn]),Tc=d.useCallback(m=>{if(m.streamPurpose!=="wall"||Ye.current[m.deviceId])return;const x=uo(m);Wr.current.get(m.deviceId)!==x&&(Wr.current.set(m.deviceId,x),Zn(ln.current.get(m.deviceId)))},[Zn]),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:cI,forceRestart:ml>0,forceRestartToken:ml>0?`document-presentation-resume-${ml}`:"",restartReason:ml>0?"document-presentation-resume":"",connectionSessionIds:xs,monitorSelections:rn,onFrame:Pr,onStreamReady:Tc}),[xs,ml,Pr,Tc,Kt,rn,wt.frameMode,On.fps,On.maxHeight,On.maxWidth,On.quality]),Ft=d.useCallback(m=>{const x=Nt.current;if(Ye.current[m.deviceId]||!x||Kn(Ga.current,x)||x.deviceId!==m.deviceId||m.deviceId!==de||m.streamPurpose!=="control"||m.monitorIndex!==Ea)return;const C=pt.find(T=>T.deviceId===m.deviceId);if(!C?.sessionId||C.sessionId!==m.sessionId)return;const E=Re.current;(!E||uo(E)!==uo(m))&&Zn(kn.current.get(m.deviceId)),Nt.current=Cg(x.deviceId,x.transitionGeneration,m),Re.current=m,qe(m),Ge(T=>T==="connecting"?"active":T)},[pt,de,Zn,Ea]);d.useEffect(()=>{Zn(kn.current.get(de)),Re.current=null,qe(null)},[de,ue,Ir,Zn,Ea]);const sn=ue?`${ue}-monitor-${Ea}`:"",Jn=d.useMemo(()=>({fps:Gn,maxWidth:gs.maxWidth,maxHeight:gs.maxHeight,quality:_n.quality,mode:Ir,frameMode:Ir,streamPurpose:"control",forceRestart:sn!=="",forceRestartToken:sn,restartReason:sn?"control-session-or-monitor-change":"",connectionSessionIds:xs,monitorSelections:rn,onFrame:hi,onStreamReady:Ft}),[xs,sn,_n.quality,hi,Gn,Ir,gs.maxHeight,gs.maxWidth,Ft,rn]),{frames:Rc,state:Us,error:Qi,stats:qs,restartLive:Yi,reconnectLive:Ho}=iw(pr,wt.autoStartLive&&pr.length>0,X,gi);d.useEffect(()=>{const m=new Set(pr);for(const x of Wr.current.keys())m.has(x)||(Wr.current.delete(x),Zn(ln.current.get(x)))},[pr,Zn]);const{frame:xl,layout:vn,state:jc,stats:Gd,refreshInputs:Vd}=oN(Za,Kt&&wt.autoStartLive&&Za.length>0,X,{fps:Yn.atlasOutputFps,inputFps:Mc,width:1920,height:1080,tileWidth:Yr.maxWidth,tileHeight:Yr.maxHeight,captureDeviceIds:Za,connectionSessionIds:xs,monitorSelections:rn,onFrame:Vn});d.useEffect(()=>{ul.current=vn,vn&&window.requestAnimationFrame(Bo)},[vn,Bo]),d.useEffect(()=>{if(!Kt||jc!=="open"){mc.current=0,gu.current=0,Ta.current=0;return}const m=window.setInterval(()=>{const x=Rr.current,C=performance.now();if(!x||document.visibilityState!=="visible"||C-Ii.current<Og)return;const E=gu.current,T=mc.current;if(E<=0||T<=0||C-E>500)return;const U=Ta.current||T,K=C-U;if(K>=pI&&C-vu.current>=gI){yd(x)&&(vu.current=C,Pi.current=C);return}K>=mI&&C-Pi.current>=hI&&ZA(x)&&(Pi.current=C)},250);return()=>window.clearInterval(m)},[jc,Kt]);const{frames:Sl,state:Kd,error:zo,stats:Qd,restartLive:Cl,reconnectLive:ia}=iw(zs,zs.length>0,X,Jn);d.useEffect(()=>{const m=ll.current,x=new Set([...Object.keys(m),...Object.keys(rn)]);for(const C of x){const E=Math.max(0,Math.floor(Number(m[C])||0)),T=Math.max(0,Math.floor(Number(rn[C])||0));E!==T&&(Wr.current.delete(C),Zn(ln.current.get(C)),Zn(kn.current.get(C)),Zn(Aa.current.get(C)),ua("wall",C),ua("control",C),yd(ln.current.get(C)||null),yd(kn.current.get(C)||null))}x.size>0&&(Zn(Rr.current),yd(Rr.current)),ll.current={...rn}},[rn,ua,Zn]);const Mn=d.useMemo(()=>{const m=(C,E)=>{const T=pt.find(K=>K.deviceId===C),U=T?Es(T,rn[C]):0;return!Number.isFinite(Number(E.monitorIndex))||Number(E.monitorIndex)===U},x=new Map;for(const[C,E]of Rc.entries())m(C,E)&&x.set(C,E);if(Kt&&xl&&Za.length>0){const C=new Map((vn?.tiles||[]).map(T=>[T.deviceId,T])),E=Math.max(1,C.size);for(const T of Za){const U=C.get(T);U&&x.set(T,{...xl,deviceId:T,width:U.width,height:U.height,sourceWidth:U.width,sourceHeight:U.height,byteLength:Math.round(xl.byteLength/E)})}}for(const[C,E]of Sl.entries())m(C,E)&&x.set(C,E);for(const C of _o){if(!lr.current.has(C)||x.has(C))continue;const E=Ua.current.get(C);E&&m(C,E)&&x.set(C,E)}return x},[xl,vn,pt,Sl,Za,Kt,rn,Rc,_o,xo]),kl=dt&&zs.length>0?Kd:Za.length>0?jc:Us,Xi=dt&&zs.length>0?Qd:Za.length>0?Gd:qs;d.useCallback((m,x="browser-stale")=>{const C=Yi(m,x),E=Cl(m,x);return C||E},[Cl,Yi]),d.useEffect(()=>{Kt&&Za.length>0&&!dt&&Vd()},[Za.length,Kt,Vd,dt]);const vi=d.useCallback((m,x,C)=>{const E=x==="control"?kn.current.get(m)||null:ln.current.get(m)||null;if(!E)return!1;yd(E);const T=performance.now();return oi.current.set(la(x,m),T),!0},[]),Ml=d.useCallback(m=>{if(Ir!=="mode3-h264-hw"||!de||Xe)return!1;const x=pt.find(ee=>ee.deviceId===de)||xa,C=String(x?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const E="mode5-lzo-delta",T=la("control",de),U=performance.now();Li.current.set(T,U),ii.current.delete(T),Di.current.delete(T),Fs.current.delete(T),Bs.current.delete(T),li.current.delete(T),yd(kn.current.get(de)||null),ia([de],"control-decode-fallback"),at(E),Fe(`control-${E}-fallback-${de}-${Date.now()}`),ke(!1),Wa(!1);const K=m==="no first frame"||m==="control-first-frame-timeout";return jt(ee=>ee||(K?`Control frame transport timeout; retrying Control with Mode 5 (${m})`:`H.264 decode failed; retrying Control with Mode 5 (${m})`)),Ge("connecting"),!0},[pt,xa,de,Xe,Ir,ia]);d.useEffect(()=>{const m=dt?xa:null;if(m){pu.current={deviceId:m.deviceId,monitorIndex:Ea,frameMode:Ir,startedAtEpochMs:Date.now()},Wa(de===m.deviceId&&me);return}pu.current=null,Wa(!1)},[xa?.sessionId,ye,de,me,Ir,Ea,dt]);const Ws=d.useCallback(async(m,x)=>{const C=String(x.streamId||"").trim(),E=String(x.streamPurpose||"").trim(),T=String(x.sessionId||"").trim(),U=String(x.commandId||"").trim(),K=Number(x.captureGeneration||0),ee=Number(x.monitorIndex??-1);if(!C||!["wall","atlas"].includes(E)||!T||!U||!Number.isSafeInteger(K)||K<=0||!Number.isSafeInteger(ee)||ee<0)throw new Error("wall-start-owner-incomplete");const ie=performance.now()+3e3;for(;;){const se=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:E,expectedSessionId:T,expectedCommandId:U,expectedCaptureGeneration:K,expectedMonitorIndex:ee,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},X);if(se?.ok===!1)throw new Error(se.error||"revoked-wall-start-stop-failed");if(se?.captureStopConfirmed===!0||se?.alreadyStopped===!0||se?.staleOwner===!0)return se;if(se?.presentationOwnerActive===!0||se?.retainedForPresentation===!0){if(jr.current&&Qa.current)return se;if(performance.now()<ie){await new Promise(et=>window.setTimeout(et,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[X]),Gs=d.useCallback(async m=>{if(Ye.current[m])throw new Error("LIVE_CAPTURE_PAUSED");if(!jr.current||!Qa.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const x=ds.current,C=G.find(K=>K.deviceId===m);_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(C?.platform)});const E=C?Es(C,rn[m]):0,T={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:E},U=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/start`,{method:"POST",body:JSON.stringify(T)},X);if(U?.ok===!1)throw new Error(U.error||"wall-stream-start-failed");return x!==ds.current||!jr.current||!Qa.current?(await Ws(m,U),{...U,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):U},[Mc,G,Ia,X,Kt,rn,Ws,wt.frameMode,Yr.maxHeight,Yr.maxWidth,On.fps,On.maxHeight,On.maxWidth,On.quality]),Iu=d.useCallback(async m=>{const x=G.find(E=>E.deviceId===m);_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,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},[G,Ia,X,Kt]),Lu=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]),Ja=d.useCallback((m,x={})=>{Ga.current?.deviceId===m&&(Ga.current=null);const C=kn.current.get(m);if(C){const T=$a.current.has(m)||ln.current.has(m)||Aa.current.has(m);x.preservePresentation!==!1&&!T&&pi(m,C),kn.current.delete(m),Ra(C),!(Xn.current.get(m)||ln.current.get(m)||Aa.current.get(m))&&!Fn.current&&(Fn.current=C)}const E=Xn.current.get(m);E&&vd(E),Ua.current.delete(m),lr.current.delete(m),qa.current.delete(m),ai.current.delete(m),Ma.current.delete(m)},[pi,Ra]),Ec=d.useCallback(m=>{const x=[la("wall",m),la("control",m)];for(const C of x){const E=Ei.current.get(C);E?.lastFrame&&(E.lastFrame=tu(E.lastFrame))}dc(C=>{let E=!1;const T={...C};for(const U of x){const K=C[U];!K?.lastFrame||K.lastFrame.payload.byteLength===0||(T[U]={...K,lastFrame:tu(K.lastFrame)},E=!0)}return E?T:C})},[]),Pu=d.useCallback(m=>{Wr.current.delete(m),Hn(m),Ja(m,{preservePresentation:!1});const x=new Set;for(const C of[Xn.current.get(m),ln.current.get(m),Aa.current.get(m)])C&&x.add(C);for(const C of x)Ra(C);Xr(m),de===m&&(pu.current=null,Wa(!1),ke(!1)),ut.current.add(m),Ec(m)},[Xr,de,Ra,Ja,Ec,Hn]);d.useEffect(()=>{const m=new Set(Object.keys(Ie));for(const x of m)ut.current.has(x)||Pu(x);for(const x of ut.current)m.has(x)||ut.current.delete(x)},[Pu,Ie]);const $o=d.useCallback(m=>{const x=hw(fm.current,m);return fm.current=x.tail,x.result},[]),_r=d.useCallback(m=>{const x=hw(Od.current,m);return Od.current=x.tail,x.result},[]),Fr=d.useCallback(m=>{cr.current=m,cu.current=0;const x=m?.deviceId||"";Ri.current=x,cl(x),x&&lr.current.add(x)},[]),Zi=d.useCallback(m=>$o(async()=>{if(Ye.current[m.deviceId])return!1;const x=cr.current;return!Kn(x,m)||!mp(m.deviceId,m,Nt.current)?!1:(await Gs(m.deviceId),Kn(cr.current,m)&&Fr(null),!0)}),[Fr,$o,Gs]),Yd=d.useCallback((m,x,C)=>$o(async()=>{const E=cr.current;if(Kn(E,m))return C.stoppedWallDeviceId=m.deviceId,!0;if(E)if(Ye.current[E.deviceId])Kn(cr.current,E)&&Fr(null);else{if(!mp(E.deviceId,E,Nt.current))return!1;await Gs(E.deviceId),Kn(cr.current,E)&&Fr(null)}if(!x())return!1;if(await Iu(m.deviceId),C.stoppedWallDeviceId=m.deviceId,!x()){if(mp(C.stoppedWallDeviceId,m,Nt.current))try{await Gs(C.stoppedWallDeviceId)}catch(T){throw Fr(m),T}finally{C.stoppedWallDeviceId=""}return!1}return vd(ln.current.get(m.deviceId)||null),Fr(m),!0}),[Fr,$o,Gs,Iu]),_u=d.useCallback(async(m,x)=>{if(x.stoppedWallDeviceId){if(Kn(cr.current,m)){try{await Zi(m)}catch(C){Be(C instanceof Error?C.message:String(C))}finally{x.stoppedWallDeviceId=""}return}await $o(async()=>{if(!x.stoppedWallDeviceId||!mp(x.stoppedWallDeviceId,m,Nt.current))return;const C=x.stoppedWallDeviceId;try{await Gs(C)}catch(E){Fr(m),Be(E instanceof Error?E.message:String(E))}finally{x.stoppedWallDeviceId=""}})}},[Fr,$o,Zi,Be,Gs]),Or=d.useCallback(async(m,x,C={})=>{const E=C.allowStopFailure===!0,T=C.resumeWall!==!1;try{await Lu(m.deviceId,x)}catch(U){if(!E)throw U}if(!Kn(Nt.current,m))return!1;if(Nt.current=null,Re.current=null,qe(null),Ja(m.deviceId),ke(!1),Fe(""),at(""),jt(""),Ke(U=>U===m.deviceId?"":U),!T)return Kn(cr.current,m)&&Fr(null),!0;try{await Zi(m)}catch(U){Be(U instanceof Error?U.message:String(U))}return!0},[Fr,Ja,Zi,Be,Lu]),Xd=(Na&&dt&&Xt&&ye&&!Ct.has(ye)&&pt.find(m=>m.deviceId===ye)||null)?.deviceId||"";d.useEffect(()=>{ko.current=Xd},[Xd]),d.useEffect(()=>{const m=ye&&pt.find(U=>U.deviceId===ye)||null;if(!Na||!dt||!Xt||!m){ya.current&&(++qn.current,ya.current="");return}if(Ye.current[m.deviceId]){ya.current&&(++qn.current,ya.current=""),de===m.deviceId&&Ge("paused");return}if(ba.current){if(ba.current===m.deviceId)return;ba.current=""}if(de===m.deviceId&&(Ee==="active"||Ee==="warm"||Ee==="connecting")){Ge(U=>U==="warm"?"active":U);return}if(ya.current===m.deviceId)return;const x=++qn.current,C=Cg(m.deviceId,x,{sessionId:m.sessionId,monitorIndex:Ea});ya.current=m.deviceId;const E={stoppedWallDeviceId:""},T=()=>x===qn.current&&ko.current===C.deviceId;_r(async()=>{if(!T())return;const U=Nt.current;if(U){Ge("stopping");try{await Or(U,"control-session-switch")}catch(ie){T()&&(Ge("error"),Be(ie instanceof Error?ie.message:String(ie)));return}if(!T()){Nt.current||Ge("idle");return}}try{if(!await Yd(C,T,E)||!T()){await _u(C,E),Nt.current||Ge("idle");return}}catch(ie){await _u(C,E),T()&&(Ge("error"),Be(ie instanceof Error?ie.message:String(ie)));return}if(!T()){await _u(C,E);return}Nt.current=C,Ga.current=null,ba.current="",Mo.current=null,fl.current=0,fc.current="",E.stoppedWallDeviceId="";const K=la("control",C.deviceId),ee=`control-session-${x}-${C.deviceId}`;Li.current.set(K,performance.now()),ii.current.delete(K),Di.current.delete(K),li.current.delete(K),Bs.current.delete(K),at(""),jt(""),Fe(ee),Ke(C.deviceId),ke(!1),Ge("connecting")}).catch(U=>{T()&&(Ge("error"),Be(U instanceof Error?U.message:String(U)))}).finally(()=>{qn.current===x&&ya.current===C.deviceId&&(ya.current="")})},[pt,ye,de,Ee,Na,_r,Xt,Yd,_u,Ea,Be,dt,Or,Ie]),d.useEffect(()=>{if(!de||pt.some(C=>C.deviceId===de))return;const m=de;++qn.current,ya.current="";const x=Nt.current;Ge("stopping"),_r(async()=>{x&&x.deviceId===m?await Or(x,"control-device-disconnected",{allowStopFailure:!0}):(Ja(m),Ke(C=>C===m?"":C)),Nt.current||Ge("idle")})},[pt,de,_r,Ja,Or]),d.useEffect(()=>{if(Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),!Ka||dt||!de||Ye.current[de]||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm")return;const m=de,x=Nt.current;if(!x||x.deviceId!==m)return;const C=window.setTimeout(()=>{Gr.current===C&&(Gr.current=null);const E=Nt.current;if(ko.current||Ye.current[m]||!Kn(E,x))return;Ga.current=x;const T=++qn.current;ya.current="",Ge("stopping"),_r(async()=>{if(T!==qn.current||ko.current||!Kn(Nt.current,x)){Kn(Ga.current,x)&&(Ga.current=null),Kn(Nt.current,x)&&ko.current===m&&Ge("active");return}try{await Or(x,"control-session-wall-downshift")}catch(U){Kn(Ga.current,x)&&(Ga.current=null),T===qn.current&&!ko.current&&Kn(Nt.current,x)&&(Ge("active"),Be(U instanceof Error?U.message:String(U)));return}Ga.current=null,T===qn.current&&!Nt.current&&Ge("idle")})},yI);return Gr.current=C,()=>{Gr.current===C&&(window.clearTimeout(C),Gr.current=null)}},[de,Ee,_r,Be,dt,Or,Ie,Ka]);const Al=d.useCallback(m=>{if(hm.current===m)return;hm.current=m;const x=Nt.current,C=x?.deviceId||de,E=++qn.current;ya.current="",Re.current=null,si.current=!0,qe(null),ke(!1),Wa(!1),C&&(ua("control",C),Ja(C,{preservePresentation:!1}),Ge("stopping"),_r(async()=>{if(x&&x.deviceId===C)try{await Or(x,"control-session-document-hidden",{resumeWall:!1})}catch(T){!jr.current&&ds.current===m&&(Ge("error"),Be(T instanceof Error?T.message:String(T)));return}else Ja(C,{preservePresentation:!1}),Ke(T=>T===C?"":T);!Nt.current&&qn.current===E&&Ge("idle")}))},[de,_r,Ja,ua,Be,Or]);d.useEffect(()=>{if(us.current!==null&&(window.clearTimeout(us.current),us.current=null),!de||Ee==="idle"||Ee==="paused"||Ee==="error")return;if(!Na){Al(ds.current);return}if(Ee==="stopping"||Eo){de&&Dr&&Ee==="connecting"&&(si.current=!1),de&&Dr&&si.current&&(Ee==="warm"||Ee==="active")&&(si.current=!1,Re.current=null,qe(null),ke(!1),Wa(!1),ua("control",de),Fe(`control-presentation-resume-${Date.now()}-${de}`),Ge("connecting"));return}Re.current=null,si.current=!0,qe(null),ke(!1),Wa(!1),Ge(x=>x==="idle"||x==="stopping"?x:"warm");const m=de;return Ja(m,{preservePresentation:!1}),us.current=window.setTimeout(()=>{us.current=null,++qn.current,ya.current="";const x=Nt.current;Ge("stopping"),_r(async()=>{if(x&&x.deviceId===m)try{await Or(x,"control-session-warm-timeout")}catch(C){Ge("error"),Be(C instanceof Error?C.message:String(C));return}else Ja(m),Ke(C=>C===m?"":C);Nt.current||Ge("idle")})},vI),()=>{us.current!==null&&(window.clearTimeout(us.current),us.current=null)}},[Eo,Dr,de,Ee,Na,_r,Ja,Al,ua,Be,Or]),d.useEffect(()=>()=>{us.current!==null&&window.clearTimeout(us.current),Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),Ga.current=null},[]);const Dc=d.useCallback(()=>{const m=new Set(hu.current),x=Nt.current?.deviceId||"";de&&m.add(de),x&&m.add(x),hu.current=[];for(const E of m){Wr.current.delete(E),Hn(E),Ja(E,{preservePresentation:!1});for(const T of[ln.current.get(E),Xn.current.get(E),Aa.current.get(E)])T&&Ra(T);Xr(E),ua("wall",E),ua("control",E),Ec(E)}const C=Rr.current;C&&Ra(C),cc.current="",ul.current=null,uc.current=0},[Xr,de,Ra,Ja,Ec,Hn,ua]);d.useEffect(()=>{if(Na){hu.current=[...bl];return}Dc()},[Na,bl,Dc]),d.useEffect(()=>{const m=cr.current,x=Nt.current;if(!Ka||!m||Ye.current[m.deviceId]||x&&x.deviceId===m.deviceId){cu.current=0;return}const C=cu.current,E=Math.min(5e3,500*2**Math.min(C,4)),T=window.setTimeout(()=>{ji.current===T&&(ji.current=null);const U=cr.current;!Er.current||!U||Ye.current[U.deviceId]||!Kn(U,m)||(cu.current=C+1,Zi(U).catch(K=>{Be(K instanceof Error?K.message:String(K)),Kn(cr.current,U)&&!Nt.current&&wo(ee=>ee+1)}))},E);return ji.current=T,()=>{window.clearTimeout(T),ji.current===T&&(ji.current=null)}},[Ee,Zi,Be,Ka,lc,ni]);const Nl=de&&pt.find(m=>m.deviceId===de)||null,Ic=!!(dt&&$e&&Ee==="active"&&me&&Nl?.sessionId&&pe?.deviceId===Nl.deviceId&&pe.sessionId===Nl.sessionId&&pe.streamPurpose==="control"&&pe.commandId&&pe.captureGeneration>0&&pe.monitorIndex===Ea),{state:Fu,sendInput:Zd,stats:Vs,error:Jd}=lN(Na&&ys&&Ic,X),Ji=Nl?.deviceId||"",Ou=Nl?.sessionId||"",Tl=pe?.commandId||"",Rl=Number(pe?.captureGeneration||0),ef=Number(pe?.monitorIndex||0),Uo=d.useCallback((m,x)=>!jr.current||!Ic||!Ji||!Ou||!Tl||Rl<=0||m!==Ji?!1:Zd(m,{...x,monitorIndex:ef,controlSessionId:Ou,controlCommandId:Tl,captureGeneration:Rl}),[Ic,Rl,Tl,Ji,ef,Ou,Zd]),Ks=Na&&jr.current&&Ic&&Fu==="open",Bu={shiftKey:Et.includes("ShiftLeft"),ctrlKey:Et.includes("ControlLeft"),altKey:Et.includes("AltLeft"),metaKey:Et.includes("MetaLeft")},Zr=d.useCallback(m=>Ne.current.enqueueStop(m),[]),eo=d.useCallback(m=>Ne.current.enqueueStart(m),[]),Ca=d.useCallback((m,x=ce.current)=>(te.current=m,ce.current=m?String(x||""):"",fe.current+=1,fe.current),[]),Jr=d.useCallback((m,x,C)=>IN({generation:m,currentGeneration:fe.current,enabled:te.current,deviceId:x,currentDeviceId:ce.current,documentVisible:jr.current,presentationVisible:He.current,streamId:C,currentStreamId:Ae.current.get(x)||""}),[]),vr=d.useCallback(async(m,x,C)=>{if(!x)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const T=await(K=>rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({...K?{streamId:K}:{},reason:C})},X))(x),U=LN(T);if(U.staleOwner)return T;if(!U.confirmed)throw new Error(T?.error||"Remote audio capture stop was not confirmed.");return T},[X]),Hu=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]),wm=d.useCallback(m=>{const x=fe.current,C=Ae.current.get(m)||"";return Zr(()=>vr(m,C,"remote-audio-automatic-restart")).then(()=>eo(async()=>{if(x!==fe.current||!te.current||ce.current!==m||!jr.current||!He.current||!Xt||!vs||(je.current||De?.deviceId||"")!==m)return"";const E=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(Ae.current.set(m,E),!Jr(x,m,E))return Ae.current.delete(m),"";const T=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(T?.ok===!1)throw Ae.current.get(m)===E&&Ae.current.delete(m),new Error(T.error||"Remote audio restart failed.");return Jr(x,m,E)?E:(await vr(m,E,"remote-audio-stale-restart-compensation"),Ae.current.get(m)===E&&Ae.current.delete(m),"")}))},[eo,Zr,Xt,X,Jr,vs,De?.deviceId,vr]),zu=De?.deviceId&&Ae.current.get(De.deviceId)||"",xm=d.useCallback(async(m,x,C)=>{Ca(!1),be(!1),await Zr(()=>vr(m,x,C)),Ae.current.get(m)===x&&Ae.current.delete(m)},[Zr,Ca,vr]),{state:$u,lastFrame:tf,stats:An,error:Uu}=dN(De?.deviceId||"",Na&&ju&&Ze,X,ml,En||Ht||uu.current,zu,wm,xm),Lc=d.useRef(new Map);d.useEffect(()=>{const m=[["hub",W],["registry",l],["license",P],["wall-stream",Qi],["control-stream",zo],["control-decode",st],["remote-input",Jd],["remote-audio",Uu]];for(const[x,C]of m){const E=String(C||"").trim();if(x==="hub"&&Bt?.requiresHubRestart&&Bt.stage==="updating"){Lc.current.delete(x);continue}if(!E){Lc.current.delete(x);continue}Lc.current.get(x)!==E&&(Lc.current.set(x,E),Be(E))}},[Uu,st,zo,W,Jd,P,l,Be,Qi,Bt]);const jl=De?.deviceId||"",nf=De?Es(De,rn[jl]):0;d.useEffect(()=>{if(!$e||!ys||!Ks||!jl)return;const m=yN(),x=jl,C=nf,E=ze=>{if(!ze)return!1;const _e=Uo(x,{...ze,monitorIndex:C});return!_e&&ze.type!=="keyboard.reset"&&(m.reset("browser-input-send-rejected"),lt([])),_e},T=(ze,_e)=>{const xt=ze.target,yn=xt?.tagName?.toLowerCase(),vt=xt?.isContentEditable||yn==="input"||yn==="textarea"||yn==="select",bn=m.isPressed(ze);if(vt&&(_e==="keydown"||!bn))return;const Ln=m.event(ze,_e);Ln&&(ze.preventDefault(),ze.stopPropagation(),E(Ln))},U=ze=>T(ze,"keydown"),K=ze=>T(ze,"keyup"),ee=(ze,_e=!1)=>{const xt=m.reset(ze,_e);xt&&(E(xt),lt([]))};ht.current=ze=>{const _e=m.snapshot().latchedCodes.includes(ze),xt=m.modifier(ze,!_e);xt&&(E(xt),lt(yn=>_e?yn.filter(vt=>vt!==ze):[...yn.filter(vt=>vt!==ze),ze]))};const ie=()=>ee("browser-window-blur"),se=()=>ee("browser-page-hidden"),et=()=>{document.visibilityState==="hidden"&&ee("browser-document-hidden")};return window.addEventListener("keydown",U,!0),window.addEventListener("keyup",K,!0),window.addEventListener("blur",ie),window.addEventListener("pagehide",se),document.addEventListener("visibilitychange",et),()=>{window.removeEventListener("keydown",U,!0),window.removeEventListener("keyup",K,!0),window.removeEventListener("blur",ie),window.removeEventListener("pagehide",se),document.removeEventListener("visibilitychange",et),ht.current=null,ee("control-keyboard-owner-changed",!0)}},[ys,Ks,jl,nf,$e,Uo]);const af=d.useCallback(m=>{He.current=m;const x=je.current||De?.deviceId||"";if(!Ze||!x)return;const C=Ca(te.current,x);if(!m){const T=Ae.current.get(x)||"";Zr(async()=>{await vr(x,T,"remote-audio-document-hidden")}).catch(U=>{(je.current||De?.deviceId||"")===x&&(Ca(!1),Ae.current.delete(x),be(!1),Be(U instanceof Error?U.message:String(U)))});return}const E=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Ae.current.set(x,E),eo(async()=>{if(!Jr(C,x,E)||!Xt||!vs||(je.current||De?.deviceId||"")!==x)return;const T=await rt(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(T?.ok===!1)throw new Error(T.error||"Remote audio presentation resume failed.");Jr(C,x,E)||(await vr(x,E,"remote-audio-stale-presentation-compensation"),Ae.current.get(x)===E&&Ae.current.delete(x))}).catch(T=>{jr.current&&C===fe.current&&(Ca(!1),Ae.current.delete(x),be(!1),Be(T instanceof Error?T.message:String(T)))})},[Ze,eo,Zr,Ca,Xt,X,Jr,vs,De?.deviceId,Be,vr]);d.useEffect(()=>{const m=T=>{const U=jr.current;T!==U&&(jr.current=T,ds.current+=1,yc.current={active:T&&Qa.current,epoch:ds.current},T||(Dc(),Al(ds.current)),af(T),gh(T),T&&!U&&(vh(K=>K+1),Ii.current=performance.now()))},x=()=>{m(document.visibilityState==="visible")},C=()=>m(!1),E=()=>x();return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",C),window.addEventListener("pageshow",E),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",E)}},[Dc,Al,af]),d.useEffect(()=>{if(!de||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm"||Kd!=="open")return;const m=de,x=la("control",m),C=window.setInterval(()=>{const E=performance.now();if(document.visibilityState!=="visible"||E-Ii.current<Og)return;const T=ii.current.get(x)||0,U=Di.current.get(x)||0,K=Fs.current.get(x)||0,ee=Li.current.get(x)||E;Li.current.has(x)||Li.current.set(x,ee);const ie=T<=0,se=ie?E-ee>EI:E-T>jx,et=yw({lastReceivedAt:T,lastPaintedAt:U,now:E,staleAfterMs:jx}),ze=vw({paintStale:et,lastRecoveryAt:oi.current.get(x)||0,now:E,recoveryCooldownMs:Dx,transportRecoveryAfterMs:Ix});if(!se&&ze==="reset-decoder"&&vi(m,"control","decoder-paint-stale")||!se&&ze==="wait")return;if(!(se||ze==="recover-transport")){et&&vi(m,"control","decoder-paint-stale"),ie&&E-ee>jI&&!Os.current.has(x)&&ia([m],"control-frame-socket-recovery")&&Os.current.set(x,E);return}const xt=Os.current.get(x)||0;if(xt<=0){ia([m],"control-frame-socket-recovery")&&Os.current.set(x,E);return}if(E-xt<Ex)return;const yn=Bs.current.get(x)||0;if(yn>0){if(E-yn<II)return;Bs.current.delete(x)}const vt=li.current.get(x)||0;if(vt>=LI){if(Ml(ie?"no first frame":"stale stream"))return;ke(!1),Wa(!1),ba.current=m,Ge("error");return}if(E-K<Lx(DI,vt))return;Cl([m],ie?"control-first-frame-timeout":ze==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(Os.current.delete(x),oi.current.delete(x),Fs.current.set(x,E),Bs.current.set(x,E),Li.current.set(x,E),li.current.set(x,vt+1))},650);return()=>window.clearInterval(C)},[Kd,de,Ee,Ml,ia,vi,Cl]),d.useEffect(()=>{!st||de&&Ye.current[de]||Ir!=="mode3-h264-hw"||Ml(st)||(ke(!1),Wa(!1),ba.current=Nt.current?.deviceId||"",Ge("error"))},[st,de,Ir,Ml]),d.useEffect(()=>{!dt||!de||Ye.current[de]||!zo||(ba.current=de,Ge(m=>m==="error"?m:"error"))},[zo,de,dt]),d.useEffect(()=>{if(Ee!=="error")return;const m=Nt.current;if(!m)return;ba.current=m.deviceId,Kn(Mo.current,m)||(Mo.current=m,fl.current=0);const x=fl.current,C=x===0?0:Math.min(5e3,500*2**Math.min(x-1,4)),E=window.setTimeout(()=>{Kn(Nt.current,m)&&(++qn.current,ya.current="",Ge("stopping"),_r(async()=>{if(Kn(Nt.current,m))try{if(!await Or(m,"control-session-terminal-error"))return;Mo.current=null,fl.current=0,fc.current===m.deviceId?(fc.current="",ba.current="",Ge("idle")):Ge("error")}catch(T){if(!Kn(Nt.current,m))return;fl.current+=1,Be(T instanceof Error?T.message:String(T)),Ge("error"),qr(U=>U+1)}}))},C);return()=>window.clearTimeout(E)},[Ee,Ur,_r,Be,Or]);const Pc=d.useCallback(m=>{if(!m||ba.current!==m)return!1;const x=Nt.current;return++qn.current,ya.current="",fl.current=0,x&&x.deviceId===m?(fc.current=m,Mo.current=null,Ge("error"),qr(C=>C+1),!0):(fc.current="",ba.current="",Mo.current=null,Ge("idle"),!0)},[]);d.useEffect(()=>{if(Us!=="open"||!wt.autoStartLive||pr.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),E=Math.max(FI,Math.ceil(C*4)),T=[],U=[];for(const K of pr){if(U.length+T.length>=HI)break;const ee=la("wall",K),ie=ii.current.get(ee)||0,se=ie<=0,et=Ao.current.get(ee)||x;Ao.current.has(ee)||Ao.current.set(ee,et);const ze=Fs.current.get(ee)||0,_e=Di.current.get(ee)||0,xt=se||x-ie>E,yn=yw({lastReceivedAt:ie,lastPaintedAt:_e,now:x,staleAfterMs:E}),vt=vw({paintStale:yn,lastRecoveryAt:oi.current.get(ee)||0,now:x,recoveryCooldownMs:Dx,transportRecoveryAfterMs:Ix});if(!xt&&vt==="reset-decoder"&&vi(K,"wall","decoder-paint-stale")||!xt&&vt==="wait")continue;if(!(xt||vt==="recover-transport")){yn&&vi(K,"wall","decoder-paint-stale");continue}const Ln=Os.current.get(ee)||0;if(Ln<=0&&(!se||x-et>PI)){T.push(K);continue}if(se&&x-et<=_I||Ln>0&&x-Ln<Ex)continue;const br=li.current.get(ee)||0;x-ze>=Lx(OI,br)&&U.push(K)}if(T.length>0&&Ho(T,"wall-frame-socket-recovery"))for(const K of T)Os.current.set(la("wall",K),x);if(U.length>0&&Yi(U,U.some(K=>(ii.current.get(la("wall",K))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const K of U){const ee=la("wall",K);Os.current.delete(ee),oi.current.delete(ee),Fs.current.set(ee,x),Ao.current.set(ee,x),ii.current.delete(ee),Di.current.delete(ee),li.current.set(ee,(li.current.get(ee)||0)+1)}},BI);return()=>window.clearInterval(m)},[kc,pr,Ho,vi,Yi,wt.autoStartLive,Qt,Us]),d.useEffect(()=>{or(Qt),Cu.current=Date.now(),Wn.current=0,ms.current=0,da.current=0,gc.current=0,jo.current=""},[Qt,wt.frameMode,wt.adaptiveLoadShedding]),d.useEffect(()=>{LA({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,E=RN(m,b),T=()=>{const K=zg(x.map(ee=>String(ee.dataset.liveDeviceId||"")).filter(ee=>(C.get(ee)||0)>0));ti(ee=>Hg(ee,K)?ee:K)},U=new IntersectionObserver(K=>{for(const ee of K){const ie=String(ee.target.dataset.liveDeviceId||"");ie&&C.set(ie,ee.isIntersecting?ee.intersectionRatio||.01:0)}T()},{root:E,rootMargin:b?kN:Si.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return x.forEach(K=>U.observe(K)),T(),()=>U.disconnect()},[yl,Xt,b,dt,mi,wt.visibleOnlyLive,Gt]),d.useEffect(()=>{if(!wt.adaptiveLoadShedding||!wt.autoStartLive||pr.length===0){ms.current=0,da.current=0,gc.current=0,jo.current="";return}const m=Qt;if(Us!=="open"||qs.sampleMs<500||qs.lastUpdatedAt<=0||gc.current===qs.lastUpdatedAt)return;gc.current=qs.lastUpdatedAt;const x=Date.now(),C=pr.map(ze=>({deviceId:ze,receive:fu[la("wall",ze)],paint:dl[la("wall",ze)]}));if(!C.every(({receive:ze,paint:_e})=>{const xt=ze?.lastFrame,yn=Math.max(0,Number(xt?.requestedFps||0)),vt=xt?uo(xt):"";return UN({receiveSampleMs:Number(ze?.sampleMs||0),paintSampleMs:Number(_e?.sampleMs||0),currentGenerationVerified:xt?.currentGenerationVerified===!0,frameRequestedFps:yn,adaptiveFps:Bn})&&_e?.bindingKey===vt})){ms.current=0,da.current=0,Wn.current=0;return}const T=[Bn,...C.map(({deviceId:ze,receive:_e})=>`${ze}:${uo(_e.lastFrame)}`).sort()].join("|");if(jo.current!==T){jo.current=T,ms.current=x,da.current=0,Wn.current=0;return}if(!ms.current){ms.current=x,da.current=0;return}if(x-ms.current<Si.downshiftStableSampleMs)return;const U=C.reduce((ze,{receive:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0)),0),K=C.reduce((ze,{receive:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0))*Math.max(0,Number(_e?.averageFrameBytes||0)),0),ee=C.reduce((ze,{paint:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0)),0),ie=Math.max(0,...C.map(({receive:ze})=>Number(ze?.maxIntervalMs||0))),se=Math.max(0,...C.map(({paint:ze})=>Number(ze?.p95IntervalMs||0))),et=$N({directDeviceCount:pr.length,requestedFps:Bn,measuredFramesPerSecond:U,measuredPaintFramesPerSecond:ee,measuredBytesPerSecond:K,maxBytesPerSecond:Si.maxWallBytesPerSecond,worstReceiveGapMs:ie,worstPaintP95Ms:se,maxFrameGapMs:Si.maxFrameGapMs});if(et.overloaded){if(Wn.current=0,da.current+=1,da.current<Si.downshiftConsecutiveSamples)return;const ze=Si.minFps;if(x-Cu.current>=Si.downshiftCooldownMs&&Bn>ze){const _e=Math.max(ze,rL(Bn,ze));_e<Bn&&(or(_e),Cu.current=x,ms.current=0,da.current=0)}return}if(da.current=0,!et.healthyForRecovery||Bn>=m){et.healthyForRecovery||(Wn.current=0);return}if(!Wn.current){Wn.current=x;return}if(x-Wn.current>=Si.recoveryCooldownMs){const ze=Math.min(m,sL(Bn,m));ze>Bn&&(or(ze),Cu.current=x,Wn.current=0,ms.current=0,da.current=0)}},[Bn,pr.length,pr,dl,fu,Us,qs.lastUpdatedAt,qs.sampleMs,wt.adaptiveLoadShedding,wt.autoStartLive,wt.frameMode,Qt]),d.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("checkout");if(m==="success"){Be("Checkout returned. Waiting for Dodo confirmation."),re();const x=window.setInterval(()=>{re()},4e3),C=window.setTimeout(()=>{window.clearInterval(x)},45e3);return()=>{window.clearInterval(x),window.clearTimeout(C)}}m==="cancelled"&&Be("Checkout cancelled.")},[re]),d.useEffect(()=>{!Xt&&$e&&We(!1),!Xt&&Ze&&(Ca(!1),be(!1))},[Ze,$e,Ca,Xt]),d.useEffect(()=>{Ze&&(!De||!vs)&&(Ca(!1),be(!1))},[Ze,Ca,vs,De]),d.useEffect(()=>{const m=De?.deviceId||"",x=je.current;if(je.current=m,!x||x===m)return;const C=Ca(Ze,m),E=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";m&&Ze&&Ae.current.set(m,E);let T=!0;const U=Ae.current.get(x)||"";return(async()=>{try{await Zr(async()=>{await vr(x,U,"remote-audio-device-switch"),Ae.current.delete(x)}),await eo(async()=>{if(!T||!Jr(C,m,E)||!m||!Xt||!vs)return;const K=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(K.ok===!1)throw new Error(K.error||"Remote audio start failed.");Jr(C,m,E)||(await vr(m,E,"remote-audio-stale-device-switch-compensation"),Ae.current.get(m)===E&&Ae.current.delete(m))})}catch(K){T&&(Ca(!1),Ae.current.delete(m),be(!1),Be(K instanceof Error?K.message:String(K)))}})(),()=>{T=!1}},[Ze,eo,Zr,Ca,Xt,X,Jr,vs,De?.deviceId,vr]),d.useEffect(()=>{const m=pt.map(T=>T.deviceId),x=new Set(m),C=new Map(pt.map(T=>[T.deviceId,T])),E=new Map;for(const T of pt){const U=GI(T);if(!U)continue;const K=ki(T.status),ee=[T.lastStatusAt,K.capturedAt,K.collectedAt,K.timestamp,K.updatedAt].find(se=>typeof se=="string"&&se.trim()),ie=wN(Js.current[T.deviceId],U,ee);ie&&(Js.current[T.deviceId]=ie,E.set(T.deviceId,ie),X0({platform:T.platform,topologyFingerprint:U,consecutiveTopologySamples:ie.consecutiveSamples})&&(oc.current[T.deviceId]=U))}for(const T of Object.keys(Js.current))x.has(T)||delete Js.current[T];Z(T=>{const U=T.filter(K=>x.has(K));return Hg(T,U)?T:U}),ae(T=>T&&x.has(T)?T:""),Pe(T=>T&&x.has(T)?T:""),cs(T=>{let U=!1;const K={};for(const[ee,ie]of Object.entries(T)){const se=C.get(ee);if(!se){K[ee]=ie;continue}const et=E.get(ee)||Js.current[ee],ze=xN({requestedIndex:ie,monitorCount:mo(se),platform:se.platform,topologyFingerprint:et?.fingerprint||"",consecutiveTopologySamples:et?.consecutiveSamples||0});K[ee]=ze,ze!==ie&&(U=!0)}return U?K:T}),hl(T=>{const U=T.filter(K=>x.has(K));return Hg(T,U)?T:U})},[pt,Do]),d.useEffect(()=>{gm([]),wu(!1)},[$s]),d.useEffect(()=>{!Hi||To!=="selected"||ja.length>0||In.length===0||hl(In.map(m=>m.deviceId))},[In,ja.length,To,Hi]),d.useEffect(()=>{try{localStorage.setItem(YS,$r)}catch{}},[$r]),d.useEffect(()=>{ZI(wt)},[wt]),d.useEffect(()=>{eL(_n)},[_n]),d.useEffect(()=>{YI(rn,oc.current)},[pt,rn]);const qu=d.useCallback(async()=>{const m=new Set(w);m.add($n);try{const U=await rt("/api/remote/status",void 0,$n);Ob({endpoint:U.agentEndpoint,endpoint_candidates:[...U.agentEndpointCandidates||[],...U.hostTargetEndpointCandidates||[]]}).forEach(K=>m.add(K))}catch{}const x=[...m].sort((U,K)=>{const ee=ie=>{const se=Zf(ie);return se==="local"?0:se==="loopback"?1:2};return ee(U)-ee(K)||U.localeCompare(K)});let C=!1,E="",T=!1;try{for(const U of x){const K=Zf(U);try{if(await rt("/api/health",void 0,U),K==="local")return H(!0),xd(!0),U;K==="loopback"&&(C=!0,E=U)}catch{K==="local"&&(T=!0)}}return C?(T&&Be("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),xd(!0),E||$n):(H(!1),xd(!1),"")}catch{return H(!1),xd(!1),""}},[w]),qo=async()=>{if(hn("auth"),sr(!1),window.liveDesk?.auth?.signInWithGoogle){const E=window.liveDesk.auth.signInWithGoogle();qu();const T=await E;T?.ok===!1&&(Be(T.error||"LiveDesk could not open the system browser for Google sign-in."),hn(""));return}const m=$t.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});qu();const{data:x,error:C}=await m;C&&(Be(C.message),hn(""))},_c=async()=>{hn("auth"),sr(!1),window.liveDesk?.auth?.persistSession||await rt("/api/auth/session",{method:"DELETE"},X||$n).catch(()=>{}),await $t.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1&&Be("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),hn("")};d.useEffect(()=>{if(!Ai)return;const m=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||sr(!1))},x=C=>{C.key==="Escape"&&sr(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Ai]);const Wu=d.useCallback(async(m={})=>{const x=m.silent===!0,C=m.takeover===!0,E=m.requestLocalAccess===!0;if(!n?.user){x||Be("Sign in before publishing this host.","error");return}if(!Bi.current){Bi.current=!0,x||(hn("host"),it("Hub · 1/4 · Checking the local runtime…"));try{const U=(E?await qu():"")||X||$n;if(!($||await rt("/api/remote/status",void 0,U)).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}})},U);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})},U);if(!ie.ok)throw new Error(ie.error||"host-target-failed");if(!x){it("Hub · 4/4 · Verifying the endpoint and lease renewal…");const se=await rt("/api/hub/status",void 0,U);if(!se.hostTargetActive)throw new Error(se.hostTargetLease?.lastError||"host-target-not-active-after-sync");const et=se.hostTargetEndpoint||se.agentEndpoint||"endpoint ready",ze=Number(se.connectedDeviceCount||0),_e=ze>0?`${ze} client${ze===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Be(`Hub ready · ${et} · lease auto-renewal active. ${_e}`,"success"),(E||j)&&(H(!0),xd(!0)),V()}u()}catch(T){if(!x){const U=T instanceof Error?T.message:String(T);U.includes("local network access")&&(H(!1),xd(!1)),Be(`Hub setup failed · ${U}`,"error")}}finally{Bi.current=!1,x||hn("")}}},[X,j,V,u,qu,n,Be,it,$]),to=d.useCallback((m=!0)=>{kt!=="host"&&(Dt(!1),m&&window.requestAnimationFrame(()=>Mr.current?.focus()))},[kt]),Sm=d.useCallback(()=>{kt!=="host"&&(Mr.current=document.activeElement instanceof HTMLElement?document.activeElement:null,sr(!1),Dt(!0))},[kt]),Cm=d.useCallback(()=>{Dt(!1),Wu({takeover:!0,requestLocalAccess:!0})},[Wu]);d.useEffect(()=>{if(!nt)return;const m=window.requestAnimationFrame(()=>gn.current?.focus()),x=E=>{E.target instanceof Element&&E.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||to(!1)},C=E=>{E.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(!(!$?.update?.canApply||kt==="update")){hn("update");try{const m=await rt("/api/update/apply",{method:"POST",body:JSON.stringify({})},X||$n);if(!m.ok)throw new Error(m.error||"LiveDesk update could not be started.");const x=[...new Set((m.targets||[]).map(T=>String(T.deviceId||"").trim()).filter(Boolean))],C=!!(m.managerUpdateAvailable||m.clientPackageUpdateAvailable),E=m.state==="hub-restart-requested"?Date.now():void 0;(x.length>0||C)&&Tr({operationId:String(m.operationId||`wall-update-${Date.now()}`),targetIds:x,stage:m.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String($.hostInstanceId||""),targetManagerVersion:String(m.latestVersion||$.update?.latestVersion||""),targetClientVersion:String(m.latestClientVersion||$.update?.latestClientVersion||""),restartRequestedAt:E,restartDeadlineAt:E?E+Ap:void 0}),it(m.state==="hub-restart-requested"?Mp:xx),V()}catch(m){Be(m instanceof Error?m.message:String(m),"error")}finally{hn("")}}},[kt,X,V,Be,it,$]);d.useEffect(()=>{const m=Bt,x=$?.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.`;Tr(se=>se?.operationId===m.operationId?{...se,stage:"restored",error:ie}:se),Be(`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.";Tr(se=>se?.operationId===m.operationId?{...se,stage:"failed",error:ie}:se),Be(`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.";Tr(se=>se?.operationId===m.operationId?{...se,stage:"failed",error:ie}:se),Be(ie,"error");return}if(x.operationId===m.operationId){if(x.state==="hub-restart-requested"&&!m.restartDeadlineAt){const ie=Date.now();Tr(se=>se?.operationId===m.operationId?{...se,restartRequestedAt:ie,restartDeadlineAt:ie+Ap}:se),it(Mp)}!m.requiresHubRestart&&x.state==="clients-updated"&&(Tr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Be("LiveDesk clients updated and reconnected successfully.","success"));return}if(!m.requiresHubRestart)return;const E=$.started===!0&&(!m.initialHostInstanceId||$.hostInstanceId&&$.hostInstanceId!==m.initialHostInstanceId),T=!!x.checkedAt,U=kx(x.currentVersion,m.targetManagerVersion),K=!m.targetClientVersion||kx(x.currentClientVersion,m.targetClientVersion),ee=T&&x.state==="idle"&&x.updateAvailable===!1&&U&&K;E&&ee&&(Tr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Be(`LiveDesk Hub ${x.currentVersion||C?.appVersion||m.targetManagerVersion} restarted and passed version verification.`,"success"))},[Be,it,$,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||m.restartDeadlineAt)return;const x=()=>{const E=Date.now();Tr(T=>T?.operationId===m.operationId&&T.stage==="updating"&&!T.restartDeadlineAt?{...T,restartRequestedAt:E,restartDeadlineAt:E+Ap}:T),it(Mp)};if($?.update?.state==="hub-restart-requested"){x();return}if(!W)return;const C=window.setTimeout(x,SI);return()=>window.clearTimeout(C)},[W,it,$?.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,E=window.setTimeout(()=>{const T=`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.`;Tr(U=>U?.operationId===C&&U.stage==="updating"?{...U,stage:"failed",error:T}:U),Be(T,"error")},x);return()=>window.clearTimeout(E)},[Be,Bt]),d.useEffect(()=>{if(!Bt||Bt.stage!=="updated")return;const m=Bt.operationId,x=window.setTimeout(()=>{Tr(C=>C?.operationId===m?null:C)},Sx);return()=>window.clearTimeout(x)},[Bt]),d.useEffect(()=>{ir.current.clear(),ei({})},[Bt?.operationId]),d.useEffect(()=>{if(!Bt||$?.update?.operationId!==Bt.operationId)return;const m=($.update.targets||[]).filter(C=>C.state==="completed").map(C=>Cx(Bt.operationId,C)).filter(C=>!ir.current.has(C));if(m.length===0)return;const x=Date.now()+Sx;for(const C of m)ir.current.add(C);ei(C=>({...C,...Object.fromEntries(m.map(E=>[E,x]))}))},[$?.update,Bt]),d.useEffect(()=>{const m=Math.min(...Object.values(bo));if(!Number.isFinite(m))return;const x=window.setTimeout(()=>{const C=Date.now();ei(E=>Object.fromEntries(Object.entries(E).filter(([,T])=>T>C)))},Math.max(0,m-Date.now()));return()=>window.clearTimeout(x)},[bo]),d.useEffect(()=>{if(Hr!==xx&&Hr!==Mp)return;const m=$?.update;if(String(m?.state||"")==="failed"){Be(m?.error||"LiveDesk update failed.","error");return}Bt?.stage==="updated"&&Be("")},[Hr,Be,$?.update?.error,$?.update?.state,Bt?.stage]);const km=d.useCallback(async()=>{if(!kt){hn("pin");try{const x=await rt("/api/remote/pairing-pin",{method:"POST"},X||$n);if(!x.ok)throw new Error(x.error||"pin-rotation-failed");await V(),Be("New PIN published.")}catch(m){Be(m instanceof Error?m.message:String(m))}finally{hn("")}}},[kt,X,V]),Fc=d.useCallback(m=>{m&&(ae(m),Z(x=>x.includes(m)?x:[...x,m]))},[]),Gu=d.useCallback(m=>{if(!m)return;const x=dr.has(m);ae(C=>x?C===m?"":C:m),Z(C=>x?C.filter(E=>E!==m):C.includes(m)?C:[...C,m])},[dr]),Wo=d.useCallback(()=>{Z([]),ae("")},[Ss]),Vu=d.useCallback(()=>{Z(pt.map(m=>m.deviceId)),ae("")},[pt]),Ku=d.useCallback((m,x)=>{const C=pt.find(T=>T.deviceId===m);if(!C)return;const E=mo(C);if(!(E<=1)&&(cs(T=>{const U=Gf(T[m],E),K=(U+x+E)%E;return K===U?T:{...T,[m]:K}}),ua("wall",m),ua("control",m),za(T=>{if(!T.has(m))return T;const U=new Set(T);return U.delete(m),U}),Ua.current.delete(m),lr.current.delete(m),dt)){const T=Pc(m);ke(!1),T||Ge("connecting"),Wa(!1),Pe(m)}},[pt,ua,Pc,dt]);d.useEffect(()=>{const m=x=>{if($e&&ys&&Ks)return;const C=x.target,E=C?.tagName?.toLowerCase();C?.isContentEditable||E==="input"||E==="textarea"||E==="select"||((x.ctrlKey||x.metaKey)&&x.key.toLowerCase()==="a"&&(x.preventDefault(),Vu()),x.key==="Escape"&&Wo())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[ys,Wo,Ks,$e,Vu]);const Mm=(m,x)=>{const C=pt.find(K=>K.deviceId===m),E=C?mo(C):1,T=Gf(rn[m],E),U=Gf(x,E);if(T!==U&&(cs(K=>({...K,[m]:U})),za(K=>{if(!K.has(m))return K;const ee=new Set(K);return ee.delete(m),ee}),Ua.current.delete(m),lr.current.delete(m),qa.current.delete(m),ai.current.delete(m),Ma.current.delete(m),ua("wall",m),ua("control",m)),dt){const K=Pc(m);T!==U&&(ke(!1),K||Ge("connecting")),Wa(!1),Pe(m)}else Fc(m)},Go=m=>{const x=je.current||De?.deviceId||"",C=[...new Set([x,m].filter(Boolean))],E=Ze||C.some(T=>Ae.current.has(T));Ca(!1),be(!1);for(const T of C)Ae.current.delete(T);C.length!==0&&(async()=>{for(const T of C)await Zr(()=>Hu(T,"remote-audio-control-entry"))})().catch(T=>{E&&Be("Remote audio was muted locally, but Client capture stop was not confirmed: "+(T instanceof Error?T.message:String(T)),"error")})},no=async m=>{const x={requestId:++hh.current,deviceId:m,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ri.current=x,!fr.has(m)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Be(vl);return}const C=pt.find(T=>T.deviceId===m);if(tl(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Be("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Go(m),Pc(m),Wa(!1),Pe(m),bt("control"),We(!0),Be(`Opening remote control${C?` for ${La(C)}`:""}.`,"success")},rf=async()=>{if(!De){Be("Select a Client before playing audio.");return}if(!Xt){Be(vl);return}if(!vs){Be("Selected Client does not report remote audio support yet.");return}if(en)return;const m=!Ze,x=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Ae.current.get(De.deviceId),C=Ca(m,De.deviceId);m&&x?Ae.current.set(De.deviceId,x):m||Ae.current.delete(De.deviceId),q("audio"),be(m);try{m?(await Zr(()=>Hu(De.deviceId,"remote-audio-user-enable-reconcile")),await eo(async()=>{if(!x||!Jr(C,De.deviceId,x))return;const E=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(E?.ok===!1)throw new Error(E.error||"Remote audio start failed.");Jr(C,De.deviceId,x)||await vr(De.deviceId,x,"remote-audio-stale-user-start-compensation")})):await Zr(()=>Hu(De.deviceId,"remote-audio-user-disabled")),Be(`${m?"Audio started":"Audio stopped"} for ${La(De)}.`,"success")}catch(E){Ca(!1),m&&Ae.current.delete(De.deviceId),be(!1),Be(E instanceof Error?E.message:String(E),"error")}finally{q("")}},Am=async(m,x)=>{const C=m.deviceId,E=La(m),T=String(Ye.current[C]||""),U=!!T&&mt[C]===!0;if(x&&T&&!U)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:E};if(!x&&!T)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:E};if(!x&&T.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:E,error:"Pause is still pending confirmation."};if(x){const et=T||`pending:${Date.now()}:${C}`,ze=Nt.current?.deviceId===C?Nt.current:null,_e=!!ze||de===C,xt=_e?++qn.current:0,yn=()=>pw({deviceId:C,requestTransitionGeneration:xt,currentTransitionGeneration:qn.current,actualControlOwner:Nt.current}),vt=yt.current.get(C);yt.current.set(C,{deviceId:C,monitorIndex:Es(m,rn[C]??vt?.monitorIndex),previousControlOwner:ze||vt?.previousControlOwner||null}),va(C,!0),an(C,!1),mn(C,et),Pu(C),_e&&(ya.current="",Ge("paused"));try{const bn=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},X);if(!bn?.pauseToken)return _t.current.delete(C),mn(C,""),an(C,!1),yt.current.delete(C),yn()&&(Re.current=null,qe(null),ke(!1),Fe(`control-pause-rollback-${Date.now()}-${C}`),Ge("connecting")),{ok:!1,action:"pause",deviceId:C,title:E,error:bn?.error||"video-capture-pause-failed"};const Ln=String(Ye.current[C]||"");if(Ln!==et&&Ln!==bn.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:E,error:"Pause ownership changed before confirmation."};const br=yn(),As=br&&Nt.current?.deviceId===C?Nt.current:ze,Yo=yt.current.get(C);return Yo&&(Yo.previousControlOwner=As),br&&Nt.current?.deviceId===C&&(Nt.current=null),br&&(Re.current=null,qe(null)),mn(C,bn.pauseToken),br&&Ge("paused"),bn.ok===!1||bn.captureStopConfirmed!==!0?(an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:E,error:bn.stopError||bn.error||"Client capture shutdown was not confirmed."}):(an(C,!1),{ok:!0,action:"pause",deviceId:C,title:E})}catch(bn){return an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:E,error:bn instanceof Error?bn.message:String(bn)}}}const K=yt.current.get(C),ee=K?.previousControlOwner||null,ie=de===C&&(ee!==null||cr.current?.deviceId===C||Ee==="paused"),se=ie?qn.current:0;try{va(C,!1);const et=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:T})},X);if(et?.ok===!1)throw new Error(et.error||"video-capture-resume-failed");if(String(Ye.current[C]||"")!==T)return{ok:!1,action:"resume",deviceId:C,title:E,error:"Resume ownership changed before confirmation."};const ze=yt.current.get(C)||K,_e=ze?.previousControlOwner||ee,xt=ie&&pw({deviceId:C,requestTransitionGeneration:se,currentTransitionGeneration:qn.current,actualControlOwner:Nt.current});if(mn(C,""),an(C,!1),yt.current.delete(C),xt){const yn=++qn.current;ya.current="";const vt=Cg(C,yn,{sessionId:m.sessionId||_e?.sessionId,monitorIndex:Es(m,rn[C]??ze?.monitorIndex)});Nt.current=vt,Fr(vt),ba.current="",Mo.current=null,Re.current=null,qe(null),at(""),jt(""),ke(!1),ua("control",C);const bn=`control-video-resume-${yn}-${C}`;Fe(bn),Ke(C),Ge("connecting")}else ua("wall",C);return{ok:!0,action:"resume",deviceId:C,title:E}}catch(et){return _t.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:E,error:et instanceof Error?et.message:String(et)}}},Oc=async()=>{if(bs.length===0){Be("Select one or more Clients before pausing video.");return}if(Da.length===0){Be(vl);return}if(en)return;const m=Da.some(C=>{const E=String(Ye.current[C.deviceId]||"");return!E||E.startsWith("pending:")||mt[C.deviceId]===!0}),x=Da.filter(C=>{const E=String(Ye.current[C.deviceId]||"");return m?!E||E.startsWith("pending:")||mt[C.deviceId]===!0:!!E});if(x.length===0){Be(m?"Selected Clients are already paused.":"Selected Clients are already playing.");return}q("video");try{const C=await Promise.all(x.map(se=>Am(se,m)));V();const E=C.filter(se=>se.ok&&!se.skipped),T=C.filter(se=>!se.ok&&se.unconfirmed),U=C.filter(se=>!se.ok&&!se.unconfirmed),K=Da.length-x.length+C.filter(se=>se.skipped).length,ee=bs.length-Da.length,ie=m?"pause":"resume";if(U.length>0||T.length>0){const se=U.slice(0,2).map(et=>`${et.title}: ${et.error||"unknown error"}`).join(" · ");Be([`Video ${ie} completed for ${E.length}/${x.length} Clients.`,T.length>0?`${T.length} Client capture stop${T.length===1?"":"s"} remain unconfirmed.`:"",se,ee>0?`${ee} selected Client${ee===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Be([`Video ${m?"paused":"resumed"} for ${E.length} Client${E.length===1?"":"s"}.`,K>0?`${K} already ${m?"paused":"playing"}.`:"",ee>0?`${ee} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{q("")}},Nm=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,E={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[m];if(window.confirm(`${E} ${La(x)}? Unsaved work on that computer may be lost.`)){q(m),Be(`Sending ${E.toLowerCase()} request to ${La(x)}...`);try{const T=await rt(`/api/remote/devices/${encodeURIComponent(x.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:m})},X);if(!T.ok)throw new Error(T.error||"The remote action could not be sent.");Be(`${E} request sent to ${La(x)}.`,"success"),V()}catch(T){Be(Nm(T),"error")}finally{q("")}}},sf=async(m,x,C="files")=>{const E=m.filter(ee=>ee.file.size>=0);if(E.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 T=crypto.randomUUID(),U=E.reduce((ee,ie)=>ee+ie.file.size,0);let K=0;di({id:T,status:"reading",progress:1,message:`Preparing ${E.length} ${C}`});try{for(let ee=0;ee<E.length;ee+=1){const ie=E[ee],se=ie.file,et=Math.max(1,Math.ceil(se.size/Fg));for(let ze=0;ze<et;ze+=1){const _e=ze*Fg,xt=Math.min(se.size,_e+Fg),yn=se.size===0?new ArrayBuffer(0):await se.slice(_e,xt).arrayBuffer(),vt=ze===et-1;di({id:T,status:"sending",progress:Math.max(2,Math.min(98,Math.round(K/Math.max(1,U)*96))),message:`${ee+1}/${E.length} ${ie.relativePath}`});const bn=await rt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:T,deviceIds:x,remoteDirectory:$r.trim(),name:se.name,relativePath:ie.relativePath,size:se.size,type:se.type,lastModified:se.lastModified,offset:_e,totalBytes:se.size,final:vt,dataBase64:iL(yn)})},X);if(!bn.ok||bn.queued!==x.length)throw new Error(bn.error||`file-chunk-not-queued-${bn.queued}/${x.length}`);K+=yn.byteLength,await new Promise(Ln=>window.setTimeout(Ln,0))}}return di({id:T,status:"queued",progress:100,message:`Sent ${E.length} file${E.length===1?"":"s"} to ${x.length} Client${x.length===1?"":"s"}`}),window.setTimeout(()=>{di(ee=>ee?.id===T&&ee.status==="queued"?null:ee)},4500),{files:E.length,bytes:U}}catch(ee){throw di({id:T,status:"failed",progress:100,message:ee instanceof Error?ee.message:String(ee)}),ee}},of=async m=>{const x=In.length>0?In.map(C=>C.deviceId):De?[De.deviceId]:[];try{await sf(Fx(m),x)}catch(C){Be(C instanceof Error?C.message:String(C))}},Tm=async m=>{try{await sf(Fx(m),Sa)}catch(x){Be(x instanceof Error?x.message:String(x))}};d.useEffect(()=>{Su.current=!1},[]);const lf=m=>{m.preventDefault(),m.stopPropagation(),Hd(!1),of(m.dataTransfer.files)},zn=async(m="ltd")=>{if(!n){Be("Sign in with Google before checkout.");return}if(J&&m===Ut){Be("LiveDesk license is already active.");return}if(J&&Ut==="pro"){Be("LiveDesk Pro is already active.");return}hn("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){Be(x instanceof Error?x.message:String(x)),hn("")}},ea=zI(),cf=$I(),Qu=bl.filter(m=>Mn.has(m)).length,Yu=kl==="open"&&Xi.sampleMs>0?`${Xi.framesPerSecond.toFixed(1)} fps`:kl,Ve=De?dt?Sl.get(De.deviceId):Mn.get(De.deviceId):void 0,ao=De?Es(De,rn[De.deviceId]):0,Rm=De?WI(De):[],Xu=typeof Ve?.monitorIndex=="number"?Gf(Ve.monitorIndex,Math.max(1,Ve.monitorCount||1)):ao,uf=(Ve&&Xu===ao?rC(Ve):null)||(De?aC(De,ao):null);uf&&`${uf.width}${uf.height}`;const Vo=De?la(dt?"control":"wall",De.deviceId):"",oa=Vo?fu[Vo]:void 0,yr=Vo?dl[Vo]:void 0,Mt=yr?.lastInfo,jm=oa&&oa.sampleMs>0?`${oa.framesPerSecond.toFixed(1)} fps`:"waiting";oa&&`${oa.totalFrames}${jm}`,yr&&yr.sampleMs>0&&`${yr.framesPerSecond.toFixed(1)}`,yr&&yr.sampleMs>0&&`${yr.changedFramesPerSecond.toFixed(1)}`,Mt&&(`${Mt.frameSeq}${Mt.decoderLabel}${Mt.queueSize}${Mt.renderQueueSize}${Mt.droppedForLatency}${Mt.decoderFlushCount}${Mt.decoderTimestampFallbacks}${Mt.decoderInputCount}${Mt.decoderOutputCount}`,Mt.visualChanged),Mt&&`${Math.round(Mt.queuedForMs)}${Math.round(Mt.decodedForMs)}${Math.round(Mt.scheduledForMs)}${Mt.drawMs.toFixed(1)}`,Mt?.targetPaintIntervalMs&&`${Mt.targetPaintIntervalMs.toFixed(1)}${(1e3/Mt.targetPaintIntervalMs).toFixed(1)}`,yr&&`${yr.decoderInputFps.toFixed(1)}${yr.decoderOutputFps.toFixed(1)}`,Mt?.canvasPresentation,Mt&&`${Mt.interactiveBufferWaitCount}${Math.round(Mt.interactiveBufferWaitMs)}${Mt.interactiveQueueDrainCount}`,oa&&(Ve?.frameMode==="mode5-lzo-delta"?`${Vf(oa.averageFrameBytes)}${Ve.deltaVisualTileCount||0}${Ve.deltaRefreshTileCount||0}${Ve.deltaTotalTiles||0}`:`${Vf(oa.averageFrameBytes)}${Math.round(oa.tinyFrameRatio*100)}${Math.round(oa.repeatedFrameRatio*100)}`),oa&&oa.sourceSendSampleCount>0&&`${oa.sourceSendAverageMs.toFixed(1)}${oa.sourceSendP95Ms.toFixed(1)}`,Nx(oa),Nx(yr),oa&&yr&&`${Tx(oa)}${Tx(yr)}`,Ve?Ve.frameMode||Ve.mode||Ve.codec||Ve.mimeType:dt?_n.frameMode:wt.frameMode,dt?_n.frameMode:wt.frameMode,Ve?`${Ve.width}${Ve.height}${Vf(Ve.byteLength)}`:dt?`${gs.maxWidth}${gs.maxHeight}`:`${wt.maxWidth}${wt.maxHeight}`,Ve&&`${Ve.isKeyFrame?"key":String(Ve.chunkType||"delta")}`,Ve&&Ve.monitorCount&&((Ve.monitorIndex??0)+1,`${Ve.monitorCount}`),Ve&&[`src ${Math.round(Ve.sourceGapMs||0)}ms`,`gap ${Math.round(Ve.agentSendGapMs||0)}ms`,`tx ${Math.round(Ve.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ve.agentPaceMs||0)}ms`,`queue ${Math.round(Ve.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ve.agentFrameAgeMs||0)}ms`,Ve.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ve.hubPacketTransitAgeMs))}ms`:"",Ve.droppedByAgent?`drop ${Ve.droppedByAgent}`:"",Ve.hubIngressDropped?`ingress-drop ${Ve.hubIngressDropped}`:"",Ve.hubClientDropped?`ws-drop ${Ve.hubClientDropped}`:"",Ve.captureStageMs?`capture ${Math.round(Ve.captureStageMs)}ms`:"",Ve.requestedFps?`req ${Math.round(Ve.requestedFps)}fps`:"",Ve.effectiveFps?`eff ${Math.round(Ve.effectiveFps)}fps`:"",Ve.captureAverageMs?`avg ${Math.round(Ve.captureAverageMs)}ms`:"",Ve.captureP95Ms?`p95 ${Math.round(Ve.captureP95Ms)}ms`:"",Ve.slowFrameCount?`slow ${Math.round(Ve.slowFrameCount)}`:"",Ve.captureHelperRestarts?`helper ${Math.round(Ve.captureHelperRestarts)}`:"",Ve.convertMs?`rgb565 ${Math.round(Ve.convertMs)}ms`:"",Ve.compressMs?`lzo ${Math.round(Ve.compressMs)}ms`:"",Ve.captureSourceSerial?`cap #${Ve.captureSourceSerial}`:"",Ve.captureSourceSkipped?`cap skip ${Ve.captureSourceSkipped}`:"",Ve.frameMode==="mode5-lzo-delta"?`tiles ${Ve.deltaVisualTileCount||0}+${Ve.deltaRefreshTileCount||0}/${Ve.deltaTotalTiles||0}@${Ve.deltaTileSize||0}`:"",Ve.platformProfile||Ve.hardwareEncoder||"-",Ve.atlasComposeMs?`atlas ${Ve.atlasComposeMs.toFixed(1)}ms`:"",Ve.atlasPoolStarved?`pool ${Ve.atlasPoolStarved}`:"",Ve.atlasTileCount?`tiles ${Ve.atlasReadyTiles||0}/${Ve.atlasTileCount}`:"",Ve.atlasInputRevision?`input #${Ve.atlasInputRevision}`:"",Ve.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ve.atlasSourceMaxAgeMs)}ms`:"",Mt?.inputFeedbackMs!==void 0&&Mt.inputFeedbackAt!==void 0&&performance.now()-Mt.inputFeedbackAt<=gx?`feedback ${Math.round(Mt.inputFeedbackMs)}ms`:"",Ve.contentHash?`enc ${Ve.contentHash.slice(0,6)}`:"",Mt?.visualHash?`pix ${Mt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Fu==="open"&&[`${Vs.sentPerSecond.toFixed(1)} hz`,Vs.lastInputSeq>0?`rtt ${Math.round(Vs.lastRoundTripMs)}ms`:"",Vs.lastInputSeq>0?`apply ${Vs.lastAgentApplyMs.toFixed(1)}ms`:"",Vs.droppedPerSecond>0?`drop ${Vs.droppedPerSecond.toFixed(1)}/s`:"",Vs.bufferedAmount>0?`buf ${Vf(Vs.bufferedAmount)}`:"",Vs.lastInputType||"ready"].filter(Boolean).join(" / "),Mt?.inputFeedbackMs!==void 0&&Mt.inputFeedbackAt!==void 0&&performance.now()-Mt.inputFeedbackAt<=gx&&[Mt.inputFeedbackExact?"exact":"estimated",Mt.inputFeedbackInputType||"",`total ${Math.round(Mt.inputFeedbackMs)}ms`,Mt.inputFeedbackAgentApplyMs!==void 0?`apply ${Mt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",Mt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(Mt.inputFeedbackApplyToCaptureMs)}ms`:"",Mt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(Mt.inputFeedbackInputToFrameMs)}ms`:"",Mt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(Mt.inputFeedbackFrameToPaintMs)}ms`:"",Mt.inputFeedbackSampleCount?`p50 ${Math.round(Mt.inputFeedbackP50Ms||0)}ms`:"",Mt.inputFeedbackSampleCount?`p95 ${Math.round(Mt.inputFeedbackP95Ms||0)}ms`:"",Mt.inputFeedbackSampleCount?`n=${Mt.inputFeedbackSampleCount}`:"",`input #${Mt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ve&&`${Ve.frameSeq}${c0(Ve.receivedAt||Ve.capturedAt)}`;const ro=Math.max(0,Xi.bytesPerSecond*8/1e6),Zu={activeTool:Tt,audioError:Uu,audioMode:Ze,audioState:$u,audioStats:An,lastAudioFrame:tf,selectedAudioCaptureStreamId:zu,controlFrames:Sl,controlInputReady:Ks,controlMode:$e,controlPresentationReady:Fd,controlSessionDeviceId:de,controlSessionFrameReady:me,controlSessionState:Ee,controlStreamBinding:pe,devices:G,documentPresentationVisible:Na,focusedDeviceId:Se,frames:Mn,localFeatureAccess:Xt,quickActionBusy:en,selectedDeviceId:De?.deviceId||"",selectedIds:we,showControlFocus:dt,videoCaptureStopUnconfirmedByDeviceId:mt,videoCapturePausedDeviceIds:Ct,wallPresentationReadyDeviceIds:So},Ju=d.useRef(Zu);Ju.current=Zu,d.useEffect(()=>{if(!uu.current)return;const m=window,x=ee=>{if(!ee)return null;const ie=ee.sourceGapMs,se=ie==null||ie===""?null:Number.isFinite(Number(ie))?Number(ie):null,et=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:et.currentGenerationVerified===!0,receivedAt:et.receivedAt||"",capturedAt:et.capturedAt||"",sourceGapMs:se,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),se=ee.getBoundingClientRect(),et=Math.max(0,Math.min(se.right,window.innerWidth)-Math.max(se.left,0)),ze=Math.max(0,Math.min(se.bottom,window.innerHeight)-Math.max(se.top,0)),_e=Number(ie.opacity),xt=ee.isConnected&&ie.display!=="none"&&ie.visibility!=="hidden"&&ie.visibility!=="collapse"&&Number.isFinite(_e)&&_e>0&&se.width>0&&se.height>0&&et>0&&ze>0;return{connected:ee.isConnected,userVisible:xt,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(_e)?_e:0},rect:{left:se.left,top:se.top,right:se.right,bottom:se.bottom,width:se.width,height:se.height,viewportIntersectionWidth:et,viewportIntersectionHeight:ze},codec:up(ee)}},E=(ee,ie)=>{const se=_s.current.get(la(ee,ie));return se?{bindingKey:se.bindingKey||"",totalFrames:se.totalFrames,totalChangedFrames:se.totalChangedFrames,lastFrameSeq:Number(se.lastFrameSeq||0),lastPaintAgeMs:se.lastAt===void 0?-1:Math.max(0,performance.now()-se.lastAt),lastInfo:se.lastInfo?{frameSeq:Number(se.lastInfo.frameSeq||0),decoderInputCount:Number(se.lastInfo.decoderInputCount||0),decoderOutputCount:Number(se.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(se.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(se.lastInfo.droppedForLatency||0),visualChanged:se.lastInfo.visualChanged===!0,inputFeedbackExact:se.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(se.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(se.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(se.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(se.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:yx,inputFeedbackTargetMinSamples:bx,inputFeedbackOnTarget:se.lastInfo.inputFeedbackExact===!0&&Number(se.lastInfo.inputFeedbackSampleCount||0)>=bx&&Number(se.lastInfo.inputFeedbackP95Ms)<yx}:null}:null},T=(ee,ie)=>{if(!ee)return null;if(ie==="wall-visible"){const et=_s.current.get(la("wall",ee));return et?{bindingKey:et.bindingKey||"",total:et.totalFrames,lastFrameSeq:Number(et.lastFrameSeq||0),lastPaintAgeMs:et.lastAt===void 0?-1:Math.max(0,performance.now()-et.lastAt)}:null}if(ie!=="control-visible"&&ie!=="wall-reuse-visible")return null;const se=du.current.get(`${ie}:${ee}`);return se?{bindingKey:se.bindingKey,total:se.totalPaints,lastFrameSeq:se.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-se.lastPaintAt)}:null},U=(ee,ie)=>{const se=T(ee,ie);return se?{bindingKey:se.bindingKey,totalPaints:se.total,lastPaintAgeMs:se.lastPaintAgeMs,lastFrameSeq:se.lastFrameSeq}:null},K={readPresentationCounter(ee,ie){return T(String(ee||""),ie)},snapshot(ee,ie={}){const se=String(ee||""),et=ie.includeHistory===!0,ze=Math.max(0,Number(ie.presentationAfterSequence||0)),_e=Ju.current,xt=_e.devices.find(Ns=>Ns.deviceId===se)?.liveCapturePause,yn=String(Ye.current[se]||""),vt=ln.current.get(se)||null,bn=kn.current.get(se)||null,Ln=Xn.current.get(se)||null,br=U1(),As=q1(),Yo={frameStats:mu.current===null?0:1,wallRecovery:ji.current===null?0:1,controlWarm:us.current===null?0:1,controlWallDownshift:Gr.current===null?0:1},Wc=ri.current?.deviceId===se?ri.current:null,ts=pm.current.get(se)||null;return{capturedAt:Date.now(),deviceId:se,activeTool:_e.activeTool,documentPresentationVisible:_e.documentPresentationVisible,showControlFocus:_e.showControlFocus,selectedDeviceId:_e.selectedDeviceId,focusedDeviceId:_e.focusedDeviceId,selectedDeviceIds:[..._e.selectedIds],localFeatureAccess:_e.localFeatureAccess,quickActionBusy:_e.quickActionBusy,audioMode:_e.audioMode,audioState:_e.audioState,audioError:_e.audioError,audioCaptureStreamId:_e.selectedAudioCaptureStreamId,audioFrame:_e.lastAudioFrame?{deviceId:_e.lastAudioFrame.deviceId,streamId:_e.lastAudioFrame.streamId,frameSeq:Number(_e.lastAudioFrame.frameSeq||0),mimeType:_e.lastAudioFrame.mimeType,sampleRate:Number(_e.lastAudioFrame.sampleRate||0),channels:Number(_e.lastAudioFrame.channels||0),byteLength:Number(_e.lastAudioFrame.byteLength||0)}:null,audioStats:{..._e.audioStats},videoCapturePausePhase:yn?yn.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:_e.videoCaptureStopUnconfirmedByDeviceId[se]===!0,authoritativeLiveCapturePause:xt?{phase:xt.phase||"",captureStopConfirmed:xt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(xt.stopAttemptCount||0)),stopError:xt.stopError||""}:null,controlMode:_e.controlMode,controlSessionDeviceId:_e.controlSessionDeviceId,controlSessionState:_e.controlSessionState,controlSessionFrameReady:_e.controlSessionFrameReady,controlPresentationReady:_e.controlPresentationReady,controlInputReady:_e.controlInputReady,controlConnection:ts?{...ts}:null,pendingControlConnection:Wc?{...Wc,elapsedMs:Math.max(0,performance.now()-Wc.startedAt)}:null,videoCapturePaused:_e.videoCapturePausedDeviceIds.has(se),wallPresentationReady:_e.wallPresentationReadyDeviceIds.has(se),controlBinding:_e.controlStreamBinding?.deviceId===se?{..._e.controlStreamBinding}:null,actualControlOwner:Nt.current?.deviceId===se?{...Nt.current}:null,wallCapturePauseOwner:cr.current?.deviceId===se?{...cr.current}:null,frameSubscriptions:br,audioSubscriptions:As,presentationTimers:{...Yo,total:Object.values(Yo).reduce((Ns,oo)=>Ns+oo,0)},wallFrame:x(_e.frames.get(se)),controlFrame:x(Ua.current.get(se)||_e.controlFrames.get(se)),wallPaint:E("wall",se),controlPaint:E("control",se),controlVisiblePaint:U(se,"control-visible"),wallReuseVisiblePaint:U(se,"wall-reuse-visible"),presentationPaintSequence:mm.current,presentationPaintEvents:et?Pd.current.filter(Ns=>Ns.deviceId===se&&Ns.sequence>ze).sort((Ns,oo)=>Ns.sequence-oo.sequence).map(Ns=>({...Ns})):[],wallCanvas:C(vt),controlDecodeCanvas:C(bn),controlPresentationCanvas:C(Ln),globalCodec:up(void 0,{includeLifecycleEvents:et})}}};return m.__liveDeskTransmissionProbe=K,()=>{m.__liveDeskTransmissionProbe===K&&delete m.__liveDeskTransmissionProbe}},[]);const Ko=d.useCallback(()=>{rr(!0),Is(Date.now()),V(),Dn.current!==null&&window.clearTimeout(Dn.current),Dn.current=window.setTimeout(()=>{Dn.current=null,Is(Date.now()),rr(!1)},650)},[V]),ed=d.useCallback(()=>{if(En){zr(!1);return}Pn(!1),zr(!0),Ko()},[Ko,En]),Bc=d.useCallback(()=>{if(Ht){Pn(!1);return}zr(!1),Pn(!0),Ko()},[Ht,Ko]),td=d.useCallback(()=>{if(Ba){ar(!1);return}ar(!0),Ko()},[Ba,Ko]),df=En||Ht,nd=JSON.stringify(pt.filter(m=>m.connected).map(m=>m.deviceId).sort());d.useEffect(()=>{if(!df)return;const m=JSON.parse(nd);if(m.length===0){rr(!1);return}const x=new AbortController,C=[];let E=!1;return Dn.current!==null&&(window.clearTimeout(Dn.current),Dn.current=null),rr(!0),Is(Date.now()),Promise.allSettled(m.map(T=>rt(`/api/remote/devices/${encodeURIComponent(T)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:x.signal,timeoutMs:1500},X))).then(()=>{E||[500,1800,4500].forEach((T,U,K)=>{const ee=window.setTimeout(()=>{E||(V(),Is(Date.now()),U===K.length-1&&rr(!1))},T);C.push(ee)})}),()=>{E=!0,x.abort();for(const T of C)window.clearTimeout(T)}},[X,V,nd,df]);const Qo=new Map,Br=new Map;if(En||Ht||Ba)for(const m of pt){const x=m.deviceId,C=dt&&de===x,T=la(C?"control":"wall",x),U=C?Sl.get(x):Mn.get(x),K=C?kn.current.get(x)||Xn.current.get(x)||null:ln.current.get(x)||(Kt?Rr.current:null),ee={device:m,frame:U,receiveStat:fu[T],paintStat:dl[T],codec:K?up(K):{},selectedMonitorIndex:Es(m,rn[x]),control:C,controlInputReady:C&&Ks,controlBinding:C&&pe?.deviceId===x?pe:void 0,hubRelay:$?.relay,capturePaused:Ct.has(x),capturePauseConfirmed:m.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:m.liveCapturePause?.stopError||"",clientHeartbeatMs:Number($?.heartbeatMs||5e3),now:Date.now()},ie=["open","playing","silent"].includes($u),se=An.nativeCallbackDiagnosticsAvailable&&(An.nativeRejectedCallbackCount>0||An.nativeCurrentnessDropCount>0),et=ie&&!se,ze=x===De?.deviceId&&Ze?{id:"browser-remote-audio",state:et?"ok":"warning",label:et?"Remote audio is healthy":"Remote audio needs attention",detail:An.lastUpdatedAt>0?[$u,`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}`:"",tf?`frame #${tf.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(En||Ba){const _e=HD(ee);En&&ze&&_e.push(ze),Qo.set(x,_e)}if(Ht){const _e=zD(ee);ze&&_e.push(ze),Br.set(x,_e)}}const ff=Ba?$D({status:$||{},deviceDiagnostics:[...Qo.values()],codec:up(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Xi}):[],Em=xl?.atlasReadyTiles??Qu,ad=xl?.atlasTileCount??Qu,yi=Em===ad?`${ad} tiles`:`${Em}/${ad} tiles`,mf=Za.length>0;dt?`${Yu}${ro.toFixed(ro>=10?0:1)}`:mf?`${yi}${Yu}${ro.toFixed(ro>=10?0:1)}`:`${Qu}${Yu}${ro.toFixed(ro>=10?0:1)}`;const rd=In.length,Hc=dt?De?La(De):"No Client":rd===0?"No Client":rd>1?`${rd} selected`:De?La(De):"No Client",zc=dt?[De?.deviceId].filter(m=>!!m):In.map(m=>m.deviceId),qt=Td[on]||Td.en,sd=qt.sync||Td.en.sync,Sh=r||z?"checking":J?Ut==="pro"?"Pro LTD active":`Plus LTD ${pt.length}/${Wf}`:gl?`Free ${pt.length}/${qf}`:`Upgrade ${pt.length}/${qf}`,$c=J?Ut==="pro"?"Pro active":"Upgrade to Pro LTD":n?kt==="checkout"?"Opening checkout":Ut==="ltd"?"Buy Pro LTD":"Buy Plus LTD":kt==="auth"?"Opening Google":"Sign in to buy",so=Ut==="pro"||kt==="checkout"||kt==="auth"||r||z,pf=n?.user?.user_metadata,Uc=Ox(pf,"avatar_url","picture"),bi=Ox(pf,"full_name","name")||n?.user?.email||"Google",ks=bi.slice(0,1).toUpperCase(),Dm=$?.started?"Local app ready":"Start LiveDesk",hf=o?.active?"Published":n?"Not published":"Sign in required",Im=/^\d{6}$/.test($?.pairingPin||"")?$?.pairingPin:"------",wi=m=>{if(typeof window<"u"&&(m==="support"?window.history.pushState({},"","/support"):Tt==="support"&&window.history.pushState({},"","/")),m==="control"){const x=xa||Wi;if(x&&(Pc(x.deviceId),Wa(!1),Pe(x.deviceId)),bt(m),!Xt){We(!1),Be(vl);return}We(!0);return}m==="wall"&&Ps(x=>x+1),bt(m),We(!1)},es=kt==="update"||Bt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes($?.update?.state||""),qc=!!($?.update?.updateAvailable&&$.update.canApply||es||Bt?.error||!$&&Bt),io=WM(on),Ms=d.useCallback(m=>{if(!Bt?.targetIds.includes(m))return;const x=$?.update?.operationId===Bt.operationId?$.update.targets?.find(C=>C.deviceId===m):void 0;switch(x?.state){case"completed":return bo[Cx(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}},[$?.update,bo,Bt]),ta=r?"checking":$?.started?"online":"offline",gf=r?"Checking Hub":$?.started?`${pt.length} online`:n?"Hub offline":"Sign in required",vf=b&&g&&!n;return i.jsxs("main",{className:`app-shell ${b?"mobile-console-shell":""}`,"data-mobile-auth-required":vf?"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(u0,{size:25})}),i.jsx("nav",{className:"rail-tools",children:mL.map(m=>{const x=m.icon,C=qp(m.tooltip,on);return i.jsxs("button",{className:`rail-tool ${m.id==="sync-server"?"sync-server hub-sync-trigger":""} ${Tt===m.id?"active":""} accent-${m.accent}`,onClick:()=>m.id==="sync-server"?Sm():wi(m.id),"data-tooltip":m.id==="sync-server"&&nt?void 0:Zg(m.label,m.tooltip,on),"aria-label":`${m.label}. ${C}`,type:"button",disabled:m.id==="sync-server"&&kt==="host","aria-busy":m.id==="sync-server"&&kt==="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"&&kt==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(x,{size:19}),i.jsx("span",{children:m.id==="sync-server"&&kt==="host"?"Syncing…":m.label})]},m.id)})}),i.jsxs("div",{className:"rail-footer",children:[pL.map(m=>{const x=m.icon;return i.jsxs("button",{className:`rail-tool compact ${Tt===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 ${ps?"active":""}`,onClick:()=>{bt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),sr(!1),We(!1),vo(!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:()=>{sr(m=>!m)},disabled:r||kt==="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:ks}):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:ks}):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:Dm}),i.jsx("dt",{children:"Access"}),i.jsx("dd",{children:hf}),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:kt==="auth",type:"button",children:[i.jsx(Ux,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:qo,disabled:kt==="auth",type:"button",children:[i.jsx(Ql,{size:16}),"Sign in with Google"]})]})]})]}),b&&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-${ta}`,role:"status","aria-live":"polite",children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:gf}),i.jsx("small",{children:$?.deviceName||(W?"Desktop Hub unavailable":"Remote management")})]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[g&&!R&&(k||A.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:es||!$?.update?.canApply,"aria-label":es?"LiveDesk update in progress":"Update LiveDesk","aria-busy":es,type:"button",children:es?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:18,"aria-hidden":"true"})})]})]}),b&&D&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>I(!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(Jx,{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:()=>I(!1),"aria-label":"Close install guide",children:i.jsx(nr,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",A.browserName==="browser"?"the browser":A.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:A.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:()=>I(!1),children:"Got it"})]})}),vf&&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(ha,{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:()=>{qo()},disabled:r||kt==="auth","aria-busy":r||kt==="auth",children:[r||kt==="auth"?i.jsx(is,{className:"spin",size:19,"aria-hidden":"true"}):i.jsx(Ql,{size:19,"aria-hidden":"true"}),kt==="auth"?"Opening Google…":r?"Checking sign-in…":"Sign in with Google"]}),i.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),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(po,{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(nr,{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(ha,{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:gn,className:"primary",type:"button",onClick:Cm,disabled:kt==="host",children:[i.jsx(po,{size:16}),io.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${hs&&!Ls?"dock-open":""} ${dt?"control-stage":""} ${Va?"agents-stage":""} ${Hi?"file-share-stage":""}`,children:[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 ${$?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,"aria-label":Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:es?"LiveDesk update in progress":`Update LiveDesk to ${$?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,type:"button",disabled:es||!$?.update?.canApply,"aria-busy":es,children:[es?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:19,"aria-hidden":"true"}),es&&$?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[$.update.completedCount||0,"/",$.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(Dk,{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:$r.trim()||"Desktop/LiveDeskFiles"})]})]})]}),hs&&!dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(fx,{active:Ba,refreshing:Ba&&Nr,onClick:td}),i.jsx(ux,{active:En,refreshing:En&&Nr,onClick:ed}),i.jsx(dx,{active:Ht,refreshing:Ht&&Nr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(cx,{controller:Sc,onError:Be}),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:dL.map(m=>i.jsx("button",{className:Cn===m.id?"active":"",onClick:()=>{Un(m.id),or(m.fps),nL(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:fL.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(fx,{active:Ba,refreshing:Ba&&Nr,onClick:td}),i.jsx(ux,{active:En,refreshing:En&&Nr,onClick:ed}),i.jsx(dx,{active:Ht,refreshing:Ht&&Nr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(cx,{controller:Sc,onError:Be})]})]})]}),Ba&&hs&&i.jsx(jD,{items:ff,collectedAt:Zs,onClose:()=>ar(!1)}),$d?i.jsxs("section",{className:"doc-page",lang:on,dir:on==="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(Ik,{size:17}),qt.languageLabel]}),i.jsx("select",{value:on,onChange:m=>il(m.target.value),children:gL.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 E=[po,jp,Sb,ha,eh][x]||Hp;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(E,{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(T=>i.jsx("li",{children:T},T))})]})]},m.title)})}),sd&&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:sd.title}),i.jsx("p",{children:sd.body})]})]}),i.jsx("ul",{children:sd.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(ha,{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:cf}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(cf),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:ea}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(ea),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:`${ea} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(`${ea} 3`),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]})]})]})]}):Va?i.jsx(ix,{hubUrl:X,devices:G}):Hi?i.jsx(jE,{hubUrl:X,devices:pt,localFeatureAccess:Xt,upgradeNotice:vl,remoteDirectory:$r,onRemoteDirectoryChange:ol,targetMode:To,selectedTargetIds:ja,onTargetModeChange:zd,onTargetToggle:m=>hl(x=>x.includes(m)?x.filter(C=>C!==m):[...x,m]),filePickerRef:Ro,folderPickerRef:ym,onBrowserFileImport:m=>{Tm(m)},onBrowserFolderImport:m=>{Tm(m)},onNotice:Be,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)}}):Mu?i.jsx(a0,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:qo}):ps?i.jsx(VN,{hubUrl:X,runtimeRole:$?.runtimeRole||"hub",runtimeDeviceId:$?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:i.jsxs(KN,{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(kr,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Im}),i.jsxs("button",{className:"text-button ghost compact",onClick:km,disabled:!$?.started||kt==="pin",type:"button",children:[i.jsx(nl,{size:15}),kt==="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(kd,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:$r,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(YN,{hubUrl:X,showToast:Be}),captureGallery:i.jsx(RD,{hubUrl:X,onToast:Be})}):ku?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(nr,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:Ru.name}),i.jsxs("small",{children:[pt.length,"/",RI(Lo)," 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(Pa,{size:16})," Up to ",qf," devices"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(Pa,{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(Lk,{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(Pa,{size:16})," Up to ",Wf," devices"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," No standard ad banner"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," ",Xc.ltd.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>zn("ltd"):qo,disabled:Ut!=="free"||kt==="checkout"||kt==="auth"||r||z,type:"button",children:[i.jsx(Qf,{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(ha,{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(Pa,{size:16})," 30+ Client walls"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," Commercial use included"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," ",Xc.pro.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>zn("pro"):qo,disabled:Ut==="pro"||kt==="checkout"||kt==="auth"||r||z,type:"button",children:[i.jsx(Qf,{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(kr,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ slots"})]}),i.jsxs("div",{children:[i.jsx($f,{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(kd,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(Pa,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>zn(Ut==="ltd"?"pro":"ltd"):qo,disabled:so,type:"button",children:[i.jsx(Qf,{size:18}),$c]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Ls?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:hc,className:`screen-wall-panel ${yh?"drop-active":""}`,onClick:m=>{m.currentTarget===m.target&&Wo()},onDragEnter:m=>{m.preventDefault(),Hd(!0)},onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="copy"},onDragLeave:m=>{m.currentTarget===m.target&&Hd(!1)},onDrop:lf,children:[Za.length>0&&i.jsx("canvas",{ref:Wd,className:"atlas-source-canvas",width:vn?.width||1920,height:vn?.height||1080,"aria-hidden":"true"}),b&&hs&&!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"} · ${mo(De)} display${mo(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:!ys||!!en,type:"button",children:[i.jsx($f,{size:17}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Ze?"active":"",onClick:()=>{rf()},disabled:!ju||!!en,"aria-pressed":Ze,type:"button",children:[en==="audio"?i.jsx(is,{className:"spin",size:17}):i.jsx(ig,{size:17}),i.jsx("span",{children:"Audio"})]}),i.jsxs("button",{className:mr?"":"active",onClick:()=>{Oc()},disabled:Da.length===0||!!en,"aria-pressed":!mr,type:"button",children:[en==="video"?i.jsx(is,{className:"spin",size:17}):mr?i.jsx(Cb,{size:17}):i.jsx(kb,{size:17}),i.jsx("span",{children:mr?"Pause":"Resume"})]}),i.jsxs("button",{onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Io,type:"button",children:[en==="restart"?i.jsx(is,{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 ${La(De)}`,children:[i.jsx("strong",{className:"control-computer-name",title:La(De),children:La(De)}),Rm.map(m=>i.jsxs("button",{className:m.index===ao?"active":"",onClick:()=>Mm(De.deviceId,m.index),title:VI(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&&Ks&&i.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:dI.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:Ve,selected:!1,controlEnabled:ys&&$e&&Ks,showStatus:_n.showScreenStatus,showDeviceTitle:!1,monitorIndex:Es(De,rn[De.deviceId]),monitorCount:mo(De),onSelect:()=>{},onFocusDevice:()=>Pe(De.deviceId),onOpenControl:()=>no(De.deviceId),onCycleMonitor:m=>Ku(De.deviceId,m),onCanvasReady:Eu,sendInput:Uo,remoteModifierState:Bu,presentationReady:Fd,remoteDiagnostics:Ht?Br.get(De.deviceId):En?Qo.get(De.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},De.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(kr,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),De&&Tu&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(ha,{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&&!Tu&&!Fd&&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.":zo||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(bL,{device:m,slotNumber:x,selected:dr.has(m.deviceId),updateIndicator:Ms(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote",onSelect:()=>Gu(m.deviceId),onOpenControl:()=>no(m.deviceId)},m.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(kr,{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&&Wo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:dr.has(m.deviceId),controlEnabled:!1,showStatus:wt.showScreenStatus,monitorIndex:Es(m,rn[m.deviceId]),monitorCount:mo(m),onSelect:()=>Gu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Ku(m.deviceId,C),onCanvasReady:_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(m.platform)})==="direct"?Oo:Ki,sendInput:Uo,remoteModifierState:Bu,updateIndicator:Ms(m.deviceId),presentationReady:wt.autoStartLive&&Xa.includes(m.deviceId)?So.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Xa.includes(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(Hx,{index:x},`slot-${x}`))}):i.jsx("div",{className:`screen-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&Wo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:dr.has(m.deviceId),controlEnabled:ys&&$e&&Ks&&De?.deviceId===m.deviceId,showStatus:wt.showScreenStatus,monitorIndex:Es(m,rn[m.deviceId]),monitorCount:mo(m),onSelect:()=>Gu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Ku(m.deviceId,C),onCanvasReady:Oo,sendInput:Uo,remoteModifierState:Bu,updateIndicator:Ms(m.deviceId),presentationReady:wt.autoStartLive&&Xa.includes(m.deviceId)?So.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Xa.includes(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(Hx,{index:x},`slot-${x}`))}),i.jsx(SL,{visible:bm&&!dt})]}),!ps&&i.jsxs("aside",{className:`right-dock actions-mode ${Ls?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>vo(m=>!m),"aria-label":Ls?"Show control panel":"Hide control panel",title:Ls?"Show control panel":"Hide control panel",type:"button",children:Ls?i.jsx(t0,{size:18}):i.jsx(Mv,{size:18})}),!Ls&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:xu,className:"hidden-file-input",type:"file",multiple:!0,onChange:m=>{m.currentTarget.files&&of(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?Tu?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ys?Ks?"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&&$e){We(!1),Be("Remote control paused. Screen viewing stays on.");return}no(De.deviceId)}},disabled:!ys||!!en,active:$e,pressed:dt&&$e,children:i.jsx($f,{size:17})}),i.jsx(Yc,{label:"Audio",tooltip:De?vs?Ze?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{rf()},disabled:!ju||!!en,active:Ze,pressed:Ze,children:en==="audio"?i.jsx(is,{className:"spin",size:17}):i.jsx(ig,{size:17})}),i.jsx(Yc,{label:Po?"Retry pause":mr?"Pause video":"Resume video",tooltip:bs.length===0?"Select one or more Clients to pause video":Po?"Retry every selected Client whose capture shutdown is unconfirmed":mr?`Pause video for ${Da.length} selected Client${Da.length===1?"":"s"}`:`Resume video for ${Da.length} selected Client${Da.length===1?"":"s"}`,onClick:()=>{Oc()},disabled:Da.length===0||!!en,active:!mr,pressed:!mr,children:en==="video"?i.jsx(is,{className:"spin",size:17}):!mr&&!Po?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:()=>{Be(`Choose files to send to ${Hc}.`),xu.current?.click()},disabled:!!en||!Xt||(dt?!De:In.length===0),children:i.jsx(kd,{size:17})}),i.jsx(Yc,{label:"Restart",tooltip:De?Io?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Io,children:en==="restart"?i.jsx(is,{className:"spin",size:17}):i.jsx(Vg,{size:17})}),i.jsx(Yc,{label:"Sleep",tooltip:De?Io?"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||!Io,children:en==="sleep"?i.jsx(is,{className:"spin",size:17}):i.jsx(Pk,{size:17})}),i.jsx(Yc,{label:"Shut down",tooltip:De?Io?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Dl("shutdown")},disabled:!De||!Xt||!!en||!Io,danger:!0,children:en==="shutdown"?i.jsx(is,{className:"spin",size:17}):i.jsx(Gx,{size:17})})]})]}),i.jsx(ix,{hubUrl:X,devices:G,variant:"dock",selectedDeviceIds:zc})]})]})]})})]}),b&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Tt==="wall"?"active":"",onClick:()=>wi("wall"),type:"button",children:[i.jsx(e0,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:dt?"active":"",onClick:()=>De&&void no(De.deviceId),disabled:!De||!ys,type:"button",children:[i.jsx($f,{size:19}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Hi?"active":"",onClick:()=>wi("share-files"),type:"button",children:[i.jsx(Yf,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:Va?"active":"",onClick:()=>wi("agents"),type:"button",children:[i.jsx(jp,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:ps?"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(Pa,{size:18}):Oi.status==="failed"?i.jsx(nr,{size:18}):i.jsx(Kx,{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:()=>Be(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(nr,{size:15})})]})]})}const kL=1e3,ML=5e3;function AL(){return typeof window>"u"?[]:[...new Set([window.location.origin,$n].filter(Boolean))]}function NL(){const r=Av(),[o,l]=d.useState(null),u=d.useRef(null);return d.useEffect(()=>{if(r){l({role:"hub",baseUrl:$n});return}let f=!1,h=!1,g=null;const y=new AbortController,w=async()=>{for(const k of AL()){if(y.signal.aborted)return;try{const A=(await rt("/api/runtime/status",{signal:y.signal,timeoutMs:900},k)).role==="hub"?"hub":"client";h=!0,f||l(D=>D?.role===A&&D.baseUrl===k?D:{role:A,baseUrl:k});return}catch{if(y.signal.aborted)return}}},b=()=>{Up(u,w).finally(()=>{!f&&!y.signal.aborted&&(g=window.setTimeout(b,h?ML:kL))}).catch(()=>{})};b();const S=window.setTimeout(()=>{!f&&!h&&l(k=>k?.role==="client"&&k.baseUrl===$n?k:{role:"client",baseUrl:$n})},2500);return()=>{f=!0,y.abort(new Error("LiveDesk runtime role probe stopped.")),g!==null&&window.clearTimeout(g),window.clearTimeout(S)}},[null,r]),o?o.role==="client"?i.jsx(rA,{runtimeBaseUrl:o.baseUrl}):i.jsx(CL,{runtimeBaseUrl:o.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..."})]})}Uk.createRoot(document.getElementById("root")).render(i.jsx(d.StrictMode,{children:i.jsx(NL,{})}));"serviceWorker"in navigator&&window.isSecureContext&&window.location.protocol==="https:"&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).catch(t=>{console.warn("[LiveDesk] PWA service worker registration failed.",t)})},{once:!0});
187
+ ${Lt}`:Lt;try{if(H==="custom"){const yt=await gD(t,Q,$);if(!yt.ok)throw new Error(yt.error||"Custom Agent policy could not be saved.")}const ut=await uD(t,{instruction:Ye,deviceIds:He,permissionMode:H,customPolicyId:Q});if(!ut.ok||!ut.runId)throw new Error(ut.error||"Codex Agent run could not be started.");V(ut.approvals||[]),Ke({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:Hf("codex-run-error"),text:kD(ut)}])}},Re=async(fe,te)=>{ve(fe.approvalId);try{const ce=await pD(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 hD(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 fD(t,te);for(const He of Ne.taskBatches||[])ke(He);_(He=>He===te?"":He),Ke(He=>He?.runId===te?null:He);return}const ce=await yD(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||!D&&!R)){z(!0);try{const fe=await mD(t);if(!fe.ok)throw new Error(fe.error||"모든 Agent 작업을 취소하지 못했습니다.");I(""),_(""),Ke(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{z(!1)}}},$e=async fe=>{F(fe);try{const te=await bD(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`,Ze=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"&&lt.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:Ze})]}),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(rm,{size:12})," All"]}),i.jsxs("button",{type:"button",disabled:!0,title:"Saved Client groups are coming next.",children:[i.jsx(rm,{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(kr,{size:12}):null,fe[0].toUpperCase()+fe.slice(1)]},fe))})]}),i.jsxs("div",{className:"agents-workspace",children:[(D||R)&&i.jsxs("div",{className:"agents-page-status",children:[i.jsxs("span",{children:[Ge.length," Clients · ",SD(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:()=>re(null),children:"Cancel"}),i.jsx("button",{type:"button",className:"danger",onClick:()=>{const fe=P;re(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(UE,{items:N,onCancel:jt,onRetry:$e,busyBatchId:B,approvals:W,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(sD,{devices:n,targetMode:f,selectedIds:g,permissionMode:H,customCategories:$,onSelectPrompt:We,onClose:()=>Pe(!1)}),i.jsx(DE,{ref:ue,value:S,onChange:k,onSubmit:()=>{qe()},onOpenSuggestedTasks:()=>Pe(fe=>!fe),suggestedOpen:ye,suggestedTaskCount:me,disabled:!!D||!!R,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(iD,{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=>{j(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:IE.map(fe=>i.jsxs("label",{children:[i.jsx("span",{children:CD(fe)}),i.jsxs("select",{value:$[fe],onChange:te=>G(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 PS(t){return{type:t.type,deviceIds:t.deviceIds,monitorIndex:t.monitorIndex,label:t.label}}async function _S(t){try{return(await t.json()).error||`${t.status} ${t.statusText}`}catch{return`${t.status} ${t.statusText}`}}async function FS(t,n,r){const o=encodeURIComponent(JSON.stringify({kind:n.kind,fileName:n.fileName,mimeType:t.type||"application/octet-stream",durationMs:n.durationMs,target:PS(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 _S(l));return await l.json()}async function MD(t,n){return await rt("/api/capture-sessions",{method:"POST",body:JSON.stringify({...t,target:PS(t.target)})},n)}async function AD(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 _S(l));return await l.json()}async function ND(t,n,r){return await rt(`/api/capture-sessions/${encodeURIComponent(t)}/finalize`,{method:"POST",body:JSON.stringify({durationMs:n})},r)}async function ox(t,n){await rt(`/api/capture-sessions/${encodeURIComponent(t)}`,{method:"DELETE"},n)}async function TD(t){return await rt("/api/captures",void 0,t)}function lx(t,n){return`${lu(n)}/api/captures/${encodeURIComponent(t)}/content`}async function RD(t,n){return await rt(`/api/captures/${encodeURIComponent(t)}`,{method:"DELETE"},n)}function jD({hubUrl:t,onToast:n}){const[r,o]=d.useState([]),[l,u]=d.useState(!0),f=d.useCallback(async()=>{u(!0);try{o((await TD(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=lx(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(Rd,{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=lx(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(Nk,{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(Jx,{size:15})}),i.jsx("button",{className:"icon-button danger",title:"Delete","aria-label":"Delete",onClick:()=>{window.confirm(`Delete ${g.fileName}?`)&&RD(g.id,t).then(()=>f()).catch(w=>n(w instanceof Error?w.message:String(w)))},type:"button",children:i.jsx(Qx,{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 cx({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(Tk,{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(Yx,{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(Rk,{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(jk,{size:17})})]})}function OS({state:t}){return t==="ok"?i.jsx(Pa,{size:15,"aria-hidden":"true"}):i.jsx(Zx,{size:15,"aria-hidden":"true"})}function ux({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(Ek,{size:18,"aria-hidden":"true"})})}function dx({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($x,{size:18,"aria-hidden":"true"})})}function fx({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(po,{size:18,"aria-hidden":"true"})})}function BS({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(OS,{state:r.state}),i.jsxs("span",{children:[i.jsx("strong",{children:r.label}),i.jsx("small",{children:r.detail})]})]},r.id))})}function ED({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(po,{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(nr,{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(OS,{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 DD=/(nvenc|videotoolbox|qsv|quick\s*sync|amf|vaapi|v4l2m2m|mediafoundation|h264_mf)/i,ID=/(libx264|openh264|software|cpu)/i,xv=2,LD=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 fn(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 At(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 HS(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=At(t,...n);if(r!==void 0)return Math.max(0,Math.min(1,r>1?r/100:r))}function Qe(t,n,r,o){return{id:t,state:n,label:r,detail:o}}function zS(t){const n=fn(t),r=At(n,"helperCount"),o=At(n,"helperOwnedIoTaskCount"),l=At(n,"helperUndisposedProcessCount"),u=At(n,"helperOwnedExitObserverCount"),f=At(n,"helperQuarantineCount"),h=At(n,"utilityQuarantineCount"),g=At(n,"utilityOwnedIoTaskCount"),y=At(n,"utilityUndisposedProcessCount"),w=Number(At(n,"helperDisposeFailureCount")||0),b=Number(At(n,"utilityDisposeFailureCount")||0),S=Math.max(0,Number(r||0)),k=Number(o||0),N=Number(l||0),A=Number(u||0),D=Math.max(0,Number(f||0)),I=Math.max(0,Number(h||0)),R=Number(g||0),_=Number(y||0),B=[o,l,u,f,h,g,y].every(j=>j!==void 0),F=B&&(k<0||N<0||A<0||N!==S||A!==0||S===0&&k!==0||S>0&&k===0),H=B&&(R<0||_<0||_!==I||R!==I*2);return{telemetryAvailable:B,helperOwnedIoTaskCount:k,helperUndisposedProcessCount:N,helperOwnedExitObserverCount:A,helperQuarantineCount:D,helperDisposeFailureCount:w,helperLastDisposeFailure:zt(n,"helperLastDisposeFailure"),helperLedgerMismatch:F,utilityQuarantineCount:I,utilityOwnedIoTaskCount:R,utilityUndisposedProcessCount:_,utilityQuarantinePids:Array.isArray(n.utilityQuarantinePids)?n.utilityQuarantinePids.map(j=>Number(j)).filter(j=>Number.isSafeInteger(j)&&j>0):[],utilityQuarantineProfiles:Array.isArray(n.utilityQuarantineProfiles)?n.utilityQuarantineProfiles.map(j=>String(j||"").trim()).filter(Boolean).slice(0,4):[],utilityQuarantineStartCount:Math.max(0,Number(At(n,"utilityQuarantineStartCount")||0)),utilityQuarantineStopCount:Math.max(0,Number(At(n,"utilityQuarantineStopCount")||0)),utilityDisposeFailureCount:b,utilityLastDisposeFailure:zt(n,"utilityLastDisposeFailure"),utilityLedgerMismatch:H,historicalCleanupFailure:w!==0||b!==0,currentProblem:D>0||I>0||F||H}}function $S({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=nm(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>=LD&&Qc.delete(Qc.keys().next().value),Qc.set(t,{sampleId:o,sampleEpochMs:l,count:h}),{count:h,confirmed:h>=xv}}function nm(t){const n=Date.parse(String(t||""));return Number.isFinite(n)&&n>0?n:void 0}function mx(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 PD(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 US(t){const n=fn(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 px(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 _D(t){const n=US(t);return n==="encrypted-rendezvous-relay"?Qe("control-transport","ok","Control connection: Encrypted rendezvous relay","Commands and remote input use the end-to-end encrypted rendezvous relay."):n==="direct-tcp"?Qe("control-transport","ok","Control connection: Direct TCP","Commands and remote input use the direct Hub connection."):Qe("control-transport","warning","Control connection is not identified","Waiting for Direct TCP or encrypted rendezvous relay status.")}function FD(t,n){const r=fn(t),o=fn(n),l=US(r);if(l==="encrypted-rendezvous-relay"){const u=zt(o,"state")||(o.connected===!0?"registered":"unknown"),f=px(zt(o,"endpoint"))||px(zt(r,"relayEndpoint")),h=r.connected!==!0||o.connected===!1||/(connecting|reconnect|failed|error|degraded|unavailable|disabled)/.test(u);return Qe("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=At(r,"remotePort"),h=u?`${u}${f?`:${f}`:""}`:"-";return Qe("debug-control-transport",r.connected===!0?"ok":"warning","Direct TCP control",`peer ${h} · protocol ${zt(r,"protocol")||"-"} v${At(r,"protocolVersion")??"-"} · input ${fn(r.channels).input===!1?"shared control channel":"dedicated channel"}`)}return Qe("debug-control-transport","warning","Control transport is not identified","No Direct TCP or encrypted rendezvous relay metadata is available.")}function qS(t,n){const r=Number(t?.browserReceivedEpochMs);return Number.isFinite(r)&&r>0?Math.max(0,n-r):Number.POSITIVE_INFINITY}function WS(t,n,r){const o=fn(n?.frameTransport),l=zt(t,"frameTransportChangedAt"),u=zt(o,"changedAt"),f=nm(l),h=nm(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(),D=/(?:^|[-_])ws(?:$|[-_])|websocket/.test(A)||/(?:^|[-_])ws(?:$|[-_])|websocket/.test(b),R=/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"||D?D?"direct-ws":"direct-tcp":"",_=(zt(y,g?"state":"frameTransportState")||zt(w,g?"frameTransportState":"state")||(R?"active":"")).toLowerCase(),B=zt(y,g?"reason":"frameTransportReason")||zt(w,g?"frameTransportReason":"reason"),F=g?u||l:l||u,H=nm(F),j=H===void 0?void 0:Math.max(0,r-H),Q=j===void 0?"":j<1e3?"changed now":j<6e4?`changed ${Math.round(j/1e3)}s ago`:j<36e5?`changed ${Math.round(j/6e4)}m ago`:`changed ${F}`,$=g?o.switchCount??t?.frameTransportSwitchCount:t?.frameTransportSwitchCount??o.switchCount,G=g?o.tcpFailureCount??t?.frameTransportTcpFailureCount:t?.frameTransportTcpFailureCount??o.tcpFailureCount,W=g?typeof o.p2pReady=="boolean"?o.p2pReady:t?.frameTransportP2pReady===!0:typeof t?.frameTransportP2pReady=="boolean"?t.frameTransportP2pReady:o.p2pReady===!0;return{rawTransport:b,videoTransport:R,state:_,reason:B,changedAt:F,changedLabel:Q,switchCount:Math.max(0,Number($??0)||0),tcpFailureCount:Math.max(0,Number(G??0)||0),p2pReady:W}}function OD(t,n,r){const o=WS(t,n,r),l=/(connecting|recovering|failed|error|degraded|unavailable)/.test(o.state);if(o.videoTransport==="encrypted-relay")return Qe("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 Qe("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 Qe("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 Qe("transport","warning","Video transport is not identified",o.reason||"Waiting for Direct TCP, encrypted UDP P2P, or encrypted TCP relay transport data.")}const BD=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 GS(t){const r=String(t?.platformProfile||"").toLowerCase().includes("macos-screencapturekit"),o=Number(t?.nativeCaptureTelemetryVersion)>=5&&BD.every(u=>At(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 HD(t){const n=String(t?.frameMode||t?.mode||t?.codec||"").toLowerCase(),r=[t?.hardwareEncoder,t?.platformProfile].filter(Boolean).join(" · "),o=HS(t,"nativeEncoderHardwareAccelerated"),l=t?.nativeEncoderHardwareAccelerationKnown===!0||o!==void 0,u=GS(t);return!t||!/h264/.test(n)?Qe("encoder","warning","Video encoder unavailable","Waiting for an H.264 frame."):u.required&&!u.available?Qe("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)?Qe("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?Qe("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?Qe("encoder","warning","H.264 hardware acceleration is not active",`${r||"Native encoder"} is running without confirmed hardware acceleration.`):l&&o===!0?Qe("encoder","ok","Hardware H.264 encoding",`${r||"Native encoder"} · hardware acceleration confirmed`):DD.test(r)?Qe("encoder","ok","Hardware H.264 encoding",r):ID.test(r)?Qe("encoder","warning","Software H.264 encoding",`${r||"CPU encoder"} may limit frame rate.`):Qe("encoder","warning","H.264 encoder not identified",r||"The Client has not reported its active encoder profile.")}function zD({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=fn(t),D=fn(A.status),I=fn(o?.lastInfo),R=[],_=qS(n,N);R.push(_D(A)),R.push(w?b?Qe("connection","ok","Video capture is paused","Client screen capture and video encoder shutdown were confirmed by the Client."):Qe("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?Qe("connection","ok","Video connection is current",`${Math.round(_)}ms since the latest frame.`):Qe("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."))),R.push(OD(n,D,N)),R.push(HD(n));const B=zS(D.capture),F=fn(D.capture),H=$S({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)&&R.push(Qe("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 j=Math.max(0,Number(n?.requestedFps||n?.effectiveFps||0)),Q=Math.max(0,Number(r?.framesPerSecond||0));Math.max(0,Number(n?.sourceGapMs||0));const $=Math.max(0,Number(n?.nativeCaptureFps||0)),G=Math.max(0,Number(n?.nativeEncodedFps||0)),W=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),V=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),X=At(n,"nativeCaptureTelemetryAgeMs"),J=Math.max(0,Number(X||0))+(Number.isFinite(_)?_:0),z=V<2||X!==void 0&&J<=It.nativeTelemetryStaleMs,P=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),re=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),we=n?.nativeCaptureTelemetryAvailable===!0&&W>0&&z,Z=At(n,"captureP95Ms","captureAverageMs","captureStageMs"),Se=Math.max(0,Number(Z||0)),ae=n?.captureTimingAvailable===!0&&j>0&&Number(r?.sampleMs||0)>0&&Z!==void 0,ye=ae||we,Pe=Math.max(It.minimumCaptureBudgetMs,j>0?1e3/j*It.captureBudgetMultiplier:0),de=j>0?1e3/j:100,Ke=j>0&&$>=j*It.receiveRatioWarning,ue=G>0&&G<j*It.receiveRatioWarning,Fe=we&&Ke&&ue&&G>=1&&re>=Math.max(10,$*.6)&&P===0,Xe=we&&j>0&&($<j*It.receiveRatioWarning||!Fe&&G>0&&G<j*It.receiveRatioWarning),at=we?Xe:ae&&Se>Pe;R.push(ye?at?Qe("capture","warning","Screen capture cannot keep target speed",we?`${$.toFixed(1)} native capture · ${G.toFixed(1)} encoded · ${j||"?"} requested fps`:`${Se?`capture p95 ${Math.round(Se)}ms`:"capture timing unavailable"} · ${Q.toFixed(1)}/${j||"?"} fps`):Qe("capture","ok","Screen capture speed is healthy",we?`${$.toFixed(1)} native capture · ${G.toFixed(1)} encoded · ${j||"?"} requested fps${Fe?" · idle optimized":""}`:`${Se?`capture p95 ${Math.round(Se)}ms`:"no slow capture reported"}${j?` · ${Q.toFixed(1)}/${j} fps`:""}`):Qe("capture","warning","Screen capture data is still collecting","A current frame-rate and capture-time sample is required."));const Ee=At(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)),Je=!PD(A.remoteAddress),Me=Ci(D,"network.usageRatio"),pe=At(D,"network.latencyMs"),qe=(Me??0)>=It.networkUsageWarningRatio||(pe??0)>=It.networkLatencyWarningMs,Re=n?.hubClientQueueTelemetryAvailable===!0||At(n,"hubClientDropped")!==void 0&&At(n,"hubClientQueueDepth")!==void 0&&At(n,"hubClientQueueLimit")!==void 0&&At(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,$e=Ee!==void 0&&Number(r?.sampleMs||0)>0,We=!Fe&&j>0&&Number(r?.sampleMs||0)>0&&Q<j*It.deliveryRatioWarning,Et=!Fe&&me>Math.max(It.networkDelayWarningMs,de*3),lt=Ge>It.networkDelayWarningMs||Et||ke>It.networkDelayWarningMs||We||_>It.frameAgeWarningMs||qe||O;R.push($e?lt||Je?Qe("network","warning",Je?"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?`${Q.toFixed(1)} of ${j} 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}`:"",Je?String(A.remoteAddress||"external route"):""].filter(Boolean).join(" · ")||"Frame delivery is not current."):Qe("network","ok","Network delivery is healthy",`${Math.round(Ge)}ms Hub-to-browser · ${Fe?`idle optimized at ${G.toFixed(1)} fps`:"the current video rate is on target."}`):Qe("network","warning","Network delivery data is still collecting","A calibrated Hub-to-browser transit sample is required."));const ht=Ci(D,"cpu.usageRatio","cpu.usedRatio","cpu.percent"),Ze=Ci(D,"memory.usedRatio","usedMemRatio"),be=Ci(D,"gpu.usageRatio"),je=Ci(D,"gpu.memory.usedRatio"),Ae=At(D,"gpu.temperatureC","thermal.gpuC"),fe=ht!==void 0&&Ze!==void 0,te=nm(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||(Ze??0)>=It.memoryWarningRatio||(be??0)>=It.gpuWarningRatio||(je??0)>=It.gpuMemoryWarningRatio||(Ae??0)>=It.gpuTemperatureWarningC;R.push(fe?He?Ie?Qe("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(Ze*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(" · ")):Qe("computer","ok","Client computer has working capacity",[`CPU ${Math.round(ht*100)}%`,`memory ${Math.round(Ze*100)}%`,be!==void 0?`GPU ${Math.round(be*100)}%`:""].filter(Boolean).join(" · ")):Qe("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."):Qe("computer","warning","Client performance data is unavailable","CPU and memory telemetry have not been reported yet."));const Lt=Number(n?.monitorIndex),Ye=Number.isInteger(Lt)&&Lt===Number(u),ut=fn(A.channels),yt=fn(A.capabilities),_t=ut.input!==!1&&yt.remoteInput!==!1&&yt.accessibilityPermission!==!1,mt=yt.screenRecordingPermission!==!1,Vt=fn(g),Ct=!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),mn=!f||h&&Ct;R.push(Ye&&mn&&_t&&mt?Qe("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"}.`):Qe("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 an=fn(l),va=Array.isArray(an.canvases)?fn(an.canvases[0]):{},kt=Math.max(0,Number(o?.decoderInputFps||0)),hn=Math.max(0,Number(o?.decoderOutputFps||0)),en=kt>0&&Number(o?.sampleMs||r?.sampleMs||0)>0,nt=Q>0&&Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0&&kt<Q*It.decoderInputRatioWarning,Dt=kt>0?hn/kt:0,gn=zt(va,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Mr=zt(va,"softwareFallbackReason"),Hr=!!Mr||gn==="prefer-software";return R.push(nt?Qe("decoder","warning","Browser decoder input is dropping frames",`${Q.toFixed(1)} received / ${kt.toFixed(1)} decoder input / ${hn.toFixed(1)} output fps.`):en?Hr||Dt<It.decoderOutputRatioWarning?Qe("decoder","warning",Hr?"Browser is using software H.264 fallback":"Browser decoder output is slow",`${Mr||String(I.decoderLabel||gn||"decoder")} · ${kt.toFixed(1)} in / ${hn.toFixed(1)} out fps.`):Qe("decoder","ok",gn==="prefer-hardware"?"Browser requests hardware H.264":"Browser H.264 path is responsive",`${kt.toFixed(1)} in / ${hn.toFixed(1)} out fps. Chrome does not expose definitive hardware acceptance.`):Qe("decoder","warning","Browser decoder data is still collecting","Decoder input and output samples are required before this path can be marked healthy.")),R}function co(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 $D({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=fn(t),S=fn(b.status),k=fn(S.runtimeProcess),N=fn(S.capture),A=zS(N),D=fn(g),I=fn(o?.lastInfo),R=fn(l),_=Array.isArray(R.canvases)?fn(R.canvases[0]):{},B=[],F=Number(u),H=Number(n?.monitorIndex),j=Number.isInteger(H)&&H===F,Q=Number(n?.captureGeneration||0),$=Number(D.captureGeneration||0),G=!f||j&&String(n?.sessionId||"")===String(D.sessionId||"")&&String(n?.commandId||"")===String(D.commandId||"")&&Q>0&&Q===$,W=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)),z=Number(r?.sampleMs||0)>0&&Number(o?.sampleMs||0)>0,P=W>0&&z&&Math.min(V,X||V,J||V)<W*It.deliveryRatioWarning,re=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=At(n,"hubPacketTransitAgeMs"),de=Math.max(0,Number(n?.droppedByAgent||0)),Ke=Math.max(0,Number(n?.hubIngressDropped||0)),ue=n?.hubClientQueueTelemetryAvailable===!0||At(n,"hubClientDropped")!==void 0&&At(n,"hubClientQueueDepth")!==void 0&&At(n,"hubClientQueueLimit")!==void 0&&At(n,"hubClientBufferedBytes")!==void 0,Fe=ue?Math.max(0,Number(n?.hubClientDropped||0)):0,Xe=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+Ke+Fe,ke=qS(n,w),Je=zt(_,"configuredAcceleration","requestedAcceleration")||zt(I,"h264DecodeAcceleration"),Me=zt(_,"softwareFallbackReason"),pe=Math.max(0,Number(R.hardwareReleaseGeneration||0)),qe=Math.max(0,Number(R.hardwareRecoveryProbeCount||0)),Re=Number(R.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=z&&V>0&&ve<V*It.decoderInputRatioWarning,$e=WS(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"),Ze=At(b,"pid","runtimePid")??At(S,"pid","runtimePid","process.pid"),be=At(k,"pid"),je=Ci(k,"cpuUsageRatio"),Ae=At(k,"cpuCorePercent"),fe=At(k,"workingSetBytes"),te=At(k,"privateMemoryBytes"),ce=Math.max(fe||0,te||0),Ne=(be??0)>0&&(fe??0)>0,He=Ne&&(Ze??0)>0&&be!==Ze,Ie=(je??0)>=It.runtimeProcessCpuWarningRatio||ce>=It.runtimeProcessMemoryWarningBytes,Lt=Ci(S,"cpu.usageRatio"),Ye=Ci(S,"memory.usedRatio","usedMemRatio"),ut=Math.max(0,Number(At(N,"videoStreamCount")||0)),yt=Math.max(0,Number(At(N,"audioStreamCount")||0)),_t=At(N,"helperCount"),mt=Math.max(0,Number(_t||0)),Vt=At(N,"helperMaxConcurrent"),Ct=Math.max(mt,Number(Vt||0)),mn=Array.isArray(N.helperPids)?N.helperPids.map(Ma=>Number(Ma)).filter(Ma=>Number.isSafeInteger(Ma)&&Ma>0):[],an=Array.isArray(N.helperProfiles)?N.helperProfiles.map(Ma=>String(Ma||"").trim()).filter(Boolean).slice(0,4):[],va=Ci(N,"helperCpuUsageRatio"),kt=At(N,"helperCpuCorePercent"),hn=At(N,"helperWorkingSetBytes"),en=At(N,"helperPrivateMemoryBytes"),q=Math.max(hn||0,en||0),nt=Math.max(0,Number(At(N,"helperStartCount")||0)),Dt=Math.max(0,Number(At(N,"helperStopCount")||0)),gn=_t!==void 0,Mr=gn&&nt>=Dt&&nt-Dt!==mt,Hr=mt>1||Ct>1||ut>1||Mr||A.currentProblem,Ar=gn&&(ut>0&&mt===0||ut===0&&mt>0),oe=$S({key:We&&Et?`${We}:${Et}`:"",sampleId:zt(N,"sampledAt"),mismatch:Ar}),Ue=Ar&&!oe.confirmed,tt=Hr||oe.confirmed,Pt=(va??0)>=It.captureHelperCpuWarningRatio||q>=It.captureHelperMemoryWarningBytes,wn=!!(We&&Et&&lt&&ht&&(Ze??0)>0),Be=n?.nativeCaptureTelemetryAvailable===!0,it=Math.max(0,Number(n?.nativeCaptureTelemetryVersion||0)),Tt=it>=2,bt=GS(n),Gt=!bt.required||bt.available,ra=At(n,"nativeCaptureTelemetryAgeMs"),Un=Math.max(0,Number(ra||0))+(Number.isFinite(ke)?ke:0),Qt=ra===void 0?"-":`${Math.round(Un)}ms`,En=!Tt||ra!==void 0&&Un<=It.nativeTelemetryStaleMs,zr=Be&&!En,Ht=HS(n,"nativeEncoderHardwareAccelerated"),Pn=n?.nativeEncoderHardwareAccelerationKnown===!0||Ht!==void 0,Ba=zt(n,"nativeEncoderHardwareQueryStatus"),ar=Ba==="0"?"confirmed":Ba,Nr=Math.max(0,Number(n?.nativeCaptureDisplayId||0)),rr=Math.max(0,Number(n?.nativeCaptureFps||0)),Zs=Math.max(0,Number(n?.nativeCompressionOutputCount||0)),Is=Math.max(0,Number(n?.nativeCompressionFps||0)),Dn=Math.max(0,Number(n?.nativeEncodedFps||0)),on=Tt||Zs>0?Is:Dn,il=Math.max(0,Number(n?.nativeCaptureSampleCount||0)),Ls=Math.max(0,Number(n?.nativeEncodableFrameCount||0)),vo=Math.max(0,Number(n?.nativeSkippedFrameCount||0)),Ai=Math.max(0,Number(n?.nativeEncodedFrameCount||0)),sr=Math.max(0,Number(n?.nativeEncodeFramesInFlight||0)),Ld=bt.pending,Ha=bt.timestampOwners,$r=bt.timestampOwnerHighWatermark,ol=bt.coalesced,wt=Math.max(0,Number(n?.nativeBackpressureSkippedFrameCount||0)),_n=bt.pendingReplaced,yo=Math.max(0,Number(n?.nativeIdleSkippedFrameCount||0)),rn=bt.vtActive,cs=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)),Tr=Math.max(0,Number(n?.nativeOutputQueueDroppedCount||0)),bo=n?.nativeOutputQueueAwaitingKeyFrame===!0,ei=bt.nativeAndPipeResidenceAgeMs,ir=bt.handoffDropped,Ni=bt.handoffRecoveryRequests,ti=bt.handoffOldestAgeMs,Bn=sr>2||Ld>1||Ha>2||$r>2||ol>0||sr>=2&&wt>0,or=bt.required&&bt.available&&(rn!==1||cs>1||Ha>2||$r>2),ni=oc>=3||Js>=6*1024*1024||ll>120||Tr>0||bo||ei>250||ir>0||Ni>0||ti>120,cl=`in-flight ${sr}/2 · backpressure skipped ${wt} · idle skipped ${yo} · stdout queue ${oc} AU/${Math.round(Js/1024)} KB/${Math.round(ll)}ms · HWM ${Bt} · dropped ${Tr} · awaiting key ${bo?"yes":"no"} · native+pipe ${Math.round(ei)}ms · handoff ${Math.round(ti)}ms/drop ${ir}/recovery ${Ni}`,lc=`pending ${Ld}/1; timestamp owners ${Ha}/2 (HWM ${$r}); coalesced ${ol}; pending replaced ${_n}; VideoToolbox ${rn} active/HWM ${cs}`,wo=bt.available&&bt.annexBAllocations>0&&bt.annexBPayloadCopies>=bt.annexBAllocations&&bt.annexBPayloadCopiedBytes>0&&bt.pipePayloadAllocations>0&&bt.pipePayloadCopies>=bt.pipePayloadAllocations&&bt.pipePayloadCopiedBytes>0,Ur=`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)`,qr=Be&&il>0&&En,xo=W>0?1e3/W:100,Ps=W>0&&rr>=W*It.receiveRatioWarning,So=on>0&&on<W*It.receiveRatioWarning,za=qr&&Ps&&So&&on>=1&&Dn>=1&&yo>=Math.max(10,rr*.6)&&wt===0,ln=P&&!za,Xn=!za&&we>Math.max(It.networkDelayWarningMs,xo*3),$a=qr&&W>0&&rr<W*It.receiveRatioWarning,kn=qr&&!za&&rr>0&&(Tt&&on<=0||on>0&&on<rr*It.receiveRatioWarning),Fn=qr&&Zs>0&&on>0&&Dn<on*It.receiveRatioWarning,Ua=zr?"Native capture telemetry is stale":Gt?or?"VideoToolbox encoder ownership needs attention":qr?$a?"Native screen capture is below request":kn||Bn?"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(FD(b,y)),B.push(wn?Qe("debug-runtime","ok",`LiveDesk ${lt} · Agent ${ht}`,`pid ${Ze} · session ${co(Et)} · device ${co(We)}`):Qe("debug-runtime","warning","Runtime identity is incomplete",`LiveDesk ${lt||"-"} · Agent ${ht||"-"} · pid ${Ze??"-"} · session ${co(Et)} · device ${co(We)}`)),B.push(Ne&&!He&&!Ie?Qe("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(Ye)}`):Qe("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 ${Ze??"-"} · CPU ${Vl(je)} machine / ${kp(Ae)} core · RSS ${Gl(fe)} · private ${Gl(te)} · system CPU ${Vl(Lt)} · memory ${Vl(Ye)}`)),B.push(n?Qe("debug-frame","ok",`Frame #${Number(n.frameSeq||0)} · ${String(n.streamPurpose||(f?"control":"wall"))}`,`stream ${co(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`):Qe("debug-frame","warning","No current frame",`Device ${co(b.deviceId)} has not produced a frame.`));const lr=/(connecting|recovering|failed|error|degraded|unavailable)/.test($e.state);B.push($e.videoTransport&&!lr?Qe("debug-transport","ok",`${$e.videoTransport==="encrypted-relay"?"Encrypted TCP relay fallback":$e.videoTransport==="p2p-udp"?"P2P UDP":$e.videoTransport==="direct-ws"?"Direct WebSocket":"Direct TCP"} · ${$e.state||"active"}`,[`raw ${$e.rawTransport||"-"}`,`P2P ${$e.p2pReady?"ready":"standby unavailable"}`,`switch ${$e.switchCount}`,`TCP failure ${$e.tcpFailureCount}`,$e.changedLabel,$e.reason].filter(Boolean).join(" · ")):Qe("debug-transport","warning",$e.videoTransport?`Video transport ${$e.state||"needs attention"}`:"Video transport is not identified",[$e.videoTransport||"no active path",`raw ${$e.rawTransport||"-"}`,`P2P ${$e.p2pReady?"ready":"not ready"}`,$e.changedLabel,$e.reason].filter(Boolean).join(" · "))),B.push(j?Qe("debug-monitor","ok",`Monitor selected ${F+1} · frame ${H+1}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${Q||"-"}`):Qe("debug-monitor","warning",`Monitor mismatch: selected ${F+1} · frame ${Number.isInteger(H)?H+1:"-"}`,`reported ${Number(n?.monitorCount||0)||"?"} displays · generation ${Q||"-"}`)),B.push(G&&(!f||h)?Qe("debug-binding","ok",f?"Control generation is bound":"Wall capture generation is current",`session ${co(n?.sessionId)} · command ${co(n?.commandId)} · generation ${Q||"-"}`):Qe("debug-binding","warning",f?"Control generation is not bound":"Wall capture generation is unavailable",`frame ${co(n?.commandId)}/${Q||"-"} · expected ${co(D.commandId)}/${$||"-"} · input ${h?"ready":"waiting"}`)),B.push(z&&!ln?Qe("debug-cadence","ok",`Cadence ${Rn(V)} rx · ${Rn(X)} paint · ${Rn(J)} decode`,`requested ${Rn(W)} · decoder input ${Rn(ve)} fps · receive p95 ${Rn(r?.p95IntervalMs)}ms${za?" · idle optimized":""}`):Qe("debug-cadence","warning",z?"Frame cadence is below request":"Frame cadence sample is collecting",`requested ${Rn(W)} · receive ${Rn(V)} · paint ${Rn(X)} · decode ${Rn(J)} fps`)),B.push(qr&&Gt&&!$a&&!kn&&!Fn&&!Bn&&!or&&!ni&&Ht!==!1?Qe("debug-native-capture","ok",`Native capture ${Rn(rr)} fps · compress ${Rn(on)} fps · stdout ${Rn(Dn)} fps${za?" · idle optimized":""}`,`telemetry v${it||1} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${ar?` (${ar})`:""} · display ${Nr||"-"} · capture samples ${il} · encodable ${Ls} · skipped ${vo} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(re)}ms`):Qe("debug-native-capture","warning",Ua,`telemetry ${Be?`v${it||1}`:"no"} · age ${Qt} · hardware ${Pn?Ht?"yes":"no":"unknown"}${ar?` (${ar})`:""} · display ${Nr||"-"} · capture ${Rn(rr)} fps · compress ${Rn(on)} fps · stdout ${Rn(Dn)} fps · capture samples ${il} · encodable ${Ls} · skipped ${vo} · compression outputs ${Zs} · stdout written ${Ai} · ${cl} · encoded AU output gap ${Math.round(re)}ms`)),bt.required&&(B.push(Gt&&!Bn&&!or?Qe("debug-native-resource","ok","VideoToolbox resource ownership is bounded",lc):Qe("debug-native-resource","warning",Gt?or?"VideoToolbox session ownership is not exclusive":"VideoToolbox encode lane is coalescing":"VideoToolbox resource telemetry is unavailable",lc)),B.push(Gt&&wo?Qe("debug-native-copy","ok","Capture copy accounting is current",Ur):Qe("debug-native-copy","warning",Gt?"Capture copy accounting needs attention":"Capture copy accounting is unavailable",Ur))),B.push(gn&&!tt&&!Pt?Qe("debug-capture-ownership","ok",Ue?"Capture ownership transition is settling":mt>0?"Capture helper ownership is exclusive":"Capture helpers are idle",`video ${ut} · audio ${yt} · helpers ${mt} (max ${Ct||"-"}) · pid ${mn.join(",")||"-"} · profile ${an.join(", ")||"-"} · CPU ${Vl(va)} machine / ${kp(kt)} core · RSS ${Gl(hn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}${Ue?` · mismatch samples ${oe.count}/${xv}`:""}`):Qe("debug-capture-ownership","warning",gn?mt>1||Ct>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 ${Ct||"-"}) · pid ${mn.join(",")||"-"} · profile ${an.join(", ")||"-"} · CPU ${Vl(va)} machine / ${kp(kt)} core · RSS ${Gl(hn)} · private ${Gl(en)} · starts ${nt} / stops ${Dt}`));const qa=`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?Qe("debug-capture-cleanup","ok",mt>0?"Capture cleanup ownership is exact":"Capture cleanup is idle",qa):Qe("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",qa)),B.push(ue?me===0&&Ge===0&&(at<=0||Xe<at)&&!Xn&&Z<=It.networkDelayWarningMs&&ye<=It.networkDelayWarningMs&&(Pe===void 0||Pe<=It.networkDelayWarningMs)?Qe("debug-delivery","ok","Delivery counters are clear",`encoded AU output gap ${Math.round(re)}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 ${Ke} · browser queue drop ${Fe} (${Xe}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}${za?" · idle optimized":""}`):Qe("debug-delivery","warning","Delivery counters show loss or delay",`encoded AU output gap ${Math.round(re)}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 ${Ke} · browser queue drop ${Fe} (${Xe}/${at||"-"}) · buffered ${Math.round(Ee/1024)} KB · UDP incomplete ${Ge}`):Qe("debug-delivery","warning","Browser queue counters are available in Hub Status",`encoded AU output gap ${Math.round(re)}ms · Client send gap ${Math.round(we)}ms · Agent drop ${de} · Hub ingress drop ${Ke} · per-browser lane counters are intentionally collected outside video packets.`));const ai=At(n,"captureP95Ms");return B.push(n?.captureTimingAvailable===!0&&ai!==void 0?Qe("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)}`):qr&&Tt?Qe("debug-capture","ok","Capture latency is not instrumented; native cadence is current",`ScreenCaptureKit ${Rn(rr)} fps · VideoToolbox ${Rn(on)} fps · stdout ${Rn(Dn)} fps · telemetry age ${Qt}`):Qe("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&&Je!=="prefer-software"&&!O?Qe("debug-decoder","ok",`Decoder ${Je||"acceleration unknown"}`,`${String(n?.frameMode||n?.codec||"-")} · ${String(n?.hardwareEncoder||"-")} · ${String(n?.platformProfile||"-")} · ${jt}`):Qe("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||Je||"software"} · ${Rn(ve)} in / ${Rn(J)} out fps · ${jt}`)),B}function UD({status:t,deviceDiagnostics:n=[],codec:r,browser:o,frameStats:l}={}){const u=fn(t),f=fn(u.diagnostics),h=fn(f.system),g=fn(f.network),y=fn(r),w=fn(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=At(h,"totalMemoryBytes"),D=At(h,"cpuLogicalCores")??At(w,"hardwareConcurrency"),I=At(w,"deviceMemory"),R=(D??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=(D??0)>0&&D<4||(k??0)>=It.cpuWarningRatio||(N??0)>=It.memoryWarningRatio||_||B,H=Math.max(0,Number(y.activeSoftwareFallbackCount??y.softwareFallbackCount??0)),j=Math.max(0,Number(y.activeDecoderCount||0)),Q=Math.max(0,Number(l?.bytesPerSecond||0)*8/1e6),$=At(g,"externalDeviceCount"),G=zt(g,"route"),W=$!==void 0&&!!G,V=($??0)>0||G==="external",X=fn(u.frameLanes),ve=fn(X.packetFanout),J=["packetBuilds","metadataSerializations","payloadCopyOperations","fanoutEligibleSubscribers"].every(ye=>At(ve,ye)!==void 0),z=Array.isArray(X.clients)?X.clients.map(fn):[],P=At(X,"clientCount")!==void 0&&Array.isArray(X.clients)&&J,re=z.some(ye=>{const Pe=Math.max(0,Number(ye.queueDepth||0)),de=Math.max(0,Number(ye.queueLimit||0)),Ke=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&&Ke>=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?Qe("hub-runtime","ok","Hub runtime is ready",`${u.connectedDeviceCount||0} Clients connected.`):Qe("hub-runtime","warning","Hub runtime needs attention",String(u.lastError||"Hub is not ready.")),R?F?Qe("hub-computer","warning",_?"Hub has limited system memory":B?"Browser reports limited memory capacity":"Hub computer may limit remote performance",[`${D||"?"} logical cores`,`${mx(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(" · ")):Qe("hub-computer","ok","Hub computer capacity is healthy",`${D||"?"} logical cores · ${mx(A)} RAM · CPU ${k===void 0?"not reported":`${Math.round(k*100)}%`}.`):Qe("hub-computer","warning","Hub performance data is unavailable","Logical-core, CPU, used-memory, and total-memory telemetry are required."),j<=0?Qe("hub-codec","warning","No active browser H.264 decoder to check","Open Wall or Control and wait for a video frame."):H>0?Qe("hub-codec","warning","Some browser decoders use software fallback",`${j} active H.264 decoders · ${H} software fallbacks. Chrome does not expose definitive hardware acceptance.`):Qe("hub-codec","ok","All active streams request hardware H.264",`${j} active decoders. Chrome hardware acceptance is inferred from health, not directly exposed.`),P?re?Qe("hub-frame-lanes","warning","A Hub browser video lane needs attention",`${z.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Qe("hub-frame-lanes","ok","Hub browser video lanes are bounded",`${z.length}/${X.clientCount||0} lanes reported · packet builds ${we} · metadata serializations ${Z} · payload copies ${Se} · fanout deliveries ${ae}.`):Qe("hub-frame-lanes","warning","Hub browser queue data is unavailable","Per-browser queue, drop, buffered-byte, and packet-allocation evidence is required."),S>0?Qe("hub-clients","warning",`${S} Clients need attention`,"Open the matching Wall slot lines for the exact cause."):Qe("hub-clients","ok","Connected Clients report healthy remote paths",`${b.length} Client reports checked.`),Qe("hub-network",!W||V||Q>120?"warning":"ok",W?V?`${$} Clients use an external network route`:Q>120?"Hub receive load is high":"Hub receive load is within range":"Hub network route data is unavailable",W?`${G.toUpperCase()} route · ${Q.toFixed(Q>=10?0:1)} Mbps received by this browser.`:"The Hub has not reported LAN/external route classification yet.")]}async function qD(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,D=N*g,I=S.canvas,R=Math.min(h/I.width,g/I.height),_=Math.max(1,Math.floor(I.width*R)),B=Math.max(1,Math.floor(I.height*R)),F=A+Math.floor((h-_)/2),H=D+Math.floor((g-B)/2);w.drawImage(I,F,H,_,B),n.includeLabels!==!1&&(w.fillStyle="rgba(4, 10, 20, .74)",w.fillRect(A,D+g-28,h,28),w.fillStyle="#f8fafc",w.fillText(S.label,A+9,D+g-9))}return y}function WD(t){return t?.signature||"none"}function GD(t){return t?.label||"No capture target"}function hx(t){return{...t,deviceIds:[...t.deviceIds],sourceCanvas:t.sourceCanvas||null}}function VD(){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 KD(t){return t.replace(/[^a-zA-Z0-9._-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,80)||"Wall"}function QD(t){return`LiveDesk_${t.type==="wall"||t.type==="selection"?"Wall":`${KD(t.label)}_Monitor-${Number(t.monitorIndex||0)+1}`}_${VD()}.png`}async function YD(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 FS(o,{kind:"screenshot",fileName:QD(n),target:n},r);try{await navigator.clipboard.write([new ClipboardItem({"image/png":o})])}catch{}return l.capture}function VS(){return["video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm"].find(n=>typeof MediaRecorder<"u"&&MediaRecorder.isTypeSupported(n))||""}function XD(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 KS(t){if(typeof MediaRecorder>"u"||typeof t.canvas.captureStream!="function")throw new Error("This browser does not support video recording.");const n=VS();if(!n)throw new Error("This browser does not support WebM recording.");const r=t.kind||"recording",o=await MD({kind:r,fileName:XD(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(()=>AD(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 ox(o.sessionId,t.hubUrl).catch(()=>{}),y;await ND(o.sessionId,Math.max(0,performance.now()-f),t.hubUrl)}},cancel:async()=>{g||(g=!0,u.stop(),l.getTracks().forEach(b=>b.stop()),await ox(o.sessionId,t.hubUrl).catch(()=>{}))}}}class ZD{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=VS();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 FS(o,{kind:"last-30s",fileName:u,target:n,durationMs:Math.min(3e4,this.segments.length*1e3)},r)}}async function JD(t,n,r,o,l){const u=await KS({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 QS="livedesk.captureSettings";function eI(){const t={rollingEnabled:!1,recordingQuality:"standard",timelapseIntervalSeconds:10,includeRemoteCursor:!0};try{const n=JSON.parse(localStorage.getItem(QS)||"null");return{...t,...n&&typeof n=="object"?n:{}}}catch{return t}}function tI(t){const[n,r]=d.useState(eI),[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),D=d.useRef(null),I=d.useRef(null),R=d.useRef(new ZD),_=t.sourceRegistry.resolveCurrentTarget(),B=WD(_),F=GD(_),H=typeof MediaRecorder<"u"&&typeof HTMLCanvasElement<"u"&&"captureStream"in HTMLCanvasElement.prototype;d.useEffect(()=>{if(localStorage.setItem(QS,JSON.stringify(n)),!S.current)return;const re=JSON.stringify(n);re!==k.current&&(k.current=re,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 re=!0;return rt("/api/settings",void 0,t.hubUrl).then(we=>{if(!re)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}),()=>{re=!1}},[t.hubUrl]);const j=d.useCallback(async re=>{if(re.sourceCanvas&&re.sourceCanvas.width>0&&re.sourceCanvas.height>0)return{target:hx(re),canvas:re.sourceCanvas,cleanup:()=>{}};const we=await t.sourceRegistry.composeWall(re.deviceIds,{maxWidth:1920,maxHeight:1080,includeLabels:!0});let Z=!1;const Se=window.setInterval(async()=>{if(Z)return;const ae=await t.sourceRegistry.composeWall(re.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:hx(re),canvas:we,cleanup:()=>{Z=!0,window.clearInterval(Se)}}},[t.sourceRegistry]);d.useEffect(()=>{const re=R.current;if(!n.rollingEnabled||!_||!H){re.stop(),g(0);return}let we=!1,Z=null;return(async()=>{try{if(Z=await j(_),we)return;await re.start(Z.canvas,Z.target);const ae=window.setInterval(()=>g(Math.round(re.seconds)),500),ye=()=>{window.clearInterval(ae),Z?.cleanup()};re.__cleanup=ye}catch(ae){we||t.onToast(ae instanceof Error?ae.message:String(ae))}})(),()=>{we=!0,re.stop(),re.__cleanup?.(),re.__cleanup=void 0,g(0)}},[j,t.onToast,n.rollingEnabled,B,H]);const Q=d.useCallback(re=>r(we=>({...we,rollingEnabled:re})),[]),$=d.useCallback(re=>r(we=>({...we,recordingQuality:re})),[]),G=d.useCallback(re=>r(we=>({...we,timelapseIntervalSeconds:re})),[]),W=d.useCallback(async()=>{const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);let we=null;try{we=await j(re),await YD(we.canvas,we.target,t.hubUrl),t.onToast("Screenshot saved")}finally{we?.cleanup(),w(!1)}},[j,t.hubUrl,t.onToast,t.sourceRegistry]),V=d.useCallback(async()=>{if(D.current)throw new Error("Stop the timelapse before recording.");const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await j(re),Z=await KS({canvas:we.canvas,target:we.target,fps:re.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")},[j,t.hubUrl,t.onToast,t.sourceRegistry]),X=d.useCallback(async()=>{const re=N.current;if(re){w(!0);try{await re.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||D.current)throw new Error("Last 30s is unavailable during a recording.");const re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");w(!0);try{await R.current.save(re,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 re=t.sourceRegistry.resolveCurrentTarget();if(!re)throw new Error("화면이 준비된 후 다시 시도하세요.");const we=await j(re),Z=await JD(we.canvas,we.target,n.timelapseIntervalSeconds,t.hubUrl,Se=>t.onToast(Se.message));I.current=we.cleanup,D.current=Z,f(Date.now()),t.onToast("Timelapse started")},[j,t.hubUrl,t.onToast,t.sourceRegistry,n.timelapseIntervalSeconds]),z=d.useCallback(async()=>{const re=D.current;if(re){w(!0);try{await re.stop(),t.onToast("Timelapse saved")}finally{D.current=null,I.current?.(),I.current=null,f(0),w(!1)}}},[t.onToast]);return d.useEffect(()=>{const re=we=>{!N.current&&!D.current||(we.preventDefault(),we.returnValue="")};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[]),d.useEffect(()=>()=>{R.current.stop(),N.current?.cancel(),D.current?.cancel(),A.current?.(),I.current?.()},[]),{state:d.useMemo(()=>({recording:!!N.current,recordingStartedAt:o,timelapse:!!D.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:Q,setRecordingQuality:$,setTimelapseInterval:G,takeScreenshot:W,startRecording:V,stopRecording:X,saveLast30Seconds:ve,startTimelapse:J,stopTimelapse:z}}function nI(){if(typeof window>"u")return{isIos:!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=n&&/CriOS/i.test(t),o=n&&/Safari/i.test(t)&&!/(CriOS|FxiOS|EdgiOS|OPiOS|DuckDuckGo)/i.test(t);return{isIos:n,isSafari:o,browserName:r?"Chrome":o?"Safari":"browser"}}const aI=120,rI=999,qf=5,Wf=30,sI=Number.POSITIVE_INFINITY,YS="livedesk.remoteDirectory",Sv="livedesk.localHubAccessEnabled",iI="livedesk.streamSettings",oI=18,lI="livedesk.controlStreamSettings",cI=10,XS="livedesk.wallCadence",uI=1e3,ZS="livedesk.wallMonitorSelections",JS=2,Fg=512*1024,dI=!1;"".trim();"".trim();const fI=Object.freeze([{code:"ShiftLeft",label:"Shift"},{code:"ControlLeft",label:"Ctrl"},{code:"AltLeft",label:"Alt"},{code:"MetaLeft",label:"Win"}]),mI=1e3/60,Og=1500,pI=650,hI=1800,gI=650,vI=2500,Bg=1500,gx=15e3,vx=120,yx=100,bx=20,yI=6e4,bI=6e4,wx=240,wI=1024,xI=640,SI=360,xx="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,CI=5e3,Sx=2e3,kI=8e3;function Cx(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 MI(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:qf,audience:"Personal trial",note:"5 devices with a standard ad banner."},ltd:{name:"Plus",price:"$79 LTD",ltd:"$79 LTD",limit:Wf,audience:"Creators and homelabs",note:"30 devices, no ads, personal use."},pro:{name:"Pro",price:"$199 LTD",ltd:"$199 LTD",limit:sI,audience:"Business and studios",note:"Commercial use and larger Client walls."}},AI={"mode3-h264-hw":30};function kx(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 NI=512;function la(t,n){return`${t}:${n}`}function uo(t){return[t.deviceId,t.sessionId||"",t.streamId||"",t.commandId||"",Number(t.captureGeneration||0),Number(t.monitorIndex??-1),t.streamPurpose||""].join("|")}const TI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:AI["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},RI={frameMode:"mode3-h264-hw",h264DecodeAcceleration:"prefer-hardware",fps:30,maxWidth:3840,maxHeight:2160,quality:75,showScreenStatus:!1},Mx={maxWidth:3840,maxHeight:2160};function zf(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 eC(t,n){t.push(n),t.length>wx&&t.splice(0,t.length-wx)}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 Ax(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),eC(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 Nx(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 Tx(t){return!t||t.seqGapCount<=0?"none":`${t.seqGapCount} gaps / max ${t.maxSeqGap}`}function jI(t){return Number.isFinite(t)?String(t):"30+"}const tC=[1,2,5,8,12,20,30],Rx={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:Yn.adaptiveDownshiftStableMs,downshiftConsecutiveSamples:Yn.adaptiveDownshiftConsecutiveSamples,recoveryCooldownMs:14e3,minFps:5},jx=2200,EI=2500,DI=8e3,II=3500,LI=7e3,PI=2,_I=2500,FI=7e3,OI=2600,BI=4200,HI=750,zI=2,Ex=2500,Dx=4200,Ix=2200;function Lx(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 La(t){return t.deviceName||t.hostname||t.deviceId}function $I(){return"npx -y --prefer-online livedesk@latest client"}function UI(){return"npx -y --prefer-online livedesk@latest"}function qI(){try{return localStorage.getItem(YS)||""}catch{return""}}function WI(){try{return localStorage.getItem(Sv)==="1"}catch{return!1}}function xd(t){try{t?localStorage.setItem(Sv,"1"):localStorage.removeItem(Sv)}catch{}}function ki(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function mo(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 nC(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=nC(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 GI(t){const n=mo(t);return Array.from({length:n},(r,o)=>ey(t,o))}function VI(t){const n=nC(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 KI(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 aC(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 rC(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 QI(t,n,r){const u=((typeof n?.monitorIndex=="number"?Gf(n.monitorIndex,Math.max(1,n.monitorCount||1)):r)===r?rC(n):null)||aC(t,r);return u?Math.max(.25,Math.min(4,u.width/u.height)):16/9}const Tp=16/9;function Gf(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 Es(t,n){return SN(n,mo(t),t.platform)}function YI(){try{const t=localStorage.getItem(ZS);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)!==JS||!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 XI(t,n){try{const r=Object.fromEntries(Object.entries(t).map(([o,l])=>[o,{monitorIndex:l,topologyFingerprint:n[o]||""}]));localStorage.setItem(ZS,JSON.stringify({version:JS,selections:r}))}catch{}}function ZI(){return{...TI}}function JI(t){try{localStorage.setItem(iI,JSON.stringify({...t,version:oI}))}catch{}}function eL(){return{...RI}}function tL(t){try{localStorage.setItem(lI,JSON.stringify({...t,version:cI}))}catch{}}function nL(){try{return localStorage.getItem(XS)==="slow"?"slow":"fast"}catch{return"fast"}}function aL(t){try{localStorage.setItem(XS,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 rL(t){return Si.fallbackVisibleCounts[t]||Si.fallbackVisibleCounts.large}function Px(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=Rx[n]||Rx.large;return{maxWidth:Math.min(t.maxWidth,o.maxWidth),maxHeight:Math.min(t.maxHeight,o.maxHeight)}}function sL(t,n=Si.minFps){const r=[...tC].sort((l,u)=>l-u),o=Math.max(n,Math.floor(t/2));return[...r].reverse().find(l=>l<t&&l>=n)||o}function iL(t,n){return[...tC].sort((o,l)=>o-l).find(o=>o>t&&o<=n)||n}function Vf(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 _x(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`${_x(r)} / ${_x(t)}`}function oL(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 Fx(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 lL(t){return t===1?"middle":t===2?"right":"left"}function Ox(t,...n){for(const r of n){const o=t?.[r];if(typeof o=="string"&&o.trim())return o.trim()}return""}function Bx(t){const n=Number(t);return Number.isInteger(n)&&n>=1&&n<=rI?n:0}const cL={cpu:"CPU",memory:"MEM",disk:"Disk",gpu:"GPU",vram:"VRAM",npu:"NPU",temp:"Temp",network:"Net"};function uL(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=cL[l.id]||l.label;return l.value&&l.value!=="-"?`${u} ${l.value}`:u}function sC(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=sC(t,r),l=Number(o);if(Number.isFinite(l))return l}}function fo(t,...n){for(const r of n){const o=sC(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 Sd(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 dL(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 iC(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=fo(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"),D=el(aa(n,"gpu.memory.usedRatio","gpu.vramUsedRatio"))??Ug(N,A),I=aa(n,"gpu.temperatureC","thermal.gpuC"),R=el(aa(n,"npu.usedRatio","npu.usageRatio","npu.usedPct","npu.usagePct","npu.percent","accelerators.npu.usageRatio")),_=fo(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"),j=aa(n,"network.latencyMs","network.rttMs"),Q=el(aa(n,"network.usedRatio","network.usageRatio","network.saturationRatio")),$=fo(n,"network.link","network.interface","network.name"),G=Math.max(b??Number.NEGATIVE_INFINITY,I??Number.NEGATIVE_INFINITY),W=Number.isFinite(G)?G:void 0,V=W===void 0?void 0:el((W-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=fo(n,"workload.role","role","lane")||(Op(t,"taskDispatch")?"Command-ready Client":"Local machine"),J=fo(t.latestTask,"status")||fo(n,"workload.status")||"idle",z=fo(t.latestTask,"title","instructionPreview")||fo(n,"workload.title"),P=fo(t.latestTask,"resultSummary","error","instructionPreview")||fo(n,"workload.summary"),re=Date.parse(t.lastSeenAt||t.connectedAt||""),we=Number.isFinite(re)?Date.now()-re:0;let Z="online";t.connected?we>5*6e4?Z="stale":(b??0)>=86||(I??0)>=88||(l??0)>=.94||(S??0)>=.96||(D??0)>=.96||(R??0)>=.96||(h??0)>=.94||(w??0)>=.94||(j??0)>=200||J==="failed"?Z="critical":(b??0)>=78||(I??0)>=80||(l??0)>=.82||(S??0)>=.86||(D??0)>=.88||(R??0)>=.86||(h??0)>=.82||(w??0)>=.86||(j??0)>=80?Z="warn":["queued","running","targeted"].includes(J)&&(Z="busy"):Z="offline";const Se=[{id:"cpu",label:"CPU",value:Sd(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:Sd(h),detail:$g(u,f),ratio:h,state:Zc(h,.92,.78)},{id:"disk",label:"DISK",value:Sd(w),detail:$g(g,y),ratio:w,state:Zc(w,.92,.82)},{id:"gpu",label:"GPU",value:Sd(S),detail:k||(N&&A!==void 0?`${Vf(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:Sd(D),detail:$g(N,A),ratio:D,state:Zc(D,.96,.88)},{id:"npu",label:"NPU",value:R!==void 0?Sd(R):B!==void 0?`${Math.round(B)} TOPS`:"-",detail:_||(B!==void 0?"neural engine":"not reported"),ratio:R,state:Zc(R,.96,.86)},{id:"temp",label:"TEMP",value:X,detail:`uptime ${dL(aa(n,"uptimeSec"))}`,ratio:V,state:W===void 0?"unknown":W>=86?"critical":W>=78?"warn":"good"},{id:"network",label:"NET",value:qg(F)||(j!==void 0?`${Math.round(j)}ms`:$||"-"),detail:qg(H)?`${qg(H)} up`:$||"not reported",ratio:Q,state:j!==void 0&&j>=200?"critical":j!==void 0&&j>=80?"warn":Zc(Q,.9,.75)}];return{state:Z,label:uL(Z,Se,J),role:ve,taskLabel:z||(J==="idle"?"idle":J),taskStatus:J,taskSummary:P,metrics:Se}}const fL=[{id:"slow",label:"Slow",fps:pv("slow")},{id:"fast",label:"Fast",fps:pv("fast")}],mL=[{id:"list",label:"List"},{id:"medium",label:"Small"},{id:"large",label:"Large"}],pL=[{id:"sync-server",label:"Hub",icon:po,accent:"blue",tooltip:"hub"},{id:"wall",label:"Wall",icon:e0,accent:"blue",tooltip:"wall"},{id:"control",label:"Control",icon:$f,accent:"red",tooltip:"control"},{id:"share-files",label:"Share Files",icon:Yf,accent:"green",tooltip:"share-files"},{id:"agents",label:"Agents",icon:jp,accent:"violet",tooltip:"agents"}],hL=[{id:"doc",label:"Doc",icon:Hp,accent:"amber"},{id:"support",label:"Support",icon:Kf,accent:"violet"},{id:"pricing",label:"Pricing",icon:Qf,accent:"green"}];function gL(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 Qn(t){return gL(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=>Qn(n))}function Sr(t){return{languageName:t.languageName,languageLabel:t.languageLabel,eyebrow:t.eyebrow,title:Qn(t.title),intro:Qn(t.intro),sections:[{title:Qn(t.managerTitle),body:Qn(t.managerBody),points:Jc(t.managerPoints)},{title:Qn(t.clientTitle),body:Qn(t.clientBody),points:Jc(t.clientPoints)},{title:Qn(t.syncTitle),body:Qn(t.syncBody),points:Jc(t.syncPoints)},...t.agentTitle&&t.agentBody&&t.agentPoints?[{title:Qn(t.agentTitle),body:Qn(t.agentBody),points:Jc(t.agentPoints)}]:[],{title:Qn(t.platformTitle),body:Qn(t.platformBody),points:Jc(t.platformPoints)}],sync:{title:Qn(t.syncTitle),body:Qn(t.syncBody),points:Jc(t.syncPoints)},firewall:{title:Qn(t.firewallTitle),body:Qn(t.firewallBody),points:Jc(t.firewallPoints)},commands:{title:Qn(t.commandsTitle),body:Qn(t.commandsBody),manager:Qn(t.managerCommandLabel),primary:Qn(t.clientCommandLabel),slot:Qn(t.slotCommandLabel),manual:Qn(t.manualCommandLabel)}}}const Td={ko:Sr({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:Sr({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:Sr({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":Sr({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":Sr({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:Sr({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:Sr({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:Sr({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":Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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:Sr({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ı"})},vL=Object.entries(Td).map(([t,n])=>({id:t,label:n.languageName}));function yL(){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(Td[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(Td[o])return o}return"en"}function Hx({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(kr,{size:24}),i.jsxs("strong",{children:["Slot ",String(n).padStart(3,"0")]})]})]})})}const bL=["cpu","gpu","memory","vram","network","disk","temp"];function wL({device:t,slotNumber:n,selected:r,updateIndicator:o,remoteDiagnostics:l,diagnosticsMode:u="remote",onSelect:f,onOpenControl:h}){const g=iC(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(kr,{size:17})}),i.jsxs("span",{children:[i.jsx("strong",{children:La(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})]}),bL.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(BS,{items:l,mode:u})})]})}function xL(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 SL(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:D,showPresentationSpinner:I=!1,remoteDiagnostics:R,diagnosticsMode:_="remote"}){const B=d.useRef(null),F=d.useRef(null),H=d.useRef(0),j=d.useRef(null),Q=iC(t),$=["cpu","gpu","memory","vram"].map(ue=>Q.metrics.find(Fe=>Fe.id===ue)).filter(ue=>!!ue),G=Fv(f),W=h>1,V=D??!!n,X=xL(t)&&!V,ve=I&&t.connected&&!V&&!X,J=QI(t,n,G),z=J>=Tp?100:J/Tp*100,P=J>=Tp?Tp/J*100:100,re={"--screen-aspect":J.toFixed(5),"--screen-content-width":`${Math.max(1,Math.min(100,z)).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 Fe=ue.currentTarget.getBoundingClientRect();return mN(ue.clientX,ue.clientY,Fe)},Se=ue=>gN(ue,N),ae=d.useCallback(()=>{j.current!==null&&(window.cancelAnimationFrame(j.current),j.current=null)},[]),ye=d.useCallback(()=>{const ue=F.current;if(!ue)return;F.current=null;const Fe=Number(ue.input.normalizedX),Xe=Number(ue.input.normalizedY);if(!Number.isFinite(Fe)||!Number.isFinite(Xe))return;k(t.deviceId,{...ue.input,normalizedX:Fe,normalizedY:Xe})&&(H.current=performance.now())},[t.deviceId,k]),Pe=d.useCallback(()=>{j.current===null&&(j.current=window.requestAnimationFrame(()=>{j.current=null,ye()}))},[ye]);d.useEffect(()=>()=>{ae(),F.current=null},[ae]);const de=(ue,Fe)=>{if(!o)return;const Xe={type:Fe,monitorIndex:G,...Z(ue),button:lL(ue.button),...Se(ue)};if(Fe==="pointermove"){const at=performance.now();F.current={input:Xe},at-H.current>=mI&&(ae(),ye()),Pe();return}F.current&&(ae(),ye()),k(t.deviceId,Xe)},Ke=d.useCallback(ue=>{const Fe=document.activeElement;Fe instanceof HTMLElement&&ue.contains(Fe)&&Fe.classList.contains("monitor-cycle-button")&&Fe.blur()},[]);return i.jsx("article",{className:`device-tile ${r?"selected":""} ${t.connected?"online":"offline"}`,"data-live-device-id":t.deviceId,style:re,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=>Ke(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":G,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:G,...Z(ue),deltaX:ue.deltaX,deltaY:ue.deltaY,...Se(ue)}))},onContextMenu:ue=>o&&ue.preventDefault()},`${t.deviceId}:monitor:${G}`)}),!V&&i.jsx("span",{className:"empty-screen",children:i.jsx(kr,{size:26})}),u&&i.jsx("span",{className:"wall-device-title",title:La(t),children:La(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(ha,{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(Pa,{size:20,"aria-hidden":"true"}):A.state==="failed"?i.jsx(nr,{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-${Q.state}`,children:Q.label}),i.jsx("span",{className:"tile-metrics","aria-label":`${La(t)} status`,children:$.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))})]}),R&&i.jsx(BS,{items:R,mode:_}),W&&i.jsxs("span",{className:"monitor-cycle","aria-label":`${La(t)} display ${G+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(t0,{size:18})}),i.jsxs("span",{className:"monitor-cycle-count",children:["Screen ",G+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 CL({visible:t}){const n=dI;return d.useEffect(()=>{},[n]),null}function kL({runtimeBaseUrl:t=""}){const{session:n,loading:r}=G1();HM(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}=K1(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,$n]).filter(Boolean))],[g,h,y]),[b,S]=d.useState(()=>typeof window<"u"&&window.matchMedia(gw).matches),[k,N]=d.useState(null),[A]=d.useState(nI),[D,I]=d.useState(!1),[R,_]=d.useState(()=>typeof window>"u"?!1:!!window.navigator.standalone||window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)").matches);d.useEffect(()=>{if(!g){N(null);return}const m=window.matchMedia("(display-mode: standalone), (display-mode: fullscreen)"),x=()=>_(m.matches||!!window.navigator.standalone),C=T=>{T.preventDefault(),N(T)},E=()=>{N(null),_(!0)};return x(),m.addEventListener("change",x),window.addEventListener("beforeinstallprompt",C),window.addEventListener("appinstalled",E),()=>{m.removeEventListener("change",x),window.removeEventListener("beforeinstallprompt",C),window.removeEventListener("appinstalled",E)}},[g]);const B=d.useCallback(async()=>{const m=k;if(!m){A.isIos&&I(!0);return}N(null);try{await m.prompt(),(await m.userChoice).outcome==="accepted"&&_(!0)}catch(x){N(m),console.warn("[LiveDesk] PWA install prompt failed.",x)}},[A.isIos,k]);d.useEffect(()=>{const m=window.matchMedia(gw),x=()=>S(m.matches);return x(),m.addEventListener("change",x),()=>m.removeEventListener("change",x)},[]),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(!b){x();return}m.classList.add("livedesk-mobile-console-active");const C=window.visualViewport;let E=0;const T=()=>{E=0;const K=EN(C,window.innerHeight,window.innerWidth);m.style.setProperty("--livedesk-mobile-viewport-height",`${K.height}px`),m.style.setProperty("--livedesk-mobile-viewport-top",`${K.offsetTop}px`),m.style.setProperty("--livedesk-mobile-viewport-width",`${K.width}px`),m.style.setProperty("--livedesk-mobile-viewport-left",`${K.offsetLeft}px`)},U=()=>{E||(E=window.requestAnimationFrame(T))};return T(),C?.addEventListener("resize",U),C?.addEventListener("scroll",U),window.addEventListener("resize",U),window.addEventListener("orientationchange",U),window.addEventListener("pageshow",U),()=>{E&&window.cancelAnimationFrame(E),C?.removeEventListener("resize",U),C?.removeEventListener("scroll",U),window.removeEventListener("resize",U),window.removeEventListener("orientationchange",U),window.removeEventListener("pageshow",U),x()}},[b]);const[F,H]=d.useState(WI),j=d.useMemo(()=>w.some(m=>!!Zf(m)),[w]),Q=g?!!n:!j||F,{status:$,devices:G,error:W,refresh:V,hubBaseUrl:X}=V1(w,Q,n?.access_token||""),{entitlement:ve,licensed:J,loading:z,error:P,refresh:re}=Q1(n),[we,Z]=d.useState([]),[Se,ae]=d.useState(""),[ye,Pe]=d.useState(""),[de,Ke]=d.useState(""),[ue,Fe]=d.useState(""),[Xe,at]=d.useState(""),[Ee,Ge]=d.useState("idle"),[me,ke]=d.useState(!1),[Je,Me]=d.useState(""),[pe,qe]=d.useState(null),Re=d.useRef(null),[st,jt]=d.useState(""),O=d.useRef("");O.current=ue;const[$e,We]=d.useState(!1),[Et,lt]=d.useState([]),ht=d.useRef(null),[Ze,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=IN());const He=d.useRef(document.visibilityState==="visible"),[Ie,Lt]=d.useState({}),Ye=d.useRef({}),ut=d.useRef(new Set),yt=d.useRef(new Map),_t=d.useRef(new Map),[mt,Vt]=d.useState({}),Ct=d.useMemo(()=>new Set(Object.keys(Ie)),[Ie]),mn=d.useCallback((m,x)=>{if(!m)return;const C={...Ye.current};x?C[m]=x:delete C[m],Ye.current=C,Lt(C)},[]),an=d.useCallback((m,x)=>{m&&Vt(C=>{if(!!C[m]===x)return C;const E={...C};return x?E[m]=!0:delete E[m],E})},[]),va=d.useCallback((m,x)=>{m&&_t.current.set(m,{paused:x,expiresAt:Date.now()+kI})},[]),[kt,hn]=d.useState(""),[en,q]=d.useState(""),[nt,Dt]=d.useState(!1),gn=d.useRef(null),Mr=d.useRef(null);d.useEffect(()=>{kt==="auth"&&n?.access_token&&hn("")},[kt,n?.access_token]);const[Hr,Ar]=d.useState(""),[oe,Ue]=d.useState(null),tt=d.useRef(null),Pt=d.useRef(0),wn=d.useCallback((m,x,C)=>{const E=String(m||"").trim();if(Ar(E),tt.current!==null&&(window.clearTimeout(tt.current),tt.current=null),!E){Ue(null);return}const T=++Pt.current;if(Ue({id:T,message:E,tone:x}),!C)return;const U=window.setTimeout(()=>{Ue(K=>K?.id===T?null:K),tt.current===U&&(tt.current=null)},5e3);tt.current=U},[]),Be=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[Tt,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,Un]=d.useState(nL),Qt=pv(Cn),[En,zr]=d.useState(!1),[Ht,Pn]=d.useState(!1),[Ba,ar]=d.useState(!1),[Nr,rr]=d.useState(!1),[Zs,Is]=d.useState(Date.now),Dn=d.useRef(null);d.useEffect(()=>()=>{Dn.current!==null&&window.clearTimeout(Dn.current)},[]);const[on,il]=d.useState(yL),[Ls,vo]=d.useState(!1),[Ai,sr]=d.useState(!1),[Ld,Ha]=d.useState(!1),[$r,ol]=d.useState(qI),[wt]=d.useState(ZI),[_n]=d.useState(eL),[yo]=d.useState(YI),[rn,cs]=d.useState(yo.selections),oc=d.useRef({...yo.topologyFingerprints}),Js=d.useRef({}),ll=d.useRef({...yo.selections}),[Bt,Tr]=d.useState(null),[bo,ei]=d.useState({}),ir=d.useRef(new Set),[Ni,ti]=d.useState([]),[Bn,or]=d.useState(Qt),[ni,cl]=d.useState(""),[lc,wo]=d.useState(0),[Ur,qr]=d.useState(0),[xo,Ps]=d.useState(0),[So,za]=d.useState(()=>new Set),ln=d.useRef(new Map),Xn=d.useRef(new Map),$a=d.useRef(new Map),kn=d.useRef(new Map),Fn=d.useRef(null),Ua=d.useRef(new Map),lr=d.useRef(new Set),qa=d.useRef(new Map),ai=d.useRef(new Map),Ma=d.useRef(new Map),Wr=d.useRef(new Map),Ti=d.useRef(new WeakMap),Co=d.useRef(new WeakMap),Ri=d.useRef(""),cr=d.useRef(null),fm=d.useRef(Promise.resolve()),cu=d.useRef(0),ji=d.useRef(null),Rr=d.useRef(null),cc=d.useRef(""),Aa=d.useRef(new Map),ul=d.useRef(null),uc=d.useRef(0),_s=d.useRef(new Map),uu=d.useRef(typeof window<"u"&&new URLSearchParams(window.location.search).get("livedeskTransmissionProbe")==="1"),du=d.useRef(new Map),Pd=d.useRef([]),mm=d.useRef(0),[dl,_d]=d.useState({}),Ei=d.useRef(new Map),[fu,dc]=d.useState({}),mu=d.useRef(null),[Fd,Wa]=d.useState(!1),pu=d.useRef(null),hh=d.useRef(0),ri=d.useRef(null),pm=d.useRef(new Map),us=d.useRef(null),Gr=d.useRef(null),Ga=d.useRef(null),si=d.useRef(!1),hm=d.useRef(0),qn=d.useRef(0),ya=d.useRef(""),Od=d.useRef(Promise.resolve()),ko=d.useRef(""),Nt=d.useRef(null),ba=d.useRef(""),Mo=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()),Fs=d.useRef(new Map),Os=d.useRef(new Map),Bs=d.useRef(new Map),Li=d.useRef(new Map),Ao=d.useRef(new Map),oi=d.useRef(new Map),jr=d.useRef(document.visibilityState==="visible"),ds=d.useRef(1),hu=d.useRef([]),[Na,gh]=d.useState(document.visibilityState==="visible"),[ml,vh]=d.useState(0),mc=d.useRef(0),gu=d.useRef(0),Ta=d.useRef(0),Pi=d.useRef(0),vu=d.useRef(0),yu=d.useRef(new Map),pl=d.useRef([]),Bd=d.useRef(new Map),bu=d.useRef(new Map),li=d.useRef(new Map),ci=d.useRef(new Set),_i=d.useCallback(m=>r1(Ti.current,m),[]),Hs=d.useCallback(m=>Dv(Co.current,m),[]),ui=d.useCallback((m,x)=>Zb(Co.current,m,x),[]),Zn=d.useCallback(m=>{const x=Xb(Ti.current,m);return Xb(Co.current,m),x},[]),Vr=d.useCallback((m,x)=>Zb(Ti.current,m,x),[]),No=d.useCallback(m=>Rr.current===m||Fn.current===m?!0:[ln.current,Xn.current,$a.current,kn.current,Aa.current].some(C=>Array.from(C.values()).some(E=>E===m)),[]),wa=d.useCallback(m=>{m&&(Zn(m),ci.current.add(m),o1(m,{isCurrent:No,dispose:vd,schedule:x=>queueMicrotask(()=>{try{x()}finally{ci.current.delete(m)}})}))},[No,Zn]),Ra=d.useCallback(m=>(Zn(m),lh(m,vd)),[Zn]),Fi=d.useCallback(()=>{const m=Rr.current,x=Fn.current,C=[...ci.current];Rr.current=null,Fn.current=null,ci.current.clear(),Ti.current=new WeakMap,Co.current=new WeakMap,Wr.current.clear(),cc.current="",i1([ln.current,Xn.current,$a.current,kn.current,Aa.current],[m,x,...C],vd),ul.current=null,uc.current=0,Ua.current.clear(),lr.current.clear(),qa.current.clear(),ai.current.clear(),Ma.current.clear(),_s.current.clear(),du.current.clear(),Pd.current.length=0,Ei.current.clear(),ut.current.clear()},[]);d.useEffect(()=>()=>{Fi()},[Fi]);const ua=d.useCallback((m,x)=>{const C=la(m,x),E=performance.now();ii.current.delete(C),Di.current.delete(C),Fs.current.delete(C),Os.current.delete(C),oi.current.delete(C),li.current.delete(C),Ei.current.delete(C),_s.current.delete(C),dc(T=>{if(!Object.prototype.hasOwnProperty.call(T,C))return T;const U={...T};return delete U[C],U}),_d(T=>{if(!Object.prototype.hasOwnProperty.call(T,C))return T;const U={...T};return delete U[C],U}),m==="control"?(Bs.current.delete(C),Li.current.set(C,E)):Ao.current.set(C,E)},[]),[Oi,di]=d.useState(null),[yh,Hd]=d.useState(!1),[ty,gm]=d.useState([]),[To,zd]=d.useState("all"),[ja,hl]=d.useState([]),[fs,pc]=d.useState(!1),[vm,wu]=d.useState(!0),hc=d.useRef(null),xu=d.useRef(null),Ro=d.useRef(null),ym=d.useRef(null),Su=d.useRef(!1),Bi=d.useRef(!1),Cu=d.useRef(0),Wn=d.useRef(0),ms=d.useRef(0),da=d.useRef(0),gc=d.useRef(0),jo=d.useRef(""),ps=Tt==="settings",ku=Tt==="pricing",$d=Tt==="doc",Mu=Tt==="support",Hi=Tt==="share-files",Va=Tt==="agents",hs=!ps&&!ku&&!$d&&!Mu&&!Hi&&!Va,dt=Tt==="control",vc=_N(Tt),Ka=Na&&Tt==="wall",Er=d.useRef(Ka);Er.current=Ka;const Kr=vc&&pl.current.length>0,ur=Na&&(Tt==="wall"||dt||Kr),Qa=d.useRef(ur);Qa.current=ur;const Dr=Na&&(dt||Ka),Eo=Na&&(Dr||vc&&(Ee==="connecting"||Ee==="active")),yc=d.useRef({active:ur,epoch:ds.current});yc.current.active!==ur&&(ds.current+=1,yc.current={active:ur,epoch:ds.current}),d.useEffect(()=>{hs||(zr(!1),Pn(!1),ar(!1))},[hs]);const Kt=wt.frameMode==="mode4-h264-atlas",Ir=Xe||_n.frameMode,Gn=Ir!=="mode3-h264-hw"?Math.min(30,_n.fps):_n.fps,cn=G.find(m=>m.deviceId===ye),Yt=cn?.platform,$i=cn?Es(cn,rn[cn.deviceId]):0,Ya=cn?ey(cn,$i):null,Au=SL(Yt)?{maxWidth:1280,maxHeight:720}:Mx,fi=Ir!=="mode3-h264-hw"?{maxWidth:1920,maxHeight:1080}:Mx,bc={maxWidth:Math.min(fi.maxWidth,Au.maxWidth,_n.maxWidth),maxHeight:Math.min(fi.maxHeight,Au.maxHeight,_n.maxHeight)},gs={maxWidth:Ya?.width?Math.min(bc.maxWidth,Ya.width):bc.maxWidth,maxHeight:Ya?.height?Math.min(bc.maxHeight,Ya.height):bc.maxHeight};d.useEffect(()=>{if($?.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,$?.started]),d.useEffect(()=>{!n?.access_token||!$?.started||$.runtimeRole!=="hub"||!$.deviceId||(async()=>{try{const{data:m,error:x}=await $t.rpc("register_livedesk_device",{p_device_id:$.deviceId,p_device_name:$.deviceName||$.deviceId,p_role:"hub",p_assigned_hub_id:null,p_platform:navigator.platform||navigator.userAgent,p_os_version:navigator.userAgent,p_app_version:$.managerVersion||$.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,$?.deviceId,$?.deviceName,$?.managerPackage,$?.managerVersion,$?.runtimeRole,$?.started]);const pt=d.useMemo(()=>G.filter(m=>m.connected),[G]);d.useEffect(()=>{const m={...Ye.current},x=Date.now();let C=!1;Vt(E=>{const T={...E};let U=!1;for(const K of G){const ee=String(K.liveCapturePause?.token||"").trim(),ie=_t.current.get(K.deviceId);if(ie)if((ie.paused?!!ee:!ee)||ie.expiresAt<=x)_t.current.delete(K.deviceId);else continue;const se=!!ee&&(K.liveCapturePause?.captureStopConfirmed!==!0||K.liveCapturePause?.phase==="stop-unconfirmed");!!T[K.deviceId]!==se&&(U=!0,se?T[K.deviceId]=!0:delete T[K.deviceId])}return U?T:E});for(const E of G){const T=String(E.liveCapturePause?.token||"").trim(),U=String(m[E.deviceId]||""),K=_t.current.get(E.deviceId);if(K)if((K.paused?!!T:!T)||K.expiresAt<=x)_t.current.delete(E.deviceId);else continue;T&&T!==U?(m[E.deviceId]=T,C=!0):!T&&U&&(delete m[E.deviceId],yt.current.delete(E.deviceId),C=!0)}C&&(Ye.current=m,Lt(m))},[G]);const Ui=To==="all"?pt.length:ja.filter(m=>pt.some(x=>x.deviceId===m)).length,Ud=d.useMemo(()=>pt.reduce((m,x)=>Math.max(m,Bx(x.slotNumber)),0),[pt]),Do=Math.max(aI,pt.length,Ud),mi=d.useMemo(()=>{const m=Array(Do).fill(null),x=[];for(const C of pt){const E=Bx(C.slotNumber);E>0&&E<=Do&&!m[E-1]?m[E-1]=C:x.push(C)}for(const C of x){const E=m.findIndex(T=>!T);E<0?m.push(C):m[E]=C}return m},[pt]),qi=d.useMemo(()=>mi.flatMap((m,x)=>m?[{device:m,slotNumber:x+1}]:[]),[mi]),Qr=d.useMemo(()=>pt.map(m=>m.deviceId),[pt]),dr=d.useMemo(()=>new Set(we),[we]),In=d.useMemo(()=>pt.filter(m=>dr.has(m.deviceId)),[pt,dr]),Wi=d.useMemo(()=>G.find(m=>m.deviceId===Se)||In[0]||null,[G,Se,In]),xa=d.useMemo(()=>G.find(m=>m.deviceId===ye)||null,[ye,G]),Ea=xa?Es(xa,rn[xa.deviceId]):0,De=dt?xa:Wi,Gi=d.useMemo(()=>new Set(ja),[ja]),Sa=d.useMemo(()=>To==="all"?pt.map(m=>m.deviceId):pt.filter(m=>Gi.has(m.deviceId)).map(m=>m.deviceId),[pt,Gi,To]),Nu=De?Op(De,"control"):!1,Tu=tl(De?.platform)&&(De?.capabilities?.controlPermission===!1||De?.capabilities?.accessibilityPermission===!1),vs=De?Op(De,"audio")||Op(De,"remoteAudio"):!1,Io=(Array.isArray(De?.capabilities?.agentTools)?De.capabilities.agentTools.map(String):[]).includes("system.power"),Ut=J?ve?.plan==="pro"?"pro":"ltd":"free",Ru=Xc[Ut],Lo=Ru.limit,fr=d.useMemo(()=>new Set(HN(pt,Lo)),[Lo,pt]),qd=!De||fr.has(De.deviceId),gl=Ut==="free",Xt=qd,vl=Ut==="ltd"?`Plus includes up to ${Wf} Clients. Upgrade to Pro for commercial use and larger walls.`:`Free includes up to ${qf} Clients. Upgrade to Plus for ${Wf} devices and no ads.`,bm=Ut==="free",ys=Xt&&!!De&&Nu,ju=Xt&&!!De&&vs,bs=d.useMemo(()=>dt?De?[De]:[]:In.length>0?In:De?[De]:[],[De,In,dt]),Da=d.useMemo(()=>bs.filter(m=>fr.has(m.deviceId)),[fr,bs]),Po=Da.some(m=>String(Ie[m.deviceId]||"").startsWith("pending:")||mt[m.deviceId]===!0),mr=!(Da.length>0&&Da.every(m=>{const x=String(Ie[m.deviceId]||"");return!!x&&!x.startsWith("pending:")&&mt[m.deviceId]!==!0}))||Po,yl=d.useMemo(()=>mi.filter(m=>!!m?.connected).slice(0,rL(Gt)).map(m=>m.deviceId),[mi,Gt]),_o=d.useMemo(()=>ur?Ka?Kt||Gt==="list"?Qr:wt.visibleOnlyLive?Ni.length>0?Ni:yl:Qr:pl.current.length>0?pl.current:Qr:[],[yl,Kt,Ni,wt.visibleOnlyLive,Qr,ur,Ka,Gt]),Xa=d.useMemo(()=>zg(_o.filter(m=>fr.has(m))),[fr,_o]);pl.current=Xa;const ws=d.useMemo(()=>Xa.filter(m=>m!==ni&&!Ct.has(m)),[Ct,Xa,ni]),wc=d.useMemo(()=>new Map(pt.map(m=>[m.deviceId,m.platform])),[pt]),xs=d.useMemo(()=>Object.fromEntries(pt.map(m=>[m.deviceId,String(m.sessionId||"").trim()])),[pt]),Ia=zN(Kt,Xa.length),Za=d.useMemo(()=>Kt?ws.filter(m=>_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(wc.get(m))})==="atlas"):[],[Ia,Kt,wc,ws]),pr=d.useMemo(()=>ws.filter(m=>_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(wc.get(m))})==="direct"),[Ia,Kt,wc,ws]),Fo=d.useMemo(()=>{const m=wt.autoStartLive?ws.map(x=>la("wall",x)):[];return Eo&&Xt&&de&&fr.has(de)&&(Ee==="connecting"||Ee==="active"||Ee==="warm")&&m.push(la("control",de)),[...new Set(m)].sort()},[Eo,de,Ee,Xt,fr,wt.autoStartLive,ws]);d.useEffect(()=>{const m=new Set(Xa);za(x=>{let C=!1;const E=new Set;for(const T of x)m.has(T)?E.add(T):C=!0;return C?E:x})},[Xa]);const xc=d.useMemo(()=>{const m=T=>pt.find(U=>U.deviceId===T)||null,x=T=>{const U=m(T);return U?Es(U,rn[T]):0},C=(T,U=x(T))=>T===de&&(Ee==="connecting"||Ee==="active"||Ee==="warm")?kn.current.get(T)||Xn.current.get(T)||null:Kt?Aa.current.get(T)||ln.current.get(T)||null:ln.current.get(T)||null,E=(T,U=x(T))=>{const K=m(T);return`${K?La(K):T} · Monitor ${U+1}`};return{resolveCurrentTarget(){if(dt&&xa){const ie=Ea;return{type:"control",deviceIds:[xa.deviceId],monitorIndex:ie,label:`${La(xa)} · Monitor ${ie+1}`,sourceCanvas:C(xa.deviceId,ie),signature:`control:${xa.deviceId}:${ie}:${_n.frameMode}`}}const T=In.map(ie=>ie.deviceId).filter(ie=>ws.includes(ie)),U=Wi&&ws.includes(Wi.deviceId)?Wi.deviceId:"",K=T.length>0?T:U?[U]:ws,ee=T.length===0&&!U;if(K.length===0)return null;if(K.length===1){const ie=K[0],se=x(ie);return{type:ee?"wall":T.length>1?"selection":"device",deviceIds:K,monitorIndex:se,label:ee?"Wall":E(ie,se),sourceCanvas:ee?null:C(ie,se),signature:`${ee?"wall":"device"}:${ie}:${se}:${Kt?"atlas":"direct"}`}}return{type:T.length>1?"selection":"wall",deviceIds:K,label:T.length>1?`${K.length} selected Clients`:"Wall",sourceCanvas:null,signature:`${T.length>1?"selection":"wall"}:${K.join(",")}:${Gt}`}},getDeviceCanvas:C,composeWall(T,U={}){return qD(T.map(K=>{const ee=x(K);return{deviceId:K,label:E(K,ee),canvas:C(K,ee)}}),U)}}},[pt,xa,de,Ee,_n.frameMode,ln,Kt,rn,Ea,In,dt,ws,Wi,Gt]),Sc=tI({hubUrl:X,sourceRegistry:xc,onToast:Be}),zs=d.useMemo(()=>FN({captureOwnershipActive:Eo,localFeatureAccess:Xt,controlSessionDeviceId:de,planAllowed:fr.has(de),sessionState:Ee,controlFocusVisible:dt,presentationCanvasMounted:Je===de,wallPresentationVisible:Ka,wallPresentationCanvasMounted:ln.current.has(de)||Aa.current.has(de),decoderOwnerExists:kn.current.has(de)})?[de]:[],[Eo,de,Ee,Xt,Je,fr,dt,Ka]),bl=d.useMemo(()=>zg([...Xa,...zs]),[zs,Xa]),Cc=d.useMemo(()=>Px(wt,Gt),[wt,Gt]),Yr=d.useMemo(()=>Px(wt,"large"),[wt]),kc=$N({mode4Enabled:Kt,directMode4WallEnabled:Ia,adaptiveFps:Bn,directDeviceCount:pr.length,adaptive:wt.adaptiveLoadShedding}),On=RN({fps:kc,maxWidth:Yr.maxWidth,maxHeight:Yr.maxHeight,quality:wt.quality},b),Mc=WN({deviceCount:Za.length,targetFps:Bn,adaptive:wt.adaptiveLoadShedding});Kt&&Za.length>0;const Ss=d.useCallback((m,x,C)=>{if(m.width<=0||m.height<=0)return!1;if(m===x)return!0;const E=C?Math.min(1,C.maxWidth/m.width,C.maxHeight/m.height):1,T=Math.max(1,Math.round(m.width*E)),U=Math.max(1,Math.round(m.height*E));(x.width!==T||x.height!==U)&&(x.width=T,x.height=U);const K=x.getContext("2d",{alpha:!1});return K?(K.imageSmoothingEnabled=!0,K.imageSmoothingQuality="low",K.drawImage(m,0,0,m.width,m.height,0,0,x.width,x.height),!0):!1},[]),Cs=d.useCallback((m,x)=>{const C=Math.max(0,Number(x.clientWidth||0)),E=Math.max(0,Number(x.clientHeight||0)),T=Math.max(1,Number(window.devicePixelRatio||1)),U=C>0&&E>0?{maxWidth:Math.ceil(C*T),maxHeight:Math.ceil(E*T)}:void 0;return Ss(m,x,U)},[Ss]),Lr=d.useCallback((m,x,C)=>{if(!uu.current)return;const E=`${m}:${x.deviceId}`,T=du.current.get(E)||{bindingKey:"",totalPaints:0,lastPaintAt:0,lastFrameSeq:0};T.bindingKey=uo(x),T.totalPaints+=1,T.lastPaintAt=performance.now(),T.lastFrameSeq=Number(x.frameSeq||0),du.current.set(E,T);const U=++mm.current,K={sequence:U,scope:m,deviceId:x.deviceId,bindingKey:T.bindingKey,frameSeq:T.lastFrameSeq,paintedAt:T.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)};Pd.current[(U-1)%NI]=K},[]),hr=d.useCallback(m=>{m&&za(x=>{if(x.has(m))return x;const C=new Set(x);return C.add(m),C})},[]),Xr=d.useCallback(m=>{m&&za(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,!Ss(x,C))return wa(C),!1;const E=$a.current.get(m);return $a.current.set(m,C),E&&E!==C&&Ra(E),hr(m),!0},[hr,Ss,Ra,wa]),Hn=d.useCallback(m=>{s1($a.current,m,vd)},[]),Vi=d.useCallback((m,x)=>{const C=$a.current.get(m),E=ln.current.get(m)===x||Aa.current.get(m)===x;return Ye.current[m]?(Hn(m),!1):!C||!E||C.width<=0||C.height<=0?!1:Ss(C,x)?!0:(Hn(m),!1)},[Ss,Hn]),$s=d.useCallback((m,x=!1,C)=>{if(Ye.current[m]||!lr.current.has(m))return!1;const E=Math.max(1,Math.min(Qt,Yn.controlWallReuseMaxFps,Gn)),T=performance.now(),U=ai.current.get(m)||0,K=kn.current.get(m)||Xn.current.get(m),ee=ln.current.get(m)||Aa.current.get(m);if(!K||!ee||!ee.isConnected)return!1;const ie=BN({cadenceCredit:qa.current.get(m)||0,targetFps:E,sourceFps:Gn,elapsedSincePaintMs:U>0?T-U:0,nowMs:T,scheduledPaintAtMs:Ma.current.get(m)||0,force:x});if(!ie.shouldPaint)return qa.current.set(m,ie.nextCadenceCredit),!1;const se=Math.max(0,Number(ee.clientWidth||0)),et=Math.max(0,Number(ee.clientHeight||0)),ze=Math.max(1,Number(window.devicePixelRatio||1)),_e=se>0&&et>0?{maxWidth:Math.min(Cc.maxWidth,Math.ceil(se*ze)),maxHeight:Math.min(Cc.maxHeight,Math.ceil(et*ze))}:Cc;return Ss(K,ee,_e)?(qa.current.set(m,ie.nextCadenceCredit),ie.nextScheduledPaintAtMs>0&&Ma.current.set(m,ie.nextScheduledPaintAtMs),ai.current.set(m,performance.now()),ie.sourceCadencePassthrough&&(qa.current.delete(m),Ma.current.delete(m)),C&&Lr("wall-reuse-visible",C),hr(m),Hn(m),!0):!1},[Gn,Cc,hr,Ss,Lr,Hn,Qt]);d.useEffect(()=>{Ri.current=ni},[ni]);const Ac=d.useCallback((m,x)=>{const C=ri.current;if(!C||C.deviceId!==m)return;const E=Date.now();pm.current.set(m,{...C,source:x,completedAtEpochMs:E,durationMs:Math.max(0,performance.now()-C.startedAt)}),ri.current=null},[]),Oo=d.useCallback((m,x)=>{const C=ln.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(ln.current.set(m,x),C&&C!==x&&wa(C),Ye.current[m]){Hn(m),Ra(x),Xr(m);return}$a.current.get(m)&&Vi(m,x)&&hr(m),$s(m,!0);return}if(C&&Qa.current&&pl.current.includes(m)){pi(m,C),ln.current.delete(m),wa(C);return}ln.current.delete(m),Hn(m),wa(C),Xr(m)},[Xr,hr,$s,Vi,pi,Ra,Hn,wa]),Eu=d.useCallback((m,x)=>{const C=Xn.current.get(m);if(x){Xn.current.set(m,x),Me(m),C&&C!==x&&wa(C);const E=de===m&&me?kn.current.get(m):null;E&&Cs(E,x)&&m===ye&&(Ac(m,"warm-reuse"),Wa(!0)),E&&E!==x&&ON({decodeWidth:E.width,decodeHeight:E.height,presentationCssWidth:x.getBoundingClientRect().width,presentationCssHeight:x.getBoundingClientRect().height,devicePixelRatio:window.devicePixelRatio,sourceWidth:gs.maxWidth,sourceHeight:gs.maxHeight})&&(kn.current.set(m,x),wa(E));return}Xn.current.delete(m),Me(E=>E===m?"":E),wa(C)},[Ac,ye,de,me,gs.maxHeight,gs.maxWidth,Cs,wa]),Nc=d.useCallback((m,x,C)=>{const E=performance.now(),T=la(m,C.deviceId);let U=C;if(m==="control"&&C.visualChanged){const ie=String(x.inputFeedbackEventId||""),se=Number(x.inputFeedbackInputSeq||0),et=Number(x.inputFeedbackIssuedAtEpochMs||0),ze=Number(x.browserReceivedEpochMs||0),_e=Bd.current.get(C.deviceId)||"",xt=et>0?Math.max(0,Date.now()-et):Number.POSITIVE_INFINITY;if(ie.length>0&&se>0&&ie!==_e&&xt<=Bg){const vt=bu.current.get(C.deviceId)||[];vt.push(xt),vt.length>vx&&vt.splice(0,vt.length-vx),bu.current.set(C.deviceId,vt),U={...C,inputFeedbackSeq:se,inputFeedbackMs:xt,inputFeedbackAt:E,inputFeedbackExact:!0,inputFeedbackEventId:ie,inputFeedbackInputType:x.inputFeedbackInputType,inputFeedbackInputToFrameMs:ze>0?Math.max(0,ze-et):void 0,inputFeedbackFrameToPaintMs:ze>0?Math.max(0,Date.now()-ze):void 0,inputFeedbackAgentApplyMs:x.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:x.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:vt.length,inputFeedbackP50Ms:zf(vt,.5),inputFeedbackP95Ms:zf(vt,.95)},Bd.current.set(C.deviceId,ie),yu.current.set(C.deviceId,se)}else if(!ie){const vt=nN(C.deviceId),bn=yu.current.get(C.deviceId)||0,Ln=vt?E-vt.sentAt:Number.POSITIVE_INFINITY;vt&&vt.inputSeq>bn&&Ln<=Bg&&(U={...C,inputFeedbackSeq:vt.inputSeq,inputFeedbackMs:Math.max(0,Ln),inputFeedbackAt:E,inputFeedbackExact:!1},yu.current.set(C.deviceId,vt.inputSeq))}}Di.current.set(T,E),oi.current.delete(T);const K=_s.current.get(T)||{totalFrames:0,totalChangedFrames:0,sampleFrames:0,sampleChangedFrames:0,sampleStartedAt:E,intervalCount:0,intervalSumMs:0,minIntervalMs:Number.POSITIVE_INFINITY,maxIntervalMs:0,intervalSamplesMs:[],seqGapCount:0,maxSeqGap:0,sampleDecoderInputBase:0,sampleDecoderOutputBase:0},ee=uo(x);K.bindingKey!==ee&&(K.bindingKey=ee,K.lastAt=void 0,K.lastFrameSeq=void 0,K.sampleChangedFrames=0,K.sampleDecoderInputBase=Number(C.decoderInputCount||0),K.sampleDecoderOutputBase=Number(C.decoderOutputCount||0),Np(K,E)),m==="control"&&U.inputFeedbackMs===void 0&&K.lastInfo?.inputFeedbackMs!==void 0&&K.lastInfo.inputFeedbackAt!==void 0&&E-K.lastInfo.inputFeedbackAt<=Bg&&(U={...U,inputFeedbackSeq:K.lastInfo.inputFeedbackSeq,inputFeedbackMs:K.lastInfo.inputFeedbackMs,inputFeedbackAt:K.lastInfo.inputFeedbackAt,inputFeedbackExact:K.lastInfo.inputFeedbackExact,inputFeedbackEventId:K.lastInfo.inputFeedbackEventId,inputFeedbackInputType:K.lastInfo.inputFeedbackInputType,inputFeedbackInputToFrameMs:K.lastInfo.inputFeedbackInputToFrameMs,inputFeedbackFrameToPaintMs:K.lastInfo.inputFeedbackFrameToPaintMs,inputFeedbackAgentApplyMs:K.lastInfo.inputFeedbackAgentApplyMs,inputFeedbackApplyToCaptureMs:K.lastInfo.inputFeedbackApplyToCaptureMs,inputFeedbackSampleCount:K.lastInfo.inputFeedbackSampleCount,inputFeedbackP50Ms:K.lastInfo.inputFeedbackP50Ms,inputFeedbackP95Ms:K.lastInfo.inputFeedbackP95Ms}),K.totalFrames+=1,K.sampleFrames+=1,Ax(K,E,U.frameSeq),U.visualChanged&&(K.totalChangedFrames+=1,K.sampleChangedFrames+=1),K.lastInfo=U,_s.current.set(T,K)},[]),wl=d.useCallback((m,x)=>{if(Ye.current[m.deviceId]||Ri.current===m.deviceId)return;Nc("wall",m,x);const C=me&&de===m.deviceId,E=ln.current.get(m.deviceId)||Aa.current.get(m.deviceId);uu.current&&!dt&&!C&&E?.isConnected&&Lr("wall-visible",m,x),m.kind==="live"&&(hr(m.deviceId),Hn(m.deviceId)),Ri.current!==m.deviceId&&!C&&(lr.current.delete(m.deviceId),qa.current.delete(m.deviceId),ai.current.delete(m.deviceId),Ma.current.delete(m.deviceId))},[de,me,hr,Nc,Lr,Hn,dt]),Du=d.useCallback((m,x)=>{if(Ye.current[m.deviceId]||Kn(Ga.current,Nt.current)||!kg(m,Nt.current))return;Nc("control",m,x),jt(K=>K&&"");const C=kn.current.get(m.deviceId),E=Xn.current.get(m.deviceId);let T=!1;C&&C.width>0&&C.height>0&&(E&&dt&&m.deviceId===ye&&(T=Cs(C,E),T&&Lr("control-visible",m,x)),Ua.current.set(m.deviceId,tu(m)),lr.current.add(m.deviceId),m.deviceId===de&&(ke(!0),Ge(K=>K==="connecting"?"active":K)),$s(m.deviceId,!1,m));const U=pu.current;!U||!MI(U,m)||!T||(Ac(m.deviceId,"fresh-frame"),Wa(!0))},[Ac,ye,de,$s,Cs,Nc,Lr,dt]),sa=d.useCallback((m,x)=>{const C=performance.now(),E=la(m,x.deviceId);ii.current.set(E,C),Os.current.delete(E),li.current.delete(E),m==="control"?Bs.current.delete(E):Ao.current.delete(E);const T=Ei.current.get(E)||{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:[]},U=uo(x);if(T.bindingKey!==U&&(T.bindingKey=U,T.lastAt=void 0,T.lastFrameSeq=void 0,T.lastContentHash=void 0,T.sampleBytes=0,T.sampleH264Frames=0,T.sampleTinyFrames=0,T.sampleRepeatedFrames=0,T.sourceSendIntervalsMs.length=0,Np(T,C)),T.totalFrames+=1,T.sampleFrames+=1,T.sampleBytes+=Math.max(0,Number(x.byteLength||0)),String(x.frameMode||x.mode||x.codec||x.mimeType||"").toLowerCase().includes("h264")){T.sampleH264Frames+=1,Number(x.byteLength||0)<=wI&&(T.sampleTinyFrames+=1);const se=String(x.contentHash||"");se&&T.lastContentHash===se&&(T.sampleRepeatedFrames+=1),T.lastContentHash=se}const ie=Number(x.agentSendGapMs||0);ie>0&&ie<1e3&&eC(T.sourceSendIntervalsMs,ie),T.lastFrame=tu(x),Ax(T,C,x.frameSeq),Ei.current.set(E,T)},[]);d.useEffect(()=>{const m=new Set(Fo);for(const E of _s.current.keys())m.has(E)||_s.current.delete(E);for(const E of Ei.current.keys())m.has(E)||Ei.current.delete(E);const x=E=>{const T=Object.entries(E).filter(([U])=>m.has(U));return T.length===Object.keys(E).length?E:Object.fromEntries(T)};if(_d(x),dc(x),m.size===0)return;const C=window.setInterval(()=>{const E=performance.now(),T={},U={};for(const K of m){const ee=_s.current.get(K);if(ee){const ze=Math.max(1,E-ee.sampleStartedAt);T[K]={bindingKey:ee.bindingKey||"",totalFrames:ee.totalFrames,totalChangedFrames:ee.totalChangedFrames,framesPerSecond:ee.sampleFrames*1e3/ze,changedFramesPerSecond:ee.sampleChangedFrames*1e3/ze,averageIntervalMs:ee.intervalCount>0?ee.intervalSumMs/ee.intervalCount:0,minIntervalMs:Number.isFinite(ee.minIntervalMs)?ee.minIntervalMs:0,maxIntervalMs:ee.maxIntervalMs,p95IntervalMs:zf(ee.intervalSamplesMs,.95),intervalCount:ee.intervalCount,seqGapCount:ee.seqGapCount,maxSeqGap:ee.maxSeqGap,decoderInputFps:Math.max(0,(Number(ee.lastInfo?.decoderInputCount||0)-ee.sampleDecoderInputBase)*1e3/ze),decoderOutputFps:Math.max(0,(Number(ee.lastInfo?.decoderOutputCount||0)-ee.sampleDecoderOutputBase)*1e3/ze),sampleMs:ze,lastInfo:ee.lastInfo},ee.sampleDecoderInputBase=Number(ee.lastInfo?.decoderInputCount||0),ee.sampleDecoderOutputBase=Number(ee.lastInfo?.decoderOutputCount||0),ee.sampleChangedFrames=0,Np(ee,E)}const ie=Ei.current.get(K);if(!ie)continue;const se=Math.max(1,E-ie.sampleStartedAt),et=ie.lastFrame?tu(ie.lastFrame):void 0;ie.lastFrame=et,U[K]={totalFrames:ie.totalFrames,framesPerSecond:ie.sampleFrames*1e3/se,averageIntervalMs:ie.intervalCount>0?ie.intervalSumMs/ie.intervalCount:0,minIntervalMs:Number.isFinite(ie.minIntervalMs)?ie.minIntervalMs:0,maxIntervalMs:ie.maxIntervalMs,p95IntervalMs:zf(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((ze,_e)=>ze+_e,0)/ie.sourceSendIntervalsMs.length:0,sourceSendP95Ms:zf(ie.sourceSendIntervalsMs,.95),sourceSendSampleCount:ie.sourceSendIntervalsMs.length,sampleMs:se,lastFrame:et},ie.sampleBytes=0,ie.sampleH264Frames=0,ie.sampleTinyFrames=0,ie.sampleRepeatedFrames=0,ie.sourceSendIntervalsMs.length=0,Np(ie,E)}_d(T),dc(U)},1e3);return mu.current=C,()=>{window.clearInterval(C),mu.current===C&&(mu.current=null)}},[Fo]);const Pr=d.useCallback(m=>{const x=m.deviceId,C=uo(m);if(Ye.current[x]||Ri.current===x||m.currentGenerationVerified!==!0||Wr.current.get(x)!==C)return;sa("wall",m);const E=ln.current.get(x);if(!E)return;const T=_i(E),U=Hs(E),K=()=>ln.current.get(x)!==E||!Vr(E,T)||!!Ye.current[x]||Ri.current===x||Wr.current.get(x)!==C,ee=()=>K()||!ui(E,U),ie=GN(Kt,wt.h264DecodeAcceleration);wg(E,m,ee,wl,ie.acceleration,ie.latencyMode,K).catch(()=>{})},[_i,ui,Vr,Hs,wl,Kt,sa,wt.h264DecodeAcceleration]),hi=d.useCallback(m=>{const x=m.deviceId;if(Ye.current[x]||Kn(Ga.current,Nt.current)||!kg(m,Nt.current))return;let C=kn.current.get(x);if(!C){const _e=Xn.current.get(x),xt=Fn.current;C=_e||xt||document.createElement("canvas"),_e&&xt&&xt!==_e&&Ra(xt),Fn.current=null,C!==_e&&C.setAttribute("aria-hidden","true"),kn.current.set(x,C)}const E=C,T=m,U=_i(E),K=Hs(E),ee=()=>kn.current.get(x)!==E||!Vr(E,U)||!!Ye.current[x]||!kg(T,Nt.current),ie=()=>ee()||!ui(E,K),se=O.current,et=String(m.frameMode||m.mode||m.codec||m.mimeType||"").toLowerCase().includes("h264");et||sa("control",m);const ze=wg(E,m,ie,Du,_n.h264DecodeAcceleration,"interactive",ee);et&&sa("control",m),ze.catch(_e=>{O.current!==se||kn.current.get(x)!==E||!ui(E,K)||ee()||de!==x||jt(_e instanceof Error?_e.message:String(_e||"Control H.264 decode failed"))})},[_i,ui,Vr,Hs,de,_n.h264DecodeAcceleration,Du,sa,Ra]),Wd=d.useCallback(m=>{const x=Rr.current;Rr.current=m,x&&x!==m&&wa(x),mc.current=0,gu.current=0,Ta.current=0,Pi.current=0,vu.current=0,uc.current=0},[wa]),Bo=d.useCallback(()=>{const m=new Set,x=Rr.current,C=ul.current;if(!x||!C||x.width<=0||x.height<=0||uc.current!==C.layoutVersion)return m;for(const E of C.tiles){if(Ye.current[E.deviceId])continue;const T=Aa.current.get(E.deviceId);if(!T||E.width<=0||E.height<=0)continue;const U=Math.max(1,Math.round(E.width)),K=Math.max(1,Math.round(E.height)),ee=xI,ie=SI;(T.width!==ee||T.height!==ie)&&(T.width=ee,T.height=ie);const se=T.getContext("2d",{alpha:!1});if(se){se.imageSmoothingEnabled=!0,se.imageSmoothingQuality="high";try{se.drawImage(x,Math.round(E.x),Math.round(E.y),U,K,0,0,ee,ie),m.add(E.deviceId)}catch{}}}return m},[]),Ki=d.useCallback((m,x)=>{const C=Aa.current.get(m);if(x&&C&&C!==x&&pi(m,C),x){if(Aa.current.set(m,x),C&&C!==x&&wa(C),Ye.current[m]){Hn(m),Ra(x),Xr(m);return}$a.current.get(m)&&Vi(m,x)&&hr(m),window.requestAnimationFrame(()=>{Bo().has(m)&&Hn(m)}),window.requestAnimationFrame(()=>$s(m,!0));return}Aa.current.delete(m),Hn(m),wa(C),Xr(m)},[Xr,hr,Bo,$s,Vi,pi,Ra,Hn,wa]),gr=d.useCallback((m,x)=>{Ta.current=performance.now(),uc.current=Number(m.layoutVersion||0),Bo();const C=ul.current?.tiles||[],E=C.length>0?Math.round(m.byteLength/C.length):m.byteLength;for(const T of C){if(Ye.current[T.deviceId])continue;const U={...m,deviceId:T.deviceId,width:T.width,height:T.height,sourceWidth:T.width,sourceHeight:T.height,byteLength:E};wl(U,{...x,deviceId:T.deviceId,width:T.width,height:T.height,byteLength:E}),Ri.current===T.deviceId&&$s(T.deviceId,!0)}},[wl,Bo,$s]),Vn=d.useCallback(m=>{const x=performance.now();mc.current<=0&&(mc.current=x),gu.current=x;const C=Rr.current;if(!C)return;const E=uo(m);cc.current!==E&&(cc.current=E,Zn(C));const T=_i(C),U=Hs(C),K=()=>Rr.current!==C||cc.current!==E||!Vr(C,T),ee=()=>K()||!ui(C,U),ie=ul.current?.tiles||[],se=ie.length>0?Math.round(m.byteLength/ie.length):m.byteLength;for(const et of ie)Ye.current[et.deviceId]||sa("wall",{...m,deviceId:et.deviceId,width:et.width,height:et.height,sourceWidth:et.width,sourceHeight:et.height,byteLength:se});wg(C,m,ee,gr,void 0,"smooth",K).catch(()=>{})},[_i,ui,Vr,Hs,gr,sa,Zn]),Tc=d.useCallback(m=>{if(m.streamPurpose!=="wall"||Ye.current[m.deviceId])return;const x=uo(m);Wr.current.get(m.deviceId)!==x&&(Wr.current.set(m.deviceId,x),Zn(ln.current.get(m.deviceId)))},[Zn]),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:uI,forceRestart:ml>0,forceRestartToken:ml>0?`document-presentation-resume-${ml}`:"",restartReason:ml>0?"document-presentation-resume":"",connectionSessionIds:xs,monitorSelections:rn,onFrame:Pr,onStreamReady:Tc}),[xs,ml,Pr,Tc,Kt,rn,wt.frameMode,On.fps,On.maxHeight,On.maxWidth,On.quality]),Ft=d.useCallback(m=>{const x=Nt.current;if(Ye.current[m.deviceId]||!x||Kn(Ga.current,x)||x.deviceId!==m.deviceId||m.deviceId!==de||m.streamPurpose!=="control"||m.monitorIndex!==Ea)return;const C=pt.find(T=>T.deviceId===m.deviceId);if(!C?.sessionId||C.sessionId!==m.sessionId)return;const E=Re.current;(!E||uo(E)!==uo(m))&&Zn(kn.current.get(m.deviceId)),Nt.current=Cg(x.deviceId,x.transitionGeneration,m),Re.current=m,qe(m),Ge(T=>T==="connecting"?"active":T)},[pt,de,Zn,Ea]);d.useEffect(()=>{Zn(kn.current.get(de)),Re.current=null,qe(null)},[de,ue,Ir,Zn,Ea]);const sn=ue?`${ue}-monitor-${Ea}`:"",Jn=d.useMemo(()=>({fps:Gn,maxWidth:gs.maxWidth,maxHeight:gs.maxHeight,quality:_n.quality,mode:Ir,frameMode:Ir,streamPurpose:"control",forceRestart:sn!=="",forceRestartToken:sn,restartReason:sn?"control-session-or-monitor-change":"",connectionSessionIds:xs,monitorSelections:rn,onFrame:hi,onStreamReady:Ft}),[xs,sn,_n.quality,hi,Gn,Ir,gs.maxHeight,gs.maxWidth,Ft,rn]),{frames:Rc,state:Us,error:Qi,stats:qs,restartLive:Yi,reconnectLive:Ho}=iw(pr,wt.autoStartLive&&pr.length>0,X,gi);d.useEffect(()=>{const m=new Set(pr);for(const x of Wr.current.keys())m.has(x)||(Wr.current.delete(x),Zn(ln.current.get(x)))},[pr,Zn]);const{frame:xl,layout:vn,state:jc,stats:Gd,refreshInputs:Vd}=oN(Za,Kt&&wt.autoStartLive&&Za.length>0,X,{fps:Yn.atlasOutputFps,inputFps:Mc,width:1920,height:1080,tileWidth:Yr.maxWidth,tileHeight:Yr.maxHeight,captureDeviceIds:Za,connectionSessionIds:xs,monitorSelections:rn,onFrame:Vn});d.useEffect(()=>{ul.current=vn,vn&&window.requestAnimationFrame(Bo)},[vn,Bo]),d.useEffect(()=>{if(!Kt||jc!=="open"){mc.current=0,gu.current=0,Ta.current=0;return}const m=window.setInterval(()=>{const x=Rr.current,C=performance.now();if(!x||document.visibilityState!=="visible"||C-Ii.current<Og)return;const E=gu.current,T=mc.current;if(E<=0||T<=0||C-E>500)return;const U=Ta.current||T,K=C-U;if(K>=hI&&C-vu.current>=vI){yd(x)&&(vu.current=C,Pi.current=C);return}K>=pI&&C-Pi.current>=gI&&ZA(x)&&(Pi.current=C)},250);return()=>window.clearInterval(m)},[jc,Kt]);const{frames:Sl,state:Kd,error:zo,stats:Qd,restartLive:Cl,reconnectLive:ia}=iw(zs,zs.length>0,X,Jn);d.useEffect(()=>{const m=ll.current,x=new Set([...Object.keys(m),...Object.keys(rn)]);for(const C of x){const E=Math.max(0,Math.floor(Number(m[C])||0)),T=Math.max(0,Math.floor(Number(rn[C])||0));E!==T&&(Wr.current.delete(C),Zn(ln.current.get(C)),Zn(kn.current.get(C)),Zn(Aa.current.get(C)),ua("wall",C),ua("control",C),yd(ln.current.get(C)||null),yd(kn.current.get(C)||null))}x.size>0&&(Zn(Rr.current),yd(Rr.current)),ll.current={...rn}},[rn,ua,Zn]);const Mn=d.useMemo(()=>{const m=(C,E)=>{const T=pt.find(K=>K.deviceId===C),U=T?Es(T,rn[C]):0;return!Number.isFinite(Number(E.monitorIndex))||Number(E.monitorIndex)===U},x=new Map;for(const[C,E]of Rc.entries())m(C,E)&&x.set(C,E);if(Kt&&xl&&Za.length>0){const C=new Map((vn?.tiles||[]).map(T=>[T.deviceId,T])),E=Math.max(1,C.size);for(const T of Za){const U=C.get(T);U&&x.set(T,{...xl,deviceId:T,width:U.width,height:U.height,sourceWidth:U.width,sourceHeight:U.height,byteLength:Math.round(xl.byteLength/E)})}}for(const[C,E]of Sl.entries())m(C,E)&&x.set(C,E);for(const C of _o){if(!lr.current.has(C)||x.has(C))continue;const E=Ua.current.get(C);E&&m(C,E)&&x.set(C,E)}return x},[xl,vn,pt,Sl,Za,Kt,rn,Rc,_o,xo]),kl=dt&&zs.length>0?Kd:Za.length>0?jc:Us,Xi=dt&&zs.length>0?Qd:Za.length>0?Gd:qs;d.useCallback((m,x="browser-stale")=>{const C=Yi(m,x),E=Cl(m,x);return C||E},[Cl,Yi]),d.useEffect(()=>{Kt&&Za.length>0&&!dt&&Vd()},[Za.length,Kt,Vd,dt]);const vi=d.useCallback((m,x,C)=>{const E=x==="control"?kn.current.get(m)||null:ln.current.get(m)||null;if(!E)return!1;yd(E);const T=performance.now();return oi.current.set(la(x,m),T),!0},[]),Ml=d.useCallback(m=>{if(Ir!=="mode3-h264-hw"||!de||Xe)return!1;const x=pt.find(ee=>ee.deviceId===de)||xa,C=String(x?.platform||"").toLowerCase();if(!["win32","windows","win32nt"].includes(C))return!1;const E="mode5-lzo-delta",T=la("control",de),U=performance.now();Li.current.set(T,U),ii.current.delete(T),Di.current.delete(T),Fs.current.delete(T),Bs.current.delete(T),li.current.delete(T),yd(kn.current.get(de)||null),ia([de],"control-decode-fallback"),at(E),Fe(`control-${E}-fallback-${de}-${Date.now()}`),ke(!1),Wa(!1);const K=m==="no first frame"||m==="control-first-frame-timeout";return jt(ee=>ee||(K?`Control frame transport timeout; retrying Control with Mode 5 (${m})`:`H.264 decode failed; retrying Control with Mode 5 (${m})`)),Ge("connecting"),!0},[pt,xa,de,Xe,Ir,ia]);d.useEffect(()=>{const m=dt?xa:null;if(m){pu.current={deviceId:m.deviceId,monitorIndex:Ea,frameMode:Ir,startedAtEpochMs:Date.now()},Wa(de===m.deviceId&&me);return}pu.current=null,Wa(!1)},[xa?.sessionId,ye,de,me,Ir,Ea,dt]);const Ws=d.useCallback(async(m,x)=>{const C=String(x.streamId||"").trim(),E=String(x.streamPurpose||"").trim(),T=String(x.sessionId||"").trim(),U=String(x.commandId||"").trim(),K=Number(x.captureGeneration||0),ee=Number(x.monitorIndex??-1);if(!C||!["wall","atlas"].includes(E)||!T||!U||!Number.isSafeInteger(K)||K<=0||!Number.isSafeInteger(ee)||ee<0)throw new Error("wall-start-owner-incomplete");const ie=performance.now()+3e3;for(;;){const se=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/stop`,{method:"POST",body:JSON.stringify({streamId:C,streamPurpose:E,expectedSessionId:T,expectedCommandId:U,expectedCaptureGeneration:K,expectedMonitorIndex:ee,requireNoPresentationOwner:!0,reason:"wall-start-presentation-revoked"})},X);if(se?.ok===!1)throw new Error(se.error||"revoked-wall-start-stop-failed");if(se?.captureStopConfirmed===!0||se?.alreadyStopped===!0||se?.staleOwner===!0)return se;if(se?.presentationOwnerActive===!0||se?.retainedForPresentation===!0){if(jr.current&&Qa.current)return se;if(performance.now()<ie){await new Promise(et=>window.setTimeout(et,50));continue}throw new Error("revoked-wall-start-presentation-owner-did-not-release")}throw new Error("revoked-wall-start-stop-unconfirmed")}},[X]),Gs=d.useCallback(async m=>{if(Ye.current[m])throw new Error("LIVE_CAPTURE_PAUSED");if(!jr.current||!Qa.current)return{ok:!0,skipped:!0,reason:"wall-capture-owner-hidden"};const x=ds.current,C=G.find(K=>K.deviceId===m);_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(C?.platform)});const E=C?Es(C,rn[m]):0,T={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:E},U=await rt(`/api/remote/devices/${encodeURIComponent(m)}/live/start`,{method:"POST",body:JSON.stringify(T)},X);if(U?.ok===!1)throw new Error(U.error||"wall-stream-start-failed");return x!==ds.current||!jr.current||!Qa.current?(await Ws(m,U),{...U,skipped:!0,reason:"wall-presentation-owner-revoked",compensated:!0}):U},[Mc,G,Ia,X,Kt,rn,Ws,wt.frameMode,Yr.maxHeight,Yr.maxWidth,On.fps,On.maxHeight,On.maxWidth,On.quality]),Iu=d.useCallback(async m=>{const x=G.find(E=>E.deviceId===m);_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,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},[G,Ia,X,Kt]),Lu=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]),Ja=d.useCallback((m,x={})=>{Ga.current?.deviceId===m&&(Ga.current=null);const C=kn.current.get(m);if(C){const T=$a.current.has(m)||ln.current.has(m)||Aa.current.has(m);x.preservePresentation!==!1&&!T&&pi(m,C),kn.current.delete(m),Ra(C),!(Xn.current.get(m)||ln.current.get(m)||Aa.current.get(m))&&!Fn.current&&(Fn.current=C)}const E=Xn.current.get(m);E&&vd(E),Ua.current.delete(m),lr.current.delete(m),qa.current.delete(m),ai.current.delete(m),Ma.current.delete(m)},[pi,Ra]),Ec=d.useCallback(m=>{const x=[la("wall",m),la("control",m)];for(const C of x){const E=Ei.current.get(C);E?.lastFrame&&(E.lastFrame=tu(E.lastFrame))}dc(C=>{let E=!1;const T={...C};for(const U of x){const K=C[U];!K?.lastFrame||K.lastFrame.payload.byteLength===0||(T[U]={...K,lastFrame:tu(K.lastFrame)},E=!0)}return E?T:C})},[]),Pu=d.useCallback(m=>{Wr.current.delete(m),Hn(m),Ja(m,{preservePresentation:!1});const x=new Set;for(const C of[Xn.current.get(m),ln.current.get(m),Aa.current.get(m)])C&&x.add(C);for(const C of x)Ra(C);Xr(m),de===m&&(pu.current=null,Wa(!1),ke(!1)),ut.current.add(m),Ec(m)},[Xr,de,Ra,Ja,Ec,Hn]);d.useEffect(()=>{const m=new Set(Object.keys(Ie));for(const x of m)ut.current.has(x)||Pu(x);for(const x of ut.current)m.has(x)||ut.current.delete(x)},[Pu,Ie]);const $o=d.useCallback(m=>{const x=hw(fm.current,m);return fm.current=x.tail,x.result},[]),_r=d.useCallback(m=>{const x=hw(Od.current,m);return Od.current=x.tail,x.result},[]),Fr=d.useCallback(m=>{cr.current=m,cu.current=0;const x=m?.deviceId||"";Ri.current=x,cl(x),x&&lr.current.add(x)},[]),Zi=d.useCallback(m=>$o(async()=>{if(Ye.current[m.deviceId])return!1;const x=cr.current;return!Kn(x,m)||!mp(m.deviceId,m,Nt.current)?!1:(await Gs(m.deviceId),Kn(cr.current,m)&&Fr(null),!0)}),[Fr,$o,Gs]),Yd=d.useCallback((m,x,C)=>$o(async()=>{const E=cr.current;if(Kn(E,m))return C.stoppedWallDeviceId=m.deviceId,!0;if(E)if(Ye.current[E.deviceId])Kn(cr.current,E)&&Fr(null);else{if(!mp(E.deviceId,E,Nt.current))return!1;await Gs(E.deviceId),Kn(cr.current,E)&&Fr(null)}if(!x())return!1;if(await Iu(m.deviceId),C.stoppedWallDeviceId=m.deviceId,!x()){if(mp(C.stoppedWallDeviceId,m,Nt.current))try{await Gs(C.stoppedWallDeviceId)}catch(T){throw Fr(m),T}finally{C.stoppedWallDeviceId=""}return!1}return vd(ln.current.get(m.deviceId)||null),Fr(m),!0}),[Fr,$o,Gs,Iu]),_u=d.useCallback(async(m,x)=>{if(x.stoppedWallDeviceId){if(Kn(cr.current,m)){try{await Zi(m)}catch(C){Be(C instanceof Error?C.message:String(C))}finally{x.stoppedWallDeviceId=""}return}await $o(async()=>{if(!x.stoppedWallDeviceId||!mp(x.stoppedWallDeviceId,m,Nt.current))return;const C=x.stoppedWallDeviceId;try{await Gs(C)}catch(E){Fr(m),Be(E instanceof Error?E.message:String(E))}finally{x.stoppedWallDeviceId=""}})}},[Fr,$o,Zi,Be,Gs]),Or=d.useCallback(async(m,x,C={})=>{const E=C.allowStopFailure===!0,T=C.resumeWall!==!1;try{await Lu(m.deviceId,x)}catch(U){if(!E)throw U}if(!Kn(Nt.current,m))return!1;if(Nt.current=null,Re.current=null,qe(null),Ja(m.deviceId),ke(!1),Fe(""),at(""),jt(""),Ke(U=>U===m.deviceId?"":U),!T)return Kn(cr.current,m)&&Fr(null),!0;try{await Zi(m)}catch(U){Be(U instanceof Error?U.message:String(U))}return!0},[Fr,Ja,Zi,Be,Lu]),Xd=(Na&&dt&&Xt&&ye&&!Ct.has(ye)&&pt.find(m=>m.deviceId===ye)||null)?.deviceId||"";d.useEffect(()=>{ko.current=Xd},[Xd]),d.useEffect(()=>{const m=ye&&pt.find(U=>U.deviceId===ye)||null;if(!Na||!dt||!Xt||!m){ya.current&&(++qn.current,ya.current="");return}if(Ye.current[m.deviceId]){ya.current&&(++qn.current,ya.current=""),de===m.deviceId&&Ge("paused");return}if(ba.current){if(ba.current===m.deviceId)return;ba.current=""}if(de===m.deviceId&&(Ee==="active"||Ee==="warm"||Ee==="connecting")){Ge(U=>U==="warm"?"active":U);return}if(ya.current===m.deviceId)return;const x=++qn.current,C=Cg(m.deviceId,x,{sessionId:m.sessionId,monitorIndex:Ea});ya.current=m.deviceId;const E={stoppedWallDeviceId:""},T=()=>x===qn.current&&ko.current===C.deviceId;_r(async()=>{if(!T())return;const U=Nt.current;if(U){Ge("stopping");try{await Or(U,"control-session-switch")}catch(ie){T()&&(Ge("error"),Be(ie instanceof Error?ie.message:String(ie)));return}if(!T()){Nt.current||Ge("idle");return}}try{if(!await Yd(C,T,E)||!T()){await _u(C,E),Nt.current||Ge("idle");return}}catch(ie){await _u(C,E),T()&&(Ge("error"),Be(ie instanceof Error?ie.message:String(ie)));return}if(!T()){await _u(C,E);return}Nt.current=C,Ga.current=null,ba.current="",Mo.current=null,fl.current=0,fc.current="",E.stoppedWallDeviceId="";const K=la("control",C.deviceId),ee=`control-session-${x}-${C.deviceId}`;Li.current.set(K,performance.now()),ii.current.delete(K),Di.current.delete(K),li.current.delete(K),Bs.current.delete(K),at(""),jt(""),Fe(ee),Ke(C.deviceId),ke(!1),Ge("connecting")}).catch(U=>{T()&&(Ge("error"),Be(U instanceof Error?U.message:String(U)))}).finally(()=>{qn.current===x&&ya.current===C.deviceId&&(ya.current="")})},[pt,ye,de,Ee,Na,_r,Xt,Yd,_u,Ea,Be,dt,Or,Ie]),d.useEffect(()=>{if(!de||pt.some(C=>C.deviceId===de))return;const m=de;++qn.current,ya.current="";const x=Nt.current;Ge("stopping"),_r(async()=>{x&&x.deviceId===m?await Or(x,"control-device-disconnected",{allowStopFailure:!0}):(Ja(m),Ke(C=>C===m?"":C)),Nt.current||Ge("idle")})},[pt,de,_r,Ja,Or]),d.useEffect(()=>{if(Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),!Ka||dt||!de||Ye.current[de]||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm")return;const m=de,x=Nt.current;if(!x||x.deviceId!==m)return;const C=window.setTimeout(()=>{Gr.current===C&&(Gr.current=null);const E=Nt.current;if(ko.current||Ye.current[m]||!Kn(E,x))return;Ga.current=x;const T=++qn.current;ya.current="",Ge("stopping"),_r(async()=>{if(T!==qn.current||ko.current||!Kn(Nt.current,x)){Kn(Ga.current,x)&&(Ga.current=null),Kn(Nt.current,x)&&ko.current===m&&Ge("active");return}try{await Or(x,"control-session-wall-downshift")}catch(U){Kn(Ga.current,x)&&(Ga.current=null),T===qn.current&&!ko.current&&Kn(Nt.current,x)&&(Ge("active"),Be(U instanceof Error?U.message:String(U)));return}Ga.current=null,T===qn.current&&!Nt.current&&Ge("idle")})},bI);return Gr.current=C,()=>{Gr.current===C&&(window.clearTimeout(C),Gr.current=null)}},[de,Ee,_r,Be,dt,Or,Ie,Ka]);const Al=d.useCallback(m=>{if(hm.current===m)return;hm.current=m;const x=Nt.current,C=x?.deviceId||de,E=++qn.current;ya.current="",Re.current=null,si.current=!0,qe(null),ke(!1),Wa(!1),C&&(ua("control",C),Ja(C,{preservePresentation:!1}),Ge("stopping"),_r(async()=>{if(x&&x.deviceId===C)try{await Or(x,"control-session-document-hidden",{resumeWall:!1})}catch(T){!jr.current&&ds.current===m&&(Ge("error"),Be(T instanceof Error?T.message:String(T)));return}else Ja(C,{preservePresentation:!1}),Ke(T=>T===C?"":T);!Nt.current&&qn.current===E&&Ge("idle")}))},[de,_r,Ja,ua,Be,Or]);d.useEffect(()=>{if(us.current!==null&&(window.clearTimeout(us.current),us.current=null),!de||Ee==="idle"||Ee==="paused"||Ee==="error")return;if(!Na){Al(ds.current);return}if(Ee==="stopping"||Eo){de&&Dr&&Ee==="connecting"&&(si.current=!1),de&&Dr&&si.current&&(Ee==="warm"||Ee==="active")&&(si.current=!1,Re.current=null,qe(null),ke(!1),Wa(!1),ua("control",de),Fe(`control-presentation-resume-${Date.now()}-${de}`),Ge("connecting"));return}Re.current=null,si.current=!0,qe(null),ke(!1),Wa(!1),Ge(x=>x==="idle"||x==="stopping"?x:"warm");const m=de;return Ja(m,{preservePresentation:!1}),us.current=window.setTimeout(()=>{us.current=null,++qn.current,ya.current="";const x=Nt.current;Ge("stopping"),_r(async()=>{if(x&&x.deviceId===m)try{await Or(x,"control-session-warm-timeout")}catch(C){Ge("error"),Be(C instanceof Error?C.message:String(C));return}else Ja(m),Ke(C=>C===m?"":C);Nt.current||Ge("idle")})},yI),()=>{us.current!==null&&(window.clearTimeout(us.current),us.current=null)}},[Eo,Dr,de,Ee,Na,_r,Ja,Al,ua,Be,Or]),d.useEffect(()=>()=>{us.current!==null&&window.clearTimeout(us.current),Gr.current!==null&&(window.clearTimeout(Gr.current),Gr.current=null),Ga.current=null},[]);const Dc=d.useCallback(()=>{const m=new Set(hu.current),x=Nt.current?.deviceId||"";de&&m.add(de),x&&m.add(x),hu.current=[];for(const E of m){Wr.current.delete(E),Hn(E),Ja(E,{preservePresentation:!1});for(const T of[ln.current.get(E),Xn.current.get(E),Aa.current.get(E)])T&&Ra(T);Xr(E),ua("wall",E),ua("control",E),Ec(E)}const C=Rr.current;C&&Ra(C),cc.current="",ul.current=null,uc.current=0},[Xr,de,Ra,Ja,Ec,Hn,ua]);d.useEffect(()=>{if(Na){hu.current=[...bl];return}Dc()},[Na,bl,Dc]),d.useEffect(()=>{const m=cr.current,x=Nt.current;if(!Ka||!m||Ye.current[m.deviceId]||x&&x.deviceId===m.deviceId){cu.current=0;return}const C=cu.current,E=Math.min(5e3,500*2**Math.min(C,4)),T=window.setTimeout(()=>{ji.current===T&&(ji.current=null);const U=cr.current;!Er.current||!U||Ye.current[U.deviceId]||!Kn(U,m)||(cu.current=C+1,Zi(U).catch(K=>{Be(K instanceof Error?K.message:String(K)),Kn(cr.current,U)&&!Nt.current&&wo(ee=>ee+1)}))},E);return ji.current=T,()=>{window.clearTimeout(T),ji.current===T&&(ji.current=null)}},[Ee,Zi,Be,Ka,lc,ni]);const Nl=de&&pt.find(m=>m.deviceId===de)||null,Ic=!!(dt&&$e&&Ee==="active"&&me&&Nl?.sessionId&&pe?.deviceId===Nl.deviceId&&pe.sessionId===Nl.sessionId&&pe.streamPurpose==="control"&&pe.commandId&&pe.captureGeneration>0&&pe.monitorIndex===Ea),{state:Fu,sendInput:Zd,stats:Vs,error:Jd}=lN(Na&&ys&&Ic,X),Ji=Nl?.deviceId||"",Ou=Nl?.sessionId||"",Tl=pe?.commandId||"",Rl=Number(pe?.captureGeneration||0),ef=Number(pe?.monitorIndex||0),Uo=d.useCallback((m,x)=>!jr.current||!Ic||!Ji||!Ou||!Tl||Rl<=0||m!==Ji?!1:Zd(m,{...x,monitorIndex:ef,controlSessionId:Ou,controlCommandId:Tl,captureGeneration:Rl}),[Ic,Rl,Tl,Ji,ef,Ou,Zd]),Ks=Na&&jr.current&&Ic&&Fu==="open",Bu={shiftKey:Et.includes("ShiftLeft"),ctrlKey:Et.includes("ControlLeft"),altKey:Et.includes("AltLeft"),metaKey:Et.includes("MetaLeft")},Zr=d.useCallback(m=>Ne.current.enqueueStop(m),[]),eo=d.useCallback(m=>Ne.current.enqueueStart(m),[]),Ca=d.useCallback((m,x=ce.current)=>(te.current=m,ce.current=m?String(x||""):"",fe.current+=1,fe.current),[]),Jr=d.useCallback((m,x,C)=>LN({generation:m,currentGeneration:fe.current,enabled:te.current,deviceId:x,currentDeviceId:ce.current,documentVisible:jr.current,presentationVisible:He.current,streamId:C,currentStreamId:Ae.current.get(x)||""}),[]),vr=d.useCallback(async(m,x,C)=>{if(!x)return{ok:!0,alreadyStopped:!0,captureStopConfirmed:!0,noExactOwner:!0};const T=await(K=>rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/stop`,{method:"POST",body:JSON.stringify({...K?{streamId:K}:{},reason:C})},X))(x),U=PN(T);if(U.staleOwner)return T;if(!U.confirmed)throw new Error(T?.error||"Remote audio capture stop was not confirmed.");return T},[X]),Hu=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]),wm=d.useCallback(m=>{const x=fe.current,C=Ae.current.get(m)||"";return Zr(()=>vr(m,C,"remote-audio-automatic-restart")).then(()=>eo(async()=>{if(x!==fe.current||!te.current||ce.current!==m||!jr.current||!He.current||!Xt||!vs||(je.current||De?.deviceId||"")!==m)return"";const E=`audio-restart-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;if(Ae.current.set(m,E),!Jr(x,m,E))return Ae.current.delete(m),"";const T=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(T?.ok===!1)throw Ae.current.get(m)===E&&Ae.current.delete(m),new Error(T.error||"Remote audio restart failed.");return Jr(x,m,E)?E:(await vr(m,E,"remote-audio-stale-restart-compensation"),Ae.current.get(m)===E&&Ae.current.delete(m),"")}))},[eo,Zr,Xt,X,Jr,vs,De?.deviceId,vr]),zu=De?.deviceId&&Ae.current.get(De.deviceId)||"",xm=d.useCallback(async(m,x,C)=>{Ca(!1),be(!1),await Zr(()=>vr(m,x,C)),Ae.current.get(m)===x&&Ae.current.delete(m)},[Zr,Ca,vr]),{state:$u,lastFrame:tf,stats:An,error:Uu}=dN(De?.deviceId||"",Na&&ju&&Ze,X,ml,En||Ht||uu.current,zu,wm,xm),Lc=d.useRef(new Map);d.useEffect(()=>{const m=[["hub",W],["registry",l],["license",P],["wall-stream",Qi],["control-stream",zo],["control-decode",st],["remote-input",Jd],["remote-audio",Uu]];for(const[x,C]of m){const E=String(C||"").trim();if(x==="hub"&&Bt?.requiresHubRestart&&Bt.stage==="updating"){Lc.current.delete(x);continue}if(!E){Lc.current.delete(x);continue}Lc.current.get(x)!==E&&(Lc.current.set(x,E),Be(E))}},[Uu,st,zo,W,Jd,P,l,Be,Qi,Bt]);const jl=De?.deviceId||"",nf=De?Es(De,rn[jl]):0;d.useEffect(()=>{if(!$e||!ys||!Ks||!jl)return;const m=yN(),x=jl,C=nf,E=ze=>{if(!ze)return!1;const _e=Uo(x,{...ze,monitorIndex:C});return!_e&&ze.type!=="keyboard.reset"&&(m.reset("browser-input-send-rejected"),lt([])),_e},T=(ze,_e)=>{const xt=ze.target,yn=xt?.tagName?.toLowerCase(),vt=xt?.isContentEditable||yn==="input"||yn==="textarea"||yn==="select",bn=m.isPressed(ze);if(vt&&(_e==="keydown"||!bn))return;const Ln=m.event(ze,_e);Ln&&(ze.preventDefault(),ze.stopPropagation(),E(Ln))},U=ze=>T(ze,"keydown"),K=ze=>T(ze,"keyup"),ee=(ze,_e=!1)=>{const xt=m.reset(ze,_e);xt&&(E(xt),lt([]))};ht.current=ze=>{const _e=m.snapshot().latchedCodes.includes(ze),xt=m.modifier(ze,!_e);xt&&(E(xt),lt(yn=>_e?yn.filter(vt=>vt!==ze):[...yn.filter(vt=>vt!==ze),ze]))};const ie=()=>ee("browser-window-blur"),se=()=>ee("browser-page-hidden"),et=()=>{document.visibilityState==="hidden"&&ee("browser-document-hidden")};return window.addEventListener("keydown",U,!0),window.addEventListener("keyup",K,!0),window.addEventListener("blur",ie),window.addEventListener("pagehide",se),document.addEventListener("visibilitychange",et),()=>{window.removeEventListener("keydown",U,!0),window.removeEventListener("keyup",K,!0),window.removeEventListener("blur",ie),window.removeEventListener("pagehide",se),document.removeEventListener("visibilitychange",et),ht.current=null,ee("control-keyboard-owner-changed",!0)}},[ys,Ks,jl,nf,$e,Uo]);const af=d.useCallback(m=>{He.current=m;const x=je.current||De?.deviceId||"";if(!Ze||!x)return;const C=Ca(te.current,x);if(!m){const T=Ae.current.get(x)||"";Zr(async()=>{await vr(x,T,"remote-audio-document-hidden")}).catch(U=>{(je.current||De?.deviceId||"")===x&&(Ca(!1),Ae.current.delete(x),be(!1),Be(U instanceof Error?U.message:String(U)))});return}const E=`audio-presentation-${Date.now()}-${Math.random().toString(36).slice(2,8)}`;Ae.current.set(x,E),eo(async()=>{if(!Jr(C,x,E)||!Xt||!vs||(je.current||De?.deviceId||"")!==x)return;const T=await rt(`/api/remote/devices/${encodeURIComponent(x)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(T?.ok===!1)throw new Error(T.error||"Remote audio presentation resume failed.");Jr(C,x,E)||(await vr(x,E,"remote-audio-stale-presentation-compensation"),Ae.current.get(x)===E&&Ae.current.delete(x))}).catch(T=>{jr.current&&C===fe.current&&(Ca(!1),Ae.current.delete(x),be(!1),Be(T instanceof Error?T.message:String(T)))})},[Ze,eo,Zr,Ca,Xt,X,Jr,vs,De?.deviceId,Be,vr]);d.useEffect(()=>{const m=T=>{const U=jr.current;T!==U&&(jr.current=T,ds.current+=1,yc.current={active:T&&Qa.current,epoch:ds.current},T||(Dc(),Al(ds.current)),af(T),gh(T),T&&!U&&(vh(K=>K+1),Ii.current=performance.now()))},x=()=>{m(document.visibilityState==="visible")},C=()=>m(!1),E=()=>x();return document.addEventListener("visibilitychange",x),window.addEventListener("pagehide",C),window.addEventListener("pageshow",E),()=>{document.removeEventListener("visibilitychange",x),window.removeEventListener("pagehide",C),window.removeEventListener("pageshow",E)}},[Dc,Al,af]),d.useEffect(()=>{if(!de||Ee!=="connecting"&&Ee!=="active"&&Ee!=="warm"||Kd!=="open")return;const m=de,x=la("control",m),C=window.setInterval(()=>{const E=performance.now();if(document.visibilityState!=="visible"||E-Ii.current<Og)return;const T=ii.current.get(x)||0,U=Di.current.get(x)||0,K=Fs.current.get(x)||0,ee=Li.current.get(x)||E;Li.current.has(x)||Li.current.set(x,ee);const ie=T<=0,se=ie?E-ee>DI:E-T>jx,et=yw({lastReceivedAt:T,lastPaintedAt:U,now:E,staleAfterMs:jx}),ze=vw({paintStale:et,lastRecoveryAt:oi.current.get(x)||0,now:E,recoveryCooldownMs:Dx,transportRecoveryAfterMs:Ix});if(!se&&ze==="reset-decoder"&&vi(m,"control","decoder-paint-stale")||!se&&ze==="wait")return;if(!(se||ze==="recover-transport")){et&&vi(m,"control","decoder-paint-stale"),ie&&E-ee>EI&&!Os.current.has(x)&&ia([m],"control-frame-socket-recovery")&&Os.current.set(x,E);return}const xt=Os.current.get(x)||0;if(xt<=0){ia([m],"control-frame-socket-recovery")&&Os.current.set(x,E);return}if(E-xt<Ex)return;const yn=Bs.current.get(x)||0;if(yn>0){if(E-yn<LI)return;Bs.current.delete(x)}const vt=li.current.get(x)||0;if(vt>=PI){if(Ml(ie?"no first frame":"stale stream"))return;ke(!1),Wa(!1),ba.current=m,Ge("error");return}if(E-K<Lx(II,vt))return;Cl([m],ie?"control-first-frame-timeout":ze==="recover-transport"?"control-paint-timeout":"control-receive-stale")&&(Os.current.delete(x),oi.current.delete(x),Fs.current.set(x,E),Bs.current.set(x,E),Li.current.set(x,E),li.current.set(x,vt+1))},650);return()=>window.clearInterval(C)},[Kd,de,Ee,Ml,ia,vi,Cl]),d.useEffect(()=>{!st||de&&Ye.current[de]||Ir!=="mode3-h264-hw"||Ml(st)||(ke(!1),Wa(!1),ba.current=Nt.current?.deviceId||"",Ge("error"))},[st,de,Ir,Ml]),d.useEffect(()=>{!dt||!de||Ye.current[de]||!zo||(ba.current=de,Ge(m=>m==="error"?m:"error"))},[zo,de,dt]),d.useEffect(()=>{if(Ee!=="error")return;const m=Nt.current;if(!m)return;ba.current=m.deviceId,Kn(Mo.current,m)||(Mo.current=m,fl.current=0);const x=fl.current,C=x===0?0:Math.min(5e3,500*2**Math.min(x-1,4)),E=window.setTimeout(()=>{Kn(Nt.current,m)&&(++qn.current,ya.current="",Ge("stopping"),_r(async()=>{if(Kn(Nt.current,m))try{if(!await Or(m,"control-session-terminal-error"))return;Mo.current=null,fl.current=0,fc.current===m.deviceId?(fc.current="",ba.current="",Ge("idle")):Ge("error")}catch(T){if(!Kn(Nt.current,m))return;fl.current+=1,Be(T instanceof Error?T.message:String(T)),Ge("error"),qr(U=>U+1)}}))},C);return()=>window.clearTimeout(E)},[Ee,Ur,_r,Be,Or]);const Pc=d.useCallback(m=>{if(!m||ba.current!==m)return!1;const x=Nt.current;return++qn.current,ya.current="",fl.current=0,x&&x.deviceId===m?(fc.current=m,Mo.current=null,Ge("error"),qr(C=>C+1),!0):(fc.current="",ba.current="",Mo.current=null,Ge("idle"),!0)},[]);d.useEffect(()=>{if(Us!=="open"||!wt.autoStartLive||pr.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),E=Math.max(OI,Math.ceil(C*4)),T=[],U=[];for(const K of pr){if(U.length+T.length>=zI)break;const ee=la("wall",K),ie=ii.current.get(ee)||0,se=ie<=0,et=Ao.current.get(ee)||x;Ao.current.has(ee)||Ao.current.set(ee,et);const ze=Fs.current.get(ee)||0,_e=Di.current.get(ee)||0,xt=se||x-ie>E,yn=yw({lastReceivedAt:ie,lastPaintedAt:_e,now:x,staleAfterMs:E}),vt=vw({paintStale:yn,lastRecoveryAt:oi.current.get(ee)||0,now:x,recoveryCooldownMs:Dx,transportRecoveryAfterMs:Ix});if(!xt&&vt==="reset-decoder"&&vi(K,"wall","decoder-paint-stale")||!xt&&vt==="wait")continue;if(!(xt||vt==="recover-transport")){yn&&vi(K,"wall","decoder-paint-stale");continue}const Ln=Os.current.get(ee)||0;if(Ln<=0&&(!se||x-et>_I)){T.push(K);continue}if(se&&x-et<=FI||Ln>0&&x-Ln<Ex)continue;const br=li.current.get(ee)||0;x-ze>=Lx(BI,br)&&U.push(K)}if(T.length>0&&Ho(T,"wall-frame-socket-recovery"))for(const K of T)Os.current.set(la("wall",K),x);if(U.length>0&&Yi(U,U.some(K=>(ii.current.get(la("wall",K))||0)<=0)?"wall-first-frame-timeout":"wall-frame-stale"))for(const K of U){const ee=la("wall",K);Os.current.delete(ee),oi.current.delete(ee),Fs.current.set(ee,x),Ao.current.set(ee,x),ii.current.delete(ee),Di.current.delete(ee),li.current.set(ee,(li.current.get(ee)||0)+1)}},HI);return()=>window.clearInterval(m)},[kc,pr,Ho,vi,Yi,wt.autoStartLive,Qt,Us]),d.useEffect(()=>{or(Qt),Cu.current=Date.now(),Wn.current=0,ms.current=0,da.current=0,gc.current=0,jo.current=""},[Qt,wt.frameMode,wt.adaptiveLoadShedding]),d.useEffect(()=>{LA({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,E=jN(m,b),T=()=>{const K=zg(x.map(ee=>String(ee.dataset.liveDeviceId||"")).filter(ee=>(C.get(ee)||0)>0));ti(ee=>Hg(ee,K)?ee:K)},U=new IntersectionObserver(K=>{for(const ee of K){const ie=String(ee.target.dataset.liveDeviceId||"");ie&&C.set(ie,ee.isIntersecting?ee.intersectionRatio||.01:0)}T()},{root:E,rootMargin:b?MN:Si.visibleRootMargin,threshold:[0,.01,.2,.6,1]});return x.forEach(K=>U.observe(K)),T(),()=>U.disconnect()},[yl,Xt,b,dt,mi,wt.visibleOnlyLive,Gt]),d.useEffect(()=>{if(!wt.adaptiveLoadShedding||!wt.autoStartLive||pr.length===0){ms.current=0,da.current=0,gc.current=0,jo.current="";return}const m=Qt;if(Us!=="open"||qs.sampleMs<500||qs.lastUpdatedAt<=0||gc.current===qs.lastUpdatedAt)return;gc.current=qs.lastUpdatedAt;const x=Date.now(),C=pr.map(ze=>({deviceId:ze,receive:fu[la("wall",ze)],paint:dl[la("wall",ze)]}));if(!C.every(({receive:ze,paint:_e})=>{const xt=ze?.lastFrame,yn=Math.max(0,Number(xt?.requestedFps||0)),vt=xt?uo(xt):"";return qN({receiveSampleMs:Number(ze?.sampleMs||0),paintSampleMs:Number(_e?.sampleMs||0),currentGenerationVerified:xt?.currentGenerationVerified===!0,frameRequestedFps:yn,adaptiveFps:Bn})&&_e?.bindingKey===vt})){ms.current=0,da.current=0,Wn.current=0;return}const T=[Bn,...C.map(({deviceId:ze,receive:_e})=>`${ze}:${uo(_e.lastFrame)}`).sort()].join("|");if(jo.current!==T){jo.current=T,ms.current=x,da.current=0,Wn.current=0;return}if(!ms.current){ms.current=x,da.current=0;return}if(x-ms.current<Si.downshiftStableSampleMs)return;const U=C.reduce((ze,{receive:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0)),0),K=C.reduce((ze,{receive:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0))*Math.max(0,Number(_e?.averageFrameBytes||0)),0),ee=C.reduce((ze,{paint:_e})=>ze+Math.max(0,Number(_e?.framesPerSecond||0)),0),ie=Math.max(0,...C.map(({receive:ze})=>Number(ze?.maxIntervalMs||0))),se=Math.max(0,...C.map(({paint:ze})=>Number(ze?.p95IntervalMs||0))),et=UN({directDeviceCount:pr.length,requestedFps:Bn,measuredFramesPerSecond:U,measuredPaintFramesPerSecond:ee,measuredBytesPerSecond:K,maxBytesPerSecond:Si.maxWallBytesPerSecond,worstReceiveGapMs:ie,worstPaintP95Ms:se,maxFrameGapMs:Si.maxFrameGapMs});if(et.overloaded){if(Wn.current=0,da.current+=1,da.current<Si.downshiftConsecutiveSamples)return;const ze=Si.minFps;if(x-Cu.current>=Si.downshiftCooldownMs&&Bn>ze){const _e=Math.max(ze,sL(Bn,ze));_e<Bn&&(or(_e),Cu.current=x,ms.current=0,da.current=0)}return}if(da.current=0,!et.healthyForRecovery||Bn>=m){et.healthyForRecovery||(Wn.current=0);return}if(!Wn.current){Wn.current=x;return}if(x-Wn.current>=Si.recoveryCooldownMs){const ze=Math.min(m,iL(Bn,m));ze>Bn&&(or(ze),Cu.current=x,Wn.current=0,ms.current=0,da.current=0)}},[Bn,pr.length,pr,dl,fu,Us,qs.lastUpdatedAt,qs.sampleMs,wt.adaptiveLoadShedding,wt.autoStartLive,wt.frameMode,Qt]),d.useEffect(()=>{const m=new URLSearchParams(window.location.search).get("checkout");if(m==="success"){Be("Checkout returned. Waiting for Dodo confirmation."),re();const x=window.setInterval(()=>{re()},4e3),C=window.setTimeout(()=>{window.clearInterval(x)},45e3);return()=>{window.clearInterval(x),window.clearTimeout(C)}}m==="cancelled"&&Be("Checkout cancelled.")},[re]),d.useEffect(()=>{!Xt&&$e&&We(!1),!Xt&&Ze&&(Ca(!1),be(!1))},[Ze,$e,Ca,Xt]),d.useEffect(()=>{Ze&&(!De||!vs)&&(Ca(!1),be(!1))},[Ze,Ca,vs,De]),d.useEffect(()=>{const m=De?.deviceId||"",x=je.current;if(je.current=m,!x||x===m)return;const C=Ca(Ze,m),E=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:"";m&&Ze&&Ae.current.set(m,E);let T=!0;const U=Ae.current.get(x)||"";return(async()=>{try{await Zr(async()=>{await vr(x,U,"remote-audio-device-switch"),Ae.current.delete(x)}),await eo(async()=>{if(!T||!Jr(C,m,E)||!m||!Xt||!vs)return;const K=await rt(`/api/remote/devices/${encodeURIComponent(m)}/audio/start`,{method:"POST",body:JSON.stringify({streamId:E,mimeType:"audio/pcm;format=f32le",sampleRate:48e3,channels:2})},X);if(K.ok===!1)throw new Error(K.error||"Remote audio start failed.");Jr(C,m,E)||(await vr(m,E,"remote-audio-stale-device-switch-compensation"),Ae.current.get(m)===E&&Ae.current.delete(m))})}catch(K){T&&(Ca(!1),Ae.current.delete(m),be(!1),Be(K instanceof Error?K.message:String(K)))}})(),()=>{T=!1}},[Ze,eo,Zr,Ca,Xt,X,Jr,vs,De?.deviceId,vr]),d.useEffect(()=>{const m=pt.map(T=>T.deviceId),x=new Set(m),C=new Map(pt.map(T=>[T.deviceId,T])),E=new Map;for(const T of pt){const U=VI(T);if(!U)continue;const K=ki(T.status),ee=[T.lastStatusAt,K.capturedAt,K.collectedAt,K.timestamp,K.updatedAt].find(se=>typeof se=="string"&&se.trim()),ie=wN(Js.current[T.deviceId],U,ee);ie&&(Js.current[T.deviceId]=ie,E.set(T.deviceId,ie),X0({platform:T.platform,topologyFingerprint:U,consecutiveTopologySamples:ie.consecutiveSamples})&&(oc.current[T.deviceId]=U))}for(const T of Object.keys(Js.current))x.has(T)||delete Js.current[T];Z(T=>{const U=T.filter(K=>x.has(K));return Hg(T,U)?T:U}),ae(T=>T&&x.has(T)?T:""),Pe(T=>T&&x.has(T)?T:""),cs(T=>{let U=!1;const K={};for(const[ee,ie]of Object.entries(T)){const se=C.get(ee);if(!se){K[ee]=ie;continue}const et=E.get(ee)||Js.current[ee],ze=xN({requestedIndex:ie,monitorCount:mo(se),platform:se.platform,topologyFingerprint:et?.fingerprint||"",consecutiveTopologySamples:et?.consecutiveSamples||0});K[ee]=ze,ze!==ie&&(U=!0)}return U?K:T}),hl(T=>{const U=T.filter(K=>x.has(K));return Hg(T,U)?T:U})},[pt,Do]),d.useEffect(()=>{gm([]),wu(!1)},[$s]),d.useEffect(()=>{!Hi||To!=="selected"||ja.length>0||In.length===0||hl(In.map(m=>m.deviceId))},[In,ja.length,To,Hi]),d.useEffect(()=>{try{localStorage.setItem(YS,$r)}catch{}},[$r]),d.useEffect(()=>{JI(wt)},[wt]),d.useEffect(()=>{tL(_n)},[_n]),d.useEffect(()=>{XI(rn,oc.current)},[pt,rn]);const qu=d.useCallback(async()=>{const m=new Set(w);m.add($n);try{const U=await rt("/api/remote/status",void 0,$n);Ob({endpoint:U.agentEndpoint,endpoint_candidates:[...U.agentEndpointCandidates||[],...U.hostTargetEndpointCandidates||[]]}).forEach(K=>m.add(K))}catch{}const x=[...m].sort((U,K)=>{const ee=ie=>{const se=Zf(ie);return se==="local"?0:se==="loopback"?1:2};return ee(U)-ee(K)||U.localeCompare(K)});let C=!1,E="",T=!1;try{for(const U of x){const K=Zf(U);try{if(await rt("/api/health",void 0,U),K==="local")return H(!0),xd(!0),U;K==="loopback"&&(C=!0,E=U)}catch{K==="local"&&(T=!0)}}return C?(T&&Be("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),xd(!0),E||$n):(H(!1),xd(!1),"")}catch{return H(!1),xd(!1),""}},[w]),qo=async()=>{if(hn("auth"),sr(!1),window.liveDesk?.auth?.signInWithGoogle){const E=window.liveDesk.auth.signInWithGoogle();qu();const T=await E;T?.ok===!1&&(Be(T.error||"LiveDesk could not open the system browser for Google sign-in."),hn(""));return}const m=$t.auth.signInWithOAuth({provider:"google",options:{redirectTo:`${window.location.origin}/callback`}});qu();const{data:x,error:C}=await m;C&&(Be(C.message),hn(""))},_c=async()=>{hn("auth"),sr(!1),window.liveDesk?.auth?.persistSession||await rt("/api/auth/session",{method:"DELETE"},X||$n).catch(()=>{}),await $t.auth.signOut(),(await window.liveDesk?.auth?.persistSession?.(null))?.runtimeCleared===!1&&Be("Signed out locally. The LiveDesk runtime could not be reached to clear its session."),hn("")};d.useEffect(()=>{if(!Ai)return;const m=C=>{C.target instanceof Element&&(C.target.closest(".account-popover, .rail-account")||sr(!1))},x=C=>{C.key==="Escape"&&sr(!1)};return window.addEventListener("pointerdown",m),window.addEventListener("keydown",x),()=>{window.removeEventListener("pointerdown",m),window.removeEventListener("keydown",x)}},[Ai]);const Wu=d.useCallback(async(m={})=>{const x=m.silent===!0,C=m.takeover===!0,E=m.requestLocalAccess===!0;if(!n?.user){x||Be("Sign in before publishing this host.","error");return}if(!Bi.current){Bi.current=!0,x||(hn("host"),it("Hub · 1/4 · Checking the local runtime…"));try{const U=(E?await qu():"")||X||$n;if(!($||await rt("/api/remote/status",void 0,U)).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}})},U);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})},U);if(!ie.ok)throw new Error(ie.error||"host-target-failed");if(!x){it("Hub · 4/4 · Verifying the endpoint and lease renewal…");const se=await rt("/api/hub/status",void 0,U);if(!se.hostTargetActive)throw new Error(se.hostTargetLease?.lastError||"host-target-not-active-after-sync");const et=se.hostTargetEndpoint||se.agentEndpoint||"endpoint ready",ze=Number(se.connectedDeviceCount||0),_e=ze>0?`${ze} client${ze===1?"":"s"} connected.`:"No clients connected yet; reconnect the laptop Client.";Be(`Hub ready · ${et} · lease auto-renewal active. ${_e}`,"success"),(E||j)&&(H(!0),xd(!0)),V()}u()}catch(T){if(!x){const U=T instanceof Error?T.message:String(T);U.includes("local network access")&&(H(!1),xd(!1)),Be(`Hub setup failed · ${U}`,"error")}}finally{Bi.current=!1,x||hn("")}}},[X,j,V,u,qu,n,Be,it,$]),to=d.useCallback((m=!0)=>{kt!=="host"&&(Dt(!1),m&&window.requestAnimationFrame(()=>Mr.current?.focus()))},[kt]),Sm=d.useCallback(()=>{kt!=="host"&&(Mr.current=document.activeElement instanceof HTMLElement?document.activeElement:null,sr(!1),Dt(!0))},[kt]),Cm=d.useCallback(()=>{Dt(!1),Wu({takeover:!0,requestLocalAccess:!0})},[Wu]);d.useEffect(()=>{if(!nt)return;const m=window.requestAnimationFrame(()=>gn.current?.focus()),x=E=>{E.target instanceof Element&&E.target.closest(".client-hub-switch-popover, .hub-sync-trigger")||to(!1)},C=E=>{E.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(!(!$?.update?.canApply||kt==="update")){hn("update");try{const m=await rt("/api/update/apply",{method:"POST",body:JSON.stringify({})},X||$n);if(!m.ok)throw new Error(m.error||"LiveDesk update could not be started.");const x=[...new Set((m.targets||[]).map(T=>String(T.deviceId||"").trim()).filter(Boolean))],C=!!(m.managerUpdateAvailable||m.clientPackageUpdateAvailable),E=m.state==="hub-restart-requested"?Date.now():void 0;(x.length>0||C)&&Tr({operationId:String(m.operationId||`wall-update-${Date.now()}`),targetIds:x,stage:m.state==="clients-updated"?"updated":"updating",requiresHubRestart:C,initialHostInstanceId:String($.hostInstanceId||""),targetManagerVersion:String(m.latestVersion||$.update?.latestVersion||""),targetClientVersion:String(m.latestClientVersion||$.update?.latestClientVersion||""),restartRequestedAt:E,restartDeadlineAt:E?E+Ap:void 0}),it(m.state==="hub-restart-requested"?Mp:xx),V()}catch(m){Be(m instanceof Error?m.message:String(m),"error")}finally{hn("")}}},[kt,X,V,Be,it,$]);d.useEffect(()=>{const m=Bt,x=$?.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.`;Tr(se=>se?.operationId===m.operationId?{...se,stage:"restored",error:ie}:se),Be(`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.";Tr(se=>se?.operationId===m.operationId?{...se,stage:"failed",error:ie}:se),Be(`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.";Tr(se=>se?.operationId===m.operationId?{...se,stage:"failed",error:ie}:se),Be(ie,"error");return}if(x.operationId===m.operationId){if(x.state==="hub-restart-requested"&&!m.restartDeadlineAt){const ie=Date.now();Tr(se=>se?.operationId===m.operationId?{...se,restartRequestedAt:ie,restartDeadlineAt:ie+Ap}:se),it(Mp)}!m.requiresHubRestart&&x.state==="clients-updated"&&(Tr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Be("LiveDesk clients updated and reconnected successfully.","success"));return}if(!m.requiresHubRestart)return;const E=$.started===!0&&(!m.initialHostInstanceId||$.hostInstanceId&&$.hostInstanceId!==m.initialHostInstanceId),T=!!x.checkedAt,U=kx(x.currentVersion,m.targetManagerVersion),K=!m.targetClientVersion||kx(x.currentClientVersion,m.targetClientVersion),ee=T&&x.state==="idle"&&x.updateAvailable===!1&&U&&K;E&&ee&&(Tr(ie=>ie?.operationId===m.operationId?{...ie,stage:"updated"}:ie),Be(`LiveDesk Hub ${x.currentVersion||C?.appVersion||m.targetManagerVersion} restarted and passed version verification.`,"success"))},[Be,it,$,Bt]),d.useEffect(()=>{const m=Bt;if(!m||m.stage!=="updating"||!m.requiresHubRestart||m.restartDeadlineAt)return;const x=()=>{const E=Date.now();Tr(T=>T?.operationId===m.operationId&&T.stage==="updating"&&!T.restartDeadlineAt?{...T,restartRequestedAt:E,restartDeadlineAt:E+Ap}:T),it(Mp)};if($?.update?.state==="hub-restart-requested"){x();return}if(!W)return;const C=window.setTimeout(x,CI);return()=>window.clearTimeout(C)},[W,it,$?.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,E=window.setTimeout(()=>{const T=`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.`;Tr(U=>U?.operationId===C&&U.stage==="updating"?{...U,stage:"failed",error:T}:U),Be(T,"error")},x);return()=>window.clearTimeout(E)},[Be,Bt]),d.useEffect(()=>{if(!Bt||Bt.stage!=="updated")return;const m=Bt.operationId,x=window.setTimeout(()=>{Tr(C=>C?.operationId===m?null:C)},Sx);return()=>window.clearTimeout(x)},[Bt]),d.useEffect(()=>{ir.current.clear(),ei({})},[Bt?.operationId]),d.useEffect(()=>{if(!Bt||$?.update?.operationId!==Bt.operationId)return;const m=($.update.targets||[]).filter(C=>C.state==="completed").map(C=>Cx(Bt.operationId,C)).filter(C=>!ir.current.has(C));if(m.length===0)return;const x=Date.now()+Sx;for(const C of m)ir.current.add(C);ei(C=>({...C,...Object.fromEntries(m.map(E=>[E,x]))}))},[$?.update,Bt]),d.useEffect(()=>{const m=Math.min(...Object.values(bo));if(!Number.isFinite(m))return;const x=window.setTimeout(()=>{const C=Date.now();ei(E=>Object.fromEntries(Object.entries(E).filter(([,T])=>T>C)))},Math.max(0,m-Date.now()));return()=>window.clearTimeout(x)},[bo]),d.useEffect(()=>{if(Hr!==xx&&Hr!==Mp)return;const m=$?.update;if(String(m?.state||"")==="failed"){Be(m?.error||"LiveDesk update failed.","error");return}Bt?.stage==="updated"&&Be("")},[Hr,Be,$?.update?.error,$?.update?.state,Bt?.stage]);const km=d.useCallback(async()=>{if(!kt){hn("pin");try{const x=await rt("/api/remote/pairing-pin",{method:"POST"},X||$n);if(!x.ok)throw new Error(x.error||"pin-rotation-failed");await V(),Be("New PIN published.")}catch(m){Be(m instanceof Error?m.message:String(m))}finally{hn("")}}},[kt,X,V]),Fc=d.useCallback(m=>{m&&(ae(m),Z(x=>x.includes(m)?x:[...x,m]))},[]),Gu=d.useCallback(m=>{if(!m)return;const x=dr.has(m);ae(C=>x?C===m?"":C:m),Z(C=>x?C.filter(E=>E!==m):C.includes(m)?C:[...C,m])},[dr]),Wo=d.useCallback(()=>{Z([]),ae("")},[Ss]),Vu=d.useCallback(()=>{Z(pt.map(m=>m.deviceId)),ae("")},[pt]),Ku=d.useCallback((m,x)=>{const C=pt.find(T=>T.deviceId===m);if(!C)return;const E=mo(C);if(!(E<=1)&&(cs(T=>{const U=Gf(T[m],E),K=(U+x+E)%E;return K===U?T:{...T,[m]:K}}),ua("wall",m),ua("control",m),za(T=>{if(!T.has(m))return T;const U=new Set(T);return U.delete(m),U}),Ua.current.delete(m),lr.current.delete(m),dt)){const T=Pc(m);ke(!1),T||Ge("connecting"),Wa(!1),Pe(m)}},[pt,ua,Pc,dt]);d.useEffect(()=>{const m=x=>{if($e&&ys&&Ks)return;const C=x.target,E=C?.tagName?.toLowerCase();C?.isContentEditable||E==="input"||E==="textarea"||E==="select"||((x.ctrlKey||x.metaKey)&&x.key.toLowerCase()==="a"&&(x.preventDefault(),Vu()),x.key==="Escape"&&Wo())};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[ys,Wo,Ks,$e,Vu]);const Mm=(m,x)=>{const C=pt.find(K=>K.deviceId===m),E=C?mo(C):1,T=Gf(rn[m],E),U=Gf(x,E);if(T!==U&&(cs(K=>({...K,[m]:U})),za(K=>{if(!K.has(m))return K;const ee=new Set(K);return ee.delete(m),ee}),Ua.current.delete(m),lr.current.delete(m),qa.current.delete(m),ai.current.delete(m),Ma.current.delete(m),ua("wall",m),ua("control",m)),dt){const K=Pc(m);T!==U&&(ke(!1),K||Ge("connecting")),Wa(!1),Pe(m)}else Fc(m)},Go=m=>{const x=je.current||De?.deviceId||"",C=[...new Set([x,m].filter(Boolean))],E=Ze||C.some(T=>Ae.current.has(T));Ca(!1),be(!1);for(const T of C)Ae.current.delete(T);C.length!==0&&(async()=>{for(const T of C)await Zr(()=>Hu(T,"remote-audio-control-entry"))})().catch(T=>{E&&Be("Remote audio was muted locally, but Client capture stop was not confirmed: "+(T instanceof Error?T.message:String(T)),"error")})},no=async m=>{const x={requestId:++hh.current,deviceId:m,startedAt:performance.now(),startedAtEpochMs:Date.now()};if(ri.current=x,!fr.has(m)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Be(vl);return}const C=pt.find(T=>T.deviceId===m);if(tl(C?.platform)&&(C?.capabilities?.controlPermission===!1||C?.capabilities?.accessibilityPermission===!1)){ri.current?.requestId===x.requestId&&(ri.current=null),We(!1),Be("Mac remote control needs Accessibility permission. Allow it for the terminal app that starts LiveDesk, then restart the Mac client.","error");return}Go(m),Pc(m),Wa(!1),Pe(m),bt("control"),We(!0),Be(`Opening remote control${C?` for ${La(C)}`:""}.`,"success")},rf=async()=>{if(!De){Be("Select a Client before playing audio.");return}if(!Xt){Be(vl);return}if(!vs){Be("Selected Client does not report remote audio support yet.");return}if(en)return;const m=!Ze,x=m?`audio-${Date.now()}-${Math.random().toString(36).slice(2,8)}`:Ae.current.get(De.deviceId),C=Ca(m,De.deviceId);m&&x?Ae.current.set(De.deviceId,x):m||Ae.current.delete(De.deviceId),q("audio"),be(m);try{m?(await Zr(()=>Hu(De.deviceId,"remote-audio-user-enable-reconcile")),await eo(async()=>{if(!x||!Jr(C,De.deviceId,x))return;const E=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(E?.ok===!1)throw new Error(E.error||"Remote audio start failed.");Jr(C,De.deviceId,x)||await vr(De.deviceId,x,"remote-audio-stale-user-start-compensation")})):await Zr(()=>Hu(De.deviceId,"remote-audio-user-disabled")),Be(`${m?"Audio started":"Audio stopped"} for ${La(De)}.`,"success")}catch(E){Ca(!1),m&&Ae.current.delete(De.deviceId),be(!1),Be(E instanceof Error?E.message:String(E),"error")}finally{q("")}},Am=async(m,x)=>{const C=m.deviceId,E=La(m),T=String(Ye.current[C]||""),U=!!T&&mt[C]===!0;if(x&&T&&!U)return{ok:!0,skipped:!0,action:"pause",deviceId:C,title:E};if(!x&&!T)return{ok:!0,skipped:!0,action:"resume",deviceId:C,title:E};if(!x&&T.startsWith("pending:"))return{ok:!1,action:"resume",deviceId:C,title:E,error:"Pause is still pending confirmation."};if(x){const et=T||`pending:${Date.now()}:${C}`,ze=Nt.current?.deviceId===C?Nt.current:null,_e=!!ze||de===C,xt=_e?++qn.current:0,yn=()=>pw({deviceId:C,requestTransitionGeneration:xt,currentTransitionGeneration:qn.current,actualControlOwner:Nt.current}),vt=yt.current.get(C);yt.current.set(C,{deviceId:C,monitorIndex:Es(m,rn[C]??vt?.monitorIndex),previousControlOwner:ze||vt?.previousControlOwner||null}),va(C,!0),an(C,!1),mn(C,et),Pu(C),_e&&(ya.current="",Ge("paused"));try{const bn=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/pause`,{method:"POST",body:JSON.stringify({reason:"user-video-pause"})},X);if(!bn?.pauseToken)return _t.current.delete(C),mn(C,""),an(C,!1),yt.current.delete(C),yn()&&(Re.current=null,qe(null),ke(!1),Fe(`control-pause-rollback-${Date.now()}-${C}`),Ge("connecting")),{ok:!1,action:"pause",deviceId:C,title:E,error:bn?.error||"video-capture-pause-failed"};const Ln=String(Ye.current[C]||"");if(Ln!==et&&Ln!==bn.pauseToken)return{ok:!1,action:"pause",deviceId:C,title:E,error:"Pause ownership changed before confirmation."};const br=yn(),As=br&&Nt.current?.deviceId===C?Nt.current:ze,Yo=yt.current.get(C);return Yo&&(Yo.previousControlOwner=As),br&&Nt.current?.deviceId===C&&(Nt.current=null),br&&(Re.current=null,qe(null)),mn(C,bn.pauseToken),br&&Ge("paused"),bn.ok===!1||bn.captureStopConfirmed!==!0?(an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:E,error:bn.stopError||bn.error||"Client capture shutdown was not confirmed."}):(an(C,!1),{ok:!0,action:"pause",deviceId:C,title:E})}catch(bn){return an(C,!0),{ok:!1,unconfirmed:!0,action:"pause",deviceId:C,title:E,error:bn instanceof Error?bn.message:String(bn)}}}const K=yt.current.get(C),ee=K?.previousControlOwner||null,ie=de===C&&(ee!==null||cr.current?.deviceId===C||Ee==="paused"),se=ie?qn.current:0;try{va(C,!1);const et=await rt(`/api/remote/devices/${encodeURIComponent(C)}/live/resume`,{method:"POST",body:JSON.stringify({pauseToken:T})},X);if(et?.ok===!1)throw new Error(et.error||"video-capture-resume-failed");if(String(Ye.current[C]||"")!==T)return{ok:!1,action:"resume",deviceId:C,title:E,error:"Resume ownership changed before confirmation."};const ze=yt.current.get(C)||K,_e=ze?.previousControlOwner||ee,xt=ie&&pw({deviceId:C,requestTransitionGeneration:se,currentTransitionGeneration:qn.current,actualControlOwner:Nt.current});if(mn(C,""),an(C,!1),yt.current.delete(C),xt){const yn=++qn.current;ya.current="";const vt=Cg(C,yn,{sessionId:m.sessionId||_e?.sessionId,monitorIndex:Es(m,rn[C]??ze?.monitorIndex)});Nt.current=vt,Fr(vt),ba.current="",Mo.current=null,Re.current=null,qe(null),at(""),jt(""),ke(!1),ua("control",C);const bn=`control-video-resume-${yn}-${C}`;Fe(bn),Ke(C),Ge("connecting")}else ua("wall",C);return{ok:!0,action:"resume",deviceId:C,title:E}}catch(et){return _t.current.delete(C),{ok:!1,action:"resume",deviceId:C,title:E,error:et instanceof Error?et.message:String(et)}}},Oc=async()=>{if(bs.length===0){Be("Select one or more Clients before pausing video.");return}if(Da.length===0){Be(vl);return}if(en)return;const m=Da.some(C=>{const E=String(Ye.current[C.deviceId]||"");return!E||E.startsWith("pending:")||mt[C.deviceId]===!0}),x=Da.filter(C=>{const E=String(Ye.current[C.deviceId]||"");return m?!E||E.startsWith("pending:")||mt[C.deviceId]===!0:!!E});if(x.length===0){Be(m?"Selected Clients are already paused.":"Selected Clients are already playing.");return}q("video");try{const C=await Promise.all(x.map(se=>Am(se,m)));V();const E=C.filter(se=>se.ok&&!se.skipped),T=C.filter(se=>!se.ok&&se.unconfirmed),U=C.filter(se=>!se.ok&&!se.unconfirmed),K=Da.length-x.length+C.filter(se=>se.skipped).length,ee=bs.length-Da.length,ie=m?"pause":"resume";if(U.length>0||T.length>0){const se=U.slice(0,2).map(et=>`${et.title}: ${et.error||"unknown error"}`).join(" · ");Be([`Video ${ie} completed for ${E.length}/${x.length} Clients.`,T.length>0?`${T.length} Client capture stop${T.length===1?"":"s"} remain unconfirmed.`:"",se,ee>0?`${ee} selected Client${ee===1?"":"s"} were outside the current plan limit.`:""].filter(Boolean).join(" "),"error");return}Be([`Video ${m?"paused":"resumed"} for ${E.length} Client${E.length===1?"":"s"}.`,K>0?`${K} already ${m?"paused":"playing"}.`:"",ee>0?`${ee} outside the current plan limit.`:""].filter(Boolean).join(" "),"success")}finally{q("")}},Nm=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,E={sleep:"Sleep",restart:"Restart",shutdown:"Shut down"}[m];if(window.confirm(`${E} ${La(x)}? Unsaved work on that computer may be lost.`)){q(m),Be(`Sending ${E.toLowerCase()} request to ${La(x)}...`);try{const T=await rt(`/api/remote/devices/${encodeURIComponent(x.deviceId)}/quick-actions`,{method:"POST",body:JSON.stringify({action:m})},X);if(!T.ok)throw new Error(T.error||"The remote action could not be sent.");Be(`${E} request sent to ${La(x)}.`,"success"),V()}catch(T){Be(Nm(T),"error")}finally{q("")}}},sf=async(m,x,C="files")=>{const E=m.filter(ee=>ee.file.size>=0);if(E.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 T=crypto.randomUUID(),U=E.reduce((ee,ie)=>ee+ie.file.size,0);let K=0;di({id:T,status:"reading",progress:1,message:`Preparing ${E.length} ${C}`});try{for(let ee=0;ee<E.length;ee+=1){const ie=E[ee],se=ie.file,et=Math.max(1,Math.ceil(se.size/Fg));for(let ze=0;ze<et;ze+=1){const _e=ze*Fg,xt=Math.min(se.size,_e+Fg),yn=se.size===0?new ArrayBuffer(0):await se.slice(_e,xt).arrayBuffer(),vt=ze===et-1;di({id:T,status:"sending",progress:Math.max(2,Math.min(98,Math.round(K/Math.max(1,U)*96))),message:`${ee+1}/${E.length} ${ie.relativePath}`});const bn=await rt("/api/remote/files/chunk",{method:"POST",body:JSON.stringify({transferId:T,deviceIds:x,remoteDirectory:$r.trim(),name:se.name,relativePath:ie.relativePath,size:se.size,type:se.type,lastModified:se.lastModified,offset:_e,totalBytes:se.size,final:vt,dataBase64:oL(yn)})},X);if(!bn.ok||bn.queued!==x.length)throw new Error(bn.error||`file-chunk-not-queued-${bn.queued}/${x.length}`);K+=yn.byteLength,await new Promise(Ln=>window.setTimeout(Ln,0))}}return di({id:T,status:"queued",progress:100,message:`Sent ${E.length} file${E.length===1?"":"s"} to ${x.length} Client${x.length===1?"":"s"}`}),window.setTimeout(()=>{di(ee=>ee?.id===T&&ee.status==="queued"?null:ee)},4500),{files:E.length,bytes:U}}catch(ee){throw di({id:T,status:"failed",progress:100,message:ee instanceof Error?ee.message:String(ee)}),ee}},of=async m=>{const x=In.length>0?In.map(C=>C.deviceId):De?[De.deviceId]:[];try{await sf(Fx(m),x)}catch(C){Be(C instanceof Error?C.message:String(C))}},Tm=async m=>{try{await sf(Fx(m),Sa)}catch(x){Be(x instanceof Error?x.message:String(x))}};d.useEffect(()=>{Su.current=!1},[]);const lf=m=>{m.preventDefault(),m.stopPropagation(),Hd(!1),of(m.dataTransfer.files)},zn=async(m="ltd")=>{if(!n){Be("Sign in with Google before checkout.");return}if(J&&m===Ut){Be("LiveDesk license is already active.");return}if(J&&Ut==="pro"){Be("LiveDesk Pro is already active.");return}hn("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){Be(x instanceof Error?x.message:String(x)),hn("")}},ea=$I(),cf=UI(),Qu=bl.filter(m=>Mn.has(m)).length,Yu=kl==="open"&&Xi.sampleMs>0?`${Xi.framesPerSecond.toFixed(1)} fps`:kl,Ve=De?dt?Sl.get(De.deviceId):Mn.get(De.deviceId):void 0,ao=De?Es(De,rn[De.deviceId]):0,Rm=De?GI(De):[],Xu=typeof Ve?.monitorIndex=="number"?Gf(Ve.monitorIndex,Math.max(1,Ve.monitorCount||1)):ao,uf=(Ve&&Xu===ao?rC(Ve):null)||(De?aC(De,ao):null);uf&&`${uf.width}${uf.height}`;const Vo=De?la(dt?"control":"wall",De.deviceId):"",oa=Vo?fu[Vo]:void 0,yr=Vo?dl[Vo]:void 0,Mt=yr?.lastInfo,jm=oa&&oa.sampleMs>0?`${oa.framesPerSecond.toFixed(1)} fps`:"waiting";oa&&`${oa.totalFrames}${jm}`,yr&&yr.sampleMs>0&&`${yr.framesPerSecond.toFixed(1)}`,yr&&yr.sampleMs>0&&`${yr.changedFramesPerSecond.toFixed(1)}`,Mt&&(`${Mt.frameSeq}${Mt.decoderLabel}${Mt.queueSize}${Mt.renderQueueSize}${Mt.droppedForLatency}${Mt.decoderFlushCount}${Mt.decoderTimestampFallbacks}${Mt.decoderInputCount}${Mt.decoderOutputCount}`,Mt.visualChanged),Mt&&`${Math.round(Mt.queuedForMs)}${Math.round(Mt.decodedForMs)}${Math.round(Mt.scheduledForMs)}${Mt.drawMs.toFixed(1)}`,Mt?.targetPaintIntervalMs&&`${Mt.targetPaintIntervalMs.toFixed(1)}${(1e3/Mt.targetPaintIntervalMs).toFixed(1)}`,yr&&`${yr.decoderInputFps.toFixed(1)}${yr.decoderOutputFps.toFixed(1)}`,Mt?.canvasPresentation,Mt&&`${Mt.interactiveBufferWaitCount}${Math.round(Mt.interactiveBufferWaitMs)}${Mt.interactiveQueueDrainCount}`,oa&&(Ve?.frameMode==="mode5-lzo-delta"?`${Vf(oa.averageFrameBytes)}${Ve.deltaVisualTileCount||0}${Ve.deltaRefreshTileCount||0}${Ve.deltaTotalTiles||0}`:`${Vf(oa.averageFrameBytes)}${Math.round(oa.tinyFrameRatio*100)}${Math.round(oa.repeatedFrameRatio*100)}`),oa&&oa.sourceSendSampleCount>0&&`${oa.sourceSendAverageMs.toFixed(1)}${oa.sourceSendP95Ms.toFixed(1)}`,Nx(oa),Nx(yr),oa&&yr&&`${Tx(oa)}${Tx(yr)}`,Ve?Ve.frameMode||Ve.mode||Ve.codec||Ve.mimeType:dt?_n.frameMode:wt.frameMode,dt?_n.frameMode:wt.frameMode,Ve?`${Ve.width}${Ve.height}${Vf(Ve.byteLength)}`:dt?`${gs.maxWidth}${gs.maxHeight}`:`${wt.maxWidth}${wt.maxHeight}`,Ve&&`${Ve.isKeyFrame?"key":String(Ve.chunkType||"delta")}`,Ve&&Ve.monitorCount&&((Ve.monitorIndex??0)+1,`${Ve.monitorCount}`),Ve&&[`src ${Math.round(Ve.sourceGapMs||0)}ms`,`gap ${Math.round(Ve.agentSendGapMs||0)}ms`,`tx ${Math.round(Ve.agentSendDurationMs||0)}ms`,`pace ${Math.round(Ve.agentPaceMs||0)}ms`,`queue ${Math.round(Ve.agentQueueBeforePaceMs||0)}ms`,`age ${Math.round(Ve.agentFrameAgeMs||0)}ms`,Ve.hubPacketTransitAgeMs!==void 0?`sock ${Math.max(0,Math.round(Ve.hubPacketTransitAgeMs))}ms`:"",Ve.droppedByAgent?`drop ${Ve.droppedByAgent}`:"",Ve.hubIngressDropped?`ingress-drop ${Ve.hubIngressDropped}`:"",Ve.hubClientDropped?`ws-drop ${Ve.hubClientDropped}`:"",Ve.captureStageMs?`capture ${Math.round(Ve.captureStageMs)}ms`:"",Ve.requestedFps?`req ${Math.round(Ve.requestedFps)}fps`:"",Ve.effectiveFps?`eff ${Math.round(Ve.effectiveFps)}fps`:"",Ve.captureAverageMs?`avg ${Math.round(Ve.captureAverageMs)}ms`:"",Ve.captureP95Ms?`p95 ${Math.round(Ve.captureP95Ms)}ms`:"",Ve.slowFrameCount?`slow ${Math.round(Ve.slowFrameCount)}`:"",Ve.captureHelperRestarts?`helper ${Math.round(Ve.captureHelperRestarts)}`:"",Ve.convertMs?`rgb565 ${Math.round(Ve.convertMs)}ms`:"",Ve.compressMs?`lzo ${Math.round(Ve.compressMs)}ms`:"",Ve.captureSourceSerial?`cap #${Ve.captureSourceSerial}`:"",Ve.captureSourceSkipped?`cap skip ${Ve.captureSourceSkipped}`:"",Ve.frameMode==="mode5-lzo-delta"?`tiles ${Ve.deltaVisualTileCount||0}+${Ve.deltaRefreshTileCount||0}/${Ve.deltaTotalTiles||0}@${Ve.deltaTileSize||0}`:"",Ve.platformProfile||Ve.hardwareEncoder||"-",Ve.atlasComposeMs?`atlas ${Ve.atlasComposeMs.toFixed(1)}ms`:"",Ve.atlasPoolStarved?`pool ${Ve.atlasPoolStarved}`:"",Ve.atlasTileCount?`tiles ${Ve.atlasReadyTiles||0}/${Ve.atlasTileCount}`:"",Ve.atlasInputRevision?`input #${Ve.atlasInputRevision}`:"",Ve.atlasSourceMaxAgeMs!==void 0?`input-age ${Math.round(Ve.atlasSourceMaxAgeMs)}ms`:"",Mt?.inputFeedbackMs!==void 0&&Mt.inputFeedbackAt!==void 0&&performance.now()-Mt.inputFeedbackAt<=gx?`feedback ${Math.round(Mt.inputFeedbackMs)}ms`:"",Ve.contentHash?`enc ${Ve.contentHash.slice(0,6)}`:"",Mt?.visualHash?`pix ${Mt.visualHash.slice(0,6)}`:""].filter(Boolean).join(" / "),Fu==="open"&&[`${Vs.sentPerSecond.toFixed(1)} hz`,Vs.lastInputSeq>0?`rtt ${Math.round(Vs.lastRoundTripMs)}ms`:"",Vs.lastInputSeq>0?`apply ${Vs.lastAgentApplyMs.toFixed(1)}ms`:"",Vs.droppedPerSecond>0?`drop ${Vs.droppedPerSecond.toFixed(1)}/s`:"",Vs.bufferedAmount>0?`buf ${Vf(Vs.bufferedAmount)}`:"",Vs.lastInputType||"ready"].filter(Boolean).join(" / "),Mt?.inputFeedbackMs!==void 0&&Mt.inputFeedbackAt!==void 0&&performance.now()-Mt.inputFeedbackAt<=gx&&[Mt.inputFeedbackExact?"exact":"estimated",Mt.inputFeedbackInputType||"",`total ${Math.round(Mt.inputFeedbackMs)}ms`,Mt.inputFeedbackAgentApplyMs!==void 0?`apply ${Mt.inputFeedbackAgentApplyMs.toFixed(1)}ms`:"",Mt.inputFeedbackApplyToCaptureMs!==void 0?`apply→frame ${Math.round(Mt.inputFeedbackApplyToCaptureMs)}ms`:"",Mt.inputFeedbackInputToFrameMs!==void 0?`input→browser ${Math.round(Mt.inputFeedbackInputToFrameMs)}ms`:"",Mt.inputFeedbackFrameToPaintMs!==void 0?`browser→paint ${Math.round(Mt.inputFeedbackFrameToPaintMs)}ms`:"",Mt.inputFeedbackSampleCount?`p50 ${Math.round(Mt.inputFeedbackP50Ms||0)}ms`:"",Mt.inputFeedbackSampleCount?`p95 ${Math.round(Mt.inputFeedbackP95Ms||0)}ms`:"",Mt.inputFeedbackSampleCount?`n=${Mt.inputFeedbackSampleCount}`:"",`input #${Mt.inputFeedbackSeq||0}`].filter(Boolean).join(" / "),Ve&&`${Ve.frameSeq}${c0(Ve.receivedAt||Ve.capturedAt)}`;const ro=Math.max(0,Xi.bytesPerSecond*8/1e6),Zu={activeTool:Tt,audioError:Uu,audioMode:Ze,audioState:$u,audioStats:An,lastAudioFrame:tf,selectedAudioCaptureStreamId:zu,controlFrames:Sl,controlInputReady:Ks,controlMode:$e,controlPresentationReady:Fd,controlSessionDeviceId:de,controlSessionFrameReady:me,controlSessionState:Ee,controlStreamBinding:pe,devices:G,documentPresentationVisible:Na,focusedDeviceId:Se,frames:Mn,localFeatureAccess:Xt,quickActionBusy:en,selectedDeviceId:De?.deviceId||"",selectedIds:we,showControlFocus:dt,videoCaptureStopUnconfirmedByDeviceId:mt,videoCapturePausedDeviceIds:Ct,wallPresentationReadyDeviceIds:So},Ju=d.useRef(Zu);Ju.current=Zu,d.useEffect(()=>{if(!uu.current)return;const m=window,x=ee=>{if(!ee)return null;const ie=ee.sourceGapMs,se=ie==null||ie===""?null:Number.isFinite(Number(ie))?Number(ie):null,et=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:et.currentGenerationVerified===!0,receivedAt:et.receivedAt||"",capturedAt:et.capturedAt||"",sourceGapMs:se,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),se=ee.getBoundingClientRect(),et=Math.max(0,Math.min(se.right,window.innerWidth)-Math.max(se.left,0)),ze=Math.max(0,Math.min(se.bottom,window.innerHeight)-Math.max(se.top,0)),_e=Number(ie.opacity),xt=ee.isConnected&&ie.display!=="none"&&ie.visibility!=="hidden"&&ie.visibility!=="collapse"&&Number.isFinite(_e)&&_e>0&&se.width>0&&se.height>0&&et>0&&ze>0;return{connected:ee.isConnected,userVisible:xt,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(_e)?_e:0},rect:{left:se.left,top:se.top,right:se.right,bottom:se.bottom,width:se.width,height:se.height,viewportIntersectionWidth:et,viewportIntersectionHeight:ze},codec:up(ee)}},E=(ee,ie)=>{const se=_s.current.get(la(ee,ie));return se?{bindingKey:se.bindingKey||"",totalFrames:se.totalFrames,totalChangedFrames:se.totalChangedFrames,lastFrameSeq:Number(se.lastFrameSeq||0),lastPaintAgeMs:se.lastAt===void 0?-1:Math.max(0,performance.now()-se.lastAt),lastInfo:se.lastInfo?{frameSeq:Number(se.lastInfo.frameSeq||0),decoderInputCount:Number(se.lastInfo.decoderInputCount||0),decoderOutputCount:Number(se.lastInfo.decoderOutputCount||0),targetPaintIntervalMs:Number(se.lastInfo.targetPaintIntervalMs||0),droppedForLatency:Number(se.lastInfo.droppedForLatency||0),visualChanged:se.lastInfo.visualChanged===!0,inputFeedbackExact:se.lastInfo.inputFeedbackExact===!0,inputFeedbackMs:Number(se.lastInfo.inputFeedbackMs||0),inputFeedbackSampleCount:Number(se.lastInfo.inputFeedbackSampleCount||0),inputFeedbackP50Ms:Number(se.lastInfo.inputFeedbackP50Ms||0),inputFeedbackP95Ms:Number(se.lastInfo.inputFeedbackP95Ms||0),inputFeedbackTargetMs:yx,inputFeedbackTargetMinSamples:bx,inputFeedbackOnTarget:se.lastInfo.inputFeedbackExact===!0&&Number(se.lastInfo.inputFeedbackSampleCount||0)>=bx&&Number(se.lastInfo.inputFeedbackP95Ms)<yx}:null}:null},T=(ee,ie)=>{if(!ee)return null;if(ie==="wall-visible"){const et=_s.current.get(la("wall",ee));return et?{bindingKey:et.bindingKey||"",total:et.totalFrames,lastFrameSeq:Number(et.lastFrameSeq||0),lastPaintAgeMs:et.lastAt===void 0?-1:Math.max(0,performance.now()-et.lastAt)}:null}if(ie!=="control-visible"&&ie!=="wall-reuse-visible")return null;const se=du.current.get(`${ie}:${ee}`);return se?{bindingKey:se.bindingKey,total:se.totalPaints,lastFrameSeq:se.lastFrameSeq,lastPaintAgeMs:Math.max(0,performance.now()-se.lastPaintAt)}:null},U=(ee,ie)=>{const se=T(ee,ie);return se?{bindingKey:se.bindingKey,totalPaints:se.total,lastPaintAgeMs:se.lastPaintAgeMs,lastFrameSeq:se.lastFrameSeq}:null},K={readPresentationCounter(ee,ie){return T(String(ee||""),ie)},snapshot(ee,ie={}){const se=String(ee||""),et=ie.includeHistory===!0,ze=Math.max(0,Number(ie.presentationAfterSequence||0)),_e=Ju.current,xt=_e.devices.find(Ns=>Ns.deviceId===se)?.liveCapturePause,yn=String(Ye.current[se]||""),vt=ln.current.get(se)||null,bn=kn.current.get(se)||null,Ln=Xn.current.get(se)||null,br=U1(),As=q1(),Yo={frameStats:mu.current===null?0:1,wallRecovery:ji.current===null?0:1,controlWarm:us.current===null?0:1,controlWallDownshift:Gr.current===null?0:1},Wc=ri.current?.deviceId===se?ri.current:null,ts=pm.current.get(se)||null;return{capturedAt:Date.now(),deviceId:se,activeTool:_e.activeTool,documentPresentationVisible:_e.documentPresentationVisible,showControlFocus:_e.showControlFocus,selectedDeviceId:_e.selectedDeviceId,focusedDeviceId:_e.focusedDeviceId,selectedDeviceIds:[..._e.selectedIds],localFeatureAccess:_e.localFeatureAccess,quickActionBusy:_e.quickActionBusy,audioMode:_e.audioMode,audioState:_e.audioState,audioError:_e.audioError,audioCaptureStreamId:_e.selectedAudioCaptureStreamId,audioFrame:_e.lastAudioFrame?{deviceId:_e.lastAudioFrame.deviceId,streamId:_e.lastAudioFrame.streamId,frameSeq:Number(_e.lastAudioFrame.frameSeq||0),mimeType:_e.lastAudioFrame.mimeType,sampleRate:Number(_e.lastAudioFrame.sampleRate||0),channels:Number(_e.lastAudioFrame.channels||0),byteLength:Number(_e.lastAudioFrame.byteLength||0)}:null,audioStats:{..._e.audioStats},videoCapturePausePhase:yn?yn.startsWith("pending:")?"pending":"confirmed":"none",videoCaptureStopUnconfirmed:_e.videoCaptureStopUnconfirmedByDeviceId[se]===!0,authoritativeLiveCapturePause:xt?{phase:xt.phase||"",captureStopConfirmed:xt.captureStopConfirmed===!0,stopAttemptCount:Math.max(0,Number(xt.stopAttemptCount||0)),stopError:xt.stopError||""}:null,controlMode:_e.controlMode,controlSessionDeviceId:_e.controlSessionDeviceId,controlSessionState:_e.controlSessionState,controlSessionFrameReady:_e.controlSessionFrameReady,controlPresentationReady:_e.controlPresentationReady,controlInputReady:_e.controlInputReady,controlConnection:ts?{...ts}:null,pendingControlConnection:Wc?{...Wc,elapsedMs:Math.max(0,performance.now()-Wc.startedAt)}:null,videoCapturePaused:_e.videoCapturePausedDeviceIds.has(se),wallPresentationReady:_e.wallPresentationReadyDeviceIds.has(se),controlBinding:_e.controlStreamBinding?.deviceId===se?{..._e.controlStreamBinding}:null,actualControlOwner:Nt.current?.deviceId===se?{...Nt.current}:null,wallCapturePauseOwner:cr.current?.deviceId===se?{...cr.current}:null,frameSubscriptions:br,audioSubscriptions:As,presentationTimers:{...Yo,total:Object.values(Yo).reduce((Ns,oo)=>Ns+oo,0)},wallFrame:x(_e.frames.get(se)),controlFrame:x(Ua.current.get(se)||_e.controlFrames.get(se)),wallPaint:E("wall",se),controlPaint:E("control",se),controlVisiblePaint:U(se,"control-visible"),wallReuseVisiblePaint:U(se,"wall-reuse-visible"),presentationPaintSequence:mm.current,presentationPaintEvents:et?Pd.current.filter(Ns=>Ns.deviceId===se&&Ns.sequence>ze).sort((Ns,oo)=>Ns.sequence-oo.sequence).map(Ns=>({...Ns})):[],wallCanvas:C(vt),controlDecodeCanvas:C(bn),controlPresentationCanvas:C(Ln),globalCodec:up(void 0,{includeLifecycleEvents:et})}}};return m.__liveDeskTransmissionProbe=K,()=>{m.__liveDeskTransmissionProbe===K&&delete m.__liveDeskTransmissionProbe}},[]);const Ko=d.useCallback(()=>{rr(!0),Is(Date.now()),V(),Dn.current!==null&&window.clearTimeout(Dn.current),Dn.current=window.setTimeout(()=>{Dn.current=null,Is(Date.now()),rr(!1)},650)},[V]),ed=d.useCallback(()=>{if(En){zr(!1);return}Pn(!1),zr(!0),Ko()},[Ko,En]),Bc=d.useCallback(()=>{if(Ht){Pn(!1);return}zr(!1),Pn(!0),Ko()},[Ht,Ko]),td=d.useCallback(()=>{if(Ba){ar(!1);return}ar(!0),Ko()},[Ba,Ko]),df=En||Ht,nd=JSON.stringify(pt.filter(m=>m.connected).map(m=>m.deviceId).sort());d.useEffect(()=>{if(!df)return;const m=JSON.parse(nd);if(m.length===0){rr(!1);return}const x=new AbortController,C=[];let E=!1;return Dn.current!==null&&(window.clearTimeout(Dn.current),Dn.current=null),rr(!0),Is(Date.now()),Promise.allSettled(m.map(T=>rt(`/api/remote/devices/${encodeURIComponent(T)}/status-diagnostic`,{method:"POST",body:JSON.stringify({purpose:"remote-status-current-snapshot"}),signal:x.signal,timeoutMs:1500},X))).then(()=>{E||[500,1800,4500].forEach((T,U,K)=>{const ee=window.setTimeout(()=>{E||(V(),Is(Date.now()),U===K.length-1&&rr(!1))},T);C.push(ee)})}),()=>{E=!0,x.abort();for(const T of C)window.clearTimeout(T)}},[X,V,nd,df]);const Qo=new Map,Br=new Map;if(En||Ht||Ba)for(const m of pt){const x=m.deviceId,C=dt&&de===x,T=la(C?"control":"wall",x),U=C?Sl.get(x):Mn.get(x),K=C?kn.current.get(x)||Xn.current.get(x)||null:ln.current.get(x)||(Kt?Rr.current:null),ee={device:m,frame:U,receiveStat:fu[T],paintStat:dl[T],codec:K?up(K):{},selectedMonitorIndex:Es(m,rn[x]),control:C,controlInputReady:C&&Ks,controlBinding:C&&pe?.deviceId===x?pe:void 0,hubRelay:$?.relay,capturePaused:Ct.has(x),capturePauseConfirmed:m.liveCapturePause?.captureStopConfirmed===!0,capturePauseError:m.liveCapturePause?.stopError||"",clientHeartbeatMs:Number($?.heartbeatMs||5e3),now:Date.now()},ie=["open","playing","silent"].includes($u),se=An.nativeCallbackDiagnosticsAvailable&&(An.nativeRejectedCallbackCount>0||An.nativeCurrentnessDropCount>0),et=ie&&!se,ze=x===De?.deviceId&&Ze?{id:"browser-remote-audio",state:et?"ok":"warning",label:et?"Remote audio is healthy":"Remote audio needs attention",detail:An.lastUpdatedAt>0?[$u,`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}`:"",tf?`frame #${tf.frameSeq}`:"waiting for frame"].filter(Boolean).join(" · "):"Browser audio diagnostics are collecting while Remote or Debug status is open."}:null;if(En||Ba){const _e=zD(ee);En&&ze&&_e.push(ze),Qo.set(x,_e)}if(Ht){const _e=$D(ee);ze&&_e.push(ze),Br.set(x,_e)}}const ff=Ba?UD({status:$||{},deviceDiagnostics:[...Qo.values()],codec:up(),browser:{hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:Number(navigator.deviceMemory||0)},frameStats:Xi}):[],Em=xl?.atlasReadyTiles??Qu,ad=xl?.atlasTileCount??Qu,yi=Em===ad?`${ad} tiles`:`${Em}/${ad} tiles`,mf=Za.length>0;dt?`${Yu}${ro.toFixed(ro>=10?0:1)}`:mf?`${yi}${Yu}${ro.toFixed(ro>=10?0:1)}`:`${Qu}${Yu}${ro.toFixed(ro>=10?0:1)}`;const rd=In.length,Hc=dt?De?La(De):"No Client":rd===0?"No Client":rd>1?`${rd} selected`:De?La(De):"No Client",zc=dt?[De?.deviceId].filter(m=>!!m):In.map(m=>m.deviceId),qt=Td[on]||Td.en,sd=qt.sync||Td.en.sync,Sh=r||z?"checking":J?Ut==="pro"?"Pro LTD active":`Plus LTD ${pt.length}/${Wf}`:gl?`Free ${pt.length}/${qf}`:`Upgrade ${pt.length}/${qf}`,$c=J?Ut==="pro"?"Pro active":"Upgrade to Pro LTD":n?kt==="checkout"?"Opening checkout":Ut==="ltd"?"Buy Pro LTD":"Buy Plus LTD":kt==="auth"?"Opening Google":"Sign in to buy",so=Ut==="pro"||kt==="checkout"||kt==="auth"||r||z,pf=n?.user?.user_metadata,Uc=Ox(pf,"avatar_url","picture"),bi=Ox(pf,"full_name","name")||n?.user?.email||"Google",ks=bi.slice(0,1).toUpperCase(),Dm=$?.started?"Local app ready":"Start LiveDesk",hf=o?.active?"Published":n?"Not published":"Sign in required",Im=/^\d{6}$/.test($?.pairingPin||"")?$?.pairingPin:"------",wi=m=>{if(typeof window<"u"&&(m==="support"?window.history.pushState({},"","/support"):Tt==="support"&&window.history.pushState({},"","/")),m==="control"){const x=xa||Wi;if(x&&(Pc(x.deviceId),Wa(!1),Pe(x.deviceId)),bt(m),!Xt){We(!1),Be(vl);return}We(!0);return}m==="wall"&&Ps(x=>x+1),bt(m),We(!1)},es=kt==="update"||Bt?.stage==="updating"||["dispatching","waiting-for-clients","hub-restart-requested"].includes($?.update?.state||""),qc=!!($?.update?.updateAvailable&&$.update.canApply||es||Bt?.error||!$&&Bt),io=WM(on),Ms=d.useCallback(m=>{if(!Bt?.targetIds.includes(m))return;const x=$?.update?.operationId===Bt.operationId?$.update.targets?.find(C=>C.deviceId===m):void 0;switch(x?.state){case"completed":return bo[Cx(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}},[$?.update,bo,Bt]),ta=r?"checking":$?.started?"online":"offline",gf=r?"Checking Hub":$?.started?`${pt.length} online`:n?"Hub offline":"Sign in required",vf=b&&g&&!n;return i.jsxs("main",{className:`app-shell ${b?"mobile-console-shell":""}`,"data-mobile-auth-required":vf?"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(u0,{size:25})}),i.jsx("nav",{className:"rail-tools",children:pL.map(m=>{const x=m.icon,C=qp(m.tooltip,on);return i.jsxs("button",{className:`rail-tool ${m.id==="sync-server"?"sync-server hub-sync-trigger":""} ${Tt===m.id?"active":""} accent-${m.accent}`,onClick:()=>m.id==="sync-server"?Sm():wi(m.id),"data-tooltip":m.id==="sync-server"&&nt?void 0:Zg(m.label,m.tooltip,on),"aria-label":`${m.label}. ${C}`,type:"button",disabled:m.id==="sync-server"&&kt==="host","aria-busy":m.id==="sync-server"&&kt==="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"&&kt==="host"?i.jsx("span",{className:"sync-server-spinner","aria-hidden":"true"}):i.jsx(x,{size:19}),i.jsx("span",{children:m.id==="sync-server"&&kt==="host"?"Syncing…":m.label})]},m.id)})}),i.jsxs("div",{className:"rail-footer",children:[hL.map(m=>{const x=m.icon;return i.jsxs("button",{className:`rail-tool compact ${Tt===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 ${ps?"active":""}`,onClick:()=>{bt("settings"),typeof window<"u"&&window.history.pushState({},"","/"),sr(!1),We(!1),vo(!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:()=>{sr(m=>!m)},disabled:r||kt==="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:ks}):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:ks}):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:Dm}),i.jsx("dt",{children:"Access"}),i.jsx("dd",{children:hf}),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:kt==="auth",type:"button",children:[i.jsx(Ux,{size:16}),"Logout"]}):i.jsxs("button",{className:"account-popover-action primary",onClick:qo,disabled:kt==="auth",type:"button",children:[i.jsx(Ql,{size:16}),"Sign in with Google"]})]})]})]}),b&&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-${ta}`,role:"status","aria-live":"polite",children:[i.jsx("i",{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:gf}),i.jsx("small",{children:$?.deviceName||(W?"Desktop Hub unavailable":"Remote management")})]})]}),i.jsxs("span",{className:"mobile-console-header-actions",children:[g&&!R&&(k||A.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:es||!$?.update?.canApply,"aria-label":es?"LiveDesk update in progress":"Update LiveDesk","aria-busy":es,type:"button",children:es?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:18,"aria-hidden":"true"})})]})]}),b&&D&&i.jsx("div",{className:"mobile-pwa-guide-backdrop",role:"presentation",onClick:()=>I(!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(Jx,{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:()=>I(!1),"aria-label":"Close install guide",children:i.jsx(nr,{size:18,"aria-hidden":"true"})})]}),i.jsxs("ol",{children:[i.jsxs("li",{children:["Tap ",A.browserName==="browser"?"the browser":A.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:A.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:()=>I(!1),children:"Got it"})]})}),vf&&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(ha,{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:()=>{qo()},disabled:r||kt==="auth","aria-busy":r||kt==="auth",children:[r||kt==="auth"?i.jsx(is,{className:"spin",size:19,"aria-hidden":"true"}):i.jsx(Ql,{size:19,"aria-hidden":"true"}),kt==="auth"?"Opening Google…":r?"Checking sign-in…":"Sign in with Google"]}),i.jsx("small",{children:"After sign-in, LiveDesk returns to this installed app."})]}),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(po,{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(nr,{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(ha,{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:gn,className:"primary",type:"button",onClick:Cm,disabled:kt==="host",children:[i.jsx(po,{size:16}),io.confirm]})]})]}),i.jsxs("section",{className:`desk-stage ${hs&&!Ls?"dock-open":""} ${dt?"control-stage":""} ${Va?"agents-stage":""} ${Hi?"file-share-stage":""}`,children:[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 ${$?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,"aria-label":Bt?.error?`LiveDesk Hub update failed: ${Bt.error}`:es?"LiveDesk update in progress":`Update LiveDesk to ${$?.update?.latestVersion||Bt?.targetManagerVersion||"latest"}`,type:"button",disabled:es||!$?.update?.canApply,"aria-busy":es,children:[es?i.jsx("span",{className:"topbar-update-spinner","aria-hidden":"true"}):i.jsx(Bp,{size:19,"aria-hidden":"true"}),es&&$?.update?.targetCount?i.jsxs("span",{className:"topbar-update-count","aria-hidden":"true",children:[$.update.completedCount||0,"/",$.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(Dk,{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:$r.trim()||"Desktop/LiveDeskFiles"})]})]})]}),hs&&!dt&&i.jsxs("div",{className:"top-actions",children:[i.jsx(fx,{active:Ba,refreshing:Ba&&Nr,onClick:td}),i.jsx(ux,{active:En,refreshing:En&&Nr,onClick:ed}),i.jsx(dx,{active:Ht,refreshing:Ht&&Nr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(cx,{controller:Sc,onError:Be}),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:fL.map(m=>i.jsx("button",{className:Cn===m.id?"active":"",onClick:()=>{Un(m.id),or(m.fps),aL(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:mL.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(fx,{active:Ba,refreshing:Ba&&Nr,onClick:td}),i.jsx(ux,{active:En,refreshing:En&&Nr,onClick:ed}),i.jsx(dx,{active:Ht,refreshing:Ht&&Nr,onClick:Bc}),i.jsx("span",{className:"top-actions-divider","aria-hidden":"true"}),i.jsx(cx,{controller:Sc,onError:Be})]})]})]}),Ba&&hs&&i.jsx(ED,{items:ff,collectedAt:Zs,onClose:()=>ar(!1)}),$d?i.jsxs("section",{className:"doc-page",lang:on,dir:on==="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(Ik,{size:17}),qt.languageLabel]}),i.jsx("select",{value:on,onChange:m=>il(m.target.value),children:vL.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 E=[po,jp,Sb,ha,eh][x]||Hp;return i.jsxs("article",{className:"doc-card",children:[i.jsx("div",{className:"doc-card-icon",children:i.jsx(E,{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(T=>i.jsx("li",{children:T},T))})]})]},m.title)})}),sd&&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:sd.title}),i.jsx("p",{children:sd.body})]})]}),i.jsx("ul",{children:sd.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(ha,{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:cf}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(cf),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:ea}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(ea),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:`${ea} 3`}),i.jsx("button",{className:"icon-button",onClick:()=>Dp(`${ea} 3`),title:"Copy command",type:"button",children:i.jsx(sg,{size:16})})]})]})]})]}):Va?i.jsx(ix,{hubUrl:X,devices:G}):Hi?i.jsx(EE,{hubUrl:X,devices:pt,localFeatureAccess:Xt,upgradeNotice:vl,remoteDirectory:$r,onRemoteDirectoryChange:ol,targetMode:To,selectedTargetIds:ja,onTargetModeChange:zd,onTargetToggle:m=>hl(x=>x.includes(m)?x.filter(C=>C!==m):[...x,m]),filePickerRef:Ro,folderPickerRef:ym,onBrowserFileImport:m=>{Tm(m)},onBrowserFolderImport:m=>{Tm(m)},onNotice:Be,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)}}):Mu?i.jsx(a0,{session:n,currentProductKey:"livedesk",appVersion:"",onSignIn:qo}):ps?i.jsx(KN,{hubUrl:X,runtimeRole:$?.runtimeRole||"hub",runtimeDeviceId:$?.deviceId||"",sessionAccessToken:n?.access_token||"",pin:i.jsxs(QN,{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(kr,{size:20})]}),i.jsxs("div",{className:"settings-pin-display",children:[i.jsx("span",{children:"Hub PIN"}),i.jsx("strong",{children:Im}),i.jsxs("button",{className:"text-button ghost compact",onClick:km,disabled:!$?.started||kt==="pin",type:"button",children:[i.jsx(nl,{size:15}),kt==="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(kd,{size:20})]}),i.jsxs("label",{className:"settings-field",children:[i.jsx("span",{children:"Remote folder"}),i.jsx("input",{value:$r,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(XN,{hubUrl:X,showToast:Be}),captureGallery:i.jsx(jD,{hubUrl:X,onToast:Be})}):ku?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(nr,{size:18})})]}),i.jsxs("div",{className:"pricing-status","aria-live":"polite",children:[i.jsx("span",{children:"Current plan"}),i.jsx("strong",{children:Ru.name}),i.jsxs("small",{children:[pt.length,"/",jI(Lo)," 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(Pa,{size:16})," Up to ",qf," devices"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," Live view and local control"]}),i.jsxs("li",{children:[i.jsx(Pa,{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(Lk,{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(Pa,{size:16})," Up to ",Wf," devices"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," No standard ad banner"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," ",Xc.ltd.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>zn("ltd"):qo,disabled:Ut!=="free"||kt==="checkout"||kt==="auth"||r||z,type:"button",children:[i.jsx(Qf,{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(ha,{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(Pa,{size:16})," 30+ Client walls"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," Commercial use included"]}),i.jsxs("li",{children:[i.jsx(Pa,{size:16})," ",Xc.pro.ltd]})]}),i.jsxs("button",{className:"pricing-plan-button",onClick:n?()=>zn("pro"):qo,disabled:Ut==="pro"||kt==="checkout"||kt==="auth"||r||z,type:"button",children:[i.jsx(Qf,{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(kr,{size:17}),i.jsx("span",{children:"Screen wall"}),i.jsx("strong",{children:"120+ slots"})]}),i.jsxs("div",{children:[i.jsx($f,{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(kd,{size:17}),i.jsx("span",{children:"File transfer"}),i.jsx("strong",{children:"Included"})]})]}),i.jsxs("p",{className:"pricing-note",children:[i.jsx(Pa,{size:15})," Commercial use requires Pro. Plus LTD is for personal, creator, and homelab use."]}),i.jsxs("button",{className:"pricing-primary-cta",onClick:n?()=>zn(Ut==="ltd"?"pro":"ltd"):qo,disabled:so,type:"button",children:[i.jsx(Qf,{size:18}),$c]})]}):i.jsx(i.Fragment,{children:i.jsxs("section",{className:`monitor-layout ${Ls?"dock-collapsed":""}`,children:[i.jsxs("section",{ref:hc,className:`screen-wall-panel ${yh?"drop-active":""}`,onClick:m=>{m.currentTarget===m.target&&Wo()},onDragEnter:m=>{m.preventDefault(),Hd(!0)},onDragOver:m=>{m.preventDefault(),m.dataTransfer.dropEffect="copy"},onDragLeave:m=>{m.currentTarget===m.target&&Hd(!1)},onDrop:lf,children:[Za.length>0&&i.jsx("canvas",{ref:Wd,className:"atlas-source-canvas",width:vn?.width||1920,height:vn?.height||1080,"aria-hidden":"true"}),b&&hs&&!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"} · ${mo(De)} display${mo(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:!ys||!!en,type:"button",children:[i.jsx($f,{size:17}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Ze?"active":"",onClick:()=>{rf()},disabled:!ju||!!en,"aria-pressed":Ze,type:"button",children:[en==="audio"?i.jsx(is,{className:"spin",size:17}):i.jsx(ig,{size:17}),i.jsx("span",{children:"Audio"})]}),i.jsxs("button",{className:mr?"":"active",onClick:()=>{Oc()},disabled:Da.length===0||!!en,"aria-pressed":!mr,type:"button",children:[en==="video"?i.jsx(is,{className:"spin",size:17}):mr?i.jsx(Cb,{size:17}):i.jsx(kb,{size:17}),i.jsx("span",{children:mr?"Pause":"Resume"})]}),i.jsxs("button",{onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Io,type:"button",children:[en==="restart"?i.jsx(is,{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 ${La(De)}`,children:[i.jsx("strong",{className:"control-computer-name",title:La(De),children:La(De)}),Rm.map(m=>i.jsxs("button",{className:m.index===ao?"active":"",onClick:()=>Mm(De.deviceId,m.index),title:KI(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&&Ks&&i.jsx("div",{className:"control-modifier-bar","aria-label":"Hold remote modifier keys",children:fI.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:Ve,selected:!1,controlEnabled:ys&&$e&&Ks,showStatus:_n.showScreenStatus,showDeviceTitle:!1,monitorIndex:Es(De,rn[De.deviceId]),monitorCount:mo(De),onSelect:()=>{},onFocusDevice:()=>Pe(De.deviceId),onOpenControl:()=>no(De.deviceId),onCycleMonitor:m=>Ku(De.deviceId,m),onCanvasReady:Eu,sendInput:Uo,remoteModifierState:Bu,presentationReady:Fd,remoteDiagnostics:Ht?Br.get(De.deviceId):En?Qo.get(De.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},De.deviceId):i.jsxs("div",{className:"control-empty",children:[i.jsx(kr,{size:30}),i.jsx("strong",{children:"No Client"}),i.jsx("span",{children:"Open a Client from the Wall."})]}),De&&Tu&&i.jsxs("div",{className:"control-connection-overlay",role:"alert",children:[i.jsx(ha,{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&&!Tu&&!Fd&&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.":zo||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(wL,{device:m,slotNumber:x,selected:dr.has(m.deviceId),updateIndicator:Ms(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote",onSelect:()=>Gu(m.deviceId),onOpenControl:()=>no(m.deviceId)},m.deviceId)):i.jsxs("div",{className:"wall-device-list-empty",children:[i.jsx(kr,{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&&Wo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:dr.has(m.deviceId),controlEnabled:!1,showStatus:wt.showScreenStatus,monitorIndex:Es(m,rn[m.deviceId]),monitorCount:mo(m),onSelect:()=>Gu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Ku(m.deviceId,C),onCanvasReady:_f({mode4Enabled:Kt,directMode4WallEnabled:Ia,isMac:tl(m.platform)})==="direct"?Oo:Ki,sendInput:Uo,remoteModifierState:Bu,updateIndicator:Ms(m.deviceId),presentationReady:wt.autoStartLive&&Xa.includes(m.deviceId)?So.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Xa.includes(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(Hx,{index:x},`slot-${x}`))}):i.jsx("div",{className:`screen-wall size-${Gt}`,onClick:m=>{m.currentTarget===m.target&&Wo()},children:mi.map((m,x)=>m?i.jsx(Wg,{device:m,frame:Mn.get(m.deviceId),selected:dr.has(m.deviceId),controlEnabled:ys&&$e&&Ks&&De?.deviceId===m.deviceId,showStatus:wt.showScreenStatus,monitorIndex:Es(m,rn[m.deviceId]),monitorCount:mo(m),onSelect:()=>Gu(m.deviceId),onFocusDevice:()=>Fc(m.deviceId),onOpenControl:()=>no(m.deviceId),onCycleMonitor:C=>Ku(m.deviceId,C),onCanvasReady:Oo,sendInput:Uo,remoteModifierState:Bu,updateIndicator:Ms(m.deviceId),presentationReady:wt.autoStartLive&&Xa.includes(m.deviceId)?So.has(m.deviceId):void 0,showPresentationSpinner:wt.autoStartLive&&Xa.includes(m.deviceId),remoteDiagnostics:Ht?Br.get(m.deviceId):En?Qo.get(m.deviceId):void 0,diagnosticsMode:Ht?"debug":"remote"},m.deviceId):i.jsx(Hx,{index:x},`slot-${x}`))}),i.jsx(CL,{visible:bm&&!dt})]}),!ps&&i.jsxs("aside",{className:`right-dock actions-mode ${Ls?"collapsed":""}`,"aria-label":"LiveDesk tools",children:[i.jsx("button",{className:"dock-toggle",onClick:()=>vo(m=>!m),"aria-label":Ls?"Show control panel":"Hide control panel",title:Ls?"Show control panel":"Hide control panel",type:"button",children:Ls?i.jsx(t0,{size:18}):i.jsx(Mv,{size:18})}),!Ls&&i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"action-dock",children:[i.jsx("input",{ref:xu,className:"hidden-file-input",type:"file",multiple:!0,onChange:m=>{m.currentTarget.files&&of(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?Tu?"Allow Accessibility for the terminal app that starts LiveDesk, then restart the Mac client.":ys?Ks?"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&&$e){We(!1),Be("Remote control paused. Screen viewing stays on.");return}no(De.deviceId)}},disabled:!ys||!!en,active:$e,pressed:dt&&$e,children:i.jsx($f,{size:17})}),i.jsx(Yc,{label:"Audio",tooltip:De?vs?Ze?"Stop hearing this Client":"Hear this Client":"Audio is not available on this Client":"Select a Client to use Audio",onClick:()=>{rf()},disabled:!ju||!!en,active:Ze,pressed:Ze,children:en==="audio"?i.jsx(is,{className:"spin",size:17}):i.jsx(ig,{size:17})}),i.jsx(Yc,{label:Po?"Retry pause":mr?"Pause video":"Resume video",tooltip:bs.length===0?"Select one or more Clients to pause video":Po?"Retry every selected Client whose capture shutdown is unconfirmed":mr?`Pause video for ${Da.length} selected Client${Da.length===1?"":"s"}`:`Resume video for ${Da.length} selected Client${Da.length===1?"":"s"}`,onClick:()=>{Oc()},disabled:Da.length===0||!!en,active:!mr,pressed:!mr,children:en==="video"?i.jsx(is,{className:"spin",size:17}):!mr&&!Po?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:()=>{Be(`Choose files to send to ${Hc}.`),xu.current?.click()},disabled:!!en||!Xt||(dt?!De:In.length===0),children:i.jsx(kd,{size:17})}),i.jsx(Yc,{label:"Restart",tooltip:De?Io?"Restart Client":"Restart is not available on this Client":"Select a Client to restart",onClick:()=>{Dl("restart")},disabled:!De||!Xt||!!en||!Io,children:en==="restart"?i.jsx(is,{className:"spin",size:17}):i.jsx(Vg,{size:17})}),i.jsx(Yc,{label:"Sleep",tooltip:De?Io?"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||!Io,children:en==="sleep"?i.jsx(is,{className:"spin",size:17}):i.jsx(Pk,{size:17})}),i.jsx(Yc,{label:"Shut down",tooltip:De?Io?"Shut down Client":"Shut down is not available on this Client":"Select a Client to shut down",onClick:()=>{Dl("shutdown")},disabled:!De||!Xt||!!en||!Io,danger:!0,children:en==="shutdown"?i.jsx(is,{className:"spin",size:17}):i.jsx(Gx,{size:17})})]})]}),i.jsx(ix,{hubUrl:X,devices:G,variant:"dock",selectedDeviceIds:zc})]})]})]})})]}),b&&i.jsxs("nav",{className:"mobile-console-nav","aria-label":"Mobile Console pages",children:[i.jsxs("button",{className:Tt==="wall"?"active":"",onClick:()=>wi("wall"),type:"button",children:[i.jsx(e0,{size:19}),i.jsx("span",{children:"Wall"})]}),i.jsxs("button",{className:dt?"active":"",onClick:()=>De&&void no(De.deviceId),disabled:!De||!ys,type:"button",children:[i.jsx($f,{size:19}),i.jsx("span",{children:"Control"})]}),i.jsxs("button",{className:Hi?"active":"",onClick:()=>wi("share-files"),type:"button",children:[i.jsx(Yf,{size:19}),i.jsx("span",{children:"Files"})]}),i.jsxs("button",{className:Va?"active":"",onClick:()=>wi("agents"),type:"button",children:[i.jsx(jp,{size:19}),i.jsx("span",{children:"Agents"})]}),i.jsxs("button",{className:ps?"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(Pa,{size:18}):Oi.status==="failed"?i.jsx(nr,{size:18}):i.jsx(Kx,{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:()=>Be(""),type:"button","aria-label":"Dismiss notification",title:"Dismiss notification",children:i.jsx(nr,{size:15})})]})]})}const ML=1e3,AL=5e3;function NL(){return typeof window>"u"?[]:[...new Set([window.location.origin,$n].filter(Boolean))]}function TL(){const r=Av(),[o,l]=d.useState(null),u=d.useRef(null);return d.useEffect(()=>{if(r){l({role:"hub",baseUrl:$n});return}let f=!1,h=!1,g=null;const y=new AbortController,w=async()=>{for(const k of NL()){if(y.signal.aborted)return;try{const A=(await rt("/api/runtime/status",{signal:y.signal,timeoutMs:900},k)).role==="hub"?"hub":"client";h=!0,f||l(D=>D?.role===A&&D.baseUrl===k?D:{role:A,baseUrl:k});return}catch{if(y.signal.aborted)return}}},b=()=>{Up(u,w).finally(()=>{!f&&!y.signal.aborted&&(g=window.setTimeout(b,h?AL:ML))}).catch(()=>{})};b();const S=window.setTimeout(()=>{!f&&!h&&l(k=>k?.role==="client"&&k.baseUrl===$n?k:{role:"client",baseUrl:$n})},2500);return()=>{f=!0,y.abort(new Error("LiveDesk runtime role probe stopped.")),g!==null&&window.clearTimeout(g),window.clearTimeout(S)}},[null,r]),o?o.role==="client"?i.jsx(rA,{runtimeBaseUrl:o.baseUrl}):i.jsx(kL,{runtimeBaseUrl:o.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..."})]})}Uk.createRoot(document.getElementById("root")).render(i.jsx(d.StrictMode,{children:i.jsx(TL,{})}));"serviceWorker"in navigator&&window.isSecureContext&&window.location.protocol==="https:"&&window.addEventListener("load",()=>{navigator.serviceWorker.register("/sw.js",{updateViaCache:"none"}).catch(t=>{console.warn("[LiveDesk] PWA service worker registration failed.",t)})},{once:!0});