Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

16.1 KB
Raw Blame
// Generated by scripts/sync-remote-desktop-viewer.mjs. Do not edit.
export const DESKTOP_RTC_SCRIPT = "let trickleIce = false,\n    attemptId = null,\n    retries = 0,\n    exchangeId = 0;\n  let configPending = false;\n  let videoPresented = false,\n    videoFrameCallback = null,\n    videoPaintCallback = null;\n  function cancelVideoHandoff() {\n    if (videoFrameCallback !== null)\n      video.cancelVideoFrameCallback?.(videoFrameCallback);\n    if (videoPaintCallback !== null) cancelAnimationFrame(videoPaintCallback);\n    videoFrameCallback = videoPaintCallback = null;\n  }\n  function revealVideo(g) {\n    post({ type: \"videoFrameReady\", attemptId });\n    // Keep the JPEG decoded and painted as a backing layer. Promote the video\n    // only after its first frame; removing the image exposes WebKit repaint gaps.\n    videoPaintCallback = requestAnimationFrame(() => {\n      if (g !== generation) return;\n      videoPaintCallback = requestAnimationFrame(() => {\n        if (g !== generation) return;\n        videoPaintCallback = null;\n        videoPresented = true;\n        video.style.zIndex = \"2\";\n        if (typeof startBackgroundLoop === \"function\") startBackgroundLoop();\n        post({ type: \"streaming\", attemptId });\n        post({\n          type: \"pipCapability\",\n          supported: !!(\n            video.webkitSupportsPresentationMode?.(\"picture-in-picture\") ||\n            document.pictureInPictureEnabled\n          ),\n        });\n      });\n    });\n  }\n  function waitForVideoFrame(g) {\n    if (g !== generation) return;\n    if (\n      video.readyState >= 2 &&\n      video.videoWidth > 0 &&\n      video.videoHeight > 0\n    ) {\n      revealVideo(g);\n      return;\n    }\n    videoPaintCallback = requestAnimationFrame(() => waitForVideoFrame(g));\n  }\n  let retryTimer = null,\n    deadlineTimer = null,\n    disconnectTimer = null,\n    stableTimer = null,\n    iceTimer = null,\n    gatherTimer = null,\n    gatherDone = null;\n  let localCandidates = [],\n    localAck = 0,\n    remoteAfter = 0,\n    icePending = null,\n    remoteSeen = new Set(),\n    exchangeUntil = 0,\n    remoteComplete = false;\n  function clearRtcTimers() {\n    for (const timer of [\n      retryTimer,\n      deadlineTimer,\n      disconnectTimer,\n      stableTimer,\n      iceTimer,\n      gatherTimer,\n    ])\n      clearTimeout(timer);\n    retryTimer =\n      deadlineTimer =\n      disconnectTimer =\n      stableTimer =\n      iceTimer =\n      gatherTimer =\n        null;\n    if (gatherDone) {\n      gatherDone();\n      gatherDone = null;\n    }\n  }\n  function closeRtc(preserveFrame = true) {\n    configPending = false;\n    if (preserveFrame) retainFrame();\n    generation++;\n    clearRtcTimers();\n    cancelVideoHandoff();\n    videoPresented = false;\n    localCandidates = [];\n    localAck = remoteAfter = 0;\n    icePending = null;\n    remoteSeen = new Set();\n    attemptId = null;\n    clearInterval(statsTimer);\n    statsTimer = null;\n    statsSample = null;\n    if (dc) dc.close();\n    if (pc) pc.close();\n    pc = null;\n    dc = null;\n    video.onplaying = null;\n    video.srcObject = null;\n    video.style.display = \"none\";\n    video.style.zIndex = \"0\";\n    image.style.display = \"block\";\n    if (typeof stopBackgroundLoop === \"function\") stopBackgroundLoop();\n    if (!preserveFrame) {\n      image.removeAttribute(\"src\");\n      if (typeof clearBackground === \"function\") clearBackground();\n    }\n  }\n  function failRtc(reason, canRetry = true) {\n    const failedAttempt = attemptId;\n    release();\n    closeRtc();\n    post({ type: \"fallback\", attemptId: failedAttempt, reason });\n    // Local consent is bounded by the host's picker lifetime. Reuse this retry\n    // timer without consuming the finite network-recovery attempts.\n    const capturePending = reason === \"capture-pending\";\n    if (canRetry && epoch && (capturePending || retries < net.retryMs.length)) {\n      const delay = capturePending\n        ? net.retryMs[net.retryMs.length - 1]\n        : net.retryMs[retries++];\n      retryTimer = setTimeout(() => {\n        retryTimer = null;\n        if (epoch) connect();\n      }, delay);\n    }\n  }\n  function pollIce() {\n    if (\n      !pc ||\n      !trickleIce ||\n      !pc.remoteDescription ||\n      icePending ||\n      Date.now() >= exchangeUntil\n    )\n      return;\n    const candidates = localCandidates.slice(\n      localAck,\n      localAck + net.batchSize,\n    );\n    icePending = {\n      after: remoteAfter,\n      sent: candidates.length,\n      exchangeId: ++exchangeId,\n    };\n    post({\n      type: \"ice\",\n      attemptId,\n      candidates,\n      after: remoteAfter,\n      exchangeId,\n    });\n    iceTimer = setTimeout(() => {\n      icePending = null;\n      pollIce();\n    }, 4500);\n  }\n  async function receiveIce(message) {\n    if (\n      !pc ||\n      !icePending ||\n      message.attemptId !== attemptId ||\n      message.exchangeId !== icePending.exchangeId\n    )\n      return;\n    const rtc = pc,\n      g = generation,\n      batch = icePending;\n    clearTimeout(iceTimer);\n    try {\n      if (message.error) {\n        icePending = null;\n        iceTimer = setTimeout(pollIce, 1000);\n        return;\n      }\n      if (\n        !Array.isArray(message.candidates) ||\n        message.candidates.length > net.batchSize ||\n        message.next !== batch.after + message.candidates.length ||\n        message.next > net.maxCandidates\n      )\n        throw new Error();\n      for (const candidate of message.candidates) {\n        if (g !== generation) return;\n        const key = JSON.stringify(candidate);\n        if (remoteSeen.has(key)) continue;\n        if (remoteSeen.size >= net.maxCandidates) throw new Error();\n        await rtc.addIceCandidate(candidate);\n        if (g !== generation) return;\n        remoteSeen.add(key);\n      }\n      if (g !== generation) return;\n      localAck += batch.sent;\n      remoteAfter = message.next;\n      remoteComplete = message.complete === true;\n      icePending = null;\n      if (!(\n        remoteComplete &&\n        rtc.iceGatheringState === \"complete\" &&\n        localAck === localCandidates.length\n      ))\n        iceTimer = setTimeout(pollIce, net.pollMs);\n    } catch {\n      if (g === generation) failRtc(\"candidates\");\n    }\n  }\n  async function receiveAnswer(message) {\n    if (!pc || message.attemptId !== attemptId) return;\n    const rtc = pc,\n      g = generation;\n    try {\n      await rtc.setRemoteDescription({ type: \"answer\", sdp: message.sdp });\n      if (g !== generation) return;\n      clearTimeout(deadlineTimer);\n      deadlineTimer = setTimeout(() => {\n        if (g === generation && rtc.connectionState !== \"connected\")\n          failRtc(\"connect-timeout\");\n      }, net.connectMs);\n      exchangeUntil = Date.now() + net.exchangeMs;\n      pollIce();\n    } catch {\n      if (g === generation) failRtc(\"answer\");\n    }\n  }\n  async function connect() {\n    closeRtc();\n    const g = generation;\n    attemptId = String(g);\n    if (!window.RTCPeerConnection) {\n      failRtc(\"unsupported\", false);\n      return;\n    }\n    configPending = true;\n    deadlineTimer = setTimeout(\n      () => {\n        if (g === generation && configPending) {\n          configPending = false;\n          void startRtc(g, iceServers);\n        }\n      },\n      (net.iceConfigMs ?? 8000) + (net.iceConfigBridgeMs ?? 500),\n    );\n    return post({ type: \"iceConfig\", attemptId });\n  }\n  async function receiveIceConfig(message) {\n    if (!epoch || !configPending || message.attemptId !== attemptId) return;\n    configPending = false;\n    clearTimeout(deadlineTimer);\n    deadlineTimer = null;\n    await startRtc(generation, message.iceServers);\n  }\n  async function startRtc(g, servers) {\n    try {\n      const rtc = new RTCPeerConnection({ iceServers: servers });\n      pc = rtc;\n      dc = rtc.createDataChannel(\"input-v1\");\n      rtc.addTransceiver(\"video\", { direction: \"recvonly\" });\n      rtc.addTransceiver(\"audio\", { direction: \"recvonly\" });\n      rtc.onicecandidate = ({ candidate }) => {\n        if (g !== generation || !candidate?.candidate || !trickleIce) return;\n        if (localCandidates.length >= net.maxCandidates) {\n          failRtc(\"candidate-limit\", false);\n          return;\n        }\n        localCandidates.push({\n          candidate: candidate.candidate,\n          sdpMid: candidate.sdpMid,\n          sdpMLineIndex: candidate.sdpMLineIndex,\n          ...(candidate.usernameFragment\n            ? { usernameFragment: candidate.usernameFragment }\n            : {}),\n        });\n        // Gathering continues after the offer; the serial exchange flushes late addresses.\n      };\n      dc.onmessage = (e) => {\n        try {\n          if (g !== generation || pc !== rtc) return;\n          if (typeof e.data !== \"string\" || e.data.length > 80000) return;\n          const message = JSON.parse(e.data);\n          if (message.type === \"cursor\") receiveCursor(message.cursor);\n          if (\n            message.type === \"reply\" &&\n            typeof message.id === \"string\" &&\n            message.id.length <= 64\n          )\n            post({\n              type: \"channelReply\",\n              id: message.id,\n              ok: message.ok === true,\n              result: message.result,\n              error: typeof message.error === \"string\" ? message.error : null,\n            });\n          if (\n            (video.webkitPresentationMode === \"picture-in-picture\" ||\n              document.pictureInPictureElement === video) &&\n            message.type === \"viewPing\" &&\n            typeof message.challenge === \"string\" &&\n            message.challenge.length <= 64 &&\n            dc?.readyState === \"open\"\n          )\n            dc.send(message.challenge);\n        } catch {}\n      };\n      let readingStats = false;\n      statsTimer = setInterval(async () => {\n        if (readingStats || g !== generation) return;\n        readingStats = true;\n        try {\n          const stats = await rtc.getStats();\n          if (g !== generation || pc !== rtc) return;\n          const result = networkStats(stats, statsSample);\n          statsSample = result.sample;\n          post({\n            type: \"network\",\n            transport: result.transport,\n            bytesPerSecond: result.bytesPerSecond,\n            latencyMs: result.latencyMs,\n          });\n        } catch {\n        } finally {\n          readingStats = false;\n        }\n      }, 1000);\n      rtc.ontrack = (e) => {\n        if (g !== generation) return;\n        video.srcObject = e.streams[0] || new MediaStream([e.track]);\n        video.play().catch(() => {});\n      };\n      video.onplaying = () => {\n        if (\n          g !== generation ||\n          videoPresented ||\n          videoFrameCallback !== null ||\n          videoPaintCallback !== null\n        )\n          return;\n        video.style.display = \"block\";\n        render();\n        if (typeof scheduleBackgroundDraw === \"function\")\n          scheduleBackgroundDraw();\n        if (typeof video.requestVideoFrameCallback === \"function\") {\n          videoFrameCallback = video.requestVideoFrameCallback(() => {\n            if (g !== generation) return;\n            videoFrameCallback = null;\n            revealVideo(g);\n          });\n        } else waitForVideoFrame(g);\n      };\n      rtc.onconnectionstatechange = () => {\n        if (g !== generation) return;\n        if ([\"failed\", \"closed\"].includes(rtc.connectionState)) {\n          failRtc(\"transport\");\n          return;\n        }\n        if (rtc.connectionState === \"disconnected\") {\n          clearTimeout(stableTimer);\n          stableTimer = null;\n          if (!disconnectTimer) {\n            release();\n            post({ type: \"reconnecting\", attemptId });\n            disconnectTimer = setTimeout(() => {\n              if (g === generation) failRtc(\"disconnected\");\n            }, net.disconnectedMs);\n          }\n        } else if (rtc.connectionState === \"connected\") {\n          clearTimeout(disconnectTimer);\n          disconnectTimer = null;\n          clearTimeout(deadlineTimer);\n          if (!stableTimer)\n            stableTimer = setTimeout(() => {\n              if (g === generation) retries = 0;\n            }, net.stableMs);\n          if (videoPresented) post({ type: \"streaming\", attemptId });\n        }\n      };\n      await rtc.setLocalDescription(await rtc.createOffer());\n      if (!trickleIce)\n        await new Promise((resolve) => {\n          if (rtc.iceGatheringState === \"complete\") return resolve();\n          gatherDone = resolve;\n          gatherTimer = setTimeout(resolve, net.legacyGatherMs);\n          rtc.onicegatheringstatechange = () => {\n            if (rtc.iceGatheringState === \"complete\") {\n              clearTimeout(gatherTimer);\n              resolve();\n            }\n          };\n        });\n      if (g !== generation) return;\n      post({ type: \"offer\", attemptId, sdp: rtc.localDescription.sdp });\n      deadlineTimer = setTimeout(() => {\n        if (g === generation) failRtc(\"answer-timeout\");\n      }, net.answerMs);\n    } catch {\n      if (g === generation) failRtc(\"setup\");\n    }\n  }";
export const DESKTOP_TRANSFORM_SCRIPT = "function desktopTransform(\n      vw,\n      vh,\n      dw,\n      dh,\n      zoom,\n      fx,\n      fy,\n      fillHeight = false,\n    ) {\n      const fit = fillHeight\n        ? vh / Math.max(1, dh)\n        : Math.min(vw / Math.max(1, dw), vh / Math.max(1, dh));\n      // Pinch stops at two viewer points per desktop point, never below fit.\n      const maxZoom = Math.max(1, 2 / fit);\n      const scale = fit * Math.max(1, Math.min(maxZoom, zoom));\n      const width = dw * scale;\n      const height = dh * scale;\n      const x =\n        width <= vw\n          ? (vw - width) / 2\n          : Math.min(0, Math.max(vw - width, vw / 2 - fx * width));\n      const y =\n        height <= vh\n          ? (vh - height) / 2\n          : Math.min(0, Math.max(vh - height, vh / 2 - fy * height));\n      return { x, y, width, height, scale, maxZoom };\n    }";
export const DESKTOP_NETWORK_STATS_SCRIPT = "function networkStats(stats, previous) {\n      const rows = [...stats.values()];\n      const video = rows.find(\n        (s) =>\n          s.type === \"inbound-rtp\" &&\n          (s.kind === \"video\" || s.mediaType === \"video\"),\n      );\n      const transport = rows.find(\n        (s) => s.type === \"transport\" && s.selectedCandidatePairId,\n      );\n      const pair = transport\n        ? stats.get(transport.selectedCandidatePairId)\n        : rows.find(\n            (s) =>\n              s.type === \"candidate-pair\" &&\n              s.state === \"succeeded\" &&\n              s.nominated,\n          );\n      const local = pair && stats.get(pair.localCandidateId),\n        remote = pair && stats.get(pair.remoteCandidateId);\n      const direct = [\"host\", \"srflx\", \"prflx\"];\n      const route =\n        local?.candidateType === \"relay\" || remote?.candidateType === \"relay\"\n          ? \"relay\"\n          : direct.includes(local?.candidateType) &&\n              direct.includes(remote?.candidateType)\n            ? \"direct\"\n            : \"video\";\n      const sample =\n        video &&\n        Number.isFinite(video.bytesReceived) &&\n        Number.isFinite(video.timestamp)\n          ? {\n              id: video.id,\n              path: pair?.id,\n              bytes: video.bytesReceived,\n              time: video.timestamp,\n            }\n          : null;\n      let bytesPerSecond = null;\n      if (\n        sample &&\n        previous &&\n        sample.id === previous.id &&\n        sample.path === previous.path &&\n        sample.time > previous.time &&\n        sample.bytes >= previous.bytes\n      )\n        bytesPerSecond =\n          ((sample.bytes - previous.bytes) * 1000) /\n          (sample.time - previous.time);\n      const latencyMs =\n        Number.isFinite(pair?.currentRoundTripTime) &&\n        pair.currentRoundTripTime >= 0\n          ? pair.currentRoundTripTime * 1000\n          : null;\n      return { transport: route, bytesPerSecond, latencyMs, sample };\n    }";