feat(match): 同步比赛计时与装甲板扣血许可
- feat(client): 增加裁判比赛计时、技术暂停与选手端局域网同步 - feat(armor): 红蓝共用通用固件,按客户端选队并显示网络连接状态 - feat(armor): 仅在对局进行中允许扣血,其他阶段保留受击闪烁 - feat(client): 将计时置于血条中间并增加开赛前五秒全屏动画 - fix(client): 修复连续血条、对手镜像和图传断连灰度遮罩 - fix(client): 统一界面中文字体并整理各页面文案 - fix(maintenance): 备份迁移装甲板分区,恢复 SDK 构建与固件打包 - refactor(repo): 按 armor、vt 和 client 整理工程与脚本,移除旧参考实现 - test: 补充线路、受击许可、回环 UDP、维护和 HUD 验证 - docs: 同步构建、协议、比赛控制和硬件验证边界 验证:前端构建与 19 项相关测试通过;核心 91 项单元测试与 2 项回环 UDP 集成测试通过;装甲板规则 25 项、线路 26 项、Tauri 51 项测试通过;独立探测器 5 项与目录回归 4 项通过。完成 C3 两组阈值实际编译、导出与 ZIP 校验,检查 900×600 / 1280×720 页面、倒计时和随包中文字体。 未执行烧录、板上运行、跨电脑广播或硬件稳定性验证。
This commit is contained in:
581 files changed
+6596
-7683
No files matched your search
@@ -0,0 +1,144 @@
|
||||
"""Render the existing SVG brand sources with Tauri, then export PNG/ICO/ICNS/BMP.
|
||||
|
||||
Requires the installed desktop Node dependencies and Python's Pillow package.
|
||||
Text is rasterized with Pillow so exports do not depend on the SVG renderer's
|
||||
font discovery. No dependency is added to the application or its build hooks.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import copy
|
||||
import io
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import struct
|
||||
import subprocess
|
||||
import tempfile
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
|
||||
DESKTOP = Path(__file__).resolve().parents[1]
|
||||
ICONS = DESKTOP / "src-tauri/icons"
|
||||
INSTALLER = DESKTOP / "src-tauri/installer"
|
||||
SVG = "{http://www.w3.org/2000/svg}"
|
||||
ET.register_namespace("", SVG[1:-1])
|
||||
|
||||
|
||||
def system_font(monospace=False, bold=False):
|
||||
fonts = Path(os.environ.get("WINDIR", "C:/Windows")) / "Fonts"
|
||||
candidates = (
|
||||
[fonts / ("consolab.ttf" if bold else "consola.ttf"),
|
||||
Path("/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf")]
|
||||
if monospace else
|
||||
[fonts / ("msyhbd.ttc" if bold else "msyh.ttc"),
|
||||
Path("/System/Library/Fonts/PingFang.ttc"),
|
||||
Path("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc")]
|
||||
)
|
||||
for path in candidates:
|
||||
if path.exists():
|
||||
return path
|
||||
raise RuntimeError("Set --sans-font and --mono-font to installed fonts supporting the artwork's text.")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--sans-font", type=Path)
|
||||
parser.add_argument("--mono-font", type=Path)
|
||||
args = parser.parse_args()
|
||||
node = shutil.which("node")
|
||||
cli = DESKTOP / "node_modules/@tauri-apps/cli/tauri.js"
|
||||
if not node or not cli.exists():
|
||||
raise RuntimeError("Install Node and run pnpm install --frozen-lockfile in client/ first.")
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="rmic-brand-") as temporary:
|
||||
scratch = Path(temporary)
|
||||
|
||||
def render(root, size):
|
||||
source = scratch / "source.svg"
|
||||
ET.ElementTree(root).write(source, encoding="utf-8", xml_declaration=True)
|
||||
subprocess.run([node, str(cli), "icon", str(source), "--output", str(scratch),
|
||||
"--png", str(size)], cwd=DESKTOP, check=True, capture_output=True)
|
||||
with Image.open(scratch / f"{size}x{size}.png") as image:
|
||||
return image.convert("RGBA")
|
||||
|
||||
original = ET.parse(ICONS / "icon.svg").getroot()
|
||||
images = {}
|
||||
for size in (16, 20, 24, 32, 48, 64, 128, 256, 512, 1024):
|
||||
root = copy.deepcopy(original)
|
||||
scale = 0.97 if size <= 48 else 0.88 if size <= 128 else 0.82
|
||||
group = root.find(f"{SVG}g")
|
||||
group.set("transform", group.get("transform").replace("scale(0.82)", f"scale({scale})"))
|
||||
images[size] = render(root, size)
|
||||
for filename, size in (("32x32.png", 32), ("128x128.png", 128),
|
||||
("128x128@2x.png", 256), ("icon.png", 512)):
|
||||
images[size].save(ICONS / filename)
|
||||
|
||||
def png(size):
|
||||
stream = io.BytesIO()
|
||||
images[size].save(stream, format="PNG")
|
||||
return stream.getvalue()
|
||||
|
||||
# Supply every ICO size separately, preserving optical scaling at 16–48px.
|
||||
entries, payloads = [], []
|
||||
sizes = (16, 20, 24, 32, 48, 64, 128, 256)
|
||||
offset = 6 + 16 * len(sizes)
|
||||
for size in sizes:
|
||||
data = png(size)
|
||||
entries.append(struct.pack("<BBBBHHII", size % 256, size % 256, 0, 0, 1, 32, len(data), offset))
|
||||
payloads.append(data)
|
||||
offset += len(data)
|
||||
(ICONS / "icon.ico").write_bytes(struct.pack("<HHH", 0, 1, len(sizes)) + b"".join(entries + payloads))
|
||||
chunks = []
|
||||
for kind, size in ((b"icp4", 16), (b"icp5", 32), (b"icp6", 64), (b"ic07", 128),
|
||||
(b"ic08", 256), (b"ic09", 512), (b"ic10", 1024),
|
||||
(b"ic11", 32), (b"ic12", 64), (b"ic13", 256), (b"ic14", 512)):
|
||||
data = png(size)
|
||||
chunks.append(kind + struct.pack(">I", 8 + len(data)) + data)
|
||||
body = b"".join(chunks)
|
||||
(ICONS / "icon.icns").write_bytes(b"icns" + struct.pack(">I", 8 + len(body)) + body)
|
||||
|
||||
for name in ("header", "sidebar"):
|
||||
root = ET.parse(INSTALLER / f"{name}.svg").getroot()
|
||||
width, height = int(root.get("width")), int(root.get("height"))
|
||||
text = []
|
||||
for element in list(root):
|
||||
if element.tag == f"{SVG}text":
|
||||
text.append(element)
|
||||
root.remove(element)
|
||||
elif element.tag == f"{SVG}image":
|
||||
# Installer art may reference the unframed original mark.
|
||||
# Preserve its own viewBox instead of replacing every image
|
||||
# with the square application icon.
|
||||
source = (INSTALLER / element.get("href")).resolve()
|
||||
logo = ET.parse(source).getroot()
|
||||
for attr in ("x", "y", "width", "height"):
|
||||
logo.set(attr, element.get(attr))
|
||||
logo.set("preserveAspectRatio", "xMidYMid meet")
|
||||
index = list(root).index(element)
|
||||
root.remove(element)
|
||||
root.insert(index, logo)
|
||||
edge = max(width, height)
|
||||
root.set("width", str(edge))
|
||||
root.set("height", str(edge))
|
||||
root.set("viewBox", f"0 0 {edge} {edge}")
|
||||
factor = 4
|
||||
image = render(root, edge * factor)
|
||||
draw = ImageDraw.Draw(image)
|
||||
for element in text:
|
||||
mono = element.get("font-family") == "monospace"
|
||||
bold = element.get("font-weight") == "700"
|
||||
font_path = (args.mono_font if mono else args.sans_font) or system_font(mono, bold)
|
||||
font = ImageFont.truetype(str(font_path), round(float(element.get("font-size")) * factor))
|
||||
draw.text((float(element.get("x")) * factor, float(element.get("y")) * factor),
|
||||
element.text, font=font, fill=element.get("fill"), anchor="ls")
|
||||
image = image.crop((0, 0, width * factor, height * factor)).convert("RGB")
|
||||
image.resize((width, height), Image.Resampling.LANCZOS).save(INSTALLER / f"{name}.png")
|
||||
# MUI scales these to the dialog's font/DPI. Supply 2x bitmaps so
|
||||
# Windows does not have to enlarge the raster text on modern screens.
|
||||
image.resize((width * 2, height * 2), Image.Resampling.LANCZOS).save(INSTALLER / f"{name}.bmp")
|
||||
print("Generated rounded PNG/ICO/ICNS icons and 24-bit NSIS header/sidebar artwork.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,137 @@
|
||||
# Windows uses the executable's integrity label when creating its process. A Low
|
||||
# label inherited from a sandboxed workspace prevents NSIS from writing to TEMP,
|
||||
# before .onInit or any installer hook can run.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$OutputDir,
|
||||
[switch]$CheckProcessOnly,
|
||||
[switch]$CheckOnly
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
|
||||
# whoami's group names are localized; the mandatory-label SID is stable.
|
||||
$groups = (& whoami.exe /groups) -join "`n"
|
||||
if ($LASTEXITCODE -ne 0 -or $groups -notmatch 'S-1-16-(\d+)') {
|
||||
throw 'Cannot determine the Windows process integrity level.'
|
||||
}
|
||||
if ([int]$Matches[1] -lt 8192) {
|
||||
throw 'Windows packaging requires Medium integrity or higher. Start the terminal / CI runner outside the Low integrity sandbox. Redirecting TEMP or changing directory write permissions does not fix executable integrity labels.'
|
||||
}
|
||||
if ($CheckProcessOnly) { return }
|
||||
|
||||
if (-not ('RmicBundleIntegrity' -as [type])) {
|
||||
$compilerOptions = @{}
|
||||
if ($PSVersionTable.PSEdition -eq 'Desktop') {
|
||||
# Framework CodeDOM otherwise tries to label its private temp directory
|
||||
# High when an admin token has been capped at Medium by an exe label.
|
||||
$parameters = New-Object System.CodeDom.Compiler.CompilerParameters
|
||||
$parameters.ReferencedAssemblies.Add('System.dll') | Out-Null
|
||||
$parameters.TempFiles = New-Object System.CodeDom.Compiler.TempFileCollection([IO.Path]::GetTempPath(), $false)
|
||||
$compilerOptions.CompilerParameters = $parameters
|
||||
}
|
||||
Add-Type @compilerOptions -TypeDefinition @'
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
public static class RmicBundleIntegrity {
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode)]
|
||||
private static extern uint GetNamedSecurityInfoW(string name, int type, uint info,
|
||||
out IntPtr owner, out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr sd);
|
||||
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool ConvertSecurityDescriptorToStringSecurityDescriptorW(
|
||||
IntPtr sd, uint revision, uint info, out IntPtr text, out uint length);
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr LocalFree(IntPtr memory);
|
||||
|
||||
public static string ReadLabel(string path) {
|
||||
// LABEL_SECURITY_INFORMATION reads only the label, without requiring the
|
||||
// SeSecurityPrivilege needed to read an entire SACL (Get-Acl -Audit).
|
||||
IntPtr owner, group, dacl, sacl, sd, text = IntPtr.Zero;
|
||||
uint error = GetNamedSecurityInfoW(path, 1, 0x10, out owner, out group,
|
||||
out dacl, out sacl, out sd);
|
||||
if (error != 0) throw new Win32Exception((int)error, path);
|
||||
try {
|
||||
uint length;
|
||||
if (!ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, 1, 0x10,
|
||||
out text, out length)) throw new Win32Exception(Marshal.GetLastWin32Error());
|
||||
return Marshal.PtrToStringUni(text);
|
||||
} finally {
|
||||
if (text != IntPtr.Zero) LocalFree(text);
|
||||
LocalFree(sd);
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
function Assert-MediumIntegrity([string]$Path) {
|
||||
$label = [RmicBundleIntegrity]::ReadLabel($Path)
|
||||
# An absent label is Medium. Windows may render known SIDs as SDDL aliases.
|
||||
if ($label -match ';(LW|UN|S-1-16-(\d+))\)') {
|
||||
if ($Matches[1] -in @('LW', 'UN') -or [int]$Matches[2] -lt 8192) {
|
||||
throw "Low / Untrusted integrity label on $Path. Run prepare-windows-bundle.ps1 from a normal Windows terminal before distributing this artifact."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$hostOutputDir = $null
|
||||
if (-not $OutputDir) {
|
||||
# Ask Cargo so CARGO_TARGET_DIR and Cargo's target-dir setting are respected.
|
||||
$manifest = Join-Path $PSScriptRoot '../src-tauri/Cargo.toml'
|
||||
$metadata = & cargo +stable metadata --no-deps --format-version 1 --manifest-path $manifest
|
||||
if ($LASTEXITCODE -ne 0) { throw 'Cannot resolve the Cargo output directory.' }
|
||||
$target = $env:TAURI_ENV_TARGET_TRIPLE
|
||||
if (-not $target) { $target = 'x86_64-pc-windows-msvc' }
|
||||
$profile = if ($env:TAURI_ENV_DEBUG -eq 'true') { 'debug' } else { 'release' }
|
||||
$targetDir = ($metadata | ConvertFrom-Json).target_directory
|
||||
$OutputDir = Join-Path $targetDir "$target/$profile"
|
||||
# Cross-target Cargo builds also run host build scripts from target/<profile>.
|
||||
# Old Low executables there can fail before the bundling hook is reached.
|
||||
$hostOutputDir = Join-Path $targetDir $profile
|
||||
}
|
||||
$OutputDir = [IO.Path]::GetFullPath($OutputDir)
|
||||
|
||||
# Limit changes to build outputs. Do not relabel the workspace, TEMP, user data,
|
||||
# or DACLs, and do not request elevation for the installer.
|
||||
$directories = @(
|
||||
$OutputDir
|
||||
(Join-Path $OutputDir 'bundle')
|
||||
(Join-Path $OutputDir 'bundle/nsis')
|
||||
(Join-Path $OutputDir 'nsis')
|
||||
)
|
||||
if ($hostOutputDir) { $directories = @($hostOutputDir) + $directories }
|
||||
if (Test-Path -LiteralPath (Join-Path $OutputDir 'nsis')) {
|
||||
$directories += @(Get-ChildItem -LiteralPath (Join-Path $OutputDir 'nsis') -Directory -Recurse |
|
||||
Select-Object -ExpandProperty FullName)
|
||||
}
|
||||
foreach ($directory in $directories) {
|
||||
if (-not $CheckOnly) {
|
||||
New-Item -ItemType Directory -Force -Path $directory | Out-Null
|
||||
& icacls.exe $directory /setintegritylevel '(OI)(CI)M' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Cannot set Medium integrity on $directory" }
|
||||
}
|
||||
Assert-MediumIntegrity $directory
|
||||
}
|
||||
|
||||
$executables = @(Get-ChildItem -LiteralPath $OutputDir -Filter '*.exe' -File)
|
||||
foreach ($directory in @('nsis', 'bundle/nsis')) {
|
||||
$executables += @(Get-ChildItem -LiteralPath (Join-Path $OutputDir $directory) -Filter '*.exe' -File -Recurse)
|
||||
}
|
||||
if ($hostOutputDir -and (Test-Path -LiteralPath (Join-Path $hostOutputDir 'build'))) {
|
||||
$executables += @(Get-ChildItem -LiteralPath (Join-Path $hostOutputDir 'build') -Filter '*.exe' -File -Recurse)
|
||||
}
|
||||
foreach ($executable in $executables) {
|
||||
if (-not $CheckOnly) {
|
||||
# Also replace explicit Low labels left by an earlier Low integrity build.
|
||||
& icacls.exe $executable.FullName /setintegritylevel M | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "Cannot set Medium integrity on $($executable.FullName)" }
|
||||
}
|
||||
Assert-MediumIntegrity $executable.FullName
|
||||
}
|
||||
if ($CheckOnly -and -not (Get-ChildItem -LiteralPath (Join-Path $OutputDir 'bundle/nsis') -Filter '*.exe' -File)) {
|
||||
throw "No NSIS installer found in $OutputDir/bundle/nsis."
|
||||
}
|
||||
Write-Host "Windows bundle integrity verified: $OutputDir ($($executables.Count) executables)."
|
||||
@@ -0,0 +1,146 @@
|
||||
// Observe the native client's local video channel without adding a UDP peer.
|
||||
// Read the token internally from a deliberately enabled debug log; never print it.
|
||||
import { readFile, writeFile, appendFile, mkdir, access } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
|
||||
const args = Object.fromEntries(process.argv.slice(2).reduce((pairs, value, i, all) => {
|
||||
if (i % 2 === 0) pairs.push([value.replace(/^--/, ''), all[i+1]]);
|
||||
return pairs;
|
||||
}, []));
|
||||
if (!args.log || !args.out) throw new Error('Use --log <backend-debug-log> --out <output-prefix> [--seconds 1800] [--warmup 30]');
|
||||
const seconds = Number(args.seconds ?? 300);
|
||||
const warmup = Number(args.warmup ?? 10);
|
||||
const sampleEveryMs = 1000*Number(args['sample-every'] ?? 0);
|
||||
const camera = Number(args.camera ?? '0x3D4D8A9A');
|
||||
await mkdir(dirname(args.out), { recursive: true });
|
||||
const log = await readFile(args.log, 'utf8');
|
||||
const url = [...log.matchAll(/ws:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+/g)].at(-1)?.[0];
|
||||
if (!url) throw new Error('No local video-channel URL in the debug log');
|
||||
const ws = new WebSocket(url);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
let latest = null, demo = true, diagnostics = false, clients = 0, connected = false;
|
||||
let binary = 0, invalid = 0, lastArrival = null, gaps = [], bytes = 0;
|
||||
let firstFrame = null;
|
||||
let sampleCount = 0, nextSampleAt = 0;
|
||||
const allGaps = [], windows = [];
|
||||
let measurementStarted = null, previousAt = null, previousStats = null;
|
||||
let windowBinary = 0, windowInvalid = 0, windowBytes = 0;
|
||||
let totalFrames = 0, totalDropped = 0, counterResets = 0, socketCloses = 0;
|
||||
let offlineSnapshots = 0;
|
||||
let diagnosticsUnavailableSnapshots = 0;
|
||||
let finished = false;
|
||||
ws.addEventListener('close', () => { connected = false; if (!finished) socketCloses++; });
|
||||
ws.addEventListener('message', event => {
|
||||
if (typeof event.data === 'string') {
|
||||
const msg = JSON.parse(event.data);
|
||||
if (msg.t === 'snapshot') {
|
||||
latest = msg.stats.find(stat => stat.camera === camera) ?? null;
|
||||
demo = msg.demo;
|
||||
diagnostics = msg.diagnostics;
|
||||
clients = msg.clients;
|
||||
if (measurementStarted !== null && (!latest || !latest.online)) offlineSnapshots++;
|
||||
if (measurementStarted !== null && !diagnostics) diagnosticsUnavailableSnapshots++;
|
||||
}
|
||||
return;
|
||||
}
|
||||
const data = Buffer.from(event.data);
|
||||
if (data.length < 16 || data.readUInt32LE(0) !== camera) return;
|
||||
if (measurementStarted === null) return;
|
||||
const valid = data.length === data.readUInt32LE(12)+16 && data[16] === 255 && data[17] === 216 && data.at(-2) === 255 && data.at(-1) === 217;
|
||||
if (!valid) { invalid++; windowInvalid++; return; }
|
||||
const now = performance.now();
|
||||
if (lastArrival !== null) { gaps.push(now-lastArrival); allGaps.push(now-lastArrival); }
|
||||
lastArrival = now;
|
||||
binary++; windowBinary++;
|
||||
bytes += data.length-16; windowBytes += data.length-16;
|
||||
if (firstFrame === null) {
|
||||
firstFrame = Buffer.from(data.subarray(16));
|
||||
void writeFile(`${args.out}.first.jpg`, firstFrame).catch(error => console.error('Could not save sample JPEG:', error.message));
|
||||
}
|
||||
if (sampleEveryMs > 0 && now >= nextSampleAt) {
|
||||
nextSampleAt = now+sampleEveryMs;
|
||||
const path = `${args.out}.sample-${String(++sampleCount).padStart(4,'0')}.jpg`;
|
||||
void writeFile(path, data.subarray(16)).catch(error => console.error('Could not save diagnostic JPEG:', error.message));
|
||||
}
|
||||
});
|
||||
await Promise.race([
|
||||
new Promise((resolve, reject) => { ws.addEventListener('open', () => { connected = true; resolve(); }, { once:true }); ws.addEventListener('error', reject, { once:true }); }),
|
||||
new Promise((_, reject) => setTimeout(() => reject(new Error('Video channel open timeout')), 15_000)),
|
||||
]);
|
||||
await new Promise(resolve => setTimeout(resolve, warmup*1000));
|
||||
if (demo || !latest?.online || !latest?.hasFrames || clients < 2) throw new Error('Native GUI and online real hardware video are required before starting the soak');
|
||||
if (!diagnostics) throw new Error('Receiver counters require referee diagnostics; team release mode hides them');
|
||||
measurementStarted = previousAt = performance.now();
|
||||
previousStats = latest;
|
||||
await writeFile(`${args.out}.windows.ndjson`, '');
|
||||
|
||||
function percentile(values, p) {
|
||||
if (!values.length) return null;
|
||||
const sorted = [...values].sort((a,b) => a-b);
|
||||
return Number(sorted[Math.floor((sorted.length-1)*p)].toFixed(3));
|
||||
}
|
||||
async function sample() {
|
||||
const now = performance.now();
|
||||
const elapsed = (now-previousAt)/1000;
|
||||
let complete = 0, dropped = 0;
|
||||
if (latest && previousStats) {
|
||||
if (latest.framesShown < previousStats.framesShown || latest.framesDropped < previousStats.framesDropped) counterResets++;
|
||||
else { complete = latest.framesShown-previousStats.framesShown; dropped = latest.framesDropped-previousStats.framesDropped; }
|
||||
}
|
||||
totalFrames += complete; totalDropped += dropped;
|
||||
const row = {
|
||||
utc:new Date().toISOString(), elapsedSeconds:(now-measurementStarted)/1000, windowSeconds:elapsed,
|
||||
completeFrames:complete, framesDropped:dropped, receiverFps:complete/elapsed,
|
||||
frameLossPercent:100*dropped/Math.max(1,complete+dropped),
|
||||
binaryFrames:windowBinary, channelFps:windowBinary/elapsed, invalidJpegs:windowInvalid,
|
||||
meanJpegBytes:windowBinary ? windowBytes/windowBinary : 0,
|
||||
gapP95Ms:percentile(gaps,.95), gapMaxMs:Math.max(0,...gaps, lastArrival===null ? (now-measurementStarted) : now-lastArrival),
|
||||
cameraOnline:latest?.online ?? false, frontendConnected:clients>=2, observerConnected:connected,
|
||||
};
|
||||
windows.push(row);
|
||||
await appendFile(`${args.out}.windows.ndjson`, JSON.stringify(row)+'\n');
|
||||
await writeFile(`${args.out}.latest.json`, JSON.stringify(row,null,2)+'\n');
|
||||
console.log(JSON.stringify(row));
|
||||
previousAt = now;
|
||||
previousStats = latest;
|
||||
windowBinary = windowInvalid = windowBytes = 0;
|
||||
gaps = [];
|
||||
}
|
||||
let stoppedByRequest = false;
|
||||
while ((performance.now()-measurementStarted)/1000 < seconds) {
|
||||
if (args['stop-file'] && await access(args['stop-file']).then(() => true, () => false)) {
|
||||
stoppedByRequest = true;
|
||||
break;
|
||||
}
|
||||
const remaining = seconds-(performance.now()-measurementStarted)/1000;
|
||||
await new Promise(resolve => setTimeout(resolve, Math.min(1,remaining)*1000));
|
||||
if (performance.now()-previousAt >= 60_000 || (performance.now()-measurementStarted)/1000 >= seconds) await sample();
|
||||
}
|
||||
if (stoppedByRequest && performance.now()-previousAt > 1_000) await sample();
|
||||
finished = true;
|
||||
ws.close();
|
||||
const actualSeconds = (performance.now()-measurementStarted)/1000;
|
||||
const receiverMetricsValid = counterResets === 0 && diagnosticsUnavailableSnapshots === 0;
|
||||
const summary = {
|
||||
actualSeconds, requestedSeconds:seconds, stoppedByRequest, warmupSeconds:warmup, camera, demo, windows, binaryFrames:binary,
|
||||
invalidJpegs:invalid, receiverMetricsValid,
|
||||
completeFrames:receiverMetricsValid ? totalFrames : null, framesDropped:receiverMetricsValid ? totalDropped : null,
|
||||
rawWindowCountedCompleteFrames:totalFrames, rawWindowCountedDroppedFrames:totalDropped,
|
||||
receiverFps:receiverMetricsValid ? totalFrames/actualSeconds : null, channelFps:binary/actualSeconds,
|
||||
frameLossPercent:receiverMetricsValid ? 100*totalDropped/Math.max(1,totalFrames+totalDropped) : null,
|
||||
gapP95Ms:percentile(allGaps,.95), gapMaxMs:Math.max(0,...allGaps),
|
||||
meanJpegBytes:binary ? bytes/binary : 0, counterResets, socketCloses,
|
||||
offlineSnapshots,
|
||||
diagnosticsUnavailableSnapshots,
|
||||
diagnosticSamplesSaved:sampleCount,
|
||||
allWindowsOnline:windows.every(window => window.cameraOnline),
|
||||
zeroVideoWindows:windows.filter(window => window.binaryFrames === 0).length,
|
||||
noVideoSecondsAtEnd:lastArrival === null ? actualSeconds : (performance.now()-lastArrival)/1000,
|
||||
maxObservedSilenceMs:Math.max(0,...windows.map(window => window.gapMaxMs)),
|
||||
frontendConnected:clients>=2,
|
||||
measurementScope:'Native receiver and local JPEG WebSocket channel; not optical display latency',
|
||||
};
|
||||
await writeFile(`${args.out}.summary.json`, JSON.stringify(summary,null,2)+'\n');
|
||||
if (firstFrame) await writeFile(`${args.out}.first.jpg`, firstFrame);
|
||||
console.log(JSON.stringify({ ...summary, windows:windows.length }));
|
||||
if (demo || !binary || invalid || socketCloses || counterResets || offlineSnapshots || diagnosticsUnavailableSnapshots) process.exitCode = 1;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { createRequire } from 'node:module';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source = readFileSync(new URL('../src/components/controls.tsx', import.meta.url), 'utf8');
|
||||
const compiled = ts.transpileModule(source, {
|
||||
fileName: 'controls.tsx',
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
|
||||
}).outputText;
|
||||
const controls = {};
|
||||
new Function('require', 'exports', compiled)(createRequire(import.meta.url), controls);
|
||||
const render = (value, options) => renderToStaticMarkup(createElement(controls.Select, { value, options, onChange() {} }));
|
||||
const online = [{ value: 42, label: '在线图传板' }];
|
||||
|
||||
test('a missing saved board remains explicitly selected instead of showing the first candidate', () => {
|
||||
const html = render(99, online);
|
||||
assert.match(html, /<option value="99" disabled="" selected="">当前选择未发现,请重新选择<\/option>/);
|
||||
assert.match(html, /<option value="42">在线图传板<\/option>/);
|
||||
});
|
||||
|
||||
test('a missing board remains visible when discovery is empty', () => {
|
||||
assert.match(render(99, []), /value="99" disabled="" selected=""/);
|
||||
});
|
||||
|
||||
test('a selected online board has no unavailable placeholder', () => {
|
||||
const html = render(42, online);
|
||||
assert.doesNotMatch(html, /当前选择未发现/);
|
||||
assert.match(html, /value="42" selected=""/);
|
||||
});
|
||||
|
||||
test('an unbound select keeps the empty placeholder selected', () => {
|
||||
assert.match(render(null, online), /value="" selected="">(未选择)/);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import {readFileSync} from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import {test} from 'node:test';
|
||||
import ts from 'typescript';
|
||||
const source=readFileSync(new URL('../src/lib/latency-marker.ts',import.meta.url),'utf8');
|
||||
const code=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const exports={};new Function('exports',code)(exports);
|
||||
const {drawMarker,decodeMarker}=exports;
|
||||
function image(counter,w=320,h=240) {
|
||||
const pixels=new Uint8ClampedArray(w*h*4);
|
||||
const ctx={canvas:{width:w,height:h},fillStyle:'',fillRect(x,y,width,height){
|
||||
const c=this.fillStyle.startsWith('rgb(')?this.fillStyle.slice(4,-1).split(',').map(Number):
|
||||
this.fillStyle==='#fff'?[255,255,255]:this.fillStyle==='#000'?[0,0,0]:[60,60,60];
|
||||
for(let yy=Math.max(0,Math.ceil(y));yy<Math.min(h,y+height);yy++)
|
||||
for(let xx=Math.max(0,Math.ceil(x));xx<Math.min(w,x+width);xx++)pixels.set([...c,255],(yy*w+xx)*4);
|
||||
}};
|
||||
drawMarker(ctx,counter);return pixels;
|
||||
}
|
||||
test('screen IDs decode at Gray-code boundaries and across counter wrap',()=>{
|
||||
for(const id of [0,1,2,3,63,127,1023,2047,2048,4094,4095,4096]) {
|
||||
assert.equal(decodeMarker(image(id),320,240)?.counter,id&4095);
|
||||
}
|
||||
});
|
||||
test('camera rotation and reflection preserve the observed ID',()=>{
|
||||
const original=image(1371),rotated=new Uint8ClampedArray(original.length),flipped=new Uint8ClampedArray(original.length);
|
||||
for(let y=0;y<240;y++)for(let x=0;x<320;x++){
|
||||
rotated.set(original.subarray((y*320+x)*4,(y*320+x)*4+4),(x*240+239-y)*4);
|
||||
flipped.set(original.subarray((y*320+x)*4,(y*320+x)*4+4),(y*320+319-x)*4);
|
||||
}
|
||||
assert.equal(decodeMarker(rotated,240,320)?.counter,1371);
|
||||
assert.equal(decodeMarker(flipped,320,240)?.counter,1371);
|
||||
});
|
||||
test('missing fiducials and ambiguous rolling transitions do not invent latency samples',()=>{
|
||||
assert.equal(decodeMarker(new Uint8ClampedArray(320*240*4),320,240),null);
|
||||
const pixels=image(123);
|
||||
for(let y=90;y<152;y++)for(let x=44;x<276;x++)pixels.set([128,128,128,255],(y*320+x)*4);
|
||||
assert.equal(decodeMarker(pixels,320,240),null);
|
||||
});
|
||||
|
||||
test('washed screen primaries survive without mistaking a blue-tinted background',()=>{
|
||||
const pixels=image(1371);
|
||||
for(let i=0;i<pixels.length;i+=4){
|
||||
const r=pixels[i],g=pixels[i+1],b=pixels[i+2];
|
||||
if(r===32&&g===255&&b===32)pixels.set([190,255,208,255],i);
|
||||
else if(r===32&&g===96&&b===255)pixels.set([78,205,255,255],i);
|
||||
else if(r===255&&g===32&&b===255)pixels.set([255,112,255,255],i);
|
||||
else if(r===60&&g===60&&b===60)pixels.set([165,181,225,255],i);
|
||||
}
|
||||
assert.equal(decodeMarker(pixels,320,240)?.counter,1371);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
// Exercise the production StreamClient against native hardware video, while
|
||||
// deliberately stalling only this auxiliary local consumer. Adds no UDP peer.
|
||||
// Bitmap decoding is stubbed here; actual JPEG decoding is checked separately.
|
||||
import {readFileSync,writeFileSync} from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import ts from 'typescript';
|
||||
|
||||
const [logPath,outPath]=process.argv.slice(2);
|
||||
if(!logPath||!outPath)throw new Error('Use <private native debug log> <result JSON>');
|
||||
const log=readFileSync(logPath,'utf8');
|
||||
const url=[...log.matchAll(/ws:\/\/127\.0\.0\.1:\d+\/\?token=[A-Za-z0-9_-]+/g)].at(-1)?.[0];
|
||||
if(!url)throw new Error('No local video URL in the private debug log');
|
||||
const source=readFileSync(new URL('../src/lib/stream.ts',import.meta.url),'utf8');
|
||||
const compiled=ts.transpileModule(source,{compilerOptions:{module:ts.ModuleKind.CommonJS,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const exports={};new Function('require','exports',compiled)(()=>({FRAME_HEADER_LEN:16}),exports);
|
||||
globalThis.window={setTimeout,clearTimeout};
|
||||
globalThis.createImageBitmap=async()=>({close(){}});
|
||||
const rx=new exports.StreamClient({onMessage(){},onConnection(){}});
|
||||
const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
||||
try {
|
||||
rx.connect(url);
|
||||
const deadline=performance.now()+10_000;
|
||||
while(rx.counters.frames<10&&performance.now()<deadline)await delay(30);
|
||||
assert.ok(rx.counters.frames>=10,'Real native JPEG video did not arrive');
|
||||
const camera=[...rx.frames.keys()][0];
|
||||
const before=rx.latest(camera)?.frameId;
|
||||
const staleBefore=rx.counters.staleFrames;
|
||||
const blockedAt=performance.now();
|
||||
while(performance.now()-blockedAt<350) { /* synthetic consumer stall */ }
|
||||
await delay(700);
|
||||
const latest=rx.latest(camera);
|
||||
assert.ok(rx.counters.staleFrames>staleBefore,'Stale native-timestamped frames were not rejected');
|
||||
assert.ok(latest&&latest.frameId!==before,'The consumer did not recover to new video');
|
||||
assert.ok(performance.now()-latest.receivedAt<150,'Recovered image is still stale locally');
|
||||
const result={passed:true,stall_ms:350,stale_frames_rejected:rx.counters.staleFrames-staleBefore,
|
||||
frame_before:before,frame_after:latest.frameId,frames_received:rx.counters.frames,
|
||||
additional_udp_subscribers:0,jpeg_decoder_stubbed:true,
|
||||
scope:'Production StreamClient over real native WebSocket; tests queued-frame age and recovery, not physical display latency'};
|
||||
writeFileSync(outPath,JSON.stringify(result,null,2)+'\n');
|
||||
console.log(JSON.stringify(result));
|
||||
} finally {rx.close();}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source = readFileSync(new URL('../src/lib/maintenance-safety.ts', import.meta.url), 'utf8');
|
||||
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
|
||||
const exports = {};
|
||||
new Function('exports', compiled)(exports);
|
||||
const { maintenanceMismatch: mismatch } = exports;
|
||||
const armor = { firmwareKind: 'armor', armorTeam: 1 };
|
||||
const camera = { firmwareKind: 'camera', armorTeam: null };
|
||||
|
||||
test('universal armor needs no build or flash team selection', () => {
|
||||
const universal = { firmwareKind: 'armor', armorTeam: null };
|
||||
assert.equal(mismatch('armor', '', { chip: 'esp32c3' }, universal), null);
|
||||
assert.equal(mismatch('armor', '0', { chip: 'esp32c3' }, universal), null);
|
||||
assert.equal(mismatch('armor', '1', { chip: 'esp32c3' }, universal), null);
|
||||
assert.ok(mismatch('camera', '', { chip: 'esp32s3' }, universal));
|
||||
});
|
||||
|
||||
test('requires an explicit board kind and armor team', () => {
|
||||
assert.ok(mismatch('', '', null, null));
|
||||
assert.ok(mismatch('armor', '', { chip: 'esp32c3' }, armor));
|
||||
assert.ok(mismatch('armor', '2', { chip: 'esp32c3' }, armor));
|
||||
});
|
||||
test('blocks crossed chips, product kinds and teams', () => {
|
||||
assert.ok(mismatch('armor', '1', { chip: 'esp32s3' }, armor));
|
||||
assert.ok(mismatch('camera', '', { chip: 'esp32c3' }, camera));
|
||||
assert.ok(mismatch('armor', '1', { chip: 'esp32c3' }, camera));
|
||||
assert.ok(mismatch('camera', '', { chip: 'esp32s3' }, armor));
|
||||
assert.ok(mismatch('armor', '0', { chip: 'esp32c3' }, armor));
|
||||
});
|
||||
test('accepts each matching board kind and the chosen armor team', () => {
|
||||
assert.equal(mismatch('armor', '1', { chip: 'esp32c3' }, armor), null);
|
||||
assert.equal(mismatch('camera', '', { chip: 'esp32s3' }, camera), null);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import ts from "typescript";
|
||||
const exports = {};
|
||||
new Function("exports", ts.transpileModule(readFileSync(new URL("../src/lib/match-time.ts", import.meta.url), "utf8"), {
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText)(exports);
|
||||
const { matchTime, projectMatch } = exports;
|
||||
const base = { phase: "running", remainingMs: 10_000, elapsedMs: 170_000, pauseElapsedMs: 0,
|
||||
pauseRemainingMs: null, connected: true, freshForMs: 500 };
|
||||
test("remaining time rounds up, elapsed time rounds down", () => {
|
||||
assert.equal(matchTime(1), "00:01"); assert.equal(matchTime(999, true), "00:00");
|
||||
assert.equal(matchTime(180_000), "03:00"); assert.equal(matchTime(-1), "00:00");
|
||||
});
|
||||
test("interpolation stops at the network lease boundary and backend outage freezes immediately", () => {
|
||||
const v = projectMatch(base, 5000, true);
|
||||
assert.equal(v.remainingMs, 9500); assert.equal(v.elapsedMs, 170_500); assert.equal(v.connected, false);
|
||||
assert.equal(projectMatch(base, 5000, false).remainingMs, 10_000);
|
||||
assert.equal(projectMatch({ ...base, connected: false }, 100, true).remainingMs, 10_000);
|
||||
});
|
||||
test("paused match freezes underlying clocks; player countdown expires without changing phase", () => {
|
||||
const v = projectMatch({ ...base, phase: "paused", pauseRemainingMs: 200, pauseElapsedMs: 299_800 }, 500, true);
|
||||
assert.equal(v.remainingMs, 10_000); assert.equal(v.elapsedMs, 170_000);
|
||||
assert.equal(v.pauseRemainingMs, 0); assert.equal(v.phase, "paused"); assert.equal(v.pauseElapsedMs, 300_300);
|
||||
assert.equal(projectMatch({ ...base, phase: "paused" }, 500, true).pauseRemainingMs, null);
|
||||
});
|
||||
test("the UI never starts a match or resumes a pause by interpolating", () => {
|
||||
const v = projectMatch({ ...base, phase: "countdown", remainingMs: 100 }, 500, true);
|
||||
assert.equal(v.remainingMs, 0); assert.equal(v.phase, "countdown"); assert.equal(v.elapsedMs, 170_000);
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createRequire } from "node:module";
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import ts from "typescript";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
function load(path, overrides) {
|
||||
const source = readFileSync(new URL(path, import.meta.url), "utf8");
|
||||
const compiled = ts.transpileModule(source, {
|
||||
fileName: path,
|
||||
compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.ReactJSX },
|
||||
}).outputText;
|
||||
const exports = {};
|
||||
new Function("require", "exports", compiled)(id => overrides[id] ?? require(id), exports);
|
||||
return exports;
|
||||
}
|
||||
|
||||
const format = { teamColor: team => team === 0 ? "red" : "blue", teamName: team => `队伍${team}`, idText: String, firmwareLabel: () => "测试固件" };
|
||||
const healthModule = load("../src/components/HealthBar.tsx", { "../lib/format": format });
|
||||
const videoModule = load("../src/components/VideoSurface.tsx", { "../lib/store": {}, "../lib/reticle": {} });
|
||||
let connected = true;
|
||||
const matchTime = load("../src/lib/match-time.ts", {});
|
||||
const matchModule = load("../src/components/MatchClock.tsx", {
|
||||
"./Dialog": {}, "../lib/ipc": {},
|
||||
"../lib/store": { useAppStore: () => ({ connected }) },
|
||||
"../lib/match-time": matchTime,
|
||||
});
|
||||
const { TeamPage } = load("../src/pages/TeamPage.tsx", {
|
||||
"../components/HealthBar": healthModule,
|
||||
"../components/VideoSurface": videoModule,
|
||||
"../components/HitFlash": { HitFlash: () => null },
|
||||
"../components/MatchBanner": { MatchBanner: () => null },
|
||||
"../components/MatchClock": matchModule,
|
||||
"../lib/format": format,
|
||||
"../lib/store": { useAppStore: () => ({ connected, lastHit: null }) },
|
||||
"../lib/version": { BUILD: { protocol: 1 } },
|
||||
});
|
||||
|
||||
const config = { visible: true, width: 0.42, pulse: false, lowThreshold: 31, showTeamName: true, showNumbers: true };
|
||||
const health = { team: 0, name: "测试队伍", available: true, hp: 100, placeholder: "装甲板未接入", critical: false };
|
||||
const renderHealth = (hp, align = "left", changes = {}) => renderToStaticMarkup(createElement(healthModule.HealthBar, {
|
||||
health: { ...health, hp, ...changes }, config, align,
|
||||
}));
|
||||
|
||||
test("health length follows every HP value continuously on both sides, including one HP and zero", () => {
|
||||
for (const align of ["left", "right"]) {
|
||||
for (const hp of [0, 1, 17, 19.5, 37, 99, 100, -3, 104]) {
|
||||
const html = renderHealth(hp, align);
|
||||
const expected = Math.max(0, Math.min(100, hp));
|
||||
assert.match(html, new RegExp(`class="hp__fill" style="width:${expected}%`));
|
||||
assert.doesNotMatch(html, /hp__cell/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("an unavailable armor board has an empty track and a missing-data label", () => {
|
||||
const html = renderHealth(75, "right", { available: false });
|
||||
assert.match(html, /hp__fill" style="width:0%/);
|
||||
assert.match(html, /装甲板未接入/);
|
||||
assert.doesNotMatch(html, /hp__value|hp__impact/);
|
||||
});
|
||||
|
||||
test("the low-health marker uses the exact threshold in the track's mirrored coordinates", () => {
|
||||
for (const align of ["left", "right"]) {
|
||||
assert.match(renderHealth(37, align), /hp__threshold" style="left:31%/);
|
||||
}
|
||||
});
|
||||
|
||||
function snapshot() {
|
||||
return {
|
||||
config: { cameraId: 1, armorId: 2, teamNames: ["我方", "对手"] },
|
||||
team: 0, mirrored: false, demo: false,
|
||||
cameras: [{ id: 1, idText: "1", online: true, compatible: true }],
|
||||
armorBoards: [{ id: 2, online: true, team: 0 }],
|
||||
stats: [{ camera: 1, online: true, hasFrames: true, fps: 20 }],
|
||||
matchClock: { phase: "running", remainingMs: 93_000, elapsedMs: 87_000, connected: true, freshForMs: 1500, source: "测试裁判" },
|
||||
health: [health, { ...health, team: 1 }],
|
||||
};
|
||||
}
|
||||
const renderTeam = value => renderToStaticMarkup(createElement(TeamPage, {
|
||||
snapshot: value, hud: { health: config, hitFeedback: {}, showZoom: false }, calibrating: false, onCalibrate() {},
|
||||
}));
|
||||
|
||||
test("health bars occupy the operator HUD's first row", () => {
|
||||
const html = renderTeam(snapshot());
|
||||
assert.ok(html.indexOf('class="cockpit__health"') < html.indexOf('class="cockpit__header"'));
|
||||
assert.ok(html.indexOf('class="hp hp--left') < html.indexOf('class="team-match-clock'));
|
||||
assert.ok(html.indexOf('class="team-match-clock') < html.indexOf('class="hp hp--right'));
|
||||
assert.doesNotMatch(html, /match-readout|match-countdown__number/);
|
||||
});
|
||||
|
||||
test("only the last five connected countdown seconds cover the operator view", () => {
|
||||
const value = snapshot();
|
||||
for (const [remainingMs, expected] of [[6000, null], [5000, 5], [4001, 5], [4000, 4], [1, 1], [0, null]]) {
|
||||
value.matchClock = { ...value.matchClock, phase: "countdown", remainingMs };
|
||||
const html = renderTeam(value);
|
||||
if (expected == null) assert.doesNotMatch(html, /aria-label="开赛全屏倒计时"/);
|
||||
else assert.match(html, new RegExp(`aria-atomic="true">${expected}</strong>`));
|
||||
}
|
||||
for (const phase of ["preparation", "ready", "running", "paused", "finished"]) {
|
||||
value.matchClock.phase = phase;
|
||||
value.matchClock.remainingMs = 4000;
|
||||
assert.doesNotMatch(renderTeam(value), /aria-label="开赛全屏倒计时"/);
|
||||
}
|
||||
value.matchClock.phase = "countdown";
|
||||
value.matchClock.connected = false;
|
||||
assert.doesNotMatch(renderTeam(value), /aria-label="开赛全屏倒计时"/);
|
||||
value.matchClock.connected = true;
|
||||
connected = false;
|
||||
assert.doesNotMatch(renderTeam(value), /aria-label="开赛全屏倒计时"/);
|
||||
connected = true;
|
||||
});
|
||||
|
||||
test("the last frame is masked for camera loss, backend loss, missing binding, or missing frames, and recovers", () => {
|
||||
const cases = [
|
||||
value => { value.cameras[0].online = false; },
|
||||
value => { value.stats[0].online = false; },
|
||||
value => { value.cameras[0].compatible = false; },
|
||||
value => { value.stats[0].hasFrames = false; },
|
||||
value => { value.config.cameraId = null; },
|
||||
value => { value.cameras = []; },
|
||||
() => { connected = false; },
|
||||
];
|
||||
for (const change of cases) {
|
||||
const value = snapshot();
|
||||
change(value);
|
||||
const lost = renderTeam(value);
|
||||
assert.match(lost, /vsurface--signal-lost/);
|
||||
assert.match(lost, /vsurface__signal-mask/);
|
||||
assert.match(lost, /<canvas/);
|
||||
connected = true;
|
||||
assert.doesNotMatch(renderTeam(snapshot()), /vsurface--signal-lost|vsurface__signal-mask/);
|
||||
}
|
||||
});
|
||||
|
||||
test("an armor outage alone does not gray the live video", () => {
|
||||
const value = snapshot();
|
||||
value.armorBoards[0].online = false;
|
||||
assert.doesNotMatch(renderTeam(value), /vsurface--signal-lost|vsurface__signal-mask/);
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
import ts from 'typescript';
|
||||
|
||||
const source = readFileSync(new URL('../src/lib/stream.ts', import.meta.url), 'utf8');
|
||||
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.ES2022 } }).outputText;
|
||||
const exports = {};
|
||||
new Function('require', 'exports', compiled)(name => {
|
||||
assert.equal(name, './types');
|
||||
return { FRAME_HEADER_LEN: 16 };
|
||||
}, exports);
|
||||
const { StreamClient } = exports;
|
||||
globalThis.window = { clearTimeout, setTimeout };
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
const bitmap = () => ({ closed: false, close() { this.closed = true; } });
|
||||
function frame(id, camera = 42) {
|
||||
const bytes = new ArrayBuffer(20);
|
||||
const header = new DataView(bytes);
|
||||
header.setUint32(0, camera, true);
|
||||
header.setUint32(4, id, true);
|
||||
header.setUint16(8, 640, true);
|
||||
header.setUint16(10, 480, true);
|
||||
header.setUint32(12, 4, true);
|
||||
return bytes;
|
||||
}
|
||||
function client(now, wallNow) { return new StreamClient({ onMessage() {}, onConnection() {} },now,wallNow); }
|
||||
function deferredDecoder() {
|
||||
const requests = [];
|
||||
globalThis.createImageBitmap = () => new Promise((resolve, reject) => requests.push({ resolve, reject }));
|
||||
return requests;
|
||||
}
|
||||
|
||||
test('a slow decoder keeps only the latest pending frame for each camera', async () => {
|
||||
const requests = deferredDecoder();
|
||||
const rx = client();
|
||||
const finished = rx.onBinary(frame(1));
|
||||
for (let id = 2; id <= 100; id++) await rx.onBinary(frame(id));
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(rx.pending.size, 1);
|
||||
const first = bitmap();
|
||||
requests[0].resolve(first);
|
||||
await tick();
|
||||
assert.equal(requests.length, 2);
|
||||
requests[1].resolve(bitmap());
|
||||
await finished;
|
||||
assert.equal(rx.latest(42).frameId, 100);
|
||||
assert.equal(rx.counters.skippedDecodes, 98);
|
||||
assert.equal(first.closed, true);
|
||||
rx.close();
|
||||
});
|
||||
|
||||
test('two cameras decode independently without queues growing behind either', async () => {
|
||||
const requests = deferredDecoder();
|
||||
const rx = client();
|
||||
const a = rx.onBinary(frame(1, 1));
|
||||
const b = rx.onBinary(frame(2, 2));
|
||||
assert.equal(requests.length, 2);
|
||||
requests[1].resolve(bitmap());
|
||||
await b;
|
||||
assert.equal(rx.latest(2).frameId, 2);
|
||||
assert.equal(rx.latest(1), undefined);
|
||||
requests[0].resolve(bitmap());
|
||||
await a;
|
||||
rx.close();
|
||||
});
|
||||
|
||||
test('closing during decode releases the late bitmap and discards pending work', async () => {
|
||||
const requests = deferredDecoder();
|
||||
const rx = client();
|
||||
const work = rx.onBinary(frame(1));
|
||||
await rx.onBinary(frame(2));
|
||||
rx.close();
|
||||
const late = bitmap();
|
||||
requests[0].resolve(late);
|
||||
await work;
|
||||
assert.equal(late.closed, true);
|
||||
assert.equal(requests.length, 1);
|
||||
assert.equal(rx.latest(42), undefined);
|
||||
});
|
||||
|
||||
test('a corrupt JPEG does not stop the next frame from being decoded', async () => {
|
||||
const requests = deferredDecoder();
|
||||
const rx = client();
|
||||
const work = rx.onBinary(frame(1));
|
||||
await rx.onBinary(frame(2));
|
||||
requests[0].reject(new Error('bad JPEG'));
|
||||
await tick();
|
||||
requests[1].resolve(bitmap());
|
||||
await work;
|
||||
assert.equal(rx.counters.decodeFailures, 1);
|
||||
assert.equal(rx.latest(42).frameId, 2);
|
||||
rx.close();
|
||||
});
|
||||
|
||||
test('late frames are rejected but a reboot after silence can restart the counter', () => {
|
||||
const rx = client();
|
||||
rx.injectFrame(42, 100, 640, 480, bitmap());
|
||||
const old = bitmap();
|
||||
rx.injectFrame(42, 99, 640, 480, old);
|
||||
assert.equal(old.closed, true);
|
||||
assert.equal(rx.latest(42).frameId, 100);
|
||||
rx.latest(42).receivedAt -= 2000;
|
||||
rx.injectFrame(42, 1, 640, 480, bitmap());
|
||||
assert.equal(rx.latest(42).frameId, 1);
|
||||
rx.close();
|
||||
});
|
||||
|
||||
test('a WebView backlog is discarded before JPEG decoding using native host timing', async () => {
|
||||
const requests = deferredDecoder();
|
||||
const rx = client(() => 0, () => 2000);
|
||||
rx.onTiming({camera:42,frameId:1,publishedUnixMs:1500});
|
||||
await rx.onBinary(frame(1));
|
||||
assert.equal(requests.length,0);
|
||||
assert.equal(rx.counters.staleFrames,1);
|
||||
rx.onTiming({camera:42,frameId:2,publishedUnixMs:2000});
|
||||
const work = rx.onBinary(frame(2));
|
||||
requests[0].resolve(bitmap());await work;
|
||||
assert.equal(rx.latest(42).frameId,2);
|
||||
rx.close();
|
||||
});
|
||||
|
||||
test('a blocked decoder releases its old result and resumes with the fresh pending frame', async () => {
|
||||
let clock=0;
|
||||
const requests=deferredDecoder(),rx=client(()=>clock);
|
||||
const work=rx.onBinary(frame(1));
|
||||
clock=110;await rx.onBinary(frame(2));
|
||||
const old=bitmap();requests[0].resolve(old);await tick();
|
||||
assert.equal(old.closed,true);
|
||||
assert.equal(rx.latest(42),undefined);
|
||||
requests[1].resolve(bitmap());await work;
|
||||
assert.equal(rx.latest(42).frameId,2);
|
||||
assert.equal(rx.counters.staleFrames,1);rx.close();
|
||||
});
|
||||
|
||||
test('pending frames that expired during a decoder stall never reach the decoder', async () => {
|
||||
let clock=0;
|
||||
const requests=deferredDecoder(),rx=client(()=>clock);
|
||||
const work=rx.onBinary(frame(1));await rx.onBinary(frame(2));
|
||||
clock=200;const old=bitmap();requests[0].resolve(old);await work;
|
||||
assert.equal(old.closed,true);assert.equal(requests.length,1);
|
||||
assert.equal(rx.counters.staleFrames,2);assert.equal(rx.latest(42),undefined);rx.close();
|
||||
});
|
||||
@@ -0,0 +1,158 @@
|
||||
# Integration regression: actual Windows labels, child process tokens, and an
|
||||
# NSIS bootstrap that writes to TEMP and exits without installing anything.
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$NsisCompiler = (Join-Path $env:LOCALAPPDATA 'tauri/NSIS/makensis.exe')
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
Set-StrictMode -Version Latest
|
||||
$prepare = Join-Path $PSScriptRoot 'prepare-windows-bundle.ps1'
|
||||
& $prepare -CheckProcessOnly
|
||||
if (-not (Test-Path -LiteralPath $NsisCompiler)) { throw "NSIS compiler not found: $NsisCompiler" }
|
||||
|
||||
function Assert([bool]$Condition, [string]$Message) {
|
||||
if (-not $Condition) { throw $Message }
|
||||
}
|
||||
|
||||
$testId = [Guid]::NewGuid().ToString('N')
|
||||
$tempRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
|
||||
$fixture = Join-Path $tempRoot "rmic bundle test $testId"
|
||||
$probeFile = Join-Path $tempRoot "rmic-nsis-temp-$testId.txt"
|
||||
$installer = Join-Path $fixture 'bundle/nsis/probe-setup.exe'
|
||||
$main = Join-Path $fixture 'cam-desktop.exe'
|
||||
try {
|
||||
New-Item -ItemType Directory -Force -Path (Join-Path $fixture 'bundle/nsis'), (Join-Path $fixture 'nsis/x64') | Out-Null
|
||||
Copy-Item -LiteralPath (Join-Path $env:WINDIR 'System32/whoami.exe') -Destination $main
|
||||
$accessBefore = (Get-Acl -LiteralPath $main).Sddl
|
||||
|
||||
# A small real NSIS executable exercises its early TEMP validation and
|
||||
# plugin extraction without touching app files, registry, or shortcuts.
|
||||
$source = Join-Path $fixture 'probe.nsi'
|
||||
@"
|
||||
Unicode true
|
||||
Name "RMIC temporary directory probe"
|
||||
OutFile "$($installer.Replace('$', '$$'))"
|
||||
RequestExecutionLevel user
|
||||
SilentInstall silent
|
||||
Section
|
||||
InitPluginsDir
|
||||
FileOpen `$0 "`$TEMP\rmic-nsis-temp-$testId.txt" w
|
||||
IfErrors failed
|
||||
FileWrite `$0 "NSIS TEMP writable"
|
||||
FileClose `$0
|
||||
SetErrorLevel 0
|
||||
Quit
|
||||
failed:
|
||||
SetErrorLevel 3
|
||||
SectionEnd
|
||||
"@ | Set-Content -LiteralPath $source -Encoding UTF8
|
||||
& $NsisCompiler /V2 $source
|
||||
Assert ($LASTEXITCODE -eq 0) 'Cannot compile the NSIS TEMP probe.'
|
||||
|
||||
& icacls.exe $fixture /setintegritylevel '(OI)(CI)L' | Out-Null
|
||||
Assert ($LASTEXITCODE -eq 0) 'Cannot create a Low integrity fixture.'
|
||||
& icacls.exe $main /setintegritylevel L | Out-Null
|
||||
Assert ($LASTEXITCODE -eq 0) 'Cannot create an explicit Low executable label.'
|
||||
$before = (& $main /groups) -join "`n"
|
||||
Assert ($LASTEXITCODE -eq 0 -and $before -match 'S-1-16-4096') 'Low executable did not start with a Low token.'
|
||||
|
||||
$rejected = $false
|
||||
try { & $prepare -OutputDir $fixture -CheckOnly } catch {
|
||||
if ($_.Exception.Message -notmatch 'Low / Untrusted') { throw }
|
||||
$rejected = $true
|
||||
}
|
||||
Assert $rejected 'Read-only artifact verification accepted a Low label.'
|
||||
Assert ([RmicBundleIntegrity]::ReadLabel($installer) -match ';LW\)') 'Read-only verification changed the installer.'
|
||||
|
||||
# A Low process must fail before it tries to modify any output labels.
|
||||
$lowShell = Join-Path $fixture 'low-shell.exe'
|
||||
Copy-Item -LiteralPath (Join-Path $env:WINDIR 'System32/WindowsPowerShell/v1.0/powershell.exe') -Destination $lowShell
|
||||
# Windows PowerShell 5 treats redirected native stderr as ErrorRecord objects.
|
||||
# This command is expected to fail, so collect its diagnostic before asserting.
|
||||
try {
|
||||
$ErrorActionPreference = 'Continue'
|
||||
$lowOutput = (& $lowShell -NoProfile -ExecutionPolicy Bypass -File $prepare -CheckProcessOnly 2>&1) -join "`n"
|
||||
} finally {
|
||||
$ErrorActionPreference = 'Stop'
|
||||
}
|
||||
Assert ($LASTEXITCODE -ne 0 -and $lowOutput -match 'requires Medium integrity') 'Low packaging process was not rejected.'
|
||||
|
||||
& $prepare -OutputDir $fixture
|
||||
& $prepare -OutputDir $fixture -CheckOnly
|
||||
& $prepare -OutputDir $fixture
|
||||
$after = (& $main /groups) -join "`n"
|
||||
Assert ($LASTEXITCODE -eq 0 -and $after -match 'S-1-16-(\d+)' -and [int]$Matches[1] -ge 8192) 'Repaired executable still starts below Medium integrity.'
|
||||
Assert ((Get-Acl -LiteralPath $main).Sddl -eq $accessBefore) 'Repair changed the executable DACL.'
|
||||
|
||||
# The repaired shell now starts at Medium even from an elevated test runner.
|
||||
# Verify that repairing owned Low outputs does not require elevation.
|
||||
$mediumFixture = Join-Path $fixture 'medium repair'
|
||||
New-Item -ItemType Directory -Path $mediumFixture | Out-Null
|
||||
& icacls.exe $mediumFixture /setintegritylevel '(OI)(CI)L' | Out-Null
|
||||
Assert ($LASTEXITCODE -eq 0) 'Cannot prepare the Medium-process repair fixture.'
|
||||
$mediumOutput = (& $lowShell -NoProfile -ExecutionPolicy Bypass -File $prepare -OutputDir $mediumFixture 2>&1) -join "`n"
|
||||
Assert ($LASTEXITCODE -eq 0) "Repair failed at Medium integrity: $mediumOutput"
|
||||
Assert ([RmicBundleIntegrity]::ReadLabel($mediumFixture) -match ';ME\)') 'Medium process did not repair the output label.'
|
||||
|
||||
$probe = Start-Process -FilePath $installer -ArgumentList '/S' -PassThru -WindowStyle Hidden
|
||||
try {
|
||||
Assert ($probe.WaitForExit(15000)) 'NSIS TEMP probe timed out.'
|
||||
Assert ($probe.ExitCode -eq 0) "NSIS TEMP probe failed: $($probe.ExitCode)"
|
||||
Assert ((Get-Content -LiteralPath $probeFile -Raw) -eq 'NSIS TEMP writable') 'NSIS could not write to the normal TEMP directory.'
|
||||
} finally {
|
||||
if (-not $probe.HasExited) { $probe.Kill(); $probe.WaitForExit() }
|
||||
$probe.Dispose()
|
||||
}
|
||||
|
||||
$emptyOutput = Join-Path $fixture 'empty'
|
||||
& $prepare -OutputDir $emptyOutput
|
||||
$rejected = $false
|
||||
try { & $prepare -OutputDir $emptyOutput -CheckOnly } catch {
|
||||
if ($_.Exception.Message -notmatch 'No NSIS installer') { throw }
|
||||
$rejected = $true
|
||||
}
|
||||
Assert $rejected 'Artifact verification accepted missing installers.'
|
||||
|
||||
# Exercise automatic Cargo output discovery, debug target selection and the
|
||||
# separate host build-script directory, without invoking a real Rust build.
|
||||
$savedEnvironment = @{}
|
||||
foreach ($name in @('CARGO_TARGET_DIR', 'TAURI_ENV_TARGET_TRIPLE', 'TAURI_ENV_DEBUG')) {
|
||||
$savedEnvironment[$name] = @{
|
||||
Exists = Test-Path -LiteralPath "Env:$name"
|
||||
Value = [Environment]::GetEnvironmentVariable($name, 'Process')
|
||||
}
|
||||
}
|
||||
try {
|
||||
$env:CARGO_TARGET_DIR = Join-Path $fixture 'cargo cache'
|
||||
$env:TAURI_ENV_TARGET_TRIPLE = 'x86_64-pc-windows-msvc'
|
||||
$env:TAURI_ENV_DEBUG = 'true'
|
||||
$hostBuildDir = Join-Path $env:CARGO_TARGET_DIR 'debug/build/probe'
|
||||
New-Item -ItemType Directory -Force -Path $hostBuildDir | Out-Null
|
||||
$hostScript = Join-Path $hostBuildDir 'build-script-build.exe'
|
||||
Copy-Item -LiteralPath $main -Destination $hostScript
|
||||
& icacls.exe $env:CARGO_TARGET_DIR /setintegritylevel '(OI)(CI)L' | Out-Null
|
||||
Assert ($LASTEXITCODE -eq 0) 'Cannot create Low host build outputs.'
|
||||
& $prepare
|
||||
Assert ([RmicBundleIntegrity]::ReadLabel($hostScript) -match ';ME\)') 'Host build script was not repaired.'
|
||||
$targetOutput = Join-Path $env:CARGO_TARGET_DIR 'x86_64-pc-windows-msvc/debug/bundle/nsis'
|
||||
Assert (Test-Path -LiteralPath $targetOutput) 'Cargo target directory or debug profile was ignored.'
|
||||
} finally {
|
||||
foreach ($name in $savedEnvironment.Keys) {
|
||||
if ($savedEnvironment[$name].Exists) {
|
||||
Set-Item -LiteralPath "Env:$name" -Value $savedEnvironment[$name].Value
|
||||
} else {
|
||||
Remove-Item -LiteralPath "Env:$name" -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
}
|
||||
Write-Host 'PASS: Low token reproduction, process guard, read-only rejection, label repair, unchanged DACL, repeat repair, NSIS TEMP bootstrap, missing artifacts, custom Cargo output and host build scripts.'
|
||||
} finally {
|
||||
# Only delete this test's uniquely named fixture, after checking its absolute path.
|
||||
$resolvedFixture = [IO.Path]::GetFullPath($fixture)
|
||||
if ($resolvedFixture.StartsWith($tempRoot.TrimEnd('\') + '\', [StringComparison]::OrdinalIgnoreCase) -and
|
||||
(Split-Path -Leaf $resolvedFixture) -eq "rmic bundle test $testId") {
|
||||
if (Test-Path -LiteralPath $resolvedFixture) { Remove-Item -LiteralPath $resolvedFixture -Recurse -Force }
|
||||
}
|
||||
if (Test-Path -LiteralPath $probeFile) { Remove-Item -LiteralPath $probeFile -Force }
|
||||
}
|
||||
Reference in new issue
Block a user