ci(native): add the frontend workspace, fast CI lanes, and headless gates

This commit is contained in:
DarkSky committed 2026-11-22 04:26:28 +09:00
1 parent bc511a18bf
commit edabbe1409
67 files changed
+19095 -289

No files matched your search

+5 -1
View File
@@ -170,7 +170,11 @@ runs:
- name: Install Playwright's dependencies
shell: bash
if: inputs.playwright-install == 'true'
run: yarn playwright install --with-deps $(echo "${{ inputs.playwright-platform }}" | tr ',' ' ')
run: |
if [ "${{ runner.os }}" = "Linux" ]; then
sudo apt-get update
fi
yarn playwright install --with-deps $(echo "${{ inputs.playwright-platform }}" | tr ',' ' ')
working-directory: ${{ steps.workspace-path.outputs.workspace_path }}
env:
PLAYWRIGHT_BROWSERS_PATH: ${{ steps.workspace-path.outputs.workspace_path }}/node_modules/.cache/ms-playwright
File diff suppressed because it is too large. Load diff
+179
View File
@@ -0,0 +1,179 @@
name: Native Playground Backend Checks
on:
workflow_call:
env:
CARGO_ENCODED_RUSTFLAGS: ''
CARGO_INCREMENTAL: '0'
CARGO_NET_GIT_FETCH_WITH_CLI: 'true'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_TERM_COLOR: always
jobs:
server-harness-check:
name: Server Contracts & Test Harness
runs-on: ubuntu-24.04
env:
# One installed toolchain for packages/backend/ and tools/parity-harness alike.
RUSTUP_TOOLCHAIN: '1.98.1'
AFFINE_COMMUNITY_DEFAULT_PUBLIC_KEY: ${{ secrets.AFFINE_COMMUNITY_DEFAULT_PUBLIC_KEY_V2 }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: ./.github/actions/setup-node
with:
electron-install: false
playwright-install: false
full-cache: true
- name: Frozen v0.27.5 server contracts
run: |
node scripts/oracle/extract-v0275-contracts.mjs --check
node scripts/oracle/test-extractor.mjs
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.98.1
with:
components: rustfmt, clippy
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: |
packages/backend -> target
tools/frame-audit -> target
tools/parity-harness -> target
key: server-harness
- name: Pull pinned test images
run: |
docker pull -q docker.io/pgvector/pgvector:pg16@sha256:484e838076e04939d27d3e176e91c86eea96236126023be8d3059761122e579f &
docker pull -q docker.io/library/redis:7-alpine@sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe &
wait
- name: Format, clippy and test packages/backend/ (real PostgreSQL and Redis) and the parity harness
working-directory: packages/backend
run: |
mkdir -p ../../.artifacts/server-harness
status=passed
timings=()
step() {
local name=$1; shift
local start=$(date +%s%3N)
echo "::group::$name"
"$@" || status=failed
echo "::endgroup::"
timings+=(--timing "$name=$(( $(date +%s%3N) - start ))")
}
step fmt cargo fmt --all -- --check
step clippy cargo clippy --locked --workspace --all-targets -- -D warnings
step test cargo test --locked --workspace
audit=(--manifest-path ../../tools/frame-audit/Cargo.toml)
step audit-fmt cargo fmt "${audit[@]}" --all -- --check
step audit-clippy cargo clippy --locked "${audit[@]}" --workspace --all-targets -- -D warnings
step audit-test cargo test --locked "${audit[@]}" --workspace
parity=(--manifest-path ../../tools/parity-harness/Cargo.toml)
step parity-fmt cargo fmt "${parity[@]}" --all -- --check
step parity-clippy cargo clippy --locked "${parity[@]}" --workspace --all-targets -- -D warnings
step parity-test cargo test --locked "${parity[@]}" --workspace
step csf-frame-audit node ../../scripts/ci/check-csf-frame-audit.mjs
cargo run --locked --quiet -p test-db-harness --bin affine-test-env -- \
run-json --out ../../.artifacts/server-harness/run.json --lane server-harness --status "$status" \
--sha "${{ github.sha }}" --run-id "${{ github.run_id }}-${{ github.run_attempt }}" \
--select frame-audit --select csf-frame-audit --select test-db-harness --select parity-harness \
--select server-types --select server-db --select server-spi --select server-domain \
--select server-mail --select server-blob --select server-sync \
--select server-http --select server-worker --select affine-server "${timings[@]}"
cat ../../.artifacts/server-harness/run.json
test -s ../../.artifacts/server-harness/run.json
test -s ../../.artifacts/csf-frame-audit/frames.json
test "$status" = passed
- name: Upload run report
if: always()
uses: actions/upload-artifact@v4
with:
name: server-harness-run
path: |
.artifacts/server-harness/run.json
.artifacts/csf-frame-audit/frames.json
if-no-files-found: ignore
cloud-e2e-rust-server:
name: Cloud E2E (Rust affine-server)
runs-on: ubuntu-24.04
timeout-minutes: 25
env:
RUSTUP_TOOLCHAIN: '1.98.1'
CARGO_ENCODED_RUSTFLAGS: ''
AFFINE_COMMUNITY_DEFAULT_PUBLIC_KEY: ${{ secrets.AFFINE_COMMUNITY_DEFAULT_PUBLIC_KEY_V2 }}
DATABASE_URL: postgresql://affine:affine@127.0.0.1:5432/affine
REDIS_URL: redis://127.0.0.1:6379/0
AFFINE_E2E_RUST_SERVER: '1'
AFFINE_SERVER_EXTERNAL_URL: http://localhost:8080
services:
postgres:
image: docker.io/pgvector/pgvector:pg16@sha256:484e838076e04939d27d3e176e91c86eea96236126023be8d3059761122e579f
env:
POSTGRES_USER: affine
POSTGRES_PASSWORD: affine
POSTGRES_DB: affine
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 5s
--health-timeout 5s
--health-retries 10
redis:
image: docker.io/library/redis:7-alpine@sha256:7f7d30b7fdd09467bac58198a1f166dd69789d348d4fe859cccb20e0cf287fbe
ports:
- 6379:6379
options: >-
--health-cmd "redis-cli ping"
--health-interval 5s
--health-timeout 5s
--health-retries 10
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js and Playwright
uses: ./.github/actions/setup-node
with:
electron-install: false
playwright-install: true
full-cache: true
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.98.1
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/backend -> target
key: server-harness
- name: Build affine-server binary
working-directory: packages/backend
run: cargo build --locked -p affine-server --bin affine-server
- name: Generate Prisma client for test helpers
run: yarn affine @affine/server prisma generate
- name: Run deterministic affine-cloud Playwright E2E against Rust affine-server
run: |
yarn --cwd tests/affine-cloud playwright test \
e2e/login.spec.ts \
e2e/workspace.spec.ts \
e2e/storage.spec.ts \
e2e/collaboration.spec.ts \
e2e/share-page-1.spec.ts \
e2e/share-page-2.spec.ts \
e2e/page-history.spec.ts \
e2e/comments.spec.ts \
e2e/open-in-app.spec.ts
+810
View File
@@ -0,0 +1,810 @@
name: Native Playground Mobile CI
on:
push:
branches:
- 'darksky/np/mobile'
- 'darksky/np/mobile-**'
workflow_dispatch:
inputs:
force_all:
description: Force all native mobile jobs
required: false
type: boolean
default: false
concurrency:
group: np-mobile-${{ github.ref }}
cancel-in-progress: true
env:
CARGO_ENCODED_RUSTFLAGS: ''
CARGO_INCREMENTAL: '0'
CARGO_NET_GIT_FETCH_WITH_CLI: 'true'
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_TERM_COLOR: always
jobs:
changes:
name: Changed Paths
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
web-host-only: ${{ steps.classify.outputs.web_host_only }}
desktop-leaf-only: ${{ steps.classify.outputs.desktop_leaf_only }}
desktop-rs-only: ${{ steps.classify.outputs.desktop_rs_only }}
backend-only: ${{ steps.classify.outputs.backend_only }}
web-wrapper-only: ${{ steps.classify.outputs.web_wrapper_only }}
apple-specific: ${{ steps.base.outputs.force_all == 'true' && 'true' || steps.classify.outputs.apple_specific }}
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
fetch-depth: 50
- name: Resolve the base commit
id: base
env:
BEFORE: ${{ github.event.before }}
PR_BASE_SHA: ${{ github.event.pull_request.base.sha }}
INPUT_FORCE_ALL: ${{ inputs.force_all }}
run: |
set -euo pipefail
force_all=false
sha=""
if [ "${INPUT_FORCE_ALL:-false}" = "true" ]; then
force_all=true
fi
case "${GITHUB_REF:-}" in
refs/heads/darksky/np/mobile|refs/heads/canary|refs/heads/darksky/native-playground)
force_all=true
;;
esac
if [ "$force_all" != "true" ]; then
if [ "${GITHUB_EVENT_NAME:-}" = "pull_request" ] && [ -n "${PR_BASE_SHA:-}" ]; then
if ! git cat-file -e "${PR_BASE_SHA}^{commit}" 2>/dev/null; then
git fetch --no-tags --depth=50 origin "$PR_BASE_SHA" >/dev/null 2>&1 || true
fi
if git cat-file -e "${PR_BASE_SHA}^{commit}" 2>/dev/null; then
sha=$PR_BASE_SHA
fi
else
case "${GITHUB_REF_NAME:-}" in
darksky/np/mobile-*)
git fetch --no-tags --depth=50 origin darksky/np/mobile:refs/remotes/origin/darksky/np/mobile >/dev/null 2>&1 || true
git fetch --no-tags --depth=50 origin canary:refs/remotes/origin/canary >/dev/null 2>&1 || true
if git rev-parse --verify origin/darksky/np/mobile >/dev/null 2>&1; then
sha=$(git merge-base HEAD origin/darksky/np/mobile 2>/dev/null || true)
fi
if [ -z "$sha" ] && git rev-parse --verify origin/canary >/dev/null 2>&1; then
sha=$(git merge-base HEAD origin/canary 2>/dev/null || true)
fi
;;
*)
if [ -n "${BEFORE//0/}" ]; then
if ! git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
git fetch --no-tags --depth=50 origin "$BEFORE" >/dev/null 2>&1 || true
fi
if git cat-file -e "${BEFORE}^{commit}" 2>/dev/null; then
sha=$BEFORE
fi
fi
if [ -z "$sha" ]; then
git fetch --no-tags --depth=50 origin darksky/np/mobile:refs/remotes/origin/darksky/np/mobile >/dev/null 2>&1 || true
git fetch --no-tags --depth=50 origin canary:refs/remotes/origin/canary >/dev/null 2>&1 || true
if git rev-parse --verify origin/darksky/np/mobile >/dev/null 2>&1; then
sha=$(git merge-base HEAD origin/darksky/np/mobile 2>/dev/null || true)
elif git rev-parse --verify origin/canary >/dev/null 2>&1; then
sha=$(git merge-base HEAD origin/canary 2>/dev/null || true)
fi
fi
;;
esac
fi
fi
if [ -z "$sha" ]; then
force_all=true
fi
echo "sha=$sha" >> "$GITHUB_OUTPUT"
echo "force_all=$force_all" >> "$GITHUB_OUTPUT"
- name: Classify web host and Desktop leaf changes
id: classify
env:
BASE: ${{ steps.base.outputs.sha }}
FORCE_ALL: ${{ steps.base.outputs.force_all }}
run: |
node scripts/ci/classify-web-host-only.mjs \
--base "$BASE" \
--force-all "$FORCE_ALL" \
--ref "$GITHUB_REF" \
--event "${GITHUB_EVENT_NAME:-}" \
--github-output "$GITHUB_OUTPUT"
mobile-gates-and-web:
name: L0, Invariants, Web Host & Preview Tests
needs: changes
if: needs.changes.outputs.backend-only != 'true'
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: L0 Tier A static gates
run: |
node scripts/ci/check-l0-tier-a.mjs
node --test scripts/ci/classify-web-host-only.test.mjs
- name: Web mobile thin host and perf comparator tests
working-directory: packages/frontend
run: |
node --test hosts/web/tests/*.test.mjs scripts/check-snapshot-prefixes.test.mjs
node hosts/web/scripts/verify-zero-third-party-js.mjs
node --test perf/compare-n3.test.mjs
- name: Install Linux fontconfig, Mesa Lavapipe Vulkan, and CJK fallback font
if: needs.changes.outputs.desktop-leaf-only != 'true'
run: |
sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends mesa-vulkan-drivers libvulkan1 libfontconfig1-dev libfreetype-dev fonts-wqy-zenhei
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.98.1
with:
components: rustfmt, clippy
targets: wasm32-unknown-unknown
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
key: np-mobile-gates
shared-key: np-mobile-gates
- name: Format check
working-directory: packages/frontend
run: cargo fmt --all -- --check
- name: Clippy check
if: needs.changes.outputs.desktop-leaf-only != 'true'
working-directory: packages/frontend
run: cargo clippy --locked --workspace --all-targets --features harness -- -D warnings
- name: Host and preview tests
if: needs.changes.outputs.desktop-leaf-only != 'true'
working-directory: packages/frontend
run: cargo test --locked -p affine-android-host -p affine-ios-host -p blocksuite-preview --all-features
- name: Mobile tests
if: needs.changes.outputs.desktop-leaf-only != 'true'
working-directory: packages/frontend
run: cargo test --locked -p affine-mobile --all-targets
- name: Mobile harness audit matrix
if: needs.changes.outputs.desktop-leaf-only != 'true'
working-directory: packages/frontend
run: cargo run --locked -p affine-mobile --features harness --bin mobile-harness -- audit-matrix
- name: Mobile harness frame replay
if: needs.changes.outputs.desktop-leaf-only != 'true'
working-directory: packages/frontend
run: cargo run --locked -p affine-mobile --features harness --bin mobile-harness -- fps-replay
- name: Static invariants and link-flag check
working-directory: packages/frontend
run: ./scripts/check-invariants.sh
s1-probes-bench:
name: S1 Release Probes (SQLite, Mermaid, RaTeX, Hayro PDF)
needs: changes
if: >-
needs.changes.outputs.backend-only != 'true' &&
needs.changes.outputs.web-wrapper-only != 'true' &&
needs.changes.outputs.web-host-only != 'true' &&
needs.changes.outputs.desktop-leaf-only != 'true'
runs-on: ubuntu-24.04
timeout-minutes: 30
env:
CARGO_PROFILE_RELEASE_LTO: 'false'
CARGO_PROFILE_RELEASE_CODEGEN_UNITS: '16'
CARGO_PROFILE_RELEASE_DEBUG: '0'
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.98.1
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
key: np-mobile-s1-probes-v2
shared-key: np-mobile-s1-probes-v2
- name: Cache Noto CJK font
id: noto-cjk-cache
uses: actions/cache@v4
with:
path: ~/.cache/affine-s1-fonts
key: s1-noto-cjk-${{ runner.os }}-b76b0433203017ca
- name: Install Noto CJK font for 24-case Mermaid visual probes
run: |
NOTO_SHA256="b76b0433203017ca80401b2ee0dd69350349871c4b19d504c34dbdd80541690a"
NOTO_URL="https://github.com/notofonts/noto-cjk/raw/523d033d6cb47f4a80c58a35753646f5c3608a78/Sans/OTC/NotoSansCJK-Regular.ttc"
FONT_CACHE_DIR="$HOME/.cache/affine-s1-fonts"
FONT_CACHE_FILE="$FONT_CACHE_DIR/NotoSansCJK-Regular.ttc"
mkdir -p "$FONT_CACHE_DIR"
if ! echo "$NOTO_SHA256 $FONT_CACHE_FILE" | sha256sum -c - >/dev/null 2>&1; then
if ! curl -fsSL --retry 3 "$NOTO_URL" -o "$FONT_CACHE_FILE.tmp"; then
rm -f "$FONT_CACHE_FILE.tmp"
sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends 'fonts-noto-cjk=1:20230817+repack1-3*'
FOUND_FONT=$(find /usr/share/fonts -name 'NotoSansCJK-Regular.ttc' -print -quit)
test -s "$FOUND_FONT"
cp -f "$FOUND_FONT" "$FONT_CACHE_FILE.tmp"
fi
mv -f "$FONT_CACHE_FILE.tmp" "$FONT_CACHE_FILE"
fi
echo "$NOTO_SHA256 $FONT_CACHE_FILE" | sha256sum -c -
sudo mkdir -p /usr/share/fonts/opentype/noto
sudo cp -f "$FONT_CACHE_FILE" /usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc
sudo fc-cache -f /usr/share/fonts/opentype/noto
fc-list | grep -qi "Noto Sans CJK"
echo "AFFINE_CJK_FONT=$FONT_CACHE_FILE" >> "$GITHUB_ENV"
- name: Run S1 release probes and validate artifacts
working-directory: packages/frontend
env:
AFFINE_S1_OUT_DIR: /tmp/s1-artifacts
run: |
test -s "$AFFINE_CJK_FONT"
rm -rf /tmp/s1-artifacts
mkdir -p /tmp/s1-artifacts
t0=$(date +%s)
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --release --no-run \
-p affine-store --test s1_sqlite_probe \
-p blocksuite-preview --test s1_probes
echo "Compile S1 release probes duration: $(( $(date +%s) - t0 ))s"
t0=$(date +%s)
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --release \
-p affine-store --test s1_sqlite_probe \
-p blocksuite-preview --test s1_probes \
-- --nocapture
echo "Run S1 release probes duration: $(( $(date +%s) - t0 ))s"
test -s /tmp/s1-artifacts/s1-sqlite-report.json
test -s /tmp/s1-artifacts/s1-probes-report.json
PNG_COUNT=$(find /tmp/s1-artifacts -maxdepth 1 -name 'mermaid-*.png' | wc -l | tr -d ' ')
echo "Generated Mermaid PNG count: $PNG_COUNT"
test "$PNG_COUNT" -eq 24
for theme in light dark; do
for name in flowchart sequence state class pie er gantt gitgraph wrapped-latin wrapped-cjk generic-class frontmatter; do
test -s "/tmp/s1-artifacts/mermaid-${theme}-${name}.png"
done
done
- name: Upload S1 probes report and rendered PNG artifacts
uses: actions/upload-artifact@v4
with:
name: s1-probes-artifacts
path: /tmp/s1-artifacts
if-no-files-found: error
preview-wasm-workers:
name: Preview Wasm Workers (4 Independent Targets)
needs: changes
if: >-
needs.changes.outputs.backend-only != 'true' &&
needs.changes.outputs.desktop-rs-only != 'true'
runs-on: ubuntu-24.04
timeout-minutes: 20
defaults:
run:
working-directory: packages/frontend
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: 22
- name: Install Rust toolchain
uses: dtolnay/rust-toolchain@1.98.1
with:
targets: wasm32-unknown-unknown
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
key: np-mobile-preview-wasm
shared-key: np-mobile-preview-wasm
- name: Install wasm-bindgen CLI and Binaryen wasm-opt
run: |
WBG_VERSION=$(awk '/^name = "wasm-bindgen"$/{getline; gsub(/"/, "", $3); print $3; exit}' Cargo.lock)
URL="https://github.com/wasm-bindgen/wasm-bindgen/releases/download/${WBG_VERSION}/wasm-bindgen-${WBG_VERSION}-x86_64-unknown-linux-musl.tar.gz"
if curl -fsSL "$URL" | tar -xz -C /tmp; then
sudo install -m 0755 "/tmp/wasm-bindgen-${WBG_VERSION}-x86_64-unknown-linux-musl/wasm-bindgen" /usr/local/bin/wasm-bindgen
else
cargo install --locked wasm-bindgen-cli --version "$WBG_VERSION"
fi
wasm-bindgen --version
BINARYEN_VERSION="version_123"
BINARYEN_SHA256="e959f2170af4c20c552e9de3a0253704d6a9d2766e8fdb88e4d6ac4bae9388fe"
curl -fsSL "https://github.com/WebAssembly/binaryen/releases/download/${BINARYEN_VERSION}/binaryen-${BINARYEN_VERSION}-x86_64-linux.tar.gz" \
-o /tmp/binaryen.tar.gz
echo "${BINARYEN_SHA256} /tmp/binaryen.tar.gz" | sha256sum -c -
tar -xzf /tmp/binaryen.tar.gz -C /tmp
rm -f /tmp/binaryen.tar.gz
sudo install -m 0755 "/tmp/binaryen-${BINARYEN_VERSION}/bin/wasm-opt" /usr/local/bin/wasm-opt
wasm-opt --version
- name: Build and verify main playground Wasm bundle and 4 preview Wasm workers
run: |
mkdir -p /tmp/preview-wasm/pkg
REPO_ROOT="$(cd ../.. && pwd)"
CARGO_HOME_DIR="${CARGO_HOME:-$HOME/.cargo}"
WASM_RUSTFLAGS="$(printf '%s\037%s\037%s' "--remap-path-prefix=${REPO_ROOT}=/src" "--remap-path-prefix=${CARGO_HOME_DIR}=/cargo" "-Ctarget-feature=+simd128")"
work_dir=$(mktemp -d)
set -m
trap 'exit 1' USR1
trap 'for pid in $(jobs -pr); do kill -- "-$pid" 2>/dev/null || true; done; wait || true; rm -rf "$work_dir"' EXIT
kinds=(mermaid math typst pdf)
pids=()
optimize_wasm() {
wasm-opt -Oz --strip-debug --strip-producers \
--enable-bulk-memory \
--enable-nontrapping-float-to-int \
--enable-sign-ext \
--enable-mutable-globals \
--enable-simd "$1" -o "$2"
}
postprocess() (
local kind="$1"
shift
trap 'rc=$?; if [ "$rc" -ne 0 ]; then
printf "Wasm post-processing for %s failed (status %s)\n" "$kind" "$rc" >&3
cat "$work_dir/${kind}.log" >&3
kill -USR1 "$$"
fi' EXIT
"$@"
)
# Wait on Cargo so a failed optimizer can interrupt the build.
for kind in "${kinds[@]}"; do
CARGO_ENCODED_RUSTFLAGS="$WASM_RUSTFLAGS" cargo rustc --locked --target wasm32-unknown-unknown --profile wasm-worker-size -p blocksuite-preview --lib --crate-type cdylib --no-default-features --features "${kind},wasm-worker" &
wait "$!"
cp target/wasm32-unknown-unknown/wasm-worker-size/blocksuite_preview.wasm "$work_dir/${kind}.wasm"
postprocess "$kind" optimize_wasm "$work_dir/${kind}.wasm" "/tmp/preview-wasm/${kind}.wasm" 3>&2 > "$work_dir/${kind}.log" 2>&1 &
pids+=("$!")
done
CARGO_ENCODED_RUSTFLAGS="$WASM_RUSTFLAGS" cargo build --locked --profile wasm-release-size -p playground --lib --target wasm32-unknown-unknown &
wait "$!"
bindgen_playground() {
wasm-bindgen --target web --out-dir /tmp/preview-wasm/pkg target/wasm32-unknown-unknown/wasm-release-size/playground.wasm
optimize_wasm /tmp/preview-wasm/pkg/playground_bg.wasm /tmp/preview-wasm/pkg/playground_bg.opt.wasm
mv /tmp/preview-wasm/pkg/playground_bg.opt.wasm /tmp/preview-wasm/pkg/playground_bg.wasm
}
postprocess playground bindgen_playground 3>&2 > "$work_dir/playground.log" 2>&1 &
pids+=("$!")
kinds+=(playground)
for i in "${!pids[@]}"; do
wait "${pids[$i]}"
kind=${kinds[$i]}
echo "=== $kind Wasm post-processing ==="
cat "$work_dir/${kind}.log"
done
for kind in mermaid math typst pdf; do
test -s "/tmp/preview-wasm/${kind}.wasm"
done
test -s /tmp/preview-wasm/pkg/playground_bg.wasm
{
echo "### 5-Wasm Bundle Sizes (post wasm-opt -Oz)"
echo "| Artifact | Raw (bytes) | Raw (KB) | Gzip (bytes) | Gzip (KB) |"
echo "|---|---:|---:|---:|---:|"
for f in /tmp/preview-wasm/pkg/playground_bg.wasm /tmp/preview-wasm/mermaid.wasm /tmp/preview-wasm/math.wasm /tmp/preview-wasm/typst.wasm /tmp/preview-wasm/pdf.wasm; do
raw_b=$(wc -c < "$f" | tr -d ' ')
gz_b=$(gzip -c -9 "$f" | wc -c | tr -d ' ')
raw_kb=$(awk "BEGIN { printf \"%.1f\", $raw_b / 1024 }")
gz_kb=$(awk "BEGIN { printf \"%.1f\", $gz_b / 1024 }")
echo "| \`$(basename "$f")\` | ${raw_b} | ${raw_kb} KB | ${gz_b} | ${gz_kb} KB |"
done
} | tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}"
node hosts/web/scripts/stage-preview-workers.mjs /tmp/preview-wasm dev-local
node hosts/web/scripts/verify-preview-workers-e2e.mjs
- name: Warm Chromium binary into OS page cache
run: |
CHROME_WARM_BIN=${CHROME_PATH:-${CHROME_BIN:-}}
if [ -z "$CHROME_WARM_BIN" ]; then
wrapper=
for bin in /usr/bin/google-chrome-stable /usr/bin/google-chrome /usr/bin/chromium /usr/bin/chromium-browser; do
[ -e "$bin" ] || continue
if [ "$(head -c 2 "$bin" 2>/dev/null)" = '#!' ]; then
wrapper=${wrapper:-$bin}
else
CHROME_WARM_BIN=$bin
break
fi
done
if [ -z "$CHROME_WARM_BIN" ] && [ -d "$HOME/.cache/ms-playwright" ]; then
CHROME_WARM_BIN=$(find "$HOME/.cache/ms-playwright" -name chrome -type f -print -quit)
fi
CHROME_WARM_BIN=${CHROME_WARM_BIN:-$wrapper}
fi
if [ -z "$CHROME_WARM_BIN" ] || [ ! -e "$CHROME_WARM_BIN" ]; then
echo "warning: skipping Chromium warm-up (no binary found)" >&2
exit 0
fi
WARM_PROFILE=$(mktemp -d "${TMPDIR:-/tmp}/np-chrome-warm.XXXXXX")
trap 'rm -rf "$WARM_PROFILE"' EXIT
status=0
timeout --kill-after=2s 20s "$CHROME_WARM_BIN" --headless=new --no-sandbox --disable-gpu --disable-dbus --disable-dev-shm-usage --user-data-dir="$WARM_PROFILE" --dump-dom about:blank >/dev/null || status=$?
rm -rf "$WARM_PROFILE"
trap - EXIT
if [ "$status" -ne 0 ]; then
echo "warning: Chromium warm-up exited with status $status; continuing to test harness" >&2
fi
- name: Verify real-browser IndexedDB storage and V1 Yjs extraction
run: node hosts/web/scripts/verify-idb-real-browser.mjs
- name: Verify real-browser S3-Web GPU recovery, selection menu, and lazy hayro PDF worker
run: node hosts/web/scripts/verify-s3-web-real-browser.mjs
- name: Verify real-browser Canary dual-shell staging, zero-empty-IDB guard, and crash fallback CRDT round-trip
run: node hosts/web/scripts/verify-canary-dual-shell-browser.mjs /tmp/preview-wasm
android-host:
name: Android Thin Host (NDK .so Link & kotlinc)
needs: changes
if: >-
needs.changes.outputs.backend-only != 'true' &&
needs.changes.outputs.web-wrapper-only != 'true' &&
needs.changes.outputs.web-host-only != 'true' &&
needs.changes.outputs.desktop-leaf-only != 'true'
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache Kotlin compiler archive
uses: actions/cache@v4
with:
path: ${{ runner.temp }}/kotlin-compiler-2.1.20.zip
key: kotlinc-2.1.20-v1
- name: Install Kotlin compiler
run: |
archive="$RUNNER_TEMP/kotlin-compiler-2.1.20.zip"
checksum="a118197b0de55ffab2bc8d5cd03a5e39033cfb53383d6931bc761dec0784891a $archive"
if [ ! -f "$archive" ] || ! printf '%s\n' "$checksum" | sha256sum --check --status; then
curl -fsSL https://github.com/JetBrains/kotlin/releases/download/v2.1.20/kotlin-compiler-2.1.20.zip -o "$archive"
printf '%s\n' "$checksum" | sha256sum --check
fi
unzip -q "$archive" -d "$RUNNER_TEMP"
"$RUNNER_TEMP/kotlinc/bin/kotlinc" -version
echo "$RUNNER_TEMP/kotlinc/bin" >> "$GITHUB_PATH"
- name: Install Rust toolchain with Android target
uses: dtolnay/rust-toolchain@1.98.1
with:
targets: aarch64-linux-android
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
key: np-mobile-android-host
shared-key: np-mobile-android-host
- name: Install Linux fontconfig and freetype headers for host tests
run: |
sudo rm -f /etc/apt/sources.list.d/microsoft-prod.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends pkg-config libfontconfig1-dev libfreetype-dev
- name: Link Android NDK arm64-v8a .so binary
working-directory: packages/frontend
run: |
NDK_BIN="$ANDROID_NDK_LATEST_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin"
export CARGO_TARGET_AARCH64_LINUX_ANDROID_LINKER="$NDK_BIN/aarch64-linux-android24-clang"
export CC_aarch64_linux_android="$NDK_BIN/aarch64-linux-android24-clang"
export AR_aarch64_linux_android="$NDK_BIN/llvm-ar"
cargo build --locked -p affine-android-host --target aarch64-linux-android
SRC="target/aarch64-linux-android/debug/libaffine_android_host.so"
test -s "$SRC"
DST="/tmp/libaffine_android_host_aarch64-linux-android.stripped.so"
cp "$SRC" "$DST"
"$NDK_BIN/llvm-strip" --strip-unneeded "$DST"
BYTES=$(stat -c '%s' "$DST")
MAX_BYTES=165000000
echo "Stripped aarch64-linux-android libaffine_android_host.so bytes: ${BYTES} (max ${MAX_BYTES})"
test "$BYTES" -le "$MAX_BYTES"
- name: Compile Android thin host Kotlin sources with kotlinc and run real JNI parity check
run: |
ANDROID_JAR=$(ls -1 "$ANDROID_HOME"/platforms/android-*/android.jar | sort -V | tail -n 1)
echo "Using Android SDK jar: $ANDROID_JAR"
cargo build --locked --manifest-path packages/frontend/Cargo.toml -p affine-android-host --features host-jni
test -s packages/frontend/target/debug/libaffine_android_host.so
mkdir -p /tmp/affine-android-kotlin
kotlinc -classpath "$ANDROID_JAR" \
-d /tmp/affine-android-kotlin \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/MainActivity.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/LegacyLocalStorageProbe.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/AuthDataStore.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareIntentBridge.kt \
packages/frontend/hosts/android/kotlin/app/affine/pro/host/ShareReceiverActivity.kt \
packages/frontend/hosts/android/tests/ImeHostParityCheck.kt
test -s /tmp/affine-android-kotlin/app/affine/pro/host/MainActivity.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/ShareReceiverActivity.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AffineImeController.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AffineInputConnection.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/LegacyLocalStorageProbe.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AndroidBootstrapCoordinator.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AuthSessionStore.class
test -s /tmp/affine-android-kotlin/app/affine/pro/host/AuthTokenCipher.class
kotlin -J-Djava.library.path="$PWD/packages/frontend/target/debug" \
-cp "/tmp/affine-android-kotlin:$ANDROID_JAR" \
ImeHostParityCheckKt
./packages/frontend/hosts/android/scripts/package-debug-apk.sh /tmp/android-apk
rm -rf /tmp/android-apk/work
sha256sum /tmp/android-apk/AffineAndroidHost-debug.apk | tee /tmp/android-apk/AffineAndroidHost-debug.apk.sha256
- name: Upload signed Android debug APK artifact
uses: actions/upload-artifact@v4
with:
name: android-debug-apk
path: |
/tmp/android-apk/AffineAndroidHost-debug.apk
/tmp/android-apk/AffineAndroidHost-debug.apk.sha256
if-no-files-found: error
ios-device-check:
name: iOS Device SDK Check (ui & affine-ios-host)
needs: changes
if: >-
needs.changes.outputs.backend-only != 'true' &&
needs.changes.outputs.web-wrapper-only != 'true' &&
needs.changes.outputs.web-host-only != 'true' &&
needs.changes.outputs.desktop-leaf-only != 'true' &&
needs.changes.outputs.apple-specific == 'true'
runs-on: macos-15
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain with iOS device target
uses: dtolnay/rust-toolchain@1.98.1
with:
targets: aarch64-apple-ios
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
shared-key: ios-device-check
key: np-mobile-ios-device-v1
- name: Check affine-ios-host and ui for iOS device target
working-directory: packages/frontend
env:
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_INCREMENTAL: '0'
run: cargo check --locked -p ui -p affine-ios-host --target aarch64-apple-ios
ios-host:
name: iOS Thin Host (Rust staticlib & Swift Simulator Link)
needs: changes
if: >-
needs.changes.outputs.backend-only != 'true' &&
needs.changes.outputs.web-wrapper-only != 'true' &&
needs.changes.outputs.web-host-only != 'true' &&
needs.changes.outputs.desktop-leaf-only != 'true' &&
needs.changes.outputs.apple-specific == 'true'
runs-on: macos-15
timeout-minutes: 20
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Install Rust toolchain with iOS Simulator target
uses: dtolnay/rust-toolchain@1.98.1
with:
targets: aarch64-apple-ios-sim
- name: Cache Cargo artifacts
uses: Swatinem/rust-cache@v2
with:
workspaces: packages/frontend -> target
shared-key: ios-sim-host
key: np-mobile-ios-host-v5
- name: Build the iOS staticlib and select a Simulator
working-directory: packages/frontend
env:
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_INCREMENTAL: '0'
shell: bash
run: bash hosts/ios/scripts/check-sim-host.sh
- name: Link zero-CocoaPods Swift iOS host and run 7/7 Simulator smoke tests
shell: bash
run: |
run_timed() {
local label="$1" started=$SECONDS rc=0
shift
echo "$(date -u +%FT%TZ) Start $label"
"$@" || rc=$?
echo "$(date -u +%FT%TZ) End $label after $(( SECONDS - started ))s (status $rc)"
return "$rc"
}
smoke_dir=$(mktemp -d "${RUNNER_TEMP:-/tmp}/ios-host.XXXXXXXX")
trap 'rm -rf "$smoke_dir"' EXIT
SDK=$(xcrun --sdk iphonesimulator --show-sdk-path)
SMOKE_SOURCES=()
for f in packages/frontend/hosts/ios/Sources/*.swift; do
case "$(basename "$f")" in
AppDelegate.swift|SceneDelegate.swift|main.swift) continue ;;
esac
SMOKE_SOURCES+=("$f")
done
swift_flags=(
-emit-executable
-sdk "$SDK"
-target arm64-apple-ios16.0-simulator
-import-objc-header packages/frontend/hosts/ios/include/affine_mobile_host.h
-L packages/frontend/target/aarch64-apple-ios-sim/debug
-laffine_ios_host
-framework UIKit
-framework QuartzCore
-framework Metal
-framework WebKit
-framework PDFKit
-framework CoreText
-framework CoreGraphics
-framework CoreVideo
-framework CoreFoundation
-framework Foundation
-framework UniformTypeIdentifiers
-framework StoreKit
-framework AuthenticationServices
)
prepare_simulator() {
local boot_output boot_rc=0
case "$SIM_STATE" in
Shutdown)
boot_output=$(xcrun simctl boot "$SIM_UDID" 2>&1) || boot_rc=$?
if [ "$boot_rc" -ne 0 ]; then
printf '%s\n' "$boot_output" >&2
if ! grep -Exq 'Unable to boot device in current state: (Booted|Booting)' <<< "$boot_output"; then
return "$boot_rc"
fi
fi
;;
Booted|Booting) ;;
*) echo "Unexpected Simulator state $SIM_STATE for $SIM_UDID" >&2; return 1 ;;
esac
xcrun simctl bootstatus "$SIM_UDID" -b || return $?
echo "$(date -u +%FT%TZ) Simulator ready: $SIM_UDID"
}
# Each task reports when it finishes so failures appear in completion order.
mkfifo "$smoke_dir/completed"
exec 3<>"$smoke_dir/completed"
run_parallel() {
set +m
local label="$1" started=$SECONDS rc=0
run_timed "$@" > "$smoke_dir/$label.log" 2>&1 || rc=$?
printf '%s %s\n' "$label" "$(( SECONDS - started ))" >&3
return "$rc"
}
# Give each task a process group so cancellation reaches its child processes.
set -m
run_parallel AffineIosHost swiftc "${swift_flags[@]}" \
-o "$smoke_dir/AffineIosHost" packages/frontend/hosts/ios/Sources/*.swift &
host_pid=$!
run_parallel IosHostS3SmokeTest swiftc "${swift_flags[@]}" \
-o "$smoke_dir/IosHostS3SmokeTest" "${SMOKE_SOURCES[@]}" \
packages/frontend/hosts/ios/tests/IosHostS3SmokeTest.swift &
smoke_link_pid=$!
run_parallel Simulator prepare_simulator &
simulator_pid=$!
set +m
parallel_rc=0
swift_s=0
for _ in 1 2 3; do
read -r label elapsed <&3
case "$label" in
AffineIosHost) pid=$host_pid ;;
IosHostS3SmokeTest) pid=$smoke_link_pid ;;
Simulator)
pid=$simulator_pid
echo "sim_boot_s=$elapsed"
;;
esac
if [[ "$label" != Simulator && "$elapsed" -gt "$swift_s" ]]; then
swift_s=$elapsed
fi
rc=0
wait "$pid" || rc=$?
cat "$smoke_dir/$label.log"
if [ "$rc" -ne 0 ]; then
echo "::error::$label failed with status $rc"
parallel_rc=$rc
break
fi
done
exec 3>&-
if [ "$parallel_rc" -ne 0 ]; then
task_groups=("-$host_pid" "-$smoke_link_pid" "-$simulator_pid")
kill -TERM -- "${task_groups[@]}" 2>/dev/null || true
sleep 0.1
kill -KILL -- "${task_groups[@]}" 2>/dev/null || true
wait "$host_pid" "$smoke_link_pid" "$simulator_pid" || true
exit "$parallel_rc"
fi
echo "swift_s=$swift_s"
test -s "$smoke_dir/AffineIosHost"
test -s "$smoke_dir/IosHostS3SmokeTest"
echo "Running iOS smoke tests on Simulator UDID: $SIM_UDID"
smoke_started=$SECONDS
if run_timed "Seven iOS smoke tests" env SIMCTL_CHILD_NSUnbufferedIO=YES \
xcrun simctl spawn "$SIM_UDID" "$smoke_dir/IosHostS3SmokeTest"; then
echo "smoke_s=$(( SECONDS - smoke_started ))"
echo "$(date -u +%FT%TZ) Seven iOS smoke tests passed"
else
rc=$?
echo "smoke_s=$(( SECONDS - smoke_started ))"
echo "::warning::IosHostS3SmokeTest exited with status $rc; collecting last 2m Simulator WebKit logs" >&2
perl -e 'alarm 15; exec @ARGV' -- xcrun simctl spawn "$SIM_UDID" log show \
--last 2m \
--style compact \
--predicate 'subsystem BEGINSWITH "com.apple.WebKit" OR process CONTAINS "WebContent" OR process CONTAINS "Networking" OR process CONTAINS "IosHostS3SmokeTest"' \
2>&1 | tail -n 200 >&2 || true
exit "$rc"
fi
- name: Shutdown iOS Simulator
if: always() && env.SIM_UDID != ''
timeout-minutes: 1
continue-on-error: true
run: |
echo "$(date -u +%FT%TZ) Shut down Simulator $SIM_UDID"
xcrun simctl shutdown "$SIM_UDID"
echo "$(date -u +%FT%TZ) Simulator shut down"
- name: Remove iOS host archives before cache save
working-directory: packages/frontend/target/aarch64-apple-ios-sim/debug
run: rm -f libaffine_ios_host.a deps/libaffine_ios_host*
+73
View File
@@ -0,0 +1,73 @@
name: Native Playground Web Build
# Production bundles of the web, mobile web and admin apps, without the
# Electron binary, Playwright browsers or Sentry CLI downloads.
# native-playground.yml calls this only when frontend sources change.
on:
workflow_call:
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
SENTRYCLI_SKIP_DOWNLOAD: '1'
jobs:
build:
name: Build ${{ matrix.package }}
runs-on: ubuntu-24.04
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
package:
- '@affine/web'
- '@affine/mobile'
- '@affine/admin'
env:
BUILD_TYPE: canary
NODE_OPTIONS: --max-old-space-size=8192
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: ./.github/actions/setup-node
with:
electron-install: false
playwright-install: false
full-cache: true
- name: Run i18n codegen
run: |
yarn affine @affine/i18n build
git checkout packages/frontend/i18n/src/i18n-completenesses.json
- name: Build ${{ matrix.package }}
# The bundle itself must stay within eight minutes.
timeout-minutes: 8
run: yarn affine ${{ matrix.package }} build
- name: Check the bundle entry exists
# `affine bundle` can report an internal error and still exit 0.
run: |
case '${{ matrix.package }}' in
'@affine/web') dist=packages/frontend/apps/web/dist ;;
'@affine/mobile')
dist=packages/frontend/apps/mobile/dist
test -s "$dist/assets-manifest.json"
node -e '
const fs = require("node:fs");
const path = require("node:path");
const dist = process.argv[1];
const m = JSON.parse(fs.readFileSync(path.join(dist, "assets-manifest.json"), "utf8"));
if (!Array.isArray(m.js) || m.js.length === 0) throw new Error("Empty @affine/mobile js manifest");
for (const rel of [...(m.js || []), ...(m.css || [])]) {
const p = path.join(dist, String(rel).replace(/^\/+/, ""));
if (!fs.existsSync(p)) throw new Error("Missing @affine/mobile asset: " + p);
}
' "$dist"
;;
'@affine/admin') dist=packages/frontend/admin/dist ;;
esac
test -s "$dist/index.html"
du -sh "$dist"
+86
View File
@@ -0,0 +1,86 @@
name: Native Playground Web Fast Checks
on:
workflow_call:
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: '1'
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1'
SENTRYCLI_SKIP_DOWNLOAD: '1'
jobs:
lint:
name: Web Lint
runs-on: ubuntu-24.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: ./.github/actions/setup-node
with:
electron-install: false
full-cache: true
- name: Run oxlint
run: yarn lint:ox
- name: Run i18n codegen
run: |
yarn affine @affine/i18n build
git checkout packages/frontend/i18n/src/i18n-completenesses.json
- name: Run oxfmt
# setup-node may rewrite .yarnrc.yml (nmMode); format-check the tracked file.
run: |
git checkout .yarnrc.yml
yarn lint:format
typecheck:
name: Web Typecheck
runs-on: ubuntu-24.04
env:
NODE_OPTIONS: --max-old-space-size=12288
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: ./.github/actions/setup-node
with:
electron-install: false
full-cache: true
- name: Run i18n codegen
run: |
yarn affine @affine/i18n build
git checkout packages/frontend/i18n/src/i18n-completenesses.json
- name: Run type check
run: yarn typecheck
unit-test:
name: Web Unit Test (Node projects)
runs-on: ubuntu-24.04
env:
DISTRIBUTION: web
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: ./.github/actions/setup-node
with:
electron-install: false
playwright-install: false
full-cache: true
- name: Run Vitest Node projects
# Browser-mode, Electron and Rust-binary projects need downloads or
# builds this lane skips; build-test.yml and js-room-coop run them.
run: |
set -euo pipefail
raw="$(node scripts/ci/vitest-node-projects.mjs)"
read -r -a projects <<< "$raw"
test "${#projects[@]}" -gt 0
yarn vitest run "${projects[@]}"
+8
View File
@@ -104,3 +104,11 @@ storageState.json
/.playwright-browsers/
**/.vitest-attachments/
/blocksuite/framework/std/src/__tests__/gfx/__screenshots__/
/packages/frontend/target/
/packages/frontend/artifacts/
/packages/frontend/hosts/web/assets/*.wasm
/packages/frontend/hosts/web/assets/fonts/*.ttf
/blocksuite/crates/playground/web/assets/
/blocksuite/crates/playground/web/pkg/
/blocksuite/crates/playground/web/wasm-scalar-rpc.js
/blocksuite/crates/playground/web/workers/
+5 -1
View File
@@ -6,5 +6,9 @@
"tabWidth": 2,
"arrowParens": "avoid",
"sortPackageJson": false,
"ignorePatterns": ["**/*.toml"]
"ignorePatterns": [
"**/*.toml",
"packages/frontend/artifacts/**",
"blocksuite/crates/playground/web/pkg/**"
]
}
+6
View File
@@ -43,6 +43,7 @@
".vscode",
".context",
".codex",
".agents",
".yarnrc.yml",
".docker",
"**/.storybook",
@@ -72,6 +73,11 @@
"tests/blocksuite/snapshots",
"tests/oracle-contracts/**",
"packages/backend/server-types/assets/*.license.json",
"packages/ui/**",
"packages/frontend/perf/**",
"packages/frontend/scripts/**",
"packages/frontend/artifacts/**",
"blocksuite/crates/**",
"blocksuite/docs/api/**",
"blocksuite/docs-site/.vitepress/.temp/**",
"blocksuite/docs-site/api/**",
+6 -1
View File
@@ -42,10 +42,15 @@ packages/frontend/apps/ios/App/**
tests/blocksuite/snapshots
tests/oracle-contracts/**
packages/backend/server-types/assets/*.license.json
packages/backend/native/src/*.license.json
packages/ui/**
packages/frontend/perf/**
packages/frontend/scripts/**
packages/frontend/artifacts/**
blocksuite/crates/**
blocksuite/docs/api/**
blocksuite/docs-site/.vitepress/.temp/**
blocksuite/docs-site/api/**
packages/frontend/admin/src/config.json
**/test-docs.json
**/test-blocks.json
packages/backend/native/src/*.license.json
+5 -3
View File
@@ -1,6 +1,6 @@
# Working on AFFiNE Native Playground (for agents)
These rules apply at the repository root on the `darksky/native-playground` branch and on topic branches under `darksky/np/**`. Subdirectory `AGENTS.md` files (for example `packages/backend/AGENTS.md`) give narrower rules beside the code they govern.
These rules apply at the repository root on the `darksky/native-playground` branch and on topic branches under `darksky/np/**`. Subdirectory `AGENTS.md` files (for example `packages/frontend/AGENTS.md`, `packages/ui/AGENTS.md`, and `blocksuite/crates/AGENTS.md`) give narrower rules beside the code they govern.
## Branch and CI workflow
@@ -12,11 +12,13 @@ These rules apply at the repository root on the `darksky/native-playground` bran
- **Performance regression gate:** A CI benchmark metric can regress by **more than 10%** against the rolling `N-3` baseline. In that case, the performance guardian reviews the change before it lands.
- **Cargo rustflags isolation:** Root `.cargo/config.toml` adds NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`). Cargo joins these flags into nested workspaces. Always set `CARGO_ENCODED_RUSTFLAGS=""` when you build and test the standalone `packages/backend/` workspace.
- **Cargo rustflags isolation:** Root `.cargo/config.toml` adds NAPI linker flags (`-all_load`, `-undefined dynamic_lookup`, `-z nodelete`). Cargo joins these flags into nested workspaces. Always set `CARGO_ENCODED_RUSTFLAGS=""` when you build and test `packages/frontend/` and the standalone `packages/backend/` workspace.
- **Static gates:** `node scripts/ci/check-l0-tier-a.mjs` has no dependencies and runs in under a second. It guards the `packages/backend/` layering and hygiene. It also guards workflow references and the `waitForTimeout` / `.skip` ratchet in `scripts/ci/l0-ratchet.json`. The ratchet counts can only go down. To lower the ceiling, run the script with `--update-baseline`.
- **Fast lanes:** `native-playground.yml` always runs the L0 Tier-A check. It also always runs the frozen server contract checks (`scripts/oracle`), the `packages/backend/` checks and the `tools/parity-harness` checks.
- **Fast lanes:** `native-playground.yml` always runs the zero-dependency L0 Tier-A check (`scripts/ci/check-l0-tier-a.mjs`) in `changes`. It runs the frozen server contract checks (`scripts/oracle`), `packages/backend/`, `tools/parity-harness`, zero-backend CSF geometry audit (`scripts/ci/check-csf-frame-audit.mjs`), and `cloud-e2e-rust-server` lanes only when backend, contract, harness, or cloud test sources change (`backend`), and it runs the Rust UI and editor lanes (`lint-and-wasm`, `headless-linux-and-perf`, `macos-headless`, and `js-room-coop`) only when client, UI, or BlockSuite sources change (`native-ui`). Topic branches under `darksky/np/mobile-*` compute changed paths against `origin/darksky/np/mobile`. Topic branches run Apple jobs only when Apple paths, Cargo or CI files, or Apple `cfg` lines change. Trunk pushes, pull requests, and manual runs run all Apple checks.
- **Web lanes:** `native-playground.yml` calls `np-web-fast.yml` only when web sources change. That lane runs lint, typecheck and the Node-only Vitest projects. It calls `np-web-build.yml` only when frontend sources change. That lane builds the production bundles of `@affine/web`, `@affine/mobile` and `@affine/admin`. It downloads no Electron or Playwright binaries, and each bundle has eight minutes.
## Pull requests and evidence
+49
View File
@@ -0,0 +1,49 @@
# Working in `packages/frontend/` (for agents)
`packages/frontend/` holds the client Rust Cargo workspace (`Cargo.toml` and `Cargo.lock`) alongside legacy TypeScript frontend packages.
It uses `resolver = "3"`, edition 2024, and its own `rust-toolchain.toml` (`1.98.1` with `wasm32-unknown-unknown`) and `rustfmt.toml`.
## Workspace boundaries and four-domain guards
- `packages/frontend/Cargo.toml` lists every client member crate explicitly (`../ui/tokens`, `../ui/ui`, `../ui/kit`, `../common/store`, `legacy-import`, `client`, `mobile`, `desktop`, `../../blocksuite/crates/doc`, `../../blocksuite/crates/editor`, `../../blocksuite/crates/playground`, `../../blocksuite/crates/preview`, `hosts/android`, and `hosts/ios`).
Never use directory wildcards that can scan asset directories.
- `packages/frontend/Cargo.toml` excludes `native` and `mobile-native`.
Those legacy crates remain members of the root `Cargo.toml` workspace.
- Legacy directories (`native/`, `mobile-native/`, and `apps/`) carry a `1.97.1` `rust-toolchain.toml` file that matches the repository root byte-for-byte.
`native/` and `mobile-native/` also carry a `rustfmt.toml` file that matches the repository root byte-for-byte.
- Client trees (`packages/frontend/`, `packages/ui/`, `blocksuite/crates/`, and `packages/common/store/`) share byte-identical `1.98.1` `rust-toolchain.toml` and client `rustfmt.toml` files.
- `scripts/check-invariants.sh` discovers client workspace members from `cargo metadata --locked --no-deps`, enforces four-domain acyclic dependencies (zero reverse edges), checks domain isolation, wall-clock isolation, zero tester branches, module structure, LOC ceilings, toolchain/rustfmt alignment, `workspace_root` resolution, `rustup show active-toolchain` for legacy (`1.97.1`) and client (`1.98.1`) directories, workflow YAML validity, `CARGO_ENCODED_RUSTFLAGS=""` link-flag isolation, and that every harness snapshot ID prefix in `scripts/check-snapshot-prefixes.mjs` still occurs in non-test Rust sources under `blocksuite/crates/*/src` and `packages/frontend/desktop/src`.
- See `packages/ui/AGENTS.md`, `blocksuite/crates/AGENTS.md`, and `packages/common/store/AGENTS.md` for domain-specific invariants.
### Performance guardrail and theme/style oracle
- **`perf/` (`schema.json`, `accepted.json`, `compare-n3.mjs`, `compare-n3.test.mjs`)**: Zero-dependency rolling `N-3` CI comparator with strict schema validation and rerun history anchoring (`--run-id` `created_at` cutoff + pagination). Deterministic byte sizes (`artifacts_bytes.*`), work counters (non-`_ms` `benchmarks.*`), and unacknowledged `DROPPED` / `--require-n3` `BOOTSTRAP` metrics are hard-gated (`--fail-on-regression` exits `1`); shared-runner wall-clock timings (`benchmarks.*_ms` at `> 10%`, `ci_wall_ms.*` at `> 10%` and `> 15_000 ms`) are report-only `ADVISORY_SLOWDOWN`. Intentional changes are acknowledged in `packages/frontend/perf/accepted.json` via `action: "ceiling"` (`{ metric, accepted_value, reason }`), `action: "bootstrap"` (newly added metrics under `--require-n3`), or `action: "drop"` (retired metrics), with report-only `stale_acceptances` once the rolling `N-3` baseline catches up. Unmeasured sub-keys are omitted or `null` (never padded with synthetic `0`s).
## Build & verification commands
Always clear inherited root rustflags:
```sh
CARGO_ENCODED_RUSTFLAGS="" cargo fmt --all -- --check
CARGO_ENCODED_RUSTFLAGS="" cargo clippy --locked --workspace --all-targets --features harness -- -D warnings
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p ui-tokens -p ui -p ui-kit -p blocksuite-editor -p playground --target wasm32-unknown-unknown
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown
CARGO_ENCODED_RUSTFLAGS="" cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace
CARGO_ENCODED_RUSTFLAGS="" cargo test --locked --workspace --features harness
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --theme dark --mode page --out frame.png --snapshot frame.json
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- probes
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- bench --json perf-metrics.json
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-surface-sample --theme light --out surface-light.png --snapshot surface-light.json
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render-editor artifacts/editor
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- render --state slash_menu_open --out slash.png --snapshot slash.json
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- audit-states
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- fps-check
CARGO_ENCODED_RUSTFLAGS="" cargo run --locked --bin bs-harness --features harness -- record-demo artifacts/demo
./scripts/check-invariants.sh
node --test perf/compare-n3.test.mjs
node ../ui/tokens/extract-tokens.mjs --check
rustc --edition 2024 --test -D warnings ../ui/tokens/tokens.rs -o /tmp/tokens_test && /tmp/tokens_test
rustc --edition 2024 --test -D warnings ../ui/tokens/icons.rs -o /tmp/icons_test && /tmp/icons_test
rm -f /tmp/tokens_test /tmp/icons_test
```
+1
View File
@@ -0,0 +1 @@
@AGENTS.md
+8340
View File
File diff suppressed because it is too large. Load diff
+374
View File
@@ -0,0 +1,374 @@
[workspace]
resolver = "3"
members = [
"../ui/tokens",
"../ui/ui",
"../ui/kit",
"../common/store",
"legacy-import",
"client",
"mobile",
"desktop",
"../../blocksuite/crates/doc",
"../../blocksuite/crates/editor",
"../../blocksuite/crates/playground",
"../../blocksuite/crates/preview",
"hosts/android",
"hosts/ios",
]
default-members = [
"../ui/tokens",
"../ui/ui",
"../ui/kit",
"../common/store",
"legacy-import",
"client",
"mobile",
"desktop",
"../../blocksuite/crates/doc",
"../../blocksuite/crates/editor",
"../../blocksuite/crates/playground",
]
exclude = ["native", "mobile-native"]
[workspace.package]
version = "0.1.0"
edition = "2024"
publish = false
license = "Apache-2.0"
[workspace.dependencies]
anyhow = "1.0.86"
async-channel = { version = "2.5", default-features = false }
async-task = "4.7"
backtrace = "0.3"
base64 = "0.22"
bitflags = "2.6.0"
block2 = "0.6"
bytemuck = "1"
cbindgen = { version = "0.28.0", default-features = false }
chrono = { version = "0.4", default-features = false, features = ["std"] }
console_error_panic_hook = "0.1.7"
core-foundation = "0.10"
core-foundation-sys = "0.8.6"
core-graphics = "0.24"
core-text = "21"
cosmic-text = "0.19.0"
ctor = "1.0.12"
derive_more = { version = "2.1", features = ["add", "add_assign", "deref", "deref_mut", "from_str", "mul", "mul_assign", "not"] }
dispatch2 = { version = "0.3", default-features = false, features = ["std"] }
etagere = "0.2"
flume = { version = "0.12", default-features = false, features = ["async"] }
font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", default-features = false }
fontdb = { version = "0.23.0", default-features = false }
foreign-types = "0.5"
frame-audit = { path = "../../tools/frame-audit" }
futures = "0.3.34"
getrandom = { version = "0.3.4", features = ["wasm_js"] }
icu_segmenter = { version = "2.3.0", default-features = false, features = ["compiled_data"] }
image = { version = "0.25.1", default-features = false, features = ["bmp", "gif", "ico", "jpeg", "png", "webp"] }
indexmap = { version = "2.7.0", features = ["serde"] }
itertools = "0.14.0"
jiff = "1.0"
js-sys = "0.3"
libc = "0.2"
log = { version = "0.4", default-features = false, features = ["std"] }
lyon = "1.0"
mach2 = "0.6"
num_cpus = "1.13"
objc2 = "0.6"
objc2-app-kit = { version = "0.3.2", default-features = false, features = [
"NSAlert",
"NSAppearance",
"NSApplication",
"NSButton",
"NSCell",
"NSColor",
"NSControl",
"NSCursor",
"NSDocumentController",
"NSDragging",
"NSDraggingItem",
"NSEvent",
"NSGraphics",
"NSImage",
"NSMenu",
"NSMenuItem",
"NSOpenPanel",
"NSPanel",
"NSPasteboard",
"NSResponder",
"NSRunningApplication",
"NSSavePanel",
"NSScreen",
"NSScroller",
"NSTrackingArea",
"NSView",
"NSVisualEffectView",
"NSWindow",
"NSWorkspace",
"block2",
"objc2-core-foundation",
"objc2-uniform-type-identifiers",
] }
objc2-core-foundation = { version = "=0.3.2", default-features = false, features = ["std", "CFData", "CFDictionary", "CFString", "CFNumber", "CFBase", "CFCGTypes"] }
objc2-core-graphics = { version = "=0.3.2", default-features = false, features = ["CGColor", "CGColorSpace", "CGDirectDisplay", "objc2"] }
objc2-core-text = { version = "0.3.2", default-features = false, features = ["std", "CTFont", "CTFontDescriptor"] }
objc2-core-video = { version = "=0.3.2", default-features = false, features = ["CVBuffer", "CVHostTime", "CVImageBuffer", "CVMetalTexture", "CVMetalTextureCache", "CVPixelBuffer", "CVReturn", "objc2", "objc2-metal"] }
objc2-foundation = { version = "=0.3.2", default-features = false, features = [
"NSArray",
"NSAttributedString",
"NSBundle",
"NSCoder",
"NSData",
"NSDate",
"NSDictionary",
"NSEnumerator",
"NSError",
"NSGeometry",
"NSNotification",
"NSNull",
"NSObjCRuntime",
"NSObject",
"NSOperation",
"NSProcessInfo",
"NSRange",
"NSRunLoop",
"NSSet",
"NSString",
"NSThread",
"NSURL",
"NSValue",
"block2",
"objc2-core-foundation",
"std",
] }
objc2-metal = { version = "0.3.2", default-features = false, features = [
"std",
"block2",
"dispatch2",
"MTLAllocation",
"MTLBlitCommandEncoder",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
"MTLCommandQueue",
"MTLDevice",
"MTLDrawable",
"MTLLibrary",
"MTLPixelFormat",
"MTLRenderCommandEncoder",
"MTLRenderPass",
"MTLRenderPipeline",
"MTLResource",
"MTLTexture",
"MTLTypes",
] }
objc2-quartz-core = { version = "=0.3.2", default-features = false, features = ["std", "CALayer", "CAMetalDisplayLink", "CAMetalLayer", "objc2-core-foundation", "objc2-core-graphics", "objc2-metal"] }
objc2-uniform-type-identifiers = { version = "0.3", default-features = false, features = ["std", "UTCoreTypes", "UTType"] }
parking = "2.0.0"
parking_lot = "0.12.1"
pathfinder_geometry = "0.5"
pin-project = "1.1.10"
pollster = "0.4.0"
rand = { version = "0.9", default-features = false, features = ["std", "std_rng", "os_rng", "small_rng", "thread_rng"] }
raw-window-handle = "0.6"
resvg = { version = "0.46.0", default-features = false, features = ["raster-images"] }
rustc-hash = "2.1.0"
seahash = "4.1"
semver = { version = "1.0", features = ["serde"] }
serde = { version = "1.0", features = ["derive", "rc"] }
serde_json = { version = "1.0.144", features = ["preserve_order"] }
sha2 = "0.10"
slotmap = "1.0.6"
smallvec = { version = "1.6", features = ["union", "const_new"] }
smol_str = { version = "0.3.6", default-features = false, features = ["serde"] }
spin = { version = "0.10", default-features = false, features = ["mutex", "spin_mutex", "lock_api"] }
sqlx = { version = "0.8.6", default-features = false, features = ["sqlite", "migrate", "runtime-tokio", "chrono"] }
strum = { version = "0.28", features = ["derive"] }
swash = "0.2.6"
taffy = { version = "=0.15.0", default-features = false, features = ["std", "taffy_tree", "flexbox", "block_layout", "float_layout", "content_size"] }
thiserror = "2.0.12"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
ttf-parser = "0.25"
unicode-bidi = { version = "0.3.18", default-features = false, features = ["hardcoded-data"] }
unicode-normalization = "0.1.26"
unicode-properties = "=0.1.3"
unicode-script = "0.5.7"
unicode-segmentation = "1.10"
url = "2.2"
usvg = { version = "0.46.0", default-features = false }
uuid = { version = "1.1", features = ["serde", "v4"] }
waker-fn = "1.2.0"
wasm-bindgen = "0.2.120"
wasm-bindgen-futures = "0.4"
web-sys = "0.3"
web-time = "1.1.0"
wgpu = { git = "https://github.com/gfx-rs/wgpu", rev = "cddb2f5d80dc0009b2ef6767635140cacf90a007", default-features = false }
y-octo = { version = "0.4.0", default-features = false, features = ["session", "large_refs"] }
[workspace.lints.rust]
unexpected_cfgs = { level = "deny" }
[workspace.lints.clippy]
dbg_macro = "deny"
todo = "deny"
declare_interior_mutable_const = "deny"
style = { level = "allow", priority = -1 }
type_complexity = "allow"
let_underscore_future = "allow"
single_range_in_vec_init = "allow"
too_many_arguments = "allow"
large_enum_variant = "allow"
nonminimal_bool = "allow"
[patch.crates-io]
async-task = { git = "https://github.com/zed-industries/async-task.git", rev = "015845a19fc31752c02367567d3b8900a406f9da" }
[profile.dev]
debug = 0
incremental = false
codegen-units = 16
[profile.dev.package.merman]
opt-level = "s"
[profile.dev.package.merman-analysis]
opt-level = "s"
[profile.dev.package.merman-ascii]
opt-level = "s"
[profile.dev.package.merman-core]
opt-level = "s"
[profile.dev.package.merman-editor-core]
opt-level = "s"
[profile.dev.package.merman-elk-layered]
opt-level = 0
[profile.dev.package.merman-layout-elk]
opt-level = 0
[profile.dev.package.merman-markup]
opt-level = "s"
[profile.dev.package.merman-model]
opt-level = "s"
[profile.dev.package.merman-render]
opt-level = "s"
[profile.dev.package.merman-theme-contract]
opt-level = "s"
[profile.dev.package.typst]
opt-level = "s"
[profile.dev.package.typst-eval]
opt-level = "s"
[profile.dev.package.typst-html]
opt-level = "s"
[profile.dev.package.typst-layout]
opt-level = "s"
[profile.dev.package.typst-library]
opt-level = "s"
[profile.dev.package.typst-realize]
opt-level = "s"
[profile.dev.package.typst-svg]
opt-level = "s"
[profile.dev.package.typst-syntax]
opt-level = "s"
[profile.dev.package.typst-utils]
opt-level = "s"
[profile.dev.package.comemo]
opt-level = "s"
[profile.dev.package.wgpu-core]
opt-level = "s"
[profile.dev.package.wgpu-hal]
opt-level = "s"
[profile.dev.package.naga]
opt-level = "s"
[profile.dev.package.hayro]
opt-level = "s"
[profile.dev.package.hayro-interpret]
opt-level = "s"
[profile.dev.package.hayro-syntax]
opt-level = "s"
[profile.dev.package.hayro-font]
opt-level = "s"
[profile.dev.package.hayro-svg]
opt-level = "s"
[profile.dev.package.resvg]
opt-level = "s"
[profile.dev.package.usvg]
opt-level = "s"
[profile.dev.package.tiny-skia]
opt-level = "s"
[profile.dev.package.cosmic-text]
opt-level = "s"
[profile.dev.package.swash]
opt-level = "s"
[profile.dev.package.skrifa]
opt-level = "s"
[profile.test]
debug = 0
incremental = false
codegen-units = 16
[profile.release]
debug = "limited"
lto = "thin"
codegen-units = 1
[profile.release.package.merman]
opt-level = "z"
[profile.release.package.merman-analysis]
opt-level = "z"
[profile.release.package.merman-ascii]
opt-level = "z"
[profile.release.package.merman-core]
opt-level = "z"
[profile.release.package.merman-editor-core]
opt-level = "z"
[profile.release.package.merman-elk-layered]
opt-level = "z"
[profile.release.package.merman-layout-elk]
opt-level = "z"
[profile.release.package.merman-markup]
opt-level = "z"
[profile.release.package.merman-model]
opt-level = "z"
[profile.release.package.merman-render]
opt-level = "z"
[profile.release.package.merman-theme-contract]
opt-level = "z"
[profile.release.package.typst]
opt-level = "z"
[profile.release.package.typst-eval]
opt-level = "z"
[profile.release.package.typst-html]
opt-level = "z"
[profile.release.package.typst-layout]
opt-level = "z"
[profile.release.package.typst-library]
opt-level = "z"
[profile.release.package.typst-realize]
opt-level = "z"
[profile.release.package.typst-svg]
opt-level = "z"
[profile.release.package.typst-syntax]
opt-level = "z"
[profile.release.package.typst-utils]
opt-level = "z"
[profile.release.package.comemo]
opt-level = "z"
[profile.wasm-release]
inherits = "release"
debug = 0
[profile.wasm-release-size]
inherits = "wasm-release"
opt-level = "s"
lto = false
codegen-units = 1
strip = "debuginfo"
[profile.wasm-worker-size]
inherits = "release"
debug = 0
opt-level = "z"
lto = "fat"
codegen-units = 1
strip = "debuginfo"
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.97.1"
profile = "default"
@@ -0,0 +1,219 @@
import type { Meta } from '@storybook/react';
import type { CSSProperties, ReactNode } from 'react';
import { Button } from '../button';
import { Divider } from '../divider';
export default {
title: 'UI/Frame Audit',
} satisfies Meta;
interface AuditOptions {
role?: 'divider' | 'overlay';
text?: boolean;
ellipsis?: boolean;
baseline?: string;
footer?: [group: string, priority: number];
}
/** Marks an element for the geometry snapshot read by `harness.tsx`. */
const audit = (id: string, options: AuditOptions = {}) => ({
'data-audit-id': id,
'data-audit-role': options.role,
'data-audit-text': options.text ? '' : undefined,
'data-audit-ellipsis': options.ellipsis ? '' : undefined,
'data-audit-baseline': options.baseline,
'data-audit-footer': options.footer?.join(':'),
});
const Scene = ({
width = 480,
children,
}: {
width?: number;
children: ReactNode;
}) => (
<div
{...audit('scene')}
style={{ position: 'relative', width, height: 320, overflow: 'hidden' }}
>
{children}
</div>
);
const line: CSSProperties = {
display: 'block',
width: 200,
fontSize: 15,
lineHeight: '24px',
};
export const FirstLineBaseline = () => (
<Scene>
<div
style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: 16 }}
>
<span
{...audit('row.icon', { baseline: 'row' })}
style={{ width: 16, height: 16, marginTop: 4, background: 'gray' }}
/>
<span
{...audit('row.title', { text: true, baseline: 'row' })}
style={line}
>
A title long enough to wrap onto a second line of this row
</span>
<Button
{...audit('row.action')}
style={{ width: 96, height: 24, flexShrink: 0 }}
>
Open
</Button>
</div>
</Scene>
);
export const DialogFooter = () => (
<Scene width={240}>
<div
{...audit('dialog')}
style={{
display: 'flex',
flexWrap: 'wrap-reverse',
gap: 8,
width: 208,
margin: 16,
}}
>
<Button
{...audit('dialog.confirm', { footer: ['actions', 0] })}
variant="primary"
style={{ width: 128, height: 32 }}
>
Confirm
</Button>
<Button
{...audit('dialog.cancel', { footer: ['actions', 1] })}
style={{ width: 128, height: 32 }}
>
Cancel
</Button>
</div>
</Scene>
);
export const NestedRadii = () => (
<Scene>
<div
{...audit('card')}
style={{
boxSizing: 'border-box',
width: 240,
height: 120,
margin: 16,
padding: 8,
borderRadius: 16,
background: 'var(--affine-background-secondary-color)',
}}
>
<div
{...audit('card.inner')}
style={{ height: 104, borderRadius: 8, background: 'gray' }}
/>
</div>
</Scene>
);
export const DividedList = () => (
<Scene>
<div {...audit('list')} style={{ width: 240, margin: 16 }}>
{['a', 'b', 'c'].flatMap((item, index) => [
...(index > 0
? [
<Divider
key={`divider-${item}`}
{...audit(`list.divider-${item}`, { role: 'divider' })}
space={4}
/>,
]
: []),
<div key={item} {...audit(`list.${item}`)} style={{ height: 24 }}>
{item}
</div>,
])}
</div>
</Scene>
);
export const NarrowContainer = () => (
<Scene width={160}>
<span
{...audit('narrow.name', { text: true, ellipsis: true })}
style={{
...line,
width: 128,
margin: 16,
overflow: 'hidden',
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
}}
>
A document name far longer than its container
</span>
<Button
{...audit('narrow.action')}
style={{ width: 128, height: 28, marginLeft: 16 }}
>
Rename
</Button>
</Scene>
);
export const FractionalThirds = () => (
<Scene>
<div
{...audit('thirds')}
style={{ display: 'flex', width: 470, margin: 5 }}
>
{['a', 'b', 'c'].map(cell => (
<div
key={cell}
{...audit(`thirds.${cell}`)}
style={{ flex: 1, height: 24 }}
/>
))}
</div>
</Scene>
);
export const FloatingOverlay = () => (
<Scene>
<Button
{...audit('page.action')}
style={{ width: 96, height: 28, margin: 16 }}
>
Behind
</Button>
<div
{...audit('menu', { role: 'overlay' })}
style={{
position: 'absolute',
top: 8,
left: 8,
boxSizing: 'border-box',
width: 160,
height: 64,
padding: 4,
borderRadius: 8,
background: 'var(--affine-background-overlay-panel-color)',
}}
>
<Button
{...audit('menu.item')}
style={{ width: 152, height: 28, borderRadius: 4 }}
>
Menu item
</Button>
</div>
</Scene>
);
@@ -0,0 +1,196 @@
import '../../theme';
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
import * as stories from './frame-audit.stories';
type Story = Exclude<(typeof stories)[keyof typeof stories], { title: string }>;
interface Rect {
x: number;
y: number;
width: number;
height: number;
}
/**
* Layout may place a box on fractional pixels (three `flex: 1` cells in 470px),
* but the browser paints its edges on the device pixel grid. Each edge is
* rounded on its own, as painted, so adjacent boxes stay adjacent and the
* `pixel-alignment` rule reports only what native layout can get wrong.
*/
const rectOf = ({ left, top, right, bottom }: DOMRect): Rect => {
const snap = (edge: number) =>
Math.round(edge * devicePixelRatio) / devicePixelRatio;
const [x, y] = [snap(left), snap(top)];
return { x, y, width: snap(right) - x, height: snap(bottom) - y };
};
const intersect = (a: Rect, b: Rect): Rect => {
const x = Math.max(a.x, b.x);
const y = Math.max(a.y, b.y);
return {
x,
y,
width: Math.max(0, Math.min(a.x + a.width, b.x + b.width) - x),
height: Math.max(0, Math.min(a.y + a.height, b.y + b.height) - y),
};
};
const CURSORS: Record<string, string> = {
default: 'default',
pointer: 'pointer',
text: 'text',
grab: 'grab',
'not-allowed': 'not_allowed',
};
function contentMask(el: Element, viewport: Rect) {
let mask = viewport;
for (let p = el.parentElement; p; p = p.parentElement) {
if (getComputedStyle(p).overflow !== 'visible') {
mask = intersect(mask, rectOf(p.getBoundingClientRect()));
}
}
return mask;
}
function effectiveOpacity(el: Element) {
let opacity = 1;
for (let p: Element | null = el; p; p = p.parentElement) {
opacity *= Number(getComputedStyle(p).opacity);
}
return opacity;
}
function firstBaseline(el: HTMLElement) {
const probe = document.createElement('span');
probe.style.cssText =
'display:inline-block;width:0;height:0;vertical-align:baseline';
el.prepend(probe);
const baseline = probe.getBoundingClientRect().bottom;
probe.remove();
return baseline;
}
function textMetrics(el: HTMLElement) {
const range = document.createRange();
range.selectNodeContents(el);
const lines = [...range.getClientRects()];
const style = getComputedStyle(el);
const lineHeight = Number.parseFloat(style.lineHeight);
const lineCount = new Set(lines.map(r => Math.round(r.top))).size;
return {
first_baseline: firstBaseline(el),
first_line: { ...rectOf(el.getBoundingClientRect()), height: lineHeight },
line_count: lineCount,
overflowed:
el.scrollWidth > el.clientWidth || el.scrollHeight > el.clientHeight,
ellipsis_allowed:
Object.hasOwn(el.dataset, 'auditEllipsis') &&
style.textOverflow === 'ellipsis' &&
style.overflowX !== 'visible',
};
}
function snapshotElement(el: HTMLElement, viewport: Rect) {
const style = getComputedStyle(el);
const footer = el.dataset.auditFooter?.split(':');
const parent = el.parentElement?.closest<HTMLElement>('[data-audit-id]');
const interactive = el.matches('button, a[href], input, [role="button"]');
const isText = Object.hasOwn(el.dataset, 'auditText');
return {
id: el.dataset.auditId,
parent_id: parent?.dataset.auditId ?? null,
callsite: `frame-audit.stories.tsx#${el.dataset.auditId}`,
bounds: rectOf(el.getBoundingClientRect()),
content_mask: contentMask(el, viewport),
opacity: effectiveOpacity(el),
interactive,
focused: document.activeElement === el,
corner_radius: Number.parseFloat(style.borderTopLeftRadius) || 0,
padding: Number.parseFloat(style.paddingLeft) || 0,
text: isText ? el.textContent : null,
role: el.dataset.auditRole ?? 'generic',
cursor: CURSORS[style.cursor] ?? null,
selectable: isText && style.userSelect !== 'none',
text_metrics: isText ? textMetrics(el) : null,
baseline_group: el.dataset.auditBaseline ?? null,
footer: footer ? { group: footer[0], priority: Number(footer[1]) } : null,
};
}
/** The element receiving pointer events at a point, as an audited id. */
function hitProbe(x: number, y: number) {
const receiver = document
.elementFromPoint(x, y)
?.closest<HTMLElement>('[data-audit-id]');
return { x, y, receiver: receiver?.dataset.auditId ?? null };
}
function snapshotFrame(host: HTMLElement) {
const viewport = {
x: 0,
y: 0,
width: window.innerWidth,
height: window.innerHeight,
};
const nodes = [...host.querySelectorAll<HTMLElement>('[data-audit-id]')];
const elements = Object.fromEntries(
nodes.map(el => [el.dataset.auditId, snapshotElement(el, viewport)])
);
const hit_probes = nodes
.filter(el => el.dataset.auditRole === 'overlay' || el.matches('button'))
.map(el => {
const box = el.getBoundingClientRect();
return hitProbe(box.x + box.width / 2, box.y + box.height / 2);
});
return { viewport, scale_factor: 1, elements, hit_probes };
}
const nextFrame = () =>
new Promise<void>(resolve => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
});
/** A real style change on one rendered element, captured as its own frame. */
interface DomCase {
name: string;
story: string;
element: string;
style: Partial<CSSStyleDeclaration>;
}
async function captureStories(domCases: DomCase[]) {
await document.fonts.ready;
const frames: Record<string, ReturnType<typeof snapshotFrame>> = {};
const domFrames: typeof frames = {};
const scenes = Object.entries(stories).filter(
(entry): entry is [string, Story] => typeof entry[1] === 'function'
);
for (const [name, Story] of scenes) {
const host = document.createElement('div');
document.body.append(host);
const root = createRoot(host);
flushSync(() => root.render(<Story />));
await nextFrame();
frames[name] = snapshotFrame(host);
for (const domCase of domCases.filter(c => c.story === name)) {
const target = host.querySelector<HTMLElement>(
`[data-audit-id="${domCase.element}"]`
);
if (!target) throw new Error(`${name}: no ${domCase.element}`);
const original = target.style.cssText;
Object.assign(target.style, domCase.style);
await nextFrame();
domFrames[domCase.name] = snapshotFrame(host);
target.style.cssText = original;
}
root.unmount();
host.remove();
}
return { frames, domFrames };
}
Object.assign(window, { captureFrameAuditStories: captureStories });
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.97.1"
profile = "default"
@@ -0,0 +1,13 @@
edition = "2024"
max_width = 120
style_edition = "2024"
hard_tabs = false
tab_spaces = 2
format_strings = true
unstable_features = true
wrap_comments = true
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
@@ -0,0 +1,3 @@
[toolchain]
channel = "1.97.1"
profile = "default"
+13
View File
@@ -0,0 +1,13 @@
edition = "2024"
max_width = 120
style_edition = "2024"
hard_tabs = false
tab_spaces = 2
format_strings = true
unstable_features = true
wrap_comments = true
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
+85
View File
@@ -0,0 +1,85 @@
# Native Playground CI Performance Guardrail
Zero-dependency `N-3` regression detector for `darksky/native-playground`.
## Metrics Schema (`schema.json`)
Every CI run emits `perf-metrics.json` containing:
- `schema_version`: integer `1`.
- `commit`: full 40-character lowercase Git SHA.
- `timestamp_utc`: ISO-8601 UTC timestamp.
- `ci_wall_ms`: shared-runner wall-clock durations (`lint_and_wasm`, `headless_linux`, `total_critical_path`).
- `artifacts_bytes`: deterministic build output sizes (`web_wasm_raw`, `web_wasm_gzip`, `headless_bin`).
- `benchmarks`: deterministic engine timings (`{ median, p95 }`, with `p95 >= median`) and work counters:
- `doc_1k_edits_ms`
- `room_sync_1k_ops_ms`
- `layout_10k_blocks_cold_ms`
- `layout_single_keystroke_ms`
- `layout_single_keystroke_blocks_relayout`
- `edgeless_1k_pan_zoom_frame_ms`
- `headless_frame_render_ms`
Individual sub-keys inside `ci_wall_ms`, `artifacts_bytes`, and `benchmarks` are optional (or `null`) when a benchmark or artifact is not yet produced by CI. Never emit synthetic `0` placeholders for unmeasured metrics: omitted or `null` baseline keys transition cleanly through `BOOTSTRAP` when first introduced instead of triggering false `0 -> positive` (`+inf%`) regressions.
## Regression Gate vs Advisory Timings
Current commit metrics are compared against the completed push run from **3 distinct prior commits (`N-3`)** strictly older than the commit under test (`--current-created-at` or the commit's earliest push run on the branch).
- **Library / seeding mode (default)**: If `N-3` has no valid `perf-metrics.json` artifact, the comparator walks `N-3 -> N-2 -> N-1`; with 0 valid prior baselines (such as the initial seeding runs of a new integration branch like `darksky/np/mobile` before 3 runs exist) it emits `baseline_depth: "bootstrap"`. `--require-baseline` requires at least `N-1` (`baseline !== null`).
- **Strict `N-3` CI mode (`--require-n3`)**: Used on established branches (`native-playground.yml`). Requires `baseline_depth === "N-3"`, a 40-char `baseline_commit`, zero unacknowledged `DROPPED` metrics (`baseline != null && current == null`), and zero unacknowledged `BOOTSTRAP` metrics (`baseline == null && current != null`). If all prior artifacts expire after retention, set `NP_ALLOW_PERF_BOOTSTRAP=1` for 3 seeding runs on the integration branch to re-establish `N-3`.
1. **Deterministic hard gate (`artifacts_bytes.*`, non-`_ms` work counters under `benchmarks.*`, and unacknowledged `DROPPED` / `--require-n3` `BOOTSTRAP` metrics)**:
- Flagged as `REGRESSED` (`DROPPED` when missing in `current`, `BOOTSTRAP` when missing in `N-3` under `--require-n3`; sets `has_hard_regression: true`) whenever `(current - baseline) / baseline * 100 > 10.0%` (strictly greater than `--threshold-pct`), or when `baseline === 0` and `current > 0`.
- `--fail-on-regression` exits `1` when `has_hard_regression` is `true`.
2. **Shared-runner wall-clock advisories (`benchmarks.*_ms` and `ci_wall_ms.*`)**:
- `benchmarks.*_ms` exceeding `> 10.0%`, and `ci_wall_ms.*` exceeding both `> 10.0%` and `> 15000` ms (`--ci-wall-min-delta-ms`), are reported as `ADVISORY_SLOWDOWN` (`advisory: true`, `regressed: false`, sets `has_advisory_slowdown: true`).
- Advisory timings are surfaced in the Markdown summary and `advisory_metrics` in `perf-verdict.json` for investigation on pinned hardware without failing shared-runner CI.
## Lifecycle & Regression Acknowledgements (`accepted.json`)
Intentional increases, newly introduced metrics, and retired metrics are recorded in `perf/accepted.json` (loaded by default, or via `--accepted <path>`):
```json
[
{
"metric": "artifacts_bytes.web_wasm_gzip",
"accepted_value": 800000,
"reason": "Bundled new rich-text feature"
},
{
"metric": "artifacts_bytes.headless_bin",
"action": "bootstrap",
"reason": "Newly introduced metric rolling into N-3"
},
{
"metric": "benchmarks.layout_single_keystroke_blocks_relayout",
"action": "drop",
"reason": "Retired obsolete counter"
}
]
```
- **Value ceiling (`action: "ceiling"`, default)**: When a metric triggers against the rolling baseline and `current <= accepted_value`, the row is marked `ACCEPTED` (`regressed: false`). Once `baseline >= accepted_value`, it is reported in `stale_acceptances`.
- **Intentional new metric (`action: "bootstrap"`)**: Marks `baseline == null && current != null` as `ACCEPTED_BOOTSTRAP` (`regressed: false`) under `--require-n3` for the 3-commit rolling window; once `N-3` includes the metric, it is reported in `stale_acceptances` for pruning.
- **Intentional metric removal (`action: "drop"`)**: Marks `baseline != null && current == null` as `ACCEPTED_DROP` (`regressed: false`); once `N-3` no longer contains the metric, it is reported in `stale_acceptances` for pruning.
## Usage
```sh
node packages/frontend/perf/compare-n3.mjs \
--fetch-github \
--repo toeverything/AFFiNE \
--branch darksky/native-playground \
--workflow native-playground.yml \
--run-id "$GITHUB_RUN_ID" \
--current artifacts/perf-metrics.json \
--json-out artifacts/perf-verdict.json \
--fail-on-regression
```
## Self-Tests
```sh
node --test packages/frontend/perf/compare-n3.test.mjs
```
+8
View File
@@ -0,0 +1,8 @@
[
{
"metric": "artifacts_bytes.headless_bin",
"action": "ceiling",
"accepted_value": 286000000,
"reason": "Native non-wasm32 targets link full blocksuite-preview (RaTeX math, Hayro PDF, Merman Mermaid, and Typst compiler with opt-level=s on dev/test deps) alongside desktop/mobile editing, edgeless spatial blocks, and touch interaction state machines (measured 280,311,728 B); wasm32 main bundle remains isolated via lazy workers."
}
]
File diff suppressed because it is too large. Load diff
+1000
View File
@@ -0,0 +1,1000 @@
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import {
comparePerfMetrics,
extractPerfMetricsFromZip,
renderMarkdownSummary,
resolveWindowFromEligibleRuns,
selectBaselineRun,
selectPerfMetricsZipEntry,
validateAcceptedEntries,
validatePerfMetrics,
} from './compare-n3.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLI_PATH = path.join(__dirname, 'compare-n3.mjs');
function makeMetrics(commit, overrides = {}) {
return {
schema_version: 1,
commit,
timestamp_utc: '2026-11-21T18:00:00Z',
ci_wall_ms: {
lint_and_wasm: 40_000,
headless_linux: 60_000,
total_critical_path: 80_000,
...(overrides.ci_wall_ms ?? {}),
},
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 700_000,
headless_bin: 15_000_000,
...(overrides.artifacts_bytes ?? {}),
},
benchmarks: {
doc_1k_edits_ms: { median: 10.0, p95: 12.0 },
room_sync_1k_ops_ms: { median: 20.0, p95: 25.0 },
layout_10k_blocks_cold_ms: { median: 100.0, p95: 112.0 },
layout_single_keystroke_ms: { median: 0.5, p95: 0.8 },
layout_single_keystroke_blocks_relayout: 1,
edgeless_1k_pan_zoom_frame_ms: { median: 4.0, p95: 5.0 },
headless_frame_render_ms: { median: 8.0, p95: 9.5 },
...(overrides.benchmarks ?? {}),
},
};
}
function crc32(buf) {
let crc = 0xffffffff;
for (let i = 0; i < buf.length; i += 1) {
crc ^= buf[i];
for (let j = 0; j < 8; j += 1) {
crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0);
}
}
return (crc ^ 0xffffffff) >>> 0;
}
function buildStoredZip(files) {
const localParts = [];
const centralParts = [];
let offset = 0;
for (const [name, content] of files) {
const nameBuf = Buffer.from(name, 'utf8');
const dataBuf = Buffer.from(content, 'utf8');
const checksum = crc32(dataBuf);
const local = Buffer.alloc(30);
local.writeUInt32LE(0x04034b50, 0);
local.writeUInt16LE(20, 4);
local.writeUInt16LE(0, 6);
local.writeUInt16LE(0, 8);
local.writeUInt16LE(0, 10);
local.writeUInt16LE(0, 12);
local.writeUInt32LE(checksum, 14);
local.writeUInt32LE(dataBuf.length, 18);
local.writeUInt32LE(dataBuf.length, 22);
local.writeUInt16LE(nameBuf.length, 26);
local.writeUInt16LE(0, 28);
localParts.push(local, nameBuf, dataBuf);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0);
central.writeUInt16LE(20, 4);
central.writeUInt16LE(20, 6);
central.writeUInt16LE(0, 8);
central.writeUInt16LE(0, 10);
central.writeUInt16LE(0, 12);
central.writeUInt16LE(0, 14);
central.writeUInt32LE(checksum, 16);
central.writeUInt32LE(dataBuf.length, 20);
central.writeUInt32LE(dataBuf.length, 24);
central.writeUInt16LE(nameBuf.length, 28);
central.writeUInt16LE(0, 30);
central.writeUInt16LE(0, 32);
central.writeUInt16LE(0, 34);
central.writeUInt16LE(0, 36);
central.writeUInt32LE(0, 38);
central.writeUInt32LE(offset, 42);
centralParts.push(central, nameBuf);
offset += local.length + nameBuf.length + dataBuf.length;
}
const centralSize = centralParts.reduce((acc, b) => acc + b.length, 0);
const eocd = Buffer.alloc(22);
eocd.writeUInt32LE(0x06054b50, 0);
eocd.writeUInt16LE(0, 4);
eocd.writeUInt16LE(0, 6);
eocd.writeUInt16LE(files.length, 8);
eocd.writeUInt16LE(files.length, 10);
eocd.writeUInt32LE(centralSize, 12);
eocd.writeUInt32LE(offset, 16);
eocd.writeUInt16LE(0, 20);
return Buffer.concat([...localParts, ...centralParts, eocd]);
}
test('validatePerfMetrics rejects empty objects, verdict files, unknown keys, and p95 < median', () => {
assert.throws(() => validatePerfMetrics({}), /missing required/);
assert.throws(
() =>
validatePerfMetrics({
schema_version: 1,
has_hard_regression: false,
}),
/unknown top-level key/
);
assert.throws(
() =>
validatePerfMetrics({
...makeMetrics('1'.repeat(40)),
extra_field: 42,
}),
/unknown top-level key/
);
assert.throws(
() =>
validatePerfMetrics(
makeMetrics('1'.repeat(40), {
benchmarks: { doc_1k_edits_ms: { median: 15.0, p95: 10.0 } },
})
),
/p95 .* must be >= median/
);
assert.throws(
() =>
validatePerfMetrics({
...makeMetrics('1'.repeat(40)),
commit: 'not-a-sha',
}),
/40-char lowercase hex SHA/
);
});
test('selectBaselineRun handles bootstrap, rerun deduplication, and strict older anchoring', () => {
const s = n => String(n).repeat(40);
const runs = [
{ id: 7, head_sha: s(7), status: 'completed', conclusion: 'success', created_at: '2026-11-21T07:00:00Z' },
{ id: 6, head_sha: s(6), status: 'completed', conclusion: 'success', created_at: '2026-11-21T06:00:00Z' },
{ id: 5, head_sha: s(5), status: 'completed', conclusion: 'success', created_at: '2026-11-21T05:00:00Z' },
{ id: 4, head_sha: s(4), status: 'completed', conclusion: 'success', created_at: '2026-11-21T04:00:00Z' },
{ id: 3, head_sha: s(3), status: 'completed', conclusion: 'success', created_at: '2026-11-21T03:00:00Z' },
{ id: 2, head_sha: s(2), status: 'completed', conclusion: 'success', created_at: '2026-11-21T02:00:00Z' },
{ id: 1, head_sha: s(1), status: 'completed', conclusion: 'success', created_at: '2026-11-21T01:00:00Z' },
];
// Rerun of commit #4 in [7..1] must consider only [3, 2, 1] and select #1
const rerun4 = selectBaselineRun(runs, { currentCommit: s(4) });
assert.equal(rerun4.baseline?.id, 1);
assert.equal(rerun4.baselineDepth, 'N-3');
assert.deepEqual(
rerun4.eligibleRuns.map(r => r.id),
[3, 2, 1]
);
// When SHA #4 is outside the page, --current-created-at still anchors strictly older runs
const pageWithout4 = runs.filter(r => r.id !== 4);
const anchoredByTime = selectBaselineRun(pageWithout4, {
currentCommit: s(4),
currentCreatedAt: '2026-11-21T04:00:00Z',
});
assert.equal(anchoredByTime.baseline?.id, 1);
assert.deepEqual(
anchoredByTime.eligibleRuns.map(r => r.id),
[3, 2, 1]
);
// Bootstrap with 0 prior runs
const empty = selectBaselineRun([], { currentCommit: s(1) });
assert.equal(empty.baseline, null);
assert.equal(empty.baselineDepth, 'bootstrap');
});
test(
'resolveWindowFromEligibleRuns falls back to N-2 and skips artifact-less runs',
() => {
const s = n => String(n).repeat(40);
const eligible = [
{ id: 30, head_sha: s(3) }, // N-1
{ id: 20, head_sha: s(2) }, // N-2
{ id: 10, head_sha: s(1) }, // N-3 (missing artifact!)
];
const payloads = new Map([
[30, makeMetrics(s(3))],
[20, makeMetrics(s(2))],
[10, null],
]);
const resolved = resolveWindowFromEligibleRuns(eligible, r =>
payloads.get(r.id)
);
assert.equal(resolved.baselineDepth, 'N-2');
assert.equal(resolved.baseline?.commit, s(2));
assert.equal(resolved.n1?.commit, s(3));
assert.equal(resolved.n2, null);
// Path-filtered backend/docs runs with no perf-metrics artifact must not
// push valid UI runs out of the N-3 window.
const mkRun = n => ({
id: n * 10,
head_sha: s(n),
status: 'completed',
conclusion: 'success',
created_at: `2026-11-21T0${n}:00:00Z`,
});
const mixedRuns = [8, 7, 6, 5, 4, 3, 2, 1].map(mkRun);
const sel = selectBaselineRun(mixedRuns, {
currentCommit: s(8),
maxCandidates: 90,
});
const mixedPayloads = new Map([
[70, null],
[60, null],
[50, null],
[40, makeMetrics(s(4))],
[30, makeMetrics(s(3))],
[20, makeMetrics(s(2))],
[10, makeMetrics(s(1))],
]);
const visited = [];
const mixedResolved = resolveWindowFromEligibleRuns(sel.eligibleRuns, r => {
visited.push(r.id);
return mixedPayloads.get(r.id);
});
assert.equal(mixedResolved.baselineDepth, 'N-3');
assert.equal(mixedResolved.baseline?.commit, s(2));
assert.equal(mixedResolved.n1?.commit, s(4));
assert.equal(mixedResolved.n2?.commit, s(3));
assert.deepEqual(visited, [70, 60, 50, 40, 30, 20]);
});
test('selectPerfMetricsZipEntry rejects verdict-only zips and never falls back to arbitrary json', () => {
assert.equal(
selectPerfMetricsZipEntry(['perf-verdict.json', 'linux-run1.json']),
null
);
assert.equal(
selectPerfMetricsZipEntry([
'linux-run1.json',
'artifacts/perf-metrics.json',
'perf-verdict.json',
]),
'artifacts/perf-metrics.json'
);
assert.equal(
selectPerfMetricsZipEntry([
'artifacts/perf-metrics.json',
'perf-metrics.json',
]),
'perf-metrics.json'
);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'np-perf-zip-'));
try {
const verdictOnlyZip = path.join(dir, 'verdict-only.zip');
fs.writeFileSync(
verdictOnlyZip,
buildStoredZip([['perf-verdict.json', JSON.stringify({ has_hard_regression: false })]])
);
assert.throws(() => extractPerfMetricsFromZip(verdictOnlyZip), /No valid perf-metrics\.json/);
const validNestedZip = path.join(dir, 'nested.zip');
const expected = makeMetrics('9'.repeat(40));
fs.writeFileSync(
validNestedZip,
buildStoredZip([
['perf-verdict.json', JSON.stringify({ noise: true })],
['artifacts/perf-metrics.json', JSON.stringify(expected)],
])
);
const parsed = extractPerfMetricsFromZip(validNestedZip);
assert.equal(parsed.commit, expected.commit);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('deterministic hard gate vs advisory shared-runner timings and --fail-on-regression exit codes', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'np-perf-advisory-'));
try {
const basePath = path.join(dir, 'base.json');
const timingOnlyPath = path.join(dir, 'timing-only.json');
const bytesRegPath = path.join(dir, 'bytes-reg.json');
const jsonOut = path.join(dir, 'verdict.json');
// The gate itself is under test: no ceiling from the repository's perf/accepted.json applies.
const noAcceptedPath = path.join(dir, 'accepted.json');
fs.writeFileSync(noAcceptedPath, '[]');
fs.writeFileSync(basePath, JSON.stringify(makeMetrics('1'.repeat(40))));
// Only *_ms timings slowed down (>10%) -> ADVISORY_SLOWDOWN, must exit 0 under --fail-on-regression
fs.writeFileSync(
timingOnlyPath,
JSON.stringify(
makeMetrics('2'.repeat(40), {
ci_wall_ms: {
lint_and_wasm: 40_000,
headless_linux: 60_000,
total_critical_path: 100_000, // +25% and +20s -> ADVISORY_SLOWDOWN
},
benchmarks: {
doc_1k_edits_ms: { median: 15.0, p95: 18.0 }, // +50% -> ADVISORY_SLOWDOWN
},
})
)
);
// Deterministic byte size grew +12% -> REGRESSED, must exit 1 under --fail-on-regression
fs.writeFileSync(
bytesRegPath,
JSON.stringify(
makeMetrics('3'.repeat(40), {
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 784_000, // +12% -> REGRESSED
headless_bin: 15_000_000,
},
})
)
);
const advStdout = execFileSync(
process.execPath,
[
CLI_PATH,
'--current',
timingOnlyPath,
'--baseline',
basePath,
'--accepted',
noAcceptedPath,
'--json-out',
jsonOut,
'--fail-on-regression',
],
{ encoding: 'utf8' }
);
assert.match(advStdout, /ADVISORY_SLOWDOWN/);
const advVerdict = JSON.parse(fs.readFileSync(jsonOut, 'utf8'));
assert.equal(advVerdict.has_hard_regression, false);
assert.equal(advVerdict.has_advisory_slowdown, true);
assert.equal(advVerdict.needs_perf_investigation, false);
assert.deepEqual(
advVerdict.advisory_metrics.map(m => m.key).sort(),
['benchmarks.doc_1k_edits_ms', 'ci_wall_ms.total_critical_path']
);
let exitCode = 0;
let regStdout = '';
try {
execFileSync(
process.execPath,
[
CLI_PATH,
'--current',
bytesRegPath,
'--baseline',
basePath,
'--accepted',
noAcceptedPath,
'--json-out',
jsonOut,
'--fail-on-regression',
],
{ encoding: 'utf8' }
);
} catch (err) {
exitCode = err.status;
regStdout = String(err.stdout ?? '');
}
assert.equal(exitCode, 1);
assert.match(regStdout, /REGRESSION DETECTED/);
const regVerdict = JSON.parse(fs.readFileSync(jsonOut, 'utf8'));
assert.equal(regVerdict.has_hard_regression, true);
assert.equal(regVerdict.regressed_metrics[0].key, 'artifacts_bytes.web_wasm_gzip');
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('perf/accepted.json value-ceiling accepts <= ceiling, rejects > ceiling, and reports stale_acceptances without failing CI', () => {
// Validation rejects unknown keys, unknown metrics, duplicate metrics, and non-integer ceilings on integer metrics
assert.throws(
() =>
validateAcceptedEntries([
{
metric: 'artifacts_bytes.web_wasm_gzip',
accepted_value: 125,
reason: 'ok',
commit: '1'.repeat(40),
},
]),
/unknown key/
);
assert.throws(
() =>
validateAcceptedEntries([
{ metric: 'artifacts_bytes.not_a_metric', accepted_value: 125, reason: 'ok' },
]),
/not a known metric key/
);
assert.throws(
() =>
validateAcceptedEntries([
{ metric: 'artifacts_bytes.web_wasm_gzip', accepted_value: 125, reason: 'a' },
{ metric: 'artifacts_bytes.web_wasm_gzip', accepted_value: 130, reason: 'b' },
]),
/duplicate metric/
);
assert.throws(
() =>
validateAcceptedEntries([
{ metric: 'artifacts_bytes.web_wasm_gzip', accepted_value: 125.5, reason: 'float' },
]),
/must be an integer/
);
const s = n => String(n).repeat(40);
const runs = [
{ id: 4, head_sha: s(4), status: 'completed', conclusion: 'success', created_at: '2026-11-21T04:00:00Z' },
{ id: 3, head_sha: s(3), status: 'completed', conclusion: 'success', created_at: '2026-11-21T03:00:00Z' },
{ id: 2, head_sha: s(2), status: 'completed', conclusion: 'success', created_at: '2026-11-21T02:00:00Z' },
{ id: 1, head_sha: s(1), status: 'completed', conclusion: 'success', created_at: '2026-11-21T01:00:00Z' },
];
const sel = selectBaselineRun(runs, { currentCommit: s(4) });
assert.equal(sel.baseline?.head_sha, s(1));
const baseline100 = makeMetrics(s(1), {
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 100,
headless_bin: 15_000_000,
},
});
const accepted = [
{
metric: 'artifacts_bytes.web_wasm_gzip',
accepted_value: 125,
reason: 'Added rich-text shaping tables',
},
];
// current = 125 (within ceiling 125) -> ACCEPTED, no hard regression, no stale acceptances
const cur125 = makeMetrics(s(4), {
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 125,
headless_bin: 15_000_000,
},
});
const vAccepted = comparePerfMetrics({
current: cur125,
baseline: baseline100,
accepted,
});
assert.equal(vAccepted.has_hard_regression, false);
assert.equal(vAccepted.stale_acceptances.length, 0);
const accRow = vAccepted.metrics.find(m => m.key === 'artifacts_bytes.web_wasm_gzip');
assert.equal(accRow?.status, 'ACCEPTED');
assert.equal(accRow?.baseline, 100);
assert.equal(accRow?.current, 125);
assert.match(renderMarkdownSummary(vAccepted), /accepted ceiling 125 B/);
// current = 138 (above ceiling 125) -> REGRESSED
const cur138 = makeMetrics(s(4), {
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 138,
headless_bin: 15_000_000,
},
});
const vReg = comparePerfMetrics({
current: cur138,
baseline: baseline100,
accepted,
});
assert.equal(vReg.has_hard_regression, true);
assert.equal(
vReg.metrics.find(m => m.key === 'artifacts_bytes.web_wasm_gzip')?.status,
'REGRESSED'
);
// Baseline catches up to 125, current = 125 -> PASS + stale_acceptances reported, CLI exits 0
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'np-perf-stale-'));
try {
const basePath = path.join(dir, 'base125.json');
const curPath = path.join(dir, 'cur125.json');
const accPath = path.join(dir, 'accepted.json');
const jsonOut = path.join(dir, 'verdict.json');
fs.writeFileSync(
basePath,
JSON.stringify(
makeMetrics(s(1), {
artifacts_bytes: {
web_wasm_raw: 2_000_000,
web_wasm_gzip: 125,
headless_bin: 15_000_000,
},
})
)
);
fs.writeFileSync(curPath, JSON.stringify(cur125));
fs.writeFileSync(accPath, JSON.stringify(accepted));
const stdout = execFileSync(
process.execPath,
[
CLI_PATH,
'--current',
curPath,
'--baseline',
basePath,
'--accepted',
accPath,
'--json-out',
jsonOut,
'--fail-on-regression',
],
{ encoding: 'utf8' }
);
assert.match(stdout, /### Stale Acceptances/);
const verdict = JSON.parse(fs.readFileSync(jsonOut, 'utf8'));
assert.equal(verdict.has_hard_regression, false);
assert.equal(verdict.stale_acceptances.length, 1);
assert.equal(verdict.stale_acceptances[0].key, 'artifacts_bytes.web_wasm_gzip');
assert.equal(
verdict.metrics.find(m => m.key === 'artifacts_bytes.web_wasm_gzip')?.status,
'PASS'
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('CLI --fetch-github --run-id uses immutable created_at cutoff and paginates across pages to locate N-3', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'np-perf-gh-'));
try {
const binDir = path.join(dir, 'bin');
fs.mkdirSync(binDir, { recursive: true });
const logPath = path.join(dir, 'gh-calls.log');
const zip1Path = path.join(dir, 'run-1.zip');
const zip2Path = path.join(dir, 'run-2.zip');
const zip3Path = path.join(dir, 'run-3.zip');
const curPath = path.join(dir, 'current.json');
const jsonOut = path.join(dir, 'verdict.json');
const s = n => String(n).repeat(40);
fs.writeFileSync(curPath, JSON.stringify(makeMetrics(s(4))));
fs.writeFileSync(
zip1Path,
buildStoredZip([['perf-metrics.json', JSON.stringify(makeMetrics(s(1)))]])
);
fs.writeFileSync(
zip2Path,
buildStoredZip([['perf-metrics.json', JSON.stringify(makeMetrics(s(2)))]])
);
fs.writeFileSync(
zip3Path,
buildStoredZip([['perf-metrics.json', JSON.stringify(makeMetrics(s(3)))]])
);
// Fake `gh` script that logs every `gh api <endpoint>` call and serves paginated runs
const fakeGhPath = path.join(binDir, 'gh');
const fakeGhSource = `#!/usr/bin/env node
const fs = require('node:fs');
const endpoint = process.argv[3] || '';
fs.appendFileSync(${JSON.stringify(logPath)}, endpoint + '\\n');
const s = n => String(n).repeat(40);
if (endpoint === 'repos/toeverything/AFFiNE/actions/runs/400') {
process.stdout.write(JSON.stringify({
id: 400,
head_sha: s(4),
created_at: '2026-11-21T04:00:00Z',
}));
process.exit(0);
}
if (endpoint.startsWith('repos/toeverything/AFFiNE/actions/workflows/native-playground.yml/runs?')) {
if (endpoint.includes('page=1')) {
// 30 runs containing reruns of sha(4), sha(3), sha(2) -> only 2 distinct prior SHAs, forcing page=2!
const page1 = [];
for (let i = 0; i < 10; i += 1) {
page1.push({ id: 400 - i, head_sha: s(4), status: 'completed', conclusion: 'success', created_at: '2026-11-21T04:00:00Z' });
}
for (let i = 0; i < 10; i += 1) {
page1.push({ id: 300 - i, head_sha: s(3), status: 'completed', conclusion: 'success', created_at: '2026-11-21T03:00:00Z' });
}
for (let i = 0; i < 10; i += 1) {
page1.push({ id: 200 - i, head_sha: s(2), status: 'completed', conclusion: 'success', created_at: '2026-11-21T02:00:00Z' });
}
process.stdout.write(JSON.stringify({ workflow_runs: page1 }));
process.exit(0);
}
if (endpoint.includes('page=2')) {
process.stdout.write(JSON.stringify({
workflow_runs: [
{ id: 1, head_sha: s(1), status: 'completed', conclusion: 'success', created_at: '2026-11-21T01:00:00Z' },
],
}));
process.exit(0);
}
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/runs/1/artifacts?per_page=100') {
process.stdout.write(JSON.stringify({ artifacts: [{ id: 1001, name: 'perf-metrics', expired: false }] }));
process.exit(0);
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/runs/200/artifacts?per_page=100') {
process.stdout.write(JSON.stringify({ artifacts: [{ id: 1002, name: 'perf-metrics', expired: false }] }));
process.exit(0);
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/runs/300/artifacts?per_page=100') {
process.stdout.write(JSON.stringify({ artifacts: [{ id: 1003, name: 'perf-metrics', expired: false }] }));
process.exit(0);
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/artifacts/1001/zip') {
process.stdout.write(fs.readFileSync(${JSON.stringify(zip1Path)}));
process.exit(0);
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/artifacts/1002/zip') {
process.stdout.write(fs.readFileSync(${JSON.stringify(zip2Path)}));
process.exit(0);
}
if (endpoint === 'repos/toeverything/AFFiNE/actions/artifacts/1003/zip') {
process.stdout.write(fs.readFileSync(${JSON.stringify(zip3Path)}));
process.exit(0);
}
console.error('Unexpected gh api endpoint:', endpoint);
process.exit(1);
`;
fs.writeFileSync(fakeGhPath, fakeGhSource, { mode: 0o755 });
const stdout = execFileSync(
process.execPath,
[
CLI_PATH,
'--fetch-github',
'--repo',
'toeverything/AFFiNE',
'--branch',
'darksky/native-playground',
'--workflow',
'native-playground.yml',
'--run-id',
'400',
'--current',
curPath,
'--json-out',
jsonOut,
'--fail-on-regression',
],
{
encoding: 'utf8',
env: { ...process.env, PATH: `${binDir}:${process.env.PATH}` },
}
);
assert.match(stdout, /## Native Playground Performance Guardrail \(N-3\)/);
const verdict = JSON.parse(fs.readFileSync(jsonOut, 'utf8'));
assert.equal(verdict.baseline_depth, 'N-3');
assert.equal(verdict.baseline_commit, s(1));
assert.equal(verdict.n2_commit, s(2));
assert.equal(verdict.n1_commit, s(3));
assert.equal(verdict.has_hard_regression, false);
const calls = fs.readFileSync(logPath, 'utf8').trim().split('\n');
assert.ok(
calls.some(c => c === 'repos/toeverything/AFFiNE/actions/runs/400'),
'must query run 400 for immutable created_at'
);
assert.ok(
calls.some(
c =>
c.includes('created=%3C%3D2026-11-21T04%3A00%3A00Z') &&
c.includes('page=1')
),
'must filter by created<=anchor on page=1'
);
assert.ok(
calls.some(
c =>
c.includes('created=%3C%3D2026-11-21T04%3A00%3A00Z') &&
c.includes('page=2')
),
'must paginate to page=2 when page=1 has < 3 distinct prior SHAs'
);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('partial-metrics baseline to expanded-metrics current yields BOOTSTRAP on newly introduced keys', () => {
const baseline = {
schema_version: 1,
commit: '1'.repeat(40),
timestamp_utc: '2026-11-21T18:00:00Z',
ci_wall_ms: { headless_linux: 50_000, lint_and_wasm: null },
artifacts_bytes: { headless_bin: 14_000_000 },
benchmarks: {
headless_frame_render_ms: { median: 8.0, p95: 9.5 },
doc_1k_edits_ms: null,
},
};
const current = {
schema_version: 1,
commit: '2'.repeat(40),
timestamp_utc: '2026-11-21T19:00:00Z',
ci_wall_ms: {
headless_linux: 52_000,
lint_and_wasm: 35_000,
total_critical_path: 52_000,
},
artifacts_bytes: {
headless_bin: 14_500_000,
web_wasm_raw: 1_800_000,
web_wasm_gzip: 620_000,
},
benchmarks: {
headless_frame_render_ms: { median: 8.4, p95: 9.8 },
doc_1k_edits_ms: { median: 10.2, p95: 12.1 },
room_sync_1k_ops_ms: { median: 18.5, p95: 22.0 },
},
};
const verdict = comparePerfMetrics({ current, baseline });
assert.equal(verdict.has_hard_regression, false);
const byKey = new Map(verdict.metrics.map(m => [m.key, m]));
assert.equal(byKey.get('benchmarks.headless_frame_render_ms')?.status, 'PASS');
assert.equal(byKey.get('benchmarks.doc_1k_edits_ms')?.status, 'BOOTSTRAP');
assert.equal(byKey.get('artifacts_bytes.web_wasm_raw')?.status, 'BOOTSTRAP');
});
test('edgeless_1k_pan_zoom_blocks_relayout: 0->0 passes and 0->1 flags deterministic hard regression', () => {
const mkPayload = (commitChar, relayouts) => ({
schema_version: 1,
commit: commitChar.repeat(40),
timestamp_utc: '2026-11-22T06:00:00Z',
ci_wall_ms: {
headless_linux: 50_000,
lint_and_wasm: 35_000,
total_critical_path: 50_000,
},
artifacts_bytes: {
headless_bin: 14_500_000,
web_wasm_raw: 1_800_000,
web_wasm_gzip: 620_000,
},
benchmarks: {
doc_1k_edits_ms: { median: 10.0, p95: 12.0 },
room_sync_1k_ops_ms: { median: 18.0, p95: 21.0 },
layout_10k_blocks_cold_ms: { median: 120.0, p95: 135.0 },
layout_single_keystroke_ms: { median: 0.5, p95: 0.7 },
layout_single_keystroke_blocks_relayout: 1,
edgeless_1k_pan_zoom_frame_ms: { median: 2.5, p95: 3.1 },
edgeless_1k_pan_zoom_blocks_relayout: relayouts,
headless_frame_render_ms: { median: 8.0, p95: 9.5 },
},
});
const baseline = mkPayload('a', 0);
const currentPass = mkPayload('b', 0);
const passVerdict = comparePerfMetrics({ current: currentPass, baseline });
assert.equal(passVerdict.has_hard_regression, false);
const passMetric = passVerdict.metrics.find(
m => m.key === 'benchmarks.edgeless_1k_pan_zoom_blocks_relayout'
);
assert.equal(passMetric?.status, 'PASS');
assert.equal(passMetric?.regressed, false);
const currentRegressed = mkPayload('c', 1);
const failVerdict = comparePerfMetrics({ current: currentRegressed, baseline });
assert.equal(failVerdict.has_hard_regression, true);
const failMetric = failVerdict.metrics.find(
m => m.key === 'benchmarks.edgeless_1k_pan_zoom_blocks_relayout'
);
assert.equal(failMetric?.status, 'REGRESSED');
assert.equal(failMetric?.regressed, true);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'compare-n3-edgeless-'));
try {
const basePath = path.join(dir, 'baseline.json');
const passPath = path.join(dir, 'pass.json');
const failPath = path.join(dir, 'fail.json');
fs.writeFileSync(basePath, JSON.stringify(baseline));
fs.writeFileSync(passPath, JSON.stringify(currentPass));
fs.writeFileSync(failPath, JSON.stringify(currentRegressed));
execFileSync(
process.execPath,
[CLI_PATH, '--current', passPath, '--baseline', basePath, '--fail-on-regression'],
{ encoding: 'utf8' }
);
let failedExit = 0;
try {
execFileSync(
process.execPath,
[CLI_PATH, '--current', failPath, '--baseline', basePath, '--fail-on-regression'],
{ encoding: 'utf8' }
);
} catch (err) {
failedExit = err.status ?? 0;
}
assert.equal(failedExit, 1);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test('missing baseline metric in current flags DROPPED hard regression and --require-baseline rejects missing history', () => {
const baseline = makeMetrics('a'.repeat(40));
const droppedCurrent = makeMetrics('b'.repeat(40));
delete droppedCurrent.artifacts_bytes.headless_bin;
const droppedVerdict = comparePerfMetrics({
current: droppedCurrent,
baseline,
});
assert.equal(droppedVerdict.has_hard_regression, true);
assert.equal(droppedVerdict.regressed_metrics.length, 1);
assert.equal(
droppedVerdict.regressed_metrics[0].key,
'artifacts_bytes.headless_bin'
);
const droppedRow = droppedVerdict.metrics.find(
m => m.key === 'artifacts_bytes.headless_bin'
);
assert.equal(droppedRow?.status, 'DROPPED');
assert.equal(droppedRow?.regressed, true);
assert.equal(droppedRow?.current, null);
assert.equal(droppedRow?.baseline, 15_000_000);
assert.match(renderMarkdownSummary(droppedVerdict), /DROPPED/);
const missingHistoryVerdict = comparePerfMetrics({
current: makeMetrics('c'.repeat(40)),
baseline: null,
requireBaseline: true,
});
assert.equal(missingHistoryVerdict.baseline_depth, 'bootstrap');
assert.equal(missingHistoryVerdict.has_hard_regression, true);
assert.match(
renderMarkdownSummary(missingHistoryVerdict),
/Missing or Incomplete Required Baseline/
);
// Strict --require-n3 rejects N-2 / N-1 fallback and unacknowledged BOOTSTRAP,
// while perf/accepted.json action="bootstrap" and action="drop" allow intentional
// metric additions and removals cleanly until N-3 catches up.
const n2FallbackVerdict = comparePerfMetrics({
current: makeMetrics('d'.repeat(40)),
baseline: makeMetrics('1'.repeat(40)),
baselineDepth: 'N-2',
requireN3: true,
});
assert.equal(n2FallbackVerdict.baseline_depth, 'N-2');
assert.equal(n2FallbackVerdict.has_hard_regression, true);
const missingInN3Baseline = makeMetrics('1'.repeat(40));
delete missingInN3Baseline.artifacts_bytes.headless_bin;
const unackBootstrapVerdict = comparePerfMetrics({
current: makeMetrics('d'.repeat(40)),
baseline: missingInN3Baseline,
baselineDepth: 'N-3',
requireN3: true,
});
assert.equal(unackBootstrapVerdict.has_hard_regression, true);
assert.equal(
unackBootstrapVerdict.metrics.find(
m => m.key === 'artifacts_bytes.headless_bin'
)?.status,
'BOOTSTRAP'
);
const ackBootstrapVerdict = comparePerfMetrics({
current: makeMetrics('d'.repeat(40)),
baseline: missingInN3Baseline,
baselineDepth: 'N-3',
requireN3: true,
accepted: [
{
metric: 'artifacts_bytes.headless_bin',
action: 'bootstrap',
reason: 'Newly introduced binary size metric',
},
],
});
assert.equal(ackBootstrapVerdict.has_hard_regression, false);
assert.equal(
ackBootstrapVerdict.metrics.find(
m => m.key === 'artifacts_bytes.headless_bin'
)?.status,
'ACCEPTED_BOOTSTRAP'
);
const ackDropVerdict = comparePerfMetrics({
current: droppedCurrent,
baseline,
baselineDepth: 'N-3',
requireN3: true,
accepted: [
{
metric: 'artifacts_bytes.headless_bin',
action: 'drop',
reason: 'Retired legacy binary target',
},
],
});
assert.equal(ackDropVerdict.has_hard_regression, false);
assert.equal(
ackDropVerdict.metrics.find(
m => m.key === 'artifacts_bytes.headless_bin'
)?.status,
'ACCEPTED_DROP'
);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'compare-n3-dropped-'));
try {
const basePath = path.join(dir, 'baseline.json');
const droppedPath = path.join(dir, 'dropped.json');
const fullPath = path.join(dir, 'full.json');
const noAcceptedPath = path.join(dir, 'accepted.json');
fs.writeFileSync(basePath, JSON.stringify(baseline));
fs.writeFileSync(droppedPath, JSON.stringify(droppedCurrent));
fs.writeFileSync(fullPath, JSON.stringify(makeMetrics('c'.repeat(40))));
fs.writeFileSync(noAcceptedPath, '[]');
let droppedExit = 0;
try {
execFileSync(
process.execPath,
[
CLI_PATH,
'--current',
droppedPath,
'--baseline',
basePath,
'--accepted',
noAcceptedPath,
'--fail-on-regression',
],
{ encoding: 'utf8' }
);
} catch (err) {
droppedExit = err.status ?? 0;
}
assert.equal(droppedExit, 1);
let noHistoryExit = 0;
try {
execFileSync(
process.execPath,
[
CLI_PATH,
'--current',
fullPath,
'--accepted',
noAcceptedPath,
'--require-baseline',
'--fail-on-regression',
],
{ encoding: 'utf8' }
);
} catch (err) {
noHistoryExit = err.status ?? 0;
}
assert.equal(noHistoryExit, 1);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
+140
View File
@@ -0,0 +1,140 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://toeverything.info/schemas/native-playground/perf-metrics.schema.json",
"title": "Native Playground CI Performance Metrics",
"description": "Deterministic benchmark timings, work counters, artifact sizes, and CI wall-clock measurements emitted per commit on darksky/native-playground. Individual sub-keys are optional (or null) when a job or benchmark is not yet active so unmeasured metrics are never padded with synthetic zeros.",
"type": "object",
"additionalProperties": false,
"required": [
"schema_version",
"commit",
"timestamp_utc",
"ci_wall_ms",
"artifacts_bytes",
"benchmarks"
],
"properties": {
"schema_version": {
"type": "integer",
"const": 1
},
"commit": {
"type": "string",
"pattern": "^[0-9a-f]{40}$",
"description": "Full 40-character lowercase Git commit SHA."
},
"timestamp_utc": {
"type": "string",
"format": "date-time",
"description": "UTC ISO-8601 timestamp when measurements were recorded."
},
"ci_wall_ms": {
"type": "object",
"additionalProperties": false,
"properties": {
"lint_and_wasm": {
"type": ["number", "null"],
"minimum": 0
},
"headless_linux": {
"type": ["number", "null"],
"minimum": 0
},
"total_critical_path": {
"type": ["number", "null"],
"minimum": 0
}
}
},
"artifacts_bytes": {
"type": "object",
"additionalProperties": false,
"properties": {
"web_wasm_raw": {
"type": ["integer", "null"],
"minimum": 0
},
"web_wasm_gzip": {
"type": ["integer", "null"],
"minimum": 0
},
"headless_bin": {
"type": ["integer", "null"],
"minimum": 0
}
}
},
"benchmarks": {
"type": "object",
"additionalProperties": false,
"properties": {
"doc_1k_edits_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
},
"room_sync_1k_ops_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
},
"layout_10k_blocks_cold_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
},
"layout_single_keystroke_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
},
"layout_single_keystroke_blocks_relayout": {
"type": ["integer", "null"],
"minimum": 0,
"description": "Number of blocks re-laid out during a single keystroke."
},
"edgeless_1k_pan_zoom_frame_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
},
"edgeless_1k_pan_zoom_blocks_relayout": {
"type": ["integer", "null"],
"minimum": 0,
"description": "Number of blocks re-laid out during a 30-step Edgeless pan and zoom sweep."
},
"headless_frame_render_ms": {
"oneOf": [
{ "$ref": "#/$defs/timingSummary" },
{ "type": "null" }
]
}
}
}
},
"$defs": {
"timingSummary": {
"type": "object",
"additionalProperties": false,
"required": [
"median",
"p95"
],
"properties": {
"median": {
"type": "number",
"minimum": 0
},
"p95": {
"type": "number",
"minimum": 0
}
}
}
}
}
+4
View File
@@ -0,0 +1,4 @@
[toolchain]
channel = "1.98.1"
components = ["rustfmt", "clippy"]
targets = ["wasm32-unknown-unknown"]
+1
View File
@@ -0,0 +1 @@
edition = "2024"
+776
View File
@@ -0,0 +1,776 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
REPO_ROOT="$(cd "$ROOT/../.." && pwd)"
cd "$ROOT"
fail() {
echo "ERROR: $*" >&2
exit 1
}
echo "==> Enumerating client Cargo workspace members via cargo metadata"
WORKSPACE_JSON=$(CARGO_ENCODED_RUSTFLAGS="" cargo metadata --manifest-path "$ROOT/Cargo.toml" --locked --no-deps --format-version 1)
MEMBER_LINES=$(
WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY'
import json
import os
from pathlib import Path
meta = json.loads(os.environ["WORKSPACE_JSON"])
repo_root = Path(os.environ["REPO_ROOT"]).resolve()
ws_ids = set(meta["workspace_members"])
members = {}
for pkg in meta["packages"]:
if pkg["id"] in ws_ids:
manifest = Path(pkg["manifest_path"]).resolve()
members[pkg["name"]] = manifest.parent
if len(members) < 3:
raise SystemExit(f"Expected at least 3 client workspace members, found {len(members)}: {members}")
expected_core = {
"ui": (repo_root / "packages/ui/ui").resolve(),
"blocksuite-playground-doc": (repo_root / "blocksuite/crates/doc").resolve(),
"playground": (repo_root / "blocksuite/crates/playground").resolve(),
}
for name, expected_dir in expected_core.items():
actual_dir = members.get(name)
if actual_dir != expected_dir:
raise SystemExit(
f"Expected core client member {name} at {expected_dir}, found {actual_dir}"
)
for name in sorted(members):
print(f"{name}\t{members[name]}")
PY
)
echo "Client workspace members:"
echo "$MEMBER_LINES"
echo "==> Checking test targets that require the harness feature"
WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY'
import json
import os
import re
from pathlib import Path
meta = json.loads(os.environ["WORKSPACE_JSON"])
repo_root = Path(os.environ["REPO_ROOT"]).resolve()
members = set(meta["workspace_members"])
target_kinds = {"bin", "test", "example", "bench"}
cfg_attribute = re.compile(r"#\s*!?\s*\[\s*cfg\s*\((.*?)\)\s*\]", re.DOTALL)
harness_feature = re.compile(r'\bfeature\s*=\s*"harness"')
test_alternative = re.compile(r"\bany\s*\(\s*test\s*,")
targets = set()
integration_tests = set()
for pkg in meta["packages"]:
if pkg["id"] not in members:
continue
for target in pkg["targets"]:
if "harness" in target.get("required-features", []):
for kind in target_kinds.intersection(target["kind"]):
targets.add((pkg["name"], kind, target["name"]))
test_dir = Path(pkg["manifest_path"]).parent / "tests"
for path in test_dir.rglob("*.rs"):
if any(
harness_feature.search(cfg) and not test_alternative.search(cfg)
for cfg in cfg_attribute.findall(path.read_text(encoding="utf-8"))
):
integration_tests.add(path.relative_to(repo_root).as_posix())
expected_targets = {
("playground", "bin", "bs-harness"),
("affine-desktop", "bin", "desktop-harness"),
("affine-mobile", "bin", "mobile-harness"),
}
expected_integration_tests = {
"packages/ui/ui/tests/bidi_multiline_controls.rs",
"packages/ui/ui/tests/metal_atlas_fence.rs",
"packages/ui/ui/tests/touch_dispatch.rs",
}
if targets != expected_targets or integration_tests != expected_integration_tests:
for label, actual, expected in (
("Cargo targets", targets, expected_targets),
("integration test files", integration_tests, expected_integration_tests),
):
for entry in sorted(actual - expected):
print(f"ERROR: Added harness {label}: {entry}")
for entry in sorted(expected - actual):
print(f"ERROR: Removed harness {label}: {entry}")
raise SystemExit("Update the harness test commands in .github/workflows/native-playground.yml and these lists.")
PY
echo "==> Checking four-domain toolchain, rustfmt, and AGENTS.md alignment and legacy guards"
CLIENT_TREES=(
"$REPO_ROOT/packages/frontend"
"$REPO_ROOT/packages/ui"
"$REPO_ROOT/blocksuite/crates"
"$REPO_ROOT/packages/common/store"
)
for tree in "${CLIENT_TREES[@]}"; do
[ -d "$tree" ] || fail "Missing client domain directory $tree"
[ -f "$tree/rust-toolchain.toml" ] || fail "Missing $tree/rust-toolchain.toml"
[ -f "$tree/rustfmt.toml" ] || fail "Missing $tree/rustfmt.toml"
[ -f "$tree/AGENTS.md" ] || fail "Missing $tree/AGENTS.md"
[ -f "$tree/CLAUDE.md" ] || fail "Missing $tree/CLAUDE.md"
cmp -s "$ROOT/rust-toolchain.toml" "$tree/rust-toolchain.toml" \
|| fail "$tree/rust-toolchain.toml differs from packages/frontend/rust-toolchain.toml"
cmp -s "$ROOT/rustfmt.toml" "$tree/rustfmt.toml" \
|| fail "$tree/rustfmt.toml differs from packages/frontend/rustfmt.toml"
done
for legacy_dir in \
"$REPO_ROOT/packages/frontend/native" \
"$REPO_ROOT/packages/frontend/mobile-native" \
"$REPO_ROOT/packages/frontend/apps"; do
[ -f "$legacy_dir/rust-toolchain.toml" ] || fail "Missing legacy guard $legacy_dir/rust-toolchain.toml"
cmp -s "$REPO_ROOT/rust-toolchain.toml" "$legacy_dir/rust-toolchain.toml" \
|| fail "$legacy_dir/rust-toolchain.toml must match root rust-toolchain.toml"
done
for legacy_fmt_dir in \
"$REPO_ROOT/packages/frontend/native" \
"$REPO_ROOT/packages/frontend/mobile-native"; do
[ -f "$legacy_fmt_dir/rustfmt.toml" ] || fail "Missing legacy guard $legacy_fmt_dir/rustfmt.toml"
cmp -s "$REPO_ROOT/rustfmt.toml" "$legacy_fmt_dir/rustfmt.toml" \
|| fail "$legacy_fmt_dir/rustfmt.toml must match root rustfmt.toml"
done
echo "==> Checking Cargo workspace_root resolution for client and legacy crates"
EXPECTED_CLIENT_ROOT="$(cd "$ROOT" && pwd -P)"
EXPECTED_REPO_ROOT="$(cd "$REPO_ROOT" && pwd -P)"
while IFS=$'\t' read -r pkg_name member_dir; do
resolved_root=$(
cd "$member_dir" && CARGO_ENCODED_RUSTFLAGS="" cargo metadata --locked --no-deps --format-version 1 \
| python3 -c "import json, os, sys; print(os.path.realpath(json.load(sys.stdin)['workspace_root']))"
)
if [ "$resolved_root" != "$EXPECTED_CLIENT_ROOT" ]; then
fail "Client crate $pkg_name ($member_dir) resolved workspace_root=$resolved_root, expected $EXPECTED_CLIENT_ROOT"
fi
done <<< "$MEMBER_LINES"
for legacy_crate in \
"$REPO_ROOT" \
"$REPO_ROOT/packages/frontend/native" \
"$REPO_ROOT/packages/frontend/mobile-native" \
"$REPO_ROOT/packages/frontend/native/nbstore" \
"$REPO_ROOT/packages/frontend/native/schema" \
"$REPO_ROOT/packages/frontend/native/sqlite_v1"; do
resolved_root=$(
cd "$legacy_crate" && CARGO_ENCODED_RUSTFLAGS="" cargo metadata --locked --no-deps --format-version 1 \
| python3 -c "import json, os, sys; print(os.path.realpath(json.load(sys.stdin)['workspace_root']))"
)
if [ "$resolved_root" != "$EXPECTED_REPO_ROOT" ]; then
fail "Legacy crate ($legacy_crate) resolved workspace_root=$resolved_root, expected $EXPECTED_REPO_ROOT"
fi
done
echo "==> Checking four-domain acyclic dependency rules (default-deny DAG)"
WORKSPACE_JSON="$WORKSPACE_JSON" REPO_ROOT="$REPO_ROOT" python3 - <<'PY'
import json
import os
from pathlib import Path
UI_ALL = {"packages/ui/tokens", "packages/ui/ui", "packages/ui/kit"}
BS_LOWER = {"blocksuite/crates/doc", "blocksuite/crates/preview", "blocksuite/crates/editor"}
ALLOWED_DEPS = {
"packages/ui/tokens": set(),
"packages/ui/ui": {"packages/ui/tokens"},
"packages/ui/kit": {"packages/ui/tokens", "packages/ui/ui"},
"blocksuite/crates/doc": set(),
"blocksuite/crates/preview": {"packages/ui/tokens", "packages/ui/ui", "blocksuite/crates/doc"},
"blocksuite/crates/editor": UI_ALL | {"blocksuite/crates/doc", "blocksuite/crates/preview"},
"blocksuite/crates/playground": UI_ALL | BS_LOWER,
"blocksuite/crates/oracle": UI_ALL | BS_LOWER,
"packages/common/store": {"blocksuite/crates/doc"},
"packages/frontend/legacy-import": {"blocksuite/crates/doc", "packages/common/store"},
"packages/frontend/client": UI_ALL | BS_LOWER | {
"packages/common/store",
"packages/frontend/legacy-import",
},
"packages/frontend/mobile": UI_ALL | BS_LOWER | {
"blocksuite/crates/playground",
"packages/common/store",
"packages/frontend/legacy-import",
"packages/frontend/client",
},
"packages/frontend/desktop": UI_ALL | BS_LOWER | {
"blocksuite/crates/playground",
"packages/common/store",
"packages/frontend/legacy-import",
"packages/frontend/client",
},
}
HOST_ALLOWED = UI_ALL | BS_LOWER | {
"blocksuite/crates/playground",
"packages/common/store",
"packages/frontend/legacy-import",
"packages/frontend/client",
"packages/frontend/mobile",
"packages/frontend/desktop",
}
def is_allowed_edge(src_rel: str, dep_rel: str) -> bool:
if src_rel == dep_rel:
return True
if src_rel.startswith("packages/frontend/hosts/"):
parts = src_rel.split("/")
if len(parts) == 4 and parts[3]:
return dep_rel in HOST_ALLOWED
return False
allowed = ALLOWED_DEPS.get(src_rel)
if allowed is None:
return False
return dep_rel in allowed
POSITIVE_FIXTURES = [
("packages/ui/kit", "packages/ui/ui"),
("blocksuite/crates/editor", "blocksuite/crates/preview"),
("blocksuite/crates/playground", "blocksuite/crates/doc"),
("packages/common/store", "blocksuite/crates/doc"),
("packages/frontend/mobile", "packages/frontend/client"),
("packages/frontend/hosts/ios", "packages/frontend/mobile"),
]
NEGATIVE_FIXTURES = [
("packages/ui/ui", "packages/ui/kit"),
("packages/ui/kit", "blocksuite/crates/doc"),
("blocksuite/crates/doc", "blocksuite/crates/preview"),
("blocksuite/crates/preview", "blocksuite/crates/editor"),
("packages/common/store", "blocksuite/crates/editor"),
("packages/common/store", "packages/ui/ui"),
("packages/frontend/client", "packages/frontend/mobile"),
("packages/frontend/mobile", "packages/frontend/hosts/ios"),
("packages/frontend/mobile", "packages/frontend/desktop"),
("packages/frontend/hosts/ios", "packages/frontend/hosts/android"),
("packages/frontend/unregistered", "packages/ui/ui"),
]
for s_rel, d_rel in POSITIVE_FIXTURES:
if not is_allowed_edge(s_rel, d_rel):
raise SystemExit(f"DAG self-test failed: expected {s_rel} -> {d_rel} to be allowed")
for s_rel, d_rel in NEGATIVE_FIXTURES:
if is_allowed_edge(s_rel, d_rel):
raise SystemExit(f"DAG self-test failed: expected {s_rel} -> {d_rel} to be rejected")
meta = json.loads(os.environ["WORKSPACE_JSON"])
repo_root = Path(os.environ["REPO_ROOT"]).resolve()
ws_ids = set(meta["workspace_members"])
pkg_rel = {}
for pkg in meta["packages"]:
if pkg["id"] in ws_ids:
rel_dir = Path(pkg["manifest_path"]).resolve().parent.relative_to(repo_root).as_posix()
pkg_rel[pkg["name"]] = rel_dir
errors = []
for pkg in meta["packages"]:
if pkg["id"] not in ws_ids:
continue
src_name = pkg["name"]
src_rel = pkg_rel[src_name]
if src_rel not in ALLOWED_DEPS and not (
src_rel.startswith("packages/frontend/hosts/") and len(src_rel.split("/")) == 4
):
errors.append(
f"{src_name} ({src_rel}) is not registered in check-invariants.sh ALLOWED_DEPS"
)
continue
for dep in pkg.get("dependencies", []):
dep_name = dep["name"]
if dep_name not in pkg_rel:
continue
dep_rel = pkg_rel[dep_name]
if not is_allowed_edge(src_rel, dep_rel):
errors.append(f"{src_name} ({src_rel}) must not depend on {dep_name} ({dep_rel})")
if errors:
for e in errors:
print(f"ERROR: {e}")
raise SystemExit(1)
print("Four-domain default-deny dependency DAG check (with self-tests) passed.")
PY
echo "==> Checking active rustup toolchain for legacy (1.97.1) and client (1.98.1) directories"
command -v rustup >/dev/null 2>&1 || fail "rustup is required to verify active toolchains"
ROOT_CHANNEL=$(awk -F'"' '/^channel[[:space:]]*=/{print $2; exit}' "$REPO_ROOT/rust-toolchain.toml")
CLIENT_CHANNEL=$(awk -F'"' '/^channel[[:space:]]*=/{print $2; exit}' "$ROOT/rust-toolchain.toml")
for legacy_tc_dir in \
"$REPO_ROOT/packages/frontend/native" \
"$REPO_ROOT/packages/frontend/mobile-native" \
"$REPO_ROOT/packages/frontend/apps/ios/App" \
"$REPO_ROOT/packages/frontend/apps/android/App"; do
active_tc=$(cd "$legacy_tc_dir" && env -u RUSTUP_TOOLCHAIN rustup show active-toolchain) \
|| fail "rustup show active-toolchain failed in $legacy_tc_dir"
if [[ "$active_tc" != *"$ROOT_CHANNEL"* ]]; then
fail "Expected active rustup toolchain in $legacy_tc_dir to match $ROOT_CHANNEL, got: $active_tc"
fi
done
for client_tc_dir in "${CLIENT_TREES[@]}"; do
active_tc=$(cd "$client_tc_dir" && env -u RUSTUP_TOOLCHAIN rustup show active-toolchain) \
|| fail "rustup show active-toolchain failed in $client_tc_dir"
if [[ "$active_tc" != *"$CLIENT_CHANNEL"* ]]; then
fail "Expected active rustup toolchain in $client_tc_dir to match $CLIENT_CHANNEL, got: $active_tc"
fi
done
echo "==> Checking zero internal proc-macro crates"
if grep -rn 'proc-macro\s*=\s*true' "$ROOT/Cargo.toml" 2>/dev/null; then
fail "Internal proc-macro crates are forbidden in the client workspace"
fi
while IFS=$'\t' read -r pkg_name member_dir; do
if grep -rn 'proc-macro\s*=\s*true' "$member_dir/Cargo.toml" 2>/dev/null; then
fail "Internal proc-macro crates are forbidden ($pkg_name)"
fi
done <<< "$MEMBER_LINES"
UI_DIR="$REPO_ROOT/packages/ui/ui"
UI_KIT_DIR="$REPO_ROOT/packages/ui/kit"
UI_TOKENS_DIR="$REPO_ROOT/packages/ui/tokens"
DOC_DIR="$REPO_ROOT/blocksuite/crates/doc"
EDITOR_DIR="$REPO_ROOT/blocksuite/crates/editor"
PLAYGROUND_DIR="$REPO_ROOT/blocksuite/crates/playground"
echo "==> Checking packages/ui/tokens self-contained isolation (no frontend/ or blocksuite)"
if grep -rniE 'frontend/|blocksuite' "$UI_TOKENS_DIR/src" 2>/dev/null; then
fail "packages/ui/tokens/src must stay self-contained without frontend/ or blocksuite references"
fi
LEGACY_FONTS_DIR="$REPO_ROOT/packages/frontend/component/src/fonts"
if [ -d "$LEGACY_FONTS_DIR" ]; then
for rel in \
"inter/Inter-VariableFont_slnt,wght.ttf" \
"ibm-plex-mono/IBMPlexMono-Regular.ttf" \
"ibm-plex-mono/IBMPlexMono-Bold.ttf" \
"ibm-plex-mono/IBMPlexMono-Italic.ttf" \
"ibm-plex-mono/IBMPlexMono-BoldItalic.ttf"; do
if [ -f "$LEGACY_FONTS_DIR/$rel" ]; then
cmp -s "$UI_TOKENS_DIR/fonts/$rel" "$LEGACY_FONTS_DIR/$rel" \
|| fail "packages/ui/tokens/fonts/$rel drifted from $LEGACY_FONTS_DIR/$rel"
fi
done
fi
echo "==> Checking packages/ui/ui domain isolation (no blocksuite/affine words)"
if grep -rniE '\b(blocksuite|affine)\b' "$UI_DIR/src" "$UI_DIR/Cargo.toml" 2>/dev/null; then
fail "packages/ui/ui must not reference BlockSuite or AFFiNE domain terms"
fi
echo "==> Checking packages/ui/kit domain isolation and logical-geometry guard"
if grep -rniE '\b(blocksuite|affine)\b' "$UI_KIT_DIR/src" "$UI_KIT_DIR/Cargo.toml" 2>/dev/null; then
fail "packages/ui/kit must not reference BlockSuite or AFFiNE domain terms"
fi
if grep -rnE '\.(left|right|pl|pr|ml|mr|border_l|border_r)(_[0-9a-z_]+)?\s*\(' "$UI_KIT_DIR/src" --include='*.rs' 2>/dev/null; then
fail "packages/ui/kit/src must use logical inline geometry instead of physical left/right layout helpers"
fi
echo "==> Checking blocksuite/crates/doc GUI isolation and forbid(unsafe_code)"
if grep -rnE '^\s*(ui|wgpu|objc2|web-sys)\b' "$DOC_DIR/Cargo.toml" 2>/dev/null; then
fail "blocksuite/crates/doc must not depend on GUI/platform crates (ui, wgpu, objc2, web-sys)"
fi
if ! grep -q '#!\[forbid(unsafe_code)\]' "$DOC_DIR/src/lib.rs"; then
fail "blocksuite/crates/doc/src/lib.rs must declare #![forbid(unsafe_code)]"
fi
echo "==> Checking blocksuite/crates/preview zero host-font scanning"
if grep -rn 'load_system_fonts' "$REPO_ROOT/blocksuite/crates/preview/src" 2>/dev/null; then
fail "load_system_fonts is forbidden in blocksuite/crates/preview/src"
fi
echo "==> Checking no wall-clock calls outside packages/ui/ui/src/platform"
WALL_CLOCK_HITS=""
while IFS=$'\t' read -r _pkg_name member_dir; do
if [ -d "$member_dir/src" ]; then
hits=$(
grep -rnE '(Instant::now|SystemTime::now|Zoned::now|Timestamp::now)\s*\(' "$member_dir/src" \
--include='*.rs' \
| grep -v "^$UI_DIR/src/platform/" \
|| true
)
if [ -n "$hits" ]; then
WALL_CLOCK_HITS="${WALL_CLOCK_HITS}${hits}"$'\n'
fi
fi
done <<< "$MEMBER_LINES"
if [ -n "$WALL_CLOCK_HITS" ]; then
echo "$WALL_CLOCK_HITS" >&2
fail "Instant::now() / SystemTime::now() / Zoned::now() / Timestamp::now() is forbidden outside packages/ui/ui/src/platform/"
fi
echo "==> Checking zero tester branches inside shipping editor, playground, desktop, and mobile view modules"
DESKTOP_DIR="$REPO_ROOT/packages/frontend/desktop"
MOBILE_DIR="$REPO_ROOT/packages/frontend/mobile"
for view_dir in "$EDITOR_DIR" "$PLAYGROUND_DIR" "$DESKTOP_DIR" "$MOBILE_DIR"; do
if [ ! -d "$view_dir/src" ]; then
continue
fi
if grep -rn 'is_headless' "$view_dir/src" 2>/dev/null; then
fail "is_headless branches are forbidden in $view_dir/src"
fi
done
python3 - "$EDITOR_DIR" "$PLAYGROUND_DIR" "$DESKTOP_DIR" "$MOBILE_DIR" <<'PY'
from __future__ import annotations
import re
import sys
from pathlib import Path
CFG_START = re.compile(r"#\s*(?P<inner>!\s*)?\[\s*cfg\s*\(|\bcfg\s*!\s*\(")
HARNESS = re.compile(r'\bfeature\s*=\s*"harness"')
TEST = re.compile(r"\btest\b")
MOD_ITEM = re.compile(r"\s*(?:pub(?:\s*\([^)]*\))?\s+)?mod\s+(?:r#)?\w+\s*([{;])")
ATTR_START = re.compile(r"\s*#\s*\[")
ATTR_END = re.compile(r"\s*\]")
LEXEME = re.compile(
r'//[^\n]*|/\*|(?<!\w)(?:br|cr|r)(?P<hashes>\#*)"'
r'|"(?:\\[\s\S]|[^"\\])*"'
r"|'(?:\\(?:x[0-9a-fA-F]{2}|u\{[0-9a-fA-F_]+\}|[^\n])|[^'\\\n])'"
)
BLOCK_COMMENT = re.compile(r"/\*|\*/")
MASK = re.compile(r"[^\n]")
def rust_code(src: str) -> str:
"""Mask comments and literals without changing source offsets."""
parts = []
pos = 0
while token := LEXEME.search(src, pos):
start, end = token.span()
parts.append(src[pos:start])
text = token.group()
replacement = ""
if text == "/*":
depth = 1
for delimiter in BLOCK_COMMENT.finditer(src, end):
depth += 1 if delimiter.group() == "/*" else -1
if depth == 0:
end = delimiter.end()
break
else:
end = len(src)
elif not text.startswith("//"):
# Keep the feature name so cfg checks can still see it.
hashes = token.group("hashes")
if hashes is not None:
close = '"' + hashes
close_at = src.find(close, end)
if close_at != -1 and src[end:close_at] == "harness" and text.startswith("r"):
replacement = '"harness"'
end = len(src) if close_at == -1 else close_at + len(close)
elif text == '"harness"':
replacement = text
if not replacement:
replacement = "_"
parts.append(replacement + MASK.sub(" ", src[start + len(replacement):end]))
pos = end
parts.append(src[pos:])
return "".join(parts)
def matching_delimiter(code: str, start: int, opening: str, closing: str) -> int:
depth = 0
for i in range(start, len(code)):
if code[i] == opening:
depth += 1
elif code[i] == closing:
depth -= 1
if depth == 0:
return i
return len(code)
def module_item(code: str, after_attr: int) -> re.Match | None:
while attr := ATTR_START.match(code, after_attr):
after_attr = matching_delimiter(code, attr.end() - 1, "[", "]") + 1
return MOD_ITEM.match(code, after_attr)
def tester_branches(src: str, *, playground_lib: bool):
code = rust_code(src)
pos = 0
while match := CFG_START.search(code, pos):
pos = match.end()
end = matching_delimiter(code, pos - 1, "(", ")")
pred = " ".join(code[pos:end].split())
is_macro = match.group().startswith("cfg")
if HARNESS.search(pred):
yield match.start(), end + 1
continue
if not TEST.search(pred):
continue
attr_end = None if is_macro or match.group("inner") else ATTR_END.match(code, end + 1)
mod = module_item(code, attr_end.end()) if attr_end else None
if not is_macro and pred.removesuffix(",").rstrip() == "test":
if mod and mod.group(1) == "{":
pos = matching_delimiter(code, mod.end() - 1, "{", "}") + 1
continue
# The same PDF module serves Wasm and native unit tests. Scan its source as usual.
if (playground_lib and mod and attr_end and mod.start() == attr_end.end()
and src[pos:end] == 'any(target_family = "wasm", test)'
and code[mod.start():mod.end()].strip() == "mod wasm_pdf_state;"):
continue
if is_macro or re.match(r"any\s*\(", pred) or (mod and mod.group(1) == ";"):
yield match.start(), end + 1
src_dirs = [Path(view_dir) / "src" for view_dir in sys.argv[1:]]
for src_dir in src_dirs:
if not src_dir.is_dir():
sys.exit(f"ERROR: Missing required view source directory: {src_dir}")
hits = []
for src_dir in src_dirs:
for path in sorted(src_dir.rglob("*.rs")):
rel = path.relative_to(src_dir).as_posix()
if rel.startswith("bin/"):
continue
src = path.read_text(encoding="utf-8")
playground_lib = src_dir == src_dirs[1] and rel == "lib.rs"
for start, end in tester_branches(src, playground_lib=playground_lib):
# The harness imports this fixture from the editor.
if (src_dir == src_dirs[0] and rel == "rich_text/mod.rs"
and src.startswith('#[cfg(feature = "harness")]\npub fn sample_paragraph(', start)):
continue
line = src.count("\n", 0, start) + 1
hits.append(f"{path}:{line}: {' '.join(src[start:end].split())}")
if hits:
print("\n".join(hits), file=sys.stderr)
print("ERROR: Inline harness/test cfg branches are forbidden in shipping view modules", file=sys.stderr)
sys.exit(1)
PY
echo "==> Checking TOPBAR_HEIGHT single-source check in blocksuite/crates/playground/src"
PLAYGROUND_DIR="$PLAYGROUND_DIR" python3 - <<'PY'
import os
import re
import sys
from pathlib import Path
root = Path(os.environ["PLAYGROUND_DIR"]) / "src"
def strip_cfg_test(text: str) -> list[str]:
lines = text.splitlines()
out = []
i = 0
n = len(lines)
while i < n:
s = lines[i].strip()
if s == "#[cfg(test)]" and i + 1 < n and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()):
depth = 0
started = False
out.append("")
i += 1
while i < n:
line = lines[i]
if "{" in line:
started = True
depth += line.count("{") - line.count("}")
out.append("")
i += 1
if started and depth <= 0:
break
continue
out.append(lines[i])
i += 1
return out
errors = []
for p in sorted(root.rglob("*.rs")):
rel = p.relative_to(root).as_posix()
if rel.startswith("bin/") or "test" in p.name:
continue
for lineno, line in enumerate(strip_cfg_test(p.read_text(encoding="utf-8")), 1):
code = line.split("//", 1)[0]
if "TOPBAR_HEIGHT" not in code:
continue
if rel == "lib.rs" and "pub use blocksuite_editor::" in code or (rel == "lib.rs" and lineno <= 12):
continue
if rel == "embedded.rs":
continue
errors.append(f"{rel}:{lineno}: direct TOPBAR_HEIGHT reference outside embedded.rs::topbar_height(): {line.strip()}")
if errors:
for e in errors:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
print("Playground TOPBAR_HEIGHT single-source check passed.")
PY
echo "==> Checking Rust module structure, visibility, orphaned files, and per-file LOC"
MEMBER_LINES="$MEMBER_LINES" python3 - <<'PY'
import os
import re
import sys
from pathlib import Path
errors = []
roots = []
for line in os.environ["MEMBER_LINES"].splitlines():
if not line.strip():
continue
name, dir_path = line.split("\t", 1)
if name == "ui":
continue
src_dir = Path(dir_path) / "src"
if src_dir.is_dir():
roots.append(src_dir)
if len(roots) < 2:
print(f"ERROR: Expected at least 2 non-vendored client crate src roots, found {roots}", file=sys.stderr)
sys.exit(1)
def strip_cfg_test_mods(src: str) -> str:
"""Remove `#[cfg(test)] mod <name> { ... }` blocks while preserving line numbers."""
lines = src.splitlines()
out = []
i = 0
n = len(lines)
while i < n:
s = lines[i].strip()
if s == "#[cfg(test)]" and i + 1 < n and re.match(r"^(pub(\([^)]*\))?\s+)?mod\s+\w+\s*\{", lines[i + 1].strip()):
depth = 0
started = False
out.append("<TEST>")
i += 1
while i < n:
line = lines[i]
if "{" in line:
started = True
depth += line.count("{") - line.count("}")
out.append("<TEST>")
i += 1
if started and depth <= 0:
break
continue
out.append(lines[i])
i += 1
return "\n".join(out)
for src_root in roots:
rs_files = sorted(src_root.rglob("*.rs"))
declared_modules = set()
for entry in ("lib.rs", "main.rs"):
if (src_root / entry).exists():
declared_modules.add((src_root / entry).resolve())
for bin_file in (src_root / "bin").glob("*.rs") if (src_root / "bin").exists() else []:
declared_modules.add(bin_file.resolve())
for bin_main in (src_root / "bin").glob("*/main.rs") if (src_root / "bin").exists() else []:
declared_modules.add(bin_main.resolve())
mod_decl_re = re.compile(r"^\s*(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*;")
for p in rs_files:
text = p.read_text(encoding="utf-8")
parent = p.parent
for line in text.splitlines():
m = mod_decl_re.match(line)
if m:
mod_name = m.group(1)
base_dir = parent if p.name in ("lib.rs", "main.rs", "mod.rs") else parent / p.stem
cand_file = base_dir / f"{mod_name}.rs"
cand_mod = base_dir / mod_name / "mod.rs"
if cand_file.exists():
declared_modules.add(cand_file.resolve())
if cand_mod.exists():
declared_modules.add(cand_mod.resolve())
if p.name not in ("lib.rs", "main.rs", "mod.rs") and (parent / p.stem).is_dir():
errors.append(f"{p}: coexists beside directory {parent / p.stem}/; move into {parent / p.stem}/mod.rs")
non_test = strip_cfg_test_mods(text)
non_test_lines = non_test.splitlines()
for lineno, line in enumerate(non_test_lines, 1):
if "super::super::" in line:
errors.append(f"{p}:{lineno}: forbidden `super::super::` outside `mod tests`")
rel = p.relative_to(src_root)
if len(rel.parts) >= 2 and p.name != "mod.rs" and rel.parts[0] != "bin":
parent_mod = rel.parts[0]
pat = f"crate::{parent_mod}::"
for lineno, line in enumerate(non_test_lines, 1):
if pat in line:
errors.append(f"{p}:{lineno}: use `super::` instead of `{pat}` inside submodule")
actual_non_test = len([1 for orig, stripped in zip(text.splitlines(), non_test_lines) if orig == stripped])
if actual_non_test > 800:
errors.append(f"{p}: {actual_non_test} non-test lines exceeds ceiling of 800")
for p in rs_files:
if p.resolve() not in declared_modules:
errors.append(f"{p}: orphaned .rs file not declared by any `mod <name>;`")
if errors:
for e in errors:
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1)
print("Rust module structure & LOC checks passed.")
PY
echo "==> Checking packages/ui/ui SLOC ceiling"
UI_SLOC_CEILING=74268
read -r UI_RAW_LOC UI_SLOC < <(UI_DIR="$UI_DIR" python3 - <<'PY'
import os
from pathlib import Path
raw = sloc = 0
for p in Path(os.environ["UI_DIR"], "src").rglob("*.rs"):
for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
raw += 1
s = line.strip()
if s and not s.startswith("//"):
sloc += 1
print(f"{raw} {sloc}")
PY
)
echo "packages/ui/ui/src raw lines: $UI_RAW_LOC, code lines (non-blank, non-comment): $UI_SLOC (ceiling: $UI_SLOC_CEILING)"
if [ "$UI_SLOC" -gt "$UI_SLOC_CEILING" ]; then
fail "packages/ui/ui/src SLOC ($UI_SLOC) exceeds ceiling ($UI_SLOC_CEILING)"
fi
echo "==> Checking the playground Wasm font dependencies"
SKRIFA_VERSIONS=$(cargo tree --locked --target wasm32-unknown-unknown -p playground -e normal --prefix none \
| awk '$1 == "skrifa" { print $2 }' | sort -u)
[[ -n "$SKRIFA_VERSIONS" && "$SKRIFA_VERSIONS" != *$'\n'* ]] \
|| fail "Expected one skrifa version in the playground Wasm dependencies, found: $SKRIFA_VERSIONS"
echo "==> Checking workflow YAML validity"
if [ -f "$REPO_ROOT/.github/workflows/native-playground.yml" ] && [ -f "$REPO_ROOT/.github/workflows/build-test.yml" ]; then
if python3 -c "import yaml" 2>/dev/null; then
python3 -c "
import yaml, sys
for p in sys.argv[1:]:
with open(p) as f:
yaml.safe_load(f)
print('YAML OK:', p)
" "$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml"
elif command -v ruby >/dev/null 2>&1; then
ruby -ryaml -e 'ARGV.each { |p| YAML.load_file(p); puts "YAML OK: #{p}" }' \
"$REPO_ROOT/.github/workflows/build-test.yml" "$REPO_ROOT/.github/workflows/native-playground.yml"
else
fail "Neither python3-yaml nor ruby is available to validate workflow YAML files"
fi
fi
echo "==> Checking CARGO_ENCODED_RUSTFLAGS isolation (no leaked root NAPI linker flags)"
# The dependency-free `ui-tokens` test executable links quickly from a cold cache.
if ! LINK_LOG=$(CARGO_ENCODED_RUSTFLAGS="" cargo rustc -p ui-tokens --lib --profile test -- -C metadata="linkcheck-$$" --print link-args 2>&1); then
echo "$LINK_LOG" >&2
fail "cargo rustc link-args check failed"
fi
if ! grep -qE '(cc|clang|gcc|ld|lld|"[^"]*ui_tokens|ui_tokens)' <<<"$LINK_LOG"; then
echo "$LINK_LOG" >&2
fail "cargo rustc did not emit a linker invocation (cache bypass failed)"
fi
if grep -qE '(-all_load|-undefined[ ,]+dynamic_lookup|-z[ ,]+nodelete)' <<<"$LINK_LOG"; then
echo "$LINK_LOG" >&2
fail "Detected leaked root NAPI linker flags in rustc invocation"
fi
echo "==> Checking snapshot prefix liveness"
node "$SCRIPT_DIR/check-snapshot-prefixes.mjs" --source-only
echo "All static invariants passed."
@@ -0,0 +1,856 @@
#!/usr/bin/env node
// @ts-check
/**
* Verifies that production Wasm bundles (`playground_bg.wasm`,
* `affine_desktop_bg.wasm`) contain zero harness snapshot ID prefixes in
* WebAssembly Section 11 (Data).
*
* Modes:
* node scripts/check-snapshot-prefixes.mjs --source-only
* node scripts/check-snapshot-prefixes.mjs <path/to/bundle_bg.wasm>...
*/
import { createHash } from 'node:crypto';
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { basename, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const SCRIPT_DIR = fileURLToPath(new URL('.', import.meta.url));
export const DEFAULT_REPO_ROOT = resolve(SCRIPT_DIR, '../../..');
export const ZERO_IN_PRODUCTION = Object.freeze([
'edgeless.surface.',
'edgeless.note.',
'edgeless.frame.',
'edgeless.text.',
'edgeless.block.',
'page.presence.',
'page.block.',
'overlay.slash_menu.item.',
'overlay.slash_menu.group.',
'overlay.linked_doc_menu.item.',
'overlay.linked_doc_menu.group.',
'overlay.linked_doc_menu.journal.',
'overlay.pdf_viewer.page.',
'overlay.pdf_viewer.thumb.',
'overlay.attachment_toolbar.',
'overlay.code_more_menu.',
'overlay.code_lang_picker.item.',
'overlay.bookmark_toolbar',
'overlay.embed_toolbar',
'overlay.format_toolbar.',
'overlay.image_toolbar.',
'overlay.link_popup',
'overlay.callout_toolbar',
'overlay.callout_icon_picker.',
'overlay.table_toolbar.axis_menu',
'overlay.table_col_resize.',
'overlay.table_hover.',
'overlay.page_scrollbar',
'page.table_cell_focus',
'chrome.edgeless_element_toolbar.',
'chrome.edgeless_toolbar.',
'chrome.edgeless_zoom.',
'edgeless.label_format.',
'edgeless.mindmap.toggle.',
'edgeless.handle.rotate_',
'edgeless.selection_box',
'edgeless.remote_cursor.',
'edgeless.remote_selection.',
'chrome.presence.',
'overlay.context_menu.',
'overlay.context_menu',
'overlay.image_lightbox.',
'overlay.image_lightbox',
'overlay.doc_panel.',
'overlay.doc_panel',
'overlay.database_record_sheet.',
'overlay.database_record_sheet',
'desktop.list.doc.',
'desktop.trash.row.',
'desktop.outline.rail.heading.',
'desktop.inspector.heading.',
'desktop.qs.doc.',
'desktop.qs.cmd.',
'desktop.qs.collection.',
'desktop.qs.tag.',
'desktop.sidebar.workspace.',
'desktop.explorer.doc_menu.',
'desktop.outline.rail.tick.',
'desktop.outline.rail.open.',
'desktop.inspector.backlink.',
'desktop.trash.restore.',
'desktop.trash.delete.',
'desktop.inspector.journal.day.',
'desktop.app_tabs.tab.',
'desktop.split.resize.',
'desktop.explorer.group.',
'desktop.outline.rail.',
'desktop.sidebar.sec.',
'desktop.sidebar.fav.',
'desktop.sidebar.fdoc.',
'desktop.sidebar.col_doc.',
'desktop.sidebar.tag_doc.',
'desktop.sidebar.folder.',
'desktop.sidebar.col.',
'desktop.sidebar.tag.',
'desktop.trash.open.',
'desktop.sidebar.resize',
'desktop.split.resize',
'desktop.inspector.journal.previous',
'desktop.inspector.journal.today',
'desktop.inspector.journal.next',
'chrome.doc_panel_toggle',
'chrome.mode_switcher.edgeless',
'chrome.mode_switcher.indicator',
'chrome.mode_switcher.page',
'chrome.nav_back',
'chrome.theme_toggle',
'chrome.topbar',
'desktop.explorer.favorite.',
'desktop.explorer.heading',
'desktop.explorer.menu.',
'desktop.explorer.selected',
'desktop.explorer.tag_switch.',
'desktop.header.trash.body',
'desktop.inspector.frame.item.',
'desktop.inspector.journal.activity.empty',
'desktop.inspector.journal.conflict.more',
'desktop.inspector.journal.conflict.trash.',
'desktop.inspector.journal.dot.',
'desktop.inspector.journal.tab.',
'desktop.pane.0.tab.',
'desktop.peek.control.tooltip',
'desktop.settings.font.size.thumb',
'desktop.sidebar.node.add',
'desktop.sidebar.node.more',
'desktop.trash.confirm.body',
'desktop.trash.confirm.description',
'desktop.trash_prompt.body',
'desktop.trash_prompt.description',
'edgeless.auto_complete.ghost_preview',
'edgeless.caption_caret',
'edgeless.caption_focus',
'edgeless.frame_drop_highlight',
'edgeless.inline_edit',
'edgeless.marquee',
'edgeless.note_slicer',
'edgeless.snap_guideline',
'edgeless.transform_hud',
'overlay.add_block_button',
'overlay.block_drag_ghost',
'overlay.calendar_day_hover',
'overlay.calendar_day_new_row',
'overlay.calendar_drag_ghost',
'overlay.calendar_drop_settle',
'overlay.calendar_event_hover',
'overlay.calendar_event_resize_',
'overlay.code_lang_picker.empty',
'overlay.code_lang_picker.scrollbar',
'overlay.code_lang_picker.search',
'overlay.database_popover',
'overlay.drag_handle',
'overlay.drop_indicator',
'overlay.equation_editor.done',
'overlay.equation_editor.input',
'overlay.kanban_card_hover',
'overlay.kanban_drag_ghost',
'overlay.kanban_drag_placeholder',
'overlay.kanban_drop_settle',
'overlay.kanban_lane_footer_add',
'overlay.keyboard_toolbar.group.',
'overlay.keyboard_toolbar.panel.',
'overlay.linked_doc_menu.create',
'overlay.linked_doc_menu.input_mask',
'overlay.linked_doc_menu.more',
'overlay.page_marquee',
'overlay.pdf_viewer.close',
'overlay.pdf_viewer.filename',
'overlay.pdf_viewer.header_title',
'overlay.pdf_viewer.indicator',
'overlay.pdf_viewer.status',
'overlay.pdf_viewer.thumbnails_toggle',
'overlay.pdf_viewer.zoom_in',
'overlay.pdf_viewer.zoom_out',
'overlay.pdf_viewer.zoom_reset',
'overlay.slash_menu.preview',
'overlay.slash_menu.query',
'overlay.table_column_drag_ghost',
'overlay.table_header_hover',
'overlay.table_resize_guide',
'overlay.table_row_drag_ghost',
'overlay.table_row_drag_handle',
'overlay.table_toolbar.axis_selection',
'overlay.table_toolbar.more',
'overlay.toolbar_tooltip',
'overlay.touch_selection_menu',
'page.block_placeholder',
'page.block_selection',
'page.caption_caret',
'page.caption_focus',
'page.database_cell_focus',
'page.local_caret',
'page.selection',
'page.status',
'page.table_area_selection',
'page.table_cell_caret',
'.attachment_card',
'.bookmark_card',
'.builtin.',
'.custom.menu.',
'.embed_activate',
'.embed_card',
'.embed_shield',
'.highlight_menu.background.',
'.hscrollbar',
'.image_card',
'.journal_next',
'.journal_previous',
'.journal_week',
'.links.',
'.tag.attached.',
'.tag.create',
'.tag.option.',
'.toolbar.copy',
'.toolbar.language',
'desktop.collection_editor.count',
'desktop.collection_editor.doc.',
'desktop.collection_editor.filter.remove.',
'desktop.collection_editor.include.remove.',
'desktop.collection_editor.menu.item.',
'desktop.collection_editor.rules.tips',
'desktop.collection_editor.selected',
'desktop.header.dialog.close.icon',
'desktop.header.info.backlink.',
'desktop.header.info.outgoing.',
'desktop.header.trash.description',
'desktop.header.trash.title',
'desktop.inspector.outgoing.',
'desktop.settings.appearance.language',
'desktop.settings.storage.panel',
'overlay.pdf_viewer.titlebar',
'overlay.slash_menu.submenu',
'page.database_cell_caret',
'root.canvas',
'desktop.explorer.display.group.',
'desktop.explorer.group_header.',
'desktop.explorer.group_select.',
'desktop.explorer.group_toggle.',
'desktop.explorer.pinned.add_option.',
'desktop.explorer.pinned.item.',
'desktop.explorer.pinned.remove.',
'desktop.explorer.quick_select.',
'desktop.explorer.quick_split.',
'desktop.explorer.quick_tab.',
'desktop.explorer.quick_trash.',
'chrome.edgeless_element_toolbar',
'chrome.edgeless_toolbar',
'chrome.edgeless_zoom',
'chrome.mode_switcher',
'desktop.explorer.display.body',
'desktop.explorer.display.icon',
'desktop.inspector.journal.conflict',
'desktop.trash.confirm.close.icon',
'desktop.trash.confirm.title',
'desktop.trash_prompt.close.icon',
'desktop.trash_prompt.title',
'overlay.attachment_toolbar',
'overlay.code_lang_picker',
'overlay.code_more_menu',
'overlay.equation_editor',
'overlay.format_toolbar',
'overlay.image_toolbar',
'overlay.keyboard_toolbar',
'overlay.linked_doc_menu',
'overlay.pdf_viewer',
'overlay.slash_menu',
'overlay.table_toolbar',
'desktop.explorer.display.prop.',
'desktop.inspector.frame.title.',
'desktop.sidebar.linked_doc.',
'edgeless.link_picker',
'desktop.settings.about.version.',
'desktop.settings.delete_workspace_confirm.body',
'desktop.settings.delete_workspace_confirm.close.icon',
'desktop.settings.delete_workspace_confirm.description',
'desktop.settings.delete_workspace_confirm.title',
'desktop.settings.storage.export',
'desktop.trash.select.',
'desktop.sidebar.fav_doc.',
'desktop.sidebar.fav_folder.',
'desktop.sidebar.fav_group.',
]);
const WASM_MAGIC = new Uint8Array([0x00, 0x61, 0x73, 0x6d]);
const WASM_VERSION_1 = new Uint8Array([0x01, 0x00, 0x00, 0x00]);
const DATA_SECTION_ID = 11;
/**
* Returns whether `dir` exists and is a directory.
*
* @param {string} dir
* @returns {boolean}
*/
function isDirectory(dir) {
try {
return statSync(dir).isDirectory();
} catch {
return false;
}
}
/**
* Collects all `.rs` files under `blocksuite/crates/<crate>/src/**` and
* `packages/frontend/desktop/src/**`.
*
* @param {string} repoRoot
* @returns {string[]}
*/
function collectRustSourceFiles(repoRoot) {
/** @type {string[]} */
const files = [];
const cratesRoot = join(repoRoot, 'blocksuite', 'crates');
const desktopSrc = join(repoRoot, 'packages', 'frontend', 'desktop', 'src');
const hasCrates = isDirectory(cratesRoot);
const hasDesktop = isDirectory(desktopSrc);
if (!hasCrates && !hasDesktop) {
throw new Error(`Cannot read Rust source directories under ${repoRoot}`);
}
/** @param {string} dir */
function walkRs(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = join(dir, entry.name);
if (entry.isDirectory()) {
walkRs(full);
} else if (entry.isFile() && entry.name.endsWith('.rs')) {
files.push(full);
}
}
}
if (hasCrates) {
for (const entry of readdirSync(cratesRoot, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const srcDir = join(cratesRoot, entry.name, 'src');
if (isDirectory(srcDir)) {
walkRs(srcDir);
}
}
}
if (hasDesktop) {
walkRs(desktopSrc);
}
return files;
}
const TEST_CFG_LINE = /^\s*#\[cfg\((?:test|all\(\s*test\b.*)\)\]\s*$/;
const MOD_DECL_LINE =
/^(\s*)(?:pub(?:\([^)]*\))?\s+)?mod\s+([A-Za-z_][A-Za-z0-9_]*)\s*([;{])\s*$/;
/**
* Lists the module declarations of one Rust file. A declaration is test-only
* when a `#[cfg(test)]` or `#[cfg(all(test, ...))]` attribute precedes it.
* Inline test-only modules also report the line of the `}` that closes them,
* which rustfmt places at the indentation of the `mod` line.
*
* @param {string} file
* @param {string[]} lines
* @returns {Array<{ name: string, test: boolean, start: number, end: number }>}
*/
function moduleDeclarations(file, lines) {
const decls = [];
for (let i = 0; i < lines.length; i += 1) {
const match = MOD_DECL_LINE.exec(lines[i]);
if (!match) continue;
let start = i;
let test = false;
while (start > 0 && lines[start - 1].trim().startsWith('#[')) {
start -= 1;
test ||= TEST_CFG_LINE.test(lines[start]);
}
let end = i;
if (test && match[3] === '{') {
const close = match[1] + '}';
end = lines.indexOf(close, i + 1);
if (end === -1) {
throw new Error(
`${file}:${i + 1}: inline module ${match[2]} has no closing "${close}" line`
);
}
}
decls.push({ name: match[2], test, start, end });
}
return decls;
}
/**
* Returns the directory that holds the child module files of `file`.
*
* @param {string} file
*/
function childModuleDir(file) {
const name = basename(file);
return ['lib.rs', 'main.rs', 'mod.rs'].includes(name)
? dirname(file)
: join(dirname(file), name.slice(0, -'.rs'.length));
}
/**
* Reads the production text of every Rust source file. Files of test-only
* modules are left out: a module declared under `#[cfg(test)]` and every
* module below it. Inline `#[cfg(test)]` modules are cut out of the text that
* remains, so assertions in unit tests never keep a prefix alive.
*
* @param {string[]} files
* @returns {Map<string, string>}
*/
function readProductionSources(files) {
/** @type {Map<string, string[]>} */
const lines = new Map(
files.map(file => [file, readFileSync(file, 'utf8').split('\n')])
);
const decls = new Map(
files.map(file => [
file,
moduleDeclarations(file, /** @type {string[]} */ (lines.get(file))),
])
);
/** @type {string[]} */
const testRoots = [];
const isTestOnly = (/** @type {string} */ file) =>
testRoots.some(
root => file === root + '.rs' || file.startsWith(root + '/')
);
let grew = true;
while (grew) {
grew = false;
for (const file of files) {
const testFile = isTestOnly(file);
for (const decl of decls.get(file) ?? []) {
if (!decl.test && !testFile) continue;
const root = join(childModuleDir(file), decl.name);
if (!testRoots.includes(root)) {
testRoots.push(root);
grew = true;
}
}
}
}
/** @type {Map<string, string>} */
const sources = new Map();
for (const file of files) {
if (isTestOnly(file)) continue;
const kept = [...(lines.get(file) ?? [])];
let cutEnd = -1;
const cuts = [];
for (const decl of decls.get(file) ?? []) {
if (decl.test && decl.start > cutEnd) {
cuts.push(decl);
cutEnd = decl.end;
}
}
for (const cut of cuts.reverse()) {
kept.splice(cut.start, cut.end - cut.start + 1);
}
sources.set(file, kept.join('\n'));
}
return sources;
}
/**
* Checks that every prefix in `prefixes` appears at least once in Rust sources
* under `<repoRoot>/blocksuite/crates/<crate>/src/**` and
* `<repoRoot>/packages/frontend/desktop/src/**`.
*
* @param {{ repoRoot?: string, prefixes?: readonly string[] }} [options]
* @returns {{ ok: boolean, missing: string[], counts: Record<string, number>, scannedFiles: number }}
*/
export function verifySourcePrefixes(options = {}) {
const repoRoot = options.repoRoot ?? DEFAULT_REPO_ROOT;
const prefixes = options.prefixes ?? ZERO_IN_PRODUCTION;
const sources = readProductionSources(collectRustSourceFiles(repoRoot));
/** @type {Record<string, number>} */
const counts = Object.fromEntries(prefixes.map(prefix => [prefix, 0]));
for (const content of sources.values()) {
for (const prefix of prefixes) {
let from = 0;
while (true) {
const idx = content.indexOf(prefix, from);
if (idx === -1) break;
counts[prefix] += 1;
from = idx + 1;
}
}
}
const missing = prefixes.filter(prefix => counts[prefix] === 0);
return {
ok: missing.length === 0,
missing,
counts,
scannedFiles: sources.size,
};
}
/**
* Reads an unsigned LEB128 u32 from `bytes` within `[offset, end)`.
*
* @param {Uint8Array} bytes
* @param {number} offset
* @param {number} end
* @returns {{ value: number, next: number }}
*/
function readU32Leb(bytes, offset, end) {
let result = 0;
let shift = 0;
let pos = offset;
for (let count = 0; count < 5; count += 1) {
if (pos >= end) {
throw new Error(`Truncated unsigned LEB128 at byte offset ${offset}`);
}
const byte = bytes[pos++];
if (count === 4 && (byte & 0xf0) !== 0) {
throw new Error(`Unsigned LEB128 u32 overflow at byte offset ${offset}`);
}
result += (byte & 0x7f) * 2 ** shift;
if ((byte & 0x80) === 0) {
return { value: result, next: pos };
}
shift += 7;
}
throw new Error(`Overlong unsigned LEB128 at byte offset ${offset}`);
}
/**
* Skips a signed LEB128 integer of at most `maxBytes` within `[offset, end)`.
*
* @param {Uint8Array} bytes
* @param {number} offset
* @param {number} end
* @param {number} maxBytes
* @returns {number}
*/
function skipSignedLeb(bytes, offset, end, maxBytes) {
let pos = offset;
for (let count = 0; count < maxBytes; count += 1) {
if (pos >= end) {
throw new Error(`Truncated signed LEB128 at byte offset ${offset}`);
}
const byte = bytes[pos++];
if ((byte & 0x80) === 0) {
return pos;
}
}
throw new Error(`Overlong signed LEB128 at byte offset ${offset}`);
}
/**
* Skips a WebAssembly constant expression through its terminating `0x0b` opcode.
*
* @param {Uint8Array} bytes
* @param {number} offset
* @param {number} end
* @returns {number}
*/
function skipConstExpr(bytes, offset, end) {
let pos = offset;
while (pos < end) {
const opcode = bytes[pos++];
if (opcode === 0x0b) {
return pos;
}
if (opcode === 0x41) {
// i32.const
pos = skipSignedLeb(bytes, pos, end, 5);
} else if (opcode === 0x42) {
// i64.const
pos = skipSignedLeb(bytes, pos, end, 10);
} else if (opcode === 0x43) {
// f32.const
if (pos + 4 > end) {
throw new Error(`Truncated f32.const at byte offset ${pos - 1}`);
}
pos += 4;
} else if (opcode === 0x44) {
// f64.const
if (pos + 8 > end) {
throw new Error(`Truncated f64.const at byte offset ${pos - 1}`);
}
pos += 8;
} else if (opcode === 0x23 || opcode === 0xd2) {
// global.get / ref.func
pos = readU32Leb(bytes, pos, end).next;
} else if (opcode === 0xd0) {
// ref.null heaptype
pos = skipSignedLeb(bytes, pos, end, 5);
} else if (
opcode === 0x6a ||
opcode === 0x6b ||
opcode === 0x6c ||
opcode === 0x7c ||
opcode === 0x7d ||
opcode === 0x7e
) {
// Extended constant expression arithmetic (i32/i64 add/sub/mul)
} else if (opcode === 0xfd) {
// SIMD v128.const
const sub = readU32Leb(bytes, pos, end);
if (sub.value !== 0x0c) {
throw new Error(
`Unsupported SIMD opcode 0xfd 0x${sub.value.toString(16)} in constant expression`
);
}
if (sub.next + 16 > end) {
throw new Error(`Truncated v128.const at byte offset ${pos - 1}`);
}
pos = sub.next + 16;
} else {
throw new Error(
`Unsupported opcode 0x${opcode.toString(16)} in Data segment constant expression at byte offset ${pos - 1}`
);
}
}
throw new Error(
`Unterminated Data segment constant expression starting at byte offset ${offset}`
);
}
/**
* Parses Section 11 (Data) from a WebAssembly binary and returns each data
* segment's independent payload slice.
*
* @param {Uint8Array} bytes
* @returns {{ segments: Array<{ index: number, mode: number, payload: Uint8Array }>, totalDataBytes: number }}
*/
export function extractWasmDataSegments(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.length < 8) {
throw new Error('Wasm binary is shorter than the 8-byte header');
}
for (let i = 0; i < 4; i += 1) {
if (bytes[i] !== WASM_MAGIC[i]) {
throw new Error('Invalid Wasm magic header (expected \\0asm)');
}
}
for (let i = 0; i < 4; i += 1) {
if (bytes[4 + i] !== WASM_VERSION_1[i]) {
throw new Error('Unsupported Wasm binary version (expected version 1)');
}
}
let pos = 8;
/** @type {{ start: number, end: number } | null} */
let dataSection = null;
while (pos < bytes.length) {
const sectionId = bytes[pos++];
const sizeInfo = readU32Leb(bytes, pos, bytes.length);
const payloadStart = sizeInfo.next;
const payloadEnd = payloadStart + sizeInfo.value;
if (payloadEnd > bytes.length) {
throw new Error(
`Section ${sectionId} length ${sizeInfo.value} exceeds binary size ${bytes.length} at byte offset ${payloadStart}`
);
}
if (sectionId === DATA_SECTION_ID) {
if (dataSection !== null) {
throw new Error('Duplicate Wasm Section 11 (Data)');
}
dataSection = { start: payloadStart, end: payloadEnd };
}
pos = payloadEnd;
}
if (dataSection === null) {
throw new Error('Missing Wasm Section 11 (Data)');
}
if (dataSection.start === dataSection.end) {
throw new Error('Wasm Section 11 (Data) is empty');
}
const countInfo = readU32Leb(bytes, dataSection.start, dataSection.end);
const segmentCount = countInfo.value;
if (segmentCount === 0) {
throw new Error('Wasm Section 11 (Data) declares 0 data segments');
}
let segPos = countInfo.next;
/** @type {Array<{ index: number, mode: number, payload: Uint8Array }>} */
const segments = [];
let totalDataBytes = 0;
for (let index = 0; index < segmentCount; index += 1) {
const modeInfo = readU32Leb(bytes, segPos, dataSection.end);
const mode = modeInfo.value;
segPos = modeInfo.next;
if (mode === 0) {
// Active segment targeting memory 0.
segPos = skipConstExpr(bytes, segPos, dataSection.end);
} else if (mode === 1) {
// Passive segment: no memory index or offset expression.
} else if (mode === 2) {
// Active segment with explicit memory index.
const memIdxInfo = readU32Leb(bytes, segPos, dataSection.end);
segPos = skipConstExpr(bytes, memIdxInfo.next, dataSection.end);
} else {
throw new Error(
`Unsupported Wasm Data segment mode ${mode} at segment ${index}`
);
}
const lenInfo = readU32Leb(bytes, segPos, dataSection.end);
const dataStart = lenInfo.next;
const dataEnd = dataStart + lenInfo.value;
if (dataEnd > dataSection.end) {
throw new Error(
`Data segment ${index} length ${lenInfo.value} exceeds Section 11 bounds`
);
}
segments.push({
index,
mode,
payload: bytes.subarray(dataStart, dataEnd),
});
totalDataBytes += lenInfo.value;
segPos = dataEnd;
}
if (segPos !== dataSection.end) {
throw new Error(
`Trailing bytes in Wasm Section 11 (Data): parsed to ${segPos}, section ends at ${dataSection.end}`
);
}
if (totalDataBytes === 0) {
throw new Error('Wasm Section 11 (Data) contains 0 payload bytes');
}
return { segments, totalDataBytes };
}
/**
* Searches each Wasm Data segment payload independently for forbidden ASCII
* snapshot prefixes.
*
* @param {Uint8Array} bytes
* @param {readonly string[]} [prefixes]
*/
export function scanWasmDataPrefixes(bytes, prefixes = ZERO_IN_PRODUCTION) {
const sha256 = createHash('sha256').update(bytes).digest('hex');
const { segments, totalDataBytes } = extractWasmDataSegments(bytes);
/** @type {Array<{ prefix: string, count: number, firstSegment: number, firstOffset: number }>} */
const hits = [];
for (const prefix of prefixes) {
const needle = Buffer.from(prefix, 'ascii');
let count = 0;
let firstSegment = -1;
let firstOffset = -1;
for (const seg of segments) {
const hay = Buffer.from(
seg.payload.buffer,
seg.payload.byteOffset,
seg.payload.byteLength
);
let from = 0;
while (from <= hay.length - needle.length) {
const idx = hay.indexOf(needle, from);
if (idx === -1) break;
if (firstSegment === -1) {
firstSegment = seg.index;
firstOffset = idx;
}
count += 1;
from = idx + 1;
}
}
if (count > 0) {
hits.push({ prefix, count, firstSegment, firstOffset });
}
}
return {
ok: hits.length === 0,
sha256,
segmentCount: segments.length,
totalDataBytes,
hits,
};
}
/**
* CLI entrypoint.
*
* @param {string[]} argv
*/
function main(argv) {
if (
argv.length === 0 ||
(argv.includes('--source-only') && argv.length !== 1)
) {
throw new Error(
'Usage: node scripts/check-snapshot-prefixes.mjs --source-only | <path/to/bundle_bg.wasm>...'
);
}
const sourceResult = verifySourcePrefixes();
if (!sourceResult.ok) {
throw new Error(
`Snapshot prefix liveness check failed across ${sourceResult.scannedFiles} Rust files. Missing prefixes: ${sourceResult.missing.join(', ')}`
);
}
if (argv[0] === '--source-only') {
console.log(
`Snapshot prefix source liveness check passed (${ZERO_IN_PRODUCTION.length}/${ZERO_IN_PRODUCTION.length} prefixes found across ${sourceResult.scannedFiles} Rust files).`
);
return;
}
/** @type {string[]} */
const failures = [];
for (const arg of argv) {
const wasmPath = resolve(arg);
const scan = scanWasmDataPrefixes(readFileSync(wasmPath));
if (!scan.ok) {
failures.push(
`Forbidden snapshot prefixes found in Wasm Section 11 (Data): ${wasmPath}`,
`SHA-256: ${scan.sha256}`,
...scan.hits.map(
hit =>
` - ${hit.prefix}: count=${hit.count}, first_segment=${hit.firstSegment}, first_offset=${hit.firstOffset}`
)
);
continue;
}
console.log(
`Wasm Section 11 snapshot prefix gate passed for ${wasmPath} (${ZERO_IN_PRODUCTION.length}/${ZERO_IN_PRODUCTION.length} prefixes at 0, ${scan.segmentCount} segments, ${scan.totalDataBytes} data bytes, sha256=${scan.sha256}).`
);
}
if (failures.length > 0) {
throw new Error(failures.join('\n'));
}
}
const isMain =
process.argv[1] &&
resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (isMain) {
try {
main(process.argv.slice(2));
} catch (err) {
console.error(err instanceof Error ? err.message : String(err));
process.exitCode = 1;
}
}
@@ -0,0 +1,754 @@
// @ts-check
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import {
scanWasmDataPrefixes,
verifySourcePrefixes,
ZERO_IN_PRODUCTION,
} from './check-snapshot-prefixes.mjs';
const SCRIPT_PATH = fileURLToPath(
new URL('./check-snapshot-prefixes.mjs', import.meta.url)
);
const DESKTOP_PREFIXES = [
'desktop.list.doc.',
'desktop.trash.row.',
'desktop.outline.rail.heading.',
'desktop.inspector.heading.',
'desktop.qs.doc.',
'desktop.qs.cmd.',
];
const NEW_DESKTOP_PREFIXES = [
'desktop.qs.collection.',
'desktop.qs.tag.',
'desktop.sidebar.workspace.',
'desktop.explorer.doc_menu.',
'desktop.outline.rail.tick.',
'desktop.outline.rail.open.',
'desktop.inspector.backlink.',
'desktop.trash.restore.',
'desktop.trash.delete.',
'desktop.inspector.journal.day.',
'desktop.app_tabs.tab.',
'desktop.split.resize.',
'desktop.explorer.group.',
];
const SIDEBAR_AND_PANEL_PREFIXES = [
'desktop.outline.rail.',
'desktop.sidebar.sec.',
'desktop.sidebar.fav.',
'desktop.sidebar.fdoc.',
'desktop.sidebar.col_doc.',
'desktop.sidebar.tag_doc.',
'desktop.sidebar.folder.',
'desktop.sidebar.col.',
'desktop.sidebar.tag.',
'desktop.trash.open.',
'desktop.sidebar.resize',
'desktop.split.resize',
'desktop.inspector.journal.previous',
'desktop.inspector.journal.today',
'desktop.inspector.journal.next',
];
const SNAPSHOT_RATCHET_ADDITIONS = [
'chrome.doc_panel_toggle',
'chrome.mode_switcher.edgeless',
'chrome.mode_switcher.indicator',
'chrome.mode_switcher.page',
'chrome.nav_back',
'chrome.theme_toggle',
'chrome.topbar',
'desktop.explorer.favorite.',
'desktop.explorer.heading',
'desktop.explorer.menu.',
'desktop.explorer.selected',
'desktop.explorer.tag_switch.',
'desktop.header.trash.body',
'desktop.inspector.frame.item.',
'desktop.inspector.journal.activity.empty',
'desktop.inspector.journal.conflict.more',
'desktop.inspector.journal.conflict.trash.',
'desktop.inspector.journal.dot.',
'desktop.inspector.journal.tab.',
'desktop.pane.0.tab.',
'desktop.peek.control.tooltip',
'desktop.settings.font.size.thumb',
'desktop.sidebar.node.add',
'desktop.sidebar.node.more',
'desktop.trash.confirm.body',
'desktop.trash.confirm.description',
'desktop.trash_prompt.body',
'desktop.trash_prompt.description',
'edgeless.auto_complete.ghost_preview',
'edgeless.caption_caret',
'edgeless.caption_focus',
'edgeless.frame_drop_highlight',
'edgeless.inline_edit',
'edgeless.marquee',
'edgeless.note_slicer',
'edgeless.snap_guideline',
'edgeless.transform_hud',
'overlay.add_block_button',
'overlay.block_drag_ghost',
'overlay.calendar_day_hover',
'overlay.calendar_day_new_row',
'overlay.calendar_drag_ghost',
'overlay.calendar_drop_settle',
'overlay.calendar_event_hover',
'overlay.calendar_event_resize_',
'overlay.code_lang_picker.empty',
'overlay.code_lang_picker.scrollbar',
'overlay.code_lang_picker.search',
'overlay.database_popover',
'overlay.drag_handle',
'overlay.drop_indicator',
'overlay.equation_editor.done',
'overlay.equation_editor.input',
'overlay.kanban_card_hover',
'overlay.kanban_drag_ghost',
'overlay.kanban_drag_placeholder',
'overlay.kanban_drop_settle',
'overlay.kanban_lane_footer_add',
'overlay.keyboard_toolbar.group.',
'overlay.keyboard_toolbar.panel.',
'overlay.linked_doc_menu.create',
'overlay.linked_doc_menu.input_mask',
'overlay.linked_doc_menu.more',
'overlay.page_marquee',
'overlay.pdf_viewer.close',
'overlay.pdf_viewer.filename',
'overlay.pdf_viewer.header_title',
'overlay.pdf_viewer.indicator',
'overlay.pdf_viewer.status',
'overlay.pdf_viewer.thumbnails_toggle',
'overlay.pdf_viewer.zoom_in',
'overlay.pdf_viewer.zoom_out',
'overlay.pdf_viewer.zoom_reset',
'overlay.slash_menu.preview',
'overlay.slash_menu.query',
'overlay.table_column_drag_ghost',
'overlay.table_header_hover',
'overlay.table_resize_guide',
'overlay.table_row_drag_ghost',
'overlay.table_row_drag_handle',
'overlay.table_toolbar.axis_selection',
'overlay.table_toolbar.more',
'overlay.toolbar_tooltip',
'overlay.touch_selection_menu',
'page.block_placeholder',
'page.block_selection',
'page.caption_caret',
'page.caption_focus',
'page.database_cell_focus',
'page.local_caret',
'page.selection',
'page.status',
'page.table_area_selection',
'page.table_cell_caret',
];
const EXTENDED_SNAPSHOT_PREFIXES = [
'.attachment_card',
'.bookmark_card',
'.builtin.',
'.custom.menu.',
'.embed_activate',
'.embed_card',
'.embed_shield',
'.highlight_menu.background.',
'.hscrollbar',
'.image_card',
'.journal_next',
'.journal_previous',
'.journal_week',
'.links.',
'.tag.attached.',
'.tag.create',
'.tag.option.',
'.toolbar.copy',
'.toolbar.language',
'desktop.collection_editor.count',
'desktop.collection_editor.doc.',
'desktop.collection_editor.filter.remove.',
'desktop.collection_editor.include.remove.',
'desktop.collection_editor.menu.item.',
'desktop.collection_editor.rules.tips',
'desktop.collection_editor.selected',
'desktop.header.dialog.close.icon',
'desktop.header.info.backlink.',
'desktop.header.info.outgoing.',
'desktop.header.trash.description',
'desktop.header.trash.title',
'desktop.inspector.outgoing.',
'desktop.settings.appearance.language',
'desktop.settings.storage.panel',
'overlay.pdf_viewer.titlebar',
'overlay.slash_menu.submenu',
'page.database_cell_caret',
'root.canvas',
];
const EXPLORER_SNAPSHOT_PREFIXES = [
'desktop.explorer.display.group.',
'desktop.explorer.group_header.',
'desktop.explorer.group_select.',
'desktop.explorer.group_toggle.',
'desktop.explorer.pinned.add_option.',
'desktop.explorer.pinned.item.',
'desktop.explorer.pinned.remove.',
'desktop.explorer.quick_select.',
'desktop.explorer.quick_split.',
'desktop.explorer.quick_tab.',
'desktop.explorer.quick_trash.',
];
const SHELL_CONTAINER_AND_DIALOG_PREFIXES = [
'chrome.edgeless_element_toolbar',
'chrome.edgeless_toolbar',
'chrome.edgeless_zoom',
'chrome.mode_switcher',
'desktop.explorer.display.body',
'desktop.explorer.display.icon',
'desktop.inspector.journal.conflict',
'desktop.trash.confirm.close.icon',
'desktop.trash.confirm.title',
'desktop.trash_prompt.close.icon',
'desktop.trash_prompt.title',
'overlay.attachment_toolbar',
'overlay.code_lang_picker',
'overlay.code_more_menu',
'overlay.equation_editor',
'overlay.format_toolbar',
'overlay.image_toolbar',
'overlay.keyboard_toolbar',
'overlay.linked_doc_menu',
'overlay.pdf_viewer',
'overlay.slash_menu',
'overlay.table_toolbar',
];
const DISPLAY_AND_LINK_PICKER_PREFIXES = [
'desktop.explorer.display.prop.',
'desktop.inspector.frame.title.',
'desktop.sidebar.linked_doc.',
'edgeless.link_picker',
];
const SETTINGS_AND_TRASH_SELECT_PREFIXES = [
'desktop.settings.about.version.',
'desktop.settings.delete_workspace_confirm.body',
'desktop.settings.delete_workspace_confirm.close.icon',
'desktop.settings.delete_workspace_confirm.description',
'desktop.settings.delete_workspace_confirm.title',
'desktop.settings.storage.export',
'desktop.trash.select.',
];
const FAVORITE_ROW_PREFIXES = [
'desktop.sidebar.fav_doc.',
'desktop.sidebar.fav_folder.',
'desktop.sidebar.fav_group.',
];
const NON_OVERLAPPING_PREFIXES = new Set([
'desktop.explorer.display.body',
'desktop.explorer.display.icon',
'desktop.trash.confirm.close.icon',
'desktop.trash.confirm.title',
'desktop.trash_prompt.close.icon',
'desktop.trash_prompt.title',
...DISPLAY_AND_LINK_PICKER_PREFIXES,
...SETTINGS_AND_TRASH_SELECT_PREFIXES,
...FAVORITE_ROW_PREFIXES,
]);
/**
* Encodes an unsigned integer as LEB128.
*
* @param {number} value
* @returns {number[]}
*/
function encodeU32Leb(value) {
const out = [];
let v = value >>> 0;
do {
let byte = v & 0x7f;
v >>>= 7;
if (v !== 0) byte |= 0x80;
out.push(byte);
} while (v !== 0);
return out;
}
/**
* Builds a Wasm section byte array.
*
* @param {number} id
* @param {number[]} payload
* @returns {number[]}
*/
function buildSection(id, payload) {
return [id, ...encodeU32Leb(payload.length), ...payload];
}
/**
* Builds a Wasm custom section (ID 0).
*
* @param {string} name
* @param {string} body
* @returns {number[]}
*/
function buildCustomSection(name, body) {
const nameBytes = Array.from(Buffer.from(name, 'utf8'));
const bodyBytes = Array.from(Buffer.from(body, 'utf8'));
return buildSection(0, [
...encodeU32Leb(nameBytes.length),
...nameBytes,
...bodyBytes,
]);
}
/**
* Builds a Wasm Section 11 (Data) containing passive segments.
*
* @param {string[]} payloads
* @returns {number[]}
*/
function buildPassiveDataSection(payloads) {
const body = [...encodeU32Leb(payloads.length)];
for (const text of payloads) {
const raw = Array.from(Buffer.from(text, 'utf8'));
body.push(1, ...encodeU32Leb(raw.length), ...raw);
}
return buildSection(11, body);
}
/**
* Builds a complete Wasm module binary.
*
* @param {number[][]} sections
* @returns {Uint8Array}
*/
function buildWasm(sections) {
return Uint8Array.from([
0x00,
0x61,
0x73,
0x6d,
1,
0,
0,
0,
...sections.flat(),
]);
}
test('rejects bare snapshot container IDs in Wasm Data segments', () => {
for (const root of [
'overlay.context_menu',
'overlay.image_lightbox',
'overlay.doc_panel',
'overlay.database_record_sheet',
]) {
const wasm = buildWasm([buildPassiveDataSection([root])]);
const result = scanWasmDataPrefixes(wasm);
assert.equal(result.ok, false, root);
assert.deepEqual(result.hits, [
{ prefix: root, count: 1, firstSegment: 0, firstOffset: 0 },
]);
}
});
test('verifies all 260 live prefixes including desktop production sources', () => {
assert.equal(ZERO_IN_PRODUCTION.length, 260);
const firstBatchAdditions = ZERO_IN_PRODUCTION.slice(81, 175);
assert.deepEqual(
firstBatchAdditions,
SNAPSHOT_RATCHET_ADDITIONS,
'Existing 175 prefixes must keep exact order'
);
assert.deepEqual(
firstBatchAdditions,
[...firstBatchAdditions].sort(),
'First ratchet batch must stay sorted lexicographically'
);
const extendedAdditions = ZERO_IN_PRODUCTION.slice(175, 213);
assert.deepEqual(
extendedAdditions,
EXTENDED_SNAPSHOT_PREFIXES,
'Extended snapshot prefixes must match appended order'
);
assert.deepEqual(
extendedAdditions,
[...extendedAdditions].sort(),
'Extended snapshot prefixes must stay sorted lexicographically'
);
assert.deepEqual(
ZERO_IN_PRODUCTION.slice(213, 224),
EXPLORER_SNAPSHOT_PREFIXES,
'Explorer snapshot prefixes must match appended order'
);
const shellAdditions = ZERO_IN_PRODUCTION.slice(224, 246);
assert.deepEqual(
shellAdditions,
SHELL_CONTAINER_AND_DIALOG_PREFIXES,
'Shell container and dialog prefixes must match appended order'
);
assert.deepEqual(
shellAdditions,
[...shellAdditions].sort(),
'Shell container and dialog prefixes must stay sorted lexicographically'
);
assert.deepEqual(
ZERO_IN_PRODUCTION.slice(246, 250),
DISPLAY_AND_LINK_PICKER_PREFIXES
);
const settingsAndTrashAdditions = ZERO_IN_PRODUCTION.slice(250, 257);
assert.deepEqual(
settingsAndTrashAdditions,
SETTINGS_AND_TRASH_SELECT_PREFIXES,
'Settings and trash select prefixes must match appended order'
);
assert.deepEqual(
settingsAndTrashAdditions,
[...settingsAndTrashAdditions].sort(),
'Settings and trash select prefixes must stay sorted lexicographically'
);
const favoriteRowAdditions = ZERO_IN_PRODUCTION.slice(257);
assert.deepEqual(
favoriteRowAdditions,
FAVORITE_ROW_PREFIXES,
'Favorite row prefixes must match appended order'
);
assert.deepEqual(
favoriteRowAdditions,
[...favoriteRowAdditions].sort(),
'Favorite row prefixes must stay sorted lexicographically'
);
assert.equal(
new Set(ZERO_IN_PRODUCTION).size,
ZERO_IN_PRODUCTION.length,
'ZERO_IN_PRODUCTION must not contain duplicate prefixes'
);
for (let i = 0; i < SIDEBAR_AND_PANEL_PREFIXES.length; i += 1) {
for (let j = 0; j < SIDEBAR_AND_PANEL_PREFIXES.length; j += 1) {
if (i === j) continue;
assert.equal(
SIDEBAR_AND_PANEL_PREFIXES[i].startsWith(SIDEBAR_AND_PANEL_PREFIXES[j]),
false,
`Redundant prefix pair in desktop additions: ${SIDEBAR_AND_PANEL_PREFIXES[j]} covers ${SIDEBAR_AND_PANEL_PREFIXES[i]}`
);
}
}
const additionSet = new Set(SNAPSHOT_RATCHET_ADDITIONS);
for (const prefix of SNAPSHOT_RATCHET_ADDITIONS) {
for (const existing of ZERO_IN_PRODUCTION.slice(0, 175)) {
if (existing === prefix) continue;
assert.equal(
prefix.startsWith(existing),
false,
`Redundant addition ${prefix} is already covered by ${existing}`
);
if (!additionSet.has(existing)) {
assert.equal(
existing.startsWith(prefix),
false,
`Addition ${prefix} shadows existing prefix ${existing}`
);
}
}
}
for (const prefix of [
...EXTENDED_SNAPSHOT_PREFIXES,
...EXPLORER_SNAPSHOT_PREFIXES,
]) {
for (const existing of ZERO_IN_PRODUCTION.slice(0, 224)) {
if (existing === prefix) continue;
assert.equal(
prefix.startsWith(existing),
false,
`Redundant addition ${prefix} is already covered by ${existing}`
);
assert.equal(
existing.startsWith(prefix),
false,
`Addition ${prefix} shadows existing prefix ${existing}`
);
}
}
for (const prefix of [
...SHELL_CONTAINER_AND_DIALOG_PREFIXES,
...DISPLAY_AND_LINK_PICKER_PREFIXES,
...SETTINGS_AND_TRASH_SELECT_PREFIXES,
...FAVORITE_ROW_PREFIXES,
]) {
for (const existing of ZERO_IN_PRODUCTION) {
if (existing === prefix) continue;
assert.equal(
prefix.startsWith(existing),
false,
`Redundant addition ${prefix} is already covered by ${existing}`
);
if (NON_OVERLAPPING_PREFIXES.has(prefix)) {
assert.equal(
existing.startsWith(prefix),
false,
`Addition ${prefix} shadows existing prefix ${existing}`
);
}
}
}
const result = verifySourcePrefixes();
assert.equal(
result.ok,
true,
`Missing prefixes in repo: ${result.missing.join(', ')}`
);
assert.equal(Object.keys(result.counts).length, 260);
for (const prefix of [
...DESKTOP_PREFIXES,
...NEW_DESKTOP_PREFIXES,
...SIDEBAR_AND_PANEL_PREFIXES,
...SNAPSHOT_RATCHET_ADDITIONS,
...EXTENDED_SNAPSHOT_PREFIXES,
...EXPLORER_SNAPSHOT_PREFIXES,
...SHELL_CONTAINER_AND_DIALOG_PREFIXES,
...DISPLAY_AND_LINK_PICKER_PREFIXES,
...SETTINGS_AND_TRASH_SELECT_PREFIXES,
...FAVORITE_ROW_PREFIXES,
]) {
assert.ok(
result.counts[prefix] >= 1,
`Expected ${prefix} to appear in production Rust sources`
);
}
});
test('ignores desktop prefixes that appear only inside #[cfg(test)] modules', () => {
const dir = mkdtempSync(join(tmpdir(), 'snapshot-prefix-desktop-tests-'));
try {
const desktopSrc = join(dir, 'packages', 'frontend', 'desktop', 'src');
mkdirSync(join(desktopSrc, 'views_extra'), { recursive: true });
const files = {
'lib.rs': [
'mod views_extra;',
'#[cfg(test)]',
'mod tests;',
'#[cfg(all(test, feature = "harness"))]',
'mod helpers {',
' const H: &str = "desktop.qs.doc.";',
'}',
"pub fn live_list() -> &'static str {",
' "desktop.list.doc."',
'}',
],
'tests.rs': ['const T: &str = "desktop.qs.cmd.";'],
'views_extra/mod.rs': ['mod trash;', '#[cfg(test)]', 'mod tests;'],
'views_extra/trash.rs': [
'const T: &str = "desktop.trash.row.";',
'#[cfg(test)]',
'mod tests {',
' const FAKE: &str = "desktop.inspector.heading.";',
'}',
],
'views_extra/tests.rs': [
'const ONLY_TEST: &str = "desktop.outline.rail.heading.";',
],
};
for (const [rel, lines] of Object.entries(files)) {
writeFileSync(join(desktopSrc, rel), lines.join('\n') + '\n');
}
const result = verifySourcePrefixes({
repoRoot: dir,
prefixes: DESKTOP_PREFIXES,
});
assert.equal(result.scannedFiles, 3);
assert.equal(result.ok, false);
assert.deepEqual(result.counts, {
'desktop.list.doc.': 1,
'desktop.trash.row.': 1,
'desktop.outline.rail.heading.': 0,
'desktop.inspector.heading.': 0,
'desktop.qs.doc.': 0,
'desktop.qs.cmd.': 0,
});
assert.deepEqual(result.missing, [
'desktop.outline.rail.heading.',
'desktop.inspector.heading.',
'desktop.qs.doc.',
'desktop.qs.cmd.',
]);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
test('fails CLI gate on desktop prefixes in Section 11 and ignores custom/code sections', () => {
for (const prefix of [
...DESKTOP_PREFIXES,
...NEW_DESKTOP_PREFIXES,
...SIDEBAR_AND_PANEL_PREFIXES,
...SNAPSHOT_RATCHET_ADDITIONS,
...EXTENDED_SNAPSHOT_PREFIXES,
...EXPLORER_SNAPSHOT_PREFIXES,
...SHELL_CONTAINER_AND_DIALOG_PREFIXES,
...DISPLAY_AND_LINK_PICKER_PREFIXES,
...SETTINGS_AND_TRASH_SELECT_PREFIXES,
]) {
const payload = `${prefix}item-1`;
const wasm = buildWasm([buildPassiveDataSection([payload])]);
const result = scanWasmDataPrefixes(wasm);
const expectedHits = ZERO_IN_PRODUCTION.filter(candidate =>
payload.includes(candidate)
).map(candidate => ({
prefix: candidate,
count: 1,
firstSegment: 0,
firstOffset: 0,
}));
assert.equal(result.ok, false, prefix);
assert.deepEqual(result.hits, expectedHits);
}
for (const prefix of [
...EXTENDED_SNAPSHOT_PREFIXES,
...EXPLORER_SNAPSHOT_PREFIXES,
]) {
const splitAt = Math.floor(prefix.length / 2);
const splitWasm = buildWasm([
buildPassiveDataSection([
prefix.slice(0, splitAt),
prefix.slice(splitAt),
]),
]);
const splitResult = scanWasmDataPrefixes(splitWasm);
assert.equal(splitResult.ok, true, `split segment: ${prefix}`);
assert.deepEqual(splitResult.hits, []);
}
const dir = mkdtempSync(join(tmpdir(), 'snapshot-prefix-desktop-wasm-'));
try {
for (const [sample, pattern] of [
['desktop.qs.doc.doc-1', /desktop\.qs\.doc\./],
[
'desktop.inspector.frame.item.frame-1',
/desktop\.inspector\.frame\.item\./,
],
['overlay.equation_editor.input', /overlay\.equation_editor\.input/],
[
'desktop.collection_editor.doc.doc-1',
/desktop\.collection_editor\.doc\./,
],
[
'desktop.header.info.outgoing.doc-2',
/desktop\.header\.info\.outgoing\./,
],
['desktop.inspector.custom.menu.edit', /\.custom\.menu\./],
['overlay.pdf_viewer.titlebar', /overlay\.pdf_viewer\.titlebar/],
['page.database_cell_caret', /page\.database_cell_caret/],
['root.canvas', /root\.canvas/],
[
'desktop.settings.about.version.app',
/desktop\.settings\.about\.version\./,
],
['desktop.trash.select.doc-1', /desktop\.trash\.select\./],
['desktop.settings.storage.export', /desktop\.settings\.storage\.export/],
[
'desktop.settings.delete_workspace_confirm.title',
/desktop\.settings\.delete_workspace_confirm\.title/,
],
]) {
const badWasm = join(dir, 'bad.wasm');
writeFileSync(badWasm, buildWasm([buildPassiveDataSection([sample])]));
const failRun = spawnSync(process.execPath, [SCRIPT_PATH, badWasm], {
encoding: 'utf8',
});
assert.equal(failRun.status, 1);
assert.match(failRun.stderr, pattern);
}
const nonDataPayload = Buffer.from(
[
'desktop.qs.doc.doc-1 desktop.qs.cmd.0 desktop.list.doc.a',
...EXTENDED_SNAPSHOT_PREFIXES,
...EXPLORER_SNAPSHOT_PREFIXES,
...DISPLAY_AND_LINK_PICKER_PREFIXES,
...SETTINGS_AND_TRASH_SELECT_PREFIXES,
].join(' '),
'utf8'
);
const cleanWasm = join(dir, 'clean.wasm');
writeFileSync(
cleanWasm,
buildWasm([
buildCustomSection('name', nonDataPayload.toString('utf8')),
// Code section (ID 10) carrying non-data bytes must not trigger Data scan.
buildSection(10, [
1,
nonDataPayload.length + 2,
0,
...nonDataPayload,
0x0b,
]),
buildPassiveDataSection([
'desktop.inspector.outline.empty',
'desktop.inspector.frame.present',
'desktop.inspector.frame.empty',
'desktop.inspector.frame.list',
'desktop.inspector.tag.list',
'desktop.explorer.menu',
'desktop.explorer.display.order.createdAt',
'desktop.explorer.display.qa.split',
'desktop.app_tabs.drop_indicator',
...EXPLORER_SNAPSHOT_PREFIXES.map(prefix => prefix.slice(0, -1)),
'desktop.sidebar',
'desktop.sidebar.settings',
'desktop.trash.restore_selected',
'desktop.trash.delete_selected',
'desktop.pane.1.topbar.day.2026-12-01',
'desktop.settings.appearance.title',
'desktop.settings.appearance',
'desktop.collections.add',
'desktop.collection_editor.filter.method',
'desktop.collection_editor.include.toggle',
'desktop.collection_editor.menu.rows',
'desktop.workbench.topbar',
'desktop.journals.create',
]),
])
);
const passRun = spawnSync(process.execPath, [SCRIPT_PATH, cleanWasm], {
encoding: 'utf8',
});
assert.equal(passRun.status, 0, passRun.stderr);
assert.match(passRun.stdout, /260\/260 prefixes at 0/);
const desktopOnlyOptWasm = join(dir, 'affine_desktop_bg.opt.wasm');
writeFileSync(
desktopOnlyOptWasm,
buildWasm([buildPassiveDataSection(['desktop.settings.appearance'])])
);
const singleRun = spawnSync(
process.execPath,
[SCRIPT_PATH, desktopOnlyOptWasm],
{ encoding: 'utf8' }
);
assert.equal(singleRun.status, 0, singleRun.stderr);
assert.match(singleRun.stdout, /260\/260 prefixes at 0/);
assert.match(singleRun.stdout, /affine_desktop_bg\.opt\.wasm/);
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
+788
View File
@@ -0,0 +1,788 @@
#!/usr/bin/env node
/**
* Self-contained headless Chromium WebAssembly smoke test (zero npm dependencies).
*
* Serves `web/` over localhost, launches headless Chromium via CDP with SwiftShader
* WebGL2 enabled, and asserts:
* 1. Zero uncaught JS exceptions / Wasm panics.
* 2. Non-blank rendered `<canvas>` containing actual dark ink glyph pixels inside
* the title and mode-switcher pill regions.
* 3. Clicking the `"Edgeless"` button on the `<canvas>` triggers an observable
* visual state transition to Edgeless mode.
*
* `--query <string>` loads the page with a query string (for example a live room,
* `room=<room>&ws=<ws_url>`), and `--min-title-ink <pixels>` raises the amount of ink
* the title/body region must show before the page is captured, so a page that arrives
* over the network is captured after it rendered.
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import zlib from 'node:zlib';
import { measureSurfaceBaselines } from '../../../blocksuite/crates/oracle/surface-baselines.mjs';
import {
closeBrowserResources,
createChromiumHarness,
openPageTarget,
SWIFTSHADER_OPTIONS,
} from '../hosts/web/scripts/chromium-harness.mjs';
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(SCRIPT_DIR, '..');
const REPO_ROOT = path.resolve(ROOT, '../..');
const WEB_DIR = path.join(REPO_ROOT, 'blocksuite/crates/playground/web');
const ORACLE_DIR = path.join(REPO_ROOT, 'blocksuite/crates/oracle');
// `web/index.html` fetches the tracked `ui-tokens` and Source Serif 4 fonts from `assets/fonts/<file>`.
const FONT_DIRS = [
path.join(REPO_ROOT, 'packages/ui/tokens/fonts'),
path.join(REPO_ROOT, 'packages/frontend/component/src/fonts/source-serif-4'),
];
const FONT_FILES = new Map(
FONT_DIRS.flatMap(dir =>
fs
.readdirSync(dir, { recursive: true })
.filter(rel => rel.endsWith('.ttf'))
.map(rel => [path.basename(rel), path.join(dir, rel)])
)
);
function parseArgs(argv) {
const args = {
outPage: path.join(ROOT, 'artifacts', 'wasm-chromium.png'),
outEdgeless: path.join(ROOT, 'artifacts', 'wasm-chromium-edgeless.png'),
// Query string appended to the page URL, e.g. `room=<room>&ws=<ws_url>`.
query: '',
// Dark ink pixels required in the title/body region before the page is captured.
minTitleInk: 200,
};
for (let i = 2; i < argv.length; i += 1) {
if (argv[i] === '--out' && argv[i + 1]) {
args.outPage = path.resolve(argv[++i]);
} else if (argv[i] === '--out-edgeless' && argv[i + 1]) {
args.outEdgeless = path.resolve(argv[++i]);
} else if (argv[i] === '--query' && argv[i + 1]) {
args.query = argv[++i].replace(/^\?/, '');
} else if (argv[i] === '--min-title-ink' && argv[i + 1]) {
args.minTitleInk = Number(argv[++i]);
if (!Number.isFinite(args.minTitleInk) || args.minTitleInk < 0) {
throw new Error('--min-title-ink requires a non-negative number');
}
}
}
return args;
}
function mimeType(filePath) {
if (filePath.endsWith('.html')) return 'text/html; charset=utf-8';
if (filePath.endsWith('.js') || filePath.endsWith('.mjs'))
return 'application/javascript; charset=utf-8';
if (filePath.endsWith('.wasm')) return 'application/wasm';
if (filePath.endsWith('.css')) return 'text/css; charset=utf-8';
return 'application/octet-stream';
}
function createStaticServer(dir) {
return http.createServer((req, res) => {
const urlPath = (req.url || '/').split('?')[0];
const rel = urlPath === '/' ? 'index.html' : urlPath.replace(/^\/+/, '');
const fontFile = rel.startsWith('assets/fonts/')
? FONT_FILES.get(decodeURIComponent(rel.slice('assets/fonts/'.length)))
: undefined;
const abs = fontFile ?? path.resolve(dir, rel);
if (
(!fontFile && !abs.startsWith(dir)) ||
!fs.existsSync(abs) ||
fs.statSync(abs).isDirectory()
) {
res.writeHead(404);
res.end('Not found');
return;
}
res.writeHead(200, {
'Content-Type': mimeType(abs),
'Cache-Control': 'no-store',
});
fs.createReadStream(abs).pipe(res);
});
}
function decodePngRgba(buf) {
const sig = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
if (!buf.subarray(0, 8).equals(sig)) throw new Error('Invalid PNG signature');
let offset = 8;
let width = 0;
let height = 0;
let bitDepth = 0;
let colorType = 0;
const idatChunks = [];
while (offset < buf.length) {
const len = buf.readUInt32BE(offset);
const type = buf.subarray(offset + 4, offset + 8).toString('ascii');
const data = buf.subarray(offset + 8, offset + 8 + len);
offset += 12 + len;
if (type === 'IHDR') {
width = data.readUInt32BE(0);
height = data.readUInt32BE(4);
bitDepth = data[8];
colorType = data[9];
} else if (type === 'IDAT') {
idatChunks.push(data);
} else if (type === 'IEND') {
break;
}
}
if (bitDepth !== 8 || (colorType !== 6 && colorType !== 2)) {
throw new Error(
`Unsupported PNG format: bitDepth=${bitDepth}, colorType=${colorType}`
);
}
const bpp = colorType === 6 ? 4 : 3;
const raw = zlib.inflateSync(Buffer.concat(idatChunks));
const stride = width * bpp;
const rgba = new Uint8Array(width * height * 4);
const prevRow = new Uint8Array(stride);
const curRow = new Uint8Array(stride);
function paeth(a, b, c) {
const p = a + b - c;
const pa = Math.abs(p - a);
const pb = Math.abs(p - b);
const pc = Math.abs(p - c);
return pa <= pb && pa <= pc ? a : pb <= pc ? b : c;
}
for (let y = 0; y < height; y += 1) {
const filter = raw[y * (stride + 1)];
const rowStart = y * (stride + 1) + 1;
for (let i = 0; i < stride; i += 1) {
const x = raw[rowStart + i];
const a = i >= bpp ? curRow[i - bpp] : 0;
const b = prevRow[i];
const c = i >= bpp ? prevRow[i - bpp] : 0;
let val = x;
if (filter === 1) val = (x + a) & 0xff;
else if (filter === 2) val = (x + b) & 0xff;
else if (filter === 3) val = (x + ((a + b) >> 1)) & 0xff;
else if (filter === 4) val = (x + paeth(a, b, c)) & 0xff;
curRow[i] = val;
}
for (let x = 0; x < width; x += 1) {
const dst = (y * width + x) * 4;
const src = x * bpp;
rgba[dst] = curRow[src];
rgba[dst + 1] = curRow[src + 1];
rgba[dst + 2] = curRow[src + 2];
rgba[dst + 3] = bpp === 4 ? curRow[src + 3] : 255;
}
prevRow.set(curRow);
}
return { width, height, rgba };
}
function countDarkInkPixels(img, x0, y0, x1, y1) {
let dark = 0;
const minX = Math.max(0, Math.floor(x0));
const minY = Math.max(0, Math.floor(y0));
const maxX = Math.min(img.width, Math.ceil(x1));
const maxY = Math.min(img.height, Math.ceil(y1));
for (let y = minY; y < maxY; y += 1) {
for (let x = minX; x < maxX; x += 1) {
const idx = (y * img.width + x) * 4;
const r = img.rgba[idx];
const g = img.rgba[idx + 1];
const b = img.rgba[idx + 2];
if (r < 140 && g < 140 && b < 140) dark += 1;
}
}
return dark;
}
function countDifferentPixels(a, b) {
if (a.width !== b.width || a.height !== b.height) return Infinity;
let diff = 0;
for (let i = 0; i < a.rgba.length; i += 4) {
if (
Math.abs(a.rgba[i] - b.rgba[i]) > 4 ||
Math.abs(a.rgba[i + 1] - b.rgba[i + 1]) > 4 ||
Math.abs(a.rgba[i + 2] - b.rgba[i + 2]) > 4
) {
diff += 1;
}
}
return diff;
}
function sleep(ms) {
return new Promise(r => setTimeout(r, ms));
}
class CdpClient {
constructor(wsUrl) {
this.ws = new WebSocket(wsUrl);
this.nextId = 1;
this.pending = new Map();
this.listeners = new Map();
this.ready = new Promise((resolve, reject) => {
this.ws.addEventListener('open', resolve);
this.ws.addEventListener('error', reject);
});
this.ws.addEventListener('message', event => {
const msg = JSON.parse(event.data);
if (msg.id) {
const entry = this.pending.get(msg.id);
if (entry) {
this.pending.delete(msg.id);
if (msg.error)
entry.reject(new Error(entry.method + ': ' + msg.error.message));
else entry.resolve(msg.result);
}
} else if (msg.method) {
const list = this.listeners.get(msg.method) || [];
for (const fn of list) fn(msg.params);
}
});
}
on(method, fn) {
const list = this.listeners.get(method) || [];
list.push(fn);
this.listeners.set(method, list);
}
async send(method, params = {}) {
await this.ready;
const id = this.nextId++;
return new Promise((resolve, reject) => {
this.pending.set(id, { method, resolve, reject });
this.ws.send(JSON.stringify({ id, method, params }));
});
}
close() {
this.ws.close();
}
}
// Drive the page the way a person's pointer, keyboard and IME do, and read back the hidden
// textarea the browser's text input works on.
function inputProbe(cdp) {
async function evaluate(expression) {
const reply = await cdp.send('Runtime.evaluate', {
expression,
awaitPromise: true,
returnByValue: true,
});
if (reply.exceptionDetails)
throw new Error(reply.exceptionDetails.exception?.description);
return reply.result.value;
}
const mirror = () =>
evaluate(
"Array.from(document.querySelectorAll('textarea')).map(t=>({value:t.value,offset:t.selectionStart,end:t.selectionEnd}))[0]"
);
const mouse = (type, [x, y], buttons) =>
cdp.send('Input.dispatchMouseEvent', {
type,
x,
y,
button: type === 'mouseMoved' ? 'none' : 'left',
buttons,
clickCount: 1,
});
const click = async point => {
await mouse('mousePressed', point, 1);
await mouse('mouseReleased', point, 0);
await sleep(100);
return mirror();
};
const waitValue = async value => {
let state;
for (let i = 0; i < 40; i++) {
state = await mirror();
if (state.value === value) return;
await sleep(50);
}
const screenshot = path.join(ROOT, 'artifacts', 'web-smoke-failure.png');
fs.mkdirSync(path.dirname(screenshot), { recursive: true });
const shot = await cdp.send('Page.captureScreenshot', { format: 'png' });
const png = Buffer.from(shot.data, 'base64');
fs.writeFileSync(screenshot, png);
const toolbar = await evaluate(`({ focus: document.activeElement?.tagName,
readOnly: document.querySelector('textarea')?.readOnly, atLink: document.elementFromPoint(426,216)?.tagName })`);
toolbar.darkPixels = countDarkInkPixels(
decodePngRgba(png),
175,
185,
560,
243
);
console.error({ screenshot, mirror: state, toolbar });
throw new Error(
`Expected mirrored text ${JSON.stringify(value)}, got ${JSON.stringify(state)}`
);
};
const composition = (type, data) =>
evaluate(
`document.querySelector('textarea').dispatchEvent(new CompositionEvent(${JSON.stringify(type)},{bubbles:true,data:${JSON.stringify(data)}}))`
);
// `modifiers: 2` is Control, the command modifier outside macOS.
const key = async (key, code, windowsVirtualKeyCode, modifiers = 0) => {
for (const type of ['rawKeyDown', 'keyUp']) {
await cdp.send('Input.dispatchKeyEvent', {
type,
key,
code,
modifiers,
windowsVirtualKeyCode,
});
}
};
return { evaluate, mirror, mouse, click, waitValue, composition, key };
}
// Exercise the browser input handler through the same hidden textarea a platform IME uses.
async function checkComposition(cdp) {
const { mouse, click, waitValue, composition, key } = inputProbe(cdp);
const undo = () => key('z', 'KeyZ', 90, 2);
const first = [314, 215],
second = [331, 254];
const start = await click(first),
end = await click(second);
if (start.value !== 'Page mode' || !end.value.startsWith('This page')) {
throw new Error(
`Unable to select the two showcase blocks: ${JSON.stringify([start, end])}`
);
}
for (const reverse of [false, true]) {
const a = reverse ? second : first,
b = reverse ? first : second;
const original = reverse ? start : end;
await mouse('mousePressed', a, 1);
await mouse('mouseMoved', b, 1);
await mouse('mouseReleased', b, 0);
await waitValue(original.value);
await composition('compositionstart', '');
await composition('compositionupdate', 'ni');
await sleep(75);
await composition('compositionend', '');
await waitValue(original.value);
// Cancellation must restore the directional document range for the next IME.
await composition('compositionstart', '');
await composition('compositionupdate', 'nihao');
await sleep(75);
await composition('compositionend', '你好');
const joined = token =>
start.value.slice(0, start.offset) + token + end.value.slice(end.offset);
await waitValue(joined('你好'));
await undo();
await waitValue(original.value);
await cdp.send('Input.insertText', { text: 'Z' });
await waitValue(joined('Z'));
await undo();
await waitValue(original.value);
}
console.log(
'Forward and backward cross-block typing, IME cancellation, commit and undo passed'
);
}
// The formatting toolbar's link field is the text input while it is open: composition
// and paste go into the field, and the paragraph under the selection stays as it was.
async function checkLinkField(cdp) {
const { evaluate, mirror, mouse, waitValue, composition, key } =
inputProbe(cdp);
// A few words on the first line of the second showcase block.
const from = [331, 254],
to = [400, 254];
await evaluate(
'new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))'
);
await mouse('mousePressed', from, 1);
await mouse('mouseMoved', to, 1);
await mouse('mouseReleased', to, 0);
await evaluate(
'new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)))'
);
await sleep(100);
const paragraph = await mirror();
if (!(paragraph.end > paragraph.offset + 3)) {
throw new Error(
`Link toolbar drag selected fewer than four characters: ${JSON.stringify(paragraph)}`
);
}
if (!paragraph.value.startsWith('This page')) {
throw new Error(
`Unable to select in the second showcase block: ${JSON.stringify(paragraph)}`
);
}
// A selection in one paragraph shows a 462 px toolbar without Create Table.
// It sits 10 px above the selected line and is 37 px tall.
// The Link button center is 299 px from the left edge and 18 px from the top.
const midX = (from[0] + to[0]) / 2;
const link = [midX - 462 / 2 + 299, 243 - 10 - 37 + 18];
await mouse('mouseMoved', link, 0);
await mouse('mousePressed', link, 1);
await mouse('mouseReleased', link, 0);
await waitValue('');
// A composition that is cancelled leaves the field empty; one that commits lands once.
await composition('compositionstart', '');
await composition('compositionupdate', 'ni');
await sleep(75);
await composition('compositionend', '');
await waitValue('');
await composition('compositionstart', '');
await composition('compositionupdate', 'nihao');
await sleep(75);
await composition('compositionend', '你好');
await waitValue('你好');
// The paste key keeps its default action, so the browser follows it with a `paste`
// event, and that event's text goes into the field.
await evaluate(`window.__pasteKeyPrevented = null;
window.addEventListener('keydown', e => {
if (e.key === 'v' && e.ctrlKey) window.__pasteKeyPrevented = e.defaultPrevented;
})`);
await key('v', 'KeyV', 86, 2);
const prevented = await evaluate('window.__pasteKeyPrevented');
if (prevented !== false) {
throw new Error(
`Ctrl+V in the link field must keep its default action, defaultPrevented=${prevented}`
);
}
const ignored = await evaluate(`(() => {
const data = new DataTransfer();
data.setData('text/plain', '.affine.pro');
return document.querySelector('textarea').dispatchEvent(
new ClipboardEvent('paste', { bubbles: true, cancelable: true, clipboardData: data }));
})()`);
if (ignored)
throw new Error('The paste event was not taken by the link field');
await waitValue('你好.affine.pro');
// Dual-field LinkBar: clicking the Text row mirrors the selected paragraph slice, and
// clicking back to the URL row restores focus to the typed/pasted URL.
const selectedSlice = paragraph.value.slice(paragraph.offset, paragraph.end);
// With both fields open the toolbar is 100 px tall: the Text row starts 37 px and the
// URL row 65 px below its top edge, and each row is 28 px tall.
const textFieldPt = [midX, 243 - 10 - 100 + 37 + 14];
await mouse('mouseMoved', textFieldPt, 0);
await mouse('mousePressed', textFieldPt, 1);
await mouse('mouseReleased', textFieldPt, 0);
await waitValue(selectedSlice);
const urlFieldPt = [midX - 40, 243 - 10 - 100 + 65 + 14];
await mouse('mouseMoved', urlFieldPt, 0);
await mouse('mousePressed', urlFieldPt, 1);
await mouse('mouseReleased', urlFieldPt, 0);
await waitValue('你好.affine.pro');
// Closing the field hands the text input back to the paragraph, untouched.
await key('Escape', 'Escape', 27);
await waitValue(paragraph.value);
console.log(
'Link field composition, paste and dismissal left the paragraph untouched'
);
}
async function main() {
const args = parseArgs(process.argv);
const pkgJs = path.join(WEB_DIR, 'pkg', 'playground.js');
if (!fs.existsSync(pkgJs)) {
throw new Error(`Missing wasm-bindgen output at ${pkgJs}`);
}
let harness;
let server;
let cdp;
const errors = [];
const consoleLogs = [];
try {
harness = createChromiumHarness({ tmpPrefix: 'affine-web-smoke-' });
server = createStaticServer(WEB_DIR);
await new Promise((ok, fail) => {
server.once('error', fail);
server.listen(0, '127.0.0.1', ok);
});
const { port } = server.address();
const browserPort = await harness.launchChromium(SWIFTSHADER_OPTIONS);
const attachPage = async target => {
cdp?.close();
cdp = new CdpClient(target.webSocketDebuggerUrl);
await cdp.send('Page.enable');
await cdp.send('Runtime.enable');
await cdp.send('Emulation.setDeviceMetricsOverride', {
width: 1280,
height: 800,
deviceScaleFactor: 1,
mobile: false,
});
cdp.on('Runtime.exceptionThrown', params => {
const desc =
params?.exceptionDetails?.exception?.description ||
params?.exceptionDetails?.text ||
'exception';
errors.push(`Runtime.exceptionThrown: ${desc}`);
});
cdp.on('Runtime.consoleAPICalled', params => {
const text = (params.args || [])
.map(a => a.value ?? a.description ?? '')
.join(' ');
consoleLogs.push(`[console.${params.type}] ${text}`);
if (params.type === 'error') {
errors.push(`console.error: ${text}`);
}
});
await cdp.send('Emulation.setFocusEmulationEnabled', { enabled: true });
await cdp.send('Page.bringToFront');
};
await attachPage(await openPageTarget(browserPort));
const pageUrl = `http://127.0.0.1:${port}/${args.query ? `?${args.query}` : ''}`;
const navigateToCanvas = async url => {
await cdp.send('Page.navigate', { url });
// Wait for wasm init + graphics init + ResizeObserver sizing canvas to 1280x800
let ready = false;
let lastState = null;
for (let i = 0; i < 80; i += 1) {
const evalRes = await cdp.send('Runtime.evaluate', {
expression: `JSON.stringify({
ready: Boolean(window.__playgroundReady),
err: window.__playgroundError,
bodyText: (document.body && document.body.innerText || '').trim(),
inputMounted: Boolean(document.querySelector('textarea')),
canvasCount: document.querySelectorAll('canvas').length,
canvasRect: (() => {
const c = document.querySelector('canvas');
if (!c) return null;
const r = c.getBoundingClientRect();
return { w: r.width, h: r.height, cw: c.width, ch: c.height };
})()
})`,
returnByValue: true,
});
const state = JSON.parse(evalRes.result.value);
lastState = state;
if (state.err) throw new Error(`Wasm init error: ${state.err}`);
if (state.bodyText && state.bodyText.length > 0) {
throw new Error(
`Browser page reported error text: ${state.bodyText}\nLogs: ${consoleLogs.join('\n')}`
);
}
if (
state.ready &&
state.inputMounted &&
state.canvasCount > 0 &&
state.canvasRect &&
state.canvasRect.cw >= 1200 &&
state.canvasRect.ch >= 700
) {
ready = true;
break;
}
await sleep(250);
}
if (!ready) {
throw new Error(
`Timed out waiting for Wasm canvas to mount at 1280x800. lastState=${JSON.stringify(lastState)} Errors=${errors.join('; ')} Logs=${consoleLogs.join(' | ')}`
);
}
return lastState;
};
const lastState = await navigateToCanvas(pageUrl);
// Wait for SwiftShader WebGL2 first frame paint (compile + draw can take >1s)
let png1 = null;
let img1 = null;
let pillDark = 0;
let titleDark = 0;
for (let attempt = 0; attempt < 40; attempt += 1) {
await sleep(300);
const shot1 = await cdp.send('Page.captureScreenshot', { format: 'png' });
png1 = Buffer.from(shot1.data, 'base64');
img1 = decodePngRgba(png1);
pillDark = countDarkInkPixels(img1, 547, 8, 733, 44);
titleDark = countDarkInkPixels(img1, 168, 100, 900, 260);
if (pillDark >= 40 && titleDark >= args.minTitleInk) {
break;
}
}
fs.mkdirSync(path.dirname(args.outPage), { recursive: true });
fs.writeFileSync(args.outPage, png1);
// Assert actual dark ink glyph pixels exist in the mode pill and title regions
console.log(
`Web Wasm Page render: ${img1.width}x${img1.height}, pillDarkPx=${pillDark}, titleDarkPx=${titleDark}`
);
if (pillDark < 40) {
throw new Error(
`Expected rendered glyph pixels inside mode-switcher pill (>=40), got ${pillDark}. state=${JSON.stringify(lastState)} logs=${consoleLogs.join(' | ')}`
);
}
if (titleDark < args.minTitleInk) {
throw new Error(
`Expected rendered glyph pixels inside title/body region (>=${args.minTitleInk}), got ${titleDark}. state=${JSON.stringify(lastState)} logs=${consoleLogs.join(' | ')}`
);
}
if (!args.query) {
await checkComposition(cdp);
await checkLinkField(cdp);
const baselines = await measureSurfaceBaselines(inputProbe(cdp).evaluate);
assert.deepEqual(
baselines,
JSON.parse(
fs.readFileSync(
path.join(ORACLE_DIR, 'surface-baselines.json'),
'utf8'
)
)
);
console.log('Chromium DOM and Canvas surface label baselines passed');
}
// Click "Edgeless" segment (pill centered at x=640, w=186 -> pill_x=547; edgeless x=548+94..548+180 -> center=685, y=26)
const clickX = 685;
const clickY = 26;
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
x: clickX,
y: clickY,
button: 'none',
});
await cdp.send('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: clickX,
y: clickY,
button: 'left',
clickCount: 1,
});
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: clickX,
y: clickY,
button: 'left',
clickCount: 1,
});
await sleep(600);
const shot2 = await cdp.send('Page.captureScreenshot', { format: 'png' });
const png2 = Buffer.from(shot2.data, 'base64');
fs.mkdirSync(path.dirname(args.outEdgeless), { recursive: true });
fs.writeFileSync(args.outEdgeless, png2);
const img2 = decodePngRgba(png2);
const diffPx = countDifferentPixels(img1, img2);
console.log(`Web Wasm Edgeless click diffPixels=${diffPx}`);
if (diffPx < 5000) {
throw new Error(
`Clicking Edgeless did not produce expected visual transition (diffPixels=${diffPx})`
);
}
const edgelessInk = countDarkInkPixels(img2, 40, 80, 1240, 760);
console.log(`Web Wasm Edgeless canvas ink=${edgelessInk}`);
if (edgelessInk < 500) {
throw new Error(
`Expected non-trivial Edgeless canvas ink (>=500), got ${edgelessInk}`
);
}
if (!args.query) {
// Exercise Edgeless bottom creation toolbar: select Shape tool (`s`) and drag a new shape on canvas.
await cdp.send('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 640,
y: 400,
button: 'left',
clickCount: 1,
});
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 640,
y: 400,
button: 'left',
clickCount: 1,
});
await sleep(100);
for (const type of ['rawKeyDown', 'keyUp']) {
await cdp.send('Input.dispatchKeyEvent', {
type,
key: 's',
code: 'KeyS',
windowsVirtualKeyCode: 83,
});
}
await sleep(100);
await cdp.send('Input.dispatchMouseEvent', {
type: 'mousePressed',
x: 520,
y: 300,
button: 'left',
clickCount: 1,
});
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseMoved',
x: 680,
y: 400,
button: 'left',
buttons: 1,
});
await cdp.send('Input.dispatchMouseEvent', {
type: 'mouseReleased',
x: 680,
y: 400,
button: 'left',
clickCount: 1,
});
await sleep(300);
const shotShape = await cdp.send('Page.captureScreenshot', {
format: 'png',
});
const imgShape = decodePngRgba(Buffer.from(shotShape.data, 'base64'));
const shapeDiff = countDifferentPixels(img2, imgShape);
console.log(`Web Wasm Edgeless shape creation diffPixels=${shapeDiff}`);
if (shapeDiff < 100) {
throw new Error(
`Edgeless shape creation produced insufficient visual change (${shapeDiff})`
);
}
// Also verify direct `?mode=edgeless` cold load without WebGL2/WebGPU shader errors.
// A fresh target has no renderer or CDP state from the edited page.
await attachPage(await openPageTarget(browserPort));
await navigateToCanvas(`http://127.0.0.1:${port}/?mode=edgeless`);
await inputProbe(cdp).evaluate(`new Promise(resolve => {
requestAnimationFrame(() => requestAnimationFrame(() => resolve(true)));
})`);
const shot3 = await cdp.send('Page.captureScreenshot', { format: 'png' });
const img3 = decodePngRgba(Buffer.from(shot3.data, 'base64'));
const edgelessDirectInk = countDarkInkPixels(img3, 40, 80, 1240, 760);
console.log(`Web Wasm direct ?mode=edgeless ink=${edgelessDirectInk}`);
if (edgelessDirectInk < 500) {
throw new Error(
`Direct ?mode=edgeless rendered insufficient ink (${edgelessDirectInk})`
);
}
}
if (errors.length > 0) {
throw new Error(
`Uncaught browser errors during Wasm smoke test:\n${errors.join('\n')}`
);
}
console.log('Web Wasm Chromium smoke test PASSED.');
} finally {
await closeBrowserResources(harness, cdp, server);
}
}
main().catch(err => {
console.error(err);
process.exit(1);
});
+315
View File
@@ -0,0 +1,315 @@
#!/usr/bin/env node
// Zero-backend CSF geometry gate. Bundles the Frame Audit stories, lays them
// out in headless Chrome, and audits each frame with the Rust `frame-audit`
// engine. Every story must have no violations, and each corrupted copy of a
// real frame must report exactly the violations it was built to cause.
//
// node scripts/ci/check-csf-frame-audit.mjs
//
// The browser is $CHROME_BIN, or google-chrome / chromium from PATH.
import { spawnSync } from 'node:child_process';
import {
existsSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { delimiter, extname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { chromium } from '@playwright/test';
import { vanillaExtractPlugin } from '@vanilla-extract/vite-plugin';
import swc from 'unplugin-swc';
import { build } from 'vite';
const ROOT = fileURLToPath(new URL('../..', import.meta.url));
const COMPONENT = join(ROOT, 'packages/frontend/component');
const OUT = join(ROOT, '.artifacts/csf-frame-audit');
const ORIGIN = 'http://frame-audit.invalid';
const REQUIRED_STORIES = 7;
const MIME = {
'.js': 'text/javascript',
'.css': 'text/css',
'.woff2': 'font/woff2',
'.avif': 'image/avif',
};
function findChrome() {
if (process.env.CHROME_BIN) return process.env.CHROME_BIN;
for (const dir of (process.env.PATH ?? '').split(delimiter)) {
for (const name of ['google-chrome', 'chromium']) {
if (existsSync(join(dir, name))) return join(dir, name);
}
}
throw new Error('no Chrome found: set CHROME_BIN');
}
async function bundleStories() {
rmSync(OUT, { recursive: true, force: true });
mkdirSync(OUT, { recursive: true });
await build({
configFile: false,
root: COMPONENT,
logLevel: 'error',
define: { 'process.env.NODE_ENV': '"production"' },
plugins: [
vanillaExtractPlugin(),
swc.vite({
jsc: {
parser: { syntax: 'typescript', tsx: true, decorators: true },
target: 'es2022',
transform: {
react: { runtime: 'automatic' },
useDefineForClassFields: false,
decoratorVersion: '2022-03',
},
},
}),
],
build: {
outDir: OUT,
emptyOutDir: false,
minify: false,
cssCodeSplit: false,
rollupOptions: {
input: join(COMPONENT, 'src/ui/frame-audit/harness.tsx'),
output: {
format: 'es',
inlineDynamicImports: true,
entryFileNames: 'harness.js',
assetFileNames: '[name][extname]',
},
},
},
});
}
async function captureFrames() {
const browser = await chromium.launch({
executablePath: findChrome(),
args: ['--no-sandbox', '--font-render-hinting=none'],
});
try {
const page = await browser.newPage({
viewport: { width: 800, height: 600 },
deviceScaleFactor: 1,
});
const errors = [];
page.on('pageerror', error => errors.push(error.message));
// Every request is answered from the bundle; nothing leaves the process.
await page.route('**/*', route => {
const { origin, pathname } = new URL(route.request().url());
if (origin !== ORIGIN) return route.abort();
if (pathname === '/') {
return route.fulfill({
contentType: 'text/html',
body: `<!doctype html><html><head>
<link rel="stylesheet" href="/style.css">
<style>body{margin:0}</style>
<script>globalThis.BUILD_CONFIG={isMobileEdition:false}</script>
<script type="module" src="/harness.js"></script>
</head><body></body></html>`,
});
}
const file = join(OUT, pathname);
if (!existsSync(file)) return route.fulfill({ status: 404, body: '' });
return route.fulfill({
contentType: MIME[extname(file)] ?? 'application/octet-stream',
body: readFileSync(file),
});
});
await page.goto(`${ORIGIN}/`);
await page.waitForFunction(() => 'captureFrameAuditStories' in window);
const captured = await page.evaluate(
cases => window.captureFrameAuditStories(cases),
DOM_CASES
);
if (errors.length) throw new Error(`page errors: ${errors.join('; ')}`);
return captured;
} finally {
await browser.close();
}
}
function audit(frames) {
const input = join(OUT, 'frames.json');
writeFileSync(input, JSON.stringify(frames));
const result = spawnSync(
'cargo',
[
'run',
'--locked',
'--quiet',
'--manifest-path',
'tools/frame-audit/Cargo.toml',
'--bin',
'audit-frames',
'--',
'--frames',
input,
],
{
cwd: ROOT,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
env: { ...process.env, CARGO_ENCODED_RUSTFLAGS: '' },
}
);
if (result.status !== 0) {
throw new Error(`frame-audit audit-frames failed:\n${result.stderr}`);
}
return JSON.parse(result.stdout);
}
const NEGATIVE_CASES = [
{
name: 'button pushed past its clip',
story: 'DialogFooter',
corrupt: f => {
f.elements['dialog.cancel'].bounds.x = 200;
},
expected: [['parent-clip-fault', 'dialog.cancel']],
},
{
name: 'icon centered on the whole text block',
story: 'FirstLineBaseline',
corrupt: f => {
f.elements['row.icon'].bounds.y += 12;
},
expected: [['first-line-baseline', 'row.icon']],
},
{
name: 'footer wraps the primary action upward',
story: 'DialogFooter',
corrupt: f => {
const { 'dialog.confirm': a, 'dialog.cancel': b } = f.elements;
[a.bounds.y, b.bounds.y] = [b.bounds.y, a.bounds.y];
},
expected: [['footer-reverse-wrap', 'dialog.confirm']],
},
{
name: 'inner radius above the concentric limit',
story: 'NestedRadii',
corrupt: f => {
f.elements['card.inner'].corner_radius = 16;
},
expected: [['concentric-corner-radius', 'card.inner']],
},
{
name: 'double divider after a hidden row',
story: 'DividedList',
corrupt: f => {
f.elements['list.b'].opacity = 0;
},
expected: [['divider-placement', 'list.divider-c']],
},
{
name: 'dangling divider after the last row',
story: 'DividedList',
corrupt: f => {
f.elements['list.c'].opacity = 0;
},
expected: [['divider-placement', 'list.divider-c']],
},
{
name: 'invisible button still takes the pointer',
story: 'NarrowContainer',
corrupt: f => {
f.elements['narrow.action'].opacity = 0;
},
expected: [['zero-opacity-hit-through', 'narrow.action']],
},
{
name: 'page content above the overlay',
story: 'FloatingOverlay',
corrupt: f => {
for (const probe of f.hit_probes) probe.receiver = 'page.action';
},
expected: [['overlay-z-order', 'menu']],
},
];
// Applied to the rendered element in the browser, then captured again.
const DOM_CASES = [
{
name: 'ellipsis degraded to clip',
story: 'NarrowContainer',
element: 'narrow.name',
style: { textOverflow: 'clip' },
expected: [['text-truncation', 'narrow.name']],
},
{
name: 'fractional cell moved past its clip',
story: 'FractionalThirds',
element: 'thirds.c',
style: { transform: 'translateX(400px)' },
expected: [['parent-clip-fault', 'thirds.c']],
},
];
const keyOf = ([rule, element]) => `${rule} @ ${element}`;
const keys = list => [...new Set(list.map(keyOf))].sort();
await bundleStories();
const { frames, domFrames } = await captureFrames();
const names = Object.keys(frames);
const problems = [];
if (names.length < REQUIRED_STORIES) {
problems.push(`only ${names.length} stories captured`);
}
for (const [name, frame] of Object.entries(frames)) {
if (Object.keys(frame.elements).length < 2) {
problems.push(`${name}: no audited elements were captured`);
}
}
// 470px in three cells only stays gap-free when each edge is snapped alone.
const thirds = ['a', 'b', 'c'].map(
cell => frames.FractionalThirds.elements[`thirds.${cell}`].bounds.width
);
if (
thirds.reduce((sum, width) => sum + width) !== 470 ||
new Set(thirds).size < 2
) {
problems.push(`FractionalThirds: unexpected widths ${thirds.join(', ')}`);
}
const inputs = { ...frames };
for (const { name } of DOM_CASES) {
inputs[`negative: ${name}`] = domFrames[name];
}
for (const { name, story, corrupt } of NEGATIVE_CASES) {
const copy = structuredClone(frames[story]);
corrupt(copy);
inputs[`negative: ${name}`] = copy;
}
const report = audit(inputs);
for (const name of names) {
for (const v of report[name]) {
problems.push(`${name}: ${v.rule} @ ${v.element_id}: ${v.message}`);
}
}
for (const { name, expected } of [...NEGATIVE_CASES, ...DOM_CASES]) {
const found = keys(
report[`negative: ${name}`].map(v => [v.rule, v.element_id])
);
const want = keys(expected);
if (found.join('\n') !== want.join('\n')) {
problems.push(
`negative "${name}": expected [${want.join(', ')}], got [${found.join(', ')}]`
);
}
}
if (problems.length) {
console.error(problems.join('\n'));
console.error(`CSF frame audit: ${problems.length} problem(s)`);
process.exit(1);
}
console.log(
`CSF frame audit passed: ${names.length} stories clean, ${NEGATIVE_CASES.length + DOM_CASES.length} corrupted frames rejected`
);
+182
View File
@@ -20,6 +20,10 @@
// 7. compat-backlog: every `// compat(<kind>): <slug> -- <reason>` marker in
// packages/backend/ production Rust has a `### <slug>` entry in
// docs/post-cutover-ablation-backlog.md, and every entry has a marker.
// 8. Directory classification: every first-level subdirectory under
// packages/frontend/, packages/common/, and blocksuite/ belongs to a known
// legacy Web set or a known Rust/client set, and native-playground.yml's
// web-build filter covers every legacy Web subdirectory.
import { createHash } from 'node:crypto';
import {
@@ -761,6 +765,184 @@ if (!existsSync(COMPAT_BACKLOG_PATH)) {
}
}
// 8. Top-level directory classification for web-build filter ----------------
const DOMAIN_CLASSIFICATION = {
'packages/ui': {
legacyWeb: new Set([]),
newRust: new Set(['ui', 'kit', 'tokens']),
ignored: new Set(['node_modules']),
},
'packages/frontend': {
legacyWeb: new Set([
'admin',
'apps',
'component',
'core',
'electron-api',
'i18n',
'mobile-native',
'native',
'routes',
'templates',
'track',
]),
newRust: new Set([
'client',
'desktop',
'hosts',
'legacy-import',
'mobile',
'perf',
'scripts',
]),
ignored: new Set(['target', 'artifacts', 'node_modules']),
},
'packages/common': {
legacyWeb: new Set([
'auth',
'debug',
'env',
'error',
'graphql',
'infra',
'native',
'nbstore',
'reader',
'realtime',
's3-compat',
'theme',
]),
newRust: new Set(['store']),
ignored: new Set(['node_modules']),
},
blocksuite: {
legacyWeb: new Set([
'affine',
'docs',
'docs-site',
'framework',
'integration-test',
'playground',
]),
newRust: new Set(['crates']),
ignored: new Set(['node_modules']),
},
};
const WEB_BUILD_FIXED_ENTRIES = new Set([
'blocksuite/tsconfig.json',
'tools/cli/**',
'**/package.json',
'**/tsconfig*.json',
'yarn.lock',
'.yarnrc.yml',
'.yarn/**',
'.github/actions/setup-node/**',
'.github/workflows/np-web-build.yml',
]);
const npWorkflowPath = join(WORKFLOWS, 'native-playground.yml');
const npWorkflowText = existsSync(npWorkflowPath) ? read(npWorkflowPath) : '';
const webBuildSectionMatch = /^\s*web-build:\n((?:\s+-\s+.*\n)+)/m.exec(
npWorkflowText
);
const webBuildEntries = new Set(
(webBuildSectionMatch?.[1] ?? '')
.split('\n')
.map(l => /^\s*-\s+['"]?([^'"]+?)['"]?\s*$/.exec(l)?.[1])
.filter(Boolean)
);
const expectedWebBuildEntries = new Set(WEB_BUILD_FIXED_ENTRIES);
for (const [baseDir, sets] of Object.entries(DOMAIN_CLASSIFICATION)) {
const fullBase = join(ROOT, baseDir);
if (!existsSync(fullBase)) continue;
for (const entry of readdirSync(fullBase, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const name = entry.name;
if (sets.ignored.has(name)) continue;
if (!sets.legacyWeb.has(name) && !sets.newRust.has(name)) {
fail(
'dir-classification',
`${baseDir}/${name}: unclassified directory; add it to legacyWeb (and native-playground.yml web-build) or newRust in scripts/ci/check-l0-tier-a.mjs`
);
}
}
for (const legacy of sets.legacyWeb) {
expectedWebBuildEntries.add(`${baseDir}/${legacy}/**`);
}
}
for (const expected of expectedWebBuildEntries) {
if (!webBuildEntries.has(expected)) {
fail(
'dir-classification',
`.github/workflows/native-playground.yml: web-build filter is missing ${expected}`
);
}
}
for (const actual of webBuildEntries) {
if (!expectedWebBuildEntries.has(actual)) {
fail(
'dir-classification',
`.github/workflows/native-playground.yml: web-build filter contains unexpected broad or unknown pattern ${actual}`
);
}
}
function globToRegExp(glob) {
let out = '^';
for (let i = 0; i < glob.length; i += 1) {
if (glob.slice(i, i + 3) === '**/') {
out += '(?:.*/)?';
i += 2;
} else if (glob.slice(i, i + 2) === '**') {
out += '.*';
i += 1;
} else if (glob[i] === '*') {
out += '[^/]*';
} else {
out += glob[i].replace(/[.+?^${}()|[\]\\]/g, '\\$&');
}
}
return new RegExp(`${out}$`);
}
const webBuildRegexes = [...webBuildEntries].map(globToRegExp);
const matchesWebBuild = paths =>
paths.some(p => webBuildRegexes.some(re => re.test(p)));
const WEB_BUILD_FILTER_CASES = [
['oracle-only', ['blocksuite/crates/oracle/style-oracle.json'], false],
[
'rust-only',
[
'packages/ui/ui/src/lib.rs',
'packages/common/store/AGENTS.md',
'blocksuite/crates/doc/src/lib.rs',
],
false,
],
['legacy-ts', ['packages/frontend/core/src/index.ts'], true],
[
'mixed',
['packages/ui/ui/src/lib.rs', 'packages/common/infra/src/index.ts'],
true,
],
];
for (const [label, paths, expected] of WEB_BUILD_FILTER_CASES) {
const actual = matchesWebBuild(paths);
if (actual !== expected) {
fail(
'dir-classification',
`web-build filter self-test "${label}" returned ${actual}, expected ${expected}`
);
}
}
// ---------------------------------------------------------------------------
const ms = Math.round(performance.now() - started);
+458
View File
@@ -0,0 +1,458 @@
#!/usr/bin/env node
// Classify changed paths for CI.
import { execFileSync } from 'node:child_process';
import { appendFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
export const ZERO_SHA = '0000000000000000000000000000000000000000';
export const TRUNK_REFS = Object.freeze(
new Set([
'darksky/np/mobile',
'canary',
'darksky/native-playground',
'main',
'refs/heads/darksky/np/mobile',
'refs/heads/canary',
'refs/heads/darksky/native-playground',
'refs/heads/main',
])
);
// Events that always run every lane, Apple jobs included.
const FULL_RUN_EVENTS = Object.freeze(
new Set(['pull_request', 'workflow_dispatch'])
);
// A change under these paths runs the macOS and iOS jobs on topic branches.
const APPLE_PATH_PREFIXES = ['.cargo/'];
const APPLE_PATHS = new Set([
'.github/workflows/native-playground.yml',
'.github/workflows/np-mobile.yml',
'packages/ui/ui/tests/metal_atlas_fence.rs',
'scripts/ci/classify-web-host-only.mjs',
'scripts/ci/classify-web-host-only.test.mjs',
]);
const APPLE_SEGMENT_OR_MANIFEST_RE =
/(?:^|\/)(?:macos|ios|apple)\/|\.(?:swift|metal|m|mm)$|(?:^|\/)(?:Cargo\.toml|Cargo\.lock|build\.rs|rust-toolchain\.toml)$/;
// Source text that compiles only for Apple targets.
export const APPLE_TARGET_CFG_RE =
/\btarget_os\s*=\s*"(?:macos|ios)"|\btarget_vendor\s*=\s*"apple"/;
export function isAppleSpecificPath(filePath) {
return (
APPLE_PATHS.has(filePath) ||
APPLE_PATH_PREFIXES.some(prefix => filePath.startsWith(prefix)) ||
APPLE_SEGMENT_OR_MANIFEST_RE.test(filePath)
);
}
export const WEB_HOST_ONLY_ALLOWLIST = Object.freeze(
new Set([
'packages/frontend/hosts/web/src/idb-storage.js',
'packages/frontend/hosts/web/desktop/boot.js',
'packages/frontend/hosts/web/desktop/start.js',
'packages/frontend/hosts/web/desktop/index.html',
'packages/frontend/hosts/web/tests/idb-storage.test.mjs',
'packages/frontend/hosts/web/tests/desktop.test.mjs',
'packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs',
])
);
const DESKTOP_LEAF_DIRS = [
'packages/frontend/desktop/src/',
'packages/frontend/desktop/tests/',
];
function noFastLane(reason) {
return {
webHostOnly: false,
desktopLeafOnly: false,
desktopRsOnly: false,
backendOnly: false,
webWrapperOnly: false,
appleSpecific: true,
reason,
checkedPaths: [],
};
}
function fullRunReason(forceAll, ref, event) {
if (forceAll === true || forceAll === 'true') return 'force_all';
if (isTrunkRef(ref)) return 'trunk_ref';
if (event === 'pull_request' || ref.trim().startsWith('refs/pull/')) {
return 'pull_request';
}
if (FULL_RUN_EVENTS.has(event)) return event;
return null;
}
export function isTrunkRef(ref) {
return typeof ref === 'string' && TRUNK_REFS.has(ref.trim());
}
export function isValidBaseSha(baseSha) {
if (typeof baseSha !== 'string') return false;
const trimmed = baseSha.trim();
return /^[0-9a-f]{7,64}$/i.test(trimmed) && !/^0+$/.test(trimmed);
}
function parseNulTokens(raw) {
if (raw === '') return { valid: true, entries: [] };
const tokens = raw.split('\0');
if (tokens[tokens.length - 1] === '') {
tokens.pop();
}
const entries = [];
let i = 0;
while (i < tokens.length) {
const status = tokens[i++];
if (/^[RC]\d*$/.test(status)) {
const oldPath = tokens[i++];
const newPath = tokens[i++];
if (!oldPath || !newPath) {
return { valid: false, entries: [] };
}
entries.push({ status, paths: [oldPath, newPath] });
} else if (/^[AMDT]$/.test(status)) {
const filePath = tokens[i++];
if (!filePath) {
return { valid: false, entries: [] };
}
entries.push({ status, paths: [filePath] });
} else {
return { valid: false, entries: [] };
}
}
return { valid: true, entries };
}
function parseTabLines(lines) {
const entries = [];
for (const rawLine of lines) {
if (typeof rawLine !== 'string') {
return { valid: false, entries: [] };
}
if (rawLine.length === 0) continue;
const parts = rawLine.split('\t');
const status = parts[0];
if (/^[RC]\d*$/.test(status)) {
if (parts.length !== 3 || !parts[1] || !parts[2]) {
return { valid: false, entries: [] };
}
entries.push({ status, paths: [parts[1], parts[2]] });
} else if (/^[AMDT]$/.test(status)) {
if (parts.length !== 2 || !parts[1]) {
return { valid: false, entries: [] };
}
entries.push({ status, paths: [parts[1]] });
} else {
return { valid: false, entries: [] };
}
}
return { valid: true, entries };
}
export function parseNameStatus(input) {
if (Buffer.isBuffer(input)) {
return parseNulTokens(input.toString('utf8'));
}
if (typeof input === 'string') {
if (input.includes('\0')) {
return parseNulTokens(input);
}
return parseTabLines(input.split(/\r?\n/));
}
if (Array.isArray(input)) {
return parseTabLines(input);
}
return { valid: false, entries: [] };
}
export function classifyWebHostOnly(options = {}) {
const {
nameStatus,
nameStatusLines,
forceAll = false,
baseSha,
ref = '',
event = '',
contentTouchesApple = false,
} = options;
const fullRun = fullRunReason(forceAll, ref, event);
if (fullRun) {
return noFastLane(fullRun);
}
if (baseSha !== undefined && !isValidBaseSha(baseSha)) {
return noFastLane('invalid_base');
}
const rawInput = nameStatus !== undefined ? nameStatus : nameStatusLines;
if (rawInput === undefined || rawInput === null) {
return noFastLane('missing_diff');
}
const parsed = parseNameStatus(rawInput);
if (!parsed.valid) {
return noFastLane('invalid_name_status');
}
if (parsed.entries.length === 0) {
return noFastLane('empty_diff');
}
const checkedPaths = parsed.entries.flatMap(entry => entry.paths);
const webHostOnly = checkedPaths.every(filePath =>
WEB_HOST_ONLY_ALLOWLIST.has(filePath)
);
const isDesktopRustPath = filePath =>
filePath.endsWith('.rs') &&
DESKTOP_LEAF_DIRS.some(dir => filePath.startsWith(dir));
const desktopRsOnly = checkedPaths.every(isDesktopRustPath);
const appleSpecific =
contentTouchesApple === true ||
checkedPaths.some(
filePath =>
isAppleSpecificPath(filePath) ||
(contentTouchesApple instanceof Set &&
contentTouchesApple.has(filePath))
);
return {
webHostOnly,
desktopLeafOnly:
!webHostOnly &&
checkedPaths.every(
filePath =>
WEB_HOST_ONLY_ALLOWLIST.has(filePath) || isDesktopRustPath(filePath)
),
desktopRsOnly,
backendOnly: checkedPaths.every(filePath =>
filePath.startsWith('packages/backend/')
),
webWrapperOnly: checkedPaths.every(filePath =>
filePath.startsWith('packages/frontend/hosts/web/')
),
appleSpecific,
reason: webHostOnly ? 'allowlist_only' : 'non_allowlist_path',
checkedPaths,
};
}
function runGitDiff(cwd, args) {
return execFileSync('git', ['diff', '--name-status', '-z', ...args], {
cwd,
encoding: 'buffer',
maxBuffer: 64 * 1024 * 1024,
stdio: ['ignore', 'pipe', 'pipe'],
});
}
// Returns the changed paths whose old or new text has an Apple target cfg, or
// true when a blob cannot be read.
function findAppleCfgPaths(cwd, oldRev, newRev, entries) {
const hits = new Set();
const textHasAppleCfg = (rev, filePath) =>
APPLE_TARGET_CFG_RE.test(
execFileSync('git', ['cat-file', '-p', `${rev}:${filePath}`], {
cwd,
encoding: 'utf8',
maxBuffer: 32 * 1024 * 1024,
stdio: ['ignore', 'pipe', 'pipe'],
})
);
try {
for (const { status, paths } of entries) {
const oldPath = paths[0];
const newPath = paths[paths.length - 1];
const blobs =
status === 'A'
? [[newRev, newPath]]
: status === 'D'
? [[oldRev, oldPath]]
: [
[oldRev, oldPath],
[newRev, newPath],
];
if (blobs.some(([rev, filePath]) => textHasAppleCfg(rev, filePath))) {
paths.forEach(filePath => hits.add(filePath));
}
}
} catch {
return true;
}
return hits;
}
export function classifyGitDiff({
baseSha,
head = 'HEAD',
forceAll = false,
ref = '',
event = '',
cwd = process.cwd(),
} = {}) {
const fullRun = fullRunReason(forceAll, ref, event);
if (fullRun) {
return noFastLane(fullRun);
}
if (!isValidBaseSha(baseSha)) {
return noFastLane('invalid_base');
}
const trimmedBase = baseSha.trim();
const gitOpts = {
cwd,
encoding: 'buffer',
stdio: ['ignore', 'pipe', 'pipe'],
};
let mergeBase;
try {
execFileSync(
'git',
['rev-parse', '--verify', '--quiet', `${trimmedBase}^{commit}`],
gitOpts
);
execFileSync(
'git',
['rev-parse', '--verify', '--quiet', `${head}^{commit}`],
gitOpts
);
mergeBase = execFileSync('git', ['merge-base', trimmedBase, head], gitOpts)
.toString('utf8')
.trim();
} catch {
return noFastLane('unreachable_base');
}
const diffRange = `${trimmedBase}...${head}`;
let diffBuf;
try {
diffBuf = runGitDiff(cwd, [diffRange]);
} catch {
return noFastLane('git_diff_error');
}
const parsed = parseNameStatus(diffBuf);
const contentTouchesApple =
parsed.valid &&
!parsed.entries.some(entry => entry.paths.some(isAppleSpecificPath))
? findAppleCfgPaths(cwd, mergeBase, head, parsed.entries)
: false;
const classify = nameStatus =>
classifyWebHostOnly({
nameStatus,
forceAll,
baseSha: trimmedBase,
ref,
event,
contentTouchesApple,
});
const initial = classify(diffBuf);
if (
!initial.webHostOnly &&
!initial.desktopLeafOnly &&
!initial.backendOnly &&
!initial.webWrapperOnly
) {
return initial;
}
if (!parsed.entries.some(entry => entry.status === 'A')) {
return initial;
}
// Check both paths when Git detects a copy from a file that did not change.
let copyDiffBuf;
try {
copyDiffBuf = runGitDiff(cwd, ['-C', '--find-copies-harder', diffRange]);
} catch {
return noFastLane('git_diff_error');
}
return classify(copyDiffBuf);
}
function parseCliArgs(argv) {
const args = {
baseSha: process.env.BASE ?? '',
head: 'HEAD',
forceAll: process.env.FORCE_ALL ?? 'false',
ref: process.env.GITHUB_REF ?? process.env.GITHUB_REF_NAME ?? '',
event: process.env.GITHUB_EVENT_NAME ?? '',
githubOutput: process.env.GITHUB_OUTPUT ?? '',
cwd: process.cwd(),
};
for (let i = 0; i < argv.length; i++) {
const flag = argv[i];
const value = argv[i + 1];
if (flag === '--base' && value !== undefined) {
args.baseSha = value;
i++;
} else if (flag === '--head' && value !== undefined) {
args.head = value;
i++;
} else if (flag === '--force-all' && value !== undefined) {
args.forceAll = value;
i++;
} else if (flag === '--ref' && value !== undefined) {
args.ref = value;
i++;
} else if (flag === '--event' && value !== undefined) {
args.event = value;
i++;
} else if (flag === '--github-output' && value !== undefined) {
args.githubOutput = value;
i++;
} else if (flag === '--cwd' && value !== undefined) {
args.cwd = value;
i++;
} else {
throw new Error(`Unknown or incomplete argument: ${flag}`);
}
}
return args;
}
function main() {
const args = parseCliArgs(process.argv.slice(2));
const result = classifyGitDiff({
baseSha: args.baseSha,
head: args.head,
forceAll: args.forceAll,
ref: args.ref,
event: args.event,
cwd: args.cwd,
});
if (args.githubOutput) {
appendFileSync(
args.githubOutput,
`web_host_only=${result.webHostOnly}\n` +
`desktop_leaf_only=${result.desktopLeafOnly}\n` +
`desktop_rs_only=${result.desktopRsOnly}\n` +
`backend_only=${result.backendOnly}\n` +
`web_wrapper_only=${result.webWrapperOnly}\n` +
`apple_specific=${result.appleSpecific}\n`
);
}
const summary =
`web_host_only=${result.webHostOnly} ` +
`(${result.reason}, ${result.checkedPaths.length} path(s))`;
console.log(summary);
console.log(`desktop_leaf_only=${result.desktopLeafOnly}`);
console.log(`desktop_rs_only=${result.desktopRsOnly}`);
console.log(`apple_specific=${result.appleSpecific}`);
}
const isMain =
process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
if (isMain) {
main();
}
+914
View File
@@ -0,0 +1,914 @@
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import {
mkdirSync,
mkdtempSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import {
classifyGitDiff,
classifyWebHostOnly,
WEB_HOST_ONLY_ALLOWLIST,
ZERO_SHA,
} from './classify-web-host-only.mjs';
const REPO_ROOT = fileURLToPath(new URL('../..', import.meta.url));
const CLI_PATH = join(REPO_ROOT, 'scripts/ci/classify-web-host-only.mjs');
const SAMPLE_BASE = '65460a7f136d32b15d0d4398f0f4976273c51c9d';
await test('Native Playground CI applies desktop gates under the correct conditions', () => {
const workflow = readFileSync(
join(REPO_ROOT, '.github/workflows/native-playground.yml'),
'utf8'
);
const jobs = new Map();
const jobBlocks = workflow.split('\njobs:\n')[1].split(/(?=^ {2}[\w-]+:\n)/m);
for (const block of jobBlocks) {
const [heading, ...lines] = block.split('\n');
jobs.set(heading.trim().slice(0, -1), lines.join('\n'));
}
const step = (job, name) => {
const body = jobs
.get(job)
.split(/^ {6}- name: /m)
.find(block => block.startsWith(`${name}\n`));
assert.ok(body, `Missing step: ${name}`);
return body
.trimEnd()
.split('\n')
.map(line => line.trim());
};
const lintJob = 'lint-and-wasm';
const clippy = step(lintJob, 'Clippy check');
assert.deepEqual(clippy.slice(3, -1), [
'cargo clippy --locked --workspace --all-targets --features harness -- -D warnings',
]);
const tokenDrift = step(
lintJob,
'Verify generated tokens, icons, and fonts.lock have zero drift'
);
assert.equal(tokenDrift[1], 'run: |');
assert.ok(
tokenDrift.includes(
'node ../ui/tokens/extract-tokens.mjs --check --node-modules /tmp/np-token-deps/node_modules'
)
);
const wasmCheck = step(lintJob, 'Check WebAssembly target');
assert.equal(
wasmCheck[1],
"if: needs.changes.outputs.desktop-rs-only != 'true'"
);
assert.deepEqual(wasmCheck.slice(4, -1), [
'cargo check --locked -p ui-tokens -p ui -p ui-kit -p blocksuite-editor -p playground --target wasm32-unknown-unknown',
'cargo check --locked -p blocksuite-playground-doc --no-default-features --target wasm32-unknown-unknown',
'cargo check --locked -p affine-store --no-default-features --target wasm32-unknown-unknown',
'cargo check --locked -p blocksuite-preview --no-default-features --features mermaid,wasm-worker --target wasm32-unknown-unknown',
'cargo check --locked -p blocksuite-preview --no-default-features --features math,wasm-worker --target wasm32-unknown-unknown',
'cargo check --locked -p blocksuite-preview --no-default-features --features typst,wasm-worker --target wasm32-unknown-unknown',
'cargo check --locked -p blocksuite-preview --no-default-features --features pdf,wasm-worker --target wasm32-unknown-unknown',
]);
const allTargetsCheck =
'cargo check --locked -p affine-desktop --all-targets --features harness';
const desktopCheck = step(
lintJob,
'Check Desktop on Linux (default and harness)'
);
assert.equal(
desktopCheck[1],
"if: needs.changes.outputs.desktop-rs-only == 'true'"
);
assert.deepEqual(desktopCheck.slice(4, -1), [
'cargo check --locked -p affine-desktop --lib',
allTargetsCheck,
]);
const desktopTest = step(
'headless-linux-and-perf',
'Test Desktop on Linux (default and harness)'
);
assert.equal(
desktopTest[1],
"if: needs.changes.outputs.desktop-leaf-only == 'true'"
);
assert.deepEqual(desktopTest.slice(4, -1), [
'cargo test --locked -p affine-desktop',
'cargo test --locked -p affine-desktop --features harness --bin desktop-harness',
'if [ "${{ needs.changes.outputs.desktop-rs-only }}" != "true" ]; then',
allTargetsCheck,
'fi',
]);
assert.deepEqual(
[...jobs].flatMap(([job, body]) =>
[...body.matchAll(/^ +timeout-minutes: (.+)$/gm)].map(([, value]) => [
job,
value,
])
),
[
['web-wasm-smoke', '20'],
['headless-linux-and-perf', '25'],
['perf-guardrail', '5'],
]
);
});
await test('allowlist remains frozen to the seven pure web-host paths', () => {
assert.deepEqual(
[...WEB_HOST_ONLY_ALLOWLIST],
[
'packages/frontend/hosts/web/src/idb-storage.js',
'packages/frontend/hosts/web/desktop/boot.js',
'packages/frontend/hosts/web/desktop/start.js',
'packages/frontend/hosts/web/desktop/index.html',
'packages/frontend/hosts/web/tests/idb-storage.test.mjs',
'packages/frontend/hosts/web/tests/desktop.test.mjs',
'packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs',
]
);
});
await test('classifyWebHostOnly handles allowlist, rename, and guards', () => {
const cases = [
{
name: 'single allowlisted file modification',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-web-fix',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: true,
},
{
name: 'multi-file allowlist modification matching e7236462b016',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-wave-h2-idb-quota',
nameStatusLines: [
'M\tpackages/frontend/hosts/web/desktop/start.js',
'M\tpackages/frontend/hosts/web/src/idb-storage.js',
'M\tpackages/frontend/hosts/web/tests/desktop.test.mjs',
'M\tpackages/frontend/hosts/web/tests/idb-storage.test.mjs',
],
},
expected: true,
},
{
name: 'allowlist files mixed with Rust source or Cargo.toml',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-mixed',
nameStatusLines: [
'M\tpackages/frontend/hosts/web/src/idb-storage.js',
'M\tpackages/frontend/Cargo.toml',
],
},
expected: false,
},
{
name: 'allowlist files mixed with .rs file',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-mixed-rs',
nameStatusLines: [
'M\tpackages/frontend/hosts/web/desktop/start.js',
'M\tpackages/frontend/mobile/src/lib.rs',
],
},
expected: false,
},
{
name: 'preview-workers.js included by Rust tests must be false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-preview-worker',
nameStatusLines: [
'M\tblocksuite/crates/playground/web/preview-workers.js',
],
},
expected: false,
},
{
name: 'R100 rename inside allowlist is true',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-rename-in',
nameStatusLines: [
[
'R100',
'packages/frontend/hosts/web/desktop/start.js',
'packages/frontend/hosts/web/src/idb-storage.js',
].join('\t'),
],
},
expected: true,
},
{
name: 'R100 rename from outside allowlist into allowlist is false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-rename-into',
nameStatusLines: [
[
'R100',
'packages/frontend/hosts/web/src/other.js',
'packages/frontend/hosts/web/src/idb-storage.js',
].join('\t'),
],
},
expected: false,
},
{
name: 'R100 rename from allowlist to outside allowlist is false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-rename-out',
nameStatusLines: [
[
'R100',
'packages/frontend/hosts/web/desktop/start.js',
'packages/frontend/hosts/web/desktop/start-v2.js',
].join('\t'),
],
},
expected: false,
},
{
name: 'C100 copy from outside allowlist into allowlist is false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-copy-into',
nameStatusLines: [
[
'C100',
'packages/frontend/hosts/web/src/other.js',
'packages/frontend/hosts/web/src/idb-storage.js',
].join('\t'),
],
},
expected: false,
},
{
name: 'web host helper script verify-idb-real-browser.mjs must be false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-script',
nameStatusLines: [
'M\tpackages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs',
],
},
expected: false,
},
{
name: 'empty diff must be false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-empty',
nameStatusLines: [],
},
expected: false,
},
{
name: 'forceAll=true overrides allowlist diff to false',
input: {
baseSha: SAMPLE_BASE,
forceAll: true,
ref: 'refs/heads/darksky/np/mobile-force',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: false,
},
{
name: 'trunk push to refs/heads/darksky/np/mobile must be false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: false,
},
{
name: 'trunk push to refs/heads/canary must be false',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/canary',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: false,
},
{
name: 'zero SHA base must be false',
input: {
baseSha: ZERO_SHA,
ref: 'refs/heads/darksky/np/mobile-zero',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: false,
},
{
name: 'missing base SHA must be false',
input: {
baseSha: '',
ref: 'refs/heads/darksky/np/mobile-missing-base',
nameStatusLines: ['M\tpackages/frontend/hosts/web/src/idb-storage.js'],
},
expected: false,
},
{
name: 'NUL-delimited -z output works for allowlist and rejects invalid status',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-z',
nameStatus:
'M\0packages/frontend/hosts/web/desktop/index.html\0' +
'M\0packages/frontend/hosts/web/tests/dual-shell-save.browser.mjs\0',
},
expected: true,
},
{
name: 'unknown git status code fails closed',
input: {
baseSha: SAMPLE_BASE,
ref: 'refs/heads/darksky/np/mobile-unknown',
nameStatus: 'U\0packages/frontend/hosts/web/src/idb-storage.js\0',
},
expected: false,
},
];
for (const tc of cases) {
const result = classifyWebHostOnly(tc.input);
assert.equal(result.webHostOnly, tc.expected, tc.name);
}
});
await test('Desktop lanes distinguish Rust changes from mixed web host changes', () => {
const desktop = 'packages/frontend/desktop';
const source = `M\t${desktop}/src/window/mod.rs`;
const webHost = 'M\tpackages/frontend/hosts/web/src/idb-storage.js';
const cases = [
['Desktop source', [source], [false, true, true]],
['Desktop test', [`A\t${desktop}/tests/smoke.rs`], [false, true, true]],
['Desktop and web host', [source, webHost], [false, true, false]],
['web host only', [webHost], [true, false, false]],
['empty diff', [], [false, false, false]],
[
'Desktop manifest',
[source, `M\t${desktop}/Cargo.toml`],
[false, false, false],
],
[
'workspace lockfile',
[source, 'M\tpackages/frontend/Cargo.lock'],
[false, false, false],
],
['Desktop asset', [`M\t${desktop}/src/icon.png`], [false, false, false]],
['Desktop build script', [`M\t${desktop}/build.rs`], [false, false, false]],
[
'client source',
[source, 'M\tpackages/frontend/client/src/lib.rs'],
[false, false, false],
],
[
'BlockSuite source',
[source, 'M\tblocksuite/crates/editor/src/lib.rs'],
[false, false, false],
],
[
'rename from client',
[`R100\tpackages/frontend/client/src/lib.rs\t${desktop}/src/moved.rs`],
[false, false, false],
],
[
'rename within Desktop',
[`R100\t${desktop}/src/old.rs\t${desktop}/src/new.rs`],
[false, true, true],
],
['invalid status', [`U\t${desktop}/src/file.rs`], [false, false, false]],
];
for (const [label, nameStatusLines, expected] of cases) {
const { webHostOnly, desktopLeafOnly, desktopRsOnly } = classifyWebHostOnly(
{
nameStatusLines,
baseSha: SAMPLE_BASE,
}
);
assert.deepEqual(
[webHostOnly, desktopLeafOnly, desktopRsOnly],
expected,
label
);
}
for (const guard of [
{ forceAll: true },
{ ref: 'refs/heads/darksky/np/mobile' },
{ baseSha: ZERO_SHA },
]) {
const result = classifyWebHostOnly({ nameStatusLines: [source], ...guard });
assert.equal(result.webHostOnly, false, result.reason);
assert.equal(result.desktopLeafOnly, false, result.reason);
assert.equal(result.desktopRsOnly, false, result.reason);
}
});
function createGitRunner(cwd) {
return (...args) =>
execFileSync('git', args, {
cwd,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
}).trim();
}
await test('classifyGitDiff handles Git commits, lane guards, and CLI outputs', () => {
const tmpRepo = mkdtempSync(join(tmpdir(), 'classify-web-host-'));
const outputFile = join(tmpRepo, 'github-output.txt');
try {
const git = createGitRunner(tmpRepo);
git('init', '-b', 'main');
git('config', 'user.name', 'Test User');
git('config', 'user.email', 'test@example.com');
const allowFile = join(
tmpRepo,
'packages/frontend/hosts/web/src/idb-storage.js'
);
const desktopHtmlFile = join(
tmpRepo,
'packages/frontend/hosts/web/desktop/index.html'
);
const desktopStartFile = join(
tmpRepo,
'packages/frontend/hosts/web/desktop/start.js'
);
const otherFile = join(
tmpRepo,
'packages/frontend/hosts/web/scripts/verify-idb-real-browser.mjs'
);
const otherContent = [
'export function runVerify(target) {',
' const steps = ["boot", "sync", "persist", "reload"];',
' return steps.map((step, index) => `${index}:${target}:${step}`);',
'}',
'',
].join('\n');
mkdirSync(join(tmpRepo, 'packages/frontend/hosts/web/src'), {
recursive: true,
});
mkdirSync(join(tmpRepo, 'packages/frontend/hosts/web/desktop'), {
recursive: true,
});
mkdirSync(join(tmpRepo, 'packages/frontend/hosts/web/scripts'), {
recursive: true,
});
const backend = 'packages/backend/server-domain/src';
const web = 'packages/frontend/hosts/web';
const sharedSource = 'packages/common/store/shared.js';
const sharedContent = 'export const shared = "common store";\n';
mkdirSync(join(tmpRepo, backend), { recursive: true });
mkdirSync(join(tmpRepo, 'packages/common/store'), { recursive: true });
writeFileSync(join(tmpRepo, sharedSource), sharedContent);
writeFileSync(join(tmpRepo, backend, 'lib.rs'), 'pub fn first() {}\n');
writeFileSync(join(tmpRepo, web, 'index.html'), '<title>Base</title>\n');
writeFileSync(allowFile, 'export const v = 1;\n');
writeFileSync(otherFile, otherContent);
git('add', '.');
git('commit', '-m', 'base');
const baseSha = git('rev-parse', 'HEAD');
// Empty diff against self -> false.
assert.equal(
classifyGitDiff({
baseSha,
ref: 'refs/heads/darksky/np/mobile-test',
cwd: tmpRepo,
}).webHostOnly,
false
);
// Pure allowlist commit -> true.
writeFileSync(allowFile, 'export const v = 2;\n');
git('add', '.');
git('commit', '-m', 'web host only');
const cliOut = execFileSync(
process.execPath,
[
CLI_PATH,
'--base',
baseSha,
'--ref',
'refs/heads/darksky/np/mobile-test',
'--github-output',
outputFile,
],
{ cwd: tmpRepo, encoding: 'utf8' }
);
assert.match(cliOut, /^web_host_only=true /);
assert.equal(
readFileSync(outputFile, 'utf8'),
'web_host_only=true\ndesktop_leaf_only=false\ndesktop_rs_only=false\n' +
'backend_only=false\nweb_wrapper_only=true\napple_specific=false\n'
);
assert.match(cliOut, /^apple_specific=false$/m);
const webHostSha = git('rev-parse', 'HEAD');
const desktopDir = join(tmpRepo, 'packages/frontend/desktop/src');
const desktopFile = join(desktopDir, 'new.rs');
mkdirSync(desktopDir, { recursive: true });
writeFileSync(desktopFile, 'pub fn unique() {}\n');
git('add', desktopFile);
git('commit', '-m', 'add Desktop source');
const desktop = classifyGitDiff({ baseSha: webHostSha, cwd: tmpRepo });
assert.equal(desktop.desktopLeafOnly, true);
assert.equal(desktop.desktopRsOnly, true);
const mixed = classifyGitDiff({ baseSha, cwd: tmpRepo });
assert.equal(mixed.desktopLeafOnly, true);
assert.equal(mixed.desktopRsOnly, false);
assert.equal(mixed.webHostOnly, false);
writeFileSync(desktopFile, otherContent);
git('add', desktopFile);
git('commit', '-m', 'copy into Desktop source');
const desktopCopy = classifyGitDiff({ baseSha: webHostSha, cwd: tmpRepo });
assert.equal(desktopCopy.desktopLeafOnly, false);
assert.equal(desktopCopy.desktopRsOnly, false);
git('reset', '--hard', 'HEAD~2');
// Unreachable / non-existent base -> false.
assert.equal(
classifyGitDiff({
baseSha: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
ref: 'refs/heads/darksky/np/mobile-test',
cwd: tmpRepo,
}).webHostOnly,
false
);
// Brand-new unique allowlisted file -> still true after copy re-check.
writeFileSync(
desktopHtmlFile,
'<!doctype html><title>AFFiNE Workbench</title>\n'
);
git('add', desktopHtmlFile);
git('commit', '-m', 'add unique allowlisted html');
assert.equal(
classifyGitDiff({
baseSha,
ref: 'refs/heads/darksky/np/mobile-test',
cwd: tmpRepo,
}).webHostOnly,
true
);
// Copying an unmodified non-allowlisted file into a newly added
// allowlisted file -> false (caught by --find-copies-harder).
writeFileSync(desktopStartFile, otherContent);
git('add', desktopStartFile);
git('commit', '-m', 'copy non-allowlisted file into allowlisted path');
const copyResult = classifyGitDiff({
baseSha,
ref: 'refs/heads/darksky/np/mobile-test',
cwd: tmpRepo,
});
assert.equal(copyResult.webHostOnly, false);
assert.equal(copyResult.reason, 'non_allowlist_path');
// Adding a non-allowlisted file -> false.
writeFileSync(otherFile, 'export const s = 2;\n');
git('add', otherFile);
git('commit', '-m', 'touch helper script');
assert.equal(
classifyGitDiff({
baseSha,
ref: 'refs/heads/darksky/np/mobile-test',
cwd: tmpRepo,
}).webHostOnly,
false
);
const cases = [
{
name: 'backend edits and additions',
files: [
[`${backend}/lib.rs`, 'pub fn second() {}\n'],
[`${backend}/new.rs`, 'pub fn new_file() {}\n'],
],
backendOnly: true,
},
{
name: 'Web wrapper HTML and script edits',
files: [
[`${web}/index.html`, '<title>Updated</title>\n'],
[
`${web}/scripts/verify-idb-real-browser.mjs`,
'export const v = 3;\n',
],
],
webWrapperOnly: true,
},
{
name: 'copy from the common store into an allowlisted Web wrapper path',
files: [[`${web}/desktop/start.js`, sharedContent]],
copyTo: `${web}/desktop/start.js`,
},
{
name: 'copy from the common store into the backend',
files: [[`${backend}/copy.js`, sharedContent]],
copyTo: `${backend}/copy.js`,
},
{
name: 'mixed backend and Web wrapper edits',
files: [
[`${backend}/lib.rs`, 'pub fn second() {}\n'],
[`${web}/index.html`, '<title>Updated</title>\n'],
],
},
];
for (const {
name,
files,
copyTo,
backendOnly = false,
webWrapperOnly = false,
} of cases) {
git('reset', '--hard', baseSha);
for (const [path, content] of files) {
const file = join(tmpRepo, path);
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, content);
}
git('add', '--', ...files.map(([path]) => path));
git('commit', '-m', name);
if (copyTo) {
assert.equal(
git(
'diff',
'--name-status',
'-C',
'--find-copies-harder',
baseSha,
'HEAD'
),
`C100\t${sharedSource}\t${copyTo}`
);
}
const result = classifyGitDiff({ baseSha, cwd: tmpRepo });
assert.equal(result.backendOnly, backendOnly, name);
assert.equal(result.webWrapperOnly, webWrapperOnly, name);
assert.equal(result.webHostOnly, false, name);
assert.equal(result.desktopLeafOnly, false, name);
assert.equal(result.desktopRsOnly, false, name);
if (backendOnly || webWrapperOnly) {
for (const guard of [
{ forceAll: 'true' },
{ ref: 'refs/heads/darksky/np/mobile' },
{ baseSha: ZERO_SHA },
{ baseSha: 'deadbeefdeadbeefdeadbeefdeadbeefdeadbeef' },
{ baseSha: git('rev-parse', 'HEAD') },
]) {
const guarded = classifyGitDiff({ baseSha, cwd: tmpRepo, ...guard });
assert.equal(guarded.backendOnly, false, guarded.reason);
assert.equal(guarded.webWrapperOnly, false, guarded.reason);
}
}
}
} finally {
rmSync(tmpRepo, { recursive: true, force: true });
}
});
await test('classifyWebHostOnly flags Apple jobs for full runs and Apple paths', () => {
const slice = 'refs/heads/darksky/np/mobile-r29-foo';
const crossPlatform = [
'M\tpackages/frontend/desktop/src/sidebar/mod.rs',
'M\tblocksuite/crates/editor/src/directory.rs',
'M\tpackages/frontend/mobile/src/state/derived.rs',
];
const cases = [
['trunk darksky/np/mobile', { ref: 'refs/heads/darksky/np/mobile' }, true],
['trunk canary', { ref: 'refs/heads/canary' }, true],
['trunk main', { ref: 'refs/heads/main' }, true],
['pull request ref', { ref: 'refs/pull/123/merge' }, true],
['pull request event', { ref: slice, event: 'pull_request' }, true],
['manual dispatch', { ref: slice, event: 'workflow_dispatch' }, true],
['force all', { ref: slice, forceAll: true }, true],
['invalid base', { ref: slice, baseSha: ZERO_SHA }, true],
['empty diff', { ref: slice, nameStatusLines: [] }, true],
['missing diff', { ref: slice, nameStatusLines: null }, true],
['cross-platform slice', { ref: slice }, false],
['push event slice', { ref: slice, event: 'push' }, false],
['content hit', { ref: slice, contentTouchesApple: true }, true],
[
'content hit on a changed path',
{
ref: slice,
contentTouchesApple: new Set([
'blocksuite/crates/editor/src/directory.rs',
]),
},
true,
],
[
'content hit on an unchanged path',
{ ref: slice, contentTouchesApple: new Set(['other.rs']) },
false,
],
];
for (const path of [
'packages/ui/ui/src/platform/apple/metal_renderer.rs',
'packages/ui/ui/src/platform/macos/window.rs',
'packages/ui/ui/src/platform/ios/window.rs',
'packages/frontend/hosts/ios/Sources/AppDelegate.swift',
'packages/frontend/apps/ios/App/App/AppDelegate.swift',
'.cargo/config.toml',
'packages/ui/ui/tests/metal_atlas_fence.rs',
'packages/ui/ui/build.rs',
'packages/frontend/Cargo.toml',
'packages/frontend/Cargo.lock',
'packages/frontend/desktop/Cargo.toml',
'packages/frontend/native/media_capture/build.rs',
'packages/frontend/native/media_capture/src/macos/audio_buffer.rs',
'packages/frontend/rust-toolchain.toml',
'packages/ui/ui/src/platform/apple/shaders.metal',
'Cargo.lock',
'rust-toolchain.toml',
'.github/workflows/native-playground.yml',
'.github/workflows/np-mobile.yml',
'scripts/ci/classify-web-host-only.mjs',
]) {
cases.push([path, { ref: slice, nameStatusLines: [`M\t${path}`] }, true]);
}
cases.push([
'rename out of an Apple path',
{
ref: slice,
nameStatusLines: [
'R100\tpackages/ui/ui/src/platform/macos/a.rs\tpackages/ui/ui/src/b.rs',
],
},
true,
]);
for (const [label, input, expected] of cases) {
const result = classifyWebHostOnly({
baseSha: SAMPLE_BASE,
nameStatusLines: crossPlatform,
...input,
});
assert.equal(result.appleSpecific, expected, `${label} (${result.reason})`);
}
});
await test('classifyWebHostOnly skips non-Apple desktop topic branches and runs trunk', () => {
const desktopLeaf = 'packages/frontend/desktop/src/views_extra/scroll.rs';
const rows = [
[
'non-Apple desktop topic branch',
{
ref: 'refs/heads/darksky/np/mobile-test',
event: 'push',
nameStatusLines: [`M\t${desktopLeaf}`],
contentTouchesApple: false,
},
{ appleSpecific: false, desktopLeafOnly: true },
],
[
'same desktop change on trunk',
{
ref: 'refs/heads/darksky/np/mobile',
event: 'push',
nameStatusLines: [`M\t${desktopLeaf}`],
contentTouchesApple: false,
},
{ appleSpecific: true, desktopLeafOnly: false },
],
[
'Apple-cfg desktop topic branch',
{
ref: 'refs/heads/darksky/np/mobile-test',
event: 'push',
nameStatusLines: [`M\t${desktopLeaf}`],
contentTouchesApple: true,
},
{ appleSpecific: true, desktopLeafOnly: true },
],
[
'workflow push on darksky/native-playground',
{
ref: 'refs/heads/darksky/native-playground',
event: 'push',
nameStatusLines: ['M\t.github/workflows/native-playground.yml'],
contentTouchesApple: false,
},
{ appleSpecific: true, desktopLeafOnly: false },
],
];
for (const [label, input, expected] of rows) {
const result = classifyWebHostOnly({ baseSha: SAMPLE_BASE, ...input });
assert.equal(
result.appleSpecific,
expected.appleSpecific,
`${label} appleSpecific`
);
assert.equal(
result.desktopLeafOnly,
expected.desktopLeafOnly,
`${label} desktopLeafOnly`
);
}
});
await test('classifyGitDiff flags Apple jobs from Apple target cfg text', () => {
const tmpRepo = mkdtempSync(join(tmpdir(), 'classify-apple-cfg-'));
try {
const git = createGitRunner(tmpRepo);
const write = (path, content) => {
const file = join(tmpRepo, path);
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, content);
};
git('init', '-b', 'main');
git('config', 'user.name', 'Test User');
git('config', 'user.email', 'test@example.com');
const moreMenu = 'blocksuite/crates/editor/src/more_menu.rs';
const vendorFile = 'blocksuite/crates/editor/src/vendor.rs';
const plain = 'blocksuite/crates/editor/src/directory.rs';
write(
moreMenu,
'#[cfg(target_os = "macos")]\nconst COPY: &str = "C";\nfn a() {}\n'
);
write(vendorFile, '#[cfg(target_vendor = "apple")]\nfn v() {}\n');
write(plain, 'pub fn directory() {}\n');
git('add', '.');
git('commit', '-m', 'base');
const baseSha = git('rev-parse', 'HEAD');
const cases = [
[
'edit outside the cfg in a file with a macOS cfg',
() =>
write(
moreMenu,
'#[cfg(target_os = "macos")]\nconst COPY: &str = "C";\nfn b() {}\n'
),
true,
],
[
'add a file with an iOS cfg',
() =>
write(
'blocksuite/crates/editor/src/ios.rs',
'#[cfg(target_os = "ios")]\nfn i() {}\n'
),
true,
],
[
'delete a file with an Apple vendor cfg',
() => rmSync(join(tmpRepo, vendorFile)),
true,
],
[
'remove the macOS cfg from a file',
() => write(moreMenu, 'const COPY: &str = "C";\n'),
true,
],
[
'rename a file with a macOS cfg',
() => git('mv', moreMenu, 'blocksuite/crates/editor/src/menu.rs'),
true,
],
[
'edit a file with no Apple cfg',
() => write(plain, 'pub fn directory() -> u8 { 1 }\n'),
false,
],
];
for (const [label, change, expected] of cases) {
git('reset', '--hard', baseSha);
change();
git('add', '-A');
git('commit', '-m', label);
const result = classifyGitDiff({
baseSha,
ref: 'refs/heads/darksky/np/mobile-r29-foo',
cwd: tmpRepo,
});
assert.equal(result.appleSpecific, expected, label);
}
} finally {
rmSync(tmpRepo, { recursive: true, force: true });
}
});
+7 -29
View File
@@ -1,6 +1,6 @@
{
"waitForTimeout": {
"total": 371,
"total": 312,
"files": {
"blocksuite/framework/std/src/__tests__/inline/utils.ts": 3,
"tests/affine-cloud-copilot/e2e/basic/chat.spec.ts": 3,
@@ -13,7 +13,6 @@
"tests/affine-desktop/e2e/split-view.spec.ts": 1,
"tests/affine-desktop/e2e/tabs.spec.ts": 2,
"tests/affine-desktop/e2e/workspace.spec.ts": 3,
"tests/affine-local/e2e/all-page.spec.ts": 5,
"tests/affine-local/e2e/attachment-preview.spec.ts": 11,
"tests/affine-local/e2e/blocksuite/clipboard/clipboard.spec.ts": 14,
"tests/affine-local/e2e/blocksuite/database/utils.ts": 6,
@@ -31,59 +30,38 @@
"tests/affine-local/e2e/image-preview.spec.ts": 44,
"tests/affine-local/e2e/import-dialog.spec.ts": 1,
"tests/affine-local/e2e/links.spec.ts": 6,
"tests/affine-local/e2e/local-first-avatar.spec.ts": 3,
"tests/affine-local/e2e/local-first-collections-items.spec.ts": 5,
"tests/affine-local/e2e/local-first-delete-page.spec.ts": 2,
"tests/affine-local/e2e/local-first-delete-workspace.spec.ts": 2,
"tests/affine-local/e2e/local-first-favorite-page.spec.ts": 2,
"tests/affine-local/e2e/local-first-restore-page.spec.ts": 1,
"tests/affine-local/e2e/local-first-workspace-list.spec.ts": 6,
"tests/affine-local/e2e/local-first-workspace.spec.ts": 1,
"tests/affine-local/e2e/peek-view.spec.ts": 2,
"tests/affine-local/e2e/quick-search.spec.ts": 20,
"tests/affine-local/e2e/local-first-favorite-page.spec.ts": 1,
"tests/affine-local/e2e/local-first-workspace-list.spec.ts": 4,
"tests/affine-local/e2e/router.spec.ts": 1,
"tests/affine-local/e2e/settings.spec.ts": 1,
"tests/affine-local/e2e/theme.spec.ts": 1,
"tests/affine-local/e2e/undo-empty.spec.ts": 1,
"tests/affine-mobile/e2e/back-button-visibility.spec.ts": 1,
"tests/blocksuite/e2e/attachment.spec.ts": 4,
"tests/blocksuite/e2e/bookmark.spec.ts": 19,
"tests/blocksuite/e2e/clipboard/clipboard.spec.ts": 1,
"tests/blocksuite/e2e/clipboard/list.spec.ts": 2,
"tests/blocksuite/e2e/clipboard/list.spec.ts": 1,
"tests/blocksuite/e2e/clipboard/markdown.spec.ts": 4,
"tests/blocksuite/e2e/code/readonly.spec.ts": 1,
"tests/blocksuite/e2e/code/selections.spec.ts": 2,
"tests/blocksuite/e2e/cross-platform/basic.spec.ts": 3,
"tests/blocksuite/e2e/cross-platform/inline/inline-editor.spec.ts": 37,
"tests/blocksuite/e2e/database/actions.ts": 1,
"tests/blocksuite/e2e/edgeless/basic.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/brush.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/clipboard.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/frame/frame.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/note/note.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/pan.spec.ts": 1,
"tests/blocksuite/e2e/edgeless/selection/selection.spec.ts": 16,
"tests/blocksuite/e2e/edgeless/shape.spec.ts": 6,
"tests/blocksuite/e2e/edgeless/text.spec.ts": 1,
"tests/blocksuite/e2e/format-bar.spec.ts": 1,
"tests/blocksuite/e2e/hotkey/hotkey.spec.ts": 4,
"tests/blocksuite/e2e/image/load.spec.ts": 5,
"tests/blocksuite/e2e/link.spec.ts": 3,
"tests/blocksuite/e2e/list.spec.ts": 1,
"tests/blocksuite/e2e/paragraph.spec.ts": 5,
"tests/blocksuite/e2e/selection/block.spec.ts": 13,
"tests/blocksuite/e2e/selection/native.spec.ts": 7,
"tests/blocksuite/e2e/slash-menu.spec.ts": 1,
"tests/blocksuite/e2e/utils/actions/edgeless.ts": 4,
"tests/blocksuite/e2e/utils/actions/misc.ts": 3,
"tests/blocksuite/e2e/utils/actions/misc.ts": 2,
"tests/blocksuite/e2e/utils/asserts.ts": 1,
"tests/blocksuite/e2e/utils/inline-editor.ts": 1,
"tests/kit/src/utils/clipboard.ts": 1,
"tests/kit/src/utils/cloud.ts": 5,
"tests/kit/src/utils/cloud.ts": 4,
"tests/kit/src/utils/editor.ts": 7,
"tests/kit/src/utils/image.ts": 1,
"tests/kit/src/utils/page-logic.ts": 3,
"tests/kit/src/utils/properties.ts": 5
"tests/kit/src/utils/properties.ts": 2
}
},
"skip": {
+51
View File
@@ -0,0 +1,51 @@
#!/usr/bin/env node
// Prints `--project <name>` arguments for every Vitest project of the root
// config that runs in Node with nothing but JS dependencies. Left out:
// browser-mode projects (they need Playwright browsers), the Electron project
// (it needs the Electron binary and the native addon, and is not under
// blocksuite/), and the projects in NEEDS_RUST_BINARIES. Exits non-zero when
// it finds no project, so a caller never runs an unfiltered `vitest run`.
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { dirname, join, relative } from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = fileURLToPath(new URL('../..', import.meta.url));
// Projects whose tests spawn compiled Rust binaries; native-playground.yml's
// js-room-coop job builds those binaries and runs them.
const NEEDS_RUST_BINARIES = new Set(['@blocksuite/playground']);
function* configs(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
if (entry.name === 'node_modules' || entry.name === 'dist') continue;
const path = join(dir, entry.name);
if (entry.isDirectory()) yield* configs(path);
else if (entry.name === 'vitest.config.ts') yield path;
}
}
const projects = [
join(ROOT, 'vitest.config.ts'),
...configs(join(ROOT, 'blocksuite')),
];
const names = [];
for (const config of projects) {
const source = readFileSync(config, 'utf8');
if (/\bbrowser\s*:\s*\{[^}]*\benabled\s*:\s*true/s.test(source)) continue;
const explicit = /\btest\s*:\s*\{[^]*?\bname\s*:\s*'([^']+)'/.exec(source);
const pkg = join(dirname(config), 'package.json');
const name =
explicit?.[1] ??
(existsSync(pkg) ? JSON.parse(readFileSync(pkg, 'utf8')).name : null);
if (!name) {
console.error(`${relative(ROOT, config)}: cannot determine project name`);
process.exit(1);
}
if (!NEEDS_RUST_BINARIES.has(name)) names.push(name);
}
if (names.length === 0) {
console.error('no Node-only Vitest project found');
process.exit(1);
}
process.stdout.write(names.map(n => `--project ${n}`).join(' ') + '\n');
+12 -21
View File
@@ -61,27 +61,21 @@ test('enable selection and use ESC to disable selection', async ({ page }) => {
modifiers: ['Shift'],
});
// wait for 500ms
await page.waitForTimeout(500);
// there should be checkboxes in the page list now
expect(
await page
await expect(
page
.locator('[data-testid="doc-list-item-select"][data-select-mode="true"]')
.count()
).toBeGreaterThan(0);
.first()
).toBeVisible();
// esc again, checkboxes should disappear
await page.keyboard.press('Escape');
// wait for 500ms
await page.waitForTimeout(500);
expect(
await page
.locator('[data-testid="doc-list-item-select"][data-select-mode="true"]')
.count()
).toBe(0);
await expect(
page.locator(
'[data-testid="doc-list-item-select"][data-select-mode="true"]'
)
).toHaveCount(0);
});
test('select two pages and delete', async ({ page }) => {
@@ -119,12 +113,11 @@ test('select two pages and delete', async ({ page }) => {
await page.getByRole('button', { name: 'Delete' }).click();
// check the page count again
await page.waitForTimeout(300);
await expect(
page.locator('[data-testid="floating-toolbar"]')
).not.toBeVisible();
expect(await getPagesCount(page)).toBe(pageCount - 2);
await expect.poll(() => getPagesCount(page)).toBe(pageCount - 2);
});
test('select three pages with shiftKey and delete', async ({ page }) => {
@@ -158,12 +151,11 @@ test('select three pages with shiftKey and delete', async ({ page }) => {
await page.getByRole('button', { name: 'Delete' }).click();
// check the page count again
await page.waitForTimeout(300);
await expect(
page.locator('[data-testid="floating-toolbar"]')
).not.toBeVisible();
expect(await getPagesCount(page)).toBe(pageCount - 3);
await expect.poll(() => getPagesCount(page)).toBe(pageCount - 3);
});
test('select all and delete closes the floating toolbar', async ({ page }) => {
@@ -186,11 +178,10 @@ test('select all and delete closes the floating toolbar', async ({ page }) => {
await page.locator('[data-testid="list-toolbar-delete"]').click();
await page.getByRole('button', { name: 'Delete' }).click();
await page.waitForTimeout(300);
await expect(
page.locator('[data-testid="floating-toolbar"]')
).not.toBeVisible();
expect(await getPagesCount(page)).toBeLessThan(pageCount);
await expect.poll(() => getPagesCount(page)).toBeLessThan(pageCount);
});
test('create a tag and delete it', async ({ page }) => {
@@ -15,7 +15,9 @@ test('should create a page with a local first avatar and remove it', async ({
await waitForEditorLoad(page);
await clickNewPageButton(page);
await createLocalWorkspace({ name: 'Test Workspace 1' }, page);
await page.waitForTimeout(1000);
await expect(page.getByTestId('workspace-name')).toHaveText(
'Test Workspace 1'
);
await page.getByTestId('workspace-name').click();
await page
.getByTestId('workspace-card')
@@ -33,7 +35,7 @@ test('should create a page with a local first avatar and remove it', async ({
.nth(0)
.getByTestId('workspace-avatar')
.click();
await page.waitForTimeout(2000);
await expect(page.getByTestId('workspace-name')).toHaveText('Demo Workspace');
await page.getByTestId('workspace-name').click();
await page
.getByTestId('workspace-card')
@@ -63,7 +65,7 @@ test('should create a page with a local first avatar and remove it', async ({
await page.getByTestId('workspace-setting-avatar').hover();
await page.getByTestId('workspace-setting-remove-avatar-button').click();
await page.mouse.click(0, 0);
await page.waitForTimeout(1000);
await expect(page.getByTestId('setting-modal')).not.toBeVisible();
await page.getByTestId('workspace-name').click();
await page.getByTestId('workspace-card').nth(1).click();
const removedAvatarImage = await page
@@ -72,15 +72,17 @@ test('page delete -> create new page -> refresh page -> new page should be appea
await clickNewPageButton(page);
await getBlockSuiteEditorTitle(page).click();
await getBlockSuiteEditorTitle(page).fill('this is a new page1');
await page.waitForTimeout(1000);
const newPageId1 = getCurrentDocIdFromUrl(page);
await page.getByTestId('all-pages').click();
await expect(getPageItem(page, newPageId1)).toBeVisible();
await expect(getPageByTitle(page, 'this is a new page1')).toBeVisible();
await clickNewPageButton(page);
await getBlockSuiteEditorTitle(page).click();
await getBlockSuiteEditorTitle(page).fill('this is a new page2');
await page.waitForTimeout(1000);
const newPageId2 = getCurrentDocIdFromUrl(page);
await page.getByTestId('all-pages').click();
await expect(getPageItem(page, newPageId2)).toBeVisible();
await expect(getPageByTitle(page, 'this is a new page2')).toBeVisible();
await getPageItem(page, newPageId1).click();
await page.getByTestId('all-pages').click();
await getPageItem(page, newPageId2).click();
@@ -38,10 +38,7 @@ test('Create new workspace, then delete it', async ({ page, workspace }) => {
await promise;
await page.reload();
await page.waitForSelector('[data-testid="workspace-name"]');
await page.waitForTimeout(1000);
expect(await page.getByTestId('workspace-name').textContent()).toBe(
'Demo Workspace'
);
await expect(page.getByTestId('workspace-name')).toHaveText('Demo Workspace');
const currentWorkspace = await workspace.current();
expect(currentWorkspace.meta.flavour).toContain('local');
@@ -68,7 +65,6 @@ test('Delete last workspace', async ({ page }) => {
await openHomePage(page);
await expect(page.getByTestId('new-workspace')).toBeVisible();
await createLocalWorkspace({ name: 'Test Workspace' }, page, true);
await page.waitForTimeout(1000);
await page.waitForSelector('[data-testid="workspace-name"]');
await expect(page.getByTestId('workspace-name')).toHaveText('Test Workspace');
});
@@ -43,7 +43,7 @@ test('Export to html, markdown and png', async ({ page }) => {
await page.getByTestId('export-to-markdown').click();
await downloadPromise;
}
await page.waitForTimeout(50);
await expect(page.getByTestId('export-menu')).not.toBeVisible();
{
await clickPageMoreActions(page);
await page.getByTestId('export-menu').click();
@@ -33,7 +33,7 @@ test('New a page , then delete it in all pages, restore it', async ({
await page.getByRole('button', { name: 'Delete' }).click();
await page.getByTestId('trash-page').click();
await page.waitForTimeout(50);
await expect(page.getByTestId('restore-page-button')).toBeVisible();
const trashPage = page.url();
// restore it
await page.getByTestId('restore-page-button').click();
@@ -43,13 +43,9 @@ test('create one workspace in the workspace list', async ({
//check page list length
await page.keyboard.press('Escape');
await clickSideBarAllPageButton(page);
await page.waitForTimeout(2000);
const result = await getPagesCount(page);
expect(result).toBe(2);
await expect.poll(() => getPagesCount(page)).toBe(2);
await page.reload();
await page.waitForTimeout(4000);
const result1 = await getPagesCount(page);
expect(result1).toBe(2);
await expect.poll(() => getPagesCount(page)).toBe(2);
const currentWorkspace = await workspace.current();
expect(currentWorkspace.meta.flavour).toContain('local');
@@ -7,8 +7,7 @@ test('preset workspace name', async ({ page, workspace }) => {
await openHomePage(page);
await waitForEditorLoad(page);
const workspaceName = page.getByTestId('workspace-name');
await page.waitForTimeout(1000);
expect(await workspaceName.textContent()).toBe('Demo Workspace');
await expect(workspaceName).toHaveText('Demo Workspace');
const currentWorkspace = await workspace.current();
expect(currentWorkspace.meta.flavour).toContain('local');
+9 -2
View File
@@ -131,7 +131,6 @@ test('should not open peek view when content is covered by canvas element', asyn
steps: 10,
});
await page.mouse.dblclick(syncedDocCenter.x, syncedDocCenter.y);
await page.waitForTimeout(100);
await expect(page.getByTestId('peek-view-modal')).toBeVisible();
// close peek view
@@ -152,7 +151,15 @@ test('should not open peek view when content is covered by canvas element', asyn
}
);
await page.mouse.up();
await page.waitForTimeout(100);
await expect
.poll(async () => {
try {
return (await getSelectedXYWH(page))[2];
} catch {
return 0;
}
})
.toBeGreaterThan(0);
// click the same position again
await page.mouse.move(syncedDocCenter.x, syncedDocCenter.y, {
+19 -27
View File
@@ -137,7 +137,8 @@ test('Create a new page without keyword', async ({ page }) => {
await openQuickSearchByShortcut(page);
const addNewPage = page.getByText('New page', { exact: true });
await addNewPage.click();
await page.waitForTimeout(300);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await waitForEditorLoad(page);
await assertTitle(page, '');
});
@@ -151,7 +152,8 @@ test('Create a new page with keyword', async ({ page }) => {
'[cmdk-item] >> text=New ""test123456"" Page'
);
await addNewPage.click();
await page.waitForTimeout(300);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await waitForEditorLoad(page);
await assertTitle(page, '"test123456"');
});
@@ -170,28 +172,27 @@ test('Create a new page and search this page', async ({ page }) => {
await openQuickSearchByShortcut(page);
// input title and create new page
await insertInputText(page, 'test123456');
await page.waitForTimeout(300);
const addNewPage = page.locator('[cmdk-item] >> text=New "test123456" Page');
await expect(addNewPage).toBeVisible();
await addNewPage.click();
await page.waitForTimeout(300);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await waitForEditorLoad(page);
await assertTitle(page, 'test123456');
await openQuickSearchByShortcut(page);
await insertInputText(page, 'test123456');
await page.waitForTimeout(1000);
await assertResultList(page, ['test123456', 'test123456']);
await page.keyboard.press('Enter');
await page.waitForTimeout(300);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await assertTitle(page, 'test123456');
await page.reload();
await waitForEditorLoad(page);
await openQuickSearchByShortcut(page);
await insertInputText(page, 'test123456');
await page.waitForTimeout(1000);
await assertResultList(page, ['test123456', 'test123456']);
await page.keyboard.press('Enter');
await page.waitForTimeout(300);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await assertTitle(page, 'test123456');
});
@@ -228,7 +229,7 @@ test('Autofocus input after select', async ({ page }) => {
await openHomePage(page);
await waitForEditorLoad(page);
await clickNewPageButton(page);
await page.waitForTimeout(500); // wait for new page loaded
await waitForEditorLoad(page);
await openQuickSearchByShortcut(page);
await page.keyboard.press('ArrowUp');
const locator = page.locator('[cmdk-input]');
@@ -266,7 +267,7 @@ test('assert the recent browse pages are on the recent list', async ({
{
const title = getBlockSuiteEditorTitle(page);
await title.click();
await page.waitForTimeout(200);
await expect(title).toBeFocused();
await title.pressSequentially('sgtokidoki', { delay: 100 });
await expect(title).toHaveText('sgtokidoki');
}
@@ -279,11 +280,10 @@ test('assert the recent browse pages are on the recent list', async ({
{
const title = getBlockSuiteEditorTitle(page);
await title.click();
await page.waitForTimeout(200);
await expect(title).toBeFocused();
await title.pressSequentially('theliquidhorse', { delay: 100 });
await expect(title).toHaveText('theliquidhorse');
}
await page.waitForTimeout(200);
// create thrid page
await openQuickSearchByShortcut(page);
@@ -292,7 +292,7 @@ test('assert the recent browse pages are on the recent list', async ({
{
const title = getBlockSuiteEditorTitle(page);
await title.click();
await page.waitForTimeout(200);
await expect(title).toBeFocused();
await title.pressSequentially('battlekot', { delay: 100 });
await expect(title).toHaveText('battlekot');
}
@@ -320,11 +320,10 @@ test('assert the recent browse pages are on the recent list', async ({
{
const title = getBlockSuiteEditorTitle(page);
await title.click();
await page.waitForTimeout(200);
await expect(title).toBeFocused();
await title.pressSequentially('affine is the best', { delay: 100 });
await expect(title).toHaveText('affine is the best', { timeout: 500 });
}
await page.waitForTimeout(1000);
await openQuickSearchByShortcut(page);
{
const quickSearchItems = page.locator(
@@ -359,7 +358,6 @@ test('can use cmdk to delete page and restore it', async ({ page }) => {
await page.getByTestId('confirm-modal-confirm').click();
const restoreButton = page.getByTestId('page-restore-button');
await expect(restoreButton).toBeVisible();
await page.waitForTimeout(100);
await openQuickSearchByShortcut(page);
expect(await commandsIsVisible(page, 'Move to trash')).toBe(false);
expect(await commandsIsVisible(page, 'Restore from trash')).toBe(true);
@@ -388,7 +386,6 @@ test('can use cmdk to search page content and scroll to it, then the block will
await clickSideBarAllPageButton(page);
await openQuickSearchByShortcut(page);
await insertInputText(page, '123456');
await page.waitForTimeout(1000);
await assertResultList(page, [
'this is a new page to search for content',
'123456',
@@ -431,7 +428,7 @@ test('Create a new page with special characters in the title and search for this
})
.toBe(true);
await page.keyboard.press('Enter');
await page.waitForTimeout(1000);
await expect(page.getByTestId('cmdk-quick-search')).toBeHidden();
await assertTitle(page, specialTitle);
});
@@ -498,15 +495,10 @@ test('can use @ to open quick search to search for doc and insert into canvas',
).toContainText(docTitle);
// focus on the note block
await page.waitForTimeout(500);
await page
.locator('affine-embed-edgeless-synced-doc-block')
.click({ force: true });
await page.waitForTimeout(500);
// double clock to show peek view
await page
.locator('affine-embed-edgeless-synced-doc-block')
.dblclick({ force: true });
const syncedDocBlock = page.locator('affine-embed-edgeless-synced-doc-block');
await syncedDocBlock.click({ force: true });
// double click to show peek view
await syncedDocBlock.dblclick({ force: true });
await expect(page.getByTestId('peek-view-modal')).toBeVisible();
});
+1 -1
View File
@@ -29,7 +29,7 @@ test('change language using keyboard', async ({ page }) => {
const locator = page.getByTestId('language-menu-button');
const oldName = await locator.textContent();
await locator.click();
await page.waitForTimeout(200);
await expect(page.getByRole('menu')).toBeVisible();
await page.keyboard.press('ArrowDown', {
delay: 50,
});
+1 -1
View File
@@ -21,7 +21,7 @@ test('default white', async ({ page }) => {
});
await page.getByTestId('settings-modal-trigger').click();
await page.getByTestId('appearance-panel-trigger').click();
await page.waitForTimeout(50);
await expect(page.getByTestId('dark-theme-trigger')).toBeVisible();
await page.getByTestId('dark-theme-trigger').click();
const darkMode = await root.evaluate(element => element.dataset.theme);
expect(darkMode).toBe('dark');
+1 -1
View File
@@ -18,7 +18,7 @@ test('should be able to undo on empty page', async ({ page }) => {
// test editor still work
await page.locator('.edgeless-note-page-content').click({ force: true });
await page.locator('.edgeless-note-page-content').click({ force: true });
await page.waitForTimeout(100);
await expect(page.locator('.edgeless-note-page-content')).toBeVisible();
await page
.locator('.edgeless-note-page-content')
.pressSequentially('test text');
@@ -158,7 +158,7 @@ test(scoped`copy clipItems format`, async ({ page }) => {
`;
await pasteContent(page, { 'text/plain': clipData });
await page.waitForTimeout(100);
await expect(page.locator('affine-list')).toHaveCount(4);
await setSelection(page, 4, 1, 5, 1);
assertClipItems(page, 'text/plain', 'bc');
assertClipItems(page, 'text/html', '<ul><li>b<ul><li>c</li></ul></li></ul>');
+1 -1
View File
@@ -441,7 +441,7 @@ test(scoped`should copy and paste of database work`, async ({ page }) => {
await copyByKeyboard(page);
await pressEnter(page);
await pasteByKeyboard(page);
await page.waitForTimeout(100);
await expect(page.locator('affine-database')).toHaveCount(2);
let pageJson = await getPageSnapshot(page, false);
let note = (pageJson as BlockSnapshot).children[0];
+1 -1
View File
@@ -24,12 +24,12 @@ test('should code block widget be disabled in read only mode', async ({
await initEmptyCodeBlockState(page);
await focusRichTextEnd(page);
await page.waitForTimeout(300);
await switchReadonly(page);
const codeBlockController = getCodeBlock(page);
const codeBlock = codeBlockController.codeBlock;
await codeBlock.hover();
await expect(codeBlockController.moreButton).toHaveAttribute('disabled');
await codeBlockController.clickLanguageButton();
await expect(codeBlockController.langList).toBeHidden();
+1 -2
View File
@@ -326,8 +326,7 @@ test('the tooltip of more button should be hidden when the action menu is shown'
throw new Error('moreButtonBox is not found');
}
// need to wait for previous tooltip to be hidden
await page.waitForTimeout(100);
await expect(tooltip).toBeHidden();
await page.mouse.move(moreButtonBox.x + 10, moreButtonBox.y + 10);
await expect(tooltip).toBeVisible();
+3 -2
View File
@@ -162,8 +162,9 @@ test('change brush element size by component-toolbar', async ({ page }) => {
const end = { x: 200, y: 200 };
await addBasicBrushElement(page, start, end);
// wait for menu hide animation
await page.waitForTimeout(500);
await expect(page.locator('edgeless-line-width-panel:visible')).toHaveCount(
0
);
// change to line width 12
await page.mouse.click(110, 110);
@@ -44,8 +44,6 @@ test.describe('mime', () => {
await pasteContent(page, content);
// wait for paste
await page.waitForTimeout(200);
await assertRichImage(page, 1);
});
@@ -409,11 +409,10 @@ test('outline should keep updated during a new frame created by frame-tool dragg
await page.mouse.move(start[0], start[1]);
await page.mouse.down();
await page.mouse.move(end[0], end[1], { steps: 10 });
await page.waitForTimeout(50);
expect(
await pickColorAtPoints(page, [start, [end[0] - 1, end[1] - 1]])
).toEqual(['#1e96eb', '#1e96eb']);
await expect
.poll(() => pickColorAtPoints(page, [start, [end[0] - 1, end[1] - 1]]))
.toEqual(['#1e96eb', '#1e96eb']);
});
test('undo should work when create a frame by dragging', async ({ page }) => {
@@ -236,7 +236,6 @@ test('format quick bar should show up when double-clicking on text', async ({
position: { x: 10, y: 10 },
delay: 20,
});
await page.waitForTimeout(200);
const formatBar = page.locator('affine-toolbar-widget editor-toolbar');
await expect(formatBar).toBeVisible();
});
+1 -2
View File
@@ -110,8 +110,7 @@ test.describe('edgeless canvas text', () => {
state: 'attached',
});
await type(page, 'hello');
await page.waitForTimeout(100);
await assertEdgelessCanvasText(page, 'hhelloello');
await expect(() => assertEdgelessCanvasText(page, 'hhelloello')).toPass();
await page.mouse.click(145, 155);
await type(page, 'ddd\n');
-1
View File
@@ -436,7 +436,6 @@ test('should format quick bar be able to change to heading paragraph type', asyn
expect(await getPageSnapshot(page, true)).toMatchSnapshot(
`${testInfo.title}_finial.json`
);
await page.waitForTimeout(10);
// The paragraph button should prevent selection after click
await assertRichTextInlineRange(page, 0, 0, 3);
});
+1 -1
View File
@@ -333,7 +333,7 @@ test('basic indent and unindent', async ({ page }, testInfo) => {
`${testInfo.title}_after_tab.json`
);
await page.waitForTimeout(100);
await assertRichTextInlineRange(page, 1, 5);
await pressShiftTab(page);
expect(await getPageSnapshot(page, true)).toMatchSnapshot(
+1 -1
View File
@@ -767,7 +767,7 @@ test.describe('slash menu with style', () => {
await expect(slashMenu).toBeVisible();
const bold = page.getByTestId('Bold');
await bold.click();
await page.waitForTimeout(50);
await expect(slashMenu).toBeHidden();
await type(page, 'hello');
expect(await getPageSnapshot(page, true)).toMatchSnapshot(
+14 -13
View File
@@ -1066,8 +1066,10 @@ export async function getIndexCoordinate(
[richTextIndex, vIndex]: [number, number],
coordOffSet: { x: number; y: number } = { x: 0, y: 0 }
) {
for (let attempt = 0; attempt < 20; attempt++) {
const coord = await page.evaluate(
// Re-evaluated on every animation frame until the inline editor has laid out
// the range, instead of sleeping between fixed retries.
const coord = await page
.waitForFunction(
({ richTextIndex, vIndex, coordOffSet, currentEditorIndex }) => {
const editorHost =
document.querySelectorAll('editor-host')[currentEditorIndex];
@@ -1112,17 +1114,16 @@ export async function getIndexCoordinate(
vIndex,
coordOffSet,
currentEditorIndex,
}
);
if (coord) {
return coord;
}
await page.waitForTimeout(50);
}
throw new Error(
`Failed to get index coordinate: richTextIndex=${richTextIndex}, vIndex=${vIndex}`
);
},
{ polling: 'raf', timeout: 1000 }
)
.catch(error => {
throw new Error(
`Failed to get index coordinate: richTextIndex=${richTextIndex}, vIndex=${vIndex}`,
{ cause: error }
);
});
return (await coord.jsonValue()) as { x: number; y: number };
}
export function inlineEditorInnerTextToString(innerText: string): string {
+1 -2
View File
@@ -357,8 +357,7 @@ async function waitForWorkspaceSynced(page: Page) {
export async function enableShare(page: Page) {
await page.getByTestId('cloud-share-menu-button').click();
await page.getByTestId('share-link-menu-trigger').click();
// wait for the menu to be visible
await page.waitForTimeout(500);
// click() waits for the menu item to be visible, stable and enabled.
await page.getByTestId('share-link-menu-enable-share').click();
await expect(page.getByTestId('share-link-menu-trigger')).toHaveText(
'Read only',
-30
View File
@@ -107,7 +107,6 @@ export const ensureAddPropertyButtonVisible = async (
return;
}
await togglePropertyListVisibility(page);
await page.waitForTimeout(500);
await expect(
root.getByRole('button', { name: 'Add property' })
).toBeVisible();
@@ -152,35 +151,6 @@ export const openWorkspaceProperties = async (page: Page) => {
await page.getByTestId('workspace-setting:properties').click();
};
export const selectVisibilitySelector = async (
page: Page,
name: string,
option: string
) => {
await page
.getByRole('menu')
.locator(
`[data-testid="page-properties-settings-menu-item"]:has-text("${name}")`
)
.getByRole('button')
.click();
await page
.getByRole('menu')
.last()
.getByRole('menuitem', {
name: option,
exact: true,
})
.click();
await page.waitForTimeout(500);
await page.keyboard.press('Escape');
await page.waitForTimeout(500);
};
export const changePropertyVisibility = async (
page: Page,
name: string,