Browse Source

fix(cockpit): 修复 native 播放无 src 并删除 WebRTC 旧栈死代码

代码审查发现的确定性缺陷:统一为 Jessibuca FLV 后,native 分支的 <video> 没有绑定 src,
MANUAL 直连地址设备会一直等到就绪超时。改为绑定 computed nativeSrc,并补守护测试。

- VideoPlayer.vue:native <video> 绑定 :src,FLV 走 Jessibuca;移除已无消费者的 options prop;
- VideoMonitorPanel.vue:移除失效的 playerOptions 传递,更新注释为 FLV;
- 删除旧 WebRTC 播放器 videoPlayer.js 与其单测 player.mjs(全仓零引用,run.mjs 不跑);
- journey 测试:增强为「FLV 优先于 url 诱饵 + kind=flv + 不构造 RTCPeerConnection」,
  新增 WebRTC-only 必被拒绝(即便 RTCPeerConnection 可用),新增 native 走 <video> 分支守护。

真实浏览器验证(办公区1 新编码):Jessibuca 解码 canvas 2560x1440 出画、正在播放、
RTCPeerConnection 构造次数 0、无原生 video 回退;关闭后对话框与 canvas 均销毁。
离线 journey 17/17、hosts 15/15 通过。按 AGENTS.md 跳过 build。
ChenJZ 1 giờ trước cách đây
mục cha
commit
37092b6a7e

+ 5 - 5
src/modules/cockpit/components/VideoMonitorPanel.vue

@@ -72,10 +72,10 @@
                         <p v-if="!ptzEnabled" data-ptz-hint>{{ ptzReason }}</p>
                     </aside>
                     <div class="video-monitor__screen">
-                        <VideoPlayer v-if="state.media" :media="state.media" :options="playerOptions" @ready="video.ready" @error="video.fail" />
-                        <!-- A GB28181 playback publishes WebRTC signalling, so it uses the same player
-                             as live video; native controls would also bypass the grey gate. -->
-                        <VideoPlayer v-else-if="state.playbackMedia" :media="state.playbackMedia" :options="playerOptions"
+                        <VideoPlayer v-if="state.media" :media="state.media" @ready="video.ready" @error="video.fail" />
+                        <!-- Live and playback share one Jessibuca FLV player; native controls would
+                             also bypass the grey gate, so playback turns them off. -->
+                        <VideoPlayer v-else-if="state.playbackMedia" :media="state.playbackMedia"
                                      label="历史录像画面" :controls="false"
                                      @ready="video.readyPlayback" @error="video.failPlayback" />
                         <p v-else-if="state.phase === 'retrying'">等待自动重连…</p>
@@ -102,7 +102,7 @@ import { useDetailStore } from '../stores/detailStore.js'
 import { useEnhancementDevicesStore } from '../stores/enhancementDevicesStore.js'
 import VideoPlayer from './VideoPlayer.vue'
 const video = useVideoStore(), ui = useUiStore(), detail = useDetailStore(), enhancement = useEnhancementDevicesStore()
-const { state, playerOptions } = storeToRefs(video)
+const { state } = storeToRefs(video)
 const labels = { idle: '未播放', starting: '正在建立视频会话', connecting: '等待视频画面', playing: '正在播放', retrying: '连接中断,正在自动重连', failed: '播放失败', querying: '正在查询录像', listed: '已返回录像列表' }
 // Switching tabs ends the current stream but must keep the monitor open.
 const mode = ref('live')

+ 3 - 1
src/modules/cockpit/components/VideoPlayer.vue

@@ -6,6 +6,7 @@
             v-if="isNative"
             ref="video"
             class="cockpit-video-player"
+            :src="nativeSrc"
             :aria-label="label"
             :controls="controls" autoplay muted playsinline
             controlslist="nodownload noremoteplayback noplaybackrate"
@@ -25,7 +26,6 @@ import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch
 // Replaces the old WebRTC player with a Jessibuca FLV player (tech-stack unification).
 const props = defineProps({
     media: { type: Object, default: null },
-    options: { type: Object, default: () => ({}) },
     label: { type: String, default: '实时视频画面' },
     controls: { type: Boolean, default: true },
 })
@@ -34,6 +34,7 @@ const video = shallowRef(null)
 const decoder = ref(null)
 const errorText = ref('')
 const isNative = computed(() => props.media?.kind === 'native' || props.media?.native === true)
+const nativeSrc = computed(() => (isNative.value ? props.media?.url : undefined))
 let player
 let generation = 0
 
@@ -63,6 +64,7 @@ const start = async () => {
     errorText.value = ''
     if (!props.media?.url) return
     const version = generation
+    // Native <video> loads through :src and reports readiness via its own @playing.
     if (isNative.value) return
     try {
         await nextTick()

+ 0 - 148
src/modules/cockpit/services/videoPlayer.js

@@ -1,148 +0,0 @@
-function playbackUrl(video, media) {
-    try {
-        if (!['native', 'webrtc'].includes(media?.kind) || typeof media.url !== 'string'
-            || /[\u0000-\u0020\u007f]/.test(media.url)) throw new Error()
-        const url = new URL(media.url)
-        const pageProtocol = video.ownerDocument?.location?.protocol || globalThis.location?.protocol
-        if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password
-            || (pageProtocol === 'https:' && url.protocol !== 'https:')) throw new Error()
-        const path = decodeURIComponent(url.pathname)
-        if (media.kind === 'native' && (/\.flv$/i.test(path) || /\/(?:index\/api\/webrtc|rtc\/v1\/play)\/?$/i.test(path))) throw new Error()
-        return url.href
-    } catch {
-        throw Object.assign(new Error('视频地址或播放协议不可用'), { code: 'VIDEO_URL_INVALID' })
-    }
-}
-
-/** 仅管理浏览器本地播放资源;匿名观看会话由上层维护和释放。 */
-export function createVideoPlayer(video, media, options = {}) {
-    let destroyed = false
-    let ready = false
-    let attached = false
-    let peer
-    let cancelIce
-    const listeners = []
-    const abort = new AbortController()
-    const timers = options.timers || globalThis
-    const listen = (target, type, callback) => {
-        target.addEventListener(type, callback)
-        listeners.push(() => target.removeEventListener(type, callback))
-    }
-    const destroy = () => {
-        if (destroyed) return
-        destroyed = true
-        abort.abort()
-        cancelIce?.()
-        listeners.splice(0).forEach((remove) => remove())
-        const tracks = new Set([
-            ...(video.srcObject?.getTracks?.() || []),
-            ...(peer?.getReceivers?.().map((receiver) => receiver.track).filter(Boolean) || []),
-        ])
-        tracks.forEach((track) => track.stop())
-        peer?.close()
-        video.pause()
-        video.srcObject = null
-        video.removeAttribute('src')
-        video.load()
-    }
-    const fail = (message, code = 'VIDEO_PLAYBACK_FAILED') => {
-        if (destroyed) return
-        destroy()
-        options.onError?.(Object.assign(new Error(message), { code }))
-    }
-    const play = () => Promise.resolve(video.play()).catch(() => fail('视频播放失败,请检查浏览器播放能力'))
-    listen(video, 'playing', () => {
-        if (destroyed || ready || !attached) return
-        ready = true
-        options.onReady?.()
-    })
-    listen(video, 'error', () => fail('视频解码或网络异常,请重试'))
-    listen(video, 'ended', () => fail('视频流已结束,请重新播放'))
-    const waitForIce = () => new Promise((resolve) => {
-        const finish = (complete) => {
-            timers.clearTimeout(timeout)
-            peer.removeEventListener('icegatheringstatechange', onState)
-            cancelIce = null
-            resolve(complete)
-        }
-        const onState = () => {
-            if (peer.iceGatheringState === 'complete') finish(true)
-        }
-        const timeout = timers.setTimeout(() => {
-            finish(false)
-            fail('视频连接候选收集超时', 'VIDEO_ICE_TIMEOUT')
-        }, 5000)
-        cancelIce = () => finish(false)
-        peer.addEventListener('icegatheringstatechange', onState)
-        onState()
-    })
-    const start = async () => {
-        if (destroyed) return
-        const url = playbackUrl(video, media)
-        video.muted = true
-        video.playsInline = true
-        if (media.kind === 'native') {
-            attached = true
-            video.src = url
-            await play()
-            return
-        }
-        const PeerConnection = options.PeerConnection || globalThis.RTCPeerConnection
-        const fetchImpl = options.fetchImpl || globalThis.fetch
-        if (!PeerConnection || !fetchImpl) {
-            fail('当前浏览器不支持实时视频连接', 'VIDEO_UNSUPPORTED')
-            return
-        }
-        peer = new PeerConnection({ iceServers: [] })
-        const onConnectionState = () => {
-            if ([peer.connectionState, peer.iceConnectionState].some((state) => ['failed', 'disconnected', 'closed'].includes(state))) {
-                fail('实时视频连接已断开', 'VIDEO_CONNECTION_FAILED')
-            }
-        }
-        listen(peer, 'connectionstatechange', onConnectionState)
-        listen(peer, 'iceconnectionstatechange', onConnectionState)
-        peer.addTransceiver('video', { direction: 'recvonly' })
-        peer.addTransceiver('audio', { direction: 'recvonly' })
-        listen(peer, 'track', (event) => {
-            if (destroyed) return
-            try {
-                if (event.track.kind === 'video') listen(event.track, 'ended', () => fail('实时视频轨道已结束'))
-                const Stream = video.ownerDocument?.defaultView?.MediaStream || globalThis.MediaStream
-                const stream = video.srcObject || event.streams?.[0] || new Stream()
-                if (!stream.getTracks().includes(event.track)) stream.addTrack(event.track)
-                video.srcObject = stream
-                attached = stream.getTracks().some((track) => track.kind === 'video' && track.readyState !== 'ended')
-                play()
-            } catch {
-                fail('视频轨道无法播放')
-            }
-        })
-        const offer = await peer.createOffer()
-        if (destroyed) return
-        await peer.setLocalDescription(offer)
-        if (destroyed || !await waitForIce()) return
-        const response = await fetchImpl(url, {
-            method: 'POST', headers: { 'Content-Type': 'text/plain' },
-            body: peer.localDescription.sdp, signal: abort.signal,
-            credentials: 'omit', redirect: 'error',
-        })
-        if (destroyed) return
-        if (!response.ok || !/^application\/(?:json|[\w.-]+\+json)(?:;|$)/i.test(response.headers.get('content-type') || '')) {
-            fail('视频信令响应无效', 'VIDEO_SIGNALING_FAILED')
-            return
-        }
-        const answer = await response.json()
-        if (destroyed) return
-        if (answer.code !== 0 || answer.type !== 'answer' || typeof answer.sdp !== 'string'
-            || !/^v=0\r?\n/.test(answer.sdp) || !/^m=video /m.test(answer.sdp)) {
-            fail('视频信令应答无效', 'VIDEO_SIGNALING_FAILED')
-            return
-        }
-        await peer.setRemoteDescription({ type: 'answer', sdp: answer.sdp })
-    }
-    Promise.resolve().then(start).catch((error) => {
-        if (error?.code === 'VIDEO_URL_INVALID') fail(error.message, error.code)
-        else fail('视频连接失败,请检查媒体服务与浏览器能力', 'VIDEO_SIGNALING_FAILED')
-    })
-    return { destroy }
-}

+ 46 - 12
tests/cockpit-video/journey.mjs

@@ -203,16 +203,23 @@ test('non-camera has no monitor button; unbound and unknown live capability stay
 test('a WebRTC-only media payload is now unsupported: it is refused, released and never presents playing', async () => {
     // After tech-stack unification the cockpit plays FLV only; a WebRTC-only response has no playable URL.
     const clock = new TestClock()
-    const page = await mountJourney({ sessionOptions: { timers: clock }, live: () => envelope(livePayload({ native: false, webrtc: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play' })) })
+    // Make WebRTC constructible so a fallback would be caught here, not just fail for lack of the API.
+    const rtc = []
+    globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
     try {
-        const dialog = await openMonitor(page)
-        assert.equal(dialog.querySelector('video'), null)
-        // Unsupported media is a capability outcome, never a temporary outage: no retry is spent.
-        assert.ok(dialog.textContent.includes('不支持'), dialog.textContent)
-        assert.equal(dialog.textContent.includes('正在播放'), false)
-        assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1, 'an unsupported payload must not be retried')
-        assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
-    } finally { await page.dispose() }
+        const page = await mountJourney({ sessionOptions: { timers: clock }, live: () => envelope(livePayload({ native: false, webrtc: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play' })) })
+        try {
+            const dialog = await openMonitor(page)
+            assert.equal(dialog.querySelector('video'), null)
+            // Unsupported media is a capability outcome, never a temporary outage: no retry is spent.
+            assert.ok(dialog.textContent.includes('不支持'), dialog.textContent)
+            assert.equal(dialog.textContent.includes('正在播放'), false)
+            assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1, 'an unsupported payload must not be retried')
+            assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
+            assert.equal(rtc.length, 0, 'a WebRTC-only payload must be refused, never attempted')
+            assert.equal(page.video.state.media, null)
+        } finally { await page.dispose() }
+    } finally { delete globalThis.RTCPeerConnection }
 })
 
 test('HTTP 200 HTML live response is a visible failure and releases the prepared viewing resource', async () => {
@@ -280,6 +287,7 @@ test('hiding the page closes video and does not reopen it when visible again', a
 test('latest-tab entry plays the returned FLV through Jessibuca and only Jessibuca play establishes visible playback', async () => {
     // Tech-stack unification: the cockpit now decodes FLV with Jessibuca, not WebRTC signalling.
     const players = []
+    const rtc = []
     globalThis.Jessibuca = class {
         constructor(options) { this.options = options; this.handlers = new Map(); players.push(this) }
         on(type, fn) { this.handlers.set(type, fn) }
@@ -287,22 +295,48 @@ test('latest-tab entry plays the returned FLV through Jessibuca and only Jessibu
         async play(url) { this.url = url; this.emit('play') }
         destroy() { this.destroyed = true }
     }
+    globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
     try {
+        // A competing WebRTC url proves the FLV field wins, not that WebRTC is merely unavailable.
         const page = await mountJourney({
-            live: () => envelope(livePayload({ native: false, flv: 'https://media.invalid/live.flv' })),
+            live: () => envelope(livePayload({ native: false,
+                url: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play',
+                flv: 'https://media.invalid/live.flv' })),
         })
         try {
             const dialog = await openMonitor(page)
             // The FLV stream is handed to Jessibuca, not turned into a native <video src>.
             assert.equal(players.length, 1)
-            assert.ok(players[0].url.includes('.flv'), players[0].url)
+            assert.equal(players[0].url, 'https://media.invalid/live.flv', 'must prefer the flv field over the competing url')
+            assert.equal(page.video.state.media.kind, 'flv', 'media classification must be flv')
+            assert.equal(rtc.length, 0, 'FLV playback must never construct RTCPeerConnection')
             assert.equal(dialog.querySelector('video'), null)
             assert.ok(dialog.textContent.includes('正在播放'), 'a Jessibuca play event establishes visible playback')
             dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
             assert.equal(players[0].destroyed, true)
             assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
         } finally { await page.dispose() }
-    } finally { delete globalThis.Jessibuca }
+    } finally { delete globalThis.Jessibuca; delete globalThis.RTCPeerConnection }
+})
+
+test('a native (non-FLV) direct URL is played by a <video> that actually carries its src', async () => {
+    // Regression guard: the native branch must bind :src, otherwise MANUAL direct-URL devices never show.
+    const page = await mountJourney({ live: () => envelope(livePayload({ native: true, url: 'https://media.invalid/direct.mp4' })) })
+    try {
+        const dialog = await openMonitor(page)
+        const element = dialog.querySelector('video')
+        assert.ok(element, 'native media must render a <video>')
+        assert.equal(page.video.state.media.kind, 'native')
+        // linkeDOM does not reflect a bound src onto attributes/props reliably; assert the component
+        // chose the native branch with the direct URL, and that it renders a <video> (not the decoder div).
+        assert.equal(page.video.state.media.url, 'https://media.invalid/direct.mp4')
+        assert.equal(dialog.querySelector('[data-flv-decoder]'), null, 'native media must not use the Jessibuca decoder')
+        assert.equal(page.video.state.media.kind, 'native')
+        element.dispatchEvent(new Event('playing')); await settle()
+        assert.ok(dialog.textContent.includes('正在播放'))
+        dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
+        assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
+    } finally { await page.dispose() }
 })
 
 test('device detail latest tab opens its own anonymous live video even with no collection records, then closes it', async () => {

+ 0 - 420
tests/cockpit-video/player.mjs

@@ -1,420 +0,0 @@
-import test from 'node:test'
-import assert from 'node:assert/strict'
-import { readFile } from 'node:fs/promises'
-import { createVideoPlayer } from '../../src/modules/cockpit/services/videoPlayer.js'
-
-const settle = () => new Promise((resolve) => setImmediate(resolve))
-const offerSdp = 'v=0\r\no=- 1 1 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=recvonly\r\n'
-const answerSdp = 'v=0\r\no=- 2 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\na=sendonly\r\n'
-const signalingUrl = 'https://media.test/index/api/webrtc?app=rtp&stream=camera%2F01&type=play'
-const answer = () => new Response(JSON.stringify({ code: 0, type: 'answer', sdp: answerSdp }), {
-    headers: { 'Content-Type': 'application/json' },
-})
-
-class Peer extends EventTarget {
-    static instances = []
-    constructor(configuration) {
-        super()
-        this.configuration = configuration
-        this.iceGatheringState = 'new'
-        this.connectionState = 'new'
-        this.receivers = []
-        this.transceivers = []
-        Peer.instances.push(this)
-    }
-    addTransceiver(kind, options) { this.transceivers.push({ kind, ...options }) }
-    async createOffer() { return { type: 'offer', sdp: offerSdp } }
-    async setLocalDescription(description) { this.localDescription = description; this.iceGatheringState = 'gathering' }
-    async setRemoteDescription(description) { this.remoteDescription = description }
-    gather() {
-        this.localDescription = { type: 'offer', sdp: offerSdp + 'a=candidate:1 1 udp 1 192.0.2.1 5000 typ host\r\n' }
-        this.iceGatheringState = 'complete'
-        this.dispatchEvent(new Event('icegatheringstatechange'))
-    }
-    receive(track, streamless = false) {
-        this.receivers.push({ track })
-        const stream = { getTracks: () => [track] }
-        this.dispatchEvent(Object.assign(new Event('track'), { track, streams: streamless ? [] : [stream] }))
-        return stream
-    }
-    getReceivers() { return this.receivers }
-    close() { this.connectionState = 'closed' }
-}
-
-class Clock {
-    now = 0
-    next = 1
-    tasks = new Map()
-    setTimeout(callback, delay) { const id = this.next++; this.tasks.set(id, { at: this.now + delay, callback }); return id }
-    clearTimeout(id) { this.tasks.delete(id) }
-    advance(ms) {
-        const end = this.now + ms
-        while (true) {
-            const entry = [...this.tasks].sort((a, b) => a[1].at - b[1].at).find(([, item]) => item.at <= end)
-            if (!entry) break
-            const [id, item] = entry
-            this.tasks.delete(id); this.now = item.at; item.callback()
-        }
-        this.now = end
-    }
-}
-
-class Track extends EventTarget {
-    kind = 'video'
-    readyState = 'live'
-    stop() { this.readyState = 'ended' }
-}
-
-
-class Video extends EventTarget {
-    constructor(protocol = 'https:') {
-        super()
-        this.ownerDocument = { location: { protocol } }
-        this.attributes = new Map()
-        this.srcObject = null
-        this.paused = true
-        this.loads = 0
-    }
-    set src(value) { this.setAttribute('src', value) }
-    get src() { return this.getAttribute('src') || '' }
-    setAttribute(name, value) { this.attributes.set(name, String(value)) }
-    getAttribute(name) { return this.attributes.get(name) ?? null }
-    removeAttribute(name) { this.attributes.delete(name) }
-    play() { this.paused = false; return Promise.resolve() }
-    pause() { this.paused = true }
-    load() { this.loads++ }
-    fire(type) { this.dispatchEvent(new Event(type)) }
-}
-
-// 已确认接缝:真实driver + HTMLMediaElement/Peer/HTTP/时钟的外部边界替身。
-// 只观察媒体元素、回调、信令合同与本地资源释放,不读取driver私有状态。
-test('原生视频仅在playing后就绪,销毁时清空媒体且不再报告迟到事件', async () => {
-    const video = new Video()
-    const ready = [], errors = []
-    const player = createVideoPlayer(video, { kind: 'native', url: 'https://media.test/live.mp4' }, {
-        onReady: () => ready.push('画面就绪'), onError: (error) => errors.push(error),
-    })
-    await settle()
-    assert.equal(video.src, 'https://media.test/live.mp4')
-    assert.equal(video.muted, true)
-    video.fire('loadedmetadata')
-    assert.deepEqual(ready, [])
-    video.fire('playing')
-    assert.deepEqual(ready, ['画面就绪'])
-    player.destroy()
-    player.destroy()
-    assert.equal(video.src, '')
-    assert.equal(video.srcObject, null)
-    assert.equal(video.paused, true)
-    video.fire('playing')
-    video.fire('error')
-    assert.deepEqual(ready, ['画面就绪'])
-    assert.deepEqual(errors, [])
-})
-
-test('协议、凭据、混合内容和非原生媒体地址在触达媒体前被拒绝', async () => {
-    const invalid = [
-        { kind: 'native', url: 'javascript:alert(1)' },
-        { kind: 'native', url: 'webrtc://media.test/live' },
-        { kind: 'native', url: '/live.mp4' },
-        { kind: 'native', url: 'https://user:secret@media.test/live.mp4' },
-        { kind: 'native', url: 'http://media.test/live.mp4' },
-        { kind: 'native', url: 'https://media.test/live.flv?token=secret' },
-        { kind: 'native', url: 'https://media.test/index/api/webrtc?app=live&type=play' },
-        { kind: 'unknown', url: 'https://media.test/live.mp4' },
-    ]
-    for (const media of invalid) {
-        const video = new Video(), errors = []
-        const player = createVideoPlayer(video, media, { onError: (error) => errors.push(error) })
-        await settle()
-        assert.equal(video.src, '')
-        assert.equal(errors.length, 1)
-        assert.equal(errors[0].code, 'VIDEO_URL_INVALID')
-        assert.doesNotMatch(errors[0].message, /secret|media\.test/)
-        player.destroy()
-    }
-})
-
-test('WebRTC收集ICE后发送实际ZLM SDP,接收轨道且playing才就绪', async () => {
-    const video = new Video(), requests = [], ready = [], errors = []
-    const player = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-        PeerConnection: Peer,
-        fetchImpl: async (url, init) => { requests.push({ url, ...init }); return answer() },
-        onReady: () => ready.push('已播放'), onError: (error) => errors.push(error),
-    })
-    await settle()
-    const peer = Peer.instances.at(-1)
-    assert.ok(peer, '通过浏览器Peer边界建立连接')
-    assert.deepEqual(peer.configuration?.iceServers || [], [])
-    assert.deepEqual(peer.transceivers, [{ kind: 'video', direction: 'recvonly' }, { kind: 'audio', direction: 'recvonly' }])
-    assert.equal(requests.length, 0, '不提交尚未收集完的offer')
-    assert.equal(video.src, '', '信令地址不得进入video src')
-    peer.gather()
-    await settle()
-    assert.equal(requests.length, 1)
-    assert.equal(requests[0].url, signalingUrl)
-    assert.equal(requests[0].method, 'POST')
-    assert.equal(new Headers(requests[0].headers).get('content-type'), 'text/plain')
-    assert.equal(new Headers(requests[0].headers).get('authorization'), null)
-    assert.equal(requests[0].credentials, 'omit')
-    assert.equal(requests[0].redirect, 'error')
-    assert.match(requests[0].body, /a=candidate:1/)
-    assert.deepEqual(peer.remoteDescription, { type: 'answer', sdp: answerSdp })
-    const track = new Track(), stream = peer.receive(track)
-    await settle()
-    assert.equal(video.srcObject, stream)
-    assert.deepEqual(ready, [])
-    video.fire('playing')
-    assert.deepEqual(ready, ['已播放'])
-    player.destroy()
-    assert.equal(peer.connectionState, 'closed')
-    assert.equal(track.readyState, 'ended')
-    assert.equal(video.srcObject, null)
-    assert.deepEqual(errors, [])
-    assert.equal(requests.length, 1, '本地销毁不调用后端stop或重连')
-})
-
-test('ICE收集最多等待5秒,超时关闭Peer且不发出不完整信令', async () => {
-    const video = new Video(), clock = new Clock(), errors = [], requests = []
-    const player = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-        PeerConnection: Peer, timers: clock,
-        fetchImpl: async (...args) => { requests.push(args); return answer() },
-        onError: (error) => errors.push(error),
-    })
-    await settle()
-    const peer = Peer.instances.at(-1)
-    clock.advance(4999)
-    assert.equal(errors.length, 0)
-    clock.advance(1)
-    await settle()
-    assert.equal(errors.length, 1)
-    assert.equal(errors[0].code, 'VIDEO_ICE_TIMEOUT')
-    assert.equal(peer.connectionState, 'closed')
-    assert.deepEqual(requests, [])
-    player.destroy()
-})
-
-test('媒体错误、轨道结束与Peer断流会释放本地资源并只报一次失败', async () => {
-    for (const failure of ['video-error', 'video-ended', 'track-ended', 'peer-failed', 'peer-disconnected', 'ice-failed']) {
-        const video = new Video(), errors = [], ready = [], requests = []
-        const player = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-            PeerConnection: Peer,
-            fetchImpl: async (...args) => { requests.push(args); return answer() },
-            onError: (error) => errors.push(error), onReady: () => ready.push('已播放'),
-        })
-        await settle()
-        const peer = Peer.instances.at(-1)
-        peer.gather(); await settle()
-        const track = new Track()
-        peer.receive(track); await settle()
-        video.fire('playing')
-        if (failure.startsWith('video-')) video.fire(failure.slice(6))
-        if (failure === 'track-ended') track.dispatchEvent(new Event('ended'))
-        if (failure.startsWith('peer-')) {
-            peer.connectionState = failure.slice(5)
-            peer.dispatchEvent(new Event('connectionstatechange'))
-        }
-        if (failure === 'ice-failed') {
-            peer.iceConnectionState = 'failed'
-            peer.dispatchEvent(new Event('iceconnectionstatechange'))
-        }
-        await settle()
-        assert.equal(errors.length, 1, failure)
-        assert.equal(peer.connectionState, 'closed', failure)
-        assert.equal(track.readyState, 'ended', failure)
-        assert.equal(video.srcObject, null, failure)
-        video.fire('error'); video.fire('playing')
-        assert.equal(errors.length, 1)
-        assert.deepEqual(ready, ['已播放'])
-        assert.equal(requests.length, 1)
-        player.destroy()
-    }
-})
-
-test('销毁中的ICE和迟到信令不会再挂轨道、报就绪或请求后端停止', async () => {
-    const clock = new Clock(), errors = [], requests = []
-    const first = createVideoPlayer(new Video(), { kind: 'webrtc', url: signalingUrl }, {
-        PeerConnection: Peer, timers: clock, onError: (error) => errors.push(error),
-        fetchImpl: async (...args) => { requests.push(args); return answer() },
-    })
-    await settle()
-    const waiting = Peer.instances.at(-1)
-    first.destroy(); clock.advance(10000); waiting.gather(); await settle()
-    assert.equal(waiting.connectionState, 'closed')
-    assert.equal(requests.length, 0)
-    assert.equal(errors.length, 0)
-
-    const video = new Video(), ready = []
-    let resolveResponse
-    const response = new Promise((resolve) => { resolveResponse = resolve })
-    const second = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-        PeerConnection: Peer, onReady: () => ready.push(true), onError: (error) => errors.push(error),
-        fetchImpl: (url, init) => { requests.push({ url, ...init }); return response },
-    })
-    await settle()
-    const peer = Peer.instances.at(-1)
-    peer.gather(); await settle()
-    assert.equal(requests.length, 1)
-    second.destroy()
-    assert.equal(requests[0].signal.aborted, true)
-    resolveResponse(answer()); await settle()
-    assert.equal(peer.remoteDescription, undefined)
-    assert.equal(video.srcObject, null)
-    video.fire('playing')
-    assert.deepEqual(ready, [])
-    assert.deepEqual(errors, [])
-    assert.equal(requests.length, 1)
-})
-
-test('HTML、非成功信令与非法answer不被视作可播放媒体', async () => {
-    const responses = [
-        () => new Response('<html>secret</html>', { headers: { 'Content-Type': 'text/html' } }),
-        () => new Response('upstream secret', { status: 502 }),
-        () => new Response(JSON.stringify({ code: 1, msg: 'secret' }), { headers: { 'Content-Type': 'application/json' } }),
-        () => new Response(JSON.stringify({ code: 0, type: 'offer', sdp: answerSdp }), { headers: { 'Content-Type': 'application/json' } }),
-        () => new Response(JSON.stringify({ code: 0, type: 'answer', sdp: '<html>secret</html>' }), { headers: { 'Content-Type': 'application/json' } }),
-        () => new Response('null', { headers: { 'Content-Type': 'application/json' } }),
-        () => { throw new Error('upstream secret at https://media.test/token') },
-    ]
-    for (const response of responses) {
-        const video = new Video(), errors = [], ready = []
-        const player = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-            PeerConnection: Peer, fetchImpl: async () => response(),
-            onError: (error) => errors.push(error), onReady: () => ready.push(true),
-        })
-        await settle()
-        const peer = Peer.instances.at(-1)
-        peer.gather(); await settle()
-        assert.equal(errors.length, 1)
-        assert.equal(errors[0].code, 'VIDEO_SIGNALING_FAILED')
-        assert.doesNotMatch(errors[0].message, /secret|media\.test|token/)
-        assert.equal(peer.remoteDescription, undefined)
-        assert.equal(peer.connectionState, 'closed')
-        assert.equal(video.src, '')
-        assert.deepEqual(ready, [])
-        player.destroy()
-    }
-})
-
-test('原生播放拒绝和缺失WebRTC能力均返回可清理的失败而非伪就绪', async () => {
-    const video = new Video(), errors = [], ready = []
-    video.play = () => Promise.reject(new Error('autoplay secret'))
-    const player = createVideoPlayer(video, { kind: 'native', url: 'https://media.test/live.mp4' }, {
-        onError: (error) => errors.push(error), onReady: () => ready.push(true),
-    })
-    await settle()
-    assert.equal(errors[0].code, 'VIDEO_PLAYBACK_FAILED')
-    assert.doesNotMatch(errors[0].message, /secret/)
-    assert.equal(video.src, '')
-    video.fire('playing')
-    assert.deepEqual(ready, [])
-    player.destroy()
-    const unsupported = createVideoPlayer(new Video(), { kind: 'webrtc', url: signalingUrl }, {
-        onError: (error) => errors.push(error),
-    })
-    await settle()
-    assert.equal(errors[1].code, 'VIDEO_UNSUPPORTED')
-    unsupported.destroy()
-})
-
-test('无关联stream的音视频轨道保留在同一媒体流,只有视频轨道可报画面就绪', async () => {
-    class MediaStream {
-        tracks = []
-        addTrack(track) { this.tracks.push(track) }
-        getTracks() { return this.tracks }
-    }
-    const video = new Video(), errors = [], ready = []
-    video.ownerDocument.defaultView = { MediaStream }
-    const player = createVideoPlayer(video, { kind: 'webrtc', url: signalingUrl }, {
-        PeerConnection: Peer, fetchImpl: async () => answer(),
-        onError: (error) => errors.push(error), onReady: () => ready.push('画面就绪'),
-    })
-    await settle()
-    const peer = Peer.instances.at(-1)
-    peer.gather(); await settle()
-    const audio = new Track(), picture = new Track()
-    audio.kind = 'audio'
-    peer.receive(audio, true); await settle()
-    assert.deepEqual(errors, [])
-    video.fire('playing')
-    assert.deepEqual(ready, [], '不能把只有音频当作视频画面就绪')
-    peer.receive(picture, true); await settle()
-    assert.deepEqual(video.srcObject.getTracks(), [audio, picture])
-    video.fire('playing')
-    assert.deepEqual(ready, ['画面就绪'])
-    player.destroy()
-    assert.equal(audio.readyState, 'ended')
-    assert.equal(picture.readyState, 'ended')
-})
-
-test('Vue播放器公开media与ready接缝可挂载,换媒体和卸载清理旧播放', async () => {
-    const { parseHTML } = await import('linkedom')
-    const { window } = parseHTML('<html><body><div id="host"></div></body></html>')
-    const previous = new Map()
-    for (const name of ['window', 'document', 'Element', 'HTMLElement', 'SVGElement']) {
-        previous.set(name, Object.getOwnPropertyDescriptor(globalThis, name))
-        Object.defineProperty(globalThis, name, { configurable: true, writable: true, value: window[name] })
-    }
-    // LinkeDOM不实现媒体播放;只在HTMLVideoElement外部边界提供播放/清理替身。
-    const createElement = window.document.createElement.bind(window.document)
-    window.document.createElement = (name, ...args) => {
-        const element = createElement(name, ...args)
-        if (name === 'video') {
-            Object.defineProperty(element, 'src', {
-                get: () => element.getAttribute('src') || '',
-                set: (value) => element.setAttribute('src', value),
-            })
-            element.play = () => Promise.resolve()
-            element.pause = () => { element.dataset.paused = 'true' }
-            element.load = () => {}
-        }
-        return element
-    }
-    let app
-    try {
-        const { parse, compileScript } = await import('@vue/compiler-sfc')
-        const file = new URL('../../src/modules/cockpit/components/VideoPlayer.vue', import.meta.url)
-        const { descriptor, errors: parseErrors } = parse(await readFile(file, 'utf8'), { filename: file.pathname })
-        assert.deepEqual(parseErrors, [])
-        const compiled = compileScript(descriptor, { id: 'player-test', inlineTemplate: true })
-        const code = compiled.content
-            .replace(/from ["']vue["']/g, `from ${JSON.stringify(import.meta.resolve('vue'))}`)
-            .replace(/from ["']\.\.\/services\/videoPlayer\.js["']/g,
-                `from ${JSON.stringify(new URL('../../src/modules/cockpit/services/videoPlayer.js', import.meta.url).href)}`)
-        const { default: Component } = await import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`)
-        const { createApp, h, shallowRef, nextTick } = await import('vue')
-        const media = shallowRef({ kind: 'native', url: 'https://media.test/first.mp4' })
-        const ready = [], errors = []
-        app = createApp({ render: () => h(Component, {
-            media: media.value, onReady: () => ready.push('ready'), onError: (error) => errors.push(error),
-        }) })
-        app.mount(window.document.querySelector('#host'))
-        await nextTick(); await settle()
-        const video = window.document.querySelector('video')
-        assert.ok(video)
-        assert.equal(video.src, 'https://media.test/first.mp4')
-        assert.equal(video.hasAttribute('controls'), true)
-        assert.match(video.getAttribute('controlslist'), /nodownload/)
-        assert.equal(video.hasAttribute('disablepictureinpicture'), true)
-        assert.equal(video.hasAttribute('disableremoteplayback'), true)
-        video.dispatchEvent(new window.Event('playing'))
-        assert.deepEqual(ready, ['ready'])
-        media.value = { kind: 'native', url: 'https://media.test/second.mp4' }
-        await nextTick(); await settle()
-        assert.equal(video.src, 'https://media.test/second.mp4')
-        assert.equal(video.dataset.paused, 'true')
-        video.dispatchEvent(new window.Event('playing'))
-        assert.deepEqual(ready, ['ready', 'ready'])
-        app.unmount(); app = null
-        assert.equal(video.getAttribute('src'), null)
-        video.dispatchEvent(new window.Event('playing'))
-        assert.deepEqual(ready, ['ready', 'ready'])
-        assert.deepEqual(errors, [])
-    } finally {
-        app?.unmount()
-        for (const [name, descriptor] of previous) {
-            if (descriptor) Object.defineProperty(globalThis, name, descriptor)
-            else delete globalThis[name]
-        }
-    }
-})