Merge remote-tracking branch 'origin/master' into pr-4879-merge

# Conflicts:
#	frontend/src/views/Player/EmulatorJS/utils.test.ts
#	frontend/src/views/Player/EmulatorJS/utils.ts
This commit is contained in:
Georges-Antoine Assi
2026-09-28 11:45:30 -04:00
37 changed files with 915 additions and 240 deletions

View File

@@ -202,7 +202,7 @@ Run from `backend/`:
### CI gates this mirrors
`typecheck.yml` (vue-tsc + lockfile lint), `frontend.yml` (vitest + build), `i18n.yml` (locale check), `pytest.yml` (pytest on MariaDB + PostgreSQL), `migrations.yml` (alembic on both DBs), `mypy.yml` (mypy across the backend), `trunk-check.yml` (Trunk across the repo). Green locally → green in CI.
`frontend.yml` (vitest, build, vue-tsc + lockfile lint), `api-types.yml` (generated API types match the backend schema), `i18n.yml` (locale check), `pytest.yml` (pytest on MariaDB + PostgreSQL), `migrations.yml` (alembic on both DBs), `mypy.yml` (mypy across the backend), `trunk-check.yml` (Trunk across the repo). Green locally → green in CI.
### Don't

View File

@@ -0,0 +1,40 @@
name: Set up the backend
description: Install the MariaDB connector, uv, the pinned Python and the locked backend dependencies.
inputs:
sync-args:
description: Extra arguments for `uv sync --locked`, such as `--extra test`
required: false
default: ""
apt-packages:
description: Extra apt packages to install alongside the MariaDB connector
required: false
default: ""
runs:
using: composite
steps:
# The mariadb package ships only an sdist on Linux, so uv builds it against these.
- name: Install the MariaDB connector
shell: bash
env:
APT_PACKAGES: ${{ inputs.apt-packages }}
run: |
read -ra extra <<<"$APT_PACKAGES"
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev "${extra[@]}"
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install Python
shell: bash
run: uv python install
- name: Install backend dependencies
shell: bash
env:
SYNC_ARGS: ${{ inputs.sync-args }}
run: |
read -ra args <<<"$SYNC_ARGS"
uv sync --locked "${args[@]}"

View File

@@ -0,0 +1,17 @@
name: Set up the frontend
description: Install the Node version from frontend/.nvmrc and the locked frontend dependencies.
runs:
using: composite
steps:
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: frontend/.nvmrc
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
shell: bash
working-directory: frontend
run: npm ci

84
.github/workflows/api-types.yml vendored Normal file
View File

@@ -0,0 +1,84 @@
name: Check Generated API Types
on:
pull_request:
paths:
- "backend/**"
- "frontend/src/__generated__/**"
- frontend/package.json
- frontend/package-lock.json
- ".github/workflows/api-types.yml"
- pyproject.toml
- uv.lock
- .python-version
push:
branches:
- "master"
paths:
- "backend/**"
- "frontend/src/__generated__/**"
- frontend/package.json
- frontend/package-lock.json
- ".github/workflows/api-types.yml"
- pyproject.toml
- uv.lock
- .python-version
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
api-types:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up the backend
uses: ./.github/actions/setup-backend
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
# Nothing connects to the database; importing the app only needs credentials set.
- name: Dump the OpenAPI schema
working-directory: backend
env:
ROMM_AUTH_SECRET_KEY: "0000000000000000000000000000000000000000000000000000000000000000"
DB_HOST: 127.0.0.1
DB_USER: unused
DB_PASSWD: unused
DB_NAME: unused
run: |
mkdir -p "$RUNNER_TEMP/romm" "$RUNNER_TEMP/openapi"
ROMM_BASE_PATH="$RUNNER_TEMP/romm" uv run python -m tools.dump_openapi "$RUNNER_TEMP/openapi/openapi.json"
# Served where `npm run generate` reads it, so the generator flags live in
# package.json alone.
- name: Regenerate the types
working-directory: frontend
run: |
python3 -m http.server 3000 --bind 127.0.0.1 --directory "$RUNNER_TEMP/openapi" &
for _ in $(seq 1 10); do
curl -sf http://127.0.0.1:3000/openapi.json >/dev/null && break
sleep 1
done
npm run generate
- name: Fail if the committed types differ
# Intent-to-add surfaces new files; diffing against HEAD keeps deleted ones.
run: |
git add --intent-to-add frontend/src/__generated__
if ! git diff --exit-code --stat HEAD -- frontend/src/__generated__; then
git diff HEAD -- frontend/src/__generated__
echo "::error::frontend/src/__generated__ is out of date with the backend schema. Run \`npm run generate\` against a running backend and commit the result."
exit 1
fi

View File

@@ -38,6 +38,7 @@ jobs:
# Forks have no registry credentials, so their nightly would fail every day.
if: github.event_name != 'schedule' || github.repository == 'rommapp/romm'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
outputs:
@@ -70,6 +71,7 @@ jobs:
arch: arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 60
permissions:
contents: read
packages: write
@@ -203,6 +205,7 @@ jobs:
merge:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 15
env:
DOCKER_METADATA_ANNOTATIONS_LEVELS: index
permissions:
@@ -307,9 +310,16 @@ jobs:
contents: read
packages: read
security-events: write
# actionlint doesn't understand the $/ self-repository syntax yet.
uses: ./.github/workflows/image-scan.yml # zizmor: ignore[self-repository]
uses: ./.github/workflows/image-scan.yml
with:
images: >-
["ghcr.io/${{ github.repository_owner }}/romm:${{ needs.merge.outputs.version }}",
"ghcr.io/${{ github.repository_owner }}/romm:${{ needs.merge.outputs.version-slim }}"]
report-failure:
needs: [validate-tag-semver, build, merge, scan]
if: failure() && github.event_name == 'schedule'
permissions:
contents: read
issues: write
uses: ./.github/workflows/report-scheduled-failure.yml

View File

@@ -9,6 +9,7 @@ permissions:
jobs:
copilot-setup-steps:
runs-on: ubuntu-latest
timeout-minutes: 30
services:
mariadb:
image: mariadb:13.0.2
@@ -28,26 +29,14 @@ jobs:
with:
persist-credentials: false
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install Python
run: uv python install
- name: Install system dependencies
run: sudo apt-get install -y libmariadb3 libmariadb-dev libpq-dev
- name: Install backend dependencies
run: uv sync --frozen --all-extras --dev
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- name: Set up the backend
uses: ./.github/actions/setup-backend
with:
node-version-file: frontend/.nvmrc
sync-args: --all-extras --dev
apt-packages: libpq-dev
- name: Install frontend dependencies
run: npm install
working-directory: frontend
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
- name: Install Trunk CLI
run: curl https://get.trunk.io -fsSL | bash -s -- -y

97
.github/workflows/docker-pr.yml vendored Normal file
View File

@@ -0,0 +1,97 @@
name: Docker Image Check
# Releases and the nightly are the only other builds of docker/Dockerfile, so a
# change to what the image is built from gets built and booted here first.
on:
pull_request:
paths:
- "docker/**"
- "backend/**"
- "frontend/**"
- pyproject.toml
- uv.lock
- .python-version
- .github/workflows/docker-pr.yml
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
build-and-boot:
runs-on: ubuntu-latest
timeout-minutes: 45
services:
mariadb:
image: mariadb:13.0.2
ports:
- 3306:3306
env:
MARIADB_USER: romm
MARIADB_PASSWORD: passwd
MARIADB_DATABASE: romm
MARIADB_ROOT_PASSWORD: passwd
options: --health-cmd="healthcheck.sh --connect --innodb_initialized" --health-interval=5s --health-timeout=2s --health-retries=3 --health-start-period=30s
steps:
- name: Checkout code
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
# The cache is public, so fork PRs read it too. Nothing is written back:
# layers built from PR content must not reach a release image.
- name: Build the full image
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
with:
file: docker/Dockerfile
context: .
platforms: linux/amd64
target: full-image
load: true
tags: romm:pr
cache-from: type=registry,ref=ghcr.io/${{ github.repository_owner }}/romm-buildcache:release-amd64
# Host networking reaches the MariaDB service on localhost. The image
# generates its own auth key and runs its own valkey when none is set.
- name: Start the container
run: |
mkdir -p "$RUNNER_TEMP/library"
docker run -d --name romm --network host \
-e DB_HOST=127.0.0.1 \
-e DB_NAME=romm \
-e DB_USER=romm \
-e DB_PASSWD=passwd \
-v "$RUNNER_TEMP/library:/romm/library" \
romm:pr
# Startup runs the migrations first, so a green heartbeat also means the
# image migrated a fresh database.
- name: Wait for the API through nginx
run: |
for i in $(seq 1 120); do
if curl -sf http://127.0.0.1:8080/api/heartbeat >/dev/null; then
echo "API up after ${i}s"
exit 0
fi
if [[ "$(docker inspect -f '{{.State.Running}}' romm)" != "true" ]]; then
echo "::error::The container exited during startup"
exit 1
fi
sleep 1
done
echo "::error::The API did not answer within 120s"
exit 1
- name: Check the frontend is served
run: curl -sf http://127.0.0.1:8080/ | grep -q '<div id="app"'
- name: Dump container logs
if: failure()
run: docker logs romm 2>&1 | tail -200 || true

View File

@@ -22,12 +22,18 @@ on:
- uv.lock
- .python-version
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
e2e:
runs-on: ubuntu-latest
timeout-minutes: 20
services:
mariadb:
image: mariadb:13.0.2
@@ -65,31 +71,11 @@ jobs:
with:
persist-credentials: false
- name: Install mariadb connectors
run: |
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev
- name: Set up the backend
uses: ./.github/actions/setup-backend
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: uv python install
# pyproject.toml lives at the repo root, so sync from there
- name: Install backend dependencies
run: uv sync --frozen
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: frontend/.nvmrc
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install frontend dependencies
run: npm ci
working-directory: frontend
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
# Headless runs use only the headless shell, so skip the full Chrome build.
- name: Install Playwright browser

View File

@@ -16,12 +16,18 @@ on:
- "frontend/src/console/**"
- "frontend/src/layouts/**"
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
check-v1-frozen:
runs-on: ubuntu-latest
timeout-minutes: 5
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1

View File

@@ -10,28 +10,26 @@ on:
paths:
- "frontend/**"
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: frontend/.nvmrc
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
- name: Run tests (vitest, includes Storybook play() tests)
run: npm test
@@ -39,23 +37,41 @@ jobs:
build:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: frontend/.nvmrc
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
- name: Build
run: npm run build
working-directory: frontend
typecheck:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up the frontend
uses: ./.github/actions/setup-frontend
- name: Run typecheck
run: npm run typecheck
working-directory: frontend
- name: Run scripts typecheck
run: npm run typecheck:scripts
working-directory: frontend
- name: Lockfile lint
run: |
[ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value.resolved | contains("git+ssh") | not) and (.value | has("resolved") and has("integrity") | not)) | .key' < package-lock.json)" ]
working-directory: frontend

View File

@@ -5,12 +5,18 @@ on:
paths:
- "frontend/src/locales/**/*.json"
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
check-translations:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- name: Checkout code

View File

@@ -25,6 +25,7 @@ permissions:
jobs:
resolve:
runs-on: ubuntu-latest
timeout-minutes: 5
outputs:
images: ${{ steps.resolve.outputs.images }}
steps:
@@ -51,6 +52,7 @@ jobs:
matrix:
image: ${{ fromJSON(needs.resolve.outputs.images) }}
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: read
packages: read
@@ -112,3 +114,12 @@ jobs:
# Keyed by image ref, so a dispatched scan of an older tag can't
# replace the analysis of latest.
category: trivy-image-${{ matrix.image }}
# When the nightly build calls this, its own report-failure job covers it.
report-failure:
needs: [resolve, scan]
if: failure() && github.event_name == 'schedule' && !inputs.images
permissions:
contents: read
issues: write
uses: ./.github/workflows/report-scheduled-failure.yml

View File

@@ -9,12 +9,18 @@ on:
- uv.lock
- .python-version
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
migrate-postgres:
runs-on: ubuntu-latest
timeout-minutes: 15
services:
postgres:
image: postgres:18
@@ -35,19 +41,8 @@ jobs:
with:
persist-credentials: false
- name: Install mariadb connectors
run: |
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: uv python install
- name: Install dependencies
run: uv sync --frozen
- name: Set up the backend
uses: ./.github/actions/setup-backend
- name: Run PostgreSQL Migrations
working-directory: backend
@@ -68,6 +63,7 @@ jobs:
# migration SQL that a default utf8mb4 server accepts (issue #4350).
name: migrate-mariadb (${{ matrix.mariadb }}, ${{ matrix.collation }})
runs-on: ubuntu-latest
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
@@ -91,19 +87,8 @@ jobs:
with:
persist-credentials: false
- name: Install mariadb connectors
run: |
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: uv python install
- name: Install dependencies
run: uv sync --frozen
- name: Set up the backend
uses: ./.github/actions/setup-backend
- name: Start MariaDB
env:

View File

@@ -24,33 +24,28 @@ on:
- uv.lock
- .python-version
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
mypy:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Install mariadb connectors
run: |
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: |
uv python install
- name: Install dependencies
run: |
uv sync --frozen --extra dev --extra test
- name: Set up the backend
uses: ./.github/actions/setup-backend
with:
sync-args: --extra dev --extra test
# mypy revalidates each cached module against its source and options, so
# any earlier master cache is safe to seed from.

View File

@@ -22,12 +22,18 @@ on:
- Dockerfile
- docker/Dockerfile
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
jobs:
pytest:
runs-on: ubuntu-latest
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -64,21 +70,11 @@ jobs:
with:
persist-credentials: false
- name: Install mariadb connectors
run: |
sudo apt-get update
sudo apt-get install -y libmariadb3 libmariadb-dev 7zip
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: |
uv python install
- name: Install dependencies
run: |
uv sync --frozen --extra test
- name: Set up the backend
uses: ./.github/actions/setup-backend
with:
sync-args: --extra test
apt-packages: 7zip
- name: Initiate MariaDB database
if: matrix.db == 'mariadb'
@@ -102,4 +98,41 @@ jobs:
run: |
cd backend
# GitHub-hosted Linux runners have 4 vCPUs; run one worker per core.
uv run pytest -n 4 -vv --maxfail=10 --junitxml=pytest-report.xml --cov --cov-report xml:coverage.xml --cov-config=.coveragerc .
# --cov=.. makes report paths repo-relative (backend/...), as code coverage expects.
uv run pytest -n 4 -vv --maxfail=10 --junitxml=pytest-report.xml --cov=.. --cov-report xml:coverage.xml --cov-config=.coveragerc .
# Both legs cover the same code, so one report is enough. Fork PRs can't upload.
- name: Upload coverage report artifact
if: matrix.db == 'mariadb' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository)
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: coverage-report
path: backend/coverage.xml
if-no-files-found: error
retention-days: 1
# A separate job keeps code-quality: write away from the job that runs the PR's code.
upload-coverage:
needs: pytest
if: ${{ !cancelled() && needs.pytest.result == 'success' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) }}
runs-on: ubuntu-latest
timeout-minutes: 10
permissions:
contents: read
# actionlint doesn't know the code-quality scope yet.
# trunk-ignore(actionlint)
code-quality: write
steps:
- name: Download coverage report
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: coverage-report
# Best-effort while GitHub code coverage is in preview; errors still show as annotations.
- name: Upload coverage to GitHub
uses: actions/upload-code-coverage@d8e329117199404bba6fc81efe8093dc7c015e34 # v1.4.2
with:
file: coverage.xml
language: Python
label: code-coverage/pytest
fail-on-error: false

View File

@@ -0,0 +1,36 @@
name: Report Scheduled Failure
# GitHub emails a failed scheduled run only to whoever last edited its cron, so
# callers route those failures here to land in one tracking issue per workflow.
on:
workflow_call:
permissions:
contents: read
jobs:
report:
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
issues: write
steps:
- name: Open or update the tracking issue
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
WORKFLOW: ${{ github.workflow }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
title="Scheduled run failing: ${WORKFLOW}"
# Search is fuzzy, so keep only an exact title match.
number=$(gh issue list --state open --search "in:title \"${title}\"" --json number,title |
jq -r --arg title "$title" 'map(select(.title == $title)) | .[0].number // empty')
if [[ -n "$number" ]]; then
gh issue comment "$number" --body "Failed again: ${RUN_URL}"
else
gh issue create --title "$title" --body "$(
printf 'The scheduled run of **%s** failed: %s\n\nLater failures are added here as comments. Close this once it passes again.' "$WORKFLOW" "$RUN_URL"
)"
fi

View File

@@ -34,6 +34,7 @@ jobs:
github.event_name == 'pull_request' &&
contains(github.event.pull_request.labels.*.name, 'build-preview')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: write
steps:
@@ -60,6 +61,7 @@ jobs:
arch: arm64
runner: ubuntu-24.04-arm
runs-on: ${{ matrix.runner }}
timeout-minutes: 60
permissions:
contents: read
packages: write
@@ -142,6 +144,7 @@ jobs:
merge:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: read
packages: write
@@ -222,6 +225,7 @@ jobs:
github.event_name == 'pull_request' &&
contains(github.event.pull_request.labels.*.name, 'build-preview')
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
pull-requests: write
steps:

View File

@@ -14,6 +14,7 @@ permissions:
jobs:
trunk-check-all:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
@@ -24,3 +25,11 @@ jobs:
uses: trunk-io/trunk-action@e1234e67a86010d61ddac8d8ebf4b783e2ffd2fa # v2.0.0
with:
check-mode: all
report-failure:
needs: [trunk-check-all]
if: failure() && github.event_name == 'schedule'
permissions:
contents: read
issues: write
uses: ./.github/workflows/report-scheduled-failure.yml

View File

@@ -6,9 +6,10 @@ on:
branches:
- "master"
# A new push cancels a PR's superseded run; each master commit keeps its own.
concurrency:
group: ${{ github.head_ref || github.run_id }}
cancel-in-progress: true
group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.event.pull_request.number || github.sha }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
@@ -16,6 +17,7 @@ permissions:
jobs:
trunk_check:
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
checks: write # For trunk to post annotations
contents: read # For repo checkout

View File

@@ -11,6 +11,7 @@ permissions:
jobs:
trunk-upgrade:
runs-on: ubuntu-latest
timeout-minutes: 20
permissions:
contents: write # For create-pull-request to push the branch
pull-requests: write # For create-pull-request to open the PR
@@ -33,3 +34,11 @@ jobs:
github-token: ${{ secrets.TRUNK_UPGRADE_TOKEN || github.token }}
reviewers: |
gantoine
report-failure:
needs: [trunk-upgrade]
if: failure() && github.event_name == 'schedule'
permissions:
contents: read
issues: write
uses: ./.github/workflows/report-scheduled-failure.yml

View File

@@ -1,47 +0,0 @@
name: Run Typescript Typecheck
on:
pull_request:
paths:
- "frontend/**"
push:
branches:
- "master"
paths:
- "frontend/**"
permissions:
contents: read
jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Set up Node.js
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
with:
node-version-file: frontend/.nvmrc
cache: "npm"
cache-dependency-path: frontend/package-lock.json
- name: Install dependencies
run: npm ci
working-directory: frontend
- name: Run typecheck
run: npm run typecheck
working-directory: frontend
- name: Run scripts typecheck
run: npm run typecheck:scripts
working-directory: frontend
- name: Lockfile lint
run: |
[ -z "$(jq -r '.packages | to_entries[] | select((.key | contains("node_modules")) and (.value.resolved | contains("git+ssh") | not) and (.value | has("resolved") and has("integrity") | not)) | .key' < package-lock.json)" ]
working-directory: frontend

View File

@@ -13,6 +13,7 @@ permissions:
jobs:
update-hltb-api-url:
runs-on: ubuntu-latest
timeout-minutes: 15
permissions:
contents: write # For create-pull-request to push the branch
pull-requests: write # For create-pull-request to open the PR
@@ -22,16 +23,8 @@ jobs:
with:
persist-credentials: false
- name: Install uv
uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- name: Install python
run: |
uv python install
- name: Install dependencies
run: |
uv sync --frozen
- name: Set up the backend
uses: ./.github/actions/setup-backend
- name: Run HLTB API URL discovery script
# Only satisfies the backend config import; discovery authenticates nothing.
@@ -53,3 +46,11 @@ jobs:
title: "Update HLTB API URL [skip CI]"
reviewers: |
gantoine
report-failure:
needs: [update-hltb-api-url]
if: failure() && github.event_name == 'schedule'
permissions:
contents: read
issues: write
uses: ./.github/workflows/report-scheduled-failure.yml

5
.github/zizmor.yml vendored Normal file
View File

@@ -0,0 +1,5 @@
rules:
# actionlint doesn't understand the $/ self-repository syntax yet, so local
# actions and reusable workflows stay on ./ paths.
self-repository:
disable: true

View File

@@ -25,6 +25,7 @@ lint:
- mypy
enabled:
- zizmor@1.30.1
# pinact 5 accepts only --format, but the Trunk plugin release passes -format.
- pinact@4.1.1
- dotenv-linter@4.0.0
- hadolint@2.15.1
@@ -33,21 +34,21 @@ lint:
- actionlint@1.7.12
- bandit@1.9.4
- black@26.5.1
- checkov@3.3.19
- checkov@3.3.20
- git-diff-check
- no-emdash
- isort@9.0.1
- osv-scanner@2.6.0
- prettier@3.9.8:
- prettier@3.9.9:
packages:
- "@trivago/prettier-plugin-sort-imports@6.0.2"
- "@vue/compiler-sfc@3.5.43"
- ruff@0.16.8
- ruff@0.16.9
- shellcheck@0.11.0
- shfmt@3.14.1
- taplo@0.10.0
- trivy@0.74.0
- trufflehog@3.97.5
- trufflehog@3.97.9
- yamllint@1.38.0
ignore:
- linters: [ALL]

View File

@@ -0,0 +1,36 @@
"""rename platforms scanned with their ScreenScraper sibling's name
Revision ID: 0143_sibling_platform_names
Revises: 0142_state_core
Create Date: 2026-09-28 00:00:00.000000
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "0143_sibling_platform_names"
down_revision = "0142_state_core"
branch_labels = None
depends_on = None
# (slug, name a scan stored, correct name)
RENAMES = (
("c128", "Commodore 64", "Commodore 128"),
("videopac-g7400", "Videopac G7000", "Videopac+ G7400"),
)
def upgrade() -> None:
# Only the stale name is replaced, so a name set by another provider stays.
for slug, stale, name in RENAMES:
op.execute(
sa.text(
"UPDATE platforms SET name = :name WHERE slug = :slug AND name = :stale"
).bindparams(name=name, slug=slug, stale=stale)
)
def downgrade() -> None:
pass

View File

@@ -1319,16 +1319,11 @@ class DBRomsHandler(DBBaseHandler):
predicate = not_(predicate)
return query.filter(predicate)
def _filter_by_status[S: Select[Any]](
self,
query: S,
*,
values: Sequence[str],
match_all: bool = False,
match_none: bool = False,
) -> S:
def _rom_user_visibility(self, filters: RomFilterParams) -> ColumnElement[bool]:
"""The per-user predicate a rom must pass to show in the gallery."""
values = filters.statuses
if not values:
return query
return _rom_user_not_hidden()
status_filters: list[ColumnElement[bool]] = []
for selected_status in values:
@@ -1341,17 +1336,16 @@ class DBRomsHandler(DBBaseHandler):
else:
status_filters.append(RomUser.status == selected_status)
comb = and_ if match_all else or_
comb = and_ if filters.statuses_logic == "all" else or_
condition = comb(*status_filters)
if filters.statuses_logic == "none":
condition = ~condition
# Apply negation if match_none, otherwise apply condition
query = query.filter(~condition) if match_none else query.filter(condition)
# Don't apply the hidden filter is hidden is set
# Selecting the hidden status is what opts hidden roms back in
if "hidden" in values:
return query
return condition
return query.filter(_rom_user_not_hidden())
return and_(condition, _rom_user_not_hidden())
def _apply_filter_spec[S: Select[Any]](
self,
@@ -1615,6 +1609,9 @@ class DBRomsHandler(DBBaseHandler):
if hidden_rom_ids:
query = query.filter(Rom.id.not_in(hidden_rom_ids))
# The RomUser table is already joined if user_id is set
visibility = self._rom_user_visibility(filters) if user_id else true()
# BEWARE YE WHO ENTERS HERE 💀
if filters.group_by_meta_id:
# Convert NULL is_main_sibling to 0 (false) so it sorts after true values
@@ -1633,9 +1630,9 @@ class DBRomsHandler(DBBaseHandler):
)
# Create a subquery that identifies the primary ROM in each group.
# Priority order: is_main_sibling (desc), then a full release over
# a pre-release, then the configured region priority, then
# fs_name_no_ext (asc) as a stable tiebreak.
# Priority order: visible to this user, then is_main_sibling (desc),
# then a full release over a pre-release, then the configured
# region priority, then fs_name_no_ext (asc) as a stable tiebreak.
# Materialize only the columns the dedup window needs (not all of
# Rom, whose JSON metadata blobs make the derived table huge), and
# drop the carried-over ORDER BY the window doesn't use.
@@ -1720,16 +1717,20 @@ class DBRomsHandler(DBBaseHandler):
base_subquery.c.region_rank.asc(),
base_subquery.c.fs_name_no_ext.asc(),
]
if user_id:
# A sibling the visibility filter below drops can't represent
# its group while a visible one exists.
window_order.insert(0, case((visibility, 0), else_=1).asc())
window_columns: list[ColumnElement[Any]] = [
func.row_number()
.over(partition_by=partition_key, order_by=window_order)
.label("row_num"),
]
if aggregates_sort_key:
# MIN/MAX skip NULL siblings, and a hidden sibling's key is
# masked to NULL so it cannot drive a group it is absent from.
# MIN/MAX skip NULL siblings, and a filtered-out sibling's key
# is masked to NULL so it cannot drive a group it is absent from.
visible_sort_key = case(
(_rom_user_not_hidden(), _zero_unset_folded(sort_key.column))
(visibility, _zero_unset_folded(sort_key.column))
)
group_aggregate = func.max if order_dir == "desc" else func.min
window_columns.append(
@@ -1787,16 +1788,8 @@ class DBRomsHandler(DBBaseHandler):
)
)
# The RomUser table is already joined if user_id is set
if filters.statuses and user_id:
query = self._filter_by_status(
query,
values=filters.statuses,
match_all=(filters.statuses_logic == "all"),
match_none=(filters.statuses_logic == "none"),
)
elif user_id:
query = query.filter(_rom_user_not_hidden())
if user_id:
query = query.filter(visibility)
return query

View File

@@ -1237,7 +1237,8 @@ SCREENSAVER_PLATFORM_LIST: dict[UPS, SlugToSSId] = {
UPS.COLECOADAM: {"id": 89, "name": "Coleco Adam"},
UPS.COLECOVISION: {"id": 48, "name": "Colecovision"},
UPS.COLOUR_GENIE: {"id": 92, "name": "EG2000 Colour Genie"},
UPS.C128: {"id": 66, "name": "Commodore 64"},
# ScreenScraper files C128 under its C64 system; keep the display name distinct.
UPS.C128: {"id": 66, "name": "Commodore 128"},
UPS.C_PLUS_4: {"id": 99, "name": "Plus/4"},
UPS.C16: {"id": 99, "name": "Plus/4"},
UPS.C64: {"id": 66, "name": "Commodore 64"},
@@ -1368,7 +1369,7 @@ SCREENSAVER_PLATFORM_LIST: dict[UPS, SlugToSSId] = {
UPS.VSMILE: {"id": 120, "name": "V.Smile"},
UPS.VIC_20: {"id": 73, "name": "Vic-20"},
UPS.VECTREX: {"id": 102, "name": "Vectrex"},
UPS.VIDEOPAC_G7400: {"id": 104, "name": "Videopac G7000"},
UPS.VIDEOPAC_G7400: {"id": 104, "name": "Videopac+ G7400"},
UPS.VIRTUALBOY: {"id": 11, "name": "Virtual Boy"},
UPS.WII: {"id": 16, "name": "Wii"},
UPS.WIIU: {"id": 18, "name": "Wii U"},

View File

@@ -423,3 +423,105 @@ class TestGroupedRomUserSortQueryShape:
assert "group_sort_value" not in sql
assert "IN (SELECT" in sql
assert order_clause in sql
class TestGroupedRepresentativeVisibility:
"""A group's representative is picked among the siblings the user sees."""
def _names(self, user: User, platform: Platform, **kwargs: Any) -> list[str]:
return _ordered_names(
user,
"name",
"asc",
attr="fs_name_no_ext",
platform_ids=[platform.id],
group_by_meta_id=True,
**kwargs,
)
def test_hidden_representative_promotes_a_visible_sibling(
self, admin_user: User, platform: Platform
):
_set_rom_user_fields(
_make_rom(platform, "Sonic", region="USA", igdb_id=100),
admin_user,
{"hidden": True},
)
_make_rom(platform, "Sonic", region="Japan", igdb_id=100)
assert self._names(admin_user, platform) == ["Sonic (Japan)"]
def test_fully_hidden_group_stays_out(self, admin_user: User, platform: Platform):
for region in ("USA", "Japan"):
_set_rom_user_fields(
_make_rom(platform, "Sonic", region=region, igdb_id=100),
admin_user,
{"hidden": True},
)
assert self._names(admin_user, platform) == []
def test_hidden_status_view_shows_the_hidden_sibling(
self, admin_user: User, platform: Platform
):
_make_rom(platform, "Sonic", region="USA", igdb_id=100)
_set_rom_user_fields(
_make_rom(platform, "Sonic", region="Japan", igdb_id=100),
admin_user,
{"hidden": True},
)
assert self._names(admin_user, platform, statuses=["hidden"]) == [
"Sonic (Japan)"
]
def test_status_match_on_a_non_primary_sibling_keeps_the_group(
self, admin_user: User, platform: Platform
):
_make_rom(platform, "Sonic", region="USA", igdb_id=100)
_set_rom_user_fields(
_make_rom(platform, "Sonic", region="Japan", igdb_id=100),
admin_user,
{"now_playing": True},
)
assert self._names(admin_user, platform, statuses=["now_playing"]) == [
"Sonic (Japan)"
]
def test_non_matching_sibling_does_not_drive_the_group_sort(
self, admin_user: User, platform: Platform
):
# Sonic's newest play belongs to the Japan sibling, which the status
# filter drops, so its group sorts by the matching USA play.
_set_rom_user_fields(
_make_rom(platform, "Sonic", region="USA", igdb_id=100),
admin_user,
{
"now_playing": True,
"last_played": datetime(2020, 1, 1, tzinfo=timezone.utc),
},
)
_set_rom_user_fields(
_make_rom(platform, "Sonic", region="Japan", igdb_id=100),
admin_user,
{"last_played": datetime(2026, 1, 1, tzinfo=timezone.utc)},
)
_set_rom_user_fields(
_make_rom(platform, "Tails", region="USA", igdb_id=200),
admin_user,
{
"now_playing": True,
"last_played": datetime(2024, 1, 1, tzinfo=timezone.utc),
},
)
assert _ordered_names(
admin_user,
"last_played",
"desc",
attr="fs_name_no_ext",
platform_ids=[platform.id],
group_by_meta_id=True,
statuses=["now_playing"],
) == ["Tails (USA)", "Sonic (USA)"]

View File

@@ -20,8 +20,10 @@ from sqlalchemy import DefaultClause, FetchedValue, Table, UniqueConstraint
from sqlalchemy.sql.schema import NULL_UNSPECIFIED
import models
from handler.database import db_platform_handler
from handler.database.base_handler import sync_engine
from models.base import BaseModel
from models.platform import Platform
from models.rom import FULL_PATH_HASH_LENGTH, Rom, compute_full_path_hash
from utils.database import (
AUTOGENERATE_EXEMPT_INDEX_NAMES,
@@ -241,6 +243,7 @@ def _replay(connection: sa.Connection, filename: str) -> None:
("0140_device_save_sync_baseline.py", "device_save_sync"),
("0141_device_capabilities.py", "devices"),
("0142_state_core.py", "states"),
("0143_sibling_platform_names.py", "platforms"),
],
)
def test_a_revision_replayed_over_the_migrated_schema_is_a_no_op(
@@ -850,3 +853,30 @@ def test_the_group_rename_leaves_admin_changes_alone():
"Editor": "Custom",
}
assert keys == {"viewer": "Viewer (legacy)", "editor": "Editor"}
def test_the_sibling_platform_names_revision_renames_only_the_stale_name():
migration = _load_migration("0143_sibling_platform_names.py")
for name, slug, fs_slug in (
("Commodore 64", "c128", "c128"),
("Videopac G7000", "videopac-g7400", "videopac-g7400"),
("Commodore 64", "c64", "c64"),
("C128 (custom)", "c128", "c128-custom"),
):
db_platform_handler.add_platform(
Platform(name=name, slug=slug, fs_slug=fs_slug)
)
with sync_engine.begin() as connection:
with Operations.context(MigrationContext.configure(connection)):
migration.upgrade()
names = set(
connection.execute(sa.text("SELECT fs_slug, name FROM platforms")).all()
)
assert names == {
("c128", "Commodore 128"),
("videopac-g7400", "Videopac+ G7400"),
("c64", "Commodore 64"),
("c128-custom", "C128 (custom)"),
}

View File

@@ -52,3 +52,11 @@ async def test_filesystem_platform_resolves_frontend_folder_name(monkeypatch):
platforms = await get_filesystem_platforms()
assert [(p.fs_slug, p.slug) for p in platforms] == [("gamecube", "ngc")]
def test_supported_platform_sharing_ss_id_keeps_its_own_name():
"""A platform sharing a ScreenScraper system ID must not take its sibling's name."""
supported = {p.slug: p for p in get_supported_platforms()}
assert supported["c128"].name == "Commodore 128"
assert supported["videopac-g7400"].name == "Videopac+ G7400"

View File

@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Write the app's OpenAPI schema to a JSON file without starting the server."""
import json
import sys
from pathlib import Path
from main import app
if __name__ == "__main__":
# Importing the app needs DB credentials set but never connects. The app
# logs to stdout, so the schema goes to a file rather than a pipe.
Path(sys.argv[1]).write_text(json.dumps(app.openapi()))

View File

@@ -17,7 +17,7 @@ export type DeviceSchema = {
sync_mode: SyncMode;
sync_enabled: boolean;
sync_config: (Record<string, any> | null);
capabilities: (Record<string, any> | null);
capabilities: (Record<string, boolean> | null);
last_seen: (string | null);
created_at: string;
updated_at: string;

View File

@@ -38,6 +38,7 @@ import {
resolveScreenshot,
} from "@/views/Player/EmulatorJS/utils";
import {
bootEmulatorJSSave,
installEJSDefaultOptionsTrap,
invalidateEmulatorJSRomCacheIfRenamed,
} from "@/views/Player/EmulatorJS/utils";
@@ -638,20 +639,8 @@ async function boot() {
if (!resp.ok) throw new Error("Failed to fetch save");
const buf = new Uint8Array(await resp.arrayBuffer());
try {
const FS = gameManager.FS;
const path = gameManager.getSaveFilePath();
// Ensure dirs
const segs = path.split("/");
let accum = "";
for (let i = 0; i < segs.length - 1; i++) {
if (!segs[i]) continue;
accum += "/" + segs[i];
if (!FS.analyzePath(accum).exists) FS.mkdir(accum);
}
if (FS.analyzePath(path).exists) FS.unlink(path);
FS.writeFile(path, buf);
gameManager.loadSaveFiles?.();
console.info("[ConsolePlay] Loaded server save into path", path);
bootEmulatorJSSave(buf);
console.info("[ConsolePlay] Loaded server save");
} catch (err) {
console.warn("[ConsolePlay] Failed writing save file", err);
}

View File

@@ -47,6 +47,7 @@ import {
heldFor,
resolveScreenshot,
saveState,
bootEmulatorJSSave,
loadEmulatorJSSave,
loadEmulatorJSState,
invalidateEmulatorJSRomCacheIfRenamed,
@@ -643,7 +644,10 @@ function onPageHide() {
// Saves management
// Resolves whether this pick reached the core: a later pick, a state load or
// leaving the player voids a download still in flight.
async function loadSave(save: SaveSchema): Promise<boolean> {
async function loadSave(
save: SaveSchema,
apply: (bytes: Uint8Array) => void = loadEmulatorJSSave,
): Promise<boolean> {
const generation = ++saveGeneration;
saveLoading = true;
@@ -654,7 +658,7 @@ async function loadSave(save: SaveSchema): Promise<boolean> {
});
if (disposed || generation !== saveGeneration) return false;
const bytes = new Uint8Array(data);
loadEmulatorJSSave(bytes);
apply(bytes);
// Writes follow the picked save only once its bytes are in the core.
loadedSave = save;
sessionSaveRef.value = null;
@@ -861,7 +865,7 @@ window.EJS_onGameStart = async () => {
);
await loadState(props.state);
} else if (props.save) {
await loadSave(props.save);
await loadSave(props.save, bootEmulatorJSSave);
} else {
baselineSaveTrackerFromEmulator();
}

View File

@@ -11,7 +11,9 @@ import {
createSaveSyncTracker,
RETRY_BACKOFF_MAX_MS,
RETRY_BACKOFF_MIN_MS,
bootEmulatorJSSave,
installEJSDefaultOptionsTrap,
loadEmulatorJSSave,
pollSaveFiles,
resolveScreenshot,
saveSave,
@@ -248,6 +250,70 @@ describe("installEJSDefaultOptionsTrap", () => {
"/neogeo.zip": "/api/firmware/1/content/neogeo.zip",
});
});
describe("cheats", () => {
function makeCheatEmulator(
cheats: { desc: string; code: string; checked: boolean }[],
) {
const emulator = makeEmulator({});
emulator.cheats = cheats;
emulator.gameManager = { setCheat: vi.fn(), resetCheat: vi.fn() };
window.EJS_emulator = emulator;
return emulator;
}
it("never hands a disabled cheat to the core", () => {
// fceumm applies every code it receives, whatever the flag (#4208).
const emulator = makeCheatEmulator([
{ desc: "lives", code: "SLUSZTVS", checked: false },
]);
emulator.cheatChanged(false, "SLUSZTVS", 0);
expect(emulator.gameManager.resetCheat).toHaveBeenCalled();
expect(emulator.gameManager.setCheat).not.toHaveBeenCalled();
});
it("reapplies the other enabled cheats when one is turned off", () => {
const emulator = makeCheatEmulator([
{ desc: "lives", code: "SLUSZTVS", checked: false },
{ desc: "time", code: "AAAAAAAA", checked: true },
]);
emulator.cheatChanged(false, "SLUSZTVS", 0);
expect(emulator.gameManager.setCheat).toHaveBeenCalledExactlyOnceWith(
1,
true,
"AAAAAAAA",
);
});
it("drops a checked cheat that is being removed", () => {
const emulator = makeCheatEmulator([
{ desc: "lives", code: "SLUSZTVS", checked: true },
]);
emulator.cheatChanged(false, "SLUSZTVS", 0);
expect(emulator.gameManager.setCheat).not.toHaveBeenCalled();
});
it("enables a cheat without resetting the others", () => {
const emulator = makeCheatEmulator([
{ desc: "lives", code: "SLUSZTVS", checked: true },
]);
emulator.cheatChanged(true, "SLUSZTVS", 0);
expect(emulator.gameManager.resetCheat).not.toHaveBeenCalled();
expect(emulator.gameManager.setCheat).toHaveBeenCalledWith(
0,
true,
"SLUSZTVS",
);
});
});
});
describe("createSaveSyncTracker", () => {
@@ -551,6 +617,70 @@ describe("dumpSaveFile", () => {
/* eslint-enable @typescript-eslint/no-explicit-any */
});
describe("loadEmulatorJSSave", () => {
/* eslint-disable @typescript-eslint/no-explicit-any */
const path = "/data/saves/nds/game.sav";
function mountEmulator(existing: Uint8Array | null) {
const files = new Map<string, Uint8Array>();
if (existing) files.set(path, existing);
const FS = {
analyzePath: (p: string) => ({ exists: files.has(p) || p !== path }),
mkdir: vi.fn(),
readFile: (p: string) => files.get(p),
unlink: (p: string) => files.delete(p),
writeFile: (p: string, bytes: Uint8Array) => files.set(p, bytes),
};
const loadSaveFiles = vi.fn();
const restart = vi.fn();
(window as any).EJS_emulator = {
gameManager: { FS, getSaveFilePath: () => path, loadSaveFiles, restart },
};
return { files, loadSaveFiles, restart };
}
afterEach(() => {
(window as any).EJS_emulator = undefined;
});
it("reports a change when the browser had no save cached", () => {
const { files, loadSaveFiles } = mountEmulator(null);
expect(loadEmulatorJSSave(new Uint8Array([1, 2]))).toBe(true);
expect(files.get(path)).toEqual(new Uint8Array([1, 2]));
expect(loadSaveFiles).toHaveBeenCalledOnce();
});
it("reports a change when the cached save differs", () => {
mountEmulator(new Uint8Array([9]));
expect(loadEmulatorJSSave(new Uint8Array([1, 2]))).toBe(true);
});
it("reports no change when the core booted with the same save", () => {
mountEmulator(new Uint8Array([1, 2]));
expect(loadEmulatorJSSave(new Uint8Array([1, 2]))).toBe(false);
});
it("restarts a freshly booted core when the save changed", () => {
const { files, restart } = mountEmulator(null);
bootEmulatorJSSave(new Uint8Array([1, 2]));
expect(files.get(path)).toEqual(new Uint8Array([1, 2]));
expect(restart).toHaveBeenCalledOnce();
});
it("leaves a core that booted with the same save running", () => {
const { restart } = mountEmulator(new Uint8Array([1, 2]));
bootEmulatorJSSave(new Uint8Array([1, 2]));
expect(restart).not.toHaveBeenCalled();
});
/* eslint-enable @typescript-eslint/no-explicit-any */
});
describe("resolveScreenshot", () => {
/* eslint-disable @typescript-eslint/no-explicit-any */
afterEach(() => {

View File

@@ -415,7 +415,14 @@ export function toArrayBuffer(view: Uint8Array): ArrayBuffer {
return copy.buffer;
}
export function loadEmulatorJSSave(save: Uint8Array) {
/**
* Writes a save over the core's save file and reloads it into the SRAM.
*
* Returns:
* Whether the bytes differ from the file already there. Games read their
* SRAM at boot, so a changed save only shows once the core restarts.
*/
export function loadEmulatorJSSave(save: Uint8Array): boolean {
const FS = window.EJS_emulator.gameManager.FS;
const path = window.EJS_emulator.gameManager.getSaveFilePath();
const paths = path.split("/");
@@ -425,9 +432,19 @@ export function loadEmulatorJSSave(save: Uint8Array) {
cp += "/" + paths[i];
if (!FS.analyzePath(cp).exists) FS.mkdir(cp);
}
if (FS.analyzePath(path).exists) FS.unlink(path);
let previous: Uint8Array | null = null;
if (FS.analyzePath(path).exists) {
previous = FS.readFile(path);
FS.unlink(path);
}
FS.writeFile(path, save);
window.EJS_emulator.gameManager.loadSaveFiles();
return !bytesEqual(previous, save);
}
/** Loads a save into a core that just booted, restarting it when the save changed. */
export function bootEmulatorJSSave(save: Uint8Array) {
if (loadEmulatorJSSave(save)) window.EJS_emulator.gameManager.restart();
}
export function loadEmulatorJSState(state: Uint8Array) {
@@ -528,6 +545,31 @@ function replayConnectedGamepads(emulator: any) {
}
}
// Some cores (fceumm) ignore retro_cheat_set's enabled flag and apply every
// code they get, so a disabled cheat must never reach the core at all.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function applyOnlyEnabledCheats(emulator: any) {
if (emulator.__rommCheatsPatched) return;
emulator.__rommCheatsPatched = true;
emulator.cheatChanged = (checked: boolean, code: string, index: number) => {
const gameManager = emulator.gameManager;
if (!gameManager) return;
if (checked) {
gameManager.setCheat(index, true, code);
return;
}
gameManager.resetCheat();
// A removed cheat is still in the list, and may still be checked.
(emulator.cheats ?? []).forEach(
(cheat: { checked?: boolean; code: string }, i: number) => {
if (cheat.checked && i !== index)
gameManager.setCheat(i, true, cheat.code);
},
);
};
}
// Trap the window.EJS_emulator assignment so the instance is patched right
// after the constructor returns, before the async core download and boot
// consume any of the patched values. Patching later (e.g. in EJS_onGameStart)
@@ -545,6 +587,7 @@ export function installEJSDefaultOptionsTrap() {
installDefaultOptionsFallback(value);
replayConnectedGamepads(value);
keepArcadeBiosWhole(value);
applyOnlyEnabledCheats(value);
},
});
}

View File

@@ -3,7 +3,13 @@
"extends": ["config:recommended", ":semanticCommitTypeAll(chore)"],
"description": "Updates wait out a week before Renovate proposes them, so a compromised release has time to be pulled before it reaches a PR here.",
"minimumReleaseAge": "7 days",
"enabledManagers": ["github-actions", "docker-compose", "custom.regex"],
"enabledManagers": [
"github-actions",
"docker-compose",
"npm",
"pep621",
"custom.regex"
],
"ignorePaths": ["examples/**"],
"packageRules": [
{
@@ -28,6 +34,31 @@
"matchManagers": ["github-actions"],
"matchDepTypes": ["action"],
"groupName": "github actions"
},
{
"description": "Keep the ranges maintainers chose in package.json and pyproject.toml; in-range updates only refresh the lockfile.",
"matchManagers": ["npm", "pep621"],
"rangeStrategy": "update-lockfile"
},
{
"description": "One weekly PR per ecosystem for minor and patch updates, so app dependencies don't open a PR each.",
"matchManagers": ["npm"],
"matchFileNames": ["frontend/package.json"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "frontend dependencies",
"schedule": ["before 6am on monday"]
},
{
"matchManagers": ["pep621"],
"matchUpdateTypes": ["minor", "patch"],
"groupName": "backend dependencies",
"schedule": ["before 6am on monday"]
},
{
"description": "Major updates usually need code changes, so they wait for approval on the Dependency Dashboard.",
"matchManagers": ["npm", "pep621"],
"matchUpdateTypes": ["major"],
"dependencyDashboardApproval": true
}
],
"customManagers": [