mirror of
https://github.com/zxsos/HGhubX
synced 2026-11-26 22:27:53 +08:00
ci,test,docs: unify CI/CD into single workflow, trim regression suite, and finalize v2.2.0 docs
This commit is contained in:
58 files changed
+1785
-2926
No files matched your search
@@ -1,162 +0,0 @@
|
||||
name: Android package
|
||||
|
||||
# Shared Android build used twice by Release: the normal app and the standalone
|
||||
# HGhubX TV app. Keeping one implementation prevents the two packages drifting.
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
edition:
|
||||
description: "standard or tv"
|
||||
required: true
|
||||
type: string
|
||||
platforms:
|
||||
description: "Caller's build scope"
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
quick:
|
||||
description: "Use the quick release profile"
|
||||
required: false
|
||||
type: boolean
|
||||
default: false
|
||||
tag:
|
||||
description: "Optional release tag"
|
||||
required: false
|
||||
type: string
|
||||
default: ""
|
||||
secrets:
|
||||
ANDROID_KEY_BASE64:
|
||||
required: true
|
||||
ANDROID_KEY_ALIAS:
|
||||
required: true
|
||||
ANDROID_KEYSTORE_PASSWORD:
|
||||
required: true
|
||||
ANDROID_KEY_PASSWORD:
|
||||
required: true
|
||||
|
||||
env:
|
||||
CI: "true"
|
||||
|
||||
jobs:
|
||||
android:
|
||||
name: Android ${{ inputs.edition == 'tv' && 'TV' || 'standard' }} (split per ABI)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "${{ inputs.tag }}" ]]; then
|
||||
V="${{ inputs.tag }}"
|
||||
V="${V#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "17"
|
||||
|
||||
- name: 准备 Android SDK / NDK
|
||||
run: |
|
||||
SDK="${ANDROID_HOME:-/usr/local/lib/android/sdk}"
|
||||
echo "ANDROID_HOME=$SDK" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> "$GITHUB_ENV"
|
||||
SDKM="$SDK/cmdline-tools/latest/bin/sdkmanager"
|
||||
yes | "$SDKM" --licenses > /dev/null 2>&1 || true
|
||||
"$SDKM" --install "platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358"
|
||||
echo "NDK_HOME=$SDK/ndk/28.2.13676358" >> "$GITHUB_ENV"
|
||||
ls "$SDK/ndk"
|
||||
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: android-${{ inputs.edition }}
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 选择 Android TV 配置
|
||||
if: inputs.edition == 'tv'
|
||||
run: cp src-tauri/tauri.tv.conf.json src-tauri/tauri.android.conf.json
|
||||
|
||||
- name: 生成 Android 工程
|
||||
run: pnpm tauri android init --ci
|
||||
|
||||
- name: 编译 APK(按 ABI 分包)
|
||||
run: |
|
||||
if [ "${{ inputs.quick }}" = "true" ] || [ "${{ inputs.platforms }}" = "android-arm64" ]; then
|
||||
TARGETS="aarch64"
|
||||
else
|
||||
TARGETS="aarch64 armv7 x86_64"
|
||||
fi
|
||||
echo "targets: $TARGETS"
|
||||
pnpm tauri android build --apk --split-per-abi --target $TARGETS
|
||||
|
||||
- name: 签名 APK
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.ANDROID_KEY_BASE64 }}
|
||||
KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${KEYSTORE_BASE64:-}" ]; then
|
||||
echo "::error::缺少 ANDROID_KEY_BASE64 secret,无法签名"; exit 1
|
||||
fi
|
||||
if [ "${{ inputs.edition }}" = "tv" ]; then PREFIX="HGhubX-TV"; else PREFIX="HGhubX"; fi
|
||||
KS="$RUNNER_TEMP/release.keystore"
|
||||
echo "$KEYSTORE_BASE64" | base64 -d > "$KS"
|
||||
BT="$(ls "$ANDROID_SDK_ROOT/build-tools" | sort -V | tail -1)"
|
||||
APKSIGNER="$ANDROID_SDK_ROOT/build-tools/$BT/apksigner"
|
||||
mkdir -p artifacts
|
||||
found=0
|
||||
for f in $(find src-tauri/gen/android/app/build/outputs/apk -name '*-release*.apk'); do
|
||||
abi="$(basename "$(dirname "$(dirname "$f")")")"
|
||||
out="artifacts/${PREFIX}_${VERSION}_${abi}.apk"
|
||||
"$APKSIGNER" sign \
|
||||
--ks "$KS" --ks-key-alias "$KEY_ALIAS" \
|
||||
--ks-pass "pass:$STORE_PASSWORD" --key-pass "pass:$KEY_PASSWORD" \
|
||||
--v4-signing-enabled false \
|
||||
--out "$out" "$f"
|
||||
"$APKSIGNER" verify --print-certs "$out" | head -3
|
||||
found=$((found+1))
|
||||
done
|
||||
rm -f "$KS"
|
||||
if [ "$found" -eq 0 ]; then echo "::error::没有找到 release APK"; exit 1; fi
|
||||
AAPT2="$(ls "$ANDROID_SDK_ROOT"/build-tools/*/aapt2 | sort -V | tail -1)"
|
||||
for a in artifacts/*.apk; do "$AAPT2" dump badging "$a" | grep -m1 "^package:"; done
|
||||
ls -lh artifacts
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ inputs.edition == 'tv' && 'android-tv' || 'android' }}
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
@@ -1,60 +0,0 @@
|
||||
name: iOS check (unsigned ipa)
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
ios:
|
||||
name: iOS build only
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
env:
|
||||
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-ios,aarch64-apple-ios-sim
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: ios
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 生成 iOS 工程(带横竖屏 + ATS)
|
||||
run: |
|
||||
pnpm tauri ios init --ci
|
||||
for plist in $(find src-tauri/gen/apple -name "Info.plist" 2>/dev/null); do
|
||||
for key in "UISupportedInterfaceOrientations" "UISupportedInterfaceOrientations~iphone" "UISupportedInterfaceOrientations~ipad"; do
|
||||
/usr/libexec/PlistBuddy -c "Delete :${key}" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :${key} array" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:0 string UIInterfaceOrientationPortrait" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:1 string UIInterfaceOrientationLandscapeLeft" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:2 string UIInterfaceOrientationLandscapeRight" "$plist"
|
||||
done
|
||||
/usr/libexec/PlistBuddy -c "Delete :NSAppTransportSecurity" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity dict" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity:NSAllowsArbitraryLoads bool true" "$plist"
|
||||
done
|
||||
|
||||
- name: 构建并打包 ipa
|
||||
shell: bash
|
||||
env:
|
||||
APP_VERSION: ${{ github.run_number }}
|
||||
run: bash scripts/build-ios-unsigned.sh "$APP_VERSION"
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ios
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
+639
-31
@@ -1,47 +1,80 @@
|
||||
name: CI
|
||||
name: CI/CD
|
||||
|
||||
# 统一工作流:日常 PR/push 跑全量校验(前端 + Rust + Smoke + 播放/TV 诊断),
|
||||
# 打 v* tag 或手动选择 mode=package 时按平台出包并发布 GitHub Release,每次触发仅产生一条工作流记录。
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ["v*"]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
mode:
|
||||
description: "运行模式:ci 跑全量校验;playback 只跑播放/TV 诊断;package 打安装包(配合 tag 发版)"
|
||||
type: choice
|
||||
default: ci
|
||||
options: [ci, playback, package]
|
||||
platforms:
|
||||
description: "打包范围(仅 mode=package 生效):all 全平台(含 TV),或指定单一平台"
|
||||
type: choice
|
||||
default: all
|
||||
options: [all, android-arm64, android, android-tv, linux, windows, macos, ios]
|
||||
quick:
|
||||
description: "快速编译(仅 mode=package 生效):thin LTO + 4 个 codegen 单元,快一倍"
|
||||
type: boolean
|
||||
default: true
|
||||
tag:
|
||||
description: "发版 tag(仅 mode=package 生效,如 v2.2.0):配合 platforms=all 且 quick=false 发布 Release;留空只出产物"
|
||||
type: string
|
||||
default: ""
|
||||
prerelease:
|
||||
description: "标记为 Pre-release(预发布,不出正式版)"
|
||||
type: boolean
|
||||
default: false
|
||||
scenarios:
|
||||
description: "播放诊断场景(mode=ci/playback 生效):all 或逗号分隔子集"
|
||||
type: string
|
||||
default: all
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
group: cicd-${{ github.ref }}-${{ github.event_name }}-${{ (startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch') && github.run_id || 'branch' }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/v') && (github.event_name != 'workflow_dispatch' || inputs.tag == '') }}
|
||||
|
||||
env:
|
||||
CI: "true"
|
||||
|
||||
jobs:
|
||||
# ================= 日常 CI 与播放/TV 诊断 =================
|
||||
frontend:
|
||||
name: Frontend build
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
if: >-
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/v')) ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'ci')
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Version fields
|
||||
run: node scripts/check-version-sync.mjs
|
||||
|
||||
- name: Documentation links
|
||||
run: node scripts/check-doc-links.mjs
|
||||
|
||||
- name: Build frontend
|
||||
run: pnpm build
|
||||
|
||||
- name: Build frontend (standard & TV)
|
||||
run: |
|
||||
VITE_APP_EDITION=tv pnpm build
|
||||
pnpm build
|
||||
- name: Size budgets
|
||||
run: node scripts/check-size-budgets.mjs
|
||||
|
||||
@@ -49,27 +82,57 @@ jobs:
|
||||
name: Rust check and test
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 30
|
||||
if: >-
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/v')) ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'ci')
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Cache Linux WebKitGTK .deb packages
|
||||
id: apt-cache
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/apt-webkit-debs
|
||||
key: apt-webkit-ubuntu24-v1
|
||||
- name: Install system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev patchelf build-essential curl wget file libssl-dev libxdo-dev
|
||||
|
||||
install_from_mirror() {
|
||||
mkdir -p ~/apt-webkit-debs
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sudo find /etc/apt/sources.list.d -maxdepth 1 -type f ! -name 'ubuntu.sources' -delete
|
||||
printf 'https://mirrors.edge.kernel.org/ubuntu/\nhttp://archive.ubuntu.com/ubuntu/\n' | sudo tee /etc/apt/apt-mirrors.txt >/dev/null
|
||||
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
|
||||
sudo sed -i -E 's|^URIs:.*|URIs: https://mirrors.edge.kernel.org/ubuntu/|g' /etc/apt/sources.list.d/ubuntu.sources
|
||||
fi
|
||||
if [ -f /etc/apt/sources.list ]; then
|
||||
sudo sed -i -E 's|https?://[^/[:space:]]+/ubuntu/?|https://mirrors.edge.kernel.org/ubuntu/|g' /etc/apt/sources.list
|
||||
fi
|
||||
sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 update
|
||||
sudo apt-get -o Dir::Cache::archives="$HOME/apt-webkit-debs" -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 \
|
||||
install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev patchelf build-essential curl wget file libssl-dev libxdo-dev
|
||||
sudo rm -rf ~/apt-webkit-debs/lock ~/apt-webkit-debs/partial 2>/dev/null || true
|
||||
sudo chown -R "$USER:$USER" ~/apt-webkit-debs
|
||||
}
|
||||
if [ "${{ steps.apt-cache.outputs.cache-hit }}" = "true" ] && compgen -G "$HOME/apt-webkit-debs/*.deb" >/dev/null; then
|
||||
echo "Installing WebKitGTK dependencies from cached .deb packages..."
|
||||
if ! (sudo dpkg --unpack ~/apt-webkit-debs/*.deb && sudo dpkg --configure -a); then
|
||||
sudo apt-get -f install -y || true
|
||||
rm -rf ~/apt-webkit-debs/*
|
||||
install_from_mirror
|
||||
fi
|
||||
else
|
||||
install_from_mirror
|
||||
fi
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: ci-rust
|
||||
|
||||
- name: Cargo check
|
||||
working-directory: src-tauri
|
||||
run: cargo check --all-targets
|
||||
|
||||
- name: Cargo test
|
||||
working-directory: src-tauri
|
||||
run: cargo test --lib
|
||||
@@ -78,28 +141,573 @@ jobs:
|
||||
name: Browser smoke
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 20
|
||||
if: >-
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/v')) ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'ci')
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Install Chromium
|
||||
run: pnpm exec playwright-core install --with-deps chromium
|
||||
|
||||
- name: Resolve Chromium
|
||||
- name: Resolve pre-installed Chrome (or fallback to Playwright Chromium)
|
||||
run: |
|
||||
BROWSER="$(node --input-type=module -e "import { chromium } from 'playwright-core'; console.log(chromium.executablePath())")"
|
||||
if [ -x /usr/bin/google-chrome ]; then
|
||||
BROWSER="/usr/bin/google-chrome"
|
||||
else
|
||||
pnpm exec playwright-core install --with-deps chromium
|
||||
BROWSER="$(node --input-type=module -e "import { chromium } from 'playwright-core'; console.log(chromium.executablePath())")"
|
||||
fi
|
||||
echo "Using browser: $BROWSER"
|
||||
echo "BROWSER_EXECUTABLE=$BROWSER" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Run smoke fixtures
|
||||
run: pnpm test:smoke
|
||||
|
||||
playback:
|
||||
name: Playback (${{ matrix.shard }})
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 15
|
||||
if: >-
|
||||
github.event_name == 'pull_request' ||
|
||||
(github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/v')) ||
|
||||
(github.event_name == 'workflow_dispatch' && (inputs.mode == 'ci' || inputs.mode == 'playback'))
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix: >-
|
||||
${{
|
||||
(inputs.scenarios == '' || inputs.scenarios == 'all') &&
|
||||
fromJSON('{"include":[{"shard":"core","scenarios":"seek,legacy,lifecycle,gesture,proxy,portrait-fit"},{"shard":"extended","scenarios":"ios-native,recovery,review,tv"}]}') ||
|
||||
fromJSON(format('{{"include":[{{"shard":"custom","scenarios":{0}}}]}}', toJSON(inputs.scenarios)))
|
||||
}}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Resolve pre-installed FFmpeg & Chrome
|
||||
run: |
|
||||
if ! command -v ffmpeg >/dev/null 2>&1; then
|
||||
sudo find /etc/apt/sources.list.d -maxdepth 1 -type f ! -name 'ubuntu.sources' -delete
|
||||
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
|
||||
sudo sed -i -E 's|^URIs:.*|URIs: https://mirrors.edge.kernel.org/ubuntu/|g' /etc/apt/sources.list.d/ubuntu.sources
|
||||
fi
|
||||
sudo apt-get update && sudo apt-get install -y --no-install-recommends ffmpeg
|
||||
fi
|
||||
if [ -x /usr/bin/google-chrome ]; then
|
||||
BROWSER="/usr/bin/google-chrome"
|
||||
else
|
||||
pnpm exec playwright-core install --with-deps chromium
|
||||
BROWSER="$(node --input-type=module -e "import { chromium } from 'playwright-core'; console.log(chromium.executablePath())")"
|
||||
fi
|
||||
echo "Using browser: $BROWSER, ffmpeg: $(command -v ffmpeg)"
|
||||
echo "BROWSER_EXECUTABLE=$BROWSER" >> "$GITHUB_ENV"
|
||||
- name: Run playback checks and collect diagnostics
|
||||
env:
|
||||
PLAYBACK_SCENARIOS: ${{ matrix.scenarios }}
|
||||
run: pnpm test:playback --browser-executable "$BROWSER_EXECUTABLE" --scenarios "$PLAYBACK_SCENARIOS" --output test-results/playback-ci
|
||||
- name: Upload diagnostics even when a check fails
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: playback-diagnostics-${{ matrix.shard }}
|
||||
path: test-results/
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
|
||||
# ================= 平台构建与发布(仅 tag 或 mode=package 触发) =================
|
||||
windows:
|
||||
name: Windows (setup + portable)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' &&
|
||||
(inputs.platforms == 'all' || inputs.platforms == 'windows'))
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "$INPUT_TAG" ]]; then
|
||||
V="${INPUT_TAG#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: 构建(NSIS 安装包)
|
||||
run: pnpm tauri build --bundles nsis
|
||||
- name: 收集产物(安装包 + 便携包)
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = "${{ steps.ver.outputs.version }}"
|
||||
New-Item -ItemType Directory -Force artifacts | Out-Null
|
||||
Copy-Item "src-tauri/target/release/bundle/nsis/*.exe" artifacts/
|
||||
$bin = "src-tauri/target/release/hghubx.exe"
|
||||
if (-not (Test-Path $bin)) {
|
||||
$bin = (Get-ChildItem "src-tauri/target/release" -Filter *.exe | Select-Object -First 1).FullName
|
||||
}
|
||||
Copy-Item $bin "artifacts/HGhubX.exe"
|
||||
Compress-Archive -Path "artifacts/HGhubX.exe" -DestinationPath "artifacts/HGhubX_${v}_x64_portable.zip" -Force
|
||||
Remove-Item "artifacts/HGhubX.exe"
|
||||
Get-ChildItem artifacts | Select-Object Name, Length
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: windows
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
android:
|
||||
name: Android ${{ matrix.edition == 'tv' && 'TV' || 'standard' }} (split per ABI)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' &&
|
||||
(inputs.platforms == 'all' || inputs.platforms == 'android' || inputs.platforms == 'android-arm64' || inputs.platforms == 'android-tv'))
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
edition: >-
|
||||
${{
|
||||
(github.event_name == 'workflow_dispatch' && inputs.platforms == 'android-tv') && fromJSON('["tv"]') ||
|
||||
(github.event_name == 'workflow_dispatch' && (inputs.platforms == 'android' || inputs.platforms == 'android-arm64')) && fromJSON('["standard"]') ||
|
||||
fromJSON('["standard", "tv"]')
|
||||
}}
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "$INPUT_TAG" ]]; then
|
||||
V="${INPUT_TAG#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: actions/setup-java@v6
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: "17"
|
||||
- name: 准备 Android SDK / NDK
|
||||
run: |
|
||||
SDK="${ANDROID_HOME:-/usr/local/lib/android/sdk}"
|
||||
echo "ANDROID_HOME=$SDK" >> "$GITHUB_ENV"
|
||||
echo "ANDROID_SDK_ROOT=$SDK" >> "$GITHUB_ENV"
|
||||
SDKM="$SDK/cmdline-tools/latest/bin/sdkmanager"
|
||||
yes | "$SDKM" --licenses > /dev/null 2>&1 || true
|
||||
"$SDKM" --install "platform-tools" "platforms;android-36" "build-tools;36.0.0" "ndk;28.2.13676358"
|
||||
echo "NDK_HOME=$SDK/ndk/28.2.13676358" >> "$GITHUB_ENV"
|
||||
ls "$SDK/ndk"
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-linux-android,armv7-linux-androideabi,x86_64-linux-android
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: android-${{ matrix.edition }}
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: 选择 Android TV 配置
|
||||
if: matrix.edition == 'tv'
|
||||
run: cp src-tauri/tauri.tv.conf.json src-tauri/tauri.android.conf.json
|
||||
- name: 生成 Android 工程
|
||||
run: pnpm tauri android init --ci
|
||||
- name: 编译 APK(按 ABI 分包)
|
||||
run: |
|
||||
if [ "${{ inputs.platforms }}" = "android-arm64" ]; then
|
||||
TARGETS="aarch64"
|
||||
elif [ "${{ inputs.quick }}" = "true" ]; then
|
||||
TARGETS="aarch64 armv7"
|
||||
else
|
||||
TARGETS="aarch64 armv7 x86_64"
|
||||
fi
|
||||
echo "targets: $TARGETS"
|
||||
pnpm tauri android build --apk --split-per-abi --target $TARGETS
|
||||
- name: 签名 APK
|
||||
env:
|
||||
KEYSTORE_BASE64: ${{ secrets.ANDROID_KEY_BASE64 }}
|
||||
KEY_ALIAS: ${{ secrets.ANDROID_KEY_ALIAS }}
|
||||
STORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }}
|
||||
KEY_PASSWORD: ${{ secrets.ANDROID_KEY_PASSWORD }}
|
||||
VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -z "${KEYSTORE_BASE64:-}" ]; then
|
||||
echo "::error::缺少 ANDROID_KEY_BASE64 secret,无法签名"; exit 1
|
||||
fi
|
||||
if [ "${{ matrix.edition }}" = "tv" ]; then PREFIX="HGhubX-TV"; else PREFIX="HGhubX"; fi
|
||||
KS="$RUNNER_TEMP/release.keystore"
|
||||
echo "$KEYSTORE_BASE64" | base64 -d > "$KS"
|
||||
BT="$(ls "$ANDROID_SDK_ROOT/build-tools" | sort -V | tail -1)"
|
||||
APKSIGNER="$ANDROID_SDK_ROOT/build-tools/$BT/apksigner"
|
||||
mkdir -p artifacts
|
||||
found=0
|
||||
for f in $(find src-tauri/gen/android/app/build/outputs/apk -name '*-release*.apk'); do
|
||||
abi="$(basename "$(dirname "$(dirname "$f")")")"
|
||||
out="artifacts/${PREFIX}_${VERSION}_${abi}.apk"
|
||||
"$APKSIGNER" sign \
|
||||
--ks "$KS" --ks-key-alias "$KEY_ALIAS" \
|
||||
--ks-pass "pass:$STORE_PASSWORD" --key-pass "pass:$KEY_PASSWORD" \
|
||||
--v4-signing-enabled false \
|
||||
--out "$out" "$f"
|
||||
"$APKSIGNER" verify --print-certs "$out" | head -3
|
||||
found=$((found+1))
|
||||
done
|
||||
rm -f "$KS"
|
||||
if [ "$found" -eq 0 ]; then echo "::error::没有找到 release APK"; exit 1; fi
|
||||
AAPT2="$(ls "$ANDROID_SDK_ROOT"/build-tools/*/aapt2 | sort -V | tail -1)"
|
||||
for a in artifacts/*.apk; do "$AAPT2" dump badging "$a" | grep -m1 "^package:"; done
|
||||
ls -lh artifacts
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ${{ matrix.edition == 'tv' && 'android-tv' || 'android' }}
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
macos:
|
||||
name: macOS (universal dmg)
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' &&
|
||||
(inputs.platforms == 'all' || inputs.platforms == 'macos'))
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "$INPUT_TAG" ]]; then
|
||||
V="${INPUT_TAG#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-darwin,x86_64-apple-darwin
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: macos
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: 构建(Universal dmg)
|
||||
run: |
|
||||
if [ "${{ inputs.quick }}" = "true" ]; then
|
||||
pnpm tauri build --target aarch64-apple-darwin
|
||||
else
|
||||
pnpm tauri build --target universal-apple-darwin
|
||||
fi
|
||||
- name: 收集产物
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
DIR=universal-apple-darwin
|
||||
SUFFIX=universal
|
||||
if [ "${{ inputs.quick }}" = "true" ]; then DIR=aarch64-apple-darwin; SUFFIX=arm64; fi
|
||||
cp "src-tauri/target/$DIR/release/bundle/dmg/"*.dmg \
|
||||
"artifacts/HGhubX_${{ steps.ver.outputs.version }}_${SUFFIX}.dmg"
|
||||
ls -lh artifacts
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: macos
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
ios:
|
||||
name: iOS (unsigned ipa)
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' &&
|
||||
(inputs.platforms == 'all' || inputs.platforms == 'ios'))
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "$INPUT_TAG" ]]; then
|
||||
V="${INPUT_TAG#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V"
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-ios,aarch64-apple-ios-sim
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: ios
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: 生成 iOS 工程(带横竖屏 + ATS)
|
||||
run: |
|
||||
pnpm tauri ios init --ci
|
||||
for plist in $(find src-tauri/gen/apple -name "Info.plist" 2>/dev/null); do
|
||||
for key in "UISupportedInterfaceOrientations" "UISupportedInterfaceOrientations~iphone" "UISupportedInterfaceOrientations~ipad"; do
|
||||
/usr/libexec/PlistBuddy -c "Delete :${key}" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :${key} array" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:0 string UIInterfaceOrientationPortrait" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:1 string UIInterfaceOrientationLandscapeLeft" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:2 string UIInterfaceOrientationLandscapeRight" "$plist"
|
||||
done
|
||||
/usr/libexec/PlistBuddy -c "Delete :NSAppTransportSecurity" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity dict" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity:NSAllowsArbitraryLoads bool true" "$plist"
|
||||
done
|
||||
- name: 构建并打包 ipa
|
||||
shell: bash
|
||||
env:
|
||||
APP_VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: bash scripts/build-ios-unsigned.sh "$APP_VERSION"
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ios
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
linux:
|
||||
name: Linux (deb)
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 60
|
||||
if: >-
|
||||
startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' &&
|
||||
(inputs.platforms == 'all' || inputs.platforms == 'linux'))
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "$INPUT_TAG" ]]; then
|
||||
V="${INPUT_TAG#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
- name: 缓存 Linux WebKitGTK .deb 依赖
|
||||
id: apt-cache
|
||||
uses: actions/cache@v6
|
||||
with:
|
||||
path: ~/apt-webkit-debs
|
||||
key: apt-webkit-ubuntu22-v1
|
||||
- name: 安装系统依赖
|
||||
run: |
|
||||
install_from_mirror() {
|
||||
mkdir -p ~/apt-webkit-debs
|
||||
sudo rm -rf /var/lib/apt/lists/*
|
||||
sudo find /etc/apt/sources.list.d -maxdepth 1 -type f ! -name 'ubuntu.sources' -delete
|
||||
printf 'https://mirrors.edge.kernel.org/ubuntu/\nhttp://archive.ubuntu.com/ubuntu/\n' | sudo tee /etc/apt/apt-mirrors.txt >/dev/null
|
||||
if [ -f /etc/apt/sources.list ]; then
|
||||
sudo sed -i -E 's|https?://[^/[:space:]]+/ubuntu/?|https://mirrors.edge.kernel.org/ubuntu/|g' /etc/apt/sources.list
|
||||
fi
|
||||
sudo apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 update
|
||||
sudo apt-get -o Dir::Cache::archives="$HOME/apt-webkit-debs" -o Acquire::Retries=3 -o Acquire::http::Timeout=15 -o Acquire::https::Timeout=15 \
|
||||
install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev patchelf build-essential curl wget file libssl-dev libxdo-dev
|
||||
sudo rm -rf ~/apt-webkit-debs/lock ~/apt-webkit-debs/partial 2>/dev/null || true
|
||||
sudo chown -R "$USER:$USER" ~/apt-webkit-debs
|
||||
}
|
||||
if [ "${{ steps.apt-cache.outputs.cache-hit }}" = "true" ] && compgen -G "$HOME/apt-webkit-debs/*.deb" >/dev/null; then
|
||||
if ! (sudo dpkg --unpack ~/apt-webkit-debs/*.deb && sudo dpkg --configure -a); then
|
||||
sudo apt-get -f install -y || true
|
||||
rm -rf ~/apt-webkit-debs/*
|
||||
install_from_mirror
|
||||
fi
|
||||
else
|
||||
install_from_mirror
|
||||
fi
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: linux
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: 构建(deb)
|
||||
run: pnpm tauri build
|
||||
- name: 收集产物
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
cp src-tauri/target/release/bundle/deb/*.deb "artifacts/HGhubX_${{ steps.ver.outputs.version }}_amd64.deb"
|
||||
ls -lh artifacts
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: linux
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [windows, android, macos, linux, ios]
|
||||
# iOS 失败时不能把整包卡住,但成功时要等它的 ipa 一起发;其余平台必须全部成功且工作流未被取消
|
||||
if: >-
|
||||
always() &&
|
||||
!cancelled() &&
|
||||
needs.windows.result == 'success' &&
|
||||
needs.android.result == 'success' &&
|
||||
needs.macos.result == 'success' &&
|
||||
needs.linux.result == 'success' &&
|
||||
(needs.ios.result == 'success' || needs.ios.result == 'failure') &&
|
||||
(startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.mode == 'package' && inputs.tag != '' && inputs.platforms == 'all' && !inputs.quick))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
- name: 列出待发布文件
|
||||
run: ls -lh artifacts
|
||||
- name: 取版本说明
|
||||
id: notes
|
||||
env:
|
||||
INPUT_TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
TAG="${INPUT_TAG:-$GITHUB_REF_NAME}"
|
||||
F="docs/release-notes/${TAG}.md"
|
||||
if [ -f "$F" ]; then
|
||||
echo "body_path=$F" >> "$GITHUB_OUTPUT"
|
||||
echo "使用 $F"
|
||||
else
|
||||
echo "body_path=" >> "$GITHUB_OUTPUT"
|
||||
echo "没有 $F,回退自动生成的说明"
|
||||
fi
|
||||
- uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ inputs.tag != '' && inputs.tag || github.ref_name }}
|
||||
name: ${{ inputs.tag != '' && inputs.tag || github.ref_name }}
|
||||
body_path: ${{ steps.notes.outputs.body_path }}
|
||||
files: artifacts/*
|
||||
generate_release_notes: ${{ steps.notes.outputs.body_path == '' }}
|
||||
prerelease: ${{ inputs.prerelease || contains(inputs.tag != '' && inputs.tag || github.ref_name, '-') }}
|
||||
fail_on_unmatched_files: true
|
||||
@@ -1,44 +0,0 @@
|
||||
name: Playback diagnostics
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
scenarios:
|
||||
description: Comma-separated checks (seek,legacy,stall,lifecycle,mms)
|
||||
default: seek,legacy,stall,lifecycle,mms
|
||||
required: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
playback:
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- run: pnpm install --frozen-lockfile
|
||||
- name: Install local media generator and headless browser
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y ffmpeg
|
||||
pnpm exec playwright-core install --with-deps chromium
|
||||
- name: Run playback checks and collect diagnostics
|
||||
env:
|
||||
PLAYBACK_SCENARIOS: ${{ inputs.scenarios }}
|
||||
run: pnpm test:playback --scenarios "$PLAYBACK_SCENARIOS" --output test-results/playback-ci
|
||||
- name: Upload diagnostics even when a check fails
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: playback-diagnostics
|
||||
path: test-results/
|
||||
retention-days: 7
|
||||
if-no-files-found: warn
|
||||
@@ -1,453 +0,0 @@
|
||||
name: Release
|
||||
|
||||
# 打 tag(v1.2.3)即自动出包并发布 Release;也可以在 Actions 页手动跑:
|
||||
# platforms=all + quick=false + 填好 tag,等价于一次正式发版。
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
# 手动跑:默认 quick + 单平台,验证改动用;选 all 且关掉 quick 就是发版那套全量构建。
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
platforms:
|
||||
description: "构建范围:check 只查编译不出包;all 全平台(含 TV);选单个只出那一个"
|
||||
type: choice
|
||||
default: all
|
||||
options: [all, android-arm64, android, android-tv, linux, windows, macos, ios, check]
|
||||
quick:
|
||||
description: "quick 编译:thin LTO + 4 个 codegen 单元,快一倍,体积大几 MB"
|
||||
type: boolean
|
||||
default: true
|
||||
tag:
|
||||
description: "发版用:填 tag(如 v1.2.4+hg.1),配合 platforms=all 构建完直接发 Release;留空则只出产物"
|
||||
type: string
|
||||
default: ""
|
||||
prerelease:
|
||||
description: "标记为 Pre-release(预发布,不出正式版)"
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.ref }}-${{ github.event_name }}-${{ github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
CI: "true"
|
||||
|
||||
jobs:
|
||||
# ================= Windows:NSIS 安装包 + 便携包 =================
|
||||
windows:
|
||||
name: Windows (setup + portable)
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 60
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'windows' }}
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "${{ inputs.tag }}" ]]; then
|
||||
V="${{ inputs.tag }}"
|
||||
V="${V#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
# 版本号 + Android versionCode 一起写(Tauri 自己会忽略 +hg.N 后缀)
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 构建(NSIS 安装包)
|
||||
run: pnpm tauri build --bundles nsis
|
||||
|
||||
- name: 收集产物(安装包 + 便携包)
|
||||
shell: pwsh
|
||||
run: |
|
||||
$v = "${{ steps.ver.outputs.version }}"
|
||||
New-Item -ItemType Directory -Force artifacts | Out-Null
|
||||
Copy-Item "src-tauri/target/release/bundle/nsis/*.exe" artifacts/
|
||||
$bin = "src-tauri/target/release/hghubx.exe"
|
||||
if (-not (Test-Path $bin)) {
|
||||
$bin = (Get-ChildItem "src-tauri/target/release" -Filter *.exe | Select-Object -First 1).FullName
|
||||
}
|
||||
Copy-Item $bin "artifacts/HGhubX.exe"
|
||||
Compress-Archive -Path "artifacts/HGhubX.exe" -DestinationPath "artifacts/HGhubX_${v}_x64_portable.zip" -Force
|
||||
Remove-Item "artifacts/HGhubX.exe"
|
||||
Get-ChildItem artifacts | Select-Object Name, Length
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: windows
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
# ================= Android:标准版 + TV 版,共享同一构建实现 =================
|
||||
android:
|
||||
name: Android standard
|
||||
uses: ./.github/workflows/android-build.yml
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'android' || inputs.platforms == 'android-arm64' }}
|
||||
with:
|
||||
edition: standard
|
||||
platforms: ${{ inputs.platforms }}
|
||||
quick: ${{ inputs.quick }}
|
||||
tag: ${{ inputs.tag }}
|
||||
secrets: inherit
|
||||
|
||||
android-tv:
|
||||
name: Android TV
|
||||
uses: ./.github/workflows/android-build.yml
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'android-tv' }}
|
||||
with:
|
||||
edition: tv
|
||||
platforms: ${{ inputs.platforms }}
|
||||
quick: ${{ inputs.quick }}
|
||||
tag: ${{ inputs.tag }}
|
||||
secrets: inherit
|
||||
|
||||
# ================= macOS:Universal(Apple Silicon + Intel)dmg =================
|
||||
macos:
|
||||
name: macOS (universal dmg)
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'macos' }}
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "${{ inputs.tag }}" ]]; then
|
||||
V="${{ inputs.tag }}"
|
||||
V="${V#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
# 版本号 + Android versionCode 一起写(Tauri 自己会忽略 +hg.N 后缀)
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-darwin,x86_64-apple-darwin
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: macos
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# 打包目标(app + dmg)取自 src-tauri/tauri.macos.conf.json;未配置开发者证书,产物为 ad-hoc 签名
|
||||
- name: 构建(Universal dmg)
|
||||
run: |
|
||||
# quick 只编 arm64:universal 要交叉编两遍,时间翻倍
|
||||
if [ "${{ inputs.quick }}" = "true" ]; then
|
||||
pnpm tauri build --target aarch64-apple-darwin
|
||||
else
|
||||
pnpm tauri build --target universal-apple-darwin
|
||||
fi
|
||||
|
||||
- name: 收集产物
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
DIR=universal-apple-darwin
|
||||
SUFFIX=universal
|
||||
if [ "${{ inputs.quick }}" = "true" ]; then DIR=aarch64-apple-darwin; SUFFIX=arm64; fi
|
||||
cp "src-tauri/target/$DIR/release/bundle/dmg/"*.dmg \
|
||||
"artifacts/HGhubX_${{ steps.ver.outputs.version }}_${SUFFIX}.dmg"
|
||||
ls -lh artifacts
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: macos
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
ios:
|
||||
name: iOS (unsigned ipa)
|
||||
runs-on: macos-latest
|
||||
timeout-minutes: 60
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'ios' }}
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
APPLE_DEVELOPMENT_TEAM: "ABCDE12345"
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "${{ inputs.tag }}" ]]; then
|
||||
V="${{ inputs.tag }}"
|
||||
V="${V#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
node scripts/set-version.mjs "$V"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V"
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: aarch64-apple-ios,aarch64-apple-ios-sim
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: ios
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# 跟上游一致:不在 pbxproj 里绕开 xcode-script,而是让 tauri ios build 的
|
||||
# options server 活着,由 Xcode 用 release 配置跑 Build Rust Code。
|
||||
- name: 生成 iOS 工程(带横竖屏 + ATS)
|
||||
run: |
|
||||
pnpm tauri ios init --ci
|
||||
for plist in $(find src-tauri/gen/apple -name "Info.plist" 2>/dev/null); do
|
||||
for key in "UISupportedInterfaceOrientations" "UISupportedInterfaceOrientations~iphone" "UISupportedInterfaceOrientations~ipad"; do
|
||||
/usr/libexec/PlistBuddy -c "Delete :${key}" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :${key} array" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:0 string UIInterfaceOrientationPortrait" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:1 string UIInterfaceOrientationLandscapeLeft" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :${key}:2 string UIInterfaceOrientationLandscapeRight" "$plist"
|
||||
done
|
||||
/usr/libexec/PlistBuddy -c "Delete :NSAppTransportSecurity" "$plist" 2>/dev/null || true
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity dict" "$plist"
|
||||
/usr/libexec/PlistBuddy -c "Add :NSAppTransportSecurity:NSAllowsArbitraryLoads bool true" "$plist"
|
||||
done
|
||||
|
||||
- name: 构建并打包 ipa
|
||||
shell: bash
|
||||
env:
|
||||
APP_VERSION: ${{ steps.ver.outputs.version }}
|
||||
run: bash scripts/build-ios-unsigned.sh "$APP_VERSION"
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: ios
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
# ================= Linux:deb =================
|
||||
linux:
|
||||
name: Linux (deb)
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 60
|
||||
if: ${{ github.event_name != 'workflow_dispatch' || inputs.platforms == 'all' || inputs.platforms == 'linux' }}
|
||||
env:
|
||||
CARGO_PROFILE_RELEASE_LTO: ${{ inputs.quick && 'thin' || 'true' }}
|
||||
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: ${{ inputs.quick && '4' || '1' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐 tag
|
||||
id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "$GITHUB_REF" == refs/tags/v* ]]; then
|
||||
V="${GITHUB_REF_NAME#v}"
|
||||
elif [[ -n "${{ inputs.tag }}" ]]; then
|
||||
V="${{ inputs.tag }}"
|
||||
V="${V#v}"
|
||||
else
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
fi
|
||||
# 版本号 + Android versionCode 一起写(Tauri 自己会忽略 +hg.N 后缀)
|
||||
node scripts/set-version.mjs "$V"
|
||||
CODE="$(node -p "require('./src-tauri/tauri.conf.json').bundle.android.versionCode")"
|
||||
echo "version=$V" >> "$GITHUB_OUTPUT"
|
||||
echo "versionCode=$CODE" >> "$GITHUB_OUTPUT"
|
||||
echo "versionName=$V versionCode=$CODE"
|
||||
|
||||
# Tauri 2 在 Linux 上依赖 webkit2gtk-4.1;22.04 的 jammy-updates 已提供
|
||||
- name: 安装系统依赖
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev patchelf build-essential curl wget file libssl-dev libxdo-dev
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: linux
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
# 打包目标取自 src-tauri/tauri.linux.conf.json
|
||||
- name: 构建(deb)
|
||||
run: pnpm tauri build
|
||||
|
||||
- name: 收集产物
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p artifacts
|
||||
cp src-tauri/target/release/bundle/deb/*.deb "artifacts/HGhubX_${{ steps.ver.outputs.version }}_amd64.deb"
|
||||
ls -lh artifacts
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: linux
|
||||
path: artifacts/*
|
||||
if-no-files-found: error
|
||||
|
||||
# ================= 只查编译:不出包,最快拿到「过 / 不过」 =================
|
||||
check:
|
||||
name: 编译检查(tsc + cargo check + 单测)
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 60
|
||||
if: ${{ github.event_name == 'workflow_dispatch' && inputs.platforms == 'check' }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: 版本号对齐
|
||||
run: |
|
||||
V="$(node -p "require('./src-tauri/tauri.conf.json').version")"
|
||||
node scripts/set-version.mjs "$V"
|
||||
|
||||
- name: 安装系统依赖
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends \
|
||||
libwebkit2gtk-4.1-dev libgtk-3-dev libayatana-appindicator3-dev \
|
||||
librsvg2-dev patchelf build-essential curl wget file libssl-dev libxdo-dev
|
||||
|
||||
- uses: pnpm/action-setup@v6
|
||||
with:
|
||||
version: 10
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 22
|
||||
cache: pnpm
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: swatinem/rust-cache@v2.9.3
|
||||
continue-on-error: true
|
||||
timeout-minutes: 8
|
||||
with:
|
||||
workspaces: src-tauri -> target
|
||||
key: check
|
||||
|
||||
- run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: 前端类型检查
|
||||
run: npx tsc --noEmit -p tsconfig.json
|
||||
|
||||
- name: cargo check(含测试目标)
|
||||
working-directory: src-tauri
|
||||
run: cargo check --all-targets
|
||||
|
||||
- name: 单元测试
|
||||
working-directory: src-tauri
|
||||
run: cargo test --lib
|
||||
|
||||
# ================= 发布 =================
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [windows, android, android-tv, macos, linux, ios]
|
||||
# always():iOS 失败时不能把整包卡住,但成功时要等它的 ipa 一起发
|
||||
if: >-
|
||||
always() &&
|
||||
(startsWith(github.ref, 'refs/tags/v') ||
|
||||
(github.event_name == 'workflow_dispatch' && inputs.tag != ''))
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 60
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
path: artifacts
|
||||
merge-multiple: true
|
||||
|
||||
- name: 列出待发布文件
|
||||
run: ls -lh artifacts
|
||||
|
||||
- name: 取版本说明
|
||||
id: notes
|
||||
run: |
|
||||
TAG="${{ inputs.tag != '' && inputs.tag || github.ref_name }}"
|
||||
F="docs/release-notes/${TAG}.md"
|
||||
if [ -f "$F" ]; then
|
||||
echo "body_path=$F" >> "$GITHUB_OUTPUT"
|
||||
echo "使用 $F"
|
||||
else
|
||||
echo "body_path=" >> "$GITHUB_OUTPUT"
|
||||
echo "没有 $F,回退自动生成的说明"
|
||||
fi
|
||||
- uses: softprops/action-gh-release@v3
|
||||
with:
|
||||
tag_name: ${{ inputs.tag != '' && inputs.tag || github.ref_name }}
|
||||
name: ${{ inputs.tag != '' && inputs.tag || github.ref_name }}
|
||||
body_path: ${{ steps.notes.outputs.body_path }}
|
||||
files: artifacts/*
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ inputs.prerelease }}
|
||||
fail_on_unmatched_files: true
|
||||
@@ -26,7 +26,7 @@ make check
|
||||
|
||||
- `pnpm build` 执行两份 TypeScript 检查和 Vite 构建。
|
||||
- `pnpm test:smoke` 运行不需要 ffmpeg、真实 Tauri 宿主或上游网络的稳定浏览器用例。
|
||||
- `make check` 当前执行 `test-rust`、`test-web`、`docs`、`budget`;**不包含** `test:smoke`。
|
||||
- `make check` 当前执行 `test-rust`、`test-web`、`docs`、`budget`、`release-check`;**不包含** `test:smoke`。
|
||||
- `make release-check` 检查版本字段和 Android `versionCode`;发版由 CI 执行,不在本地发布。
|
||||
- 完整播放回归用 `pnpm test:playback`;它需要 FFmpeg 和 Chromium,属于手动诊断而非 PR smoke。
|
||||
|
||||
@@ -36,11 +36,12 @@ CI 是验证记录。命令写了不等于已经运行;报告里必须写清
|
||||
|
||||
### 前端
|
||||
|
||||
- `src/main.tsx`:挂载 React、启动诊断,并在使用协议确认后装配应用 Provider 和自动选线。
|
||||
- `src/editionEntry.ts`、`src/legacyRuntime.ts`、`src/main.tsx`:加载旧版 WebView 垫片,按构建变体挂载标准版或 `src/tv/`(Android TV 版),并在使用协议确认后装配应用 Provider 和自动选线。
|
||||
- `src/app/`:`App.tsx` 负责页面栈、桌面/移动布局和全局交互;`shell/` 放窗口控件,
|
||||
`startup/` 放启动门。
|
||||
- `src/features/`:按 `account/category/discover/feed/playback/posts/search/settings` 归组页面、
|
||||
专属组件与 hooks。Feed 的详情/评论/选集面板、设置页的线路/代理控件都随功能放置。
|
||||
- `src/tv/`:独立 Android TV 版页面、焦点导航、本地片库与播放界面。
|
||||
- `src/shared/`:`api`(IPC 与响应类型)、`model`(应用/账号/内容偏好状态)、`network`(自动选线)、
|
||||
`storage`(存储键与协议版本)、`diagnostics`、`lib`、`ui`(跨功能控件)。
|
||||
- `src/shared/model/store.tsx` 仍聚合导航、账号与播放偏好;这次目录迁移没有拆 Provider。
|
||||
@@ -52,12 +53,11 @@ CI 是验证记录。命令写了不等于已经运行;报告里必须写清
|
||||
|
||||
### Rust
|
||||
|
||||
- `src-tauri/src/api/`:Tauri command 与上游 endpoint,按 account/feed/video/interact/update/platform/lines 分文件。
|
||||
- `src-tauri/src/api/`:Tauri command 与上游 endpoint,按 account/feed/video/interact/update/platform/lines 分文件;GitHub Release 更新检查与版本对比在 `updater.rs`。
|
||||
- `src-tauri/src/net/`:`line`(线路状态)、`proxy_env`、`client`(客户端缓存/DNS/GET)、
|
||||
`redact`、`diagnostics`、`edge`(信封/重试/字节下载);共享 statics 和测试在 `mod.rs`/`tests.rs`。
|
||||
`redact`、`edge`(信封/重试/字节下载);网络诊断与草稿代理探测在 `net_diag.rs`;共享 statics 和测试在 `mod.rs`/`tests.rs`。
|
||||
- `src-tauri/src/media/`:图片、HLS、分片、Range、响应整形和本地媒体协议入口。
|
||||
- `src-tauri/src/lines/`:`mirror`、`jsparse`、`probe` 三块,负责固定/发布镜像/自定义线路、
|
||||
JS-as-data 解析、探测与自动选线。
|
||||
- `src-tauri/src/lines/`:`mirror`、`probe` 负责固定/发布镜像/自定义线路、探测与自动选线;无状态发布页与 JS-as-data 解析在 `publish_parser.rs`。
|
||||
- `src-tauri/src/ios_layout.rs`、`ios_media_http.rs`、`linux_http.rs`、`linux_webview.rs`、
|
||||
`macos_titlebar.rs`:按 `cfg` 编译的平台壳;Windows/Android 的壳逻辑部分在 `lib.rs` 与前端。
|
||||
- `src-tauri/src/session.rs`、`cache.rs`、`env.rs`、`playback_log.rs`、`network_policy.rs`:
|
||||
@@ -91,6 +91,10 @@ CI 是验证记录。命令写了不等于已经运行;报告里必须写清
|
||||
上游网络,fixture 要接近真实响应;尺寸预算只能在搬走关注点后下调。
|
||||
10. **日志不含秘密。** 不记录 token、Cookie、代理认证、播放直链、查询参数或密钥内容;
|
||||
错误链由 `err_text`/`redact_error_proxy_auth` 脱敏,诊断只输出协议/主机/端口和固定资源编号。
|
||||
11. **新增测试必须先经维护者同意。** 任何新增测试文件、场景或用例,先向维护者说明
|
||||
它验证什么、为什么现有测试覆盖不了,得到明确同意后才能加入。既有测试的断言适配
|
||||
(契约变化导致的 fixture/断言更新)不算新增,但不得借适配削弱覆盖。测试体系保持
|
||||
最精简:一个契约一个回归,不重复建同义用例。
|
||||
|
||||
## 变更协议
|
||||
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
|
||||
# The verification of record is GitHub Actions. These targets are the same
|
||||
# commands CI runs, so a local run (when requested) and CI cannot drift.
|
||||
check: test-rust test-web docs budget
|
||||
check: test-rust test-web docs budget release-check
|
||||
|
||||
test-rust:
|
||||
cargo check --manifest-path src-tauri/Cargo.toml --all-targets
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
|
||||
test-web:
|
||||
|
||||
@@ -37,7 +37,7 @@ Windows / macOS / Linux / Android / iOS · iOS 圆角与玻璃材质 · 沉浸
|
||||
|
||||
## 仿冒提醒
|
||||
|
||||
> 🚫 **已发现的恶意修改版**:[`hichuv 仓库`](https://github.com/hichuv 仓库)
|
||||
> 🚫 **已发现的恶意修改版**:[`hichuv` 仓库](https://github.com/hichuv)
|
||||
>
|
||||
> 该仓库与本项目无关,是在旧版本源码基础上擅自加入**卡密验证、VIP 付费解锁**等变现功能的修改版,
|
||||
> 代码改动不透明、安全性无法验证。**请勿下载、勿注册、勿付费**;如已安装,建议立即卸载,改用官方 Release 包安装。
|
||||
@@ -69,6 +69,7 @@ Windows / macOS / Linux / Android / iOS · iOS 圆角与玻璃材质 · 沉浸
|
||||
| --- | --- |
|
||||
| `src/app/` | 应用装配、页面栈、窗口壳与启动门 |
|
||||
| `src/features/` | 首页与 Feed、播放、账号、分类、发现、图文、搜索、设置 |
|
||||
| `src/tv/` | 独立 Android TV 版界面、遥控器焦点与本地搜索片库 |
|
||||
| `src/shared/` | IPC、共享状态、存储、自动选线、诊断与跨功能 UI |
|
||||
| `src/styles/`、`src/index.css` | 统一样式入口与样式文件 |
|
||||
| `src-tauri/src/` | Rust 的 API、网络、媒体、线路与平台实现 |
|
||||
|
||||
@@ -7,8 +7,12 @@
|
||||
|
||||
```text
|
||||
src/
|
||||
├── main.tsx React 挂载与启动初始化
|
||||
├── editionEntry.ts 启动入口,加载旧 WebView 垫片并按构建变体装配应用
|
||||
├── edition.ts 标准版 / Android TV 变体标识
|
||||
├── legacyRuntime.ts 旧版 Chromium / Safari 运行时 API 兼容垫片
|
||||
├── main.tsx 标准版 React 挂载与启动初始化
|
||||
├── app/
|
||||
│ ├── AcceptedApp.tsx 协议确认后的应用装配(AppProvider + 自动选线 + App)
|
||||
│ ├── App.tsx 页面栈、布局、全局返回与键盘处理
|
||||
│ ├── shell/ 桌面标题栏、侧栏、窗口缩放热区
|
||||
│ └── startup/ 启动动画与使用协议门
|
||||
@@ -21,6 +25,7 @@ src/
|
||||
│ ├── posts/ 图文列表、正文页与热度数据处理
|
||||
│ ├── search/ 搜索、排行榜、标签与列表内搜索
|
||||
│ └── settings/ 设置页、线路、代理与内容偏好编辑
|
||||
├── tv/ 独立 Android TV 版页面、遥控器焦点与本地索引
|
||||
├── shared/
|
||||
│ ├── api/ Tauri IPC、响应类型、平台与媒体地址封装
|
||||
│ ├── model/ 应用状态、账号同步、内容偏好
|
||||
@@ -54,7 +59,7 @@ Feed 与评论、选集、详情面板放在 `features/feed/`。跨功能使用
|
||||
## 共享状态的当前边界
|
||||
|
||||
[`shared/model/store.tsx`](../src/shared/model/store.tsx) 仍是一个应用 Provider,聚合导航、
|
||||
主题、账号与播放偏好;这次只整理文件归属,没有拆状态订阅或改变渲染更新方式。
|
||||
主题、账号与播放偏好;Toast 列表通过独立的 `useToasts()`(`useSyncExternalStore`)订阅,避免提示弹层触发全树重渲染。
|
||||
|
||||
`store` 调用同目录的 `accountData` 处理账号数据缓存与同步。`accountData` 对 `store`
|
||||
中的 `WatchProgress` 仅有类型引用,须保留 `import type`;`contentPreferences` 仍是独立的
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
# 封面与播放列表缓存对比
|
||||
|
||||
> 历史记录(2026-11-08):文内路径对应目录拆分前的单文件结构,当前实现路径见 [`docs/subsystems/network-proxy-media.md`](../subsystems/network-proxy-media.md)。
|
||||
|
||||
对比基准:Minireel/HGhubX `8665ffcaa553bc6eb1b52629fd91b35cc6e02678`。检查对象为 2026-11-08 当前工作区代码,包括尚未提交的修改。基准提交已在本地仓库中,使用 `git show`/`git diff` 比对,未访问上游接口。首次核查发现子播放列表缓存指令被收紧;后续按保持上游行为的要求,已将该成功响应恢复为 1 小时缓存。
|
||||
|
||||
## 内置内存缓存
|
||||
|
||||
+4
-2
@@ -7,7 +7,7 @@
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| 2026-11-04 | 系统代理 | 浏览器能打开站点,HGhubX 一直直连失败;只有 TUN 模式看起来正常 | `reqwest` 使用 `default-features = false`,漏了 `system-proxy`,应用不读 Windows/macOS 固定代理 | 显式保留 `system-proxy` feature;代理模式/地址变化要能重建客户端;不要用“浏览器能开”代替应用层验证 | `1260a70`;`src-tauri/Cargo.toml` 的 reqwest feature;`src-tauri/src/net/tests.rs` 的 `ProxyRoute`/`client_key` 测试 |
|
||||
| 2026-11-09 | Android 自定义协议 | 接口正常,m3u8 一加载就 `manifestLoadError`/networkError | 部分 Android WebView 拦截 `http://hg.localhost` 时不给 `Origin`,严格模式把缺失 Origin 当成外部来源 | 进程内媒体地址可放行缺失/空/`"null"` Origin,但必须同时校验 Host、capability 和 `/img`、`/hls`、`/seg` 白名单;不能放宽业务 origin | `30cde3d`;`src-tauri/src/lib.rs` 的 `origin_ok`;Android 实机回归待核实 |
|
||||
| 2026-11-09 | Linux 媒体传输 | Linux 桌面 `<video>` 打不开 `hg://`;hls.js 也没有 MediaSource | WebKitGTK 把 `<video>` 交给 GStreamer,GStreamer 只认 http/https/file,不认自定义 scheme | Linux 用只监听 `127.0.0.1` 的 loopback HTTP;端口与前端 `LOCAL` 同步;WebView 对本机媒体绕过 GNOME 代理 | `683ffaf`;`src-tauri/src/linux_http.rs`、`linux_webview.rs`;`scripts/test-linux-media-policy.mjs` |
|
||||
| 2026-11-09 | Linux 媒体传输 | Linux 桌面 `<video>` 打不开 `hg://`;hls.js 也没有 MediaSource | WebKitGTK 把 `<video>` 交给 GStreamer,GStreamer 只认 http/https/file,不认自定义 scheme | Linux 用只监听 `127.0.0.1` 的 loopback HTTP;端口与前端 `LOCAL` 同步;WebView 对本机媒体绕过 GNOME 代理 | `683ffaf`;`src-tauri/src/linux_http.rs`、`linux_webview.rs`(原 CSP 回归脚本已随测试精简移除,契约见 network-proxy-media.md) |
|
||||
| 2026-11-10 | 自动选线 | 主站和镜像都不通时客户端仍切到 `.ai`,随后接口全 404 | 选线只看“能连/能返回 200”,没有验证解包后的视频列表;all-down 仍返回可切换地址 | 选线判据必须是真实 `items/pagination` 数据;全部不可用时返回 `all-down` 并保持当前线路 | `87b42f1`;`src-tauri/src/lines/probe.rs` 的 `healthy_video_data`/`pick_from_hits` 测试 |
|
||||
| 2026-11-10 | seek 与播放意图 | 原本暂停的视频拖动/点击进度条后自动播放;或片尾 seek 后卡住 | seek 完成后无条件 `play()`,没有保留用户的暂停意图;iOS 片尾没有贴边保护 | seek 只恢复“seek 前正在播放”的状态;目标夹到 `duration - 0.15`;拖动预览与提交分离 | `73c6610`;`tests/player-seek.tsx`;`playback.md` 的 seek 状态转换 |
|
||||
| 2026-11-10 | 线路代次 | 切换线路后,之前加载失败的首页/分类数据不重拉,仍显示旧错误 | `lineEpoch` 已存在但没有进入请求 key/失效判断 | 线路变化必须推进 epoch,并让列表、详情、标签门、播放地址和动作上下文都使用它;旧响应丢弃 | `dc74ff0`;`src/features/feed/useFeedDetails.ts`;`feed-and-detail.md` 的 scope/epoch 规则 |
|
||||
@@ -18,7 +18,9 @@
|
||||
| 2026-11-17 | 设置页 smoke 定位 | CI 的线路测试等待“播放源”按钮超时 | 设置分组默认折叠,脚本未通过分组按钮展开;另有旧推荐列表断言与当前仅渲染 `items` 的实现失配 | 先用分组按钮的可访问名称展开并检查 `aria-expanded`,再操作组内控件;镜像断言对应实际发布项,保留切线、取消、会话和复制失败断言 | [CI 43949517841](https://github.com/zxsos/HGhubX/actions/runs/43949517841/job/133587970186);`src/features/settings/SettingsSection.tsx`、`LinePicker.tsx`;`scripts/test-line-selection.mjs`、`scripts/test-diagnostic-copy.mjs`、`scripts/test-network-settings.mjs` |
|
||||
| 2026-11-17 | 播放测试前置条件 | 手势测试等待播放超时;失活后延迟挂载测试等不到播放器 | 首次长按教程会暂停播放;失活的 Feed 不请求播放地址,因此没有挂载播放器 | 手势测试先点击真实教程确认按钮;延迟挂载用真实 VideoSurface/Player,先确认父页面失活且无 video,再挂载并检查无播放/分片请求,激活后确认可播 | [Playback 43952408893](https://github.com/zxsos/HGhubX/actions/runs/43952408893);`scripts/test-playback.mjs`、`tests/player-seek.tsx` |
|
||||
| 2026-11-17 | 冷启动与返回键 | 启动动画期间提前挂载 App 后,从视频页按返回不弹栈;真机上动画期返回可能直接退出应用 | App 与启动动画同时注册 `back-button`;旧 fixture 只保留最后注册者且 `remove_listener` 是 no-op,动画卸载后返回仍打在已完成的动画回调上 | 覆盖层期间用 `holdBackForStartup()` 让 `runBack()` 只消费不导航;fixture 按真实 Tauri 建模多监听广播与按 channelId 注销;动画结束后恢复原有返回顺序 | `4dd7844`;`src/shared/lib/back.ts`、`src/app/startup/LaunchAnimation.tsx`、`scripts/fixtures/app-ui.mjs`;`scripts/test-inplace-search-back.mjs` |
|
||||
| 2026-11-17 | 切线掉登录(#145) | 手动/自动切换线路后登录被清空,需重新登录;`.ai` 线路接口全 404 | 上游可信线路共享同一账号库(实测同 uid、token 跨线可用、收藏一致),但客户端切线一律 `session.clear()` + 前端 `setUser(null)`;`.ai` 只是导航站却被列为固定线路 | 会话跨 origin 只能走 `rebase_or_clear()`(两端都是固定/发布页确认镜像才保留,revision 递增落盘);自定义线路永远清空;前端由 boot 决定会话,本地账号桶随 rebase 迁移并立即落盘;导航站不授予线路与凭据信任 | `12f1968`..`c5f6091`;`src-tauri/src/session.rs` rebase 测试;`scripts/test-line-selection.mjs`、`scripts/test-network-settings.mjs`;实测记录 `outputs/issue-145/evidence/live-login-test.json` |
|
||||
| 2026-11-17 | 切线掉登录(#145) | 手动/自动切换线路后登录被清空,需重新登录;`.ai` 线路接口全 404 | 上游可信线路共享同一账号库(实测同 uid、token 跨线可用、收藏一致),但客户端切线一律 `session.clear()` + 前端 `setUser(null)`;`.ai` 只是导航站却被列为固定线路 | 会话跨 origin 只能走 `rebase_or_clear()`(两端都是固定/发布页确认镜像才保留,revision 递增落盘);自定义线路永远清空;前端由 boot 决定会话,本地账号桶随 rebase 迁移并立即落盘;导航站不授予线路与凭据信任 | `12f1968`..`c5f6091`;`src-tauri/src/session.rs` rebase 测试;`scripts/test-line-selection.mjs`、`scripts/test-network-settings.mjs` |
|
||||
| 2026-11-18 | 切线转圈与冷启动镜像登录 | 后台自动选线后在播视频永久转圈或报错黑屏;镜像站登录后重启切回固定线路掉登录 | `hg:line-changed` 无条件 `setWaiting(true)` 但未刷新已解析 `playUrl`;`reconcile_on_boot` 遇到固定线路跳过发布页拉取导致旧镜像不在 `TRUSTED_MIRRORS` | 区分 `hg:proxy-changed`(保 `<video>` 重连)与 `hg:line-changed`(健康在播流不置 `waiting`、其余与预取全部按新线路重解析);`reconcile_on_boot` 必须同时验证旧存储 origin 与当前 origin | `src/features/feed/Feed.tsx`、`scripts/test-playback.mjs`;`src-tauri/src/session.rs` `boot_reconcile_verifies_stored_mirror_even_when_current_line_is_fixed` |
|
||||
| 2026-11-18 | 全屏按钮命中遮挡与跨平台全屏 | 移动端下移右侧操作栏后「全屏」点击无响应;旧版 WebKit 无前缀回退或 Linux WebKitGTK 全屏不同步窗口状态 | `FeedItemChrome` 底部 `inset-x-0 z-20` 信息盒在 DOM 后方且默认 `pointer-events: auto`,透明右内边距完整盖住同级 `z-20` 的右侧操作栏底部按钮;`useFeedViewport` 直接调无前缀 `requestFullscreen` 且无拒绝回退,Linux 缺 `enter/leave-fullscreen` 窗口桥接 | 横跨视口的浮层外框一律 `pointer-events-none`、仅交互子控件 `pointer-events-auto`,右侧操作栏层级高于信息盒;全屏统一走 `fullscreen.ts`(兼容 `webkit` 前缀 + Tauri 窗口回退)并在 `linux_webview.rs` 同步窗口全屏;按钮排版变更必须跑不带 `force` 的真实点击命中验证 | `src/features/feed/FeedItemChrome.tsx`、`src/features/feed/useFeedViewport.ts`、`src/shared/lib/fullscreen.ts`、`src-tauri/src/linux_webview.rs` |
|
||||
|
||||
新回归的追加方式:
|
||||
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
|
||||
减少动态效果时关闭过渡;减少透明度、提高对比度或不支持 backdrop-filter 时,核心玻璃面板使用实色背景。没有依赖持续渲染的 canvas 动效。
|
||||
|
||||
运行 `pnpm build`、`pnpm test:ios-ui`、`pnpm test:ios-overlays`,并执行现有播放、加载、分页、移动布局、诊断复制和存储迁移回归。浏览器安装使用 `pnpm exec playwright-core install chromium`;可通过 `BROWSER_EXECUTABLE` 指定本机浏览器。报告和截图写入忽略目录 `test-results/`。
|
||||
运行 `pnpm build`,并执行现有播放、加载、诊断复制和存储迁移回归。浏览器安装使用 `pnpm exec playwright-core install chromium`;可通过 `BROWSER_EXECUTABLE` 指定本机浏览器。报告和截图写入忽略目录 `test-results/`。
|
||||
|
||||
浏览器回归使用真实 App 与模拟 Tauri IPC,不能替代原生 iOS WKWebView、Android 系统返回键及 Windows/macOS 窗口的设备验收。发布前需核对这些设备上的视频合成、模糊材质和安全区。
|
||||
|
||||
@@ -29,6 +29,6 @@
|
||||
|
||||
按钮按下反馈 55ms;分段选择、标签页和页面进入采用约 320–420ms 的轻微回弹,弹层保留约 150–180ms 的快速退出。减少动态效果设置关闭回弹。开关使用主题蓝轨道、金属高光滑块与勾选状态,保留 role=switch 与44px触摸区域。
|
||||
|
||||
`pnpm test:ui-performance` 记录本地 IPC fixture、Chromium 开发构建、4倍 CPU 降速下的点击到两个动画帧时间;此数据用于同环境比较,不代表原生设备 INP。本次单次对比中位数 130.9→119.6ms、P95 167.4→153.2ms;另有真实 Feed 手势回归记录首击22ms,去掉了原先固定230ms的等待。实际设备、数据量和网络不同,仍需设备复核。
|
||||
历史本地 IPC fixture(Chromium 开发构建、4倍 CPU 降速)记录点击到两个动画帧时间中位数 130.9→119.6ms、P95 167.4→153.2ms(原基准脚本已随测试精简移除);另有真实 Feed 手势回归(`pnpm test:playback --scenarios gesture`)记录首击22ms,去掉了原先固定230ms的等待。实际设备、数据量和网络不同,仍需设备复核。
|
||||
|
||||
动效节奏参考:[yui540 motions](https://yui540.com/motions),使用本项目自写的 CSS 与交互逻辑。
|
||||
@@ -87,32 +87,28 @@ pnpm test:playback
|
||||
|
||||
可用 `pnpm exec playwright-core show-trace <trace.zip路径>` 打开追踪。输出目录已经加入 gitignore;文件保存在执行命令的服务器,不会自动上传。
|
||||
|
||||
CLI 默认选择七个场景;下表描述预期覆盖,具体通过情况以对应运行的 `report.json` 为准:
|
||||
CLI 默认选择六个场景;下表描述预期覆盖,具体通过情况以对应运行的 `report.json` 为准:
|
||||
|
||||
| 场景 | 检查内容 |
|
||||
| --- | --- |
|
||||
| `seek` | 共用播放器的真实鼠标点击/拖动、拖动松手后仅定位一次、首帧恢复、暂停/键盘定位、失活取消拖动、开关关闭和保存失败 |
|
||||
| `legacy` | 吃瓜详情独立播放器的相同检查 |
|
||||
| `stall` | 人为停止 HLS 缓冲后点击未缓冲位置,检查 8 秒超时日志以及恢复缓冲后的首帧;属于故障注入 |
|
||||
| `lifecycle` | 两个播放器延迟清单后失活、后台禁止自动播放和分片加载、重新激活后恢复、手动暂停状态保留,以及视频延迟挂载时保持失活 |
|
||||
| `mms` | 两个播放器在两种 API 同时存在时优先使用标准 MSE;在模拟 MMS-only 环境中,endstreaming 停止缓冲后点击未缓冲位置,即使没有 startstreaming 事件也能自动恢复并输出首帧 |
|
||||
| `gesture` | Feed 移动端首击在 230ms 内切换净屏,双击恢复界面并只切换一次播放状态 |
|
||||
| `proxy` | 代理变化后重建媒体连接,保留同一 video 元素、当前视频、位置和播放/暂停意图;播放地址接口失败后可重试 |
|
||||
| `portrait-fit` | 竖屏视频在移动端保持原始比例(contain),横屏视频的铺满/适应切换正常 |
|
||||
|
||||
`ios-native`、`recovery`、`review` 是额外可选场景,需通过 `--scenarios` 显式选择。
|
||||
`ios-native`、`recovery`、`review`、`tv` 是额外可选场景,需通过 `--scenarios` 显式选择。`review` 执行当前代码的三项回归(就地搜索返回与焦点、账号同步空态、网络设置交互);`tv` 执行 TV 版验收(真实 TV bootstrap/Worker/片库,mock IPC)。
|
||||
|
||||
任何检查失败,命令退出码为 1,仍保留日志和报告。不要把日志采集通过理解成所有播放问题已修复。只运行诊断回归可以选择:
|
||||
|
||||
```sh
|
||||
pnpm test:playback --scenarios seek,legacy,stall
|
||||
pnpm test:playback --scenarios seek,legacy
|
||||
```
|
||||
|
||||
仅验证 hls.js 的 MMS 兼容修复可运行 `pnpm test:playback --scenarios mms`。该场景由 Chromium 的真实 MSE 完成解码和缓冲,仅模拟 MMS 构造器与 streaming 事件;报告标记 `simulated_mms: true`,不能替代 macOS 27 实机确认。
|
||||
|
||||
其他参数:`--media-dir DIR` 复用已有 `list.m3u8` 与 `seg*.ts`;`--browser-executable PATH` 使用已安装的匹配版本 Chromium;`--output NEW_DIR` 指定新的产物目录。`FFMPEG_PATH` 可指定 FFmpeg 可执行文件。命令拒绝覆盖已经存在的输出目录。
|
||||
|
||||
仓库附带手动触发的 GitHub Actions 工作流 **Playback diagnostics**。工作流输入默认仍为五个场景
|
||||
`seek,legacy,stall,lifecycle,mms`,与 CLI 默认值不同;需要完整默认组时显式填写
|
||||
`seek,legacy,stall,lifecycle,mms,gesture,proxy`。它会在检查失败时仍上传日志、截图与追踪,保留 7 天;不会随推送自动运行。
|
||||
仓库附带手动触发的 GitHub Actions 工作流 **Playback diagnostics**。工作流输入默认为
|
||||
`seek,legacy,lifecycle,gesture,proxy`;需要其余场景(`portrait-fit,ios-native,recovery,review,tv`)时显式填写。它会在检查失败时仍上传日志、截图与追踪,保留 7 天;不会随推送自动运行。
|
||||
|
||||
**覆盖边界:** 这些测试使用真实 React 控件、video、hls.js 与本地 HTTP 分片,但业务 API 和 Tauri 日志 IPC 使用替身。它们不执行真实 Rust 媒体代理,不验证真实 CDN、代理/TUN、Tauri 的 CSP/Origin/DNS 策略,也不能证明 macOS 27 的 ManagedMediaSource 问题已复现或修复。Rust 日志持久化/轮转/脱敏由 Rust 回归覆盖,执行结果以对应 GitHub Actions 记录为准;macOS 特有问题使用实机 `playback.log` 确认。
|
||||
@@ -0,0 +1,41 @@
|
||||
## HGhubX 2.2.0-pre.2(预发布)
|
||||
|
||||
在 pre.1 基础上修复三组反馈:切线掉登录(#145)、播放器手势与全屏控件(#146)、
|
||||
TV 货架排版。欢迎试用反馈;不作为正式版本推送。
|
||||
|
||||
### 新增
|
||||
|
||||
- **长按加速可换挡**:右上长按 2x 起,按住左右滑每 80px 换一档(2x → 3x → 4x → 6x,
|
||||
来回滑可升可降,每档震动反馈);上滑后松手锁定当前档位,不再固定 2x(#146)。
|
||||
- 设置 → 播放新增「全屏无操作自动隐藏控件」:关 / 3秒 / 5秒 / 10秒(默认 3 秒,
|
||||
暂停时不隐藏)(#146)。
|
||||
|
||||
### 改进
|
||||
|
||||
- 加速提示弱化:去掉高亮底色,改半透明黑底白字;锁定提示并入顶部倍速胶囊
|
||||
(「上滑后松手锁定 / 松手锁定」),移除画面中部误导性的拖放目标提示(#146)。
|
||||
- 全屏右上角「退出全屏 / 锁定控制」两键显式 44×44 并留出 12px 间距,不再贴死(#146)。
|
||||
- 专题列表卡片去掉可选简介,封面 + 数量 + 单行标题统一高度对齐;
|
||||
专题详情页的可展开简介保留。
|
||||
|
||||
### 修复
|
||||
|
||||
- **切换线路不再掉登录**(#145):固定线路与发布页确认的镜像之间手动/自动切线、
|
||||
重启后均保留会话(实测同账号库跨线可用);自定义线路仍会清空会话,token 不外带。
|
||||
`.ai` 只是导航站(接口全 404),已从线路列表移除。
|
||||
- **横屏全屏左右滑可以调进度了**(#146):旋转舞台的手势坐标统一换算
|
||||
(进度拖动 / 上下划切集 / 长按换挡与锁定),全屏时不再被原生滚动取消手势。
|
||||
- **全屏控件不再一碰就闪、单击稳定显隐**(#146):移除 2.8s 不分平台的自动隐藏
|
||||
与单击语义的冲突,移动端按上面的新设置计时。
|
||||
- TV:「继续观看」封面与货架等宽对齐;选集每格固定高度,长标题两行截断不再参差。
|
||||
|
||||
### 验证
|
||||
|
||||
- CI 全绿:Rust 109 通过 / 0 失败,浏览器 smoke 4/4,构建与尺寸预算通过。
|
||||
- 播放回归 10/10(含 TV 遥控验收 13/13、竖屏适配、恢复与代理切换)。
|
||||
- 真机手势手感与 TV 实机显示请以安装包实测为准。
|
||||
|
||||
### 已知限制
|
||||
|
||||
- TV↔手机标准包之间的账号/片库跨包迁移后端尚未移植,TV 端迁移入口保持隐藏。
|
||||
- iOS 包为无证书构建(需自行签名侧载);macOS 为 ad-hoc 签名。
|
||||
@@ -0,0 +1,45 @@
|
||||
## HGhubX 2.2.0
|
||||
|
||||
架构重构 + Android TV / 车机老内核兼容 + 开屏与播放体验全面升级的正式版本。包含 pre.1 / pre.2 及后续全仓审计与性能打磨的全部内容。
|
||||
|
||||
### 新增
|
||||
|
||||
- **Android TV 独立版**(`com.hghubx.tv`):Leanback 桌面入口与横屏 Banner、遥控器方向键 / 确认 / 返回 / 媒体键导航、本地 IndexedDB 片库与拼音/标题搜索索引、overscan 安全边距设置。
|
||||
- **老 WebView 与车机大屏兼容**(#138):前端构建降级至 `chrome66 / safari14.1`(含 CSS `dvh / color-mix / cascade-layers` 回退、经典 `iife` Worker、ES5 启动看门狗与运行时 API 垫片);Android 标准版原生层桥接系统状态栏与车机常驻底栏安全区(`--native-sat/sab/sal/sar`),`quick` 与正式构建均覆盖 32 位 `arm` 与 64 位 `arm64`。
|
||||
- **长按加速可换挡**(#146):右上长按 2x 起,按住左右滑每 80px 换一档(2x → 3x → 4x → 6x,来回滑可升可降,每档震动反馈);上滑后松手锁定当前档位。
|
||||
- 设置 → 播放新增「全屏无操作自动隐藏控件」:关 / 3秒 / 5秒 / 10秒(默认 3 秒,暂停时不隐藏)(#146)。
|
||||
- 长按操作提示加入「双击暂停播放」说明。
|
||||
|
||||
### 改进
|
||||
|
||||
- **开屏零闪烁与冷启动大幅提速**:
|
||||
- 原生窗口、`index.html` `data-hg-launching` 背景锁与开屏层统一锚定 `#071218`,彻底消除亮色/暗色主题切换时的首尾白屏或灰屏闪烁,以及 `<Suspense>` 未就绪时的空帧跳变;
|
||||
- 开屏动画改为全外层独立 GPU 合成层(仅驱动 `transform3d` + `opacity`),消除逐帧 SVG 路径重绘与多段缓动顿挫,首帧独占上屏后下一帧并发挂载业务壳;
|
||||
- 消除入口二次动态分包瀑布流,并将 `Feed` + `hls.js`(`524 kB`)从首屏壳剥离并行预热,`AcceptedApp` 关键路径体积缩减 **84.6%**(降至 `113.8 kB`),首屏选线与推荐流请求显著提前。
|
||||
- **前端渲染与状态隔离**:Toast 通知与账号同步状态改为独立订阅,避免全局重渲染;内联播放器全屏与分页请求逻辑收口复用;亮色模式表面层次与对比度优化。
|
||||
- 加速提示弱化并入顶部倍速胶囊(「上滑后松手锁定 / 松手锁定」),移除画面中部拖放提示;全屏右上「退出 / 锁定」两键 44×44、间距 12px(#146);大屏横屏操作栏自动切换双列紧凑布局避免顶边裁切(#138)。
|
||||
- **全站界面视觉对齐与内容屏蔽补全**:修复分类页「排行榜 / 专题 / 标签」窄屏高度偏大与上偏错位并补齐专属语义图标,统一全站二级页顶栏尺寸与边距、标签分组卡片与单行屏蔽工具条、搜索页三段式卡片间距、海报双徽章等高防撞、桌面侧栏图标中轴及设置展开面板双重内边距问题;搜索页「热搜榜」与「热门题材」同步接入屏蔽标签过滤;移除视频与帖子详情的分享入口并重排操作栏对齐;清理冗余副标题,「HGhubX 热榜」统一为「排行榜」。
|
||||
- 仓库结构整理:前端按 `app / features / shared` 归组并拆分 `Feed` 子面板与手势模块;Rust 按 `api / net / media / lines` 拆分并独立 `updater / net_diag / publish_parser`。
|
||||
|
||||
### 修复
|
||||
|
||||
- **切换线路不再掉登录,且在播流不中断转圈**(#145):
|
||||
- 固定线路与发布页确认镜像之间手动/自动切线及冷启动重启均保留登录会话(即使当前回退到固定线路也会校验已存镜像信任);自定义线路仍严格清空凭据,移除 `.ai` 导航站;
|
||||
- 区分代理变更与线路变更事件:后台自动选线后健康在播视频保持连贯播放,仅对未就绪/报错/预取项按新线路重拉。
|
||||
- **播放与多实例交互修复**:
|
||||
- 修复移动端底部信息浮层遮挡右侧「全屏」按钮命中区域,并补齐旧版 WebKit 前缀 Fullscreen API、桌面窗口全屏回退及 Linux WebKitGTK 窗口全屏状态同步;
|
||||
- 暂停状态下进入/退出全屏或拖动进度条均保留用户暂停意图,不再意外恢复播放(#138);
|
||||
- 修复压栈多级 `Feed` 页面同时响应全屏快捷键或画中画状态串扰、音量滑块松手跳变、锁屏态残留手势、搜索返回焦点与我的/关注列表状态同步细节;
|
||||
- 竖屏视频按原始比例完整显示,横屏保留「铺满 / 适应」切换(#142)。
|
||||
- **后端安全与缓存隔离加固**:媒体分片与图片缓存纳入代理/安全模式代次隔离,严格校验本机 loopback Host/Origin 边界,更新检查精确匹配当前平台安装包后缀,安卓剪贴板诊断日志裁剪至 256KiB 上限(#142)。
|
||||
- 启动动画期间按返回键仅跳过开屏,不再误触发底层页面弹栈或直接退出应用。
|
||||
- TV:「继续观看」封面与货架等宽;选集每格固定高度、长标题两行截断;跨包迁移后端未移植时正常启动。
|
||||
|
||||
### 验证
|
||||
|
||||
- 全部 CI/CD 合并为单一工作流,并复用预装工具链与包缓存加速:Rust 112 通过 / 0 失败,浏览器 smoke 全通过,前端双版本(标准版 + TV 版)构建、文档链接、尺寸预算与播放回归矩阵全绿通过。
|
||||
|
||||
### 已知限制
|
||||
|
||||
- TV↔手机标准包之间的账号/片库跨包迁移后端尚未移植,TV 端迁移入口保持隐藏。
|
||||
- iOS 包为无证书构建(需自行签名侧载);macOS 为 ad-hoc 签名。
|
||||
@@ -11,25 +11,27 @@ ad-hoc 签名都不应进入仓库或本机脚本输出。
|
||||
## 事实来源
|
||||
|
||||
- 前端脚本与版本:[`package.json`](../../package.json)、[`vite.config.ts`](../../vite.config.ts)、
|
||||
[`tsconfig.json`](../../tsconfig.json)、[`tsconfig.tests.json`](../../tsconfig.tests.json)。
|
||||
[`tsconfig.json`](../../tsconfig.json)、[`tsconfig.node.json`](../../tsconfig.node.json)、
|
||||
[`tsconfig.tests.json`](../../tsconfig.tests.json)。
|
||||
- Tauri 配置:[`src-tauri/tauri.conf.json`](../../src-tauri/tauri.conf.json) 的
|
||||
`beforeBuildCommand`、`bundle`、`bundle.android.versionCode`;
|
||||
[`tauri.macos.conf.json`](../../src-tauri/tauri.macos.conf.json)、
|
||||
[`tauri.linux.conf.json`](../../src-tauri/tauri.linux.conf.json)、
|
||||
[`tauri.ios.conf.json`](../../src-tauri/tauri.ios.conf.json)。
|
||||
[`tauri.ios.conf.json`](../../src-tauri/tauri.ios.conf.json)、
|
||||
[`tauri.tv.conf.json`](../../src-tauri/tauri.tv.conf.json)。
|
||||
- Rust 版本:[`src-tauri/Cargo.toml`](../../src-tauri/Cargo.toml) 的 `[package].version`、
|
||||
`custom-protocol` feature;[`src-tauri/Cargo.lock`](../../src-tauri/Cargo.lock) 的 `hghubx` 包。
|
||||
- CI:[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) 的 `frontend`、`rust`、`smoke`
|
||||
job;[`playback.yml`](../../.github/workflows/playback.yml);
|
||||
[`build-ios.yml`](../../.github/workflows/build-ios.yml);
|
||||
[`release.yml`](../../.github/workflows/release.yml) 的 `windows`、`android`、`macos`、`ios`、
|
||||
`linux`、`check`、`release` job。
|
||||
- CI/CD(全仓唯一工作流):[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml),
|
||||
合并了日常校验(`frontend`、`rust`、`smoke`、`playback` 矩阵)与发版构建(`windows`、
|
||||
`android` 标准/TV 矩阵、`macos`、`ios`、`linux`、`release`),每次事件只产生一条运行记录。
|
||||
- 版本/预算门禁:[`scripts/set-version.mjs`](../../scripts/set-version.mjs)、
|
||||
[`scripts/check-version-sync.mjs`](../../scripts/check-version-sync.mjs)、
|
||||
[`scripts/check-doc-links.mjs`](../../scripts/check-doc-links.mjs)、
|
||||
[`scripts/check-size-budgets.mjs`](../../scripts/check-size-budgets.mjs)、
|
||||
[`tools/size-budgets.json`](../../tools/size-budgets.json)。
|
||||
- iOS 打包:[`scripts/build-ios-unsigned.sh`](../../scripts/build-ios-unsigned.sh);图标/启动屏:
|
||||
- iOS/TV 打包:[`scripts/build-ios-unsigned.sh`](../../scripts/build-ios-unsigned.sh)、
|
||||
[`scripts/build-android-tv.mjs`](../../scripts/build-android-tv.mjs)、
|
||||
[`scripts/patch-android-tv.mjs`](../../scripts/patch-android-tv.mjs);图标/启动屏:
|
||||
`generate-ios-icons.mjs`、`sync-ios-icons.mjs`、`patch-ios-splash.mjs`、
|
||||
`sync-android-icons.mjs`、`patch-android-splash.mjs`。
|
||||
- 本地入口:[`Makefile`](../../Makefile) 的 `check`、`test-rust`、`test-web`、`test-smoke`、
|
||||
@@ -38,30 +40,41 @@ ad-hoc 签名都不应进入仓库或本机脚本输出。
|
||||
## 主运行时路径
|
||||
|
||||
1. 安装依赖用 `pnpm install --frozen-lockfile`(CI 全部如此)。`pnpm build` 执行
|
||||
`tsc --noEmit`、`tsc --project tsconfig.tests.json`、`vite build`;`vite.config.ts` 从
|
||||
`tsc --noEmit`、`tsc --project tsconfig.node.json`、`tsc --project tsconfig.tests.json`、`vite build`;`vite.config.ts` 从
|
||||
`package.json` 注入 `__APP_VERSION__`,避免界面版本写死。
|
||||
2. Tauri 构建的 `beforeBuildCommand` 在 Vite 构建后跑图标生成/同步和 Android/iOS 启动屏补丁,
|
||||
再打包 `dist`。桌面入口为 `pnpm tauri build`;开发为 `pnpm tauri dev`。
|
||||
3. `make check` 等价于 `test-rust` + `test-web` + `docs` + `budget`:
|
||||
Vite 构建目标是 `["chrome66","safari14.1"]`(CSS 目标 `chrome66/safari13`,Worker 格式
|
||||
`iife` 以兼容无 module worker 的 Chromium 66–79),`cssCodeSplit:false`、`cssMinify:false`;
|
||||
`scripts/legacy-css.ts`(enforce:post)在 generateBundle 阶段对汇总后的 CSS 做旧引擎回退
|
||||
(dvh、color-mix、cascade layers)、追加 `src/styles/legacy-webview.css` 并用 lightningcss
|
||||
压缩。Tailwind 插件以 `optimize:false` 运行,避免其内置优化先吃掉需要降级的语法。TV 构建脚本
|
||||
`build-android-tv.mjs` 复用同一 `pnpm build`,自动获得同一条兼容链。
|
||||
2. Tauri 构建的 `beforeBuildCommand` 在 Vite 构建后跑图标生成/同步和 Android 启动屏补丁
|
||||
(iOS 启动屏补丁由 `scripts/build-ios-unsigned.sh` 执行),再打包 `dist`。桌面入口为
|
||||
`pnpm tauri build`;开发为 `pnpm tauri dev`。
|
||||
3. `make check` 等价于 `test-rust` + `test-web` + `docs` + `budget` + `release-check`:
|
||||
`cargo check --manifest-path src-tauri/Cargo.toml --all-targets`、
|
||||
`cargo test --manifest-path src-tauri/Cargo.toml --lib`、`pnpm build`、
|
||||
`node scripts/check-doc-links.mjs`、`node scripts/check-size-budgets.mjs`。它**不包含**
|
||||
`node scripts/check-doc-links.mjs`、`node scripts/check-size-budgets.mjs`、
|
||||
`node scripts/check-version-sync.mjs`。它**不包含**
|
||||
`pnpm test:smoke`;smoke 由 CI 的独立 job 和 `make test-smoke` 执行。
|
||||
4. CI `frontend`:Node 22、pnpm 10、`pnpm install --frozen-lockfile`、版本字段检查、文档链接、
|
||||
`pnpm build`、尺寸预算。
|
||||
`rust`:Linux 系统依赖、`cargo check --all-targets`、`cargo test --lib`。
|
||||
`smoke`:安装 Chromium,解析 `BROWSER_EXECUTABLE`,运行 `pnpm test:smoke` 的四个稳定用例。
|
||||
5. `playback.yml` 和 `build-ios.yml` 都是 `workflow_dispatch`,不在每个 PR 自动跑。前者需要
|
||||
FFmpeg + Chromium,按 `seek,legacy,stall,lifecycle,mms` 等场景输出诊断;后者只验证 iOS
|
||||
工程能编出未签名 ipa。
|
||||
6. `release.yml` 在推送 `v*` tag 或手动触发时运行;在分支上手动运行且 `tag` 留空时,
|
||||
只构建所选范围,不发布 GitHub Release。各平台构建 job 先跑
|
||||
4. CI/CD 日常校验(`pull_request`、分支 `push` 或手动 `mode=ci`):
|
||||
- `frontend`:Node 22、pnpm 10、版本字段检查、文档链接、标准版与 TV 版 `pnpm build`、尺寸预算。
|
||||
- `rust`:Linux 系统依赖、`cargo check --all-targets`、`cargo test --lib`。
|
||||
- `smoke`:安装 Chromium,运行 `pnpm test:smoke`。
|
||||
- `playback`:安装 FFmpeg + Chromium,单次工作流内按矩阵并行执行 `core` 与 `extended`
|
||||
(覆盖 `seek,legacy,lifecycle,gesture,proxy,portrait-fit,ios-native,recovery,review,tv`);
|
||||
手动 `mode=playback` 可只跑播放诊断或指定 `scenarios` 子集。
|
||||
5. CI/CD 打包与发布(推送 `v*` tag 或手动 `mode=package`):在分支上手动运行且 `tag` 留空时,
|
||||
只构建所选范围(如 `platforms=ios` 仅验证未签名 ipa),不发布 GitHub Release。各平台构建 job 先跑
|
||||
`node scripts/set-version.mjs "$V"`:同步 `package.json`、`tauri.conf.json`(含
|
||||
`bundle.android.versionCode`)、`Cargo.toml` 和 `Cargo.lock` 的 `hghubx` 版本。
|
||||
`versionCode = major*1_000_000 + minor*1_000 + patch`,minor/patch 超过 999 会报错。
|
||||
7. 平台产物:
|
||||
6. 平台产物:
|
||||
- Windows:NSIS 安装包 + `HGhubX_<version>_x64_portable.zip`。
|
||||
- Android:`pnpm tauri android build --apk --split-per-abi`,按 ABI 产出并用 secrets 中的
|
||||
keystore `apksigner` 签名,文件名 `HGhubX_<version>_<abi>.apk`;随后 `aapt2 dump badging`
|
||||
- Android 标准版与 TV 版:`android` 矩阵(`standard` / `tv`)执行 `pnpm tauri android build --apk --split-per-abi`
|
||||
(正式发布编 `aarch64 armv7 x86_64`,`quick` 编 `aarch64 armv7`,显式 `android-arm64` 仅编 `aarch64`),
|
||||
按 ABI 产出并用 secrets 中的 keystore `apksigner` 签名,文件名分别为
|
||||
`HGhubX_<version>_<abi>.apk` 与 `HGhubX-TV_<version>_<abi>.apk`;随后 `aapt2 dump badging`
|
||||
打印实际 versionCode。
|
||||
- macOS:`quick` 只编 arm64;正式发布编 universal,产物 `HGhubX_<version>_universal.dmg`
|
||||
(quick 为 `_arm64.dmg`),ad-hoc 签名。
|
||||
@@ -69,19 +82,17 @@ ad-hoc 签名都不应进入仓库或本机脚本输出。
|
||||
`scripts/build-ios-unsigned.sh <version>`;Xcode `CODE_SIGNING_ALLOWED=NO`,产出
|
||||
`HGhubX_<version>_ios.ipa`。
|
||||
- Linux:`pnpm tauri build` 产出 deb,文件名 `HGhubX_<version>_amd64.deb`。
|
||||
8. `release` job 依赖五个平台 job,以 `always()` 等待它们结束;发布条件是 `v*` tag ref,
|
||||
或手动触发且 `tag` 非空,条件中没有限制 `platforms=all` 或 `quick=false`。
|
||||
它下载已有 artifact,用 `softprops/action-gh-release` 上传 `artifacts/*`;
|
||||
如果存在 `docs/release-notes/<tag>.md` 就作为正文,否则自动生成说明。`fail_on_unmatched_files`
|
||||
为 true,没有匹配产物时失败,但不保证五个平台的产物全部存在。
|
||||
9. `check` job 只做编译/类型检查/单测,不产包;手动 `platforms=check` 是最快的“能不能编”验证。
|
||||
7. `release` job 依赖五个平台构建 job(其中 `android` 矩阵覆盖标准版与 TV 版),在 `!cancelled()` 且
|
||||
`windows`、`android`、`macos`、`linux` 全部成功(`ios` 允许成功或失败)时执行;发布条件是 `v*` tag ref,
|
||||
或手动 `mode=package` 且 `tag` 非空、`platforms=all`、`quick=false`。它下载已有 artifact,用
|
||||
`softprops/action-gh-release` 上传 `artifacts/*`;如果存在 `docs/release-notes/<tag>.md` 就作为正文,
|
||||
否则开启 `generate_release_notes` 自动生成说明。
|
||||
|
||||
## 状态转换
|
||||
|
||||
- 版本:源版本(tag 或 `tauri.conf.json`)→ `set-version.mjs` 校验 `major.minor.patch` →
|
||||
写四份文件 → 平台构建。`check-version-sync.mjs` 由常规 CI 的 `frontend` job 调用,
|
||||
不在当前 release workflow 中;它要求四处版本字符串一致,并检查 Android `versionCode`
|
||||
为正整数,没有校验该值与版本号公式是否一致。
|
||||
写四份文件 → 平台构建。`check-version-sync.mjs` 由 `ci.yml` 的 `frontend` job 调用;
|
||||
它要求四处版本字符串一致,并检查 Android `versionCode` 与公式推导值一致。
|
||||
- Android versionCode:版本号解析 → `major*1e6 + minor*1e3 + patch` → 写入
|
||||
`bundle.android.versionCode` → APK 签名 → `aapt2` 复核。
|
||||
- iOS:`ios init` 生成工程 → 补 plist → 启动 Tauri options server → Xcode release 构建 →
|
||||
@@ -121,5 +132,5 @@ node scripts/check-version-sync.mjs
|
||||
```
|
||||
|
||||
`make check` 不包含 smoke;需要浏览器用例时单独 `pnpm test:smoke`。`pnpm test:playback` 需要
|
||||
FFmpeg/Chromium,`build-ios.yml` 需要 macOS runner。报告里必须写清命令、版本/输入、字面结果和
|
||||
退出状态;没有运行的命令不能写成“已通过”。
|
||||
FFmpeg/Chromium,iOS 打包校验通过 `ci.yml`(`mode=package, platforms=ios`)在 macOS runner 执行。
|
||||
报告里必须写清命令、版本/输入、字面结果和退出状态;没有运行的命令不能写成“已通过”。
|
||||
@@ -11,8 +11,12 @@ Feed 负责列表播放页的条目位置、详情/帖子读取、标签门、
|
||||
|
||||
- [`src/features/feed/Feed.tsx`](../../src/features/feed/Feed.tsx):`requestPlay`、
|
||||
`useFeedDetails` 的调用、`tagKey`/`permissionKey`、`effectiveVideoIds`、
|
||||
`details`/`posts`、`relatedByVideo`、`actionContext`、`actionIsCurrent`、
|
||||
`onLike`/`onFav`/`onFollow`、桌面 dock 与移动 Sheet。
|
||||
`details`/`posts`、`relatedByVideo`、`actionContext`;视口/手势/动作与界面覆盖层分别位于同目录的
|
||||
[`useFeedViewport.ts`](../../src/features/feed/useFeedViewport.ts)、
|
||||
[`useFeedTouchGestures.ts`](../../src/features/feed/useFeedTouchGestures.ts)、
|
||||
[`useFeedActions.ts`](../../src/features/feed/useFeedActions.ts)、
|
||||
[`FeedItemChrome.tsx`](../../src/features/feed/FeedItemChrome.tsx)、
|
||||
[`FeedPlayerShellChrome.tsx`](../../src/features/feed/FeedPlayerShellChrome.tsx)。
|
||||
- [`src/features/feed/useFeedDetails.ts`](../../src/features/feed/useFeedDetails.ts):
|
||||
`detailRequests`、`requestDetail`、`effectiveVideoIds`、`detailsRef`。
|
||||
- [`src/features/feed/Panels.tsx`](../../src/features/feed/Panels.tsx) 的
|
||||
@@ -47,7 +51,8 @@ Feed 负责列表播放页的条目位置、详情/帖子读取、标签门、
|
||||
7. `requestPlay(id, episode)` 的 key 是
|
||||
`` `${accountScope}:${lineEpoch}:${id}:${episode}` ``,最多缓存 12 个 Promise。
|
||||
当前集开始播放后,才预取下一集的地址;下一部视频还要先通过详情/标签检查。
|
||||
8. 评论面板使用 `api.comments` 或 `api.postComments`,选集使用当前 `detail.episodes`,
|
||||
8. 评论面板使用 `api.comments` 或 `api.postComments`(仅短剧开放评论发送,帖子评论只读,
|
||||
不向短剧接口串写),选集使用当前 `detail.episodes`,
|
||||
详情面板显示作者/标签/相关推荐。桌面端停靠 `desktop-dock-panel`,移动端使用
|
||||
`Sheet`;面板本身不在 Feed 之外维护第二套详情缓存。
|
||||
9. 相关推荐只在 `panel === "detail"` 时调用 `api.related`,缓存键是
|
||||
@@ -91,11 +96,9 @@ Feed 负责列表播放页的条目位置、详情/帖子读取、标签门、
|
||||
pnpm build
|
||||
pnpm test:smoke
|
||||
pnpm test:api-loading
|
||||
pnpm test:channel-pagination
|
||||
pnpm test:topic-pagination
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
`test:smoke` 当前包含 `api-loading`、`storage-migration`、`line-selection`、
|
||||
`diagnostic-copy`;分页脚本单独运行。浏览器 fixture 使用 mock Tauri IPC 且阻断外部请求,
|
||||
`diagnostic-copy`。浏览器 fixture 使用 mock Tauri IPC 且阻断外部请求,
|
||||
不能证明真实上游的正文结构或账号接口;真实接口变化需要另加网络隔离的 fixture 或手动验证。
|
||||
@@ -36,7 +36,7 @@
|
||||
[`segment.rs`](../../src-tauri/src/media/segment.rs) 的 `load_segment()`;
|
||||
[`response.rs`](../../src-tauri/src/media/response.rs) 的 `respond()`、`apply_byte_range()`、
|
||||
`segment_response()`。
|
||||
- 诊断与脱敏:[`src-tauri/src/net/diagnostics.rs`](../../src-tauri/src/net/diagnostics.rs) 的
|
||||
- 诊断与脱敏:[`src-tauri/src/net_diag.rs`](../../src-tauri/src/net_diag.rs) 的
|
||||
`diagnose()`、`proxy_state()`、`test_proxy()`;
|
||||
[`src-tauri/src/net/redact.rs`](../../src-tauri/src/net/redact.rs) 的
|
||||
`redact_proxy()`、`is_proxy_error()`、`heal_client()`、`err_text()`、
|
||||
@@ -110,7 +110,6 @@ cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
node scripts/test-network-settings.mjs
|
||||
node scripts/test-diagnostic-copy.mjs
|
||||
node scripts/test-ios-native-media.mjs
|
||||
node scripts/test-linux-media-policy.mjs
|
||||
```
|
||||
|
||||
`src-tauri/src/net/`、`media_dns.rs`、`media/*`、`network_policy.rs` 的单元测试覆盖信封形状、重试终止、
|
||||
|
||||
@@ -15,8 +15,8 @@ loopback、Windows 的自定义标题栏与注册表代理判断、Android 的 W
|
||||
- 模块注册与启动:[`src-tauri/src/lib.rs`](../../src-tauri/src/lib.rs) 的 `mod` 列表、
|
||||
`media_http_origin`、`allowed_dev_host`、`allowed_frontend_origin`、`run()` 的
|
||||
`on_page_load`/`setup`、`generate_handler!`。
|
||||
- iOS 布局:[`src-tauri/src/ios_layout.rs`](../../src-tauri/src/ios_layout.rs) 的 `apply()`、
|
||||
`set_text_interaction_on_webview()`;原生媒体服务:
|
||||
- iOS 布局与方向:[`src-tauri/src/ios_layout.rs`](../../src-tauri/src/ios_layout.rs) 的 `apply()`、
|
||||
`set_text_interaction_on_webview()`、`request_orientation()`;原生媒体服务:
|
||||
[`src-tauri/src/ios_media_http.rs`](../../src-tauri/src/ios_media_http.rs) 的 `origin()`、
|
||||
`start()`、`Endpoint`、`parse_request()`、`app_origin()`、`MAX_CONNECTIONS`。
|
||||
- macOS 标题栏:[`src-tauri/src/macos_titlebar.rs`](../../src-tauri/src/macos_titlebar.rs) 的
|
||||
@@ -74,12 +74,15 @@ loopback、Windows 的自定义标题栏与注册表代理判断、Android 的 W
|
||||
1. WebKitGTK 4.1 默认没有 MediaSource,hls.js 用不上;`<video>` 交给 GStreamer,而 GStreamer
|
||||
不认 `hg://`。`setup` 调 `linux_http::start()`,在 `127.0.0.1:17650` 起一个只服务
|
||||
`/img`、`/hls`、`/seg` 的 HTTP 代理。
|
||||
2. `linux_http::serve()` 只接受 `GET/HEAD`,单线程处理每个连接,读/写超时 30 秒;只处理
|
||||
单个、无 `If-Range` 的 `Range`,HEAD 保留表示长度但不发 body。响应头只保留一份
|
||||
2. `linux_http::serve()` 只接受 `GET/HEAD` 且要求唯一合法 `Host` 与至多一个合法 `Origin`,
|
||||
单线程处理每个连接,读/写超时 30 秒;只处理单个、无 `If-Range` 的 `Range`,
|
||||
HEAD(含错误响应)保留表示长度但不发 body。响应头只保留一份
|
||||
`Content-Length`/CORS,并强制 `Connection: close`。
|
||||
3. `linux_webview::configure()` 在 WebKit 的 `WebsiteDataManager` 上设置 `NoProxy`。API/CDN
|
||||
仍由 Rust 按用户代理访问;这只防止 127.0.0.1 媒体请求被 GNOME 代理二次转发。
|
||||
`media::LOCAL_ORIGIN` 在这里等于 `http://127.0.0.1:17650`,与前端 `LOCAL` 必须同步修改。
|
||||
3. `linux_webview::configure()` 在 WebKit 的 `WebsiteDataManager` 上设置 `NoProxy`(API/CDN
|
||||
仍由 Rust 按用户代理访问,只防止 127.0.0.1 媒体请求被 GNOME 代理二次转发),并把 WebKitGTK
|
||||
的 `enter-fullscreen`/`leave-fullscreen` 信号桥接到 `tauri::Window::set_fullscreen`(对齐
|
||||
Windows `ContainsFullScreenElementChanged` 行为)。`media::LOCAL_ORIGIN` 在这里等于
|
||||
`http://127.0.0.1:17650`,与前端 `LOCAL` 必须同步修改。
|
||||
4. Linux bundling 只发布 deb,依赖 GStreamer base/good/bad/ugly/libav/vaapi 和
|
||||
`intel-media-va-driver`。
|
||||
|
||||
@@ -112,6 +115,22 @@ loopback、Windows 的自定义标题栏与注册表代理判断、Android 的 W
|
||||
覆盖层卸载时释放(引用计数 + 幂等释放,StrictMode 安全)。动画结束后只剩 App 监听,
|
||||
顺序恢复为 面板/弹层 → 全屏 → 登录框 → 页面栈 → 回首页 → 退出。未同意首启不持门。
|
||||
TV 版走 `registerBack`(remote.ts 的 scope 分发),不经 `runBack()`,门对 TV 无影响。
|
||||
6. 老 WebView(Chromium 66 车机/电视、旧 iOS WKWebView)启动支持分三层:
|
||||
`index.html` 内嵌 ES5 启动看门狗(模块图之外的 error/unhandledrejection 监听 +
|
||||
15s 超时,失败渲染可复制诊断的 `#hg-startup-error` 面板);`src/legacyRuntime.ts`
|
||||
补 `globalThis`/`Object.fromEntries`/`Promise.allSettled`/`flat(Map)`/`queueMicrotask`/
|
||||
`matchMedia.addEventListener`/`ResizeObserver` 等运行时 API,并探测 flex-gap 写
|
||||
`data-legacy-flex-gap`;构建层 `vite.config.ts` 以 `chrome66/safari14.1` 为语法目标,
|
||||
`scripts/legacy-css.ts` 在 CSS 汇总后做 dvh/color-mix 回退、postcss-preset-env 降级与
|
||||
lightningcss 压缩,并追加 `src/styles/legacy-webview.css` 的几何回退。标准入口
|
||||
`src/main.tsx` 与 TV 入口 `src/tv/bootstrap.tsx` 都在首个成功 commit 调
|
||||
`markStartupReady()` 解除看门狗;协议未签署不算启动失败。
|
||||
7. 冷启动无闪烁链路:原生窗口/系统启动屏(`tauri.conf.json`、`patch-android-splash.mjs`、
|
||||
`patch-ios-splash.mjs`)、`index.html` 的 `html[data-hg-launching]` 背景锁与 `.hg-launch`
|
||||
统一固定为 `#071218`,阻止外链 CSS 在 React 挂载前把 `body` 刷成亮色 `#eeece7` 或暗灰底。
|
||||
`StartupGate` 首帧独占提交合成线程动画,下一帧再并发挂载已分离 `Feed`/`hls.js` 的业务壳,
|
||||
待入场时间满足且底层界面提交(`contentReady` 或超时兜底)后再释放 `data-hg-launching`、同步
|
||||
`meta[name="theme-color"]` 并淡出覆盖层。
|
||||
|
||||
## 状态转换
|
||||
|
||||
@@ -145,9 +164,6 @@ loopback、Windows 的自定义标题栏与注册表代理判断、Android 的 W
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
pnpm build
|
||||
node scripts/test-ios-native-media.mjs
|
||||
node scripts/test-linux-media-policy.mjs
|
||||
node scripts/test-mobile-layout.mjs
|
||||
node scripts/test-ios-ui.mjs
|
||||
```
|
||||
|
||||
单元测试覆盖 macOS 红绿灯居中、Apple 代理匹配、Linux 响应头/HEAD、iOS 请求校验和媒体
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
[`useProxyPlaybackRecovery.ts`](../../src/features/playback/useProxyPlaybackRecovery.ts)。
|
||||
- 输入与传输:[`useSeekInput.ts`](../../src/features/playback/useSeekInput.ts)、
|
||||
[`useInlinePlayerFullscreen.tsx`](../../src/features/playback/useInlinePlayerFullscreen.tsx)、
|
||||
[`src/shared/lib/fullscreen.ts`](../../src/shared/lib/fullscreen.ts)、
|
||||
[`mediaTransport.ts`](../../src/features/playback/mediaTransport.ts)、
|
||||
[`mediaErrors.ts`](../../src/features/playback/mediaErrors.ts)。
|
||||
- 后端传输:[`src-tauri/src/ios_media_http.rs`](../../src-tauri/src/ios_media_http.rs)、
|
||||
@@ -38,8 +39,8 @@
|
||||
|
||||
## 主运行时路径
|
||||
|
||||
1. Feed 通过 `api.play(id, ep)` 取得 `streams.main` 或旧字段 `video_url`;
|
||||
`preferHevc` 且存在 `streams.hevc` 时优先 HEVC。播放器拿到的是上游 m3u8,
|
||||
1. Feed 通过 `api.play(id, ep)` 取得 `streams.main`、旧字段 `video_url`,或仅存在 HEVC 时的
|
||||
`streams.hevc`/`video_url_hevc` 回退;`preferHevc` 且存在 `streams.hevc` 时优先 HEVC。播放器拿到的是上游 m3u8,
|
||||
通过 `playbackSource` 转成 `${LOCAL}/hls?u=...`;已经是 `/hls`、`/seg` 的本地地址
|
||||
不会被重复包裹。
|
||||
2. `VideoSurface` 在 `Hls.isSupported()` 且不是直通 `/seg` 时创建 hls.js;
|
||||
@@ -49,8 +50,9 @@
|
||||
3. hls.js 使用 `autoStartLoad: false`,在 `MANIFEST_PARSED` 后按
|
||||
`startPosition`/`resume` 调 `startLoad`。`FRAG_BUFFERED` 清空恢复计数和错误;
|
||||
`ERROR` 只把 fatal network/media 交给 `createHlsRecovery`。
|
||||
4. `usePlaybackActivity` 在页面失活时暂停并 `stopLoad()`,在重新激活时按
|
||||
`wanted` 恢复;`play()` 的 Promise 返回后会再次检查页面是否仍激活。
|
||||
4. `usePlaybackActivity` 在页面失活时暂停并 `stopLoad()`(处于画中画 `pictureInPictureElement`
|
||||
时保持播放,退出画中画且页面仍失活时再暂停),在重新激活时按 `wanted` 与 `startPosition`
|
||||
恢复;`play()` 的 Promise 返回后会再次检查页面是否仍激活。
|
||||
5. seek 有两种入口:桌面 `useSeekInput`/`PlayerControls`,移动端
|
||||
`useSeekInput`/进度条手势。指针移动只预览,松手提交一次;
|
||||
`VideoSurface.seek` 把目标夹到 `duration - 0.15`(避免 iOS 片尾卡死),
|
||||
@@ -74,6 +76,17 @@
|
||||
“之前自动播放过”强行继续。
|
||||
- seek:preview → commit → `seeking` → `seeked`/`playing`;拖动取消、
|
||||
页面失活或换源不会提交旧目标。
|
||||
- 控件闲置隐藏(`src/features/feed/fsIdle.ts`):桌面 2.8s(键盘聚焦控件时不隐藏);
|
||||
移动沉浸全屏按设置 `fsIdleSecs`(`hghubx_app_v1` 内,0/3/5/10 秒,默认 3,0=不自动隐藏),
|
||||
单击画面切换显隐、双击仍是暂停/播放;暂停时不隐藏。桌面与内嵌全屏统一经
|
||||
`src/shared/lib/fullscreen.ts` 兼容标准与 `webkit` 前缀 Fullscreen API,不支持或被拒绝时
|
||||
回退至应用内全屏并同步 Tauri 窗口全屏;移动端 Feed 底部信息容器保持 `pointer-events: none`
|
||||
(仅对详情按钮与进度条显式开启命中),避免跨宽布局盒遮挡右侧操作栏(如「全屏」)与画面手势。CSS 旋转舞台(`.fs-landscape`)上
|
||||
的分区判定/横拖定位/上下划切集/长按换挡都先经 `getHoldPoint` 把屏幕坐标换算回
|
||||
播放器坐标(rotate(90deg):播放器 x=屏幕 dy、y=屏幕 -dx),长按锁定的命中检测则用
|
||||
顶部倍速胶囊的实时 DOM 矩形(`isInsideHoldTarget`,旋转后同样成立):手指移动 ≥12px
|
||||
且移入胶囊才提示「松手即可锁定」,松手位置再验一次命中。全屏 overlay 的 touch-action
|
||||
固定为 none,避免原生 pan-y 把视觉横滑取消掉。
|
||||
- 媒体错误:hls fatal 显示 `type/details/status`,原生错误走
|
||||
`mediaErrorMessage`;手动重试走同一个 `useProxyPlaybackRecovery` 路径。
|
||||
|
||||
@@ -98,9 +111,8 @@
|
||||
|
||||
```sh
|
||||
pnpm build
|
||||
pnpm test:playback --scenarios seek,legacy,stall,lifecycle,mms,gesture,proxy,ios-native,recovery,review
|
||||
pnpm test:playback --scenarios seek,legacy,lifecycle,gesture,proxy,portrait-fit,ios-native,recovery,review,tv
|
||||
node scripts/test-ios-native-media.mjs
|
||||
node scripts/test-linux-media-policy.mjs
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
|
||||
@@ -40,10 +40,14 @@
|
||||
|
||||
| 运行期键 | 旧键 | 内容 |
|
||||
| --- | --- | --- |
|
||||
| `hghubx_app_v1` | `hghub_app_v1` | 游客偏好、收藏、关注、观看记录、搜索历史、音量、`swipeEp`、`preferHevc` |
|
||||
| `hghubx_app_v1` | `hghub_app_v1` | 游客偏好、收藏、关注、观看记录、搜索历史、音量、`muteOnStartup`、`swipeEp`、`preferHevc`、`fsIdleSecs` |
|
||||
| `hghubx_swipe_ep_v2` | `hghub_swipe_ep_v2` | 上下划切集的一次性迁移标记 |
|
||||
| `hghubx_theme` | `hghub_theme` | `light`/`dark`/`system` |
|
||||
| `hghubx_auto_line` | `hg.autoLine` | 自动选线开关 |
|
||||
| `hghubx_usage_agreement` | — | 使用协议版本与签署时间 |
|
||||
| `hghubx_mobile_hold_guide_v1` | — | 移动端首次长按倍速教程已读标记 |
|
||||
| `hghubx_tv_display_v1` | `hghubx.tv.display.v1` | TV 端缩放、过扫描与减少动效设置 |
|
||||
| `hghubx_tv_playback_v1` | `hghubx-tv-playback-v1` | TV 端连播、倍速与编码偏好 |
|
||||
| `CONTENT_PREFERENCES_KEY` | — | 屏蔽标签、暂停过滤、隐藏无标签内容 |
|
||||
| `ACCOUNT_KEY` | — | 按 `[origin, user.id]` 分桶的账号本地副本 |
|
||||
|
||||
@@ -119,7 +123,6 @@
|
||||
```sh
|
||||
node scripts/test-storage-migration.mjs
|
||||
node scripts/test-account-sync-empty-state.mjs
|
||||
node scripts/test-clear-history-confirm.mjs
|
||||
cargo test --manifest-path src-tauri/Cargo.toml --lib
|
||||
```
|
||||
|
||||
|
||||
@@ -22,11 +22,10 @@ origin”,不负责 HTTP 客户端、代理、DNS 固定或媒体字节(见
|
||||
`trusted_auth_origin()`、`persisted_line()`、`bind_base()`、`set_base()`、
|
||||
`set_custom_base()`、`save_line()`、`apply_base()`。
|
||||
- 固定线路与发布页:[`src-tauri/src/lines/mirror.rs`](../../src-tauri/src/lines/mirror.rs) 的
|
||||
`FIXED`、`PUBLISH_PAGES`、`MIRROR_MAX`、`mirrors()`、`merge_publishers()`、
|
||||
`parse_mirrors()`、`script_src()`、`absolute()`、`remember_published()`、
|
||||
`FIXED`、`PUBLISH_PAGES`、`mirrors()`、`merge_publishers()`、`remember_published()`、
|
||||
`is_trusted_mirror()`、`is_fixed()`、`verify_published_origin()`。
|
||||
- JS-as-data 解析:[`src-tauri/src/lines/jsparse.rs`](../../src-tauri/src/lines/jsparse.rs) 的
|
||||
`js_tokens()`、`js_string()`、`js_array()`。
|
||||
- 发布脚本与 JS-as-data 解析:[`src-tauri/src/publish_parser.rs`](../../src-tauri/src/publish_parser.rs) 的
|
||||
`MIRROR_MAX`、`parse_mirrors()`、`script_src()`、`absolute()`、`js_tokens()`、`js_string()`、`js_array()`。
|
||||
- 探测与选择:[`src-tauri/src/lines/probe.rs`](../../src-tauri/src/lines/probe.rs) 的
|
||||
`healthy_video_data()`、`probe_hit()`、`probe()`、`auto_candidates()`、`pick_from_hits()`、
|
||||
`auto_pick()`、`try_main()`、`health()`。
|
||||
@@ -71,9 +70,9 @@ origin”,不负责 HTTP 客户端、代理、DNS 固定或媒体字节(见
|
||||
8. 当前是镜像时,健康检查会调用 `line_try_main()`:只探固定线路 1,通了就切回,代价是一个
|
||||
请求;两端可信时会话经 rebase 保留,旧 origin 不可信(如自定义线路)则清空。切回后
|
||||
`hg:line-changed` 让列表和详情按新 `lineEpoch` 重新读取。`line_auto` 落盘切换时同样执行
|
||||
rebase-or-clear;`app_boot` 在当前 origin 查不到会话、但存有旧 origin 会话时,先做
|
||||
`verify_published_origin()` 可信刷新(填充 `TRUSTED_MIRRORS`),再尝试 rebase,覆盖
|
||||
重启后 `line.json` 已是新线路的场景。
|
||||
rebase-or-clear;`app_boot` 在当前 origin 查不到会话、但存有旧 origin 会话时,同时对旧 origin
|
||||
与当前 origin 做 `verify_published_origin()` 可信刷新(填充 `TRUSTED_MIRRORS`),再尝试 rebase,覆盖
|
||||
镜像登录后重启回固定线路或切新镜像的场景。
|
||||
9. 带 token 的业务请求在严格模式下还要过 `trusted_auth_origin()`:固定线路、本次进程内由发布页
|
||||
确认过的镜像,或用户显式保存的自定义线路。已落盘但尚未验证的镜像会触发
|
||||
`verify_published_origin()`;验证失败只允许游客浏览,登录/注册被拒绝。
|
||||
@@ -115,6 +114,6 @@ node scripts/test-line-selection.mjs
|
||||
pnpm test:smoke
|
||||
```
|
||||
|
||||
`src-tauri/src/lines/mod.rs` 的单元测试覆盖脚本词法、域名规范化、发布页同源、交错合并、
|
||||
`src-tauri/src/publish_parser.rs` 与 `src-tauri/src/lines/mod.rs` 的单元测试覆盖脚本词法、域名规范化、发布页同源、交错合并、
|
||||
all-down、健康判据和候选排序;`test-line-selection` 覆盖前端自动选线状态。
|
||||
发布页和真实镜像的可达性属于外部状态,测试不请求上游网络;实机结果需单独记录。
|
||||
@@ -111,7 +111,10 @@ for (const [rel, entry] of Object.entries(config)) {
|
||||
}
|
||||
|
||||
if (update && !failed) {
|
||||
for (const [rel, count] of Object.entries(measured)) config[rel] = count;
|
||||
for (const [rel, count] of Object.entries(measured)) {
|
||||
const existing = config[rel];
|
||||
config[rel] = typeof existing === "object" && existing !== null ? { ...existing, budget: count } : count;
|
||||
}
|
||||
fs.writeFileSync(configPath, `${JSON.stringify(config, null, 2)}\n`);
|
||||
console.log(`budget: wrote ${path.relative(root, configPath)}`);
|
||||
}
|
||||
|
||||
@@ -32,4 +32,15 @@ if (!Number.isInteger(versionCode) || versionCode < 1) {
|
||||
console.error("release-check: src-tauri/tauri.conf.json has no bundle.android.versionCode.");
|
||||
process.exit(1);
|
||||
}
|
||||
const parsed = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(pkg.version ?? "");
|
||||
if (!parsed) {
|
||||
console.error(`release-check: invalid version format "${pkg.version}".`);
|
||||
process.exit(1);
|
||||
}
|
||||
const [, major, minor, patch] = parsed.map(Number);
|
||||
const expectedCode = major * 1_000_000 + minor * 1_000 + patch;
|
||||
if (versionCode !== expectedCode) {
|
||||
console.error(`release-check: bundle.android.versionCode=${versionCode} does not match expected ${expectedCode} for ${pkg.version}; run scripts/set-version.mjs.`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`release-check: ok ${pkg.version}, android versionCode=${versionCode}`);
|
||||
@@ -1,22 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>iOS overlay interaction fixture</title>
|
||||
<style>
|
||||
/* Keep this behavior fixture independent of the app's visual theme. */
|
||||
body { margin: 0; }
|
||||
button, input, [tabindex] { margin: 4px; }
|
||||
.ios-overlay { position: fixed; inset: 0; z-index: calc(260 + var(--ios-overlay-order, 0)); display: grid; place-items: center; }
|
||||
.ios-overlay-backdrop { position: absolute; inset: 0; background: #7775; }
|
||||
.ios-dialog { position: relative; min-width: 200px; padding: 24px; border: 2px solid #555; background: white; }
|
||||
.is-closing { opacity: 0; pointer-events: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<aside id="pre-inert" inert><button>Previously inert background</button></aside>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="./ios-overlays.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,39 +0,0 @@
|
||||
import { StrictMode, useEffect, useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { Modal, Sheet } from "../../src/shared/ui/ios/overlays";
|
||||
import { registerOverlayBack, runBack, setBackHandler } from "../../src/shared/lib/back";
|
||||
|
||||
const events = { closed: [] as string[], escapedToPage: 0 };
|
||||
|
||||
function Fixture() {
|
||||
const initiallyNested = new URLSearchParams(location.search).has("nested");
|
||||
const [parent, setParent] = useState(initiallyNested);
|
||||
const [child, setChild] = useState(initiallyNested);
|
||||
const [empty, setEmpty] = useState(false);
|
||||
Object.assign(window, { iosOverlayFixture: { setParent, runBack, registerOverlayBack, setBackHandler, events } });
|
||||
|
||||
useEffect(() => {
|
||||
const onKey = (event: KeyboardEvent) => { if (event.key === "Escape") events.escapedToPage++; };
|
||||
window.addEventListener("keydown", onKey);
|
||||
return () => window.removeEventListener("keydown", onKey);
|
||||
}, []);
|
||||
|
||||
return <main id="background">
|
||||
<button id="opener" onClick={() => setParent(true)}>Open parent</button>
|
||||
<button id="empty-opener" onClick={() => setEmpty(true)}>Open empty</button>
|
||||
<Modal open={parent} onClose={() => { events.closed.push("parent"); setParent(false); }} label="Parent">
|
||||
{/* Native autoFocus runs before the frame's layout effect; its opener must survive. */}
|
||||
<button id="first" data-autofocus autoFocus={!initiallyNested} onClick={() => setChild(true)}>Open child</button>
|
||||
<button id="skip" tabIndex={-1}>Skip in tab order</button>
|
||||
<div id="custom" tabIndex={0}>Focusable custom control</div>
|
||||
<button id="last">Last</button>
|
||||
<Sheet open={child} onClose={() => { events.closed.push("child"); setChild(false); }} label="Child">
|
||||
<button id="child-first" data-autofocus>Child first</button>
|
||||
<button id="child-last">Child last</button>
|
||||
</Sheet>
|
||||
</Modal>
|
||||
<Modal open={empty} onClose={() => setEmpty(false)} label="Empty"><p>No interactive controls</p></Modal>
|
||||
</main>;
|
||||
}
|
||||
|
||||
createRoot(document.getElementById("root")!).render(<StrictMode><Fixture /></StrictMode>);
|
||||
@@ -1,23 +0,0 @@
|
||||
# 历史调查脚本
|
||||
|
||||
这里保存针对特定历史版本的对照与取证脚本,不加入常规回归入口。
|
||||
|
||||
`round-review-20261115.mjs` 保留 2026-11-15 修复审查的六项检查,以及固定基线
|
||||
`455f3ab744ba360b50f7af80803e91d2eaee15be` 的对照逻辑。它会拉取该提交,在独立目录中
|
||||
解压基线与当前 `HEAD`,生成差异和回滚脚本,再检查恢复后的历史收藏空态行为。
|
||||
取证和回滚都在隔离副本上执行,不重置当前工作区。
|
||||
|
||||
只有需要复查这次历史修复时,才在已安装依赖和 Chromium 的 GitHub Actions 环境中手动运行:
|
||||
|
||||
```sh
|
||||
node scripts/investigations/round-review-20261115.mjs
|
||||
```
|
||||
|
||||
脚本保留 `GITHUB_ACTIONS` 环境检查;结果写入
|
||||
`test-results/investigations/round-review-20261115/`。这里记录的是固定历史问题的预期,
|
||||
不能作为当前代码通用的验证入口。
|
||||
|
||||
常规审查继续使用 [`../test-round-review.mjs`](../test-round-review.mjs),由现有
|
||||
[`playback.yml`](../../.github/workflows/playback.yml) 的 `review` 场景调用。它只执行当前
|
||||
代码的七项回归(原有六项和网络设置交互),把结果写入 `test-results/round-review/report.json`,
|
||||
不拉取历史基线或生成历史回滚证据。
|
||||
@@ -1,102 +0,0 @@
|
||||
// Historical 2026-11-15 comparison and rollback evidence; run manually in GitHub Actions.
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { chmod, copyFile, mkdir, readFile, symlink, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = fileURLToPath(new URL("../../", import.meta.url));
|
||||
const output = join(root, "test-results", "investigations", "round-review-20261115");
|
||||
if (process.env.GITHUB_ACTIONS !== "true") throw new Error("Run this review only in GitHub Actions.");
|
||||
const baseline = "455f3ab744ba360b50f7af80803e91d2eaee15be";
|
||||
const scripts = [
|
||||
"test-inplace-search-back.mjs",
|
||||
"test-inplace-search-focus.mjs",
|
||||
"test-clear-history-confirm.mjs",
|
||||
"test-account-sync-empty-state.mjs",
|
||||
"test-topic-pagination.mjs",
|
||||
"test-post-detail-hot.mjs",
|
||||
];
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = { baseline, checks: [] };
|
||||
async function run(command, cwd) {
|
||||
const result = await new Promise((resolve) => {
|
||||
const child = spawn(command[0], command.slice(1), {
|
||||
cwd,
|
||||
env: { ...process.env, BROWSER_EXECUTABLE: process.env.BROWSER_EXECUTABLE || chromium.executablePath() },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let output = "";
|
||||
child.stdout.on("data", (chunk) => { output += chunk; process.stdout.write(chunk); });
|
||||
child.stderr.on("data", (chunk) => { output += chunk; process.stderr.write(chunk); });
|
||||
child.on("error", (error) => resolve({ exit: 1, output: `${output}\n${error.message}` }));
|
||||
child.on("close", (code) => resolve({ exit: code ?? 1, output }));
|
||||
});
|
||||
return { command, cwd, ...result };
|
||||
}
|
||||
for (const script of scripts) {
|
||||
const command = [process.execPath, join(root, "scripts", script)];
|
||||
const result = await run(command, root);
|
||||
report.checks.push({ script, command, ...result });
|
||||
}
|
||||
|
||||
// Reproduce one concrete regression before/after, and exercise the rollback on
|
||||
// an extracted copy. Never reset the checked-out feature branch.
|
||||
const evidence = join(output, "evidence");
|
||||
await mkdir(evidence, { recursive: true });
|
||||
execFileSync("git", ["fetch", "--depth=1", "origin", baseline], { cwd: root, stdio: "pipe" });
|
||||
execFileSync("git", ["archive", "--format=tar", `--output=${join(evidence, "BASELINE.tar")}`, baseline], { cwd: root });
|
||||
execFileSync("git", ["archive", "--format=tar.gz", `--output=${join(evidence, "MODIFIED_FILE.tar.gz")}`, "HEAD"], { cwd: root });
|
||||
const patch = execFileSync("git", ["diff", "--binary", baseline, "HEAD"], { cwd: root });
|
||||
await writeFile(join(evidence, "DIFF_FILE.patch"), patch);
|
||||
const rollback = `#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
target="\${1:?Pass an isolated checkout directory}"
|
||||
artifact_dir="$(cd -- "$(dirname -- "\${BASH_SOURCE[0]}")" && pwd)"
|
||||
git -C "$target" apply --reverse "$artifact_dir/DIFF_FILE.patch"
|
||||
printf 'Restored baseline source ${baseline}\\n'
|
||||
`;
|
||||
await writeFile(join(evidence, "ROLLBACK.sh"), rollback);
|
||||
await chmod(join(evidence, "ROLLBACK.sh"), 0o755);
|
||||
const prepare = async (name, archive) => {
|
||||
const target = join(output, name);
|
||||
await mkdir(target, { recursive: true });
|
||||
execFileSync("tar", ["-xf", join(evidence, archive), "-C", target]);
|
||||
execFileSync("git", ["init", "--quiet", target]);
|
||||
await symlink(join(root, "node_modules"), join(target, "node_modules"), "dir");
|
||||
return target;
|
||||
};
|
||||
const baselineCopy = await prepare("baseline-copy", "BASELINE.tar");
|
||||
const rollbackCopy = await prepare("rollback-copy", "MODIFIED_FILE.tar.gz");
|
||||
const accountScript = "scripts/test-account-sync-empty-state.mjs";
|
||||
await copyFile(join(root, accountScript), join(baselineCopy, accountScript));
|
||||
report.before = await run([process.execPath, accountScript], baselineCopy);
|
||||
report.rollback = await run(["bash", join(evidence, "ROLLBACK.sh"), rollbackCopy], root);
|
||||
// The same new regression check must detect the restored old behavior.
|
||||
await copyFile(join(root, accountScript), join(rollbackCopy, accountScript));
|
||||
report.restoredBehavior = await run([process.execPath, accountScript], rollbackCopy);
|
||||
const expectedRegression = result => result.exit !== 0 && result.output.includes("还没有收藏");
|
||||
const rollbackOkay = report.rollback.exit === 0 && expectedRegression(report.before) && expectedRegression(report.restoredBehavior);
|
||||
report.checks.push({ script: "baseline and isolated rollback", exit: rollbackOkay ? 0 : 1 });
|
||||
report.passed = report.checks.filter((check) => check.exit === 0).length;
|
||||
report.failed = report.checks.length - report.passed;
|
||||
await writeFile(join(output, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
const digest = data => createHash("sha256").update(data).digest("hex");
|
||||
const details = {
|
||||
changed: ["HLS fatal/manual retry and hidden-page queue", "media configuration generation", "favoritesKnown", "search key event propagation", "topic loaded count wording"],
|
||||
paths: ["MODIFIED_FILE.tar.gz", "DIFF_FILE.patch", "VERIFICATION.txt", "ROLLBACK.sh"].map(file => join(evidence, file)),
|
||||
baselineCommit: baseline,
|
||||
baselineArchiveSha256: digest(await readFile(join(evidence, "BASELINE.tar"))),
|
||||
modifiedCommit: execFileSync("git", ["rev-parse", "HEAD"], { cwd: root, encoding: "utf8" }).trim(),
|
||||
BASELINE: report.before,
|
||||
MODIFIED: report.checks,
|
||||
ROLLBACK: report.rollback,
|
||||
restoredBehavior: report.restoredBehavior,
|
||||
result: { passed: report.passed, failed: report.failed, originalCheckoutRemainsModified: true },
|
||||
};
|
||||
await writeFile(join(evidence, "VERIFICATION.txt"), `${JSON.stringify(details, null, 2)}\n`);
|
||||
// Reopen every deliverable before upload.
|
||||
for (const file of details.paths) await readFile(file);
|
||||
console.log(`Round review checks: ${report.passed} passed, ${report.failed} failed.`);
|
||||
process.exitCode = report.failed ? 1 : 0;
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { access, mkdir, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
@@ -12,10 +12,16 @@ const report = { environment: "Real App in Chromium with delayed mocked Tauri IP
|
||||
let vite, browser;
|
||||
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 14283, strictPort: true } });
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || "/usr/bin/google-chrome" });
|
||||
let executablePath = process.env.BROWSER_EXECUTABLE;
|
||||
if (!executablePath) {
|
||||
for (const candidate of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(candidate).then(() => true, () => false)) { executablePath = candidate; break; }
|
||||
}
|
||||
}
|
||||
browser = await chromium.launch({ headless: true, executablePath });
|
||||
|
||||
const openProfile = async ({ favoriteIds = [], delaySync = false, rejectFirstSync = false, rejectHistory = false, omitFavorites = false } = {}) => {
|
||||
const context = await browser.newContext({ viewport: { width: 390, height: 844 } });
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
// ChannelPage pagination regression: page 2 must stay after page 1, and sort must be page-local.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const output = join(root, "test-results", "channel-pagination", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
const report = {
|
||||
transport: "local browser fixture; Tauri IPC mocked",
|
||||
passed: [],
|
||||
external: [],
|
||||
pageErrors: [],
|
||||
};
|
||||
await mkdir(output, { recursive: true });
|
||||
let vite, browser, page;
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined });
|
||||
page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
||||
page.on("pageerror", error => report.pageErrors.push(error.message));
|
||||
await page.route("**/*", route => {
|
||||
const url = route.request().url();
|
||||
if (new URL(url).origin === new URL(origin).origin) return route.continue();
|
||||
report.external.push(url);
|
||||
return route.abort();
|
||||
});
|
||||
|
||||
await page.goto(`${origin}tests/channel-pagination.html`);
|
||||
await page.waitForFunction(() => window.channelPaginationFixture.history.length === 1);
|
||||
await page.evaluate(() => window.channelPaginationFixture.resolveNext("latest", 1));
|
||||
await page.waitForFunction(() => document.querySelectorAll(".ios-media-grid .ios-poster-title").length === 20);
|
||||
|
||||
const fixture = await page.evaluate(() => ({
|
||||
page1: window.channelPaginationFixture.page1,
|
||||
page2: window.channelPaginationFixture.page2,
|
||||
}));
|
||||
const titles = async () => page.locator(".ios-media-grid .ios-poster-title").allInnerTexts();
|
||||
const expectedPage = (list, sort) => {
|
||||
const arr = [...list];
|
||||
if (sort === "hot_window") arr.sort((a, b) => b.hot - a.hot);
|
||||
else if (sort === "random") arr.sort((a, b) => (a.id % 13) - (b.id % 13));
|
||||
else arr.sort((a, b) => b.id - a.id);
|
||||
return arr.map(v => v.title);
|
||||
};
|
||||
const scroller = page.locator(".scroll-y").last();
|
||||
const before = await titles();
|
||||
assert.equal(before.length, 20, "First page must show 20 cards");
|
||||
assert.deepEqual(before, expectedPage(fixture.page1, "latest"), "First page must follow server latest order");
|
||||
|
||||
await scroller.evaluate(el => { el.scrollTop = el.scrollHeight; });
|
||||
await page.waitForFunction(() => window.channelPaginationFixture.history.length === 2);
|
||||
const scrollBefore = await scroller.evaluate(el => ({ top: el.scrollTop, height: el.clientHeight, scrollHeight: el.scrollHeight }));
|
||||
await page.evaluate(() => window.channelPaginationFixture.resolveNext("latest", 2));
|
||||
await page.waitForFunction(() => document.querySelectorAll(".ios-media-grid .ios-poster-title").length === 40);
|
||||
await page.waitForTimeout(250);
|
||||
|
||||
const after = await titles();
|
||||
const scrollAfter = await scroller.evaluate(el => ({ top: el.scrollTop, height: el.clientHeight, scrollHeight: el.scrollHeight }));
|
||||
assert.equal(after.length, 40, "Second page must append all cards");
|
||||
assert.deepEqual(after.slice(0, 20), before, "All page 1 cards must remain above page 2 cards");
|
||||
assert.deepEqual(after.slice(20), expectedPage(fixture.page2, "latest"), "Page 2 cards must stay in page-local latest order");
|
||||
assert(scrollAfter.top > 0 && scrollAfter.top >= scrollBefore.top - 1, "Loading page 2 must not reset scrollTop");
|
||||
report.passed.push("ChannelPage: page 2 appended after page 1 and scrollTop preserved");
|
||||
|
||||
await page.getByRole("button", { name: "当前热播", exact: true }).click();
|
||||
await page.waitForFunction(() => {
|
||||
const h = window.channelPaginationFixture.history;
|
||||
return h.length > 0 && h[h.length - 1].args.sort === "hot_window";
|
||||
});
|
||||
await page.evaluate(() => window.channelPaginationFixture.resolveNext("hot_window", 1));
|
||||
await page.waitForFunction(() => document.querySelectorAll(".ios-media-grid .ios-poster-title").length === 20);
|
||||
assert.deepEqual(await titles(), expectedPage(fixture.page1, "hot_window"), "当前热播 must follow server hot_window order");
|
||||
report.passed.push("ChannelPage: 当前热播 is server-sorted");
|
||||
|
||||
await page.getByRole("button", { name: "精选推荐", exact: true }).click();
|
||||
await page.waitForFunction(() => {
|
||||
const h = window.channelPaginationFixture.history;
|
||||
return h.length > 0 && h[h.length - 1].args.sort === "random";
|
||||
});
|
||||
await page.evaluate(() => window.channelPaginationFixture.resolveNext("random", 1));
|
||||
await page.waitForFunction(() => document.querySelectorAll(".ios-media-grid .ios-poster-title").length === 20);
|
||||
assert.deepEqual(await titles(), expectedPage(fixture.page1, "random"), "精选推荐 must follow server random order");
|
||||
report.passed.push("ChannelPage: 精选推荐 is server-sorted");
|
||||
|
||||
assert.deepEqual(report.pageErrors, [], "No page errors");
|
||||
assert.deepEqual(report.external, [], "No upstream traffic");
|
||||
await page.screenshot({ path: join(output, "final.png"), fullPage: true });
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error);
|
||||
await page?.screenshot({ path: join(output, "failure.png"), fullPage: true }).catch(() => {});
|
||||
console.error(report.error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
console.log(`Artifacts: ${output}`);
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
import { installFixture } from "./fixtures/app-ui.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const output = new URL("../test-results/clear-history-confirm/", import.meta.url);
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = { environment: "Real App in Chromium with mocked Tauri IPC", checks: [], errors: [] };
|
||||
let vite, browser;
|
||||
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 14282, strictPort: true } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || "/usr/bin/google-chrome" });
|
||||
|
||||
const openProfile = async (loggedIn) => {
|
||||
const context = await browser.newContext({ viewport: { width: 390, height: 844 } });
|
||||
await context.addInitScript(installFixture, { theme: "light", titles: ["城市与晚风", "重逢在夏日以后", "星河旅人"] });
|
||||
await context.addInitScript(loggedIn => {
|
||||
localStorage.setItem("hghubx_usage_agreement", JSON.stringify({
|
||||
version: "2026-11-15-v1", accepted: true, acceptedAt: "2026-11-15T00:00:00.000Z",
|
||||
}));
|
||||
if (!loggedIn) return;
|
||||
const original = window.__TAURI_INTERNALS__.invoke;
|
||||
const user = {
|
||||
id: 9, username: "fixture", nickname: "示例用户", avatar: "", avatar_color: "#63748b",
|
||||
counts: { like: 2, collect: 3, following: 4 },
|
||||
interactions: { favorite_video_ids: [1, 2, 3], like_video_ids: [1] },
|
||||
};
|
||||
window.__CLEAR_HISTORY_DELETE_CALLS__ = [];
|
||||
window.__TAURI_INTERNALS__.invoke = async (command, args = {}) => {
|
||||
if (command === "app_boot") return { user, logged_in: true, base: "https://fixture.invalid", strict_security: true };
|
||||
if (command === "api_me") return { user, interactions: user.interactions, origin: "https://fixture.invalid" };
|
||||
if (command === "api_account_history") return {
|
||||
items: [{ id: 1, video_id: 1, target_type: "video", last_ep: 3, updated_at: "2026-11-15 00:00:00" }],
|
||||
pagination: { page: 1, pages: 1, size: 100, total: 1 },
|
||||
};
|
||||
if (command === "api_account_history_delete") {
|
||||
window.__CLEAR_HISTORY_DELETE_CALLS__.push(args.ids);
|
||||
return null;
|
||||
}
|
||||
return original(command, args);
|
||||
};
|
||||
}, loggedIn);
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => report.errors.push(error.message));
|
||||
await page.route("**/*", route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === new URL(origin).origin) return route.continue();
|
||||
return route.abort();
|
||||
});
|
||||
await page.goto(origin);
|
||||
await page.getByRole("navigation", { name: "主导航" }).waitFor();
|
||||
await page.getByRole("navigation", { name: "主导航" }).getByRole("button", { name: "我的", exact: true }).click();
|
||||
await page.getByRole("heading", { name: "我的", exact: true }).waitFor();
|
||||
return { context, page };
|
||||
};
|
||||
|
||||
{
|
||||
const { context, page } = await openProfile(false);
|
||||
await page.getByRole("button", { name: "观看历史", exact: true }).click();
|
||||
const clear = page.getByRole("button", { name: "清空观看历史", exact: true });
|
||||
await clear.waitFor();
|
||||
const before = await page.evaluate(() => localStorage.getItem("hghubx_app_v1"));
|
||||
await clear.click();
|
||||
const dialog = page.getByRole("dialog", { name: "清空观看历史", exact: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await dialog.getByRole("heading", { name: "清空观看历史" }).isVisible(), true);
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem("hghubx_app_v1")), before, "Opening confirmation must not delete guest history");
|
||||
await dialog.getByRole("button", { name: "取消", exact: true }).click();
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem("hghubx_app_v1")), before, "Cancel must preserve guest history");
|
||||
assert.equal(await clear.isVisible(), true, "Guest history remains after cancel");
|
||||
report.checks.push("guest clear action opens confirmation and cancel preserves history");
|
||||
await context.close();
|
||||
}
|
||||
|
||||
{
|
||||
const { context, page } = await openProfile(true);
|
||||
await page.getByRole("button", { name: "观看历史", exact: true }).click();
|
||||
const clear = page.getByRole("button", { name: "清空观看历史", exact: true });
|
||||
await clear.waitFor({ timeout: 10000 });
|
||||
await clear.click();
|
||||
const dialog = page.getByRole("dialog", { name: "清空观看历史", exact: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await dialog.getByText(/当前账号的云端观看历史与本机缓存都会被清除/).isVisible(), true);
|
||||
await dialog.getByRole("button", { name: "取消", exact: true }).click();
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.deepEqual(await page.evaluate(() => window.__CLEAR_HISTORY_DELETE_CALLS__), [], "Cancel must not call account history deletion");
|
||||
assert.equal(await clear.isVisible(), true, "Account history remains after cancel");
|
||||
report.checks.push("logged-in clear action requires confirmation and cancel makes no account deletion request");
|
||||
await context.close();
|
||||
}
|
||||
|
||||
report.passed = true;
|
||||
} catch (error) {
|
||||
report.failure = String(error?.stack || error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
await writeFile(new URL("report.json", output), JSON.stringify(report, null, 2));
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
console.log(fileURLToPath(output));
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { access, mkdir, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
@@ -12,10 +12,16 @@ const report = { environment: "Real App in Chromium with Android UA and mocked T
|
||||
let vite, browser;
|
||||
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 14280, strictPort: true } });
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || "/usr/bin/google-chrome" });
|
||||
let executablePath = process.env.BROWSER_EXECUTABLE;
|
||||
if (!executablePath) {
|
||||
for (const candidate of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(candidate).then(() => true, () => false)) { executablePath = candidate; break; }
|
||||
}
|
||||
}
|
||||
browser = await chromium.launch({ headless: true, executablePath });
|
||||
const context = await browser.newContext({
|
||||
viewport: { width: 375, height: 812 },
|
||||
userAgent: "Mozilla/5.0 (Linux; Android 15; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36",
|
||||
@@ -69,6 +75,52 @@ try {
|
||||
assert.equal(await page.getByRole("heading", { name: "专题", exact: true }).count(), 0, "Second back leaves the topic page");
|
||||
assert.equal(await page.getByRole("heading", { name: "分类", exact: true }).isVisible(), true, "Second back returns to the category tab");
|
||||
report.checks.push("second back follows the normal page stack");
|
||||
|
||||
// Focus/inert contract merged from the retired test-inplace-search-focus.mjs
|
||||
// (same component, mobile context): modal focus, inert background, shortcut
|
||||
// containment, Tab wrap, and trigger-focus restore on close.
|
||||
// The stack pop returned to the category tab; re-enter the topic page where
|
||||
// the in-place search trigger lives.
|
||||
await page.getByRole("button").filter({ has: page.getByText("专题", { exact: true }) }).click();
|
||||
await page.getByRole("heading", { name: "专题", exact: true }).waitFor();
|
||||
await searchButton.click();
|
||||
const dialog = page.getByRole("dialog", { name: "短剧搜索", exact: true });
|
||||
await dialog.waitFor();
|
||||
await field.waitFor();
|
||||
assert.equal(await field.evaluate(element => element === document.activeElement), true, "Search input receives initial focus");
|
||||
assert.equal(await dialog.getAttribute("aria-modal"), "true");
|
||||
assert.equal(await page.getByRole("heading", { name: "专题", exact: true }).evaluate(element => !!element.closest("[inert]")), true,
|
||||
"Page content behind the in-place search is inert");
|
||||
report.checks.push("search is a modal dialog, receives focus, and makes the covered page inert");
|
||||
|
||||
await dialog.getByRole("button", { name: "退出搜索", exact: true }).focus();
|
||||
for (const key of ["/", "1", "2", "3", "4"]) {
|
||||
await page.keyboard.press(key);
|
||||
assert.equal(await dialog.count(), 1, `${key} must not switch tabs or discard the search page`);
|
||||
assert.equal(await field.isVisible(), true, `${key} keeps the search field visible`);
|
||||
}
|
||||
await field.focus();
|
||||
report.checks.push("shell slash and number shortcuts stay inside search without navigating away");
|
||||
|
||||
const activeInside = () => page.evaluate(() => {
|
||||
const dialogElement = document.querySelector(".ios-inplace-search");
|
||||
return !!dialogElement && !!document.activeElement && dialogElement.contains(document.activeElement);
|
||||
});
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(await activeInside(), true, `Tab ${index + 1} stays inside the search dialog`);
|
||||
}
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert.equal(await activeInside(), true, `Shift+Tab ${index + 1} stays inside the search dialog`);
|
||||
}
|
||||
report.checks.push("Tab and Shift+Tab wrap without reaching the inert page");
|
||||
|
||||
await field.fill("都市");
|
||||
await field.press("Escape");
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.equal(await searchButton.evaluate(element => element === document.activeElement), true, "Closing search restores focus to its trigger");
|
||||
report.checks.push("Escape closes only the search and restores focus");
|
||||
report.passed = true;
|
||||
await page.screenshot({ path: fileURLToPath(new URL("final.png", output)), animations: "disabled" });
|
||||
} catch (error) {
|
||||
|
||||
@@ -1,150 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
import { installFixture } from "./fixtures/app-ui.mjs";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const output = new URL("../test-results/inplace-search-focus/", import.meta.url);
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = { environment: "Real App in Chromium with mocked Tauri IPC", checks: [], errors: [] };
|
||||
let vite, browser;
|
||||
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 14281, strictPort: true } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || "/usr/bin/google-chrome" });
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
|
||||
page.on("pageerror", error => report.errors.push(error.message));
|
||||
await page.addInitScript(installFixture, { theme: "light", titles: ["城市与晚风", "重逢在夏日以后", "星河旅人"] });
|
||||
await page.addInitScript(() => localStorage.setItem("hghubx_usage_agreement", JSON.stringify({
|
||||
version: "2026-11-15-v1", accepted: true, acceptedAt: "2026-11-15T00:00:00.000Z",
|
||||
})));
|
||||
await page.route("**/*", route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === new URL(origin).origin) return route.continue();
|
||||
return route.abort();
|
||||
});
|
||||
|
||||
await page.goto(origin);
|
||||
await page.getByRole("navigation", { name: "主导航" }).waitFor();
|
||||
await page.getByRole("navigation", { name: "主导航" }).getByRole("button", { name: "分类", exact: true }).click();
|
||||
await page.getByRole("button").filter({ has: page.getByText("专题", { exact: true }) }).click();
|
||||
await page.getByRole("heading", { name: "专题", exact: true }).waitFor();
|
||||
|
||||
const trigger = page.getByRole("button", { name: "搜索短剧", exact: true });
|
||||
await trigger.click();
|
||||
const dialog = page.getByRole("dialog", { name: "短剧搜索", exact: true });
|
||||
await dialog.waitFor();
|
||||
const field = dialog.getByRole("textbox", { name: "短剧搜索关键词", exact: true });
|
||||
await field.waitFor();
|
||||
assert.equal(await field.evaluate(element => element === document.activeElement), true, "Search input receives initial focus");
|
||||
assert.equal(await dialog.getAttribute("aria-modal"), "true");
|
||||
assert.equal(await page.getByRole("heading", { name: "专题", exact: true }).evaluate(element => !!element.closest("[inert]")), true,
|
||||
"Page content behind the in-place search is inert");
|
||||
report.checks.push("search is a modal dialog, receives focus, and makes the covered page inert");
|
||||
|
||||
// Non-input controls must not leak shortcuts to the shell's window listener.
|
||||
await dialog.getByRole("button", { name: "退出搜索", exact: true }).focus();
|
||||
for (const key of ["/", "1", "2", "3", "4"]) {
|
||||
await page.keyboard.press(key);
|
||||
assert.equal(await dialog.count(), 1, `${key} must not switch tabs or discard the search page`);
|
||||
assert.equal(await field.isVisible(), true, `${key} keeps the search field visible`);
|
||||
assert.equal(await page.getByRole("heading", { name: "专题", exact: true, includeHidden: true }).count(), 1,
|
||||
`${key} keeps the underlying topic page mounted`);
|
||||
}
|
||||
await field.focus();
|
||||
report.checks.push("shell slash and number shortcuts stay inside search without navigating away");
|
||||
|
||||
const activeInside = () => page.evaluate(() => {
|
||||
const dialogElement = document.querySelector(".ios-inplace-search");
|
||||
return !!dialogElement && !!document.activeElement && dialogElement.contains(document.activeElement);
|
||||
});
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await page.keyboard.press("Tab");
|
||||
assert.equal(await activeInside(), true, `Tab ${index + 1} stays inside the search dialog`);
|
||||
}
|
||||
for (let index = 0; index < 8; index += 1) {
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert.equal(await activeInside(), true, `Shift+Tab ${index + 1} stays inside the search dialog`);
|
||||
}
|
||||
report.checks.push("Tab and Shift+Tab wrap without reaching the inert page");
|
||||
|
||||
await page.evaluate(() => {
|
||||
const escaped = document.createElement("button");
|
||||
escaped.id = "escaped-focus";
|
||||
escaped.textContent = "background";
|
||||
const pageRoot = document.querySelector(".ios-page:not(.ios-inplace-search)");
|
||||
pageRoot?.append(escaped);
|
||||
escaped.focus();
|
||||
});
|
||||
assert.equal(await activeInside(), true, "Programmatic background focus is redirected into the dialog");
|
||||
await page.waitForFunction(() => document.getElementById("escaped-focus")?.closest("[inert]"));
|
||||
report.checks.push("escaped programmatic focus returns to the search dialog");
|
||||
|
||||
await field.fill("都市");
|
||||
await field.press("Escape");
|
||||
await dialog.waitFor({ state: "detached" });
|
||||
assert.equal(await trigger.evaluate(element => element === document.activeElement), true, "Closing search restores focus to its trigger");
|
||||
report.checks.push("Escape closes only the search and restores focus");
|
||||
|
||||
await trigger.click();
|
||||
await page.getByRole("dialog", { name: "短剧搜索", exact: true }).waitFor();
|
||||
await page.getByRole("textbox", { name: "短剧搜索关键词", exact: true }).fill("都市");
|
||||
await page.getByRole("textbox", { name: "短剧搜索关键词", exact: true }).press("Enter");
|
||||
await page.getByRole("button").filter({ hasText: "城市与晚风" }).first().waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("dialog", { name: "短剧搜索", exact: true }).waitFor({ state: "detached" });
|
||||
assert.equal(await trigger.evaluate(element => element === document.activeElement), true);
|
||||
report.checks.push("Escape also closes the search from a field/results state");
|
||||
|
||||
await trigger.click();
|
||||
const coveredDialog = page.getByRole("dialog", { name: "短剧搜索", exact: true, includeHidden: true });
|
||||
await coveredDialog.waitFor();
|
||||
await page.getByRole("textbox", { name: "短剧搜索关键词", exact: true }).fill("都市");
|
||||
await page.getByRole("textbox", { name: "短剧搜索关键词", exact: true }).press("Enter");
|
||||
await page.getByRole("button").filter({ hasText: "城市与晚风" }).first().click();
|
||||
await page.locator(".desktop-context-header").first().waitFor();
|
||||
assert.equal(await coveredDialog.evaluate(element => !!element.closest("[inert]")), true,
|
||||
"Opening a Feed covers and inerts the mounted in-place search");
|
||||
|
||||
await page.evaluate(() => {
|
||||
document.body.tabIndex = -1;
|
||||
document.body.focus();
|
||||
});
|
||||
assert.equal(await page.evaluate(() => document.activeElement === document.body), true);
|
||||
await page.keyboard.press("Tab");
|
||||
const coveredTabState = await page.evaluate(() => ({
|
||||
onBody: document.activeElement === document.body,
|
||||
insideSearch: !!document.activeElement?.closest(".ios-inplace-search"),
|
||||
insideInert: !!document.activeElement?.closest("[inert]"),
|
||||
}));
|
||||
assert.deepEqual(coveredTabState, { onBody: false, insideSearch: false, insideInert: false },
|
||||
"Tab in a visible Feed is not swallowed by the hidden search");
|
||||
report.checks.push("covered search does not intercept Tab in the Feed");
|
||||
|
||||
await page.evaluate(() => {
|
||||
document.body.tabIndex = -1;
|
||||
document.body.focus();
|
||||
});
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator(".desktop-context-header").first().waitFor({ state: "detached" });
|
||||
assert.equal(await coveredDialog.isVisible(), true, "Escape exits the Feed instead of closing the covered search");
|
||||
await page.keyboard.press("Escape");
|
||||
await coveredDialog.waitFor({ state: "detached" });
|
||||
report.checks.push("covered search does not intercept Escape; returning to it preserves the open search");
|
||||
|
||||
report.passed = true;
|
||||
await page.screenshot({ path: fileURLToPath(new URL("final.png", output)), animations: "disabled" });
|
||||
} catch (error) {
|
||||
report.failure = String(error?.stack || error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
await writeFile(new URL("report.json", output), JSON.stringify(report, null, 2));
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
console.log(fileURLToPath(output));
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from "node:assert/strict";
|
||||
import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
const here = dirname(fileURLToPath(import.meta.url));
|
||||
const root = process.argv[2] ? resolve(process.argv[2]) : join(here, "..");
|
||||
// Tauri CLI 2.10.1 templates/mobile/ios/Assets.xcassets/AppIcon.appiconset/Contents.json.
|
||||
const contents = readFileSync(join(here, "fixtures", "ios-appicon-contents.json"));
|
||||
const manifest = JSON.parse(contents);
|
||||
const temp = mkdtempSync(join(tmpdir(), "hghubx-ios-icons-"));
|
||||
|
||||
try {
|
||||
const script = join(root, "scripts", "sync-ios-icons.mjs");
|
||||
assert(existsSync(script), "iOS icon sync missing; generated projects keep Tauri template icons");
|
||||
const config = JSON.parse(readFileSync(join(root, "src-tauri", "tauri.conf.json"), "utf8"));
|
||||
assert(config.build.beforeBuildCommand.includes("node scripts/generate-ios-icons.mjs"), "Normal Tauri builds must generate square iOS artwork");
|
||||
assert(config.build.beforeBuildCommand.includes("node scripts/sync-ios-icons.mjs"), "Normal Tauri builds must sync iOS icons");
|
||||
const sourceSvg = readFileSync(join(root, "src-tauri", "icons", "ios", "source.svg"), "utf8");
|
||||
assert(!/<rect[^>]*\brx\s*=|<rect[^>]*\bstroke\s*=/.test(sourceSvg), "iOS source must not pre-mask its full-bleed background");
|
||||
assert(readdirSync(join(root, "src-tauri", "icons", "ios")).includes("source.svg"), "Tracked iOS source is missing");
|
||||
const generator = readFileSync(join(root, "scripts", "generate-ios-icons.mjs"), "utf8");
|
||||
assert.match(generator, /execFileSync\(process\.execPath/,
|
||||
"iOS icon generation must invoke the installed CLI through Node on Windows");
|
||||
assert.doesNotMatch(generator, /pnpm\.cmd/,
|
||||
"iOS icon generation must not spawn pnpm.cmd from beforeBuildCommand");
|
||||
const build = readFileSync(join(root, "scripts", "build-ios-unsigned.sh"), "utf8");
|
||||
const generateIndex = build.indexOf("node scripts/generate-ios-icons.mjs");
|
||||
const syncIndex = build.indexOf("node scripts/sync-ios-icons.mjs --required");
|
||||
assert(generateIndex >= 0 && generateIndex < build.indexOf("pnpm tauri ios build"), "Unsigned builds must generate artwork before starting Tauri/Xcode");
|
||||
assert(syncIndex >= 0 && syncIndex < build.indexOf("pnpm tauri ios build"), "Unsigned builds must sync before starting Tauri/Xcode");
|
||||
console.log("PASS: standard and unsigned build hooks");
|
||||
|
||||
for (const slot of manifest.images) {
|
||||
const [width, height] = slot.size.split("x").map(value => Number(value) * Number(slot.scale[0]));
|
||||
const image = readFileSync(join(root, "src-tauri", "icons", "ios", slot.filename));
|
||||
assert(image.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])), `${slot.filename} is not PNG`);
|
||||
assert.equal(image.readUInt32BE(16), width, `${slot.filename} width`);
|
||||
assert.equal(image.readUInt32BE(20), height, `${slot.filename} height`);
|
||||
}
|
||||
console.log("PASS: tracked iOS artwork has all 18 expected dimensions");
|
||||
|
||||
mkdirSync(join(temp, "scripts"), { recursive: true });
|
||||
cpSync(script, join(temp, "scripts", "sync-ios-icons.mjs"));
|
||||
const invoke = (...args) => spawnSync(process.execPath, [join(temp, "scripts", "sync-ios-icons.mjs"), ...args], { encoding: "utf8" });
|
||||
const expectFailure = (pattern, ...args) => {
|
||||
const result = invoke(...args);
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, pattern);
|
||||
};
|
||||
const skipped = invoke();
|
||||
assert.equal(skipped.status, 0);
|
||||
assert.match(skipped.stdout, /skipped/);
|
||||
expectFailure(/Apple project missing/, "--required");
|
||||
console.log("PASS: desktop skip and required Apple project");
|
||||
|
||||
const apple = join(temp, "src-tauri", "gen", "apple");
|
||||
const catalog = join(apple, "Assets.xcassets", "AppIcon.appiconset");
|
||||
mkdirSync(catalog, { recursive: true });
|
||||
expectFailure(/Contents.json/);
|
||||
writeFileSync(join(catalog, "Contents.json"), contents);
|
||||
const source = join(temp, "src-tauri", "icons", "ios");
|
||||
cpSync(join(root, "src-tauri", "icons", "ios"), source, { recursive: true });
|
||||
const seed = () => {
|
||||
for (const { filename } of manifest.images) writeFileSync(join(catalog, filename), "template icon");
|
||||
};
|
||||
const assertSeeded = () => {
|
||||
for (const { filename } of manifest.images) assert.equal(readFileSync(join(catalog, filename), "utf8"), "template icon");
|
||||
};
|
||||
seed();
|
||||
const last = manifest.images.at(-1).filename;
|
||||
const artwork = readFileSync(join(source, last));
|
||||
rmSync(join(source, last));
|
||||
expectFailure(new RegExp(last.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
|
||||
assertSeeded();
|
||||
writeFileSync(join(source, last), artwork);
|
||||
const wrongSize = Buffer.from(artwork);
|
||||
wrongSize.writeUInt32BE(1, 16);
|
||||
writeFileSync(join(source, last), wrongSize);
|
||||
expectFailure(/Wrong dimensions/);
|
||||
assertSeeded();
|
||||
writeFileSync(join(source, last), artwork);
|
||||
console.log("PASS: missing manifest, missing artwork and wrong dimensions fail before copying");
|
||||
|
||||
for (const bad of [{ images: [] }, { images: [{ filename: "../outside.png", size: "20x20", scale: "1x" }] }]) {
|
||||
writeFileSync(join(catalog, "Contents.json"), JSON.stringify(bad));
|
||||
expectFailure(/no image slots|no valid PNG filename/);
|
||||
assertSeeded();
|
||||
}
|
||||
writeFileSync(join(catalog, "Contents.json"), contents);
|
||||
console.log("PASS: malformed icon catalog is rejected");
|
||||
|
||||
for (let pass = 0; pass < 2; pass++) {
|
||||
const result = invoke("--required");
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /synced and verified: 18 slots/);
|
||||
for (const { filename } of manifest.images) {
|
||||
assert.deepEqual(readFileSync(join(catalog, filename)), readFileSync(join(source, filename)), filename);
|
||||
}
|
||||
assert.deepEqual(readFileSync(join(catalog, "Contents.json")), contents);
|
||||
}
|
||||
console.log("PASS: all 18 iPhone/iPad/marketing slots match tracked artwork; manifest preserved; repeat run unchanged");
|
||||
} catch (error) {
|
||||
console.error(`FAIL: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
rmSync(temp, { recursive: true, force: true });
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
// Exercise the real overlay/back components in StrictMode without Tauri or upstream traffic.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const output = join(root, "test-results", "ios-overlays", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
const report = {
|
||||
environment: "Real Modal/Sheet/controls/back in React StrictMode; Chromium behavior fixture; not native WebView verification",
|
||||
passed: [], pageErrors: [], external: [],
|
||||
};
|
||||
await mkdir(output, { recursive: true });
|
||||
let vite, browser, page;
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined });
|
||||
page = await browser.newPage();
|
||||
page.on("pageerror", error => report.pageErrors.push(error.message));
|
||||
await page.route("**/*", route => {
|
||||
if (new URL(route.request().url()).origin === new URL(origin).origin) return route.continue();
|
||||
report.external.push(route.request().url());
|
||||
return route.abort();
|
||||
});
|
||||
const url = `${origin}scripts/fixtures/ios-overlays.html`;
|
||||
const active = () => page.evaluate(() => document.activeElement?.id || document.activeElement?.getAttribute("aria-label"));
|
||||
const waitActive = id => page.waitForFunction(id =>
|
||||
(document.activeElement?.id || document.activeElement?.getAttribute("aria-label")) === id, id);
|
||||
const load = async (query = "") => {
|
||||
await page.goto(`${url}${query}`);
|
||||
await page.waitForFunction(() => !!window.iosOverlayFixture);
|
||||
};
|
||||
const openParent = async () => { await page.locator("#opener").click(); await waitActive("first"); };
|
||||
const openChild = async () => { await page.locator("#first").click(); await waitActive("child-first"); };
|
||||
const waitNoOverlays = () => page.waitForFunction(() => document.querySelectorAll(".ios-overlay").length === 0);
|
||||
|
||||
await load();
|
||||
await openParent();
|
||||
assert(await page.locator("#background").evaluate(el => el.inert), "Modal background must be inert");
|
||||
assert(await page.locator("#pre-inert").evaluate(el => el.inert));
|
||||
await page.keyboard.press("Shift+Tab"); assert.equal(await active(), "last");
|
||||
await page.keyboard.press("Tab"); assert.equal(await active(), "first");
|
||||
await page.keyboard.press("Tab"); assert.equal(await active(), "custom", "Skip negative tabindex but include custom controls");
|
||||
await page.keyboard.press("Tab"); assert.equal(await active(), "last");
|
||||
await page.evaluate(() => {
|
||||
const button = document.createElement("button");
|
||||
button.id = "late"; button.textContent = "Late background";
|
||||
document.body.append(button); button.focus();
|
||||
});
|
||||
assert.notEqual(await active(), "late", "Programmatic focus must stay in the dialog");
|
||||
await page.waitForFunction(() => document.getElementById("late").inert);
|
||||
await page.keyboard.press("Escape"); await waitActive("opener");
|
||||
await waitNoOverlays();
|
||||
assert(!(await page.locator("#background").evaluate(el => el.inert)));
|
||||
assert(!(await page.locator("#late").evaluate(el => el.inert)));
|
||||
assert(await page.locator("#pre-inert").evaluate(el => el.inert), "Pre-existing inert must survive close");
|
||||
report.passed.push("Native autoFocus restores its opener; Tab wraps through custom controls; escaped focus and late background nodes stay isolated; original inert values are restored");
|
||||
|
||||
await load();
|
||||
await openParent(); await openChild();
|
||||
assert(await page.getByRole("dialog", { name: "Parent", includeHidden: true }).evaluate(el => !!el.closest("[inert]")));
|
||||
await page.keyboard.press("Shift+Tab"); assert.equal(await active(), "child-last");
|
||||
await page.keyboard.press("Tab"); assert.equal(await active(), "child-first");
|
||||
await page.keyboard.press("Escape"); await waitActive("first");
|
||||
assert(!(await page.getByRole("dialog", { name: "Parent" }).evaluate(el => !!el.closest("[inert]"))));
|
||||
await page.keyboard.press("Escape"); await waitActive("opener");
|
||||
assert.deepEqual(await page.evaluate(() => window.iosOverlayFixture.events), { closed: ["child", "parent"], escapedToPage: 0 });
|
||||
report.passed.push("Escape closes only the top nested dialog, restores parent focus, then restores the page opener without reaching page navigation");
|
||||
|
||||
await load();
|
||||
await openParent(); await openChild();
|
||||
assert(await page.evaluate(() => window.iosOverlayFixture.runBack())); await waitActive("first");
|
||||
assert(await page.evaluate(() => window.iosOverlayFixture.runBack())); await waitActive("opener");
|
||||
assert.deepEqual(await page.evaluate(() => window.iosOverlayFixture.events.closed), ["child", "parent"]);
|
||||
report.passed.push("Hardware-back dispatch closes child then parent, restoring focus one layer at a time");
|
||||
|
||||
await load();
|
||||
await page.locator("#empty-opener").click(); await waitActive("Empty");
|
||||
await page.keyboard.press("Tab"); assert.equal(await active(), "Empty");
|
||||
await page.keyboard.press("Shift+Tab"); assert.equal(await active(), "Empty");
|
||||
await page.keyboard.press("Escape"); await waitActive("empty-opener");
|
||||
report.passed.push("A dialog without interactive controls receives and retains focus until Escape restores its opener");
|
||||
|
||||
await load();
|
||||
await openParent(); await openChild();
|
||||
await page.evaluate(() => window.iosOverlayFixture.setParent(false));
|
||||
assert.equal(await active(), "child-first", "Closing a background layer must not steal child focus");
|
||||
await page.getByRole("dialog", { name: "Child", includeHidden: true }).waitFor({ state: "detached" });
|
||||
await waitActive("opener");
|
||||
report.passed.push("Closing a parent while its child remains mounted preserves child focus and passes the original opener through final unmount");
|
||||
|
||||
await load("?nested=1"); await waitActive("child-first");
|
||||
const nesting = await page.locator(".ios-overlay.is-open").evaluateAll(elements => elements.map(element => ({
|
||||
name: element.querySelector('[role="dialog"]').getAttribute("aria-label"), inert: element.inert,
|
||||
z: Number(getComputedStyle(element).zIndex),
|
||||
})));
|
||||
const parent = nesting.find(layer => layer.name === "Parent"), child = nesting.find(layer => layer.name === "Child");
|
||||
assert(parent.inert && !child.inert && child.z > parent.z, "Initially mounted child must be the interactive and visual top layer");
|
||||
assert(await page.evaluate(() => window.iosOverlayFixture.runBack())); await waitActive("first");
|
||||
await page.keyboard.press("Escape"); await waitNoOverlays();
|
||||
report.passed.push("Initially open nested dialogs preserve child-above-parent order despite StrictMode and child-first layout effects");
|
||||
|
||||
await load();
|
||||
const back = await page.evaluate(() => {
|
||||
const { registerOverlayBack: register, runBack, setBackHandler } = window.iosOverlayFixture;
|
||||
const calls = [];
|
||||
setBackHandler(() => { calls.push("page"); return true; });
|
||||
const shared = () => { calls.push("shared"); return true; };
|
||||
const offFirst = register(shared), offSecond = register(shared);
|
||||
offFirst(); offFirst(); runBack(); offSecond();
|
||||
const offLower = register(() => { calls.push("lower"); return false; });
|
||||
const offMiddle = register(() => { calls.push("removed-middle"); return false; });
|
||||
const offTop = register(() => { calls.push("top"); offMiddle(); return false; });
|
||||
runBack(); offTop(); offLower();
|
||||
let offNew;
|
||||
const offOpening = register(() => { calls.push("opening"); offNew = register(() => { calls.push("new"); return true; }); return false; });
|
||||
runBack(); offOpening(); runBack(); offNew();
|
||||
const offError = register(() => { throw Error("fixture: close failed"); });
|
||||
const failedConsumed = runBack(); offError();
|
||||
setBackHandler(null);
|
||||
return { calls, failedConsumed, empty: runBack() };
|
||||
});
|
||||
assert.deepEqual(back, { calls: ["shared", "top", "lower", "page", "opening", "page", "new"], failedConsumed: true, empty: false });
|
||||
report.passed.push("Back registration cleanup is idempotent; mutation cannot repeat handlers or dismiss a newly opened layer; close failures cannot navigate the page underneath");
|
||||
|
||||
assert.deepEqual(report.pageErrors, [], "Fixture must have no uncaught browser errors");
|
||||
assert.deepEqual(report.external, [], "Overlay interaction tests must not require external traffic");
|
||||
console.log(`PASS: ${report.passed.length} iOS overlay regressions (React StrictMode)`);
|
||||
console.log(`Report: ${join(output, "report.json")}`);
|
||||
} catch (error) {
|
||||
report.error = error instanceof Error ? error.stack : String(error);
|
||||
await page?.screenshot({ path: join(output, "failure.png"), fullPage: true }).catch(() => {});
|
||||
throw error;
|
||||
} finally {
|
||||
await writeFile(join(output, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
}
|
||||
@@ -1,514 +0,0 @@
|
||||
/** Real application smoke coverage for the iOS material UI. No live account or media is used.
|
||||
* Run: BROWSER_EXECUTABLE=/opt/google/chrome/chrome node scripts/test-ios-ui.mjs
|
||||
* Screenshots and a machine-readable report are written below test-results/ios-ui/.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import { installFixture } from "./fixtures/app-ui.mjs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const output = new URL(`../test-results/ios-ui/${new Date().toISOString().replace(/[:.]/g, "-")}/`, import.meta.url);
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = {
|
||||
environment: "Real App in Chromium; mocked Tauri IPC and poster images. Android back event exercises the real App listener; native WebViews and media playback are not covered.",
|
||||
cases: [], errors: [], external: [],
|
||||
};
|
||||
const iphone = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 Version/17.1 Mobile/15E148 Safari/604.1";
|
||||
const android = "Mozilla/5.0 (Linux; Android 15; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Mobile Safari/537.36";
|
||||
const cases = [
|
||||
{ width: 1440, height: 960, mobile: false, theme: "dark" },
|
||||
{ width: 900, height: 740, mobile: false, theme: "light" },
|
||||
{ width: 390, height: 844, mobile: true, theme: "dark" },
|
||||
{ width: 320, height: 694, mobile: true, theme: "light", reduced: true },
|
||||
{ width: 844, height: 390, mobile: true, theme: "dark", reduced: true },
|
||||
{ width: 390, height: 844, mobile: true, theme: "light", android: true },
|
||||
{ width: 375, height: 812, mobile: true, theme: "light" },
|
||||
{ width: 375, height: 812, mobile: true, theme: "dark", minimumFontSize: 20 },
|
||||
];
|
||||
const caseName = test => `${test.width}x${test.height}-${test.theme}${test.android ? "-android" : ""}${test.minimumFontSize ? `-font${test.minimumFontSize}` : ""}`;
|
||||
const selectedCases = process.env.IOS_UI_CASE ? cases.filter(test => caseName(test) === process.env.IOS_UI_CASE) : cases;
|
||||
assert(selectedCases.length, "IOS_UI_CASE must match one of the defined scenarios");
|
||||
const titles = ["城市与晚风", "重逢在夏日以后", "星河旅人", "无声的答案", "我的奇妙假期", "晴天来信"];
|
||||
const titlePattern = new RegExp(`^(${titles.join("|")})$`);
|
||||
let vite, browser;
|
||||
|
||||
// Passed directly to addInitScript so every reload starts with isolated fixture data.
|
||||
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0 } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
const browserOptions = { headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined };
|
||||
browser = await chromium.launch(browserOptions);
|
||||
for (const test of selectedCases) {
|
||||
const name = caseName(test);
|
||||
const result = { ...test, name, checks: [], screenshots: [], passed: false };
|
||||
report.cases.push(result);
|
||||
const caseBrowser = test.minimumFontSize ? await chromium.launch({ ...browserOptions,
|
||||
args: [`--blink-settings=minimumFontSize=${test.minimumFontSize},minimumLogicalFontSize=${test.minimumFontSize}`],
|
||||
}) : browser;
|
||||
const context = await caseBrowser.newContext({
|
||||
viewport: { width: test.width, height: test.height }, colorScheme: test.theme,
|
||||
reducedMotion: test.reduced ? "reduce" : "no-preference",
|
||||
...(test.mobile ? { userAgent: test.android ? android : iphone, isMobile: true, hasTouch: true } : {}),
|
||||
});
|
||||
await context.addInitScript(installFixture, { theme: test.theme, titles });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(12000);
|
||||
page.on("pageerror", error => report.errors.push({ case: name, message: error.message }));
|
||||
await page.route("**/*", route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === new URL(origin).origin) return route.continue();
|
||||
if (url.pathname === "/img") return route.fulfill({
|
||||
contentType: "image/svg+xml", headers: { "Access-Control-Allow-Origin": "*" },
|
||||
body: '<svg xmlns="http://www.w3.org/2000/svg" width="360" height="480"><defs><linearGradient id="g" x2="1" y2="1"><stop stop-color="#5b7e94"/><stop offset="1" stop-color="#172e42"/></linearGradient></defs><rect width="360" height="480" fill="url(#g)"/><circle cx="180" cy="150" r="60" fill="#8ca8b5"/><path d="M45 480Q180 100 315 480" fill="#263f50"/></svg>',
|
||||
});
|
||||
report.external.push({ case: name, url: url.href });
|
||||
return route.abort();
|
||||
});
|
||||
const check = label => result.checks.push(label);
|
||||
const shot = async label => {
|
||||
// Playwright finishes finite CSS transitions; infinite loaders cannot stall the run.
|
||||
const filename = `${name}-${label}.png`;
|
||||
await page.screenshot({ path: fileURLToPath(new URL(filename, output)), animations: "disabled" });
|
||||
result.screenshots.push(filename);
|
||||
const layout = await page.evaluate(() => ({
|
||||
document: document.documentElement.scrollWidth <= innerWidth + 1,
|
||||
grids: [...document.querySelectorAll(".ios-media-grid")]
|
||||
.filter(el => !el.closest("[inert], [aria-hidden=true]") && el.getClientRects().length)
|
||||
.every(el => el.scrollWidth <= el.clientWidth + 1 && el.getBoundingClientRect().right <= innerWidth + 1),
|
||||
}));
|
||||
assert(layout.document && layout.grids, `${label}: no horizontal page or media-grid overflow`);
|
||||
};
|
||||
const assertSlider = async (group, count, index, label) => {
|
||||
await group.waitFor();
|
||||
await group.evaluate(async el => {
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
await Promise.all(el.getAnimations({ subtree: true }).filter(animation => animation.effect?.getTiming().iterations !== Infinity)
|
||||
.map(animation => animation.finished.catch(() => undefined)));
|
||||
});
|
||||
const geometry = await group.evaluate(el => {
|
||||
const buttons = [...el.querySelectorAll(".ios-segmented-items > button")];
|
||||
const selected = buttons.findIndex(button => button.getAttribute("aria-pressed") === "true");
|
||||
const rectangle = element => { const { x, y, width, height } = element.getBoundingClientRect(); return { x, y, width, height }; };
|
||||
return { count: buttons.length, selected, declaredCount: el.style.getPropertyValue("--segment-count"),
|
||||
indicator: rectangle(el.querySelector(".ios-segmented-indicator")), button: selected >= 0 ? rectangle(buttons[selected]) : null };
|
||||
});
|
||||
(result.segmented ??= []).push({ label, ...geometry });
|
||||
assert.equal(geometry.count, count, `${label}: expected option count`);
|
||||
assert.equal(geometry.declaredCount, String(count), `${label}: shared control uses the actual option count`);
|
||||
assert.equal(geometry.selected, index, `${label}: the requested option is selected`);
|
||||
for (const property of ["x", "y", "width", "height"]) assert(Math.abs(geometry.indicator[property] - geometry.button[property]) < 1.1,
|
||||
`${label}: slider and selected button align in ${property}`);
|
||||
};
|
||||
const returnFromOverlay = async () => {
|
||||
if (test.android) await page.evaluate(() => window.__IOS_UI_FIXTURE__.hardwareBack());
|
||||
else assert.equal(await page.evaluate(async () => (await import("/src/shared/lib/back.ts")).runBack()), true, "Overlay consumes the shared back handler");
|
||||
};
|
||||
try {
|
||||
await page.goto(origin);
|
||||
if (test.minimumFontSize) assert(await page.evaluate(minimum => {
|
||||
const probe = document.createElement("span"); probe.style.fontSize = "12px"; probe.textContent = "字号";
|
||||
document.body.append(probe); const size = parseFloat(getComputedStyle(probe).fontSize); probe.remove();
|
||||
return size >= minimum;
|
||||
}, test.minimumFontSize), "Chromium applies the enlarged minimum text size");
|
||||
const nav = page.getByRole("navigation", { name: "主导航" });
|
||||
for (const label of ["首页", "搜索", "分类", "我的"]) await nav.getByRole("button", { name: label, exact: true }).waitFor();
|
||||
await page.waitForFunction(theme => document.documentElement.dataset.theme === theme, test.theme);
|
||||
if (test.android) await page.waitForFunction(() => window.__IOS_UI_FIXTURE__.hasHardwareBack());
|
||||
check("original navigation and persisted appearance");
|
||||
if (test.mobile) {
|
||||
const videoNav = page.locator('nav[aria-label="主导航"]');
|
||||
await videoNav.waitFor();
|
||||
const navBackground = await videoNav.evaluate(nav => nav.getAttribute("data-over-video"));
|
||||
assert.equal(navBackground, "true", "Home navigation declares its video background");
|
||||
await nav.getByRole("button", { name: "首页", exact: true }).click();
|
||||
const homeVideoMaterial = await page.evaluate(() => {
|
||||
const nav = document.querySelector('nav[aria-label="主导航"]');
|
||||
const selected = nav?.querySelector('[aria-current="page"]');
|
||||
const unselected = nav?.querySelector('button:not([aria-current="page"])');
|
||||
const glass = nav?.querySelector(".hg-glass");
|
||||
return { video: nav?.getAttribute("data-over-video"), selected: selected && getComputedStyle(selected).color,
|
||||
unselected: unselected && getComputedStyle(unselected).color, background: glass && getComputedStyle(glass).backgroundColor };
|
||||
});
|
||||
assert.equal(homeVideoMaterial.selected, "rgb(25, 25, 25)", "Home selection uses dark ink over the selected light surface");
|
||||
assert.equal(homeVideoMaterial.unselected, "rgb(242, 240, 235)", "Home navigation labels stay bright over dark video");
|
||||
assert.equal(homeVideoMaterial.background, "rgba(28, 28, 32, 0.94)", "Home navigation keeps an opaque dark glass surface over black video");
|
||||
check("home navigation text contrast on video in both themes");
|
||||
}
|
||||
await nav.getByRole("button", { name: "搜索", exact: true }).click();
|
||||
|
||||
const hotSearch = page.getByRole("region", { name: "热搜榜", exact: true });
|
||||
await hotSearch.getByRole("button", { name: "播放 城市与晚风", exact: true }).waitFor();
|
||||
assert.equal(await hotSearch.locator("ol > li").count(), titles.length, "Hot searches retain upstream rank order");
|
||||
assert.equal(await hotSearch.locator("ol > li").first().innerText(), "01\n城市与晚风\n550.1w播放量");
|
||||
await hotSearch.getByRole("button", { name: "播放 城市与晚风", exact: true }).click();
|
||||
const playbackPositionSelector = test.mobile ? ".feed-position-pill" : ".desktop-context-header small";
|
||||
await page.waitForFunction(selector => [...document.querySelectorAll(selector)].some(el => {
|
||||
const bounds = el.getBoundingClientRect();
|
||||
return el.textContent.trim() === "1 / 6" && bounds.width > 0 && bounds.top >= 0 && bounds.bottom <= innerHeight
|
||||
&& getComputedStyle(el).visibility !== "hidden" && !el.closest("[inert], [aria-hidden=true]");
|
||||
}), playbackPositionSelector);
|
||||
const activePlaybackPositions = await page.locator(playbackPositionSelector).evaluateAll(elements => elements.filter(el => {
|
||||
const bounds = el.getBoundingClientRect();
|
||||
return bounds.width > 0 && bounds.top >= 0 && bounds.bottom <= innerHeight
|
||||
&& getComputedStyle(el).visibility !== "hidden" && !el.closest("[inert], [aria-hidden=true]");
|
||||
}).map(el => el.textContent.trim()));
|
||||
assert.deepEqual(activePlaybackPositions, ["1 / 6"], "Only the viewport's active playback surface shows its position counter");
|
||||
await page.keyboard.press("Escape");
|
||||
check("official hot video titles, play counts, rank order, and direct playback");
|
||||
|
||||
const query = page.getByRole("textbox", { name: "搜索短剧、帖子、题材…" });
|
||||
await query.fill("都市"); await query.press("Enter");
|
||||
await page.getByRole("button", { name: titles[0], exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: titlePattern }).count(), titles.length);
|
||||
assert.equal(await page.getByRole("button", { name: titles[0], exact: true }).locator("img").getAttribute("loading"), "eager");
|
||||
assert.equal(await page.getByRole("button", { name: titles[0], exact: true }).locator("img").getAttribute("fetchpriority"), "high");
|
||||
assert.equal(await page.getByRole("button", { name: titles[2], exact: true }).locator("img").getAttribute("loading"), "lazy");
|
||||
await shot("search"); check("search results and responsive poster grid"); check("first-screen covers load eagerly at high priority; remaining covers stay lazy");
|
||||
if (test.android) {
|
||||
await page.getByRole("button", { name: titles[0], exact: true }).click();
|
||||
const position = page.locator(".feed-position-pill").first();
|
||||
await position.waitFor();
|
||||
const topControls = await position.evaluate(el => {
|
||||
const counter = el.getBoundingClientRect();
|
||||
const mute = document.querySelector('[aria-label="静音"], [aria-label="取消静音"]')?.getBoundingClientRect();
|
||||
return { counter: { left: counter.left, right: counter.right, top: counter.top, bottom: counter.bottom },
|
||||
mute: mute ? { left: mute.left, right: mute.right, top: mute.top, bottom: mute.bottom } : null };
|
||||
});
|
||||
assert(topControls.mute, "Playback mute control is visible");
|
||||
assert.equal(topControls.counter.left < topControls.mute.right && topControls.counter.right > topControls.mute.left
|
||||
&& topControls.counter.top < topControls.mute.bottom && topControls.counter.bottom > topControls.mute.top, false,
|
||||
"Playback position and mute control do not overlap");
|
||||
await page.keyboard.press("Escape");
|
||||
await nav.getByRole("button", { name: "搜索", exact: true }).waitFor();
|
||||
check("Android player counter clears the mute control");
|
||||
}
|
||||
|
||||
const searchPage = page.locator(".ios-page").filter({ has: query });
|
||||
await searchPage.getByRole("button", { name: "排行榜", exact: true }).click();
|
||||
const rankSegment = page.getByRole("group", { name: "榜单类型", exact: true });
|
||||
for (const [index, label] of ["热播榜", "推荐榜", "潜力榜"].entries()) {
|
||||
await rankSegment.getByRole("button", { name: label, exact: true }).click();
|
||||
await assertSlider(rankSegment, 3, index, `rank:${label}`);
|
||||
await page.locator(".ios-rank-row").first().waitFor();
|
||||
assert.equal(await page.locator(".ios-rank-row").count(), titles.length, `${label} shows all ranked fixture videos`);
|
||||
}
|
||||
await shot("ranks");
|
||||
await page.keyboard.press("Escape");
|
||||
await query.waitFor();
|
||||
check("all three rank choices move the shared indicator into the selected button bounds");
|
||||
|
||||
await nav.getByRole("button", { name: "分类", exact: true }).click();
|
||||
await page.getByRole("button").filter({ has: page.getByText("专题", { exact: true }) }).click();
|
||||
const topic = page.getByRole("button").filter({ has: page.getByText("本周精选", { exact: true }) });
|
||||
await topic.waitFor();
|
||||
const topicShape = await topic.evaluate(el => {
|
||||
const style = getComputedStyle(el), bounds = el.getBoundingClientRect();
|
||||
return { radii: [style.borderTopLeftRadius, style.borderTopRightRadius, style.borderBottomRightRadius, style.borderBottomLeftRadius], width: bounds.width, height: bounds.height };
|
||||
});
|
||||
result.topicShape = topicShape;
|
||||
assert.deepEqual(topicShape.radii, ["16px", "16px", "16px", "16px"], "Topic cards keep four 16px corners");
|
||||
assert(topicShape.width > 32 && topicShape.height > 32, "A topic card retains a rectangular surface rather than becoming circular");
|
||||
await topic.click();
|
||||
await page.getByRole("button", { name: titles[0], exact: true }).waitFor();
|
||||
assert.equal(await topic.count(), 0, "Covered topic-list controls are removed from the accessibility tree");
|
||||
assert.equal(await page.getByRole("button", { name: "返回", exact: true }).count(), 1, "Only the top page's back control is accessible");
|
||||
await shot("topic");
|
||||
await page.keyboard.press("Escape");
|
||||
await topic.waitFor(); // Wait for React to commit before a second Escape.
|
||||
await page.keyboard.press("Escape");
|
||||
await page.getByRole("button").filter({ has: page.getByText("专题", { exact: true }) }).waitFor();
|
||||
check("topic navigation, inert background, and sequential Escape");
|
||||
|
||||
await nav.getByRole("button", { name: "我的", exact: true }).click();
|
||||
await page.getByRole("button", { name: titles[0], exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: titlePattern }).count(), titles.length);
|
||||
await page.getByRole("button", { name: /未登录/ }).click();
|
||||
const profileLogin = page.getByRole("dialog", { name: "登录 HGhubX", exact: true });
|
||||
await profileLogin.getByLabel("账号", { exact: true }).fill("profile-fixture");
|
||||
await profileLogin.getByLabel("密码", { exact: true }).fill("test-password");
|
||||
await profileLogin.getByRole("button", { name: "登录", exact: true }).last().click();
|
||||
const profileLinks = page.locator(".ios-profile-links");
|
||||
await profileLinks.getByRole("button", { name: /^我的关注/ }).waitFor();
|
||||
await profileLinks.getByRole("button", { name: /^我的主页/ }).waitFor();
|
||||
await profileLogin.waitFor({ state: "hidden" });
|
||||
await page.getByRole("button", { name: titles[0], exact: true }).locator(".ios-score-badge").waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: titles[0], exact: true }).locator(".ios-score-badge").innerText(), "8.5");
|
||||
assert.equal(await page.getByRole("button", { name: titles[1], exact: true }).locator(".ios-score-badge").count(), 0, "Unrated videos do not show an empty score badge");
|
||||
const scorePosition = await page.getByRole("button", { name: titles[0], exact: true }).evaluate(el => {
|
||||
const art = el.querySelector(".ios-poster-art");
|
||||
const score = el.querySelector(".ios-score-badge");
|
||||
if (!art || !score) return null;
|
||||
const artBounds = art.getBoundingClientRect();
|
||||
const scoreBounds = score.getBoundingClientRect();
|
||||
return { top: scoreBounds.top - artBounds.top, right: artBounds.right - scoreBounds.right,
|
||||
artWidth: artBounds.width, scoreWidth: scoreBounds.width };
|
||||
});
|
||||
assert(scorePosition, "Rated poster exposes a positioned score badge");
|
||||
assert(Math.abs(scorePosition.top - 9) < 1.1, "Score badge stays in the cover's top corner");
|
||||
assert(Math.abs(scorePosition.right - 9) < 1.1, "Score badge stays in the cover's right corner");
|
||||
assert(scorePosition.top < scorePosition.artWidth * .25, "Score badge is not vertically centered on the cover");
|
||||
result.posterWidth = Math.round(await page.getByRole("button", { name: titles[0], exact: true }).evaluate(el => el.getBoundingClientRect().width));
|
||||
await shot("favorites");
|
||||
const profileSegment = page.getByRole("group", { name: "我的内容", exact: true });
|
||||
await assertSlider(profileSegment, 2, 0, "profile:我的收藏");
|
||||
const linkGeometry = () => profileLinks.evaluate(el => {
|
||||
const parent = el.getBoundingClientRect();
|
||||
return { x: parent.x, width: parent.width, height: parent.height, columns: [...el.children].map(child => {
|
||||
const bounds = child.getBoundingClientRect();
|
||||
return { left: bounds.x - parent.x, top: bounds.y - parent.y, width: bounds.width, height: bounds.height };
|
||||
}) };
|
||||
});
|
||||
const linksBefore = await linkGeometry();
|
||||
assert.equal(linksBefore.columns.length, 2, "Logged-in profile shows both shortcuts");
|
||||
const [followingColumn, homepageColumn] = linksBefore.columns;
|
||||
assert(followingColumn.width > 0 && Math.abs(followingColumn.width - homepageColumn.width) < 1
|
||||
&& Math.abs(followingColumn.top - homepageColumn.top) < 1 && homepageColumn.left >= followingColumn.left + followingColumn.width,
|
||||
"Following and homepage shortcuts form two equal, adjacent columns");
|
||||
const assertStableLinks = async label => {
|
||||
const after = await linkGeometry();
|
||||
for (const property of ["x", "width", "height"]) assert(Math.abs(after[property] - linksBefore[property]) < 1, `${label}: shortcut group keeps its ${property}`);
|
||||
for (const [index, column] of after.columns.entries()) for (const property of ["left", "top", "width", "height"])
|
||||
assert(Math.abs(column[property] - linksBefore.columns[index][property]) < 1, `${label}: shortcut ${index + 1} keeps its ${property}`);
|
||||
return after;
|
||||
};
|
||||
await profileSegment.getByRole("button", { name: "观看历史", exact: true }).click();
|
||||
await assertSlider(profileSegment, 2, 1, "profile:观看历史");
|
||||
await page.getByText("第 3 集 · 0:55", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: titlePattern }).count(), 1);
|
||||
const linksHistory = await assertStableLinks("History switch");
|
||||
await profileSegment.getByRole("button", { name: "我的收藏", exact: true }).click();
|
||||
await assertSlider(profileSegment, 2, 0, "profile:我的收藏 restored");
|
||||
await page.getByRole("button", { name: titles[1], exact: true }).waitFor();
|
||||
const linksRestored = await assertStableLinks("Collection switch");
|
||||
result.profileLinks = { before: linksBefore, history: linksHistory, restored: linksRestored };
|
||||
await page.getByRole("button", { name: "退出登录", exact: true }).click();
|
||||
await page.getByRole("button", { name: /未登录/ }).waitFor();
|
||||
check("local favorites, score badges, preserved playback progress, two-way slider, and stable profile shortcut columns");
|
||||
|
||||
const accountButton = page.getByRole("button", { name: /未登录/ });
|
||||
await accountButton.click();
|
||||
const dialog = page.getByRole("dialog", { name: "登录 HGhubX", exact: true });
|
||||
await dialog.waitFor();
|
||||
const username = dialog.getByLabel("账号", { exact: true });
|
||||
const password = dialog.getByLabel("密码", { exact: true });
|
||||
await username.fill("sample"); await password.fill("test-password");
|
||||
await dialog.getByRole("button", { name: "登录", exact: true }).last().click();
|
||||
await dialog.getByRole("alert").waitFor();
|
||||
assert.equal(await dialog.getByRole("alert").textContent(), "账号或密码不正确");
|
||||
assert.equal(await username.inputValue(), "sample", "An unsuccessful login preserves the account input");
|
||||
assert.equal(await page.getByRole("button", { name: "观看历史", exact: true }).count(), 0, "The login dialog makes its background inert");
|
||||
await dialog.evaluate(el => {
|
||||
const items = [...el.querySelectorAll("button:not(:disabled), input:not(:disabled)")].filter(item => item.tabIndex >= 0 && item.getClientRects().length);
|
||||
items.at(-1).focus();
|
||||
});
|
||||
await page.keyboard.press("Tab");
|
||||
assert(await dialog.evaluate(el => el.contains(document.activeElement)), "Forward Tab stays in the dialog");
|
||||
await page.keyboard.press("Shift+Tab");
|
||||
assert(await dialog.evaluate(el => el.contains(document.activeElement)), "Backward Tab stays in the dialog");
|
||||
await shot("login");
|
||||
await page.keyboard.press("Escape");
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
await page.waitForFunction(el => el === document.activeElement, await accountButton.elementHandle());
|
||||
await accountButton.click(); await dialog.waitFor();
|
||||
await returnFromOverlay(); await dialog.waitFor({ state: "hidden" });
|
||||
await accountButton.waitFor();
|
||||
check("visible form labels, login errors, focus trap, Escape, and overlay back");
|
||||
|
||||
await page.getByRole("button", { name: "设置", exact: true }).click();
|
||||
const security = page.getByRole("switch", { name: "严格安全模式", exact: true });
|
||||
const appearance = page.getByRole("group", { name: "外观模式", exact: true });
|
||||
await security.waitFor();
|
||||
await page.locator(".ios-setting-group").first().waitFor();
|
||||
await page.waitForTimeout(550);
|
||||
const controlRadii = await page.evaluate(() => {
|
||||
const icon = document.querySelector(".ios-page .ios-icon-button");
|
||||
const settingIcon = document.querySelector(".ios-setting-icon");
|
||||
const segmented = document.querySelector(".ios-appearance-picker");
|
||||
const indicator = segmented?.querySelector(".ios-segmented-indicator");
|
||||
return {
|
||||
icon: icon && getComputedStyle(icon).borderRadius,
|
||||
settingIcon: settingIcon && getComputedStyle(settingIcon).borderRadius,
|
||||
segmented: segmented && getComputedStyle(segmented).borderRadius,
|
||||
indicator: indicator && getComputedStyle(indicator).borderRadius,
|
||||
};
|
||||
});
|
||||
assert.equal(controlRadii.icon, "50%", "Icon controls render as circles");
|
||||
assert.equal(controlRadii.settingIcon, "50%", "Setting symbols render on circular backplates");
|
||||
assert.equal(controlRadii.segmented, "999px", "Segmented controls use rounded outer corners");
|
||||
assert.equal(controlRadii.indicator, "999px", "Selected segment uses matching rounded corners");
|
||||
await assertSlider(appearance, 3, test.theme === "dark" ? 2 : 1, "appearance:initial");
|
||||
check("circular icon controls and rounded segmented controls");
|
||||
const pageIn = page.locator(".a-page-in");
|
||||
if (await pageIn.count()) {
|
||||
await pageIn.first().evaluate(async el => {
|
||||
await Promise.all(el.getAnimations().map(animation => animation.finished.catch(() => undefined)));
|
||||
});
|
||||
}
|
||||
const switches = page.getByRole("switch");
|
||||
result.switches = [];
|
||||
for (const item of await switches.all()) {
|
||||
await item.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300);
|
||||
const bounds = await item.boundingBox();
|
||||
const target = await item.evaluate(el => ({ width: el.offsetWidth, height: el.offsetHeight }));
|
||||
const visual = await item.evaluate(el => {
|
||||
const track = getComputedStyle(el.querySelector(".ios-switch-track"));
|
||||
const thumb = getComputedStyle(el.querySelector(".ios-switch-thumb"));
|
||||
const rail = el.querySelector(".ios-switch-track").getBoundingClientRect();
|
||||
const thumbBounds = el.querySelector(".ios-switch-thumb").getBoundingClientRect();
|
||||
const shell = el.closest(".plat-android");
|
||||
const activeIndicator = document.querySelector(".ios-mobile-nav .hg-drop .ios-liquid-fill");
|
||||
const activeTab = document.querySelector('.ios-mobile-nav-item[aria-current="page"]');
|
||||
return { platform: el.dataset.platform, trackWidth: track.width, trackHeight: track.height,
|
||||
trackRadius: track.borderRadius, trackBorder: track.borderTopWidth, trackBackground: track.backgroundImage,
|
||||
thumbBackground: thumb.backgroundImage, thumbRadius: thumb.borderRadius,
|
||||
thumbWidth: thumbBounds.width, thumbLeft: thumbBounds.left - rail.left, thumbRight: rail.right - thumbBounds.right,
|
||||
activeIndicator: activeIndicator ? getComputedStyle(activeIndicator).backgroundColor : null,
|
||||
activeTabColor: activeTab ? getComputedStyle(activeTab).color : null,
|
||||
androidShell: !!shell };
|
||||
});
|
||||
result.switches.push({ label: await item.getAttribute("aria-label"), width: target.width, height: target.height, visualBounds: bounds, ...visual });
|
||||
assert(target.width >= 44 && target.height >= (test.android ? 48 : 44), "Switch touch target meets the platform minimum");
|
||||
assert(["true", "false"].includes(await item.getAttribute("aria-checked")), "Switch exposes its state");
|
||||
const off = await item.evaluate(el => {
|
||||
const rail = el.querySelector(".ios-switch-track").getBoundingClientRect();
|
||||
const thumb = el.querySelector(".ios-switch-thumb").getBoundingClientRect();
|
||||
return { left: thumb.left - rail.left, right: rail.right - thumb.right };
|
||||
});
|
||||
if (test.android) {
|
||||
assert.equal(visual.platform, "android", "Android selects its platform switch variant");
|
||||
assert.equal(visual.trackWidth, "52px", "Android uses the compact Material switch track");
|
||||
assert.equal(visual.trackHeight, "18px", "Android uses a slim track");
|
||||
assert.equal(visual.trackRadius, "6px", "Android uses a square-edged track rather than the iOS capsule");
|
||||
assert.equal(visual.trackBackground, "none", "Android track has a solid material fill");
|
||||
assert.equal(visual.thumbRadius, "50%", "Android thumb is circular");
|
||||
assert.equal(visual.thumbBackground, "none", "Android thumb uses a solid surface");
|
||||
assert.equal(visual.androidShell, true, "Android fixture runs in the Android app shell");
|
||||
assert.notEqual(visual.activeIndicator, "rgba(0, 0, 0, 0)", "Android active navigation has a visible selection surface");
|
||||
assert.notEqual(visual.activeTabColor, "rgb(255, 255, 255)", "Android active navigation uses the selected ink color");
|
||||
} else if (test.mobile) {
|
||||
assert.equal(visual.platform, "ios", "iOS keeps its platform switch variant");
|
||||
assert.equal(visual.trackRadius, "999px", "iOS keeps its capsule track");
|
||||
assert.equal(visual.thumbRadius, "50%", "iOS keeps its circular thumb");
|
||||
}
|
||||
const initiallyOn = await item.getAttribute("aria-checked") === "true";
|
||||
const expectedLeft = initiallyOn ? (test.android ? 25 : 27) : (test.android ? 0 : 3);
|
||||
const expectedRight = initiallyOn ? (test.android ? 1 : 3) : (test.android ? 26 : 27);
|
||||
assert(Math.abs(off.left - expectedLeft) < 1.1, `${visual.platform} switch thumb reaches the correct left/right endpoint`);
|
||||
assert(Math.abs(off.right - expectedRight) < 1.1, `${visual.platform} switch thumb clears the correct track edge`);
|
||||
const wasOn = await item.getAttribute("aria-checked") === "true";
|
||||
const targetState = !wasOn;
|
||||
await item.evaluate((el, on) => { el.dataset.state = on ? "on" : "off"; }, targetState);
|
||||
await page.waitForTimeout(360);
|
||||
const moved = await item.evaluate(el => {
|
||||
const rail = el.querySelector(".ios-switch-track").getBoundingClientRect();
|
||||
const thumb = el.querySelector(".ios-switch-thumb").getBoundingClientRect();
|
||||
return { left: thumb.left - rail.left, right: rail.right - thumb.right };
|
||||
});
|
||||
const turnedOn = targetState;
|
||||
const movedLeft = turnedOn ? (test.android ? 25 : 27) : (test.android ? 0 : 3);
|
||||
const movedRight = turnedOn ? (test.android ? 1 : 3) : (test.android ? 26 : 27);
|
||||
assert(Math.abs(moved.left - movedLeft) < 1.1 && Math.abs(moved.right - movedRight) < 1.1,
|
||||
`${visual.platform} switch reaches both travel endpoints after activation`);
|
||||
const actualState = await item.getAttribute("aria-checked") === "true";
|
||||
assert.equal(actualState, wasOn, "Layout probe leaves the application switch state unchanged");
|
||||
await item.evaluate((el, on) => { el.dataset.state = on ? "on" : "off"; }, wasOn);
|
||||
await page.waitForTimeout(360);
|
||||
}
|
||||
const switchTravel = await security.evaluate(el => {
|
||||
const rail = el.querySelector(".ios-switch-track").getBoundingClientRect();
|
||||
const thumb = el.querySelector(".ios-switch-thumb").getBoundingClientRect();
|
||||
return { left: thumb.left - rail.left, right: rail.right - thumb.right };
|
||||
});
|
||||
const strictState = await security.getAttribute("aria-checked") === "true";
|
||||
assert.equal(switchTravel.left, strictState ? (test.android ? 25 : 27) : (test.android ? 0 : 3), "Security switch thumb matches its state");
|
||||
const androidShell = page.locator(".plat-android").first();
|
||||
const material = await page.locator(".ios-setting-group").first().evaluate(el => {
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
const group = getComputedStyle(el);
|
||||
return {
|
||||
blur: group.backdropFilter || group.webkitBackdropFilter,
|
||||
surface: root.getPropertyValue("--glass-card-bg").trim(),
|
||||
background: root.getPropertyValue("--p-bg").trim(),
|
||||
text: root.getPropertyValue("--p-on").trim(),
|
||||
muted: root.getPropertyValue("--p-mut").trim(),
|
||||
};
|
||||
});
|
||||
assert.match(material.blur, new RegExp(`blur\\(${test.theme === "light" ? 28 : 22}px\\)`), "Glass panels use the theme-specific blur");
|
||||
if (test.theme === "light") {
|
||||
const contrast = (foreground, background) => {
|
||||
const rgb = color => {
|
||||
const hex = /^#([\da-f]{3}|[\da-f]{6})$/i.exec(color);
|
||||
const channels = hex
|
||||
? (hex[1].length === 3 ? [...hex[1]].map(channel => Number.parseInt(channel + channel, 16))
|
||||
: hex[1].match(/../g).map(channel => Number.parseInt(channel, 16)))
|
||||
: color.match(/[\d.]+/g).slice(0, 3).map(Number);
|
||||
return channels.map(channel => channel / 255 <= 0.04045
|
||||
? channel / 255 / 12.92 : ((channel / 255 + 0.055) / 1.055) ** 2.4);
|
||||
};
|
||||
const luminance = color => rgb(color).reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index], 0);
|
||||
const a = luminance(foreground);
|
||||
const b = luminance(background);
|
||||
return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
|
||||
};
|
||||
assert(contrast(material.text, material.background) >= 4.5, "Light primary text meets WCAG AA contrast");
|
||||
assert(contrast(material.muted, material.background) >= 4.5, "Light secondary text meets WCAG AA contrast");
|
||||
assert.match(material.surface, /\/\s*\.8[0-9]/, "Light glass remains dense enough to separate from media");
|
||||
}
|
||||
await appearance.getByRole("button", { name: test.theme === "dark" ? "浅色" : "深色", exact: true }).click();
|
||||
await assertSlider(appearance, 3, test.theme === "dark" ? 1 : 2, "appearance:opposite");
|
||||
const oppositeTheme = test.theme === "dark" ? "light" : "dark";
|
||||
await page.waitForFunction(theme => document.documentElement.dataset.theme === theme, oppositeTheme);
|
||||
const beforeThemeBounds = test.android ? await androidShell.boundingBox() : null;
|
||||
await appearance.getByRole("button", { name: test.theme === "dark" ? "深色" : "浅色", exact: true }).click();
|
||||
await page.waitForFunction(theme => document.documentElement.dataset.theme === theme, test.theme);
|
||||
if (!test.reduced) assert(await page.locator("html").evaluate(el => el.classList.contains("theme-transitioning")), "Theme swap starts its transition wash");
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
const lightBounds = test.android ? await androidShell.boundingBox() : null;
|
||||
if (test.android) assert.deepEqual(lightBounds, beforeThemeBounds, "Android page geometry stays stable during theme change");
|
||||
assert(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1), "Theme change does not cause horizontal layout overflow");
|
||||
await appearance.getByRole("button", { name: "深色", exact: true }).click();
|
||||
await page.waitForFunction(() => document.documentElement.dataset.theme === "dark");
|
||||
await assertSlider(appearance, 3, 2, "appearance:深色");
|
||||
await appearance.getByRole("button", { name: "跟随", exact: true }).click();
|
||||
await assertSlider(appearance, 3, 0, "appearance:跟随");
|
||||
await page.emulateMedia({ colorScheme: "light" });
|
||||
await page.waitForFunction(() => document.documentElement.dataset.theme === "light");
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
await page.waitForFunction(() => document.documentElement.dataset.theme === "dark");
|
||||
await appearance.getByRole("button", { name: "浅色", exact: true }).scrollIntoViewIfNeeded();
|
||||
await appearance.scrollIntoViewIfNeeded();
|
||||
await shot("settings");
|
||||
const clearCache = page.getByRole("button").filter({ has: page.getByText("清理缓存", { exact: true }) });
|
||||
await clearCache.click();
|
||||
const confirmation = page.getByRole("dialog");
|
||||
await confirmation.waitFor();
|
||||
await returnFromOverlay();
|
||||
await confirmation.waitFor({ state: "hidden" });
|
||||
await security.waitFor();
|
||||
await page.waitForFunction(el => el === document.activeElement, await clearCache.elementHandle());
|
||||
check("settings state, 44px switches, adaptive appearance, theme motion and stable Android geometry");
|
||||
result.passed = true;
|
||||
console.log(`PASS ${name}`);
|
||||
} catch (error) {
|
||||
result.error = String(error.stack || error);
|
||||
await page.screenshot({ path: fileURLToPath(new URL(`${name}-failure.png`, output)), animations: "disabled" }).catch(() => {});
|
||||
console.error(`FAIL ${name}: ${error.message}`);
|
||||
} finally { await context.close(); if (caseBrowser !== browser) await caseBrowser.close(); }
|
||||
}
|
||||
assert.equal(report.cases.filter(test => !test.passed).length, 0, "All viewport scenarios pass");
|
||||
assert.deepEqual(report.errors, [], "No uncaught browser errors");
|
||||
assert.deepEqual(report.external, [], "No unexpected requests to live services");
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error);
|
||||
console.error(report.error); process.exitCode = 1;
|
||||
} finally {
|
||||
await writeFile(new URL("report.json", output), JSON.stringify(report, null, 2));
|
||||
await browser?.close(); await vite?.close();
|
||||
console.log(`Artifacts: ${fileURLToPath(output)}`);
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
// Real Chromium CSP checks. Requests to the Linux media origin are intercepted;
|
||||
// this never contacts an upstream site or the user's running media proxy.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { createServer } from "node:http";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const config = JSON.parse(await readFile(join(root, "src-tauri/tauri.conf.json"), "utf8"));
|
||||
const linux = JSON.parse(await readFile(join(root, "src-tauri/tauri.linux.conf.json"), "utf8"));
|
||||
const mediaOrigin = "http://127.0.0.1:17650";
|
||||
const directives = policy => new Map(policy.split(";").map(value => value.trim().split(/\s+/)).map(([name, ...sources]) => [name, sources]));
|
||||
const effective = { ...config.app.security, ...linux.app.security };
|
||||
for (const key of ["csp", "devCsp"]) {
|
||||
const policy = directives(effective[key]);
|
||||
for (const directive of ["img-src", "media-src", "connect-src"]) {
|
||||
assert(policy.get(directive).includes(mediaOrigin), `${key}/${directive} must allow the Linux media proxy`);
|
||||
assert(!policy.get(directive).some(source => ["http:", "https:", "*", "http://127.0.0.1:*"].includes(source)), `${key}/${directive} must not broaden network access`);
|
||||
assert(!directives(config.app.security[key]).get(directive).includes(mediaOrigin), `${key}/${directive} loopback exception must remain Linux-only`);
|
||||
}
|
||||
}
|
||||
assert(directives(linux.app.security.csp).get("connect-src").includes(mediaOrigin), "Linux production override must retain the exact media origin");
|
||||
const previousPolicy = policy => policy.split(";").map(value => value.trim().split(/\s+/).filter(source => source !== mediaOrigin).join(" ")).join("; ");
|
||||
const policies = [
|
||||
{ name: "default-production", value: config.app.security.csp, allowsMedia: false },
|
||||
{ name: "previous-linux-development", value: previousPolicy(effective.devCsp), allowsMedia: false },
|
||||
{ name: "current-linux-production", value: effective.csp, allowsMedia: true },
|
||||
{ name: "current-linux-development", value: effective.devCsp, allowsMedia: true },
|
||||
];
|
||||
const targets = [mediaOrigin, "http://127.0.0.1:17651", "http://localhost:17650", "https://outside.fixture.invalid"];
|
||||
const output = join(root, "test-results", "linux-media-policy", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
await mkdir(output, { recursive: true });
|
||||
const temporary = await mkdtemp(join(tmpdir(), "hghubx-csp-media-"));
|
||||
const report = {
|
||||
environment: "Chromium enforces the actual default Tauri CSP; local generated video; all target requests intercepted. Existing Linux production override already allowed this origin; installed-package policy is not inferred by this test.",
|
||||
passed: [], violations: [], errors: [], intercepted: [], unexpected: [],
|
||||
};
|
||||
let server, browser;
|
||||
try {
|
||||
const videoPath = join(temporary, "fixture.webm");
|
||||
execFileSync(process.env.FFMPEG_EXECUTABLE || "ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=cyan:s=32x32:r=5", "-t", "1", "-an", "-c:v", "libvpx", "-pix_fmt", "yuv420p", "-y", videoPath], { timeout: 30000 });
|
||||
const video = await readFile(videoPath);
|
||||
server = createServer((req, res) => {
|
||||
const name = new URL(req.url, "http://localhost").searchParams.get("policy");
|
||||
const policy = policies.find(policy => policy.name === name);
|
||||
if (!policy) { res.writeHead(404); res.end(); return; }
|
||||
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": policy.value });
|
||||
res.end("<!doctype html><html><head><meta charset='utf-8'><title>Linux media policy fixture</title></head><body></body></html>");
|
||||
});
|
||||
await new Promise((done, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", done); });
|
||||
const uiOrigin = `http://127.0.0.1:${server.address().port}`;
|
||||
let executablePath = process.env.BROWSER_EXECUTABLE;
|
||||
if (!executablePath) {
|
||||
for (const path of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(path).then(() => true, () => false)) { executablePath = path; break; }
|
||||
}
|
||||
}
|
||||
browser = await chromium.launch({ headless: true, executablePath });
|
||||
for (const policy of policies) {
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => report.errors.push(error.message));
|
||||
await page.route("**/*", async route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === uiOrigin) return route.continue();
|
||||
if (url.origin !== mediaOrigin) { report.unexpected.push(url.href); return route.abort(); }
|
||||
report.intercepted.push({ policy: policy.name, path: url.pathname });
|
||||
const headers = { "Access-Control-Allow-Origin": "*" };
|
||||
if (url.pathname === "/manifest.m3u8") return route.fulfill({ headers, contentType: "application/vnd.apple.mpegurl", body: "#EXTM3U\n#EXT-X-VERSION:3\n#EXT-X-ENDLIST\n" });
|
||||
if (url.pathname === "/cover.svg") return route.fulfill({ headers, contentType: "image/svg+xml", body: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16"><rect width="16" height="16" fill="cyan"/></svg>' });
|
||||
if (url.pathname === "/video.webm") return route.fulfill({ headers, contentType: "video/webm", body: video });
|
||||
throw new Error(`Unexpected fixture media request: ${url.href}`);
|
||||
});
|
||||
await page.goto(`${uiOrigin}/?policy=${policy.name}`);
|
||||
await page.evaluate(() => {
|
||||
window.mediaPolicyViolations = [];
|
||||
document.addEventListener("securitypolicyviolation", event => window.mediaPolicyViolations.push({ directive: event.effectiveDirective, blocked: event.blockedURI }));
|
||||
});
|
||||
for (const target of targets) {
|
||||
const result = await page.evaluate(async target => {
|
||||
const fetches = fetch(`${target}/manifest.m3u8`).then(async response => response.ok && (await response.text()).startsWith("#EXTM3U"), () => false);
|
||||
const image = new Image();
|
||||
const images = new Promise(resolve => {
|
||||
const timer = setTimeout(() => resolve(false), 3000);
|
||||
image.onload = () => { clearTimeout(timer); resolve(image.naturalWidth === 16); };
|
||||
image.onerror = () => { clearTimeout(timer); resolve(false); };
|
||||
image.src = `${target}/cover.svg`; document.body.append(image);
|
||||
});
|
||||
const video = document.createElement("video"); video.muted = true; video.preload = "auto";
|
||||
const videos = new Promise(resolve => {
|
||||
const timer = setTimeout(() => resolve(false), 3000);
|
||||
video.onloadeddata = () => { clearTimeout(timer); resolve(video.videoWidth === 32); };
|
||||
video.onerror = () => { clearTimeout(timer); resolve(false); };
|
||||
video.src = `${target}/video.webm`; document.body.append(video);
|
||||
});
|
||||
const [connect, img, media] = await Promise.all([fetches, images, videos]);
|
||||
image.remove(); video.pause(); video.removeAttribute("src"); video.load(); video.remove();
|
||||
return { connect, img, media };
|
||||
}, target);
|
||||
const expected = policy.allowsMedia && target === mediaOrigin;
|
||||
assert.deepEqual(result, { connect: expected, img: expected, media: expected }, `${policy.name} → ${target}`);
|
||||
report.passed.push({ policy: policy.name, target, expected: expected ? "allowed" : "blocked", ...result });
|
||||
}
|
||||
report.violations.push({ policy: policy.name, entries: await page.evaluate(() => window.mediaPolicyViolations) });
|
||||
await context.close();
|
||||
}
|
||||
assert.deepEqual(report.unexpected, [], "Other loopback ports/hosts and upstream sites must remain blocked before requests are sent");
|
||||
assert.deepEqual(report.errors, []);
|
||||
assert(report.intercepted.some(entry => entry.path === "/video.webm"), "Allowed native video must reach the media fixture");
|
||||
console.log(`PASS: ${report.passed.length * 3} real-browser CSP resource checks; Linux production/development allow the exact media origin; default policy and other hosts/ports remain blocked`);
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error);
|
||||
console.error(report.error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
|
||||
await browser?.close();
|
||||
if (server) await new Promise(done => server.close(done));
|
||||
await rm(temporary, { recursive: true, force: true });
|
||||
console.log(`Artifacts: ${output}`);
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
// Exercise the real App and its mobile navigation; only Tauri IPC is replaced.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const output = join(root, "test-results", "mobile-layout", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
const userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.1 Mobile/15E148 Safari/604.1";
|
||||
const viewports = [{ width: 320, height: 694 }, { width: 390, height: 844 }, { width: 430, height: 932 }, { width: 844, height: 390 }];
|
||||
const tabs = ["首页", "搜索", "分类", "我的"];
|
||||
const report = {
|
||||
environment: { browser: "Chromium with iPhone UA", transport: "real App; Tauri IPC mocked; no upstream traffic", limitation: "Does not replace native iOS/WKWebView verification", userAgent },
|
||||
cases: [], external: [], pageErrors: [],
|
||||
};
|
||||
await mkdir(output, { recursive: true });
|
||||
let vite, browser, page;
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined });
|
||||
const context = await browser.newContext({ userAgent, isMobile: true, hasTouch: true, viewport: viewports[0] });
|
||||
await context.addInitScript(() => {
|
||||
const fixture = { calls: [], unexpected: [] };
|
||||
const emptyPage = { items: [], pagination: { page: 1, pages: 1, size: 8, total: 0 } };
|
||||
localStorage.setItem("hghubx_usage_agreement", JSON.stringify({
|
||||
version: "2026-11-15-v1", accepted: true, acceptedAt: "2026-11-15T00:00:00.000Z",
|
||||
}));
|
||||
Object.assign(window, {
|
||||
mobileLayoutFixture: fixture,
|
||||
__TAURI_INTERNALS__: { invoke(cmd, args = {}) {
|
||||
fixture.calls.push({ cmd, args });
|
||||
if (cmd === "app_boot") return Promise.resolve({ user: null, logged_in: false, base: "https://fixture.invalid", strict_security: true });
|
||||
if (cmd === "playback_log_status") return Promise.resolve({ enabled: false, path: null, error: null });
|
||||
if (["debug_log", "set_text_interaction"].includes(cmd)) return Promise.resolve();
|
||||
if (cmd === "line_auto") return Promise.resolve({ base: "https://fixture.invalid", previous: "https://fixture.invalid", switched: false, pick: { tier: "main", ms: 1, reason: "fixture", candidates: [] } });
|
||||
if (["api_feed", "api_category", "api_posts", "api_original_videos", "api_post_category", "api_search_hot"].includes(cmd)) return Promise.resolve(emptyPage);
|
||||
// App's development-only playback self-test must not fetch media upstream.
|
||||
if (cmd === "api_play") return Promise.reject("Layout fixture has no playback media");
|
||||
fixture.unexpected.push(cmd);
|
||||
return Promise.reject(`Unexpected IPC: ${cmd}`);
|
||||
} },
|
||||
});
|
||||
});
|
||||
page = await context.newPage();
|
||||
page.on("pageerror", error => report.pageErrors.push(error.message));
|
||||
await page.route("**/*", route => {
|
||||
const url = route.request().url();
|
||||
if (new URL(url).origin === new URL(origin).origin) return route.continue();
|
||||
report.external.push(url);
|
||||
return route.abort();
|
||||
});
|
||||
await page.goto(origin);
|
||||
const nav = page.getByRole("navigation", { name: "主导航" });
|
||||
await nav.waitFor({ state: "visible" });
|
||||
assert(await page.locator(".plat-ios").count() > 0, "The real App must select its iOS mobile shell");
|
||||
assert.equal(await page.locator(".win-titlebar").count(), 0, "Mobile navigation must not be rendered inside a desktop shell");
|
||||
|
||||
for (const viewport of viewports) {
|
||||
await page.setViewportSize(viewport);
|
||||
const result = { viewport, tabs: [] };
|
||||
report.cases.push(result);
|
||||
for (const [index, name] of tabs.entries()) {
|
||||
await nav.getByRole("button", { name, exact: true }).click();
|
||||
await page.waitForFunction(label => document.querySelector('.hg-tabbar button[aria-current="page"]')?.textContent === label, name);
|
||||
// Keep the production transition enabled and measure its final position.
|
||||
await page.locator(".hg-drop").evaluate(async el => {
|
||||
await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
|
||||
await Promise.all(el.getAnimations().map(animation => animation.finished));
|
||||
});
|
||||
const geometry = await nav.evaluate(el => {
|
||||
const rect = element => { const r = element.getBoundingClientRect(); return { left: r.left, right: r.right, width: r.width, center: r.left + r.width / 2 }; };
|
||||
return { drop: rect(el.querySelector(".hg-drop")), button: rect(el.querySelector('button[aria-current="page"]')), bar: rect(el.querySelector(".hg-glass")) };
|
||||
});
|
||||
const centerDelta = Math.abs(geometry.drop.center - geometry.button.center);
|
||||
const screenshot = `${viewport.width}x${viewport.height}-tab-${index}.png`;
|
||||
await nav.screenshot({ path: join(output, screenshot) });
|
||||
result.tabs.push({ name, centerDelta, geometry, screenshot });
|
||||
assert(centerDelta < 1, `${viewport.width}px ${name}: highlight is ${centerDelta.toFixed(2)}px off center`);
|
||||
assert(geometry.drop.left >= geometry.bar.left && geometry.drop.right <= geometry.bar.right, "Highlight must remain inside the glass bar");
|
||||
}
|
||||
result.screenshot = `${viewport.width}x${viewport.height}-full.png`;
|
||||
await page.screenshot({ path: join(output, result.screenshot), fullPage: true });
|
||||
}
|
||||
report.ipc = await page.evaluate(() => ({ calls: window.mobileLayoutFixture.calls.map(call => call.cmd), unexpected: window.mobileLayoutFixture.unexpected }));
|
||||
assert.deepEqual(report.ipc.unexpected, [], "No unexpected Tauri calls");
|
||||
assert.deepEqual(report.pageErrors, [], "No page errors");
|
||||
assert.deepEqual(report.external, [], "No upstream traffic");
|
||||
report.passed = true;
|
||||
console.log(`Passed: ${report.cases.length * tabs.length} mobile navigation alignment checks`);
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error);
|
||||
await page?.screenshot({ path: join(output, "failure.png"), fullPage: true }).catch(() => {});
|
||||
console.error(report.error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
|
||||
const escape = text => String(text).replace(/[&<>\"]/g, char => ({ "&": "&", "<": "<", ">": ">", '"': """ })[char]);
|
||||
await writeFile(join(output, "report.html"), `<!doctype html><html lang="zh-CN"><meta charset="utf-8"><title>HGhubX mobile navigation layout</title><style>body{margin:24px;font:16px system-ui;background:#151515;color:#eee}h2{margin-top:32px}.tabs{display:grid;gap:12px;grid-template-columns:repeat(2,minmax(250px,1fr));max-width:1050px}figure{margin:0;padding:12px;background:#252525;border-radius:12px}img{display:block;max-width:100%;height:auto;margin-top:8px}a{color:#79cfff}pre{white-space:pre-wrap}</style><h1>HGhubX mobile navigation layout: ${report.passed ? "PASS" : "FAIL"}</h1><p>${escape(report.environment.transport)}. ${escape(report.environment.limitation)}.</p>${report.error ? `<pre>${escape(report.error)}</pre>` : ""}${report.cases.map(result => `<h2>${result.viewport.width} × ${result.viewport.height}</h2><a href="${result.screenshot || "failure.png"}">Full viewport screenshot</a><div class="tabs">${result.tabs.map(tab => `<figure><figcaption>${escape(tab.name)} — center error ${tab.centerDelta.toFixed(3)} px</figcaption><img src="${tab.screenshot}" alt="${escape(tab.name)} navigation highlight"></figure>`).join("")}</div>`).join("")}<p><a href="report.json">JSON measurements</a></p></html>`);
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
console.log(`Artifacts: ${output}`);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Actual settings/components/store in Chromium; mocked Tauri IPC, no upstream requests.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { access, mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
@@ -16,7 +16,13 @@ try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || "/usr/bin/google-chrome" });
|
||||
let executablePath = process.env.BROWSER_EXECUTABLE;
|
||||
if (!executablePath) {
|
||||
for (const candidate of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(candidate).then(() => true, () => false)) { executablePath = candidate; break; }
|
||||
}
|
||||
}
|
||||
browser = await chromium.launch({ headless: true, executablePath });
|
||||
async function open({ mobile = false, theme = "dark", width = 375, height = 812 } = {}) {
|
||||
const context = await browser.newContext({ viewport: mobile ? { width, height } : { width: 1280, height: 900 }, reducedMotion: "reduce",
|
||||
...(mobile ? { userAgent: "Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36" } : {}) });
|
||||
@@ -229,6 +235,28 @@ try {
|
||||
assert.deepEqual(await page.evaluate(() => window.networkSettingsFixture.unknown), []);
|
||||
await context.close();
|
||||
}
|
||||
{
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
page.on("pageerror", error => report.errors.push(error.message));
|
||||
await page.route("**/*", route => {
|
||||
const target = new URL(route.request().url());
|
||||
if (target.origin === new URL(origin).origin) return route.continue();
|
||||
// html-security.ts rewrites article <img> to the local media loopback (127.0.0.1:17650/img or hg.localhost/img).
|
||||
const isLocalImgProxy = (target.origin === "http://127.0.0.1:17650" || target.hostname === "hg.localhost") && target.pathname === "/img";
|
||||
if (!isLocalImgProxy) report.external.push(route.request().url());
|
||||
return route.abort();
|
||||
});
|
||||
for (const [label, path] of [["HTML sanitizer & SSRF link policy", "tests/html-security.html"], ["Strict security boot & persistence", "tests/security-settings.html"]]) {
|
||||
await page.goto(`${origin}${path}`);
|
||||
await page.waitForFunction(() => (document.querySelector("#results")?.textContent || "").trim().startsWith("{"));
|
||||
const parsed = JSON.parse(await page.locator("#results").innerText());
|
||||
assert.equal(parsed.failed, 0, `${label}: ${JSON.stringify(parsed)}`);
|
||||
assert(parsed.passed > 0, `${label}: expected passing checks`);
|
||||
report.passed.push(`${label}: ${parsed.passed} passed`);
|
||||
}
|
||||
await context.close();
|
||||
}
|
||||
}
|
||||
assert.deepEqual(report.errors, []);
|
||||
assert.deepEqual(report.external, []);
|
||||
|
||||
+69
-84
@@ -12,16 +12,20 @@ import { chromium } from "playwright-core";
|
||||
import { createServer as createViteServer } from "vite";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const scriptScenarios = {
|
||||
tv: { script: "test-tv-remote.mjs", timeout: 480000, metrics: { transport: "mock Tauri IPC; actual TV bootstrap, worker, library and player" } },
|
||||
};
|
||||
const ALL_SCENARIOS = ["seek", "legacy", "lifecycle", "gesture", "proxy", "portrait-fit", "ios-native", "recovery", "review", "tv"];
|
||||
const { values: args } = parseArgs({ options: {
|
||||
"media-dir": { type: "string" }, output: { type: "string" }, "browser-executable": { type: "string" },
|
||||
scenarios: { type: "string", default: "seek,legacy,stall,lifecycle,mms,gesture,proxy,portrait-fit" }, help: { type: "boolean" },
|
||||
scenarios: { type: "string", default: "seek,legacy,lifecycle,gesture,proxy,portrait-fit" }, help: { type: "boolean" },
|
||||
} });
|
||||
if (args.help) {
|
||||
console.log("pnpm test:playback [--media-dir DIR] [--output NEW_DIR] [--browser-executable PATH] [--scenarios seek,legacy,stall,lifecycle,mms,gesture,proxy,portrait-fit,ios-native,recovery,review]");
|
||||
console.log(`pnpm test:playback [--media-dir DIR] [--output NEW_DIR] [--browser-executable PATH] [--scenarios all|${ALL_SCENARIOS.join(",")}]`);
|
||||
process.exit(0);
|
||||
}
|
||||
const scenarios = args.scenarios.split(",");
|
||||
assert(scenarios.length && scenarios.every(s => ["seek", "legacy", "stall", "lifecycle", "mms", "gesture", "proxy", "portrait-fit", "ios-native", "recovery", "review"].includes(s)), "Unknown scenario");
|
||||
const scenarios = args.scenarios === "all" ? ALL_SCENARIOS : args.scenarios.split(",");
|
||||
assert(scenarios.length && scenarios.every(s => ALL_SCENARIOS.includes(s)), "Unknown scenario");
|
||||
const output = resolve(args.output || join(root, "test-results", "playback", new Date().toISOString().replace(/[:.]/g, "-")));
|
||||
await mkdir(dirname(output), { recursive: true });
|
||||
await mkdir(output); // Refuse to overwrite artifacts from an earlier run.
|
||||
@@ -316,70 +320,6 @@ async function seekChecks(page, legacy) {
|
||||
return { click_ms: logs.find(e => e.event === "seek.resumed" && e.data.seek === first.data.seek)?.data.elapsed_ms, drag_requests: drags.length,
|
||||
...(!legacy ? { speed_menu_keyboard: { playing_preserved: true, paused_preserved: true, activation: ["Space", "Enter"], navigation: ["ArrowUp", "ArrowDown", "Home", "End"], exit: ["Escape", "Tab"], focus_restored: true } } : {}) };
|
||||
}
|
||||
async function stallCheck(page) {
|
||||
await loadPlayer(page);
|
||||
await page.waitForFunction(() => { const v = document.querySelector("video"); return v.buffered.length && v.buffered.end(0) >= 30; });
|
||||
await page.evaluate(async () => { await window.playerSeekFixture.setLogging(true); window.playerSeekFixture.pauseBuffering(); });
|
||||
let segmentAttempts = 0;
|
||||
await page.route("**/seg?*", route => { segmentAttempts += 1; return route.abort("failed"); });
|
||||
await clickProgress(page, .8);
|
||||
const logs = await waitLog(page, "seek.timeout");
|
||||
const timeout = logs.find(e => e.event === "seek.timeout");
|
||||
assert(timeout.data.ready < 3 && timeout.data.seeking, "Timeout must capture the stalled media state");
|
||||
await page.waitForTimeout(250);
|
||||
assert(segmentAttempts < 80, `Recoverable fragment failures must not fan out into a retry storm (${segmentAttempts} attempts)`);
|
||||
await page.unroute("**/seg?*");
|
||||
await page.evaluate(() => window.playerSeekFixture.resumeBuffering());
|
||||
await waitLog(page, "seek.resumed");
|
||||
return { fault_injected: true, timeout_ms: timeout.data.elapsed_ms, segment_attempts: segmentAttempts };
|
||||
}
|
||||
async function managedMediaCheck(page) {
|
||||
// Chromium supplies real MSE decoding/buffering; only the MMS constructor and streaming
|
||||
// events are simulated. This tests the hls.js workaround, not macOS WebKit itself.
|
||||
await page.addInitScript(() => {
|
||||
const NativeMediaSource = window.MediaSource;
|
||||
window.__managedSources = [];
|
||||
class ManagedMediaSource extends NativeMediaSource {
|
||||
constructor() { super(); this.streaming = true; window.__managedSources.push(this); }
|
||||
}
|
||||
Object.defineProperty(window, "ManagedMediaSource", { configurable: true, value: ManagedMediaSource });
|
||||
if (new URL(location.href).searchParams.get("mms") === "only") {
|
||||
Object.defineProperty(window, "MediaSource", { configurable: true, value: undefined });
|
||||
}
|
||||
});
|
||||
const players = [];
|
||||
for (const legacy of [false, true]) {
|
||||
await loadPlayer(page, legacy, "&mms=both");
|
||||
await page.evaluate(() => window.playerSeekFixture.setLogging(true));
|
||||
let logs = await getLogs(page);
|
||||
assert(logs.some(e => e.event === "player.snapshot" && e.data.engine === "MediaSource" && e.data.prefer_managed === false), "Standard MediaSource must be preferred when both APIs exist");
|
||||
assert.equal(await page.evaluate(() => window.__managedSources.length), 0, "Avoid constructing MMS on standard MSE-capable browsers");
|
||||
await loadPlayer(page, legacy, "&mms=only");
|
||||
await page.waitForFunction(() => { const v = document.querySelector("video"); return v.buffered.length && v.buffered.end(0) >= 30; });
|
||||
await page.evaluate(() => window.playerSeekFixture.setLogging(true));
|
||||
logs = await getLogs(page);
|
||||
assert(logs.some(e => e.event === "player.snapshot" && e.data.engine === "ManagedMediaSource"), "MMS-only environments must still play");
|
||||
await page.evaluate(() => {
|
||||
const source = window.__managedSources.find(s => s.readyState === "open");
|
||||
source.streaming = false;
|
||||
source.dispatchEvent(new Event("endstreaming"));
|
||||
// A delayed endstreaming event can also arrive after seeking has resumed loading.
|
||||
document.querySelector("video").addEventListener("seeking", () => source.dispatchEvent(new Event("endstreaming")), { once: true });
|
||||
});
|
||||
await page.waitForFunction(() => !window.playerSeekFixture.engineState().buffering);
|
||||
await clickProgress(page, .8);
|
||||
logs = await waitLog(page, "seek.resumed");
|
||||
assert(logs.some(e => e.event === "mms.endstreaming" && e.data.buffering_enabled === false), "Test must first suspend MMS buffering");
|
||||
assert(logs.some(e => e.event === "mms.endstreaming" && e.data.seeking && e.data.buffering_enabled === true), "Late endstreaming during seeking must not suspend buffering again");
|
||||
assert(!logs.some(e => e.event === "mms.startstreaming"), "Recovery must not depend on a startstreaming event");
|
||||
assert.equal(await page.evaluate(() => window.playerSeekFixture.engineState().buffering), true, "Seeking must automatically resume MMS buffering");
|
||||
assert(!logs.some(e => e.event === "seek.timeout"));
|
||||
players.push({ player: legacy ? "legacy" : "feed", version: logs.find(e => e.event === "app.snapshot")?.data.hls_version,
|
||||
prefer_standard_mse: true, mms_only_recovered_without_startstreaming: true,
|
||||
seek_ms: logs.find(e => e.event === "seek.resumed")?.data.elapsed_ms });
|
||||
}
|
||||
return { simulated_mms: true, players };
|
||||
}
|
||||
async function lifecyclePlayerCheck(page, legacy) {
|
||||
let release, held, holdDeadline;
|
||||
const gate = new Promise(done => { release = done; });
|
||||
@@ -501,6 +441,11 @@ async function proxyRecoveryCheck(page) {
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("hg:proxy-changed")));
|
||||
await page.waitForFunction(before => window.playerSeekFixture.logs.filter(e => e.event === "proxy.restored").length > before, playingRetries);
|
||||
await page.waitForFunction(time => !document.querySelector("video").paused && document.querySelector("video").currentTime >= time, playingAt);
|
||||
if (!legacy) {
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("hg:line-changed")));
|
||||
assert.equal(await page.locator(".spinner").count(), 0, "Background line switch must not leave a stuck loading spinner on a healthy playing stream");
|
||||
assert(!(await page.locator("video").evaluate(v => v.paused)), "Background line switch must keep healthy stream playing");
|
||||
}
|
||||
const logs = await getLogs(page);
|
||||
const current = logs.filter(e => e.data.video_id).map(e => e.data.video_id);
|
||||
assert(current.every(id => id === 991), "Proxy save must retain current video");
|
||||
@@ -604,7 +549,7 @@ async function explicitRecoveryCheck(page) {
|
||||
}
|
||||
|
||||
try {
|
||||
if (scenarios.some(name => name !== "ios-native")) {
|
||||
if (scenarios.some(name => name !== "ios-native" && name !== "tv" && name !== "review")) {
|
||||
let mediaDir = args["media-dir"] && resolve(args["media-dir"]);
|
||||
if (!mediaDir) {
|
||||
temporaryMedia = await mkdtemp(join(tmpdir(), "hghubx-playback-")); mediaDir = temporaryMedia;
|
||||
@@ -623,6 +568,33 @@ try {
|
||||
}
|
||||
for (const name of scenarios) {
|
||||
const dir = join(output, name); await mkdir(dir);
|
||||
if (name === "tv") {
|
||||
const result = { name, status: "running", started: new Date().toISOString() }; report.cases.push(result);
|
||||
let stdout = "", stderr = "";
|
||||
try {
|
||||
const child = await promisify(execFile)(process.execPath, [join(root, "scripts", scriptScenarios.tv.script)], {
|
||||
cwd: root, encoding: "utf8", timeout: scriptScenarios.tv.timeout, maxBuffer: 8 * 1024 * 1024,
|
||||
env: { ...process.env, ...(args["browser-executable"] ? { BROWSER_EXECUTABLE: args["browser-executable"] } : {}) },
|
||||
});
|
||||
stdout = child.stdout; stderr = child.stderr;
|
||||
result.metrics = { exit_code: 0, ...scriptScenarios.tv.metrics };
|
||||
result.status = "passed"; console.log(`PASS ${name}: ${JSON.stringify(result.metrics)}`);
|
||||
} catch (error) {
|
||||
stdout = error.stdout || ""; stderr = error.stderr || "";
|
||||
result.status = "failed"; result.error = error.message;
|
||||
result.exit_code = typeof error.code === "number" ? error.code : null;
|
||||
result.signal = error.signal || null;
|
||||
console.error(`FAIL ${name}: ${error.message}`);
|
||||
} finally {
|
||||
if (stdout) process.stdout.write(stdout);
|
||||
if (stderr) process.stderr.write(stderr);
|
||||
await writeFile(join(dir, "stdout.log"), stdout);
|
||||
await writeFile(join(dir, "stderr.log"), stderr);
|
||||
result.finished = new Date().toISOString();
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2) + "\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (name === "ios-native") {
|
||||
const result = { name, status: "running", started: new Date().toISOString() }; report.cases.push(result);
|
||||
let stdout = "", stderr = "";
|
||||
@@ -650,6 +622,33 @@ try {
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (name === "review") {
|
||||
const result = { name, status: "running", started: new Date().toISOString() }; report.cases.push(result);
|
||||
let stdout = "", stderr = "";
|
||||
try {
|
||||
const child = await promisify(execFile)(process.execPath, [join(root, "scripts/test-round-review.mjs")], {
|
||||
cwd: root, encoding: "utf8", timeout: 180000, maxBuffer: 4 * 1024 * 1024,
|
||||
env: { ...process.env, ...(args["browser-executable"] ? { BROWSER_EXECUTABLE: args["browser-executable"] } : {}) },
|
||||
});
|
||||
stdout = child.stdout; stderr = child.stderr;
|
||||
result.metrics = { focused_checks: true };
|
||||
result.status = "passed"; console.log(`PASS ${name}: ${JSON.stringify(result.metrics)}`);
|
||||
} catch (error) {
|
||||
stdout = error.stdout || ""; stderr = error.stderr || "";
|
||||
result.status = "failed"; result.error = error.message;
|
||||
result.exit_code = typeof error.code === "number" ? error.code : null;
|
||||
result.signal = error.signal || null;
|
||||
console.error(`FAIL ${name}: ${error.message}`);
|
||||
} finally {
|
||||
if (stdout) process.stdout.write(stdout);
|
||||
if (stderr) process.stderr.write(stderr);
|
||||
await writeFile(join(dir, "stdout.log"), stdout);
|
||||
await writeFile(join(dir, "stderr.log"), stderr);
|
||||
result.finished = new Date().toISOString();
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2) + "\n");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const mobileContext = name === "gesture" || name === "portrait-fit";
|
||||
const context = await browser.newContext({ ...(mobileContext ? {userAgent:"Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 Version/17.1 Mobile/15E148 Safari/604.1",hasTouch:true} : {}), viewport: name === "portrait-fit" ? { width: 390, height: 844 } : { width: 1000, height: 900 } });
|
||||
await context.exposeBinding("collectPlaybackLogs", (_source, entries) => {
|
||||
@@ -674,21 +673,7 @@ try {
|
||||
const result = { name, status: "running", started: new Date().toISOString() }; report.cases.push(result);
|
||||
let deadline;
|
||||
try {
|
||||
if (name === "review") {
|
||||
result.metrics = await new Promise((resolve, reject) => {
|
||||
const child = spawn(process.execPath, [join(root, "scripts/test-round-review.mjs")], {
|
||||
cwd: root,
|
||||
env: { ...process.env, BROWSER_EXECUTABLE: args["browser-executable"] || chromium.executablePath() },
|
||||
stdio: "inherit",
|
||||
});
|
||||
child.once("error", reject);
|
||||
child.once("close", code => code === 0 ? resolve({ focused_checks: true }) : reject(new Error(`Round review checks exited ${code}`)));
|
||||
});
|
||||
result.status = "passed";
|
||||
console.log(`PASS ${name}: ${JSON.stringify(result.metrics)}`);
|
||||
continue;
|
||||
}
|
||||
const action = name === "recovery" ? explicitRecoveryCheck(page) : name === "proxy" ? proxyRecoveryCheck(page) : name === "gesture" ? gestureChecks(page) : name === "portrait-fit" ? portraitFitChecks(page) : name === "seek" || name === "legacy" ? seekChecks(page, name === "legacy") : name === "stall" ? stallCheck(page) : name === "mms" ? managedMediaCheck(page) : lifecycleCheck(page);
|
||||
const action = name === "recovery" ? explicitRecoveryCheck(page) : name === "proxy" ? proxyRecoveryCheck(page) : name === "gesture" ? gestureChecks(page) : name === "portrait-fit" ? portraitFitChecks(page) : name === "seek" || name === "legacy" ? seekChecks(page, name === "legacy") : lifecycleCheck(page);
|
||||
result.metrics = await Promise.race([action, new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("Scenario exceeded 45 seconds")), 45000); })]);
|
||||
assert.deepEqual(pageErrors, [], "Browser script errors");
|
||||
assert.deepEqual(externalRequests, [], "Unexpected external network requests");
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
// Post detail hot-count regression: a null detail.hot must use counts.hot, while
|
||||
// the detail page must render the normalized value instead of calling fmt(null).
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
let vite;
|
||||
let browser;
|
||||
try {
|
||||
const postsSource = await readFile(join(root, "src", "features", "posts", "Posts.tsx"), "utf8");
|
||||
assert.match(postsSource, /fmt\(postHot\(currentPost\)\)/, "PostDetail must render the normalized hot count");
|
||||
assert.doesNotMatch(postsSource, /fmt\(currentPost\.hot\)/, "PostDetail must not format a nullable hot value directly");
|
||||
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined });
|
||||
const page = await browser.newPage();
|
||||
const external = [];
|
||||
const pageErrors = [];
|
||||
page.on("pageerror", (error) => pageErrors.push(error.message));
|
||||
await page.route("**/*", (route) => {
|
||||
const url = route.request().url();
|
||||
if (new URL(url).origin === new URL(origin).origin) return route.continue();
|
||||
external.push(url);
|
||||
return route.abort();
|
||||
});
|
||||
await page.goto(`${origin}tests/post-detail-hot.html`);
|
||||
await page.waitForFunction(() => window.postDetailHotFixture);
|
||||
const result = await page.evaluate(() => window.postDetailHotFixture.results);
|
||||
assert.deepEqual(result, {
|
||||
detailNullUsesCount: 4321,
|
||||
detailPresentWins: 21,
|
||||
missingCountsFallsBackToZero: 0,
|
||||
absentPostFallsBackToZero: 0,
|
||||
});
|
||||
assert.deepEqual(pageErrors, []);
|
||||
assert.deepEqual(external, []);
|
||||
console.log("PASS: PostDetail hot uses hot ?? counts.hot ?? 0");
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
}
|
||||
@@ -1,20 +1,22 @@
|
||||
// Run the focused current-code regression checks in GitHub Actions.
|
||||
// Run the focused current-code regression checks.
|
||||
import { spawn } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { access, mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = fileURLToPath(new URL("../", import.meta.url));
|
||||
const output = join(root, "test-results", "round-review");
|
||||
if (process.env.GITHUB_ACTIONS !== "true") throw new Error("Run this review only in GitHub Actions.");
|
||||
let browserExecutable = process.env.BROWSER_EXECUTABLE;
|
||||
if (!browserExecutable) {
|
||||
for (const candidate of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(candidate).then(() => true, () => false)) { browserExecutable = candidate; break; }
|
||||
}
|
||||
}
|
||||
if (!browserExecutable) browserExecutable = chromium.executablePath();
|
||||
const scripts = [
|
||||
"test-inplace-search-back.mjs",
|
||||
"test-inplace-search-focus.mjs",
|
||||
"test-clear-history-confirm.mjs",
|
||||
"test-account-sync-empty-state.mjs",
|
||||
"test-topic-pagination.mjs",
|
||||
"test-post-detail-hot.mjs",
|
||||
"test-network-settings.mjs",
|
||||
];
|
||||
await mkdir(output, { recursive: true });
|
||||
@@ -23,7 +25,7 @@ async function run(command, cwd) {
|
||||
const result = await new Promise((resolve) => {
|
||||
const child = spawn(command[0], command.slice(1), {
|
||||
cwd,
|
||||
env: { ...process.env, BROWSER_EXECUTABLE: process.env.BROWSER_EXECUTABLE || chromium.executablePath() },
|
||||
env: { ...process.env, ...(browserExecutable ? { BROWSER_EXECUTABLE: browserExecutable } : {}) },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
let output = "";
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
const root = resolve(process.argv[2] || new URL("..", import.meta.url).pathname);
|
||||
const css = readFileSync(join(root, "src", "styles", "ios.css"), "utf8");
|
||||
const cards = readFileSync(join(root, "src", "shared", "ui", "cards.tsx"), "utf8");
|
||||
|
||||
assert.match(cards, /ios-poster-art[\s\S]*ScoreBadge/, "MediaCard must render the score badge inside the cover layer");
|
||||
assert.match(css, /\.ios-score-badge\s*\{[^}]*position:absolute[^}]*top:9px[^}]*right:9px/s,
|
||||
"The shared score badge must use the cover's top-right inset");
|
||||
assert.doesNotMatch(css, /\.ios-poster-art\.has-poster-badge>\.ios-score-badge\s*\{[^}]*top:42px/s,
|
||||
"A status badge must not push the score into the middle of the cover");
|
||||
console.log("PASS: shared MediaCard score stays in the cover top-right corner across desktop, Android, and iOS shells");
|
||||
@@ -15,6 +15,8 @@ const state = {
|
||||
searchHist: ["保留搜索记录"], volume: 0.42, muted: false,
|
||||
muteOnStartup: false, swipeEp: false, preferHevc: true,
|
||||
};
|
||||
// 迁移会为新字段补默认值(#146-3 全屏闲置隐藏秒数):旧种子不带该字段,落盘应补齐。
|
||||
const migrated = { ...state, fsIdleSecs: 3 };
|
||||
const oldData = {
|
||||
hghub_app_v1: JSON.stringify(state), hghub_swipe_ep_v2: "1", hghub_theme: "light",
|
||||
};
|
||||
@@ -72,12 +74,12 @@ try {
|
||||
|
||||
{
|
||||
const { context, page } = await open(oldData);
|
||||
assert.deepEqual(await snapshot(page), { ...state, theme: "light" });
|
||||
assert.deepEqual(await snapshot(page), { ...migrated, theme: "light" });
|
||||
assert.equal(await page.evaluate(() => window.storageMigrationFixture.getThemePreference()), "light");
|
||||
assert.equal(await page.evaluate(() => window.initialTheme), true);
|
||||
const saved = await storage(page);
|
||||
assert.deepEqual(Object.keys(saved).sort(), ["hghubx_app_v1", "hghubx_swipe_ep_v2", "hghubx_theme"]);
|
||||
assert.deepEqual(JSON.parse(saved.hghubx_app_v1), state);
|
||||
assert.deepEqual(JSON.parse(saved.hghubx_app_v1), migrated);
|
||||
await page.evaluate(() => window.storageMigrationFixture.setTheme("system"));
|
||||
await page.waitForFunction(() => localStorage.getItem("hghubx_theme") === "system");
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
@@ -92,12 +94,12 @@ try {
|
||||
await page.waitForFunction(() => localStorage.getItem("hghubx_theme") === "dark" && JSON.parse(localStorage.getItem("hghubx_app_v1")).history.length === 0);
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => window.storageMigrationFixture?.strictSecurityReady);
|
||||
assert.deepEqual(await snapshot(page), { ...state, history: [], theme: "dark" });
|
||||
assert.deepEqual(await snapshot(page), { ...migrated, history: [], theme: "dark" });
|
||||
await context.close();
|
||||
console.log("PASS: legacy data, swipe opt-out, adaptive and explicit appearance survive migration and restart");
|
||||
}
|
||||
{
|
||||
const newer = { ...state, favs: [99], history: [] };
|
||||
const newer = { ...migrated, favs: [99], history: [] };
|
||||
const { context, page } = await open({ ...oldData, hghubx_app_v1: JSON.stringify(newer), hghubx_theme: "dark", hghubx_swipe_ep_v2: "1" });
|
||||
assert.deepEqual(await snapshot(page), { ...newer, theme: "dark" });
|
||||
assert.equal(await page.evaluate(() => window.initialTheme), false);
|
||||
@@ -117,12 +119,12 @@ try {
|
||||
}
|
||||
for (const failure of ["write", "remove"]) {
|
||||
const { context, page } = await open(oldData, failure);
|
||||
assert.deepEqual(await snapshot(page), { ...state, theme: "light" });
|
||||
assert.deepEqual(await snapshot(page), { ...migrated, theme: "light" });
|
||||
const saved = await storage(page);
|
||||
for (const [key, value] of Object.entries(oldData)) assert.equal(saved[key], value);
|
||||
await page.reload();
|
||||
await page.waitForFunction(() => window.storageMigrationFixture?.strictSecurityReady);
|
||||
assert.deepEqual(await snapshot(page), { ...state, theme: "light" });
|
||||
assert.deepEqual(await snapshot(page), { ...migrated, theme: "light" });
|
||||
await context.close();
|
||||
console.log(`PASS: ${failure} failure retains legacy data and preferences across restarts`);
|
||||
}
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
// Topic detail pagination regression: all pages load, duplicates collapse, errors retry,
|
||||
// and a stale topic response cannot overwrite the selected topic.
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const output = join(root, "test-results", "topic-pagination", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
const report = {
|
||||
transport: "local browser fixture; Tauri IPC mocked",
|
||||
passed: [],
|
||||
external: [],
|
||||
pageErrors: [],
|
||||
};
|
||||
|
||||
await mkdir(output, { recursive: true });
|
||||
let vite;
|
||||
let browser;
|
||||
let page;
|
||||
try {
|
||||
vite = await createServer({ root, server: { host: "127.0.0.1", port: 0, strictPort: false } });
|
||||
await vite.listen();
|
||||
const origin = vite.resolvedUrls.local[0];
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.BROWSER_EXECUTABLE || undefined });
|
||||
page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
||||
page.on("pageerror", (error) => report.pageErrors.push(error.message));
|
||||
await page.route("**/*", (route) => {
|
||||
const url = route.request().url();
|
||||
if (new URL(url).origin === new URL(origin).origin) return route.continue();
|
||||
report.external.push(url);
|
||||
return route.abort();
|
||||
});
|
||||
|
||||
await page.goto(`${origin}tests/topic-pagination.html`);
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 1);
|
||||
const request = (slug, pageNumber, action = "resolve") =>
|
||||
page.evaluate(({ slug: value, pageNumber: number, action: operation }) => {
|
||||
window.topicPaginationFixture[operation](value, number);
|
||||
}, { slug, pageNumber, action });
|
||||
const requestCount = (slug, pageNumber) => page.evaluate(({ slug: value, pageNumber: number }) =>
|
||||
window.topicPaginationFixture.history.filter((entry) => entry.slug === value && entry.page === number).length,
|
||||
{ slug, pageNumber });
|
||||
const titles = () => page.locator("[data-ui='media-grid'] .ios-poster-title").allInnerTexts();
|
||||
const loadMore = page.getByRole("button", { name: /加载更多/ });
|
||||
|
||||
// Start a request for A, then select B before A resolves. A's late response must be ignored.
|
||||
await page.locator("#topic-b").click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 2);
|
||||
assert.deepEqual(await page.evaluate(() => window.topicPaginationFixture.history.slice(0, 2)), [
|
||||
{ slug: "hot-aiduanju", page: 1, size: 20 },
|
||||
{ slug: "luanlun-aiduanju", page: 1, size: 20 },
|
||||
]);
|
||||
await request("hot-aiduanju", 1);
|
||||
await page.waitForTimeout(100);
|
||||
assert.equal(await page.locator("[data-ui='media-grid']").count(), 0, "Stale topic A data must not render after selecting B");
|
||||
await request("luanlun-aiduanju", 1);
|
||||
await page.waitForFunction(() => document.querySelectorAll("[data-ui='media-grid'] .ios-poster-title").length === 20);
|
||||
assert.equal(await page.getByRole("heading", { name: "第二专题", exact: true }).count(), 1);
|
||||
assert.equal((await titles())[0], "专题影片 1");
|
||||
report.passed.push("TopicPage: a stale response from the previous topic cannot replace the selected topic");
|
||||
|
||||
await page.getByText(/已加载 20 \/ 81 部/).waitFor();
|
||||
await loadMore.click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 3);
|
||||
await request("luanlun-aiduanju", 2);
|
||||
await page.waitForFunction(() => document.querySelectorAll("[data-ui='media-grid'] .ios-poster-title").length === 39);
|
||||
assert.equal((await titles()).filter((title) => title === "专题影片 20").length, 1, "A page-boundary duplicate must render once");
|
||||
await page.getByText(/已加载 39 \/ 81 部/).waitFor();
|
||||
report.passed.push("TopicPage: page 2 appends and a repeated card id is de-duplicated");
|
||||
|
||||
await loadMore.click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 4);
|
||||
await request("luanlun-aiduanju", 3, "reject");
|
||||
await page.getByText("加载更多失败:第 3 页暂时不可用", { exact: true }).waitFor();
|
||||
assert.equal(await page.locator("[data-ui='media-grid'] .ios-poster-title").count(), 39, "A failed page must preserve loaded cards");
|
||||
await page.getByRole("button", { name: "重试", exact: true }).click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 5);
|
||||
assert.equal(await requestCount("luanlun-aiduanju", 3), 2, "Retry must request the same failed page");
|
||||
await request("luanlun-aiduanju", 3);
|
||||
await page.waitForFunction(() => document.querySelectorAll("[data-ui='media-grid'] .ios-poster-title").length === 59);
|
||||
report.passed.push("TopicPage: failed page keeps existing cards and retries the same page");
|
||||
|
||||
await loadMore.click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 6);
|
||||
await request("luanlun-aiduanju", 4);
|
||||
await page.waitForFunction(() => document.querySelectorAll("[data-ui='media-grid'] .ios-poster-title").length === 79);
|
||||
await loadMore.click();
|
||||
await page.waitForFunction(() => window.topicPaginationFixture.history.length === 7);
|
||||
await request("luanlun-aiduanju", 5);
|
||||
await page.waitForFunction(() => document.querySelectorAll("[data-ui='media-grid'] .ios-poster-title").length === 81);
|
||||
await page.getByText(/已加载 81 \/ 81 部/).waitFor();
|
||||
await page.getByText("已加载全部 81 部", { exact: true }).waitFor();
|
||||
assert.equal(await page.getByRole("button", { name: /加载更多/ }).count(), 0, "All five pages must terminate pagination");
|
||||
assert.deepEqual(
|
||||
await page.evaluate(() => window.topicPaginationFixture.history.slice(1).map(({ page: pageNumber, size }) => ({ page: pageNumber, size }))),
|
||||
[{ page: 1, size: 20 }, { page: 2, size: 20 }, { page: 3, size: 20 }, { page: 3, size: 20 }, { page: 4, size: 20 }, { page: 5, size: 20 }],
|
||||
);
|
||||
report.passed.push("TopicPage: 81 cards across five pages load through an explicit, terminating load-more path");
|
||||
|
||||
assert.deepEqual(report.pageErrors, [], "No page errors");
|
||||
assert.deepEqual(report.external, [], "No upstream traffic");
|
||||
await page.screenshot({ path: join(output, "final.png"), fullPage: true });
|
||||
console.log(JSON.stringify(report, null, 2));
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error);
|
||||
await page?.screenshot({ path: join(output, "failure.png"), fullPage: true }).catch(() => {});
|
||||
console.error(report.error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
await writeFile(join(output, "report.json"), `${JSON.stringify(report, null, 2)}\n`);
|
||||
await browser?.close();
|
||||
await vite?.close();
|
||||
console.log(`Artifacts: ${output}`);
|
||||
}
|
||||
@@ -0,0 +1,486 @@
|
||||
// Executed by the existing GitHub Actions playback workflow with scenarios=tv.
|
||||
// Real TV bootstrap/components/Worker/IndexedDB. All IPC/media remain fixtures.
|
||||
import assert from "node:assert/strict";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { access, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { dirname, join, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { build, createServer } from "vite";
|
||||
import { chromium } from "playwright-core";
|
||||
import { installTvFixture } from "../tests/tv-remote-fixture.mjs";
|
||||
|
||||
const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const output = join(root, "test-results", "tv-remote", new Date().toISOString().replace(/[:.]/g, "-"));
|
||||
await mkdir(output, { recursive: true });
|
||||
const report = { environment: "Chromium actual TV edition; strict mock IPC; generated local MP4; no upstream", cases: [], errors: [], external: [], screenshots: [] };
|
||||
let vite, browser, mediaDirectory, origin;
|
||||
const contexts = [];
|
||||
let activeContext;
|
||||
const savedEdition = process.env.VITE_APP_EDITION;
|
||||
async function scenario(name, run) {
|
||||
const item = { name, status: "running" }; report.cases.push(item);
|
||||
try { item.metrics = await run(); item.status = "passed"; console.log(`PASS TV ${name}`); }
|
||||
catch (error) { item.status = "failed"; item.error = String(error.stack || error); throw error; }
|
||||
finally {
|
||||
if (activeContext) {
|
||||
for (const page of activeContext.pages()) {
|
||||
const unknown = await page.evaluate(() => window.__tvFixture?.unknown || []).catch(() => []);
|
||||
report.errors.push(...unknown.map(command => `Unexpected fixture IPC: ${command}`));
|
||||
if (item.status === "failed") await page.screenshot({ path: join(output, `${name}-failed.png`) }).catch(() => {});
|
||||
}
|
||||
await activeContext.tracing.stop({ path: join(output, `${name}-trace.zip`) }).catch(() => {});
|
||||
await activeContext.close();
|
||||
contexts.splice(contexts.indexOf(activeContext), 1); activeContext = undefined;
|
||||
}
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
|
||||
}
|
||||
}
|
||||
async function open({ accepted = true, isolated = false, width = 1280, height = 720, fixture = {}, posterSizes = {} } = {}) {
|
||||
const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce", userAgent: "Mozilla/5.0 (Linux; Android 12; TV) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36" });
|
||||
contexts.push(context);
|
||||
activeContext = context;
|
||||
await context.tracing.start({ screenshots: true, snapshots: true });
|
||||
const page = await context.newPage(); page.setDefaultTimeout(20000);
|
||||
page.on("pageerror", error => report.errors.push(error.message));
|
||||
await context.route("**/*", async route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin === origin) return route.continue();
|
||||
if (url.origin === "http://hg.localhost" && url.pathname === "/img") {
|
||||
const id = new URL(url.searchParams.get("u")).pathname.split("/").at(-1);
|
||||
const [width, height] = posterSizes[id] || [240, 360];
|
||||
return route.fulfill({ status: 200, contentType: "image/svg+xml", body: `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 240 360"><rect width="240" height="360" fill="#234960"/><path d="M95 140L160 180L95 220Z" fill="#60cdff"/></svg>` });
|
||||
}
|
||||
if (url.origin === "http://hg.localhost" && url.pathname === "/seg") {
|
||||
const data = await readFile(join(mediaDirectory, "fixture.mp4"));
|
||||
const range = route.request().headers().range;
|
||||
const match = /^bytes=(\d+)-(\d*)$/.exec(range || "");
|
||||
if (match) {
|
||||
const start = Number(match[1]), end = match[2] ? Math.min(Number(match[2]), data.length - 1) : data.length - 1;
|
||||
return route.fulfill({ status: 206, contentType: "video/mp4", headers: { "Access-Control-Allow-Origin": "*", "Accept-Ranges": "bytes", "Content-Range": `bytes ${start}-${end}/${data.length}` }, body: data.subarray(start, end + 1) });
|
||||
}
|
||||
return route.fulfill({ status: 200, contentType: "video/mp4", headers: { "Access-Control-Allow-Origin": "*", "Accept-Ranges": "bytes" }, body: data });
|
||||
}
|
||||
if (url.protocol === "blob:" || url.protocol === "data:") return route.continue();
|
||||
report.external.push(url.href); return route.abort("blockedbyclient");
|
||||
});
|
||||
await page.addInitScript(installTvFixture, { ...fixture, accepted });
|
||||
await page.goto(`${origin}${isolated ? "/tests/tv-remote.html" : "/"}`);
|
||||
if (!isolated && accepted) await page.locator('[data-tv-focus="nav-home"]').waitFor();
|
||||
return { context, page };
|
||||
}
|
||||
const activate = async (page, key) => {
|
||||
const element = page.locator(`[data-tv-focus=${JSON.stringify(key)}]`).filter({ visible: true }).first();
|
||||
await page.waitForFunction(key => {
|
||||
const element = [...document.querySelectorAll("[data-tv-focus]")].find(item => item.getAttribute("data-tv-focus") === key && item.getClientRects().length);
|
||||
return !!element && !element.matches(":disabled");
|
||||
}, key);
|
||||
await element.focus(); await page.keyboard.press("Enter");
|
||||
};
|
||||
const calls = (page, command) => page.evaluate(command => window.__tvFixture.calls.filter(call => call.command === command), command);
|
||||
const activeKey = page => page.evaluate(() => document.activeElement?.getAttribute("data-tv-focus"));
|
||||
const screenshot = async (page, file) => {
|
||||
await page.screenshot({ path: join(output, file), animations: "disabled" });
|
||||
report.screenshots.push(file);
|
||||
};
|
||||
async function assertShelfWidths(page, state) {
|
||||
const sizes = await page.evaluate(() => {
|
||||
const shelf = document.querySelector('[data-tv-region="home-继续观看"]');
|
||||
return { expected: parseFloat(getComputedStyle(document.documentElement).fontSize) * 8,
|
||||
cards: [...shelf.children].map(slot => ({ slot: slot.offsetWidth, card: slot.querySelector(".tv-card").offsetWidth,
|
||||
art: slot.querySelector(".tv-card-art").offsetWidth })),
|
||||
recommendation: document.querySelector('[data-tv-region="home-推荐"] .tv-card')?.offsetWidth };
|
||||
});
|
||||
assert(sizes.cards.length > 0, `${state}: history shelf must contain cards`);
|
||||
for (const [index, widths] of sizes.cards.entries()) for (const [part, width] of Object.entries(widths)) {
|
||||
assert(Math.abs(width - sizes.expected) <= 1, `${state}: history ${index} ${part} width ${width} must equal shelf width ${sizes.expected}`);
|
||||
}
|
||||
if (sizes.recommendation !== undefined) assert(Math.abs(sizes.recommendation - sizes.expected) <= 1, `${state}: direct recommendation cards use the same width`);
|
||||
return sizes;
|
||||
}
|
||||
const catalogStatus = page => page.evaluate(async () => {
|
||||
const request = indexedDB.open("hghubx-tv-catalog-v1", 1);
|
||||
const db = await new Promise((resolve, reject) => { request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error); });
|
||||
const read = db.transaction("checkpoints", "readonly").objectStore("checkpoints").get(window.__tvFixture.base);
|
||||
const value = await new Promise((resolve, reject) => { read.onsuccess = () => resolve(read.result); read.onerror = () => reject(read.error); }); db.close(); return value;
|
||||
});
|
||||
try {
|
||||
process.env.VITE_APP_EDITION = "tv";
|
||||
mediaDirectory = await mkdtemp(join(tmpdir(), "hghubx-tv-media-"));
|
||||
execFileSync(process.env.FFMPEG_PATH || "ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=10", "-t", "60", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p", "-movflags", "+faststart", join(mediaDirectory, "fixture.mp4")], { timeout: 60000 });
|
||||
vite = await createServer({ root, cacheDir: join(root, "node_modules/.vite-tv-remote"),
|
||||
// Worker-only dependencies otherwise arrive after the first page has mounted
|
||||
// and Vite can invalidate its optimized graph in the middle of a scenario.
|
||||
optimizeDeps: { include: ["pinyin-pro"] },
|
||||
server: { host: "127.0.0.1", port: 0, strictPort: false, hmr: false, open: false } });
|
||||
await vite.listen(); origin = `http://127.0.0.1:${vite.httpServer.address().port}`;
|
||||
let executablePath = process.env.BROWSER_EXECUTABLE;
|
||||
if (!executablePath) {
|
||||
for (const candidate of ["/usr/bin/google-chrome", "/usr/bin/chromium", "/usr/bin/chromium-browser"]) {
|
||||
if (await access(candidate).then(() => true, () => false)) { executablePath = candidate; break; }
|
||||
}
|
||||
}
|
||||
browser = await chromium.launch({ headless: true, executablePath: executablePath || chromium.executablePath(), args: ["--autoplay-policy=no-user-gesture-required"] });
|
||||
report.browser = browser.version();
|
||||
await scenario("history-shelf-width-loading-ready", async () => {
|
||||
const { page } = await open({ fixture: { heldDetailIds: [1, 2, 3], legacy: { history: [1, 2, 3].map((id, index) => ({ id, ep: 1, t: 5, dur: 60, at: 30 - index })) } },
|
||||
posterSizes: { 1: [160, 400], 2: [900, 300], 3: [500, 500] } });
|
||||
const shelf = page.locator('[data-tv-region="home-继续观看"]');
|
||||
await page.waitForFunction(() => window.__tvFixture.detailReleases.length === 2);
|
||||
assert.equal(await shelf.getByRole("button", { name: "正在加载影片信息", exact: true }).count(), 3);
|
||||
await page.locator('[data-tv-region="home-推荐"] .tv-card').first().waitFor();
|
||||
const loading = await assertShelfWidths(page, "loading");
|
||||
await page.evaluate(() => {
|
||||
const fixture = window.__tvFixture;
|
||||
fixture.cards[0].title = "短名";
|
||||
fixture.cards[1].title = "这是一部标题很长且不应改变封面宽度的作品";
|
||||
fixture.cards[2].title = "A_Long_Unbroken_Title_For_Card_Width";
|
||||
fixture.heldDetailIds = []; fixture.releaseDetails();
|
||||
});
|
||||
await page.waitForFunction(() => {
|
||||
const cards = [...document.querySelectorAll('[data-tv-region="home-继续观看"] .tv-card')];
|
||||
return cards.length === 3 && cards.every(card => {
|
||||
const image = card.querySelector("img"); return image?.complete && image.naturalWidth > 0;
|
||||
});
|
||||
});
|
||||
assert.deepEqual(await shelf.locator("strong").allTextContents(), ["短名", "这是一部标题很长且不应改变封面宽度的作品", "A_Long_Unbroken_Title_For_Card_Width"]);
|
||||
assert.deepEqual(await shelf.locator("img").evaluateAll(images => images.map(image => [image.naturalWidth, image.naturalHeight])), [[160, 400], [900, 300], [500, 500]]);
|
||||
const ready = [];
|
||||
for (const [width, height] of [[1280, 720], [1920, 1080], [3840, 2160]]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
ready.push({ width, height, ...await assertShelfWidths(page, "ready") });
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
// Simulate a WebView without flex gap; the fallback belongs to each slot,
|
||||
// including LibraryCard's observer wrapper, rather than its inner button.
|
||||
const gaps = await page.evaluate(() => {
|
||||
document.documentElement.setAttribute("data-legacy-flex-gap", "");
|
||||
return ["home-继续观看", "home-推荐"].map(region => {
|
||||
const track = document.querySelector(`[data-tv-region="${region}"]`); track.style.gap = "0px";
|
||||
const slots = [...track.children];
|
||||
return { region, expected: parseFloat(getComputedStyle(document.documentElement).fontSize) * .9,
|
||||
values: slots.slice(1, 3).map((slot, index) => slot.offsetLeft - slots[index].offsetLeft - slots[index].offsetWidth) };
|
||||
});
|
||||
});
|
||||
for (const row of gaps) for (const gap of row.values) assert(Math.abs(gap - row.expected) <= 1, `${row.region}: legacy spacing ${gap} must equal ${row.expected}`);
|
||||
await assertShelfWidths(page, "legacy gap");
|
||||
await screenshot(page, "history-shelf-equal-width-1280x720.png");
|
||||
return { loading, ready, legacyGaps: gaps };
|
||||
});
|
||||
await scenario("agreement-gate-single-controller", async () => {
|
||||
const { page } = await open({ accepted: false });
|
||||
await page.locator('[data-tv-focus="agreement-checkbox"]').waitFor();
|
||||
// index.html carries the ES5 startup watchdog again (#138); the fixture
|
||||
// counts ready() calls through __HG_STARTUP__. The gate contract here is:
|
||||
// mounting the gate IS startup success — no content IPC, exactly one
|
||||
// keyboard listener and one native back subscription before acceptance.
|
||||
const pre = await page.evaluate(() => ({ ready: window.__tvFixture.startupReady, keys: window.__tvFixture.keyboardListeners,
|
||||
native: window.__tvFixture.nativeListeners, requests: window.__tvFixture.calls.filter(call => /^(api_|app_boot|line_auto|line_health)/.test(call.command)) }));
|
||||
assert.equal(pre.keys, 1); assert.equal(pre.native, 1); assert.deepEqual(pre.requests, []);
|
||||
assert(await page.locator('[data-tv-focus="agreement-accept"]').isDisabled());
|
||||
await activate(page, "agreement-checkbox");
|
||||
assert(await page.locator('[data-tv-focus="agreement-checkbox"]').isChecked());
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", repeat: true, bubbles: true }));
|
||||
window.dispatchEvent(new KeyboardEvent("keyup", { key: "Enter", bubbles: true }));
|
||||
});
|
||||
assert(await page.locator('[data-tv-focus="agreement-checkbox"]').isChecked(), "Confirm repeat must not toggle twice");
|
||||
await activate(page, "agreement-accept");
|
||||
await page.locator('[data-tv-focus="nav-home"]').waitFor();
|
||||
assert.equal((await calls(page, "app_boot")).length, 1);
|
||||
assert.equal(await page.locator("#hg-startup-error").count(), 0);
|
||||
return pre;
|
||||
});
|
||||
await scenario("keyboard-focus-modal-tag-gate", async () => {
|
||||
const { page } = await open();
|
||||
const card = page.locator('[data-tv-region="home-推荐"] [data-tv-focus="video:1"]');
|
||||
await card.waitFor(); await card.focus(); await page.keyboard.press("Enter");
|
||||
await page.locator('[data-tv-focus="detail:video:1:more"]').waitFor();
|
||||
assert.equal(await page.locator(".tv-page-heading > :not(h1), .tv-detail-eyebrow").count(), 0, "Page chrome must contain no decorative subtitles");
|
||||
await page.waitForFunction(() => !document.querySelector('[data-tv-focus="detail:video:1:more"]')?.disabled);
|
||||
await screenshot(page, "detail-1280x720.png");
|
||||
await activate(page, "detail:video:1:more");
|
||||
await page.getByRole("dialog", { name: "屏蔽标签" }).waitFor();
|
||||
for (const key of ["Tab", "ArrowRight", "ArrowDown", "ArrowLeft", "ArrowUp", "Tab"]) {
|
||||
await page.keyboard.press(key);
|
||||
assert(await page.evaluate(() => !!document.activeElement?.closest('[data-tv-modal="detail-tags:video:1"]')), "Modal must own focus");
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute("data-tv-focus") === "detail:video:1:more");
|
||||
await page.waitForTimeout(200);
|
||||
await page.evaluate(() => {
|
||||
window.__tvFixture.back(); window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
|
||||
window.dispatchEvent(new KeyboardEvent("keyup", { key: "Escape", bubbles: true }));
|
||||
});
|
||||
await page.waitForFunction(() => document.activeElement?.getAttribute("data-tv-focus") === "video:1" && !!document.activeElement?.closest('[data-tv-region="home-推荐"]'));
|
||||
assert.equal(await page.evaluate(() => window.__tvFixture.exits), 0, "Native and keyboard back pair must pop once");
|
||||
await page.keyboard.press("Enter"); await activate(page, "detail:video:1:more");
|
||||
await activate(page, "block:都市"); await activate(page, "block-confirm");
|
||||
await page.getByRole("heading", { name: "内容已屏蔽" }).waitFor();
|
||||
assert.equal(await page.locator(".tv-detail-cover img").count(), 0); assert.equal(await page.locator("video").count(), 0);
|
||||
return { focusRestored: true, modalTrapped: true, duplicateBackSuppressed: true, blockedMediaUnmounted: true };
|
||||
});
|
||||
await scenario("episode-grid-uniform-height", async () => {
|
||||
// Episode 1 has a short label, episode 2 a long wrapping title, and the
|
||||
// legacy history marks episode 2 with the extra "上次观看" line. All three
|
||||
// stresses used to stretch a single grid cell taller than its neighbours.
|
||||
const { page } = await open({ fixture: { legacy: { history: [{ id: 1, ep: 2, t: 23, dur: 60, at: 300 }] } } });
|
||||
await page.locator('[data-tv-region="home-推荐"] [data-tv-focus="video:1"]').waitFor();
|
||||
await activate(page, "video:1");
|
||||
await page.locator('[data-tv-focus="detail:video:1:part:2"]').waitFor();
|
||||
await page.locator('[data-tv-focus="detail:video:1:part:2"] small').filter({ hasText: "上次观看" }).waitFor();
|
||||
const measure = () => page.evaluate(() => {
|
||||
const buttons = [...document.querySelectorAll(".tv-detail-episode-grid button")];
|
||||
return buttons.map(button => {
|
||||
const label = button.querySelector("span");
|
||||
return { height: button.getBoundingClientRect().height,
|
||||
scrollHeight: button.scrollHeight, clientHeight: button.clientHeight,
|
||||
labelClamped: label ? label.scrollHeight > label.clientHeight + 1 : false,
|
||||
labelText: label?.textContent || "" };
|
||||
});
|
||||
});
|
||||
const results = [];
|
||||
for (const [width, height] of [[1280, 720], [1920, 1080], [3840, 2160]]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
|
||||
const cells = await measure();
|
||||
assert.equal(cells.length, 2, "Both episodes must render");
|
||||
const expected = parseFloat(await page.evaluate(() => getComputedStyle(document.documentElement).fontSize)) * 4.6667;
|
||||
for (const [index, cell] of cells.entries()) {
|
||||
assert(Math.abs(cell.height - expected) <= 1, `${width}px: episode ${index + 1} height ${cell.height} must equal ${expected}`);
|
||||
assert(cell.scrollHeight <= cell.clientHeight + 1, `${width}px: episode ${index + 1} content must fit its fixed cell`);
|
||||
}
|
||||
assert(Math.abs(cells[0].height - cells[1].height) <= 1, `${width}px: episode cells must be equal height`);
|
||||
results.push({ width, height, heights: cells.map(cell => cell.height), longLabelClamped: cells[1].labelClamped });
|
||||
}
|
||||
assert(results.some(result => result.longLabelClamped), "The long episode title must clamp, not stretch the cell");
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await screenshot(page, "episode-grid-uniform-1280x720.png");
|
||||
return results;
|
||||
});
|
||||
await scenario("actual-worker-initials-resume-errors", async () => {
|
||||
const { page } = await open();
|
||||
await activate(page, "nav-search");
|
||||
await page.getByText(/目录同步完成/).waitFor();
|
||||
const status = await catalogStatus(page); assert.equal(status.count, 12); assert.equal(status.complete, true);
|
||||
const matches = await page.evaluate(async () => {
|
||||
const { queryCatalog } = await import("/src/tv/search/catalog.ts");
|
||||
const p = { blockedTags: [], paused: false, hideUntagged: false }, result = {};
|
||||
for (const query of ["WDSJ", "wdsj", "DSJ", "wdai sj2", "W-D_S.J"]) result[query] = (await queryCatalog(window.__tvFixture.base, query, 0, p)).items.map(item => `${item.kind}:${item.id}`);
|
||||
return result;
|
||||
});
|
||||
assert.deepEqual(matches.WDSJ, matches.wdsj); assert.deepEqual(matches.WDSJ, matches["W-D_S.J"]);
|
||||
assert.deepEqual(matches.WDSJ.slice(0, 3), ["video:1", "video:4", "video:2"]); assert(matches.DSJ.includes("video:1")); assert.deepEqual(matches["wdai sj2"], ["video:5"]);
|
||||
for (const key of "WDSJ") await activate(page, `search:key:${key}`);
|
||||
await page.waitForTimeout(350); assert.equal(await activeKey(page), "search:key:J");
|
||||
await page.waitForFunction(() => document.querySelector(".tv-search-query")?.textContent === "WDSJ");
|
||||
await page.locator('[data-tv-focus="search:video:1"]').waitFor();
|
||||
await screenshot(page, "search-1280x720.png");
|
||||
assert.equal((await calls(page, "api_search")).length, 0); assert((await page.evaluate(() => window.__tvFixture.postMax)) <= 2);
|
||||
await page.evaluate(async () => { window.__tvFixture.catalogMode = "repeat"; await (await import("/src/tv/search/catalog.ts")).retryCatalog(window.__tvFixture.base, true); });
|
||||
await page.getByText(/上游返回了重复目录页/).waitFor();
|
||||
const failed = await catalogStatus(page); assert.equal(failed.complete, false); assert.equal(failed.channels[0].nextPage, 2);
|
||||
assert.equal(await page.locator('[data-tv-focus="search:video:1"]').count(), 1, "Sync errors retain old matches");
|
||||
await page.evaluate(async () => { window.__tvFixture.catalogMode = "normal"; await (await import("/src/tv/search/catalog.ts")).retryCatalog(window.__tvFixture.base, true); });
|
||||
await page.getByText(/目录同步完成/).waitFor();
|
||||
return { matches, checkpoint: status, repeatedPageStopped: true, maxPostConcurrency: await page.evaluate(() => window.__tvFixture.postMax) };
|
||||
});
|
||||
await scenario("post-qualification-retry-source-discard", async () => {
|
||||
const { page } = await open({ isolated: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const { qualifyVisiblePosts } = await import("/src/tv/postEligibility.ts");
|
||||
const items = window.__tvFixture.posts.map(post => ({ ...post, kind: "post" }));
|
||||
window.__tvFixture.failPostIds = [1];
|
||||
const first = await qualifyVisiblePosts(items, { source: window.__tvFixture.base, isCurrent: () => true, allowed: item => item.id !== 6 });
|
||||
window.__tvFixture.failPostIds = [];
|
||||
const retry = await qualifyVisiblePosts([items[0]], { source: window.__tvFixture.base, isCurrent: () => true, allowed: () => true }, true);
|
||||
let current = true;
|
||||
const pending = qualifyVisiblePosts(items, { source: window.__tvFixture.base, isCurrent: () => current, allowed: () => true }, true);
|
||||
current = false;
|
||||
const stale = await pending;
|
||||
return { first: { items: first.items.map(item => item.id), retryable: first.retryable }, retry: retry.items.map(item => item.id), stale: stale.items,
|
||||
calls: window.__tvFixture.calls.filter(call => call.command === "api_post_playback").map(call => call.args.id), max: window.__tvFixture.postMax };
|
||||
});
|
||||
assert.deepEqual(result.first, { items: [2, 3, 4, 5], retryable: 1 }); assert.deepEqual(result.retry, [1]); assert.deepEqual(result.stale, []);
|
||||
assert(!result.calls.includes(6), "Blocked tags must prevent even eligibility parsing"); assert(result.max <= 2);
|
||||
return result;
|
||||
});
|
||||
await scenario("library-atomic-migration", async () => {
|
||||
const { page } = await open({ isolated: true });
|
||||
return page.evaluate(async () => (await import("/tests/tv-library.ts")).runTvLibraryTests());
|
||||
});
|
||||
await scenario("playback-response-compatibility", async () => {
|
||||
const { page } = await open({ isolated: true });
|
||||
const result = await page.evaluate(async () => {
|
||||
const { playStreams } = await import("/src/tv/player/content.ts");
|
||||
const current = playStreams({ id: "7", ep: "2", streams: { main: "main.m3u8", hevc: "hevc.m3u8" } }, 7, "2");
|
||||
const legacy = playStreams({ id: 7, ep_num: 2, video_url: "legacy.m3u8" }, 7, "2");
|
||||
let wrongId = "", wrongPart = "", missingId = "", missingPart = "";
|
||||
try { playStreams({ id: "8", ep: 2, streams: { main: "wrong-id.m3u8" } }, 7, "2"); }
|
||||
catch (error) { wrongId = error instanceof Error ? error.message : String(error); }
|
||||
try { playStreams({ id: "7", ep: 3, streams: { main: "wrong-part.m3u8" } }, 7, "2"); }
|
||||
catch (error) { wrongPart = error instanceof Error ? error.message : String(error); }
|
||||
try { playStreams({ ep: 2, streams: { main: "missing-id.m3u8" } }, 7, "2"); }
|
||||
catch (error) { missingId = error instanceof Error ? error.message : String(error); }
|
||||
try { playStreams({ id: "7", streams: { main: "missing-part.m3u8" } }, 7, "2"); }
|
||||
catch (error) { missingPart = error instanceof Error ? error.message : String(error); }
|
||||
return { current, legacy, wrongId, wrongPart, missingId, missingPart };
|
||||
});
|
||||
assert.deepEqual(result.current, { main: "main.m3u8", hevc: "hevc.m3u8" });
|
||||
assert.deepEqual(result.legacy, { main: "legacy.m3u8", hevc: undefined });
|
||||
assert.equal(result.wrongId, "播放信息已变化,请重试当前剧集");
|
||||
assert.equal(result.wrongPart, "播放信息已变化,请重试当前剧集");
|
||||
assert.equal(result.missingId, "播放信息已变化,请重试当前剧集");
|
||||
assert.equal(result.missingPart, "播放信息已变化,请重试当前剧集");
|
||||
return result;
|
||||
});
|
||||
await scenario("legacy-metadata-autofill-home-library", async () => {
|
||||
const legacy = { favs: [1, 4], postFavs: [1], history: [
|
||||
{ id: 1, ep: 2, t: 23, dur: 60, at: 300 },
|
||||
{ id: 2, ep: 1, t: 12, dur: 60, at: 200 },
|
||||
{ id: 3, ep: 2, t: 41, dur: 60, at: 100 },
|
||||
] };
|
||||
const { page } = await open({ fixture: { legacy, detailDelay: 120 } });
|
||||
assert.equal(await page.evaluate(() => document.querySelector(".tv-page-scroll:not([hidden])")?.scrollTop), 0, "First page must open at its heading");
|
||||
await page.waitForFunction(() => {
|
||||
const shelf = document.querySelector('[data-tv-region="home-继续观看"]');
|
||||
return ["我的时间", "我的时间 第二季", "新的时间"].every((title, index) => {
|
||||
const card = shelf?.querySelector(`[data-tv-focus="video:${index + 1}"]`);
|
||||
return card?.querySelector("strong")?.textContent === title && !!card.querySelector("img");
|
||||
});
|
||||
});
|
||||
assert.equal(await page.locator(".tv-detail-route").count(), 0, "History metadata fills without opening detail");
|
||||
const before = await page.evaluate(async () => (await import("/src/tv/library.ts")).listLibrary());
|
||||
for (const item of legacy.history) {
|
||||
const row = before.find(row => row.key === `video:${item.id}`);
|
||||
assert(row?.progress, "History must still exist after hydration");
|
||||
assert.deepEqual({ part: row.progress.part, seconds: row.progress.seconds, duration: row.progress.duration, updatedAt: row.progress.updatedAt },
|
||||
{ part: String(item.ep), seconds: item.t, duration: item.dur, updatedAt: item.at });
|
||||
}
|
||||
assert(before.find(row => row.key === "video:1")?.favorite);
|
||||
assert.equal((await calls(page, "api_video")).filter(call => call.args.id === 4).length, 0, "Unvisited library favorites are not eagerly requested");
|
||||
await screenshot(page, "legacy-history-hydrated-1280x720.png");
|
||||
await activate(page, "nav-library");
|
||||
await page.waitForFunction(() => {
|
||||
const grid = document.querySelector('[data-tv-region="library-grid"]');
|
||||
return grid?.querySelector('[data-tv-focus="video:4"] strong')?.textContent === "WDSJ"
|
||||
&& grid?.querySelector('[data-tv-focus="post:1"] strong')?.textContent === "我的时间视频1";
|
||||
});
|
||||
assert.equal(await page.locator(".tv-detail-route").count(), 0);
|
||||
const after = await page.evaluate(async () => (await import("/src/tv/library.ts")).listLibrary());
|
||||
assert(after.find(row => row.key === "video:1")?.favorite && after.find(row => row.key === "post:1")?.favorite, "Same numeric video/post IDs hydrate independently");
|
||||
assert.equal((await calls(page, "api_video")).filter(call => call.args.id === 1).length, 1, "Resolved metadata is reused across home and library");
|
||||
assert.equal((await calls(page, "api_play")).length, 0, "Metadata hydration must not request video playback");
|
||||
assert.equal(await page.locator("video").count(), 0);
|
||||
const maximum = await page.evaluate(() => window.__tvFixture.detailMax);
|
||||
assert(maximum <= 2, "Visible library hydration must stay at two concurrent detail requests");
|
||||
await screenshot(page, "legacy-favorites-hydrated-1280x720.png");
|
||||
return { automaticTitles: true, preservedProgress: true, independentKinds: true, maxDetailConcurrency: maximum };
|
||||
});
|
||||
await scenario("legacy-metadata-tag-gate-retry", async () => {
|
||||
const { page } = await open({ fixture: {
|
||||
legacy: { favs: [], history: [{ id: 1, ep: 1, t: 5, dur: 60, at: 20 }, { id: 6, ep: 2, t: 18, dur: 60, at: 10 }] },
|
||||
contentPreferences: { blockedTags: ["都市"], paused: false, hideUntagged: true },
|
||||
detailDelay: 100, failDetailIds: [6],
|
||||
} });
|
||||
await page.waitForFunction(() => {
|
||||
const shelf = document.querySelector('[data-tv-region="home-继续观看"]');
|
||||
return shelf?.querySelector('[data-tv-focus="video:1"] strong')?.textContent === "已屏蔽的内容"
|
||||
&& shelf?.querySelector('[data-tv-focus="video:6"]')?.textContent?.includes("信息加载失败");
|
||||
});
|
||||
const blocked = page.locator('[data-tv-region="home-继续观看"] [data-tv-focus="video:1"]');
|
||||
assert.equal(await blocked.locator("img").count(), 0, "Resolved blocked tags must never mount a cover");
|
||||
assert.equal((await calls(page, "api_video")).filter(call => call.args.id === 1).length, 1, "Unknown legacy tags must be resolved even when hideUntagged is enabled");
|
||||
await assertShelfWidths(page, "blocked and failed metadata");
|
||||
await page.evaluate(() => { window.__tvFixture.failDetailIds = []; });
|
||||
const retry = page.locator('[data-tv-region="home-继续观看"] [data-tv-focus="video:6"]');
|
||||
await retry.focus(); await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(() => document.querySelector('[data-tv-region="home-继续观看"] [data-tv-focus="video:6"] strong')?.textContent === "夜晚故事");
|
||||
assert.equal(await retry.locator("img").count(), 1);
|
||||
assert.equal(await page.locator(".tv-detail-route").count(), 0, "Confirm on failed metadata retries without entering detail");
|
||||
assert.equal(await activeKey(page), "video:6", "Metadata replacement preserves the focused card");
|
||||
assert.equal((await calls(page, "api_video")).filter(call => call.args.id === 6).length, 2, "Retry must request failed metadata exactly once");
|
||||
await assertShelfWidths(page, "metadata retry complete");
|
||||
return { unknownTagsHydrated: true, blockedCoverAbsent: true, retryByRemote: true, focusPreserved: true };
|
||||
});
|
||||
await scenario("player-remote-seek-last-part", async () => {
|
||||
const { page } = await open();
|
||||
await page.locator('[data-tv-region="home-推荐"] [data-tv-focus="video:1"]').waitFor();
|
||||
await page.locator('[data-tv-region="home-推荐"] [data-tv-focus="video:1"]').focus(); await page.keyboard.press("Enter");
|
||||
await activate(page, "detail:video:1:part:2");
|
||||
await page.waitForFunction(() => document.querySelector("video")?.currentTime > .1);
|
||||
await page.waitForFunction(() => document.querySelector(".tv-player-controls")?.hidden === true, null, { timeout: 10000 });
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(() => document.querySelector(".tv-player-controls")?.hidden === false && document.activeElement?.getAttribute("data-tv-focus") === "player:play");
|
||||
await screenshot(page, "player-1280x720.png");
|
||||
assert.equal(await page.locator(".tv-player-hint, .tv-detail-eyebrow").count(), 0, "Player must not render decorative subtitle hints");
|
||||
assert.equal(await page.locator("video").evaluate(video => video.paused), false, "First confirm reveals without toggling");
|
||||
await page.keyboard.press("Enter"); await page.waitForFunction(() => document.querySelector("video")?.paused);
|
||||
await activate(page, "player:progress");
|
||||
const before = await page.locator("video").evaluate(video => video.currentTime);
|
||||
await page.keyboard.press("ArrowRight");
|
||||
assert(Math.abs(await page.locator("video").evaluate(video => video.currentTime) - before) < .5, "Seek preview must not commit");
|
||||
await page.keyboard.press("Escape"); assert.equal(await page.locator(".tv-player-seek-hint").count(), 0);
|
||||
await page.waitForTimeout(200);
|
||||
await page.keyboard.press("ArrowRight"); await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(before => document.querySelector("video").currentTime >= before + 9, before);
|
||||
await page.locator("video").evaluate(video => { video.currentTime = video.duration - 1; });
|
||||
// Playwright's physical-key table omits some Android media keys; dispatch
|
||||
// the same DOM key the native remote emits through the real controller.
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new KeyboardEvent("keydown", { key: "MediaPlay", bubbles: true }));
|
||||
window.dispatchEvent(new KeyboardEvent("keyup", { key: "MediaPlay", bubbles: true }));
|
||||
});
|
||||
await page.getByRole("dialog", { name: /播放完毕/ }).waitFor();
|
||||
assert.equal(await page.locator('[data-tv-focus="player:ended-next"]').count(), 0);
|
||||
assert((await calls(page, "api_play")).every(call => call.args.id === 1 && call.args.ep === 2));
|
||||
return { confirmTwoStages: true, previewCancelCommit: true, finalPartNoOtherWork: true };
|
||||
});
|
||||
await scenario("720p-1080p-4k-layout", async () => {
|
||||
const { page } = await open(); const measurements = [];
|
||||
await page.locator('[data-tv-region="home-推荐"] .tv-card').first().waitFor();
|
||||
for (const [width, height] of [[1280, 720], [1920, 1080], [3840, 2160]]) {
|
||||
await page.setViewportSize({ width, height });
|
||||
const card = page.locator('[data-tv-region="home-推荐"] .tv-card').first(); await card.focus();
|
||||
const size = await card.evaluate(element => { const box = element.getBoundingClientRect(); return { x: box.x, y: box.y, right: box.right, bottom: box.bottom,
|
||||
text: parseFloat(getComputedStyle(element.querySelector("strong")).fontSize), helper: parseFloat(getComputedStyle(element.querySelector("small")).fontSize), outline: getComputedStyle(element).outlineStyle }; });
|
||||
assert(size.text >= 18 * width / 960 - .1); assert(size.helper >= 16 * width / 960 - .1); assert.equal(size.outline, "solid");
|
||||
assert(size.x >= 0 && size.right <= width && size.y >= 0 && size.bottom <= height);
|
||||
const file = `home-${width}x${height}.png`; await page.screenshot({ path: join(output, file), animations: "disabled" }); report.screenshots.push(file); measurements.push({ width, height, ...size });
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await activate(page, "nav-settings");
|
||||
await page.locator('[data-tv-focus="autoplay-next"]').waitFor();
|
||||
assert.equal(await page.locator(".tv-page-heading > :not(h1)").count(), 0, "Settings heading must contain only its title");
|
||||
await screenshot(page, "settings-1280x720.png");
|
||||
return measurements;
|
||||
});
|
||||
await scenario("standard-build-excludes-tv-resources", async () => {
|
||||
await vite.close(); vite = undefined;
|
||||
process.env.VITE_APP_EDITION = "standard";
|
||||
const modules = new Set();
|
||||
const result = await build({ root, logLevel: "warn", plugins: [{ name: "capture-standard-module-graph", generateBundle(_options, bundle) {
|
||||
for (const file of Object.values(bundle)) if (file.type === "chunk") for (const id of Object.keys(file.modules)) modules.add(id);
|
||||
} }], build: { write: false } });
|
||||
const forbidden = [...modules].filter(id => /\/src\/tv\/|\/pinyin-pro\//.test(id));
|
||||
assert.deepEqual(forbidden, [], "Standard app bundle must not contain TV modules or pinyin-pro");
|
||||
const outputs = (Array.isArray(result) ? result : [result]).flatMap(item => item.output || []);
|
||||
const css = outputs.filter(item => item.type === "asset" && item.fileName.endsWith(".css")).map(item => String(item.source)).join("\n");
|
||||
assert(!css.includes(".tv-search-keyboard"));
|
||||
return { modules: modules.size, forbidden, emitted: outputs.map(item => item.fileName) };
|
||||
});
|
||||
for (const context of contexts) for (const page of context.pages()) {
|
||||
assert.deepEqual(await page.evaluate(() => window.__tvFixture?.unknown || []), [], "Unexpected mock IPC is a hard failure");
|
||||
}
|
||||
assert.deepEqual(report.errors, []); assert.deepEqual(report.external, []);
|
||||
} catch (error) {
|
||||
report.error = String(error.stack || error); console.error(report.error); process.exitCode = 1;
|
||||
} finally {
|
||||
for (const [index, context] of contexts.entries()) { await context.tracing.stop({ path: join(output, `trace-${index}.zip`) }).catch(() => {}); await context.close(); }
|
||||
await browser?.close(); await vite?.close();
|
||||
if (mediaDirectory) await rm(mediaDirectory, { recursive: true, force: true });
|
||||
if (savedEdition === undefined) delete process.env.VITE_APP_EDITION; else process.env.VITE_APP_EDITION = savedEdition;
|
||||
report.passed = report.cases.filter(item => item.status === "passed").length;
|
||||
await writeFile(join(output, "report.json"), JSON.stringify(report, null, 2));
|
||||
console.log(`TV remote acceptance: ${report.passed}/${report.cases.length} scenarios. Artifacts: ${output}`);
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
// Repeatable interaction probe with local IPC fixtures; reports are not native device benchmarks.
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { createServer } from 'vite';
|
||||
import { chromium } from 'playwright-core';
|
||||
import { installFixture } from './fixtures/app-ui.mjs';
|
||||
const root = new URL('../', import.meta.url).pathname;
|
||||
const output = `${root}test-results/ui-performance/${Date.now()}`;
|
||||
await mkdir(output, {recursive:true});
|
||||
const server = await createServer({root,server:{host:'127.0.0.1',port:0}});
|
||||
let browser;
|
||||
try {
|
||||
await server.listen();
|
||||
browser = await chromium.launch({headless:true,executablePath:process.env.BROWSER_EXECUTABLE || undefined});
|
||||
const page=await browser.newPage({viewport:{width:390,height:844},isMobile:true,hasTouch:true,userAgent:'Mozilla/5.0 (iPhone; CPU iPhone OS 17_1_1 like Mac OS X) AppleWebKit/605.1.15 Version/17.1 Mobile/15E148 Safari/604.1'});
|
||||
await page.addInitScript(installFixture,{theme:'light',titles:['城市与晚风','重逢在夏日以后','星河旅人','无声的答案','我的奇妙假期','晴天来信']});
|
||||
await page.route('**/*',r=>new URL(r.request().url()).hostname==='127.0.0.1'?r.continue():r.fulfill({contentType:'image/svg+xml',body:'<svg xmlns="http://www.w3.org/2000/svg" width="300" height="400"><rect width="300" height="400" fill="#789"/></svg>'}));
|
||||
await page.goto(server.resolvedUrls.local[0]);
|
||||
await page.getByRole('navigation',{name:'主导航'}).waitFor();
|
||||
const cdp=await page.context().newCDPSession(page);await cdp.send('Emulation.setCPUThrottlingRate',{rate:4});
|
||||
const samples=[];
|
||||
for(let i=0;i<18;i++) {
|
||||
const label=['搜索','分类','我的'][i%3];
|
||||
samples.push(await page.evaluate(async label=>{
|
||||
const button=[...document.querySelectorAll('nav[aria-label="主导航"] button')].find(b=>b.textContent===label);
|
||||
const start=performance.now();button.click();
|
||||
await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(resolve)));
|
||||
return {label,ms:Math.round((performance.now()-start)*10)/10,committed:button.getAttribute('aria-current')==='page'};
|
||||
},label));
|
||||
}
|
||||
const times=samples.map(x=>x.ms).sort((a,b)=>a-b);
|
||||
const report={environment:'Chromium dev build; 4x CPU slowdown; local IPC; click dispatch to two animation frames',samples,p50:times[Math.floor(times.length*.5)],p95:times[Math.floor(times.length*.95)]};
|
||||
await writeFile(`${output}/report.json`,JSON.stringify(report,null,2));console.log(JSON.stringify(report));
|
||||
assert(samples.every(s=>s.committed),'Navigation commits before the next paint');
|
||||
} finally {await browser?.close();await server.close();}
|
||||
@@ -1 +0,0 @@
|
||||
<!doctype html><html><head><meta charset="UTF-8" /></head><body><div id="root"></div><script type="module" src="./channel-pagination.tsx"></script></body></html>
|
||||
@@ -1,78 +0,0 @@
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { ChannelPage } from "../src/features/category/Category";
|
||||
import { AppProvider } from "../src/shared/model/store";
|
||||
import "../src/index.css";
|
||||
|
||||
const page1Ids = [12, 117, 2833, 323, 7628, 2181, 4466, 89, 5000, 903, 6000, 445, 123, 800, 701, 60, 1000, 3000, 20, 40];
|
||||
const page2Ids = [3483, 131, 6174, 3273, 1237, 7000, 500, 9000, 52, 84, 600, 1200, 2500, 3300, 4100, 5200, 6600, 7100, 8100, 9100];
|
||||
|
||||
const makeVideo = (ids: number[]) => ids.map((id, index) => ({
|
||||
id,
|
||||
title: `Video ${id}`,
|
||||
cover: "",
|
||||
tags: [] as string[],
|
||||
score: (index * 13 + 5) % 101,
|
||||
hot: (index * 17 + 11) % 101,
|
||||
episode_count: 1,
|
||||
total_episodes: 1,
|
||||
is_finished: true,
|
||||
is_original: 0,
|
||||
like_count: 0,
|
||||
comment_count: 0,
|
||||
collect_count: 0,
|
||||
}));
|
||||
|
||||
const page1 = makeVideo(page1Ids);
|
||||
const page2 = makeVideo(page2Ids);
|
||||
/* 模拟服务端排序:latest 按 id 降序、hot_window 按 hot 降序、random 固定伪随机。 */
|
||||
const sortList = (list: ReturnType<typeof makeVideo>, sort: string | undefined) => {
|
||||
const arr = [...list];
|
||||
if (sort === "hot_window") return arr.sort((a, b) => b.hot - a.hot);
|
||||
if (sort === "random") return arr.sort((a, b) => (a.id % 13) - (b.id % 13));
|
||||
return arr.sort((a, b) => b.id - a.id);
|
||||
};
|
||||
const pending: { args: Record<string, unknown>; resolve: (value: unknown) => void }[] = [];
|
||||
const fixture = {
|
||||
history: [] as { cmd: string; args: Record<string, unknown> }[],
|
||||
pending,
|
||||
page1,
|
||||
page2,
|
||||
resolveNext(desiredSort?: string, desiredPage?: number) {
|
||||
const index = pending.findIndex(({ args }) =>
|
||||
(desiredSort === undefined || args.sort === desiredSort) && (desiredPage === undefined || args.page === desiredPage));
|
||||
const [request] = index < 0 ? [] : pending.splice(index, 1);
|
||||
if (!request) throw new Error(`no pending api_category request for sort=${desiredSort}, page=${desiredPage}`);
|
||||
const responsePage = Number(request.args.page);
|
||||
const responseSort = request.args.sort as string | undefined;
|
||||
const source = responsePage === 1 ? page1 : page2;
|
||||
request.resolve({
|
||||
items: sortList(source, responseSort),
|
||||
pagination: { page: responsePage, pages: 2, size: 20, total: 40 },
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
Object.assign(window, {
|
||||
channelPaginationFixture: fixture,
|
||||
__TAURI_INTERNALS__: {
|
||||
invoke(cmd: string, args: Record<string, unknown> = {}) {
|
||||
if (cmd === "app_boot") return Promise.resolve({ user: null, logged_in: false, base: "https://fixture.invalid" });
|
||||
if (cmd === "debug_log") return Promise.resolve();
|
||||
if (cmd === "api_category") {
|
||||
fixture.history.push({ cmd, args });
|
||||
return new Promise((resolve) => pending.push({ args, resolve }));
|
||||
}
|
||||
return Promise.reject(`Unexpected IPC: ${cmd}`);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// 生产构建不带 StrictMode;dev 下 StrictMode 会把挂载 effect 跑两遍,而 ChannelPage
|
||||
// 首次加载没有去重,会让 api_category 请求翻倍、后面的分页计数断言全部失真。
|
||||
createRoot(document.querySelector("#root")!).render(
|
||||
<AppProvider>
|
||||
<div style={{ position: "relative", width: 390, height: 844 }}>
|
||||
<ChannelPage cate="ai-duanju" name="AI成人短剧" onBack={() => {}} wide={false} />
|
||||
</div>
|
||||
</AppProvider>,
|
||||
);
|
||||
@@ -1,5 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="UTF-8" /></head>
|
||||
<body><pre id="result">running</pre><script type="module" src="./post-detail-hot.ts"></script></body>
|
||||
</html>
|
||||
@@ -1,11 +0,0 @@
|
||||
import { postHot } from "../src/features/posts/postData";
|
||||
|
||||
const results = {
|
||||
detailNullUsesCount: postHot({ hot: null, counts: { hot: 4321 } }),
|
||||
detailPresentWins: postHot({ hot: 21, counts: { hot: 4321 } }),
|
||||
missingCountsFallsBackToZero: postHot({ hot: null }),
|
||||
absentPostFallsBackToZero: postHot(null),
|
||||
};
|
||||
|
||||
document.querySelector("#result")!.textContent = JSON.stringify(results);
|
||||
Object.assign(window, { postDetailHotFixture: { results } });
|
||||
@@ -11,7 +11,7 @@ function Probe() {
|
||||
likes: store.likes, favs: store.favs, history: store.history, follows: store.follows,
|
||||
searchHist: store.searchHist, volume: store.volume, muted: store.muted,
|
||||
muteOnStartup: store.muteOnStartup, swipeEp: store.swipeEp,
|
||||
preferHevc: store.preferHevc, theme: store.theme,
|
||||
preferHevc: store.preferHevc, fsIdleSecs: store.fsIdleSecs, theme: store.theme,
|
||||
})}</pre>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /></head>
|
||||
<body><div id="root"></div><script type="module" src="./topic-pagination.tsx"></script></body>
|
||||
</html>
|
||||
@@ -1,105 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { TopicPage } from "../src/features/discover/Discover";
|
||||
import { AppProvider } from "../src/shared/model/store";
|
||||
import type { TopicDetail, VideoCard } from "../src/shared/api/types";
|
||||
import "../src/index.css";
|
||||
|
||||
type PendingTopic = {
|
||||
slug: string;
|
||||
page: number;
|
||||
size: number;
|
||||
resolve: (value: TopicDetail) => void;
|
||||
reject: (reason: string) => void;
|
||||
};
|
||||
|
||||
const idsByPage = [
|
||||
Array.from({ length: 20 }, (_, index) => index + 1),
|
||||
[20, ...Array.from({ length: 19 }, (_, index) => index + 21)],
|
||||
Array.from({ length: 20 }, (_, index) => index + 40),
|
||||
Array.from({ length: 20 }, (_, index) => index + 60),
|
||||
[80, 81],
|
||||
];
|
||||
|
||||
const makeVideo = (id: number): VideoCard => ({
|
||||
id,
|
||||
title: `专题影片 ${id}`,
|
||||
cover: "",
|
||||
tags: [],
|
||||
score: 8,
|
||||
episode_count: 1,
|
||||
total_episodes: 1,
|
||||
duration: "01:00",
|
||||
hot: id,
|
||||
like_count: 0,
|
||||
collect_count: 0,
|
||||
comment_count: 0,
|
||||
is_finished: true,
|
||||
is_original: 0,
|
||||
});
|
||||
|
||||
const topicTitles: Record<string, string> = {
|
||||
"hot-aiduanju": "热门专题",
|
||||
"luanlun-aiduanju": "第二专题",
|
||||
};
|
||||
|
||||
const pending: PendingTopic[] = [];
|
||||
const history: { slug: string; page: number; size: number }[] = [];
|
||||
|
||||
const fixture = {
|
||||
history,
|
||||
pending,
|
||||
resolve(slug: string, page: number) {
|
||||
const index = pending.findIndex((request) => request.slug === slug && request.page === page);
|
||||
const [request] = index < 0 ? [] : pending.splice(index, 1);
|
||||
if (!request) throw new Error(`no pending api_topic for ${slug} page ${page}`);
|
||||
const ids = idsByPage[page - 1] ?? [];
|
||||
request.resolve({
|
||||
topic: { id: 1, slug, title: topicTitles[slug] ?? slug, cover: "", video_count: 81 },
|
||||
videos: {
|
||||
items: ids.map(makeVideo),
|
||||
pagination: { page, pages: 5, size: 20, total: 81 },
|
||||
},
|
||||
related: [],
|
||||
});
|
||||
},
|
||||
reject(slug: string, page: number) {
|
||||
const index = pending.findIndex((request) => request.slug === slug && request.page === page);
|
||||
const [request] = index < 0 ? [] : pending.splice(index, 1);
|
||||
if (!request) throw new Error(`no pending api_topic for ${slug} page ${page}`);
|
||||
request.reject("第 3 页暂时不可用");
|
||||
},
|
||||
};
|
||||
|
||||
Object.assign(window, {
|
||||
topicPaginationFixture: fixture,
|
||||
__TAURI_INTERNALS__: {
|
||||
invoke(command: string, args: Record<string, unknown> = {}) {
|
||||
if (command === "app_boot") {
|
||||
return Promise.resolve({ user: null, logged_in: false, base: "https://fixture.invalid" });
|
||||
}
|
||||
if (command === "debug_log") return Promise.resolve();
|
||||
if (command === "api_topic") {
|
||||
const slug = String(args.slug);
|
||||
const page = Number(args.page);
|
||||
const size = Number(args.size);
|
||||
history.push({ slug, page, size });
|
||||
return new Promise((resolve, reject) => pending.push({ slug, page, size, resolve, reject }));
|
||||
}
|
||||
return Promise.reject(`Unexpected IPC: ${command}`);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
function Fixture() {
|
||||
const [slug, setSlug] = useState("hot-aiduanju");
|
||||
return <AppProvider>
|
||||
<div style={{ position: "relative", width: 390, height: 844 }}>
|
||||
<button id="topic-a" style={{ position: "fixed", zIndex: 10, left: 4, top: 4 }} onClick={() => setSlug("hot-aiduanju")}>专题 A</button>
|
||||
<button id="topic-b" style={{ position: "fixed", zIndex: 10, left: 72, top: 4 }} onClick={() => setSlug("luanlun-aiduanju")}>专题 B</button>
|
||||
<TopicPage slug={slug} name={slug} onBack={() => {}} wide={false} />
|
||||
</div>
|
||||
</AppProvider>;
|
||||
}
|
||||
|
||||
createRoot(document.querySelector("#root")!).render(<Fixture />);
|
||||
@@ -0,0 +1,127 @@
|
||||
import { clearHistory, hydrateLibraryContent, initializeLibrary, listLibrary, saveProgress, setFavorite } from "../src/tv/library";
|
||||
import { contentKey, needsLibraryMetadata, type TvContent } from "../src/tv/model";
|
||||
|
||||
let passed=0;
|
||||
function assert(condition: unknown, message: string): asserts condition {
|
||||
if (!condition) throw new Error(`TV library: ${message}`);
|
||||
passed++;
|
||||
}
|
||||
async function rejects(task: () => Promise<unknown>, message: string) {
|
||||
let rejected = false;
|
||||
try { await task(); } catch { rejected = true; }
|
||||
assert(rejected, message);
|
||||
}
|
||||
async function migrationMarkers(): Promise<unknown[]> {
|
||||
const db = await new Promise<IDBDatabase>((resolve,reject)=>{
|
||||
const request=indexedDB.open("hghubx-tv-library-v1",1);
|
||||
request.onsuccess=()=>resolve(request.result); request.onerror=()=>reject(request.error);
|
||||
});
|
||||
try {
|
||||
return await new Promise<unknown[]>((resolve,reject)=>{
|
||||
const transaction=db.transaction("meta","readonly"), request=transaction.objectStore("meta").getAll();
|
||||
transaction.oncomplete=()=>resolve(request.result); transaction.onabort=()=>reject(transaction.error);
|
||||
});
|
||||
} finally { db.close(); }
|
||||
}
|
||||
|
||||
/** Run only in the isolated browser profile supplied by the remote TV scenario. */
|
||||
export async function runTvLibraryTests() {
|
||||
passed=0;
|
||||
const fixture=(window as unknown as {__tvFixture:{failAck?:boolean}}).__tvFixture;
|
||||
assert(fixture, "native IPC fixture is required");
|
||||
const identity={origin:"https://library.fixture.invalid",user_id:17};
|
||||
const guest={favs:[7,7],postFavs:[7],history:[
|
||||
{id:7,ep:3,t:42,dur:120,at:200}, {id:8,ep:1,t:9,dur:60,at:100},
|
||||
]};
|
||||
const selected={favs:[7,8],postFavs:[9],history:[
|
||||
{id:7,ep:1,t:99,dur:150,at:100}, {id:8,ep:5,t:17,dur:80,at:300},
|
||||
]};
|
||||
const accounts={version:1,accounts:{
|
||||
[JSON.stringify([identity.origin,identity.user_id])]:selected,
|
||||
[JSON.stringify([identity.origin,99])]:{favs:[999],history:[]},
|
||||
[JSON.stringify(["https://other.fixture.invalid",identity.user_id])]:{favs:[998],history:[]},
|
||||
}};
|
||||
const guestRaw=JSON.stringify(guest), accountRaw=JSON.stringify(accounts);
|
||||
localStorage.setItem("hghubx_app_v1",guestRaw);
|
||||
localStorage.setItem("hghubx_accounts_v1",accountRaw);
|
||||
localStorage.setItem("hghub_app_v1",JSON.stringify({favs:[997],history:[]}));
|
||||
|
||||
// Simulate quota failure after the transaction queued its completion marker.
|
||||
// The library row callback aborts the entire transaction, including that marker.
|
||||
const put=IDBObjectStore.prototype.put;
|
||||
IDBObjectStore.prototype.put=function(value: unknown,key?:IDBValidKey):IDBRequest<IDBValidKey>{
|
||||
if(this.name==="library")throw new DOMException("fixture quota exhausted","QuotaExceededError");
|
||||
return key===undefined ? put.call(this,value) : put.call(this,value,key);
|
||||
};
|
||||
try { await rejects(()=>initializeLibrary(identity),"quota failure must reject import"); }
|
||||
finally { IDBObjectStore.prototype.put=put; }
|
||||
assert((await listLibrary()).length===0,"failed transaction must contain no partial rows");
|
||||
assert((await migrationMarkers()).length===0,"failed transaction must contain no success marker");
|
||||
assert(localStorage.getItem("hghubx_app_v1")===guestRaw,"guest source must be untouched");
|
||||
assert(localStorage.getItem("hghubx_accounts_v1")===accountRaw,"account source must be untouched");
|
||||
|
||||
// Native acknowledgement may fail after the atomic frontend commit.
|
||||
fixture.failAck=true;
|
||||
await rejects(()=>initializeLibrary(identity),"native acknowledgement failure must remain retryable");
|
||||
const rows=await listLibrary(), byKey=new Map(rows.map(row=>[row.key,row]));
|
||||
assert(rows.length===4,"only exact current account and preferred guest cache are imported");
|
||||
assert(byKey.has("video:7")&&byKey.has("post:7"),"same numeric video/post IDs remain distinct");
|
||||
assert(!byKey.has("video:999")&&!byKey.has("video:998")&&!byKey.has("video:997"),"unrelated accounts and stale guest fallback remain excluded");
|
||||
const seven=byKey.get("video:7")!, eight=byKey.get("video:8")!;
|
||||
assert(seven.progress?.part==="3"&&seven.progress.seconds===42&&seven.progress.duration===120&&seven.progress.updatedAt===200,"newer guest progress must be selected as a whole row");
|
||||
assert(eight.progress?.part==="5"&&eight.progress.seconds===17&&eight.progress.duration===80&&eight.progress.updatedAt===300,"newer account progress must be selected as a whole row");
|
||||
assert((await migrationMarkers()).length===1,"committed import needs one durable marker");
|
||||
|
||||
await setFavorite(seven.content,false);
|
||||
await clearHistory();
|
||||
fixture.failAck=false;
|
||||
await initializeLibrary(identity);
|
||||
const afterRetry=await listLibrary();
|
||||
assert(!afterRetry.some(row=>row.key==="video:7"),"ack retry must not restore a removed favorite");
|
||||
assert(afterRetry.every(row=>!row.progress),"ack retry must not restore cleared history");
|
||||
|
||||
const post:TvContent & {video_url:string}={kind:"post",id:7,title:"Mixed 123",cover:"",tags:[],hot:1,video_url:"https://temporary.fixture.invalid/expired.m3u8"};
|
||||
const progress={key:contentKey(post),content:post,part:"4",seconds:12,duration:90,updatedAt:400};
|
||||
await saveProgress(post,progress);
|
||||
await saveProgress(post,{...progress,part:"2",seconds:4,updatedAt:399});
|
||||
const saved=(await listLibrary()).find(row=>row.key==="post:7")!;
|
||||
assert(saved.progress?.part==="4"&&saved.progress.seconds===12,"stale playback writes must not replace newer segment progress");
|
||||
assert(!JSON.stringify(saved).includes("temporary.fixture.invalid"),"temporary playback URLs must never reach persistent metadata");
|
||||
await rejects(()=>saveProgress(post,{...progress,key:"video:7"}),"cross-kind progress identity must reject");
|
||||
assert(localStorage.getItem("hghubx_app_v1")===guestRaw&&localStorage.getItem("hghubx_accounts_v1")===accountRaw,"migration and edits retain original legacy data");
|
||||
// Metadata fills are separate from migration, and never write favorite/progress
|
||||
// fields from the stale snapshot that originally scheduled the request.
|
||||
const missing: TvContent = { kind:"video", id:20, title:"影片 20", cover:"", tags:[], hot:0, metadataState:"missing" };
|
||||
const filled: TvContent = { ...missing, title:"自动补全的作品", cover:"https://cover.fixture.invalid/20", tags:["剧情"], hot:18, metadataState:"ready" };
|
||||
const legacyPlaceholder: TvContent = { kind:"video", id:21, title:"影片 21", cover:"", tags:[], hot:0 };
|
||||
assert(needsLibraryMetadata(legacyPlaceholder), "already-migrated placeholders without a marker need enrichment");
|
||||
assert(!needsLibraryMetadata({...legacyPlaceholder, metadataState:"ready"}), "explicitly resolved titles resembling a placeholder stay resolved");
|
||||
await setFavorite(missing,true);
|
||||
await saveProgress(missing,{key:"video:20",content:missing,part:"3",seconds:44,duration:120,updatedAt:500});
|
||||
assert(await hydrateLibraryContent(filled,()=>true), "active unresolved library item must accept metadata");
|
||||
const hydrated=(await listLibrary()).find(row=>row.key==="video:20")!;
|
||||
assert(hydrated.favorite && hydrated.content.title===filled.title && hydrated.content.cover===filled.cover, "metadata fills preserve collection state");
|
||||
assert(hydrated.progress?.part==="3"&&hydrated.progress.seconds===44&&hydrated.progress.duration===120&&hydrated.progress.updatedAt===500,
|
||||
"metadata fills preserve the entire progress row");
|
||||
assert(hydrated.progress.content.title===filled.title, "progress metadata refreshes alongside card metadata");
|
||||
assert(!await hydrateLibraryContent({...filled,title:"旧请求的晚到信息"},()=>true), "late enrichment cannot replace metadata already resolved elsewhere");
|
||||
assert((await listLibrary()).find(row=>row.key==="video:20")?.content.title===filled.title, "newer metadata survives late response");
|
||||
|
||||
await setFavorite(legacyPlaceholder,true);
|
||||
let current=true;
|
||||
const stale=hydrateLibraryContent({...legacyPlaceholder,title:"过期来源",metadataState:"ready"},()=>current);
|
||||
current=false;
|
||||
assert(!await stale, "source or preference invalidation cancels a pending metadata write");
|
||||
assert(needsLibraryMetadata((await listLibrary()).find(row=>row.key==="video:21")!.content), "invalidated write leaves unresolved metadata for a future retry");
|
||||
await setFavorite(legacyPlaceholder,false);
|
||||
assert(!await hydrateLibraryContent({...legacyPlaceholder,title:"已取消收藏",metadataState:"ready"},()=>true), "cancelled favorite must not be resurrected by hydration");
|
||||
|
||||
const historyOnly:TvContent={kind:"video",id:22,title:"影片 22",cover:"",tags:[],hot:0,metadataState:"missing"};
|
||||
await saveProgress(historyOnly,{key:"video:22",content:historyOnly,part:"2",seconds:8,duration:60,updatedAt:600});
|
||||
let release!:()=>void;
|
||||
const deferred=new Promise<void>(resolve=>{release=resolve;}).then(()=>hydrateLibraryContent({...historyOnly,title:"晚到的详情",metadataState:"ready"},()=>true));
|
||||
await clearHistory(); release();
|
||||
assert(!await deferred, "cleared history must not be reinserted when detail arrives later");
|
||||
assert(!(await listLibrary()).some(row=>row.key==="video:22"||row.key==="video:21"), "removed records stay removed after late metadata");
|
||||
return {passed,scenarios:["atomic-quota-rollback","exact-account-selection","kind-id-isolation","whole-row-newest-history","ack-retry-idempotence","clear-history-marker","segment-progress","url-exclusion","metadata-hydration","preserve-progress-favorites","late-hydration-invalidation","no-deletion-resurrection"]};
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
/** Serialized into Chromium before the actual application module loads. */
|
||||
export function installTvFixture({ accepted = false, legacy, contentPreferences, detailDelay = 0, failDetailIds = [], heldDetailIds = [] } = {}) {
|
||||
const base = "https://tv.fixture.invalid";
|
||||
if (accepted) localStorage.setItem("hghubx_usage_agreement", JSON.stringify({ version: "2026-11-15-v1", accepted: true, acceptedAt: new Date().toISOString() }));
|
||||
localStorage.setItem("hghubx_auto_line", "off");
|
||||
if (legacy && !sessionStorage.getItem("tv-metadata-seeded")) {
|
||||
localStorage.setItem("hghubx_app_v1", JSON.stringify(legacy));
|
||||
sessionStorage.setItem("tv-metadata-seeded", "1");
|
||||
}
|
||||
if (contentPreferences) localStorage.setItem("hghubx_content_preferences_v1", JSON.stringify(contentPreferences));
|
||||
const titles = ["我的时间", "我的时间 第二季", "新的时间", "WDSJ", "我的AI时间2", "夜晚故事"];
|
||||
const cards = titles.map((title, index) => ({ id: index + 1, title, cover: `${base}/poster/${index + 1}`, tags: index === 5 ? ["夜晚"] : ["都市"],
|
||||
score: 8.5, episode_count: 2, total_episodes: 2, hot: 100 - index, like_count: 0, collect_count: 0, comment_count: 0, is_finished: true, is_original: 0,
|
||||
description: "遥控器回归用故事简介", author: { id: 1, name: "Fixture" } }));
|
||||
const posts = Array.from({ length: 6 }, (_, index) => ({ id: index + 1, title: `我的时间视频${index + 1}`, cover: `${base}/post/${index + 1}`, tags: ["视频"], hot: 20 - index, video_url: "" }));
|
||||
const fixture = { base, cards, posts, calls: [], unknown: [], failAck: false, failPosts: false, postActive: 0, postMax: 0, startupReady: 0, keyboardListeners: 0,
|
||||
detailDelay, failDetailIds, detailActive: 0, detailMax: 0, heldDetailIds, detailReleases: [],
|
||||
releaseDetails() { const releases = fixture.detailReleases.splice(0); releases.forEach(release => release()); },
|
||||
nativeListeners: 0, exits: 0, catalogMode: "normal", holdCatalog: false, releaseCatalog: null, failPostIds: [], backChannel: null,
|
||||
back() { if (!fixture.backChannel) throw new Error("Missing native back listener"); fixture.backChannel.onmessage({}); } };
|
||||
Object.defineProperty(window, "__tvFixture", { value: fixture });
|
||||
let startup;
|
||||
Object.defineProperty(window, "__HG_STARTUP__", { configurable: true, get: () => startup, set(value) {
|
||||
const original = value.ready;
|
||||
value.ready = function () { fixture.startupReady++; return original.apply(this, arguments); };
|
||||
startup = value;
|
||||
} });
|
||||
const add = window.addEventListener.bind(window);
|
||||
window.addEventListener = (type, ...rest) => { if (type === "keydown") fixture.keyboardListeners++; return add(type, ...rest); };
|
||||
const callbacks = new Map(); let callbackId = 0;
|
||||
const paged = (items, args = {}, pages = 1) => ({ items, pagination: { page: args.page || 1, pages, size: args.size || 20, total: items.length * pages } });
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
metadata: { currentWindow: { label: "main" }, currentWebview: { label: "main" } },
|
||||
transformCallback(callback) { const id = ++callbackId; callbacks.set(id, callback); return id; },
|
||||
unregisterCallback(id) { callbacks.delete(id); },
|
||||
async invoke(command, args = {}) {
|
||||
fixture.calls.push({ command, args });
|
||||
if (command === "debug_log" || command === "playback_log_write" || command === "line_cancel") return null;
|
||||
if (command === "playback_log_status") return { enabled: false, path: null, error: null };
|
||||
if (command === "plugin:app|register_listener" && args.event === "back-button") { fixture.nativeListeners++; fixture.backChannel = args.handler; return null; }
|
||||
if (command === "plugin:app|remove_listener") return null;
|
||||
if (command === "plugin:app|exit") { fixture.exits++; return null; }
|
||||
if (command === "app_boot") return { base: fixture.base, user: null, logged_in: false, local_mode: true, pending_migration_identity: null };
|
||||
if (command === "tv_migration_complete") { if (fixture.failAck) throw new Error("fixture acknowledgement interrupted"); return null; }
|
||||
if (command === "line_state") return { base: fixture.base, default: base, fixed: [{ name: "测试线路", url: base }] };
|
||||
if (command === "line_health") return { base: fixture.base, ok: true, ms: 1, status: 200 };
|
||||
if (command === "proxy_state") return { mode: "off", url: "", effective: null, system_proxy: false, env_proxy: false };
|
||||
if (command === "proxy_set") return { mode: args.mode, url: "", effective: null, system_proxy: false, env_proxy: false };
|
||||
if (command === "cache_clear") return { webCache: true, platform: "android" };
|
||||
if (command === "api_feed" && args.size === 50) {
|
||||
if (fixture.holdCatalog) await new Promise(resolve => { fixture.releaseCatalog = resolve; });
|
||||
if (fixture.catalogMode === "error") throw new Error("fixture catalog offline");
|
||||
if (fixture.catalogMode === "repeat") return paged(cards, args, 3);
|
||||
return paged(cards, args);
|
||||
}
|
||||
if (["api_feed", "api_category", "api_original_videos", "api_tag_videos"].includes(command)) return paged(cards, args);
|
||||
if (command === "api_rank") return { type: args.kind, items: cards.map((item, index) => ({ ...item, video_id: item.id, rank: index + 1, metric_value: item.hot })) };
|
||||
if (command === "api_posts") { if (fixture.failPosts) throw new Error("fixture post channel offline"); return paged(posts, args); }
|
||||
if (command === "api_video" || command === "api_post") {
|
||||
fixture.detailActive++; fixture.detailMax = Math.max(fixture.detailMax, fixture.detailActive);
|
||||
try {
|
||||
if (fixture.detailDelay) await new Promise(resolve => setTimeout(resolve, fixture.detailDelay));
|
||||
if (fixture.heldDetailIds.includes(args.id)) await new Promise(resolve => fixture.detailReleases.push(resolve));
|
||||
// Tauri invoke rejects with a host string. Keep this a string so the
|
||||
// app's network-only one-shot retry does not swallow the UI retry test.
|
||||
if (fixture.failDetailIds.includes(args.id)) throw "fixture detail unavailable";
|
||||
if (command === "api_post") {
|
||||
const post = posts.find(item => item.id === args.id); if (!post) throw new Error("Unknown post identity");
|
||||
return { ...post, content: "ARTICLE_BODY_MUST_NOT_RENDER" };
|
||||
}
|
||||
const card = cards.find(item => item.id === args.id); if (!card) throw new Error("Unknown video identity");
|
||||
// Episode 2 carries a deliberately long title so the episode grid is
|
||||
// exercised with a wrapping label next to a short one.
|
||||
const titles = { 1: "", 2: "这是一个非常长的剧集标题用于验证选集格子高度一致且不会撑破布局" };
|
||||
return { ...card, counts: { hot: card.hot, collect: 0, comment: 0, like: 0 }, episodes: [1, 2].map(ep => ({ ep_num: ep, title: titles[ep] ?? `第 ${ep} 集`, duration: 60, status: 1 })) };
|
||||
} finally { fixture.detailActive--; }
|
||||
}
|
||||
if (command === "api_play") {
|
||||
// Match the current upstream shape: string id, `ep`, and streams.main.
|
||||
return { id: String(args.id), ep: args.ep, title: cards.find(item => item.id === args.id)?.title, duration: 60,
|
||||
streams: { main: `http://hg.localhost/seg?u=${encodeURIComponent(`${base}/video-${args.id}-${args.ep}.mp4`)}` } };
|
||||
}
|
||||
if (command === "api_post_playback") {
|
||||
fixture.postActive++; fixture.postMax = Math.max(fixture.postMax, fixture.postActive);
|
||||
try {
|
||||
await new Promise(resolve => setTimeout(resolve, 40));
|
||||
if (fixture.failPostIds.includes(args.id)) throw new Error("视频不存在或不可播放");
|
||||
return { videos: [7, 12].map(index => ({ index, url: `http://hg.localhost/seg?u=${encodeURIComponent(`${base}/post-${args.id}-${index}.mp4`)}` })) };
|
||||
} finally { fixture.postActive--; }
|
||||
}
|
||||
if (command === "api_topics") return { items: [] };
|
||||
if (command === "api_tags") return { categories: [] };
|
||||
fixture.unknown.push(command);
|
||||
throw new Error(`Unexpected TV fixture IPC: ${command}`);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><title>TV isolated module checks</title></head><body><main>TV isolated module checks</main></body></html>
|
||||
@@ -1,12 +1,8 @@
|
||||
{
|
||||
"_comment": "Code lines, not raw lines. Lower a budget in the PR that moves a concern out; never raise one in a feature PR. A pure file-to-directory split may record one measured baseline only when the delta is module/import scaffolding, and must keep its previous value in metadata.",
|
||||
"src/features/feed/Feed.tsx": 1489,
|
||||
"src-tauri/src/net": {
|
||||
"budget": 1877,
|
||||
"previous": 1814,
|
||||
"reason": "pure net.rs -> net/ split; +63 lines are seven module/use headers, item inventory unchanged"
|
||||
},
|
||||
"src-tauri/src/api": 1108,
|
||||
"src/features/feed/Feed.tsx": 680,
|
||||
"src-tauri/src/net": 1320,
|
||||
"src-tauri/src/api": 920,
|
||||
"src-tauri/src/media": 1045,
|
||||
"src-tauri/src/lines": 884
|
||||
"src-tauri/src/lines": 560
|
||||
}
|
||||
Reference in new issue
Block a user