Compare commits
31
Commits
92bef4c7aa
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
86ae907f59 | ||
|
|
855b5f9f54 | ||
|
|
e6c6553afc | ||
|
|
525335e6dd | ||
|
|
e3c5e546eb | ||
|
|
607f375809 | ||
|
|
1c6c9ccc1f | ||
|
|
ab4142fb95 | ||
|
|
bf4e98fa30 | ||
|
|
fbc8af7510 | ||
|
|
518fd101a2 | ||
|
|
27ee279f28 | ||
|
|
f1b7d67aa5 | ||
|
|
458043280a | ||
|
|
6869ae433a | ||
|
|
cbf2a8ee39 | ||
|
|
cfa4628f8c | ||
|
|
914034dda0 | ||
|
|
3073baeb8b | ||
|
|
5e418bf941 | ||
|
|
a68d7ebaee | ||
|
|
1bf89a3942 | ||
|
|
ac2b8ded93 | ||
|
|
af0f0adadc | ||
|
|
36c1a72363 | ||
|
|
7999582460 | ||
|
|
218e05e71e | ||
|
|
afac1bf8e7 | ||
|
|
49d056f744 | ||
|
|
aa8cb1c96f | ||
|
|
5760059ee3 |
@@ -0,0 +1,217 @@
|
||||
name: CI
|
||||
|
||||
# Signage builds, tests, and runs only inside an Ekklesia workspace, so every job first assembles it
|
||||
# into the platform commit pinned in ci/platform.env (ci/assemble.sh) and installs that workspace
|
||||
# with --frozen-lockfile from ci/pnpm-lock.yaml.
|
||||
#
|
||||
# The same trust rules as the platform's own CI (docs/development/security.md there):
|
||||
# * every action is pinned by a full commit SHA;
|
||||
# * every checkout sets `persist-credentials: false`, and nothing in this workflow pushes;
|
||||
# * no repository, organization, or instance secret is referenced;
|
||||
# * there is no `pull_request_target`;
|
||||
# * the self-hosted runner executes trusted, reviewed code only.
|
||||
#
|
||||
# The server is Gitea 1.24, which ignores `permissions`, `concurrency`, and `timeout-minutes`
|
||||
# (https://docs.gitea.com/1.24/usage/actions/comparison). They are declared so the workflow is already
|
||||
# correct on a release that honours them; on 1.24 they bound nothing, and `permissions` does not
|
||||
# restrict the job token.
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lint:
|
||||
name: lint
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Lint
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage lint
|
||||
|
||||
- name: Check that CI cleans up every stack it starts
|
||||
run: bash ci/check-cleanup.sh
|
||||
|
||||
typecheck:
|
||||
name: typecheck
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build the platform packages Signage depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage^...'
|
||||
|
||||
- name: Typecheck the server, browser, and browser-test projects
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage typecheck
|
||||
|
||||
test:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build the platform packages Signage depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage^...'
|
||||
|
||||
- name: Unit, browser, and display contract tests
|
||||
working-directory: build/workspace
|
||||
run: pnpm --filter @ekklesia/signage test
|
||||
|
||||
build:
|
||||
name: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
# Nothing here pushes, so the job token is never needed after checkout and must not be left
|
||||
# in .git/config for a later step to read.
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
- name: Set up Node.js at the platform's version
|
||||
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
|
||||
with:
|
||||
node-version-file: build/workspace/.node-version
|
||||
|
||||
- name: Install the assembled workspace (frozen lockfile)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
corepack enable
|
||||
corepack install
|
||||
pnpm install --frozen-lockfile
|
||||
|
||||
# The same gates the platform's image build runs against exactly this module set: its boundary
|
||||
# rules (which apply to modules), the manifest, and the migrations.
|
||||
- name: Platform gates (boundaries, module manifest, migrations)
|
||||
working-directory: build/workspace
|
||||
run: |
|
||||
pnpm boundaries
|
||||
pnpm modules:validate
|
||||
pnpm migrations:validate
|
||||
|
||||
- name: Build Signage and the platform it depends on
|
||||
working-directory: build/workspace
|
||||
run: pnpm exec turbo run build --filter='@ekklesia/signage...'
|
||||
|
||||
# Signage inside Ekklesia, end to end, in a real browser: the platform's own Dockerfile builds the
|
||||
# deployment image with Signage in it, and the platform's split-topology deployment smoke runs
|
||||
# against it, pairing a kiosk display and running the scenarios in ci/display-scenarios. A
|
||||
# disposable database and object store with generated secrets; nothing is pushed or logged in to.
|
||||
integration:
|
||||
name: integration
|
||||
needs:
|
||||
- test
|
||||
- build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
env:
|
||||
DOCKER_BUILDKIT: "1"
|
||||
# Names this job's stacks, so its final step removes exactly these (the platform's
|
||||
# scripts/lib/ci-project.sh).
|
||||
EKKLESIA_CI_JOB_KEY: signage-integration
|
||||
steps:
|
||||
- name: Check out repository
|
||||
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Assemble Signage into the pinned platform
|
||||
run: bash ci/assemble.sh
|
||||
|
||||
# A job the runner killed (cancelled, or past the runner's own time limit) never ran its
|
||||
# cleanup. Anything a CI job left on this shared daemon more than three hours ago goes first.
|
||||
- name: Sweep stale CI stacks from the runner
|
||||
run: bash build/workspace/scripts/ci-sweep.sh --stale
|
||||
|
||||
- name: Build the image and run the display scenarios
|
||||
run: bash ci/integration.sh
|
||||
|
||||
# Whatever happened above, this job's own stacks do not outlive it. If assembly failed, nothing
|
||||
# was started.
|
||||
- name: Remove this job's CI stacks
|
||||
if: always()
|
||||
run: |
|
||||
if [ -f build/workspace/scripts/ci-sweep.sh ]; then
|
||||
bash build/workspace/scripts/ci-sweep.sh --job
|
||||
fi
|
||||
@@ -4,3 +4,4 @@ dist/
|
||||
coverage/
|
||||
*.log
|
||||
.DS_Store
|
||||
build/
|
||||
|
||||
@@ -16,7 +16,8 @@ Ekklesia and vendors none of its SDKs.
|
||||
|
||||
## Status
|
||||
|
||||
Version 0.1.0 is feature-complete for its declared scope and unreleased. What exists today:
|
||||
Version 0.1.2 is feature-complete for its declared scope, and Signage has run in production since
|
||||
0.1.1. What exists today:
|
||||
|
||||
- The module package, manifest (v7), four capabilities, six permissions, ten operator settings, and
|
||||
one logical storage bucket.
|
||||
@@ -34,10 +35,10 @@ Version 0.1.0 is feature-complete for its declared scope and unreleased. What ex
|
||||
renderers mounted as browser contributions, the built-in "Content unavailable" slate, deliberate
|
||||
blackout, and offline continuation from this display's own persisted state.
|
||||
|
||||
Nothing here is deployed, and no cutover from the legacy Announcements container has happened or is
|
||||
planned by this repository. Video, audio, MQTT, Home Assistant, Companion, and a notification outbox
|
||||
are out of scope; so is any content module — Signage ships with no announcements, scripture, or
|
||||
trivia, and cannot render any until one is installed.
|
||||
No cutover from the legacy Announcements container has happened or is planned by this repository.
|
||||
Video, audio, MQTT, Home Assistant, Companion, and a notification outbox are out of scope; so is
|
||||
any content module — Signage ships with no announcements, scripture, or trivia, and cannot render
|
||||
any until one is installed.
|
||||
|
||||
### Offline cold start is not yet possible
|
||||
|
||||
|
||||
Executable
+72
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env bash
|
||||
# Assembles Signage into the Ekklesia platform it is tested against: the platform at the commit pinned
|
||||
# in ci/platform.env, this checkout at modules/signage, and ci/pnpm-lock.yaml as the workspace
|
||||
# lockfile. Signage cannot build or run outside an Ekklesia workspace, so every CI job starts here.
|
||||
#
|
||||
# bash ci/assemble.sh [--allow-missing-lock] [output directory]
|
||||
#
|
||||
# The output directory (default build/workspace) is deleted and recreated. The platform is fetched
|
||||
# by its `main` branch and the pinned commit must be on it, so CI only ever runs reviewed platform
|
||||
# code; the checkout is then by commit, so nothing after it depends on a ref the network can move.
|
||||
# Every .git directory is removed afterwards.
|
||||
#
|
||||
# --allow-missing-lock keeps the platform's own lockfile. Only ci/update-lock.sh uses it.
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
allow_missing_lock=0
|
||||
if [[ "${1:-}" == "--allow-missing-lock" ]]; then
|
||||
allow_missing_lock=1
|
||||
shift
|
||||
fi
|
||||
out="${1:-$root/build/workspace}"
|
||||
|
||||
fail() {
|
||||
echo "assemble: $*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
for command in git tar; do
|
||||
command -v "$command" >/dev/null || fail "$command is required."
|
||||
done
|
||||
|
||||
# Read the two pins without sourcing the file: it is data, not a script.
|
||||
pin() {
|
||||
local value
|
||||
value="$(sed -n "s/^$1=//p" "$root/ci/platform.env")"
|
||||
[[ -n "$value" ]] || fail "ci/platform.env has no $1."
|
||||
printf '%s' "$value"
|
||||
}
|
||||
repository="$(pin EKKLESIA_PLATFORM_REPOSITORY)"
|
||||
commit="$(pin EKKLESIA_PLATFORM_COMMIT)"
|
||||
[[ "$commit" =~ ^[0-9a-f]{40}$ ]] || fail "EKKLESIA_PLATFORM_COMMIT must be a full commit SHA."
|
||||
|
||||
rm -rf "$out"
|
||||
mkdir -p "$(dirname -- "$out")"
|
||||
git init --quiet "$out"
|
||||
git -C "$out" remote add origin "$repository"
|
||||
git -C "$out" fetch --quiet --no-tags origin "+refs/heads/main:refs/remotes/origin/main" ||
|
||||
fail "cannot fetch the platform's main from ${repository}."
|
||||
git -C "$out" cat-file -e "${commit}^{commit}" 2>/dev/null ||
|
||||
fail "the pinned platform commit ${commit} is not on the platform's main."
|
||||
git -C "$out" merge-base --is-ancestor "$commit" refs/remotes/origin/main ||
|
||||
fail "the pinned platform commit ${commit} is not on the platform's main."
|
||||
git -C "$out" -c advice.detachedHead=false checkout --quiet --detach "$commit"
|
||||
[[ "$(git -C "$out" rev-parse HEAD)" == "$commit" ]] || fail "the platform did not check out at ${commit}."
|
||||
rm -rf "$out/.git"
|
||||
echo "assemble: platform ${commit}"
|
||||
|
||||
[[ ! -e "$out/modules/signage" ]] || fail "the platform checkout already has modules/signage."
|
||||
mkdir -p "$out/modules/signage"
|
||||
# Exactly the files this checkout tracks, as committed or as changed in the working tree. Nothing
|
||||
# installed, built, or ignored, and not the CI scaffolding, which is not part of the module.
|
||||
git -C "$root" ls-files -z --cached --others --exclude-standard -- . ':!ci' ':!.gitea' |
|
||||
tar -C "$root" --null --files-from=- --create --file=- |
|
||||
tar -C "$out/modules/signage" --extract --file=-
|
||||
echo "assemble: signage $(git -C "$root" rev-parse HEAD 2>/dev/null || echo "(working tree)")"
|
||||
|
||||
if [[ -f "$root/ci/pnpm-lock.yaml" ]]; then
|
||||
cp "$root/ci/pnpm-lock.yaml" "$out/pnpm-lock.yaml"
|
||||
elif ((allow_missing_lock == 0)); then
|
||||
fail "ci/pnpm-lock.yaml is missing; run bash ci/update-lock.sh."
|
||||
fi
|
||||
Executable
+45
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env bash
|
||||
# Checks that Signage's CI cleans up every stack it starts, even when the runner kills a job (the
|
||||
# platform's rule: docs/development/security.md, "Disposable stacks never outlive their job").
|
||||
#
|
||||
# bash ci/check-cleanup.sh
|
||||
#
|
||||
# The `integration` job is the one that starts Docker stacks. It must have its own
|
||||
# EKKLESIA_CI_JOB_KEY, sweep stale CI stacks before it starts anything, and remove its own in a final
|
||||
# `if: always()` step; and the image ci/integration.sh builds must carry the CI labels the sweep finds.
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
workflow="$root/.gitea/workflows/ci.yml"
|
||||
failures=0
|
||||
check() {
|
||||
if eval "$1"; then
|
||||
echo "ok $2"
|
||||
else
|
||||
echo "FAIL $2"
|
||||
failures=$((failures + 1))
|
||||
fi
|
||||
}
|
||||
|
||||
# The integration job's lines, from its key to the next job (or the end of the file).
|
||||
job="$(awk '/^ integration:$/ { inside = 1; print; next } inside && /^ [a-z][a-z-]*:$/ { exit } inside { print }' "$workflow")"
|
||||
line_of() { grep -n -F -- "$1" <<<"$job" | head -1 | cut -d: -f1 || true; }
|
||||
|
||||
stale="$(line_of 'ci-sweep.sh --stale')"
|
||||
run="$(line_of 'bash ci/integration.sh')"
|
||||
own="$(line_of 'ci-sweep.sh --job')"
|
||||
last_step="$(grep -n -- " - name:" <<<"$job" | tail -1 | cut -d: -f1 || true)"
|
||||
|
||||
check '[[ -n "$job" ]]' "the workflow has an integration job"
|
||||
check 'grep -q "EKKLESIA_CI_JOB_KEY:" <<<"$job"' "the integration job names its stacks with its own key"
|
||||
check '[[ -n "$stale" && -n "$run" ]] && ((stale < run))' "it sweeps stale CI stacks before it starts anything"
|
||||
check '[[ -n "$own" && -n "$run" ]] && ((own > run)) && ((own > last_step))' \
|
||||
"its last step removes its own stacks"
|
||||
check 'sed -n "${last_step},\$p" <<<"$job" | grep -q "if: always()"' "that last step always runs"
|
||||
check 'grep -q "EKKLESIA_CI_LABEL" "$root/ci/integration.sh" && grep -q "EKKLESIA_CI_CREATED_LABEL" "$root/ci/integration.sh"' \
|
||||
"the image ci/integration.sh builds carries the CI labels"
|
||||
|
||||
((failures == 0)) || {
|
||||
echo "check-cleanup: ${failures} check(s) failed." >&2
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
# The platform's display-device scenarios this repository's CI runs against Signage, one per line
|
||||
# (scripts/lib/deploy-smoke-display.mjs in the pinned platform). Pairing a kiosk and restarting it on
|
||||
# the same profile always run first. A change that makes another scenario pass adds it here.
|
||||
two-pages
|
||||
session-blip
|
||||
stream-failure
|
||||
stream-recycle
|
||||
Executable
+44
@@ -0,0 +1,44 @@
|
||||
#!/usr/bin/env bash
|
||||
# Signage inside Ekklesia, end to end: builds the deployment image from the assembled workspace with
|
||||
# the platform's own Dockerfile, then runs the platform's split-topology deployment smoke against it
|
||||
# with the display-device scenarios listed in ci/display-scenarios. A disposable PostgreSQL and object
|
||||
# store, generated secrets, and an explicit migration apply against that fresh database only; nothing
|
||||
# is pushed, published, or logged in to. The image is removed afterwards.
|
||||
#
|
||||
# bash ci/integration.sh (after bash ci/assemble.sh)
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
workspace="$root/build/workspace"
|
||||
[[ -f "$workspace/deploy/Dockerfile" ]] || {
|
||||
echo "integration: run bash ci/assemble.sh first." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
# Named and labeled as a CI stack of this run and job (the platform's scripts/lib/ci-project.sh), so
|
||||
# the workflow's final `ci-sweep.sh --job` removes it even if this script is killed before its trap.
|
||||
# shellcheck source=/dev/null
|
||||
source "$workspace/scripts/lib/ci-project.sh"
|
||||
project="$(ci_project_name signage-image)"
|
||||
image="${project}:latest"
|
||||
trap 'docker image rm --force "$image" >/dev/null 2>&1 || true' EXIT
|
||||
|
||||
scenarios="$(sed -e 's/#.*//' -e '/^[[:space:]]*$/d' "$root/ci/display-scenarios" | tr '\n' ' ')"
|
||||
[[ -n "${scenarios// /}" ]] || {
|
||||
echo "integration: ci/display-scenarios lists no scenario." >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
DOCKER_BUILDKIT=1 docker build --quiet --file "$workspace/deploy/Dockerfile" --tag "$image" \
|
||||
--label "${EKKLESIA_CI_LABEL}=${project}" --label "${EKKLESIA_CI_CREATED_LABEL}=$(date +%s)" \
|
||||
"$workspace" >/dev/null
|
||||
echo "integration: built the deployment image with Signage; scenarios: ${scenarios}"
|
||||
|
||||
cd "$workspace"
|
||||
EKKLESIA_SMOKE_TOPOLOGY=split \
|
||||
EKKLESIA_SMOKE_IMAGE="$image" \
|
||||
EKKLESIA_SMOKE_DISPLAY_DEVICE=1 \
|
||||
EKKLESIA_SMOKE_DISPLAY_SCENARIOS="$scenarios" \
|
||||
EKKLESIA_SMOKE_WATCH_MS=120000 \
|
||||
EKKLESIA_SMOKE_RECYCLE_WATCH_MS=120000 \
|
||||
bash scripts/smoke-deploy.sh
|
||||
@@ -0,0 +1,6 @@
|
||||
# The Ekklesia platform Signage's CI builds and tests against: one reviewed commit on the platform's
|
||||
# `main`, never a moving ref. ci/assemble.sh refuses a commit that is not on `main`.
|
||||
#
|
||||
# Move it deliberately: change the commit, run `bash ci/update-lock.sh`, and commit both.
|
||||
EKKLESIA_PLATFORM_REPOSITORY=https://git.riverofglorymn.org/River_of_Glory_Church/Ekklesia.git
|
||||
EKKLESIA_PLATFORM_COMMIT=874deabea3468eb5c3e907f0821718b077a682c7
|
||||
Generated
+4403
File diff suppressed because it is too large
Load Diff
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates ci/pnpm-lock.yaml: the lockfile of Signage assembled into the pinned platform. Run it
|
||||
# after changing Signage's dependencies or ci/platform.env, and commit the result. CI installs with
|
||||
# --frozen-lockfile, so a stale lockfile fails there rather than resolving anything new.
|
||||
#
|
||||
# bash ci/update-lock.sh
|
||||
#
|
||||
# Uses the platform's own pinned pnpm (its packageManager field) through Corepack.
|
||||
set -Eeuo pipefail
|
||||
|
||||
root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
bash "$root/ci/assemble.sh" --allow-missing-lock "$work/workspace"
|
||||
cd "$work/workspace"
|
||||
corepack enable >/dev/null 2>&1 || true
|
||||
corepack install >/dev/null
|
||||
pnpm install --lockfile-only
|
||||
cp pnpm-lock.yaml "$root/ci/pnpm-lock.yaml"
|
||||
echo "update-lock: wrote ci/pnpm-lock.yaml"
|
||||
@@ -3,7 +3,7 @@
|
||||
"id": "signage",
|
||||
"name": "Signage",
|
||||
"description": "Visual programming, timelines, synchronized channels, and display delivery for church screens.",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.2",
|
||||
"compatibility": {
|
||||
"platform": "^0.1.0",
|
||||
"moduleSdk": "^0.1.0"
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@ekklesia/signage",
|
||||
"version": "0.1.0",
|
||||
"version": "0.1.2",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Ekklesia's visual programming, timeline, synchronization, and display-delivery module.",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
/**
|
||||
* How long a display waits before trying a failed request again.
|
||||
*
|
||||
* Exponential from one second to a one-minute ceiling, so a screen whose server is restarting is
|
||||
* back within seconds, and one whose server is down for an evening asks once a minute rather than
|
||||
* hammering it. The wait is jittered between half and all of that step, so a building's worth of
|
||||
* screens that lost the server at the same moment do not all come back at the same moment.
|
||||
*
|
||||
* There is no attempt limit. A television on a wall has nobody to press Retry, so giving up is the
|
||||
* one thing it must never do.
|
||||
*/
|
||||
export const DISPLAY_RETRY_BASE_MS = 1_000;
|
||||
export const DISPLAY_RETRY_MAX_MS = 60_000;
|
||||
|
||||
export function displayRetryDelayMs(attempt: number, random: () => number = Math.random): number {
|
||||
const step = Math.min(
|
||||
DISPLAY_RETRY_MAX_MS,
|
||||
DISPLAY_RETRY_BASE_MS * 2 ** Math.min(Math.max(0, attempt), 16),
|
||||
);
|
||||
return Math.round(step / 2 + (step / 2) * Math.min(1, Math.max(0, random())));
|
||||
}
|
||||
+49
-3
@@ -36,6 +36,9 @@ export interface SignageMediaCache {
|
||||
* can never leave a screen with less than it had. */
|
||||
prune(keep: readonly string[]): Promise<void>;
|
||||
count(): Promise<number>;
|
||||
/** Gives back every local URL this cache handed out. Called when a display stops; a URL handed
|
||||
* out before this is no longer valid afterwards. */
|
||||
release(): void;
|
||||
}
|
||||
|
||||
/** The stable key a native image's bytes are cached under. Deliberately built from identity, never
|
||||
@@ -86,6 +89,9 @@ export function createMemoryMediaCache(): SignageMediaCache {
|
||||
}
|
||||
return Promise.resolve();
|
||||
},
|
||||
release(): void {
|
||||
// Holds plain URLs, nothing the browser has to be given back.
|
||||
},
|
||||
store(key: string, url: string): Promise<string | undefined> {
|
||||
stored.set(key, url);
|
||||
return Promise.resolve(url);
|
||||
@@ -179,14 +185,45 @@ export function createBrowserMediaCache(scope: typeof globalThis = globalThis):
|
||||
return `${origin}/${key}`;
|
||||
}
|
||||
|
||||
async function localUrl(cache: Cache, url: string): Promise<string | undefined> {
|
||||
const response = await cache.match(url);
|
||||
/**
|
||||
* The one object URL each cached slide is rendered from, by cache entry.
|
||||
*
|
||||
* An object URL pins its blob in the browser until it is revoked. Every state refresh looks every
|
||||
* cached slide up again, so minting a URL per lookup leaked a blob per slide per refresh, and
|
||||
* within minutes the browser refused the display's own requests for want of resources. So each
|
||||
* entry gets exactly one URL, revoked when the entry is pruned or replaced, and all of them when
|
||||
* the display stops.
|
||||
*/
|
||||
const objectUrls = new Map<string, string>();
|
||||
|
||||
function forget(request: string): void {
|
||||
const url = objectUrls.get(request);
|
||||
if (url !== undefined) {
|
||||
objectUrls.delete(request);
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
}
|
||||
|
||||
async function localUrl(cache: Cache, request: string): Promise<string | undefined> {
|
||||
const existing = objectUrls.get(request);
|
||||
if (existing !== undefined) {
|
||||
return existing;
|
||||
}
|
||||
const response = await cache.match(request);
|
||||
if (!response) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const blob = await response.blob();
|
||||
return URL.createObjectURL(blob);
|
||||
// Two lookups of one slide can be in flight at once; the first to finish wins, and the other
|
||||
// gives its URL straight back rather than leaving it pinned.
|
||||
const raced = objectUrls.get(request);
|
||||
if (raced !== undefined) {
|
||||
return raced;
|
||||
}
|
||||
const url = URL.createObjectURL(blob);
|
||||
objectUrls.set(request, url);
|
||||
return url;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
@@ -220,6 +257,7 @@ export function createBrowserMediaCache(scope: typeof globalThis = globalThis):
|
||||
for (const request of await cache.keys()) {
|
||||
if (!retained.has(request.url)) {
|
||||
await cache.delete(request);
|
||||
forget(request.url);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -227,6 +265,12 @@ export function createBrowserMediaCache(scope: typeof globalThis = globalThis):
|
||||
}
|
||||
},
|
||||
|
||||
release(): void {
|
||||
for (const request of [...objectUrls.keys()]) {
|
||||
forget(request);
|
||||
}
|
||||
},
|
||||
|
||||
async store(key: string, url: string): Promise<string | undefined> {
|
||||
const cache = await open();
|
||||
if (!cache) {
|
||||
@@ -242,6 +286,8 @@ export function createBrowserMediaCache(scope: typeof globalThis = globalThis):
|
||||
// Stored under the *stable* key, so the next refresh's freshly signed URL finds these
|
||||
// bytes instead of downloading them again.
|
||||
await cache.put(cacheRequest(key), response.clone());
|
||||
// New bytes under this key: the URL for the old ones is given back before one is made.
|
||||
forget(cacheRequest(key));
|
||||
return localUrl(cache, cacheRequest(key));
|
||||
} catch {
|
||||
return undefined;
|
||||
|
||||
+146
-70
@@ -1,4 +1,5 @@
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { displayRetryDelayMs } from "../browser/backoff.js";
|
||||
import {
|
||||
type OfflineSnapshot,
|
||||
resolveOffline,
|
||||
@@ -18,6 +19,13 @@ import {
|
||||
type SignageMediaCache,
|
||||
signageMediaKey,
|
||||
} from "../browser/storage.js";
|
||||
import {
|
||||
type DisplayChannelState,
|
||||
type DisplayHeartbeat,
|
||||
type DisplayRealtimeGroup,
|
||||
parseViewerSessionResponse,
|
||||
type ViewerSessionResponse,
|
||||
} from "../shared/display-protocol.js";
|
||||
|
||||
/**
|
||||
* The display: what it fetches, what it shows, and what it reports.
|
||||
@@ -38,36 +46,11 @@ const SNAPSHOT_STORAGE = "last-known-good";
|
||||
* must not sit on a stale frame until the next; and a delivery URL has a finite life. */
|
||||
const REFRESH_INTERVAL_MS = 4 * 60 * 1000;
|
||||
|
||||
export interface DisplayChannelStateView {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: { readonly id: string; readonly key: string; readonly groupId: string };
|
||||
readonly crossfadeMs: number;
|
||||
readonly playback: {
|
||||
readonly revision: number;
|
||||
readonly transport: string;
|
||||
readonly blackout: boolean;
|
||||
readonly remainingMs: number | null;
|
||||
readonly selectionRevision: number | null;
|
||||
readonly currentSelectionId: string | null;
|
||||
readonly currentSlotId: string | null;
|
||||
readonly activeTimelineId: string | null;
|
||||
readonly pendingTimelineId: string | null;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
};
|
||||
readonly timeline: OfflineSnapshot["timeline"];
|
||||
readonly current: SceneSelection | null;
|
||||
readonly staticHold: SceneSelection | null;
|
||||
readonly selections: readonly SceneSelection[];
|
||||
}
|
||||
/** The channel state a display renders, exactly as the server sends it (`src/shared`). */
|
||||
export type DisplayChannelStateView = DisplayChannelState;
|
||||
|
||||
export interface DisplaySessionView {
|
||||
readonly viewerId: string;
|
||||
readonly channelId: string;
|
||||
readonly channelKey: string;
|
||||
readonly groupId: string;
|
||||
readonly heartbeatIntervalMs: number;
|
||||
}
|
||||
/** The display's registration, exactly as the server answers it (`src/shared`). */
|
||||
export type DisplaySessionView = ViewerSessionResponse;
|
||||
|
||||
/** What an operator can see about this screen, and what a test asserts on. Sanitized by
|
||||
* construction: identity, counts, and a code. */
|
||||
@@ -140,6 +123,13 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
let snapshot: OfflineSnapshot | undefined;
|
||||
let offlineActive = false;
|
||||
let offlineHandle: unknown;
|
||||
/** Retries, each on its own backoff. A display has nobody to press Retry, so none of them give up;
|
||||
* each resets once its request works again. */
|
||||
let sessionHandle: unknown;
|
||||
let sessionAttempt = 0;
|
||||
let refreshAttempt = 0;
|
||||
let realtimeHandle: unknown;
|
||||
let realtimeAttempt = 0;
|
||||
/** Selections this display has tried and failed to render. A broken item is skipped rather than
|
||||
* retried in a tight loop, which is what keeps one bad slide from becoming a flicker. */
|
||||
const unusable = new Set<string>();
|
||||
@@ -515,17 +505,119 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
`channels/${session.channelId}/display-state`,
|
||||
);
|
||||
if (!response.ok) {
|
||||
online = false;
|
||||
await runOffline();
|
||||
await refreshFailed();
|
||||
return;
|
||||
}
|
||||
await apply((await response.json()) as DisplayChannelStateView);
|
||||
const state = (await response.json()) as DisplayChannelStateView;
|
||||
refreshAttempt = 0;
|
||||
await apply(state);
|
||||
} catch {
|
||||
// The server is unreachable. The frame stays and local continuation takes over; nothing about
|
||||
// a network failure belongs on a lobby wall.
|
||||
await refreshFailed();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The server is unreachable, or answered with an error. The frame stays and local continuation
|
||||
* takes over — nothing about a network failure belongs on a lobby wall — and the refresh is tried
|
||||
* again on its own, because a realtime message that would otherwise prompt it may never come.
|
||||
*/
|
||||
async function refreshFailed(): Promise<void> {
|
||||
online = false;
|
||||
await runOffline();
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (refreshHandle !== undefined) {
|
||||
clearTimer(refreshHandle);
|
||||
}
|
||||
refreshHandle = setTimer(() => {
|
||||
refreshHandle = undefined;
|
||||
void refresh();
|
||||
}, displayRetryDelayMs(refreshAttempt));
|
||||
refreshAttempt += 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers this display, and keeps trying until it can.
|
||||
*
|
||||
* Until it has registered, a display continues from its own persisted state, honestly marked as
|
||||
* offline. The first registration that works brings it live — realtime, heartbeats, and fresh
|
||||
* state — exactly as if it had worked the first time.
|
||||
*/
|
||||
async function register(): Promise<void> {
|
||||
if (stopped || session) {
|
||||
return;
|
||||
}
|
||||
let registered: DisplaySessionView | undefined;
|
||||
try {
|
||||
const response = await options.context.api.request("viewers/session", {
|
||||
body: JSON.stringify({ viewerKey: await viewerKey() }),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
if (response.ok) {
|
||||
// Read, not cast: a registration the display cannot understand is no registration, and is
|
||||
// tried again like any other failure.
|
||||
const parsed = parseViewerSessionResponse(await response.json());
|
||||
registered = parsed.ok ? parsed.value : undefined;
|
||||
}
|
||||
} catch {
|
||||
registered = undefined;
|
||||
}
|
||||
if (stopped) {
|
||||
return;
|
||||
}
|
||||
if (!registered) {
|
||||
online = false;
|
||||
report();
|
||||
sessionHandle = setTimer(() => {
|
||||
sessionHandle = undefined;
|
||||
void register();
|
||||
}, displayRetryDelayMs(sessionAttempt));
|
||||
sessionAttempt += 1;
|
||||
return;
|
||||
}
|
||||
sessionAttempt = 0;
|
||||
session = registered;
|
||||
online = true;
|
||||
subscribe();
|
||||
heartbeatHandle = setInterval(
|
||||
() => void heartbeat(),
|
||||
registered.heartbeatIntervalMs,
|
||||
) as unknown;
|
||||
await refresh();
|
||||
void heartbeat();
|
||||
report();
|
||||
}
|
||||
|
||||
/**
|
||||
* Subscribes to the display's realtime channel, and again whenever the host reports that a
|
||||
* subscription has ended for good. The host retries ordinary disconnects itself; a stream that
|
||||
* is refused outright ends, and until this resubscribes the display would only learn of changes
|
||||
* at its next slot deadline.
|
||||
*/
|
||||
function subscribe(): void {
|
||||
if (stopped || !session) {
|
||||
return;
|
||||
}
|
||||
subscription?.close();
|
||||
subscription = options.context.realtime.subscribe("display-state", {
|
||||
onSnapshot: (state) => onRealtime(state),
|
||||
onStatus: (status) => {
|
||||
online = status === "connected";
|
||||
if (status === "connected") {
|
||||
realtimeAttempt = 0;
|
||||
} else if (status === "closed" && !stopped && realtimeHandle === undefined) {
|
||||
realtimeHandle = setTimer(() => {
|
||||
realtimeHandle = undefined;
|
||||
subscribe();
|
||||
}, displayRetryDelayMs(realtimeAttempt));
|
||||
realtimeAttempt += 1;
|
||||
}
|
||||
report();
|
||||
},
|
||||
onUpdate: (state) => onRealtime(state),
|
||||
});
|
||||
}
|
||||
|
||||
async function heartbeat(): Promise<void> {
|
||||
@@ -533,11 +625,10 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await options.context.api.request(`viewers/${session.viewerId}/heartbeat`, {
|
||||
body: JSON.stringify({
|
||||
// Built as the shared message type, which is the same type the route parses with.
|
||||
const report: DisplayHeartbeat = {
|
||||
cachedAssetCount,
|
||||
error:
|
||||
lastError === undefined ? null : { code: lastError.code, detail: lastError.detail },
|
||||
error: lastError === undefined ? null : { code: lastError.code, detail: lastError.detail },
|
||||
offlineReady: snapshot !== undefined && snapshot.selections.length > 0,
|
||||
reportedContributionId:
|
||||
lastState?.current?.renderer.kind === "contribution"
|
||||
@@ -547,7 +638,9 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
reportedProviderId: lastState?.current?.providerId ?? null,
|
||||
reportedSelectionId: renderedSelectionId ?? null,
|
||||
reportedTimelineId: lastState?.playback.activeTimelineId ?? null,
|
||||
}),
|
||||
};
|
||||
await options.context.api.request(`viewers/${session.viewerId}/heartbeat`, {
|
||||
body: JSON.stringify(report),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
@@ -595,36 +688,7 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
}
|
||||
|
||||
if (telemetry) {
|
||||
try {
|
||||
const response = await options.context.api.request("viewers/session", {
|
||||
body: JSON.stringify({ viewerKey: await viewerKey() }),
|
||||
headers: { "content-type": "application/json" },
|
||||
method: "POST",
|
||||
});
|
||||
if (response.ok) {
|
||||
session = (await response.json()) as DisplaySessionView;
|
||||
online = true;
|
||||
}
|
||||
} catch {
|
||||
online = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (session) {
|
||||
subscription = options.context.realtime.subscribe("display-state", {
|
||||
onSnapshot: (state) => onRealtime(state),
|
||||
onStatus: (status) => {
|
||||
online = status === "connected";
|
||||
report();
|
||||
},
|
||||
onUpdate: (state) => onRealtime(state),
|
||||
});
|
||||
heartbeatHandle = setInterval(
|
||||
() => void heartbeat(),
|
||||
session.heartbeatIntervalMs,
|
||||
) as unknown;
|
||||
await refresh();
|
||||
void heartbeat();
|
||||
await register();
|
||||
}
|
||||
report();
|
||||
},
|
||||
@@ -641,9 +705,18 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
clearTimer(refreshHandle);
|
||||
refreshHandle = undefined;
|
||||
}
|
||||
for (const handle of [sessionHandle, realtimeHandle]) {
|
||||
if (handle !== undefined) {
|
||||
clearTimer(handle);
|
||||
}
|
||||
}
|
||||
sessionHandle = undefined;
|
||||
realtimeHandle = undefined;
|
||||
exitOffline();
|
||||
await stage?.destroy();
|
||||
stage = undefined;
|
||||
// After the stage is gone, so nothing on screen still points at a released URL.
|
||||
media.release();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -656,7 +729,10 @@ export function createDisplayController(options: DisplayControllerOptions): Disp
|
||||
if (stopped || !session) {
|
||||
return;
|
||||
}
|
||||
const groups = (payload as { groups?: readonly Record<string, unknown>[] } | null)?.groups;
|
||||
// Checked at run time as well as typed: realtime state is the platform's transport, and a frame
|
||||
// this display cannot read is simply not one it acts on.
|
||||
const groups = (payload as { groups?: readonly Partial<DisplayRealtimeGroup>[] } | null)
|
||||
?.groups;
|
||||
if (!Array.isArray(groups)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -59,7 +59,7 @@ function SignageDisplay({ context }: { readonly context: ModuleUiHostContext }):
|
||||
*/
|
||||
export default defineModuleUi({
|
||||
id: "signage",
|
||||
version: "0.1.0",
|
||||
version: "0.1.2",
|
||||
styles: displayStyles,
|
||||
mount(container, context) {
|
||||
const root = createRoot(container);
|
||||
|
||||
+18
-70
@@ -1,4 +1,9 @@
|
||||
import type { ModuleStorage } from "@ekklesia/module-sdk";
|
||||
import type {
|
||||
DisplayChannelState as DisplayChannelStateWire,
|
||||
DisplaySelection,
|
||||
DisplayTimeline,
|
||||
} from "../../shared/display-protocol.js";
|
||||
import {
|
||||
resolveNativeScene,
|
||||
SIGNAGE_NATIVE_PROVIDER_ID,
|
||||
@@ -35,78 +40,21 @@ import type {
|
||||
* and a display refreshes state long before one lapses.
|
||||
*/
|
||||
|
||||
export interface DisplayMedia {
|
||||
readonly url: string;
|
||||
readonly expiresAtMs: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
export type {
|
||||
DisplayMedia,
|
||||
DisplaySelection,
|
||||
DisplayTimeline,
|
||||
DisplayTimelineSlot,
|
||||
} from "../../shared/display-protocol.js";
|
||||
|
||||
export interface DisplaySelection {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly slotId: string | null;
|
||||
readonly providerId: string;
|
||||
readonly itemId: string;
|
||||
readonly itemRevision: string;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
readonly durationMs: number;
|
||||
readonly availableUntilMs: number | null;
|
||||
readonly withdrawn: boolean;
|
||||
readonly stale: boolean;
|
||||
/** `native-image` is drawn by Signage's own display code; `contribution` is mounted through the
|
||||
* platform's contribution ABI by id. A display never receives a URL for either. */
|
||||
readonly renderer:
|
||||
| { readonly kind: "native-image" }
|
||||
| {
|
||||
readonly kind: "contribution";
|
||||
readonly contributionId: string;
|
||||
readonly contributionVersion: string;
|
||||
}
|
||||
| { readonly kind: "unavailable" };
|
||||
/** The provider's own payload for this channel's audience, or its default. */
|
||||
readonly payload: unknown;
|
||||
readonly presentation: unknown;
|
||||
/** Native images only: fresh delivery URLs, and the already-resolved scene. */
|
||||
readonly media?: { readonly display: DisplayMedia; readonly thumbnail: DisplayMedia };
|
||||
readonly scene?: ReturnType<typeof resolveNativeScene>;
|
||||
}
|
||||
|
||||
export interface DisplayTimelineSlot {
|
||||
readonly id: string;
|
||||
readonly position: number;
|
||||
readonly enabled: boolean;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly estimatedDurationMs: number;
|
||||
}
|
||||
|
||||
export interface DisplayTimeline {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly slots: readonly DisplayTimelineSlot[];
|
||||
}
|
||||
|
||||
export interface DisplayChannelState {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly name: string;
|
||||
readonly groupId: string;
|
||||
};
|
||||
readonly crossfadeMs: number;
|
||||
/**
|
||||
* The channel state the server builds: the wire shape a display reads (`src/shared`), plus the
|
||||
* channel's name and the group's whole playback snapshot. Declared as an extension so that a field
|
||||
* the display relies on cannot be renamed or retyped here without failing to compile.
|
||||
*/
|
||||
export interface DisplayChannelState extends DisplayChannelStateWire {
|
||||
readonly channel: DisplayChannelStateWire["channel"] & { readonly name: string };
|
||||
readonly playback: PlaybackSnapshot;
|
||||
readonly timeline: DisplayTimeline | null;
|
||||
readonly current: DisplaySelection | null;
|
||||
/** The held image, already resolved as a scene. Separate from `current` because a static hold sits
|
||||
* *over* a preserved cursor rather than replacing it. */
|
||||
readonly staticHold: DisplaySelection | null;
|
||||
/** Bounded, newest first. Material for offline continuation, never a substitute for authority. */
|
||||
readonly selections: readonly DisplaySelection[];
|
||||
}
|
||||
|
||||
/** How many resolved selections travel to a display. Enough to cover a pattern and then some, small
|
||||
|
||||
@@ -91,11 +91,20 @@ export function registerPlaybackRoutes(
|
||||
const groupId = requireUuidParam(context, "groupId");
|
||||
const store = createSignageStore(context.services.database);
|
||||
const groups = await store.listChannelGroups();
|
||||
const group = groups.find((candidate) => candidate.group.id === groupId);
|
||||
if (!group) {
|
||||
throw new SignageError("SIGNAGE_NOT_FOUND");
|
||||
}
|
||||
if (groups.length <= 1) {
|
||||
// An installation always has somewhere for a viewer to land.
|
||||
throw new SignageError("SIGNAGE_CONFLICT", { reason: "last-group" });
|
||||
}
|
||||
await store.deleteChannelGroup(groupId);
|
||||
const fallbackGroup = groups.find((candidate) => candidate.group.id !== groupId);
|
||||
const fallbackChannel = fallbackGroup?.channels.find((channel) => channel.isDefault);
|
||||
if (!fallbackChannel) {
|
||||
throw new SignageError("SIGNAGE_CONFLICT", { reason: "no-fallback-channel" });
|
||||
}
|
||||
await store.deleteChannelGroup(groupId, fallbackChannel.id);
|
||||
return new Response(null, { status: 204 });
|
||||
});
|
||||
},
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import type { ModuleHttpRouteRegistrar, ModuleRouteHandlerContext } from "@ekklesia/module-sdk";
|
||||
import {
|
||||
type DisplayHeartbeatResponse,
|
||||
type ProtocolResult,
|
||||
parseDisplayHeartbeat,
|
||||
parseViewerSessionRequest,
|
||||
type ViewerSessionResponse,
|
||||
} from "../../shared/display-protocol.js";
|
||||
import { buildDisplayChannelState } from "../display/state.js";
|
||||
import { SignageError, signageBoundary } from "../errors.js";
|
||||
import {
|
||||
optionalBoolean,
|
||||
optionalInteger,
|
||||
optionalString,
|
||||
readJsonObject,
|
||||
requireUuidParam,
|
||||
} from "../http.js";
|
||||
import { optionalString, readJsonObject, requireUuidParam } from "../http.js";
|
||||
import type { SignagePlaybackService } from "../playback/service.js";
|
||||
import type { SignageProviderRegistry } from "../providers/registry.js";
|
||||
import { readSignageSettings } from "../settings.js";
|
||||
@@ -21,11 +22,23 @@ import {
|
||||
updateViewerAssignment,
|
||||
} from "../viewers/service.js";
|
||||
|
||||
const OPAQUE_ID = /^[\w][\w.:-]{0,199}$/u;
|
||||
/** How a route reaches Signage's tables. Production uses the module database; the display contract
|
||||
* test supplies the in-memory store so the real handlers can answer the real display controller. */
|
||||
/** How often a display checks in. Sent to the display rather than built into it, so the server can
|
||||
* change its own expectations without a display deployment. */
|
||||
export const SIGNAGE_HEARTBEAT_INTERVAL_MS = 12_000;
|
||||
|
||||
function store(context: ModuleRouteHandlerContext): SignageStore {
|
||||
return createSignageStore(context.services.database);
|
||||
/** A display message the shared protocol refused, as Signage's own sanitized code naming the field. */
|
||||
function accepted<Value>(result: ProtocolResult<Value>): Value {
|
||||
if (!result.ok) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: result.field });
|
||||
}
|
||||
return result.value;
|
||||
}
|
||||
|
||||
export type ViewerRouteStore = (context: ModuleRouteHandlerContext) => SignageStore;
|
||||
|
||||
const databaseStore: ViewerRouteStore = (context) => createSignageStore(context.services.database);
|
||||
|
||||
/**
|
||||
* The safe Core device identifier, when the caller is a paired display.
|
||||
@@ -57,6 +70,7 @@ export function registerViewerRoutes(
|
||||
http: ModuleHttpRouteRegistrar,
|
||||
playback: () => SignagePlaybackService,
|
||||
registry: () => SignageProviderRegistry,
|
||||
store: ViewerRouteStore = databaseStore,
|
||||
): void {
|
||||
http.route({
|
||||
method: "POST",
|
||||
@@ -65,11 +79,7 @@ export function registerViewerRoutes(
|
||||
maxBodyBytes: 2048,
|
||||
handler(request, context) {
|
||||
return signageBoundary(async () => {
|
||||
const body = await readJsonObject(request);
|
||||
const viewerKey = body.viewerKey;
|
||||
if (typeof viewerKey !== "string") {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "viewerKey" });
|
||||
}
|
||||
const { viewerKey } = accepted(parseViewerSessionRequest(await readJsonObject(request)));
|
||||
// A display registers with the identity it keeps in its own IndexedDB and lands on the
|
||||
// default channel. It never chooses one: a public screen that could would let anyone who
|
||||
// reaches the page decide what a wall shows (ADR 0004).
|
||||
@@ -79,14 +89,15 @@ export function registerViewerRoutes(
|
||||
store: store(context),
|
||||
viewerKey,
|
||||
});
|
||||
return Response.json({
|
||||
const response: ViewerSessionResponse = {
|
||||
channelId: session.channel.id,
|
||||
channelKey: session.channel.key,
|
||||
groupId: session.groupId,
|
||||
heartbeatIntervalMs: 12_000,
|
||||
heartbeatIntervalMs: SIGNAGE_HEARTBEAT_INTERVAL_MS,
|
||||
viewerId: session.viewer.id,
|
||||
viewerName: session.viewer.name,
|
||||
});
|
||||
};
|
||||
return Response.json(response);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -99,52 +110,21 @@ export function registerViewerRoutes(
|
||||
handler(request, context) {
|
||||
return signageBoundary(async () => {
|
||||
const viewerId = requireUuidParam(context, "viewerId");
|
||||
const body = await readJsonObject(request);
|
||||
const heartbeat = accepted(parseDisplayHeartbeat(await readJsonObject(request)));
|
||||
const settings = readSignageSettings(context.config);
|
||||
const rawError = body.error;
|
||||
// Telemetry only. Nothing a display reports here changes authoritative playback, and a
|
||||
// local cursor is never accepted as truth.
|
||||
const result = await recordViewerHeartbeat({
|
||||
at: new Date(),
|
||||
heartbeat: {
|
||||
cachedAssetCount:
|
||||
optionalInteger(body, "cachedAssetCount", {
|
||||
maximum: 100_000,
|
||||
minimum: 0,
|
||||
}) ?? undefined,
|
||||
offlineReady: optionalBoolean(body, "offlineReady") ?? undefined,
|
||||
reportedContributionId:
|
||||
optionalString(body, "reportedContributionId", { maxLength: 200 }) ?? null,
|
||||
reportedPlaybackRevision:
|
||||
optionalInteger(body, "reportedPlaybackRevision", {
|
||||
maximum: Number.MAX_SAFE_INTEGER,
|
||||
minimum: 0,
|
||||
}) ?? null,
|
||||
reportedProviderId:
|
||||
optionalString(body, "reportedProviderId", { maxLength: 200 }) ?? null,
|
||||
reportedSelectionId:
|
||||
optionalString(body, "reportedSelectionId", { maxLength: 64 }) ?? null,
|
||||
reportedTimelineId:
|
||||
optionalString(body, "reportedTimelineId", { maxLength: 64 }) ?? null,
|
||||
...(rawError === undefined
|
||||
? {}
|
||||
: {
|
||||
error:
|
||||
rawError === null
|
||||
? null
|
||||
: {
|
||||
code: readErrorCode(rawError),
|
||||
detail: readErrorDetail(rawError),
|
||||
},
|
||||
}),
|
||||
},
|
||||
heartbeat,
|
||||
minimumWriteIntervalMs: settings.viewerHeartbeatWriteMs,
|
||||
store: store(context),
|
||||
viewerId,
|
||||
});
|
||||
// The response says what a display needs to keep itself honest, and nothing about other
|
||||
// displays or the installation.
|
||||
return Response.json({ acknowledged: true, recorded: result.written });
|
||||
const response: DisplayHeartbeatResponse = { acknowledged: true, recorded: result.written };
|
||||
return Response.json(response);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -235,25 +215,3 @@ export function registerViewerRoutes(
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function readErrorCode(value: unknown): string {
|
||||
if (typeof value !== "object" || value === null) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error" });
|
||||
}
|
||||
const code = (value as { code?: unknown }).code;
|
||||
if (typeof code !== "string" || !OPAQUE_ID.test(code)) {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error.code" });
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
function readErrorDetail(value: unknown): string | null {
|
||||
const detail = (value as { detail?: unknown }).detail;
|
||||
if (detail === undefined || detail === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof detail !== "string") {
|
||||
throw new SignageError("SIGNAGE_INVALID_REQUEST", { field: "error.detail" });
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
type ModuleRuntimeContext,
|
||||
type ModuleRuntimeDefinition,
|
||||
} from "@ekklesia/module-sdk";
|
||||
import type { DisplayRealtimePayload } from "../shared/display-protocol.js";
|
||||
import { SIGNAGE_SLIDE_RENDERER_INPUT_VERSION } from "../shared/renderer-input.js";
|
||||
import {
|
||||
SIGNAGE_IMAGE_MAX_BYTES,
|
||||
@@ -98,10 +99,10 @@ export function createSignageModuleRuntime(
|
||||
left.groupId.localeCompare(right.groupId),
|
||||
);
|
||||
try {
|
||||
context.realtime.publish(SIGNAGE_DISPLAY_CHANNEL, {
|
||||
groups,
|
||||
serverNowMs: now().getTime(),
|
||||
});
|
||||
// The shape the display reads (`src/shared/display-protocol.ts`): each group's whole snapshot
|
||||
// carries the revisions it compares.
|
||||
const display: DisplayRealtimePayload = { groups, serverNowMs: now().getTime() };
|
||||
context.realtime.publish(SIGNAGE_DISPLAY_CHANNEL, display);
|
||||
context.realtime.publish(SIGNAGE_MANAGEMENT_CHANNEL, {
|
||||
// Revisions only. The dashboard refetches what changed over authorized HTTP.
|
||||
groups: groups.map((snapshot) => ({
|
||||
@@ -126,7 +127,7 @@ export function createSignageModuleRuntime(
|
||||
|
||||
const definition = defineModuleRuntime({
|
||||
id: "signage",
|
||||
version: "0.1.0",
|
||||
version: "0.1.2",
|
||||
|
||||
register({ capabilities, config, http, realtime }) {
|
||||
const settings = readSignageSettings(config);
|
||||
@@ -188,7 +189,7 @@ export function createSignageModuleRuntime(
|
||||
// server enforces — a UI believing a stale limit would offer an upload the server refuses.
|
||||
return Response.json({
|
||||
crossfadeMs: current.crossfadeMs,
|
||||
moduleVersion: "0.1.0",
|
||||
moduleVersion: "0.1.2",
|
||||
nativeImageDurationMs: current.nativeImageDurationMs,
|
||||
nativePresentation: current.nativePresentation,
|
||||
rendererInputVersion: SIGNAGE_SLIDE_RENDERER_INPUT_VERSION,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
playbackStates,
|
||||
selections,
|
||||
selectionVariants,
|
||||
viewers,
|
||||
} from "../../schema/tables.js";
|
||||
import {
|
||||
type NewStoredSelection,
|
||||
@@ -176,8 +177,21 @@ export function createPlaybackStore(database: ModuleDatabase): SignagePlaybackSt
|
||||
});
|
||||
},
|
||||
|
||||
async deleteChannelGroup(groupId: string): Promise<void> {
|
||||
await database.delete(channelGroups).where(eq(channelGroups.id, groupId));
|
||||
async deleteChannelGroup(groupId: string, fallbackChannelId: string): Promise<void> {
|
||||
await database.transaction(async (transaction) => {
|
||||
const removedChannels = await transaction
|
||||
.select({ id: channels.id })
|
||||
.from(channels)
|
||||
.where(eq(channels.groupId, groupId));
|
||||
const removedChannelIds = removedChannels.map((channel) => channel.id);
|
||||
if (removedChannelIds.length > 0) {
|
||||
await transaction
|
||||
.update(viewers)
|
||||
.set({ channelId: fallbackChannelId, updatedAt: new Date() })
|
||||
.where(inArray(viewers.channelId, removedChannelIds));
|
||||
}
|
||||
await transaction.delete(channelGroups).where(eq(channelGroups.id, groupId));
|
||||
});
|
||||
},
|
||||
|
||||
async findChannelGroup(groupId: string): Promise<StoredChannelGroupDetail | undefined> {
|
||||
|
||||
@@ -112,20 +112,21 @@ export function createTimelineStore(database: ModuleDatabase): SignageTimelineSt
|
||||
/**
|
||||
* Rewrites `position` for one timeline from an explicit order.
|
||||
*
|
||||
* Positions are written in two passes, through a temporary negative range, because the unique
|
||||
* Positions are written in two passes, through a temporary high range, because the unique
|
||||
* `(timeline_id, position)` index is checked per statement: moving a slot from 3 to 1 while
|
||||
* another still holds 1 would collide. Negative positions are outside every real value, so the
|
||||
* intermediate state cannot be mistaken for an order.
|
||||
* another still holds 1 would collide. Temporary positions sit beyond the final order while
|
||||
* remaining inside the database's non-negative constraint.
|
||||
*/
|
||||
async function renumber(
|
||||
transaction: ModuleDatabase,
|
||||
timelineId: string,
|
||||
orderedSlotIds: readonly string[],
|
||||
): Promise<void> {
|
||||
const temporaryOffset = orderedSlotIds.length + 1;
|
||||
for (const [index, slotId] of orderedSlotIds.entries()) {
|
||||
await transaction
|
||||
.update(timelineSlots)
|
||||
.set({ position: -1 - index })
|
||||
.set({ position: temporaryOffset + index })
|
||||
.where(eq(timelineSlots.id, slotId));
|
||||
}
|
||||
for (const [index, slotId] of orderedSlotIds.entries()) {
|
||||
@@ -175,7 +176,7 @@ export function createTimelineStore(database: ModuleDatabase): SignageTimelineSt
|
||||
position === undefined
|
||||
? existing.length
|
||||
: Math.max(0, Math.min(position, existing.length));
|
||||
await transaction.insert(timelineSlots).values(slotValues(slot, -1_000_000));
|
||||
await transaction.insert(timelineSlots).values(slotValues(slot, existing.length + 1));
|
||||
const next = [...existing.slice(0, index), slot.id, ...existing.slice(index)];
|
||||
await renumber(transaction, slot.timelineId, next);
|
||||
});
|
||||
|
||||
@@ -351,7 +351,9 @@ export interface SignagePlaybackStore {
|
||||
readonly channelId: string;
|
||||
readonly channelName: string;
|
||||
}): Promise<void>;
|
||||
deleteChannelGroup(groupId: string): Promise<void>;
|
||||
/** Deletes a group and moves every assigned viewer to the supplied fallback channel atomically,
|
||||
* so removing a group can never leave a display unassigned. */
|
||||
deleteChannelGroup(groupId: string, fallbackChannelId: string): Promise<void>;
|
||||
addChannel(channel: StoredChannel): Promise<void>;
|
||||
/** Refuses to remove a group's default channel: something must remain for a viewer to join. */
|
||||
removeChannel(channelId: string): Promise<void>;
|
||||
|
||||
@@ -0,0 +1,318 @@
|
||||
/**
|
||||
* What a display and Signage's server say to each other, defined once.
|
||||
*
|
||||
* The display controller builds these messages and the viewer routes read them, from this one file.
|
||||
* They used to be described twice — once in the controller's own interfaces and once in each
|
||||
* route's field-by-field parsing — and the two descriptions disagreed about one thing: the display
|
||||
* sent `null` for "nothing to report" and the heartbeat route accepted only a *missing* field. Every
|
||||
* heartbeat from a screen showing a native image was refused with a 400, silently, for as long as it
|
||||
* ran. Nothing here can drift that way again, because there is nothing to drift between.
|
||||
*
|
||||
* Three rules hold for every message:
|
||||
*
|
||||
* - **A nullable field accepts `null` explicitly.** `null` means "I have nothing", and is a value.
|
||||
* - **An absent field means "not reported".** A receiver keeps whatever it already had.
|
||||
* - **An unknown field is ignored, never refused.** A newer display reporting something an older
|
||||
* server does not know yet must still be heard; refusing it would be this same bug in reverse.
|
||||
*
|
||||
* Like the rest of `src/shared`, it imports nothing from outside `src/shared`: it is compiled into the browser
|
||||
* artifact as well as the server, and must pull neither the module SDK nor Node into a display.
|
||||
*/
|
||||
|
||||
import type { SignageNativeScene } from "./native-images.js";
|
||||
|
||||
// --- Parsing ---------------------------------------------------------------------------------------
|
||||
|
||||
/** The outcome of reading one message: the value, or the one field that was wrong. Never a parser's
|
||||
* own message, which is not something a client or an operator should see. */
|
||||
export type ProtocolResult<Value> =
|
||||
| { readonly ok: true; readonly value: Value }
|
||||
| { readonly ok: false; readonly field: string };
|
||||
|
||||
type Reader<Value> = (raw: unknown) => { readonly ok: true; readonly value: Value } | undefined;
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function text(options: { readonly maxLength: number; readonly pattern?: RegExp }): Reader<string> {
|
||||
return (raw) => {
|
||||
if (typeof raw !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const value = raw.trim();
|
||||
if (value.length === 0 || value.length > options.maxLength) {
|
||||
return undefined;
|
||||
}
|
||||
if (options.pattern && !options.pattern.test(value)) {
|
||||
return undefined;
|
||||
}
|
||||
return { ok: true, value };
|
||||
};
|
||||
}
|
||||
|
||||
function integer(options: { readonly minimum: number; readonly maximum: number }): Reader<number> {
|
||||
return (raw) =>
|
||||
typeof raw === "number" &&
|
||||
Number.isSafeInteger(raw) &&
|
||||
raw >= options.minimum &&
|
||||
raw <= options.maximum
|
||||
? { ok: true, value: raw }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
const flag: Reader<boolean> = (raw) =>
|
||||
typeof raw === "boolean" ? { ok: true, value: raw } : undefined;
|
||||
|
||||
function nullable<Value>(read: Reader<Value>): Reader<Value | null> {
|
||||
return (raw) => (raw === null ? { ok: true, value: null } : read(raw));
|
||||
}
|
||||
|
||||
/** Reads the named fields of a message. Absent fields are left out of the result; any other field
|
||||
* of the object is ignored. */
|
||||
function readFields<Shape extends object>(
|
||||
raw: unknown,
|
||||
readers: { readonly [Key in keyof Shape]-?: Reader<Exclude<Shape[Key], undefined>> },
|
||||
): ProtocolResult<Shape> {
|
||||
if (!isRecord(raw)) {
|
||||
return { field: "body", ok: false };
|
||||
}
|
||||
const value: Record<string, unknown> = {};
|
||||
for (const key of Object.keys(readers) as (keyof Shape & string)[]) {
|
||||
if (raw[key] === undefined) {
|
||||
continue;
|
||||
}
|
||||
const read = readers[key](raw[key]);
|
||||
if (!read) {
|
||||
return { field: key, ok: false };
|
||||
}
|
||||
value[key] = read.value;
|
||||
}
|
||||
return { ok: true, value: value as Shape };
|
||||
}
|
||||
|
||||
function requireFields<Shape>(
|
||||
result: ProtocolResult<Partial<Shape>>,
|
||||
required: readonly (keyof Shape & string)[],
|
||||
): ProtocolResult<Shape> {
|
||||
if (!result.ok) {
|
||||
return result;
|
||||
}
|
||||
for (const key of required) {
|
||||
if (result.value[key] === undefined) {
|
||||
return { field: key, ok: false };
|
||||
}
|
||||
}
|
||||
return result as ProtocolResult<Shape>;
|
||||
}
|
||||
|
||||
// --- Limits ----------------------------------------------------------------------------------------
|
||||
|
||||
/** A display's own identity, kept in its IndexedDB. */
|
||||
export const DISPLAY_VIEWER_KEY = /^[\w-]{8,128}$/u;
|
||||
/** The longest error detail a display may report. Operator-facing text a browser supplied, so it is
|
||||
* bounded, and because an unbounded one is a way to fill a table. */
|
||||
export const DISPLAY_ERROR_DETAIL_MAX = 200;
|
||||
export const DISPLAY_ERROR_CODE = /^[\w][\w.:-]{0,63}$/u;
|
||||
export const DISPLAY_CACHED_ASSET_MAX = 100_000;
|
||||
|
||||
// --- Viewer session: POST viewers/session ----------------------------------------------------------
|
||||
|
||||
export interface ViewerSessionRequest {
|
||||
readonly viewerKey: string;
|
||||
}
|
||||
|
||||
export interface ViewerSessionResponse {
|
||||
readonly viewerId: string;
|
||||
readonly viewerName: string;
|
||||
readonly channelId: string;
|
||||
readonly channelKey: string;
|
||||
readonly groupId: string;
|
||||
readonly heartbeatIntervalMs: number;
|
||||
}
|
||||
|
||||
const identifier = text({ maxLength: 200 });
|
||||
|
||||
export function parseViewerSessionRequest(raw: unknown): ProtocolResult<ViewerSessionRequest> {
|
||||
return requireFields<ViewerSessionRequest>(
|
||||
readFields<Partial<ViewerSessionRequest>>(raw, {
|
||||
viewerKey: text({ maxLength: 128, pattern: DISPLAY_VIEWER_KEY }),
|
||||
}),
|
||||
["viewerKey"],
|
||||
);
|
||||
}
|
||||
|
||||
export function parseViewerSessionResponse(raw: unknown): ProtocolResult<ViewerSessionResponse> {
|
||||
return requireFields<ViewerSessionResponse>(
|
||||
readFields<Partial<ViewerSessionResponse>>(raw, {
|
||||
channelId: identifier,
|
||||
channelKey: identifier,
|
||||
groupId: identifier,
|
||||
heartbeatIntervalMs: integer({ maximum: 600_000, minimum: 1_000 }),
|
||||
viewerId: identifier,
|
||||
viewerName: text({ maxLength: 200 }),
|
||||
}),
|
||||
["viewerId", "viewerName", "channelId", "channelKey", "groupId", "heartbeatIntervalMs"],
|
||||
);
|
||||
}
|
||||
|
||||
// --- Heartbeat: POST viewers/:viewerId/heartbeat ---------------------------------------------------
|
||||
|
||||
export interface DisplayReportedError {
|
||||
readonly code: string;
|
||||
readonly detail: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a display reports about itself. Telemetry, never authority: nothing here changes playback.
|
||||
*
|
||||
* Every field is optional on the wire (absent = not reported). The display sends all of them.
|
||||
*/
|
||||
export interface DisplayHeartbeat {
|
||||
readonly cachedAssetCount?: number;
|
||||
readonly offlineReady?: boolean;
|
||||
readonly reportedTimelineId?: string | null;
|
||||
readonly reportedSelectionId?: string | null;
|
||||
readonly reportedProviderId?: string | null;
|
||||
readonly reportedContributionId?: string | null;
|
||||
readonly reportedPlaybackRevision?: number | null;
|
||||
readonly error?: DisplayReportedError | null;
|
||||
}
|
||||
|
||||
const reportedError: Reader<DisplayReportedError> = (raw) => {
|
||||
const read = readFields<{ code?: string; detail?: string | null }>(raw, {
|
||||
code: text({ maxLength: 64, pattern: DISPLAY_ERROR_CODE }),
|
||||
detail: nullable(text({ maxLength: DISPLAY_ERROR_DETAIL_MAX })),
|
||||
});
|
||||
if (!read.ok || read.value.code === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return { ok: true, value: { code: read.value.code, detail: read.value.detail ?? null } };
|
||||
};
|
||||
|
||||
export function parseDisplayHeartbeat(raw: unknown): ProtocolResult<DisplayHeartbeat> {
|
||||
return readFields<DisplayHeartbeat>(raw, {
|
||||
cachedAssetCount: integer({ maximum: DISPLAY_CACHED_ASSET_MAX, minimum: 0 }),
|
||||
error: nullable(reportedError),
|
||||
offlineReady: flag,
|
||||
reportedContributionId: nullable(text({ maxLength: 200 })),
|
||||
reportedPlaybackRevision: nullable(integer({ maximum: Number.MAX_SAFE_INTEGER, minimum: 0 })),
|
||||
reportedProviderId: nullable(text({ maxLength: 200 })),
|
||||
reportedSelectionId: nullable(text({ maxLength: 64 })),
|
||||
reportedTimelineId: nullable(text({ maxLength: 64 })),
|
||||
});
|
||||
}
|
||||
|
||||
export interface DisplayHeartbeatResponse {
|
||||
readonly acknowledged: true;
|
||||
readonly recorded: boolean;
|
||||
}
|
||||
|
||||
// --- Channel state: GET channels/:channelId/display-state -----------------------------------------
|
||||
|
||||
/** A fresh, signed delivery URL. A bearer capability with an expiry: never persisted by a display. */
|
||||
export interface DisplayMedia {
|
||||
readonly url: string;
|
||||
readonly expiresAtMs: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
}
|
||||
|
||||
export type DisplayRenderer =
|
||||
| { readonly kind: "native-image" }
|
||||
| {
|
||||
readonly kind: "contribution";
|
||||
readonly contributionId: string;
|
||||
readonly contributionVersion: string;
|
||||
}
|
||||
| { readonly kind: "unavailable" };
|
||||
|
||||
export interface DisplaySelection {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly slotId: string | null;
|
||||
readonly providerId: string;
|
||||
readonly itemId: string;
|
||||
readonly itemRevision: string;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
readonly durationMs: number;
|
||||
readonly availableUntilMs: number | null;
|
||||
readonly withdrawn: boolean;
|
||||
readonly stale: boolean;
|
||||
/** `native-image` is drawn by Signage's own display code; `contribution` is mounted through the
|
||||
* platform's contribution ABI by id. A display never receives a URL for either. */
|
||||
readonly renderer: DisplayRenderer;
|
||||
/** The provider's own payload for this channel's audience, or its default. */
|
||||
readonly payload: unknown;
|
||||
readonly presentation: unknown;
|
||||
/** Native images only: fresh delivery URLs, and the already-resolved scene. */
|
||||
readonly media?: { readonly display: DisplayMedia; readonly thumbnail: DisplayMedia };
|
||||
readonly scene?: SignageNativeScene;
|
||||
}
|
||||
|
||||
export interface DisplayTimelineSlot {
|
||||
readonly id: string;
|
||||
readonly position: number;
|
||||
readonly enabled: boolean;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly estimatedDurationMs: number;
|
||||
}
|
||||
|
||||
export interface DisplayTimeline {
|
||||
readonly id: string;
|
||||
readonly revision: number;
|
||||
readonly eligibleFromMs: number | null;
|
||||
readonly eligibleUntilMs: number | null;
|
||||
readonly slots: readonly DisplayTimelineSlot[];
|
||||
}
|
||||
|
||||
/** The part of the group's playback a display acts on. The server sends its whole snapshot; this is
|
||||
* what a display may rely on being there. */
|
||||
export interface DisplayPlayback {
|
||||
readonly revision: number;
|
||||
readonly transport: string;
|
||||
readonly blackout: boolean;
|
||||
readonly remainingMs: number | null;
|
||||
readonly selectionRevision: number | null;
|
||||
readonly currentSelectionId: string | null;
|
||||
readonly currentSlotId: string | null;
|
||||
readonly activeTimelineId: string | null;
|
||||
readonly pendingTimelineId: string | null;
|
||||
readonly startedAtMs: number | null;
|
||||
readonly deadlineAtMs: number | null;
|
||||
}
|
||||
|
||||
export interface DisplayChannelState {
|
||||
readonly serverNowMs: number;
|
||||
readonly channel: {
|
||||
readonly id: string;
|
||||
readonly key: string;
|
||||
readonly groupId: string;
|
||||
};
|
||||
readonly crossfadeMs: number;
|
||||
readonly playback: DisplayPlayback;
|
||||
readonly timeline: DisplayTimeline | null;
|
||||
readonly current: DisplaySelection | null;
|
||||
/** The held image, already resolved as a scene. Separate from `current` because a static hold sits
|
||||
* *over* a preserved cursor rather than replacing it. */
|
||||
readonly staticHold: DisplaySelection | null;
|
||||
/** Bounded, newest first. Material for offline continuation, never a substitute for authority. */
|
||||
readonly selections: readonly DisplaySelection[];
|
||||
}
|
||||
|
||||
// --- Realtime: the display-state channel ----------------------------------------------------------
|
||||
|
||||
/** One group's revisions on the realtime channel. Compact on purpose: a revision this display has
|
||||
* not applied means "fetch the state you are authorized for", never content. */
|
||||
export interface DisplayRealtimeGroup {
|
||||
readonly groupId: string;
|
||||
readonly revision: number;
|
||||
readonly selectionRevision: number | null;
|
||||
}
|
||||
|
||||
export interface DisplayRealtimePayload {
|
||||
readonly groups: readonly DisplayRealtimeGroup[];
|
||||
readonly serverNowMs: number;
|
||||
}
|
||||
+67
-13
@@ -1,5 +1,5 @@
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { EkklesiaUiStyles, EmptyState, Tabs } from "@ekklesia/ui";
|
||||
import { EkklesiaUiStyles, EmptyState, PageHeader, Tabs } from "@ekklesia/ui";
|
||||
import { type ReactElement, useMemo, useState } from "react";
|
||||
import { DesktopOnly } from "../browser/desktop-gate.js";
|
||||
import { createSignageApi } from "./api.js";
|
||||
@@ -24,8 +24,10 @@ import type { ChannelGroupView, SettingsResponse } from "./types.js";
|
||||
*/
|
||||
export function SignageDashboard({
|
||||
context,
|
||||
copyText,
|
||||
}: {
|
||||
readonly context: ModuleUiHostContext;
|
||||
readonly copyText: (value: string) => Promise<void>;
|
||||
}): ReactElement {
|
||||
const api = useMemo(() => createSignageApi(context.api), [context.api]);
|
||||
// Read before the resources below, so a viewer who may not see Signage at all asks for nothing.
|
||||
@@ -33,7 +35,10 @@ export function SignageDashboard({
|
||||
// request it will certainly refuse is noise in a log rather than security.
|
||||
const mayView = context.permissions.has("signage.view");
|
||||
const settings = useResource(
|
||||
() => (mayView ? api.get<SettingsResponse>("settings") : Promise.resolve(undefined)),
|
||||
() =>
|
||||
mayView
|
||||
? api.get<SettingsResponse>("settings")
|
||||
: Promise.resolve(undefined),
|
||||
[mayView],
|
||||
);
|
||||
const groups = useResource(
|
||||
@@ -47,7 +52,9 @@ export function SignageDashboard({
|
||||
const [groupId, setGroupId] = useState<string | undefined>(undefined);
|
||||
|
||||
const mayManageAssets = context.permissions.has("signage.assets.manage");
|
||||
const mayManageTimelines = context.permissions.has("signage.timelines.manage");
|
||||
const mayManageTimelines = context.permissions.has(
|
||||
"signage.timelines.manage",
|
||||
);
|
||||
const mayControl = context.permissions.has("signage.playback.control");
|
||||
const mayManageDisplays = context.permissions.has("signage.displays.manage");
|
||||
|
||||
@@ -61,16 +68,31 @@ export function SignageDashboard({
|
||||
}
|
||||
|
||||
const selectedGroupId =
|
||||
groupId ?? (groups.state.status === "ready" ? groups.state.value?.groups[0]?.id : undefined);
|
||||
groupId ??
|
||||
(groups.state.status === "ready"
|
||||
? groups.state.value?.groups[0]?.id
|
||||
: undefined);
|
||||
const selectedGroup =
|
||||
groups.state.status === "ready"
|
||||
? groups.state.value?.groups.find(
|
||||
(candidate) => candidate.id === selectedGroupId,
|
||||
)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<EkklesiaUiStyles />
|
||||
<DesktopOnly>
|
||||
<PageHeader
|
||||
description="Plan visual content, operate playback, and keep every screen connected."
|
||||
eyebrow="Media"
|
||||
title="Signage"
|
||||
/>
|
||||
{renderLoadable(
|
||||
settings.state,
|
||||
(loaded) =>
|
||||
loaded === undefined ? undefined : (
|
||||
<div className="signage-workspace">
|
||||
<Tabs
|
||||
label="Signage sections"
|
||||
onSelect={setTab}
|
||||
@@ -93,18 +115,28 @@ export function SignageDashboard({
|
||||
{
|
||||
content: (
|
||||
<TimelinesPanel
|
||||
{...(selectedGroup
|
||||
? {
|
||||
activeGroupName: selectedGroup.name,
|
||||
activeTimelineId:
|
||||
selectedGroup.playback.activeTimelineId,
|
||||
}
|
||||
: {})}
|
||||
api={api}
|
||||
canManage={mayManageTimelines}
|
||||
onActivate={
|
||||
mayControl && selectedGroupId !== undefined
|
||||
? (timelineId) => {
|
||||
void api
|
||||
.send("POST", `playback/${selectedGroupId}/activate`, {
|
||||
? async (timelineId) => {
|
||||
await api.send(
|
||||
"POST",
|
||||
`playback/${selectedGroupId}/activate`,
|
||||
{
|
||||
timelineId,
|
||||
when: "now",
|
||||
})
|
||||
.then(() => setTab("playback"))
|
||||
.catch(() => setTab("playback"));
|
||||
},
|
||||
);
|
||||
groups.reload();
|
||||
setTab("playback");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
@@ -116,23 +148,45 @@ export function SignageDashboard({
|
||||
},
|
||||
{
|
||||
content: (
|
||||
<ImagesPanel api={api} canManage={mayManageAssets} settings={loaded} />
|
||||
<ImagesPanel
|
||||
api={api}
|
||||
canManage={mayManageAssets}
|
||||
settings={loaded}
|
||||
/>
|
||||
),
|
||||
id: "images",
|
||||
label: "Images",
|
||||
},
|
||||
{
|
||||
content: <DisplaysPanel api={api} canManage={mayManageDisplays} />,
|
||||
content: (
|
||||
<DisplaysPanel
|
||||
api={api}
|
||||
canManage={mayManageDisplays}
|
||||
copyText={copyText}
|
||||
displaySetupUrl={context.display?.url}
|
||||
onGroupsChanged={() => {
|
||||
setGroupId(undefined);
|
||||
groups.reload();
|
||||
}}
|
||||
/>
|
||||
),
|
||||
id: "displays",
|
||||
label: "Displays",
|
||||
},
|
||||
{
|
||||
content: <ProvidersPanel api={api} context={context} settings={loaded} />,
|
||||
content: (
|
||||
<ProvidersPanel
|
||||
api={api}
|
||||
context={context}
|
||||
settings={loaded}
|
||||
/>
|
||||
),
|
||||
id: "providers",
|
||||
label: "Providers",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
{ label: "Loading Signage…", onRetry: settings.reload },
|
||||
)}
|
||||
|
||||
+14
-2
@@ -15,11 +15,23 @@ import ownStyles from "./styles.css";
|
||||
*/
|
||||
export default defineModuleUi({
|
||||
id: "signage",
|
||||
version: "0.1.0",
|
||||
version: "0.1.2",
|
||||
styles: `${EKKLESIA_UI_STYLESHEET}\n${ownStyles}`,
|
||||
mount(container, context) {
|
||||
const root = createRoot(container);
|
||||
root.render(<SignageDashboard context={context} />);
|
||||
root.render(
|
||||
<SignageDashboard
|
||||
context={context}
|
||||
copyText={async (value) => {
|
||||
if (globalThis.navigator.clipboard === undefined) {
|
||||
throw new Error(
|
||||
"Clipboard access is not available in this browser.",
|
||||
);
|
||||
}
|
||||
await globalThis.navigator.clipboard.writeText(value);
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
return () => root.unmount();
|
||||
},
|
||||
});
|
||||
|
||||
+430
-156
@@ -1,36 +1,120 @@
|
||||
import {
|
||||
Badge,
|
||||
Button,
|
||||
EmptyState,
|
||||
Field,
|
||||
InlineNotice,
|
||||
Panel,
|
||||
Select,
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableRow,
|
||||
TextInput,
|
||||
} from "@ekklesia/ui";
|
||||
import { type ReactElement, useState } from "react";
|
||||
import type { SignageApi } from "../api.js";
|
||||
import { useAction, useResource, useTick } from "../hooks.js";
|
||||
import type { ChannelGroupView, ViewerHealthView } from "../types.js";
|
||||
import { FailureNote, formatSince, OnlineBadge, renderLoadable } from "./shared.js";
|
||||
import {
|
||||
FailureNote,
|
||||
formatSince,
|
||||
OnlineBadge,
|
||||
renderLoadable,
|
||||
} from "./shared.js";
|
||||
|
||||
const AUDIENCE_KEY = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/u;
|
||||
|
||||
function DisplayRow({
|
||||
canManage,
|
||||
groups,
|
||||
nowMs,
|
||||
onChannelChange,
|
||||
onNameChange,
|
||||
viewer,
|
||||
}: {
|
||||
readonly canManage: boolean;
|
||||
readonly groups: readonly ChannelGroupView[];
|
||||
readonly nowMs: number;
|
||||
readonly onChannelChange: (channelId: string) => void;
|
||||
readonly onNameChange: (name: string) => void;
|
||||
readonly viewer: ViewerHealthView;
|
||||
}): ReactElement {
|
||||
return (
|
||||
<div
|
||||
className="signage-display-row"
|
||||
data-testid={`signage-display-${viewer.id}`}
|
||||
>
|
||||
<div className="signage-display-row__identity">
|
||||
{canManage ? (
|
||||
<TextInput
|
||||
aria-label={`Name for ${viewer.name}`}
|
||||
defaultValue={viewer.name}
|
||||
onBlur={(event) =>
|
||||
event.target.value !== viewer.name &&
|
||||
onNameChange(event.target.value)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<strong>{viewer.name}</strong>
|
||||
)}
|
||||
<OnlineBadge online={viewer.online} />
|
||||
</div>
|
||||
<div className="signage-display-row__assignment">
|
||||
{canManage ? (
|
||||
<Field label="Audience channel">
|
||||
{(control) => (
|
||||
<Select
|
||||
{...control}
|
||||
aria-label={`Channel for ${viewer.name}`}
|
||||
onChange={(event) => onChannelChange(event.target.value)}
|
||||
value={viewer.channelId ?? ""}
|
||||
>
|
||||
{groups.map((group) => (
|
||||
<optgroup key={group.id} label={group.name}>
|
||||
{group.channels.map((channel) => (
|
||||
<option key={channel.id} value={channel.id}>
|
||||
{channel.name}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
))}
|
||||
</Select>
|
||||
)}
|
||||
</Field>
|
||||
) : undefined}
|
||||
</div>
|
||||
<div className="signage-display-row__health">
|
||||
<span>{`Seen ${formatSince(viewer.lastSeenAtMs, nowMs)}`}</span>
|
||||
<Badge tone={viewer.offlineReady ? "success" : "neutral"}>
|
||||
{viewer.offlineReady
|
||||
? `${viewer.cachedAssetCount} cached`
|
||||
: "Not offline ready"}
|
||||
</Badge>
|
||||
{viewer.lastError === null ? undefined : (
|
||||
<span
|
||||
className="signage-display-row__error"
|
||||
title={viewer.lastError.detail ?? undefined}
|
||||
>
|
||||
{viewer.lastError.code}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Channel groups, audience channels, and the display roster.
|
||||
*
|
||||
* A church starts with one group and one default channel. `in-person` and `online` are created here,
|
||||
* when someone actually needs them — not shipped as rows nobody asked for and everybody has to
|
||||
* understand and ignore (ADR 0004).
|
||||
* Channel groups, audience channels, and displays, presented in the same hierarchy they use at run
|
||||
* time: one group clock, one audience variant per channel, then the screens assigned to it.
|
||||
*/
|
||||
export function DisplaysPanel({
|
||||
api,
|
||||
canManage,
|
||||
copyText,
|
||||
displaySetupUrl,
|
||||
onGroupsChanged,
|
||||
}: {
|
||||
readonly api: SignageApi;
|
||||
readonly canManage: boolean;
|
||||
readonly copyText: (value: string) => Promise<void>;
|
||||
readonly displaySetupUrl: string | undefined;
|
||||
readonly onGroupsChanged?: () => void;
|
||||
}): ReactElement {
|
||||
const groups = useResource(
|
||||
() => api.get<{ groups: readonly ChannelGroupView[] }>("channel-groups"),
|
||||
@@ -43,31 +127,117 @@ export function DisplaysPanel({
|
||||
const edit = useAction(() => {
|
||||
groups.reload();
|
||||
viewers.reload();
|
||||
onGroupsChanged?.();
|
||||
});
|
||||
const viewerEdit = useAction(viewers.reload);
|
||||
const [groupName, setGroupName] = useState("");
|
||||
const [channelDraft, setChannelDraft] = useState<{ groupId: string; key: string; name: string }>({
|
||||
const [copyStatus, setCopyStatus] = useState<"copied" | "failed" | "idle">(
|
||||
"idle",
|
||||
);
|
||||
const [confirmGroupId, setConfirmGroupId] = useState<string | undefined>(
|
||||
undefined,
|
||||
);
|
||||
const [channelDraft, setChannelDraft] = useState<{
|
||||
groupId: string;
|
||||
key: string;
|
||||
name: string;
|
||||
}>({
|
||||
groupId: "",
|
||||
key: "",
|
||||
name: "",
|
||||
});
|
||||
// "Last seen" is a moving number: without a tick it would freeze at whatever it said when the
|
||||
// roster loaded, and an operator would read a screen that went dark ten minutes ago as current.
|
||||
useTick(5000);
|
||||
const nowMs = Date.now();
|
||||
const readyViewers =
|
||||
viewers.state.status === "ready" ? viewers.state.value.viewers : [];
|
||||
|
||||
const channels =
|
||||
groups.state.status === "ready"
|
||||
? groups.state.value.groups.flatMap((group) =>
|
||||
group.channels.map((channel) => ({ ...channel, groupName: group.name })),
|
||||
)
|
||||
: [];
|
||||
const updateViewer = (
|
||||
viewerId: string,
|
||||
changes: Record<string, string>,
|
||||
): void => {
|
||||
viewerEdit.run(() => api.send("PATCH", `viewers/${viewerId}`, changes));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="signage-columns">
|
||||
<Panel
|
||||
actions={
|
||||
displaySetupUrl === undefined ? undefined : (
|
||||
<div className="signage-pairing-actions">
|
||||
<a
|
||||
className="ek-button ek-focusable ek-button--primary"
|
||||
href={displaySetupUrl}
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
>
|
||||
Open display setup
|
||||
</a>
|
||||
<Button
|
||||
onClick={() => {
|
||||
setCopyStatus("idle");
|
||||
void copyText(displaySetupUrl).then(
|
||||
() => setCopyStatus("copied"),
|
||||
() => setCopyStatus("failed"),
|
||||
);
|
||||
}}
|
||||
>
|
||||
Copy URL
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
description="Connect a screen in three short steps."
|
||||
title="Pair a display"
|
||||
>
|
||||
<ol
|
||||
className="signage-pairing-steps"
|
||||
aria-label="Display pairing steps"
|
||||
>
|
||||
<li>
|
||||
<span className="signage-pairing-steps__number">1</span>
|
||||
<span>
|
||||
Open display setup on the screen that will show signage.
|
||||
</span>
|
||||
</li>
|
||||
<li>
|
||||
<span className="signage-pairing-steps__number">2</span>
|
||||
<span>
|
||||
Enter its six-digit code under Display devices in the Dashboard
|
||||
sidebar.
|
||||
</span>
|
||||
</li>
|
||||
<li>
|
||||
<span className="signage-pairing-steps__number">3</span>
|
||||
<span>Name the display and choose its audience channel below.</span>
|
||||
</li>
|
||||
</ol>
|
||||
{displaySetupUrl === undefined ? (
|
||||
<InlineNotice tone="warning" title="Display setup unavailable">
|
||||
This host did not provide a display setup address.
|
||||
</InlineNotice>
|
||||
) : undefined}
|
||||
<span className="signage-copy-status" aria-live="polite">
|
||||
{copyStatus === "copied"
|
||||
? "Display setup URL copied."
|
||||
: copyStatus === "failed"
|
||||
? "Could not copy the URL. Copy it from the newly opened setup page."
|
||||
: ""}
|
||||
</span>
|
||||
{viewers.state.status === "ready" &&
|
||||
viewers.state.value.viewers.length === 0 ? (
|
||||
<div className="signage-display-empty">
|
||||
<strong>No displays paired yet</strong>
|
||||
<span>
|
||||
A newly approved screen appears below in its assigned channel.
|
||||
</span>
|
||||
</div>
|
||||
) : undefined}
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
actions={
|
||||
canManage ? (
|
||||
<div className="signage-inline-form">
|
||||
<div className="signage-inline-form signage-new-group">
|
||||
<Field label="New channel group">
|
||||
{(control) => (
|
||||
<TextInput
|
||||
@@ -82,80 +252,239 @@ export function DisplaysPanel({
|
||||
disabled={edit.pending || groupName.trim().length === 0}
|
||||
onClick={() =>
|
||||
edit.run(async () => {
|
||||
await api.send("POST", "channel-groups", { name: groupName.trim() });
|
||||
await api.send("POST", "channel-groups", {
|
||||
name: groupName.trim(),
|
||||
});
|
||||
setGroupName("");
|
||||
})
|
||||
}
|
||||
variant="primary"
|
||||
>
|
||||
Create
|
||||
Create group
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
description="A group is one clock. An audience channel is one rendering of it."
|
||||
title="Channel groups"
|
||||
description="A channel group shares one playback clock. Each audience channel can receive a different content variant."
|
||||
title="Channel groups and displays"
|
||||
>
|
||||
{renderLoadable(
|
||||
groups.state,
|
||||
(value) => (
|
||||
(value) => {
|
||||
const knownChannelIds = new Set(
|
||||
value.groups.flatMap((group) =>
|
||||
group.channels.map((channel) => channel.id),
|
||||
),
|
||||
);
|
||||
const unassigned = readyViewers.filter(
|
||||
(viewer) =>
|
||||
viewer.channelId === null ||
|
||||
!knownChannelIds.has(viewer.channelId),
|
||||
);
|
||||
return (
|
||||
<div className="signage-groups" data-testid="signage-groups">
|
||||
{value.groups.map((group) => (
|
||||
<div className="signage-group" key={group.id}>
|
||||
<div className="signage-group__header">
|
||||
<h4 className="signage-editor__subtitle">{group.name}</h4>
|
||||
<Badge tone="info">{group.playback.transport}</Badge>
|
||||
<article className="signage-group" key={group.id}>
|
||||
<header className="signage-group__header">
|
||||
<div className="signage-group__identity">
|
||||
<span className="signage-hierarchy-label">
|
||||
Channel group
|
||||
</span>
|
||||
<h3>{group.name}</h3>
|
||||
</div>
|
||||
<ul className="ek-list">
|
||||
{group.channels.map((channel) => (
|
||||
<li className="ek-list__item signage-row" key={channel.id}>
|
||||
<span className="signage-row__name">{channel.name}</span>
|
||||
<Badge tone={channel.isDefault ? "success" : "neutral"}>
|
||||
{channel.key}
|
||||
<Badge tone="info">{group.playback.transport}</Badge>
|
||||
{canManage && value.groups.length > 1 ? (
|
||||
<Button
|
||||
disabled={edit.pending}
|
||||
onClick={() => setConfirmGroupId(group.id)}
|
||||
variant="danger"
|
||||
>
|
||||
Delete group
|
||||
</Button>
|
||||
) : canManage ? (
|
||||
<Badge tone="neutral">Required group</Badge>
|
||||
) : undefined}
|
||||
</header>
|
||||
{confirmGroupId === group.id ? (
|
||||
<div className="signage-confirm" role="alert">
|
||||
<p>
|
||||
Delete {group.name}? Its playback history will be
|
||||
removed. Displays assigned here will move to the
|
||||
default channel of another group.
|
||||
</p>
|
||||
<Button
|
||||
disabled={edit.pending}
|
||||
onClick={() => setConfirmGroupId(undefined)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
disabled={edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(async () => {
|
||||
await api.send(
|
||||
"DELETE",
|
||||
`channel-groups/${group.id}`,
|
||||
);
|
||||
setConfirmGroupId(undefined);
|
||||
})
|
||||
}
|
||||
variant="danger"
|
||||
>
|
||||
Confirm delete
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined}
|
||||
|
||||
<section className="signage-audiences">
|
||||
<div className="signage-audiences__heading">
|
||||
<div>
|
||||
<span className="signage-hierarchy-label">
|
||||
Audience channels
|
||||
</span>
|
||||
<h4>Who this group renders for</h4>
|
||||
</div>
|
||||
<span>
|
||||
Displays inherit the channel they are assigned to.
|
||||
</span>
|
||||
</div>
|
||||
<div className="signage-channel-list">
|
||||
{group.channels.map((channel) => {
|
||||
const assigned = readyViewers.filter(
|
||||
(viewer) => viewer.channelId === channel.id,
|
||||
);
|
||||
return (
|
||||
<article
|
||||
className="signage-channel"
|
||||
key={channel.id}
|
||||
>
|
||||
<header className="signage-channel__header">
|
||||
<div>
|
||||
<h5>{channel.name}</h5>
|
||||
<div className="signage-channel__meta">
|
||||
{channel.isDefault ? (
|
||||
<Badge tone="success">
|
||||
Default channel
|
||||
</Badge>
|
||||
) : undefined}
|
||||
<span>Audience key</span>
|
||||
<code>{channel.key}</code>
|
||||
<Badge tone="neutral">
|
||||
{`${assigned.length} display${assigned.length === 1 ? "" : "s"}`}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{canManage && !channel.isDefault ? (
|
||||
<Button
|
||||
disabled={edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(() => api.send("DELETE", `channels/${channel.id}`))
|
||||
edit.run(() =>
|
||||
api.send(
|
||||
"DELETE",
|
||||
`channels/${channel.id}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
variant="danger"
|
||||
>
|
||||
Remove
|
||||
Remove channel
|
||||
</Button>
|
||||
) : undefined}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</header>
|
||||
<div className="signage-channel__displays">
|
||||
<span className="signage-hierarchy-label">
|
||||
Displays
|
||||
</span>
|
||||
{assigned.length === 0 ? (
|
||||
<p className="signage-channel__empty">
|
||||
No displays assigned.
|
||||
</p>
|
||||
) : (
|
||||
assigned.map((viewer) => (
|
||||
<DisplayRow
|
||||
canManage={canManage}
|
||||
groups={value.groups}
|
||||
key={viewer.id}
|
||||
nowMs={nowMs}
|
||||
onChannelChange={(channelId) =>
|
||||
updateViewer(viewer.id, { channelId })
|
||||
}
|
||||
onNameChange={(name) =>
|
||||
updateViewer(viewer.id, { name })
|
||||
}
|
||||
viewer={viewer}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{canManage ? (
|
||||
<div className="signage-inline-form" data-testid="signage-add-channel">
|
||||
<Field hint="Lowercase, e.g. online" label="Audience key">
|
||||
<div
|
||||
className="signage-channel-form"
|
||||
data-testid="signage-add-channel"
|
||||
>
|
||||
<div className="signage-channel-form__heading">
|
||||
<h5>Add an audience channel</h5>
|
||||
<span>
|
||||
The default channel always remains available.
|
||||
</span>
|
||||
</div>
|
||||
<Field
|
||||
hint="Shown to administrators and when assigning displays."
|
||||
label="Channel name"
|
||||
>
|
||||
{(control) => (
|
||||
<TextInput
|
||||
{...control}
|
||||
maxLength={120}
|
||||
onChange={(event) =>
|
||||
setChannelDraft({
|
||||
setChannelDraft((current) => ({
|
||||
groupId: group.id,
|
||||
key: event.target.value,
|
||||
name: channelDraft.name,
|
||||
})
|
||||
key:
|
||||
current.groupId === group.id
|
||||
? current.key
|
||||
: "",
|
||||
name: event.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder="Online audience"
|
||||
value={
|
||||
channelDraft.groupId === group.id
|
||||
? channelDraft.name
|
||||
: ""
|
||||
}
|
||||
value={channelDraft.groupId === group.id ? channelDraft.key : ""}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
<Field label="Channel name">
|
||||
<Field
|
||||
hint="Advanced: lowercase ID sent to content providers, e.g. online."
|
||||
label="Audience key"
|
||||
>
|
||||
{(control) => (
|
||||
<TextInput
|
||||
{...control}
|
||||
maxLength={64}
|
||||
onChange={(event) =>
|
||||
setChannelDraft({
|
||||
setChannelDraft((current) => ({
|
||||
groupId: group.id,
|
||||
key: channelDraft.key,
|
||||
name: event.target.value,
|
||||
})
|
||||
key: event.target.value,
|
||||
name:
|
||||
current.groupId === group.id
|
||||
? current.name
|
||||
: "",
|
||||
}))
|
||||
}
|
||||
pattern="[a-z][a-z0-9]*(?:-[a-z0-9]+)*"
|
||||
placeholder="online"
|
||||
value={
|
||||
channelDraft.groupId === group.id
|
||||
? channelDraft.key
|
||||
: ""
|
||||
}
|
||||
value={channelDraft.groupId === group.id ? channelDraft.name : ""}
|
||||
/>
|
||||
)}
|
||||
</Field>
|
||||
@@ -163,125 +492,70 @@ export function DisplaysPanel({
|
||||
disabled={
|
||||
edit.pending ||
|
||||
channelDraft.groupId !== group.id ||
|
||||
channelDraft.key.trim() === "" ||
|
||||
!AUDIENCE_KEY.test(channelDraft.key.trim()) ||
|
||||
channelDraft.key.trim() === "default" ||
|
||||
channelDraft.name.trim() === ""
|
||||
}
|
||||
onClick={() =>
|
||||
edit.run(async () => {
|
||||
await api.send("POST", `channel-groups/${group.id}/channels`, {
|
||||
await api.send(
|
||||
"POST",
|
||||
`channel-groups/${group.id}/channels`,
|
||||
{
|
||||
key: channelDraft.key.trim(),
|
||||
name: channelDraft.name.trim(),
|
||||
},
|
||||
);
|
||||
setChannelDraft({
|
||||
groupId: "",
|
||||
key: "",
|
||||
name: "",
|
||||
});
|
||||
setChannelDraft({ groupId: "", key: "", name: "" });
|
||||
})
|
||||
}
|
||||
variant="primary"
|
||||
>
|
||||
Add audience channel
|
||||
Add channel
|
||||
</Button>
|
||||
</div>
|
||||
) : undefined}
|
||||
</div>
|
||||
</section>
|
||||
</article>
|
||||
))}
|
||||
|
||||
{unassigned.length === 0 ? undefined : (
|
||||
<section className="signage-unassigned">
|
||||
<span className="signage-hierarchy-label">
|
||||
Needs assignment
|
||||
</span>
|
||||
{unassigned.map((viewer) => (
|
||||
<DisplayRow
|
||||
canManage={canManage}
|
||||
groups={value.groups}
|
||||
key={viewer.id}
|
||||
nowMs={nowMs}
|
||||
onChannelChange={(channelId) =>
|
||||
updateViewer(viewer.id, { channelId })
|
||||
}
|
||||
onNameChange={(name) =>
|
||||
updateViewer(viewer.id, { name })
|
||||
}
|
||||
viewer={viewer}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
);
|
||||
},
|
||||
{ label: "Loading channel groups…", onRetry: groups.reload },
|
||||
)}
|
||||
</Panel>
|
||||
|
||||
<Panel
|
||||
description="Every screen Signage has seen, and what it last reported."
|
||||
title="Displays"
|
||||
>
|
||||
{renderLoadable(
|
||||
viewers.state,
|
||||
(value) =>
|
||||
value.viewers.length === 0 ? (
|
||||
<EmptyState
|
||||
description="Open a Signage display on a screen and it will register itself here."
|
||||
title="No displays yet"
|
||||
/>
|
||||
) : (
|
||||
<Table label="Display health">
|
||||
<TableHead>
|
||||
<TableRow>
|
||||
<TableCell header>Name</TableCell>
|
||||
<TableCell header>State</TableCell>
|
||||
<TableCell header>Channel</TableCell>
|
||||
<TableCell header>Last seen</TableCell>
|
||||
<TableCell header>Offline ready</TableCell>
|
||||
<TableCell header>Most recent error</TableCell>
|
||||
</TableRow>
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{value.viewers.map((viewer) => (
|
||||
<TableRow key={viewer.id}>
|
||||
<TableCell>
|
||||
{canManage ? (
|
||||
<TextInput
|
||||
aria-label={`Name for ${viewer.name}`}
|
||||
defaultValue={viewer.name}
|
||||
onBlur={(event) =>
|
||||
event.target.value !== viewer.name &&
|
||||
edit.run(() =>
|
||||
api.send("PATCH", `viewers/${viewer.id}`, {
|
||||
name: event.target.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
viewer.name
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<OnlineBadge online={viewer.online} />
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{canManage ? (
|
||||
<Select
|
||||
aria-label={`Channel for ${viewer.name}`}
|
||||
onChange={(event) =>
|
||||
edit.run(() =>
|
||||
api.send("PATCH", `viewers/${viewer.id}`, {
|
||||
channelId: event.target.value,
|
||||
}),
|
||||
)
|
||||
}
|
||||
value={viewer.channelId ?? ""}
|
||||
>
|
||||
{channels.map((channel) => (
|
||||
<option key={channel.id} value={channel.id}>
|
||||
{`${channel.groupName} · ${channel.name}`}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
) : (
|
||||
(channels.find((channel) => channel.id === viewer.channelId)?.name ?? "—")
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>{formatSince(viewer.lastSeenAtMs, nowMs)}</TableCell>
|
||||
<TableCell>
|
||||
<Badge tone={viewer.offlineReady ? "success" : "neutral"}>
|
||||
{viewer.offlineReady ? `${viewer.cachedAssetCount} cached` : "Not ready"}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{viewer.lastError === null ? (
|
||||
"—"
|
||||
) : (
|
||||
<span title={viewer.lastError.detail ?? undefined}>
|
||||
{viewer.lastError.code}
|
||||
</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
),
|
||||
{ label: "Loading displays…", onRetry: viewers.reload },
|
||||
)}
|
||||
{renderLoadable(viewers.state, () => null, {
|
||||
label: "Loading displays…",
|
||||
onRetry: viewers.reload,
|
||||
})}
|
||||
<FailureNote failure={edit.failure} />
|
||||
<FailureNote failure={viewerEdit.failure} />
|
||||
</Panel>
|
||||
</div>
|
||||
);
|
||||
|
||||
+105
-22
@@ -1,5 +1,13 @@
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { Badge, Button, EmptyState, Field, Panel, Select } from "@ekklesia/ui";
|
||||
import {
|
||||
ActionBar,
|
||||
Badge,
|
||||
Button,
|
||||
EmptyState,
|
||||
Field,
|
||||
Panel,
|
||||
Select,
|
||||
} from "@ekklesia/ui";
|
||||
import { type ReactElement, useState } from "react";
|
||||
import type { SignageApi } from "../api.js";
|
||||
import { useAction, useResource, useTick } from "../hooks.js";
|
||||
@@ -10,7 +18,12 @@ import type {
|
||||
TimelineSummary,
|
||||
} from "../types.js";
|
||||
import { PreviewPanel } from "./PreviewPanel.js";
|
||||
import { FailureNote, formatDuration, formatInstant, renderLoadable } from "./shared.js";
|
||||
import {
|
||||
FailureNote,
|
||||
formatDuration,
|
||||
formatInstant,
|
||||
renderLoadable,
|
||||
} from "./shared.js";
|
||||
|
||||
/**
|
||||
* Live transport for one channel group.
|
||||
@@ -70,8 +83,19 @@ export function PlaybackPanel({
|
||||
command.run(() => api.send("POST", `playback/${groupId}/${path}`, body));
|
||||
}
|
||||
|
||||
function timelineLabel(timelineId: string): string {
|
||||
if (timelines.state.status !== "ready") {
|
||||
return timelineId;
|
||||
}
|
||||
return (
|
||||
<div className="signage-columns">
|
||||
timelines.state.value.timelines.find(
|
||||
(timeline) => timeline.id === timelineId,
|
||||
)?.name ?? timelineId
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="signage-columns signage-playback-layout">
|
||||
<Panel
|
||||
actions={renderLoadable(
|
||||
groups.state,
|
||||
@@ -106,8 +130,16 @@ export function PlaybackPanel({
|
||||
value === undefined ? (
|
||||
<EmptyState title="No channel group selected" />
|
||||
) : (
|
||||
<div className="signage-playback" data-testid="signage-playback">
|
||||
<div
|
||||
className="signage-playback"
|
||||
data-testid="signage-playback"
|
||||
>
|
||||
<div className="signage-playback__status">
|
||||
{value.snapshot.activeTimelineId === null ? undefined : (
|
||||
<Badge tone="success">
|
||||
{`Active: ${timelineLabel(value.snapshot.activeTimelineId)}`}
|
||||
</Badge>
|
||||
)}
|
||||
<Badge
|
||||
tone={
|
||||
value.snapshot.transport === "playing"
|
||||
@@ -119,7 +151,9 @@ export function PlaybackPanel({
|
||||
>
|
||||
{value.snapshot.transport}
|
||||
</Badge>
|
||||
{value.snapshot.blackout ? <Badge tone="danger">Blackout</Badge> : undefined}
|
||||
{value.snapshot.blackout ? (
|
||||
<Badge tone="danger">Blackout</Badge>
|
||||
) : undefined}
|
||||
{value.current?.stale === true ? (
|
||||
<Badge tone="warning">Stale</Badge>
|
||||
) : undefined}
|
||||
@@ -137,7 +171,12 @@ export function PlaybackPanel({
|
||||
title="Nothing on screen"
|
||||
/>
|
||||
) : (
|
||||
<dl className="signage-playback__current" data-testid="signage-current">
|
||||
<section className="signage-playback__now">
|
||||
<h3>Now showing</h3>
|
||||
<dl
|
||||
className="signage-playback__current"
|
||||
data-testid="signage-current"
|
||||
>
|
||||
<dt>Provider</dt>
|
||||
<dd>{value.current.providerId}</dd>
|
||||
<dt>Item</dt>
|
||||
@@ -153,13 +192,26 @@ export function PlaybackPanel({
|
||||
: formatDuration(value.snapshot.remainingMs)}
|
||||
</dd>
|
||||
<dt>Started</dt>
|
||||
<dd>{formatInstant(value.current.startedAtMs, settings.timezone)}</dd>
|
||||
<dd>
|
||||
{formatInstant(
|
||||
value.current.startedAtMs,
|
||||
settings.timezone,
|
||||
)}
|
||||
</dd>
|
||||
</dl>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{canControl ? (
|
||||
<div className="signage-playback__controls" data-testid="signage-controls">
|
||||
<Button disabled={command.pending} onClick={() => run("previous")}>
|
||||
<ActionBar
|
||||
className="signage-playback__controls"
|
||||
data-testid="signage-controls"
|
||||
label="Playback controls"
|
||||
>
|
||||
<Button
|
||||
disabled={command.pending}
|
||||
onClick={() => run("previous")}
|
||||
>
|
||||
Previous
|
||||
</Button>
|
||||
{value.snapshot.transport === "paused" ? (
|
||||
@@ -171,17 +223,27 @@ export function PlaybackPanel({
|
||||
Resume
|
||||
</Button>
|
||||
) : (
|
||||
<Button disabled={command.pending} onClick={() => run("pause")}>
|
||||
<Button
|
||||
disabled={command.pending}
|
||||
onClick={() => run("pause")}
|
||||
>
|
||||
Pause
|
||||
</Button>
|
||||
)}
|
||||
<Button disabled={command.pending} onClick={() => run("next")}>
|
||||
<Button
|
||||
disabled={command.pending}
|
||||
onClick={() => run("next")}
|
||||
>
|
||||
Next
|
||||
</Button>
|
||||
<Button
|
||||
disabled={command.pending}
|
||||
onClick={() => run("blackout", { on: !value.snapshot.blackout })}
|
||||
variant={value.snapshot.blackout ? "primary" : "secondary"}
|
||||
onClick={() =>
|
||||
run("blackout", { on: !value.snapshot.blackout })
|
||||
}
|
||||
variant={
|
||||
value.snapshot.blackout ? "primary" : "secondary"
|
||||
}
|
||||
>
|
||||
{value.snapshot.blackout ? "End blackout" : "Blackout"}
|
||||
</Button>
|
||||
@@ -193,10 +255,13 @@ export function PlaybackPanel({
|
||||
Release hold
|
||||
</Button>
|
||||
)}
|
||||
<Button disabled={command.pending} onClick={() => run("reload")}>
|
||||
<Button
|
||||
disabled={command.pending}
|
||||
onClick={() => run("reload")}
|
||||
>
|
||||
Reload content
|
||||
</Button>
|
||||
</div>
|
||||
</ActionBar>
|
||||
) : undefined}
|
||||
|
||||
{canControl ? (
|
||||
@@ -209,12 +274,17 @@ export function PlaybackPanel({
|
||||
{(control) => (
|
||||
<Select
|
||||
{...control}
|
||||
onChange={(event) => setActivateId(event.target.value)}
|
||||
onChange={(event) =>
|
||||
setActivateId(event.target.value)
|
||||
}
|
||||
value={activateId}
|
||||
>
|
||||
<option value="">Choose a timeline…</option>
|
||||
{loaded.timelines.map((timeline) => (
|
||||
<option key={timeline.id} value={timeline.id}>
|
||||
<option
|
||||
key={timeline.id}
|
||||
value={timeline.id}
|
||||
>
|
||||
{timeline.name}
|
||||
</option>
|
||||
))}
|
||||
@@ -224,7 +294,10 @@ export function PlaybackPanel({
|
||||
<Button
|
||||
disabled={command.pending || activateId === ""}
|
||||
onClick={() =>
|
||||
run("activate", { timelineId: activateId, when: "now" })
|
||||
run("activate", {
|
||||
timelineId: activateId,
|
||||
when: "now",
|
||||
})
|
||||
}
|
||||
variant="primary"
|
||||
>
|
||||
@@ -233,7 +306,10 @@ export function PlaybackPanel({
|
||||
<Button
|
||||
disabled={command.pending || activateId === ""}
|
||||
onClick={() =>
|
||||
run("activate", { timelineId: activateId, when: "next-boundary" })
|
||||
run("activate", {
|
||||
timelineId: activateId,
|
||||
when: "next-boundary",
|
||||
})
|
||||
}
|
||||
>
|
||||
At next slot
|
||||
@@ -247,11 +323,18 @@ export function PlaybackPanel({
|
||||
|
||||
{value.history.length === 0 ? undefined : (
|
||||
<div className="signage-playback__history">
|
||||
<h4 className="signage-editor__subtitle">Recently played</h4>
|
||||
<h4 className="signage-editor__subtitle">
|
||||
Recently played
|
||||
</h4>
|
||||
<ul className="ek-list">
|
||||
{value.history.slice(0, 8).map((entry) => (
|
||||
<li className="ek-list__item signage-row" key={entry.id}>
|
||||
<span className="signage-row__name">{entry.itemId}</span>
|
||||
<li
|
||||
className="ek-list__item signage-row"
|
||||
key={entry.id}
|
||||
>
|
||||
<span className="signage-row__name">
|
||||
{entry.itemId}
|
||||
</span>
|
||||
<span className="signage-playback__history-meta">
|
||||
{`${entry.providerId} · ${formatInstant(entry.startedAtMs, settings.timezone)}`}
|
||||
</span>
|
||||
|
||||
@@ -44,12 +44,17 @@ export function ProvidersPanel({
|
||||
[],
|
||||
);
|
||||
const published = new Set(
|
||||
context.contributions.list(SLIDE_RENDERER_CAPABILITY).map((contribution) => contribution.id),
|
||||
context.contributions
|
||||
.list(SLIDE_RENDERER_CAPABILITY)
|
||||
.map((contribution) => contribution.id),
|
||||
);
|
||||
|
||||
return (
|
||||
<Panel
|
||||
description={`Renderer input contract ${settings.rendererInputVersion}. Only providers that are actually running appear here.`}
|
||||
actions={
|
||||
<Badge tone="neutral">{`Contract ${settings.rendererInputVersion}`}</Badge>
|
||||
}
|
||||
description="Running content sources available to timelines."
|
||||
title="Content providers"
|
||||
>
|
||||
{renderLoadable(
|
||||
@@ -73,20 +78,27 @@ export function ProvidersPanel({
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{value.providers.map((provider) => {
|
||||
const rendererPublished = published.has(provider.renderer.contributionId);
|
||||
const isNative = provider.renderer.contributionId === "signage.native-image";
|
||||
const rendererPublished = published.has(
|
||||
provider.renderer.contributionId,
|
||||
);
|
||||
const isNative =
|
||||
provider.renderer.contributionId === "signage.native-image";
|
||||
return (
|
||||
<TableRow key={provider.providerId}>
|
||||
<TableCell>
|
||||
<span className="signage-provider__id">{provider.providerId}</span>
|
||||
<span className="signage-provider__id">
|
||||
{provider.providerId}
|
||||
</span>
|
||||
<span className="signage-provider__version">{`v${provider.providerVersion}`}</span>
|
||||
</TableCell>
|
||||
<TableCell>{provider.contractVersion}</TableCell>
|
||||
<TableCell>
|
||||
{isNative ? (
|
||||
<Badge tone="success">Signage renders this</Badge>
|
||||
<Badge tone="info">Built in</Badge>
|
||||
) : rendererPublished ? (
|
||||
<Badge tone="success">{provider.renderer.contributionId}</Badge>
|
||||
<Badge tone="success">
|
||||
{provider.renderer.contributionId}
|
||||
</Badge>
|
||||
) : (
|
||||
<Badge tone="warning">Renderer not published</Badge>
|
||||
)}
|
||||
@@ -101,7 +113,10 @@ export function ProvidersPanel({
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{formatInstant(provider.lastSuccessAt, settings.timezone)}
|
||||
{formatInstant(
|
||||
provider.lastSuccessAt,
|
||||
settings.timezone,
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
|
||||
@@ -25,7 +25,12 @@ import type {
|
||||
TimelineDetail,
|
||||
TimelineSummary,
|
||||
} from "../types.js";
|
||||
import { FailureNote, formatDuration, formatInstant, renderLoadable } from "./shared.js";
|
||||
import {
|
||||
FailureNote,
|
||||
formatDuration,
|
||||
formatInstant,
|
||||
renderLoadable,
|
||||
} from "./shared.js";
|
||||
|
||||
const NATIVE_PROVIDER_ID = "signage.native-images";
|
||||
|
||||
@@ -42,11 +47,15 @@ export function TimelinesPanel({
|
||||
settings,
|
||||
canManage,
|
||||
onActivate,
|
||||
activeTimelineId,
|
||||
activeGroupName,
|
||||
}: {
|
||||
readonly api: SignageApi;
|
||||
readonly settings: SettingsResponse;
|
||||
readonly canManage: boolean;
|
||||
readonly onActivate: ((timelineId: string) => void) | undefined;
|
||||
readonly onActivate: ((timelineId: string) => Promise<void>) | undefined;
|
||||
readonly activeTimelineId?: string | null;
|
||||
readonly activeGroupName?: string;
|
||||
}): ReactElement {
|
||||
const timelines = useResource(
|
||||
() => api.get<{ timelines: readonly TimelineSummary[] }>("timelines"),
|
||||
@@ -62,6 +71,7 @@ export function TimelinesPanel({
|
||||
setNewName("");
|
||||
timelines.reload();
|
||||
});
|
||||
const activation = useAction();
|
||||
|
||||
return (
|
||||
<div className="signage-columns">
|
||||
@@ -82,7 +92,9 @@ export function TimelinesPanel({
|
||||
<Button
|
||||
disabled={create.pending || newName.trim().length === 0}
|
||||
onClick={() =>
|
||||
create.run(() => api.send("POST", "timelines", { name: newName.trim() }))
|
||||
create.run(() =>
|
||||
api.send("POST", "timelines", { name: newName.trim() }),
|
||||
)
|
||||
}
|
||||
variant="primary"
|
||||
>
|
||||
@@ -114,20 +126,50 @@ export function TimelinesPanel({
|
||||
</TableHead>
|
||||
<TableBody>
|
||||
{value.timelines.map((timeline) => (
|
||||
<TableRow key={timeline.id} selected={timeline.id === selectedId}>
|
||||
<TableRow
|
||||
key={timeline.id}
|
||||
selected={timeline.id === selectedId}
|
||||
>
|
||||
<TableCell>
|
||||
<Button onClick={() => setSelectedId(timeline.id)}>{timeline.name}</Button>
|
||||
<div className="signage-timeline-name">
|
||||
<Button
|
||||
className="signage-timeline-select"
|
||||
onClick={() => setSelectedId(timeline.id)}
|
||||
variant="quiet"
|
||||
>
|
||||
{timeline.name}
|
||||
</Button>
|
||||
{timeline.id === activeTimelineId ? (
|
||||
<Badge tone="success">
|
||||
{activeGroupName
|
||||
? `Active in ${activeGroupName}`
|
||||
: "Active"}
|
||||
</Badge>
|
||||
) : undefined}
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{timeline.eligibleFrom === null && timeline.eligibleUntil === null
|
||||
{timeline.eligibleFrom === null &&
|
||||
timeline.eligibleUntil === null
|
||||
? "Always"
|
||||
: `${formatInstant(timeline.eligibleFrom, settings.timezone)} → ${formatInstant(timeline.eligibleUntil, settings.timezone)}`}
|
||||
</TableCell>
|
||||
<TableCell>{timeline.revision}</TableCell>
|
||||
<TableCell>
|
||||
{onActivate === undefined ? undefined : (
|
||||
<Button onClick={() => onActivate(timeline.id)} variant="primary">
|
||||
Activate
|
||||
<Button
|
||||
disabled={
|
||||
activation.pending ||
|
||||
timeline.id === activeTimelineId
|
||||
}
|
||||
onClick={() =>
|
||||
activation.run(() => onActivate(timeline.id))
|
||||
}
|
||||
variant="primary"
|
||||
>
|
||||
{timeline.id === activeTimelineId
|
||||
? "Active"
|
||||
: "Activate"}
|
||||
</Button>
|
||||
)}
|
||||
</TableCell>
|
||||
@@ -139,6 +181,7 @@ export function TimelinesPanel({
|
||||
{ label: "Loading timelines…", onRetry: timelines.reload },
|
||||
)}
|
||||
<FailureNote failure={create.failure} />
|
||||
<FailureNote failure={activation.failure} />
|
||||
</Panel>
|
||||
|
||||
{selectedId === undefined ? undefined : (
|
||||
@@ -148,7 +191,11 @@ export function TimelinesPanel({
|
||||
key={selectedId}
|
||||
onChanged={timelines.reload}
|
||||
onClose={() => setSelectedId(undefined)}
|
||||
providers={providers.state.status === "ready" ? providers.state.value.providers : []}
|
||||
providers={
|
||||
providers.state.status === "ready"
|
||||
? providers.state.value.providers
|
||||
: []
|
||||
}
|
||||
settings={settings}
|
||||
timelineId={selectedId}
|
||||
/>
|
||||
@@ -178,13 +225,18 @@ function TimelineEditor({
|
||||
() => api.get<TimelineDetail>(`timelines/${timelineId}`),
|
||||
[timelineId],
|
||||
);
|
||||
const images = useResource(() => api.get<{ images: readonly ImageRecord[] }>("images"), []);
|
||||
const images = useResource(
|
||||
() => api.get<{ images: readonly ImageRecord[] }>("images"),
|
||||
[],
|
||||
);
|
||||
const edit = useAction(() => {
|
||||
detail.reload();
|
||||
onChanged();
|
||||
});
|
||||
const [providerId, setProviderId] = useState("");
|
||||
const [sources, setSources] = useState<readonly ProviderSourceDescriptor[]>([]);
|
||||
const [sources, setSources] = useState<readonly ProviderSourceDescriptor[]>(
|
||||
[],
|
||||
);
|
||||
const [items, setItems] = useState<readonly ProviderItemDescriptor[]>([]);
|
||||
|
||||
function loadProvider(nextProviderId: string): void {
|
||||
@@ -221,7 +273,10 @@ function TimelineEditor({
|
||||
<h3 className="signage-editor__title">{value.timeline.name}</h3>
|
||||
|
||||
{canManage ? (
|
||||
<div className="signage-editor__add" data-testid="signage-add-source">
|
||||
<div
|
||||
className="signage-editor__add"
|
||||
data-testid="signage-add-source"
|
||||
>
|
||||
<Field
|
||||
hint="A provider's own source. Repeat its slot to give it more turns in one rotation."
|
||||
label="Content provider"
|
||||
@@ -234,7 +289,10 @@ function TimelineEditor({
|
||||
>
|
||||
<option value="">Choose a provider…</option>
|
||||
{providers.map((provider) => (
|
||||
<option key={provider.providerId} value={provider.providerId}>
|
||||
<option
|
||||
key={provider.providerId}
|
||||
value={provider.providerId}
|
||||
>
|
||||
{provider.providerId}
|
||||
</option>
|
||||
))}
|
||||
@@ -290,9 +348,13 @@ function TimelineEditor({
|
||||
disabled={edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(() =>
|
||||
api.send("POST", `timelines/${timelineId}/slots`, {
|
||||
api.send(
|
||||
"POST",
|
||||
`timelines/${timelineId}/slots`,
|
||||
{
|
||||
sourceId: source.id,
|
||||
}),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -302,7 +364,10 @@ function TimelineEditor({
|
||||
disabled={edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(() =>
|
||||
api.send("DELETE", `timelines/${timelineId}/sources/${source.id}`),
|
||||
api.send(
|
||||
"DELETE",
|
||||
`timelines/${timelineId}/sources/${source.id}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
variant="danger"
|
||||
@@ -338,7 +403,8 @@ function TimelineEditor({
|
||||
(candidate) => candidate.id === slot.sourceId,
|
||||
);
|
||||
const image =
|
||||
slot.providerId === NATIVE_PROVIDER_ID && images.state.status === "ready"
|
||||
slot.providerId === NATIVE_PROVIDER_ID &&
|
||||
images.state.status === "ready"
|
||||
? images.state.value.images.find(
|
||||
(candidate) => candidate.id === slot.itemId,
|
||||
)
|
||||
@@ -349,7 +415,8 @@ function TimelineEditor({
|
||||
<TableCell>
|
||||
{slot.kind === "provider-source"
|
||||
? (source?.label ?? "Removed source")
|
||||
: (image?.displayName ?? `${slot.providerId} · ${slot.itemId}`)}
|
||||
: (image?.displayName ??
|
||||
`${slot.providerId} · ${slot.itemId}`)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{slot.durationOverrideMs === null
|
||||
@@ -363,9 +430,13 @@ function TimelineEditor({
|
||||
label={slot.enabled ? "On" : "Off"}
|
||||
onChange={(event) =>
|
||||
edit.run(() =>
|
||||
api.send("PATCH", `timelines/${timelineId}/slots/${slot.id}`, {
|
||||
api.send(
|
||||
"PATCH",
|
||||
`timelines/${timelineId}/slots/${slot.id}`,
|
||||
{
|
||||
enabled: event.target.checked,
|
||||
}),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
@@ -377,29 +448,44 @@ function TimelineEditor({
|
||||
disabled={index === 0 || edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(() =>
|
||||
api.send("PUT", `timelines/${timelineId}/slot-order`, {
|
||||
api.send(
|
||||
"PUT",
|
||||
`timelines/${timelineId}/slot-order`,
|
||||
{
|
||||
slotIds: swap(
|
||||
value.slots.map((candidate) => candidate.id),
|
||||
value.slots.map(
|
||||
(candidate) => candidate.id,
|
||||
),
|
||||
index,
|
||||
index - 1,
|
||||
),
|
||||
}),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
Up
|
||||
</Button>
|
||||
<Button
|
||||
disabled={index === value.slots.length - 1 || edit.pending}
|
||||
disabled={
|
||||
index === value.slots.length - 1 ||
|
||||
edit.pending
|
||||
}
|
||||
onClick={() =>
|
||||
edit.run(() =>
|
||||
api.send("PUT", `timelines/${timelineId}/slot-order`, {
|
||||
api.send(
|
||||
"PUT",
|
||||
`timelines/${timelineId}/slot-order`,
|
||||
{
|
||||
slotIds: swap(
|
||||
value.slots.map((candidate) => candidate.id),
|
||||
value.slots.map(
|
||||
(candidate) => candidate.id,
|
||||
),
|
||||
index,
|
||||
index + 1,
|
||||
),
|
||||
}),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
>
|
||||
@@ -409,7 +495,10 @@ function TimelineEditor({
|
||||
disabled={edit.pending}
|
||||
onClick={() =>
|
||||
edit.run(() =>
|
||||
api.send("DELETE", `timelines/${timelineId}/slots/${slot.id}`),
|
||||
api.send(
|
||||
"DELETE",
|
||||
`timelines/${timelineId}/slots/${slot.id}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
variant="danger"
|
||||
|
||||
+335
-9
@@ -28,7 +28,7 @@
|
||||
}
|
||||
|
||||
:host {
|
||||
--signage-gap: var(--ekklesia-spacing-lg);
|
||||
--signage-gap: var(--ekklesia-spacing-xl);
|
||||
--signage-gap-tight: var(--ekklesia-spacing-sm);
|
||||
--signage-panel-radius: var(--ekklesia-radius-lg);
|
||||
--signage-thumbnail-width: 220px;
|
||||
@@ -69,10 +69,19 @@
|
||||
|
||||
.signage-desktop {
|
||||
display: grid;
|
||||
gap: var(--signage-gap);
|
||||
gap: var(--ekklesia-spacing-xl);
|
||||
}
|
||||
}
|
||||
|
||||
.signage-workspace {
|
||||
display: grid;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.signage-workspace > .ek-tabs__list {
|
||||
padding-inline: var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-columns {
|
||||
display: grid;
|
||||
gap: var(--signage-gap);
|
||||
@@ -167,7 +176,10 @@
|
||||
.signage-image-grid {
|
||||
display: grid;
|
||||
gap: var(--signage-gap);
|
||||
grid-template-columns: repeat(auto-fill, minmax(var(--signage-thumbnail-width), 1fr));
|
||||
grid-template-columns: repeat(
|
||||
auto-fill,
|
||||
minmax(var(--signage-thumbnail-width), 1fr)
|
||||
);
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
@@ -177,13 +189,13 @@
|
||||
/* Rows sized to their content, with the slack from a taller neighbour left at the bottom rather
|
||||
than spread between the thumbnail and the name. */
|
||||
align-content: start;
|
||||
background: var(--ekklesia-background-canvas);
|
||||
background: var(--ekklesia-background-surface);
|
||||
border: var(--ekklesia-border-width) solid var(--ekklesia-border-divider);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-xs);
|
||||
gap: var(--ekklesia-spacing-sm);
|
||||
overflow: hidden;
|
||||
padding: var(--ekklesia-spacing-sm);
|
||||
padding: var(--ekklesia-spacing-md);
|
||||
}
|
||||
|
||||
/* One box, whatever shape the image is: a library of mixed aspect ratios still reads as a grid, and
|
||||
@@ -285,6 +297,19 @@
|
||||
gap: var(--ekklesia-spacing-2xs);
|
||||
}
|
||||
|
||||
.signage-timeline-name {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--ekklesia-spacing-sm);
|
||||
}
|
||||
|
||||
.signage-timeline-select {
|
||||
color: var(--ekklesia-text-primary);
|
||||
font-weight: var(--ekklesia-typography-weight-bold);
|
||||
padding-inline: var(--ekklesia-spacing-sm);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------------------------
|
||||
* Playback.
|
||||
* ------------------------------------------------------------------------------------------- */
|
||||
@@ -311,6 +336,19 @@
|
||||
row-gap: var(--ekklesia-spacing-2xs);
|
||||
}
|
||||
|
||||
.signage-playback__now {
|
||||
background: var(--ekklesia-background-inset);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-sm);
|
||||
padding: var(--ekklesia-spacing-md);
|
||||
}
|
||||
|
||||
.signage-playback__now h3 {
|
||||
font-size: var(--ekklesia-typography-size-lg);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.signage-playback__current dt {
|
||||
color: var(--ekklesia-text-secondary);
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
@@ -326,6 +364,23 @@
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
}
|
||||
|
||||
.signage-playback__history {
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-sm);
|
||||
}
|
||||
|
||||
.signage-playback__history .ek-list {
|
||||
max-height: 14rem;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
@media (min-width: 1280px) {
|
||||
.signage-playback-layout {
|
||||
align-items: start;
|
||||
grid-template-columns: minmax(0, 1fr) minmax(28rem, 1fr);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------------------------
|
||||
* Displays and providers.
|
||||
* ------------------------------------------------------------------------------------------- */
|
||||
@@ -335,20 +390,291 @@
|
||||
gap: var(--signage-gap);
|
||||
}
|
||||
|
||||
.signage-group {
|
||||
border: var(--ekklesia-border-width) solid var(--ekklesia-border-divider);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
.signage-pairing-steps {
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.signage-pairing-actions {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--signage-gap-tight);
|
||||
}
|
||||
|
||||
.signage-pairing-actions a {
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.signage-copy-status {
|
||||
color: var(--ekklesia-text-secondary);
|
||||
display: block;
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
min-height: 1.25em;
|
||||
margin-block-start: var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-pairing-steps li {
|
||||
align-items: center;
|
||||
background: var(--ekklesia-accent-subtle);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: flex;
|
||||
gap: var(--signage-gap-tight);
|
||||
min-width: 0;
|
||||
padding: var(--ekklesia-spacing-md);
|
||||
}
|
||||
|
||||
.signage-pairing-steps__number {
|
||||
align-items: center;
|
||||
background: var(--ekklesia-accent-base);
|
||||
border-radius: var(--ekklesia-radius-pill);
|
||||
color: var(--ekklesia-accent-foreground);
|
||||
display: inline-flex;
|
||||
flex: 0 0 var(--ekklesia-control-height-sm);
|
||||
font-weight: var(--ekklesia-typography-weight-bold);
|
||||
height: var(--ekklesia-control-height-sm);
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.signage-display-empty {
|
||||
align-items: baseline;
|
||||
color: var(--ekklesia-text-secondary);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--ekklesia-spacing-xs) var(--signage-gap-tight);
|
||||
margin-block-start: var(--signage-gap-tight);
|
||||
}
|
||||
|
||||
.signage-display-empty strong {
|
||||
color: var(--ekklesia-text-primary);
|
||||
}
|
||||
|
||||
.signage-new-group > .ek-field {
|
||||
min-width: 16rem;
|
||||
}
|
||||
|
||||
.signage-group {
|
||||
background: var(--ekklesia-background-inset);
|
||||
border: var(--ekklesia-border-width) solid var(--ekklesia-border-divider);
|
||||
border-radius: var(--signage-panel-radius);
|
||||
display: grid;
|
||||
gap: var(--signage-gap);
|
||||
padding: var(--ekklesia-spacing-lg);
|
||||
}
|
||||
|
||||
.signage-group__header {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
gap: var(--signage-gap-tight);
|
||||
}
|
||||
|
||||
.signage-group__header > .ek-button {
|
||||
margin-inline-start: auto;
|
||||
}
|
||||
|
||||
.signage-group__identity {
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-2xs);
|
||||
}
|
||||
|
||||
.signage-group__identity h3,
|
||||
.signage-audiences__heading h4,
|
||||
.signage-channel__header h5,
|
||||
.signage-channel-form__heading h5 {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.signage-hierarchy-label {
|
||||
color: var(--ekklesia-text-muted);
|
||||
font-size: var(--ekklesia-typography-size-xs);
|
||||
font-weight: var(--ekklesia-typography-weight-medium);
|
||||
letter-spacing: 0.05em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.signage-confirm {
|
||||
align-items: center;
|
||||
background: var(--ekklesia-status-danger-background);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
color: var(--ekklesia-text-danger);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--signage-gap-tight);
|
||||
padding: var(--ekklesia-spacing-sm);
|
||||
}
|
||||
|
||||
.signage-confirm p {
|
||||
flex: 1 1 30rem;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.signage-audiences {
|
||||
border-block-start: var(--ekklesia-border-width) solid
|
||||
var(--ekklesia-border-divider);
|
||||
display: grid;
|
||||
gap: var(--signage-gap);
|
||||
padding-block-start: var(--signage-gap);
|
||||
}
|
||||
|
||||
.signage-audiences__heading {
|
||||
align-items: end;
|
||||
display: flex;
|
||||
gap: var(--signage-gap);
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.signage-audiences__heading > div {
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-2xs);
|
||||
}
|
||||
|
||||
.signage-audiences__heading > span {
|
||||
color: var(--ekklesia-text-secondary);
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
}
|
||||
|
||||
.signage-channel-list {
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
}
|
||||
|
||||
.signage-channel {
|
||||
background: var(--ekklesia-background-surface);
|
||||
border: var(--ekklesia-border-width) solid var(--ekklesia-border-divider);
|
||||
border-inline-start: var(--ekklesia-spacing-2xs) solid
|
||||
var(--ekklesia-accent-base);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
margin-inline-start: var(--ekklesia-spacing-md);
|
||||
padding: var(--ekklesia-spacing-md);
|
||||
}
|
||||
|
||||
.signage-channel__header {
|
||||
align-items: start;
|
||||
display: flex;
|
||||
gap: var(--signage-gap-tight);
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.signage-channel__header > div {
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-channel__meta {
|
||||
align-items: center;
|
||||
color: var(--ekklesia-text-secondary);
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
gap: var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-channel__meta code,
|
||||
.signage-pairing-steps code {
|
||||
background: var(--ekklesia-background-inset);
|
||||
border-radius: var(--ekklesia-radius-sm);
|
||||
color: var(--ekklesia-text-primary);
|
||||
padding: var(--ekklesia-spacing-2xs) var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-channel__displays {
|
||||
border-block-start: var(--ekklesia-border-width) solid
|
||||
var(--ekklesia-border-divider);
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
padding-block-start: var(--signage-gap-tight);
|
||||
}
|
||||
|
||||
.signage-channel__empty {
|
||||
color: var(--ekklesia-text-muted);
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.signage-display-row {
|
||||
align-items: end;
|
||||
background: var(--ekklesia-background-canvas);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
grid-template-columns: minmax(14rem, 1.2fr) minmax(14rem, 1fr) minmax(
|
||||
14rem,
|
||||
1.2fr
|
||||
);
|
||||
padding: var(--ekklesia-spacing-sm);
|
||||
}
|
||||
|
||||
.signage-display-row__identity,
|
||||
.signage-display-row__health {
|
||||
align-items: center;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: var(--ekklesia-spacing-xs);
|
||||
}
|
||||
|
||||
.signage-display-row__identity .ek-control,
|
||||
.signage-display-row__assignment .ek-field {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.signage-display-row__health {
|
||||
color: var(--ekklesia-text-secondary);
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
}
|
||||
|
||||
.signage-display-row__error {
|
||||
color: var(--ekklesia-text-danger);
|
||||
}
|
||||
|
||||
.signage-channel-form,
|
||||
.signage-unassigned {
|
||||
background: var(--ekklesia-background-surface);
|
||||
border: var(--ekklesia-border-width) solid var(--ekklesia-border-divider);
|
||||
border-radius: var(--ekklesia-radius-md);
|
||||
display: grid;
|
||||
gap: var(--signage-gap-tight);
|
||||
margin-inline-start: var(--ekklesia-spacing-md);
|
||||
padding: var(--ekklesia-spacing-md);
|
||||
}
|
||||
|
||||
.signage-channel-form {
|
||||
align-items: start;
|
||||
grid-template-columns: minmax(16rem, 2fr) minmax(14rem, 1fr);
|
||||
}
|
||||
|
||||
.signage-channel-form__heading,
|
||||
.signage-channel-form > .ek-button {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
.signage-channel-form__heading {
|
||||
display: grid;
|
||||
gap: var(--ekklesia-spacing-2xs);
|
||||
}
|
||||
|
||||
.signage-channel-form__heading span {
|
||||
color: var(--ekklesia-text-secondary);
|
||||
font-size: var(--ekklesia-typography-size-sm);
|
||||
}
|
||||
|
||||
.signage-channel-form > .ek-button {
|
||||
justify-self: start;
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
.signage-pairing-steps,
|
||||
.signage-channel-form,
|
||||
.signage-display-row {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.signage-provider__id {
|
||||
font-weight: var(--ekklesia-typography-weight-medium);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DISPLAY_RETRY_BASE_MS,
|
||||
DISPLAY_RETRY_MAX_MS,
|
||||
displayRetryDelayMs,
|
||||
} from "../../src/browser/backoff.js";
|
||||
|
||||
describe("display retry backoff", () => {
|
||||
it("doubles from one second and stops at one minute", () => {
|
||||
const longest = (attempt: number) => displayRetryDelayMs(attempt, () => 1);
|
||||
expect([0, 1, 2, 3, 4, 5, 6, 7, 50].map(longest)).toEqual([
|
||||
1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 60_000, 60_000, 60_000,
|
||||
]);
|
||||
});
|
||||
|
||||
it("jitters between half and all of each step, and never waits zero", () => {
|
||||
for (const attempt of [0, 3, 6, 40]) {
|
||||
const step = Math.min(DISPLAY_RETRY_MAX_MS, DISPLAY_RETRY_BASE_MS * 2 ** attempt);
|
||||
expect(displayRetryDelayMs(attempt, () => 0)).toBe(step / 2);
|
||||
expect(displayRetryDelayMs(attempt, () => 1)).toBe(step);
|
||||
for (let index = 0; index < 50; index += 1) {
|
||||
const delay = displayRetryDelayMs(attempt);
|
||||
expect(delay).toBeGreaterThanOrEqual(step / 2);
|
||||
expect(delay).toBeLessThanOrEqual(step);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it("treats a nonsensical attempt or random value as the nearest sensible one", () => {
|
||||
expect(displayRetryDelayMs(-3, () => 1)).toBe(1_000);
|
||||
expect(displayRetryDelayMs(2, () => 7)).toBe(4_000);
|
||||
expect(displayRetryDelayMs(2, () => -1)).toBe(2_000);
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,7 @@ const SELECTION = {
|
||||
},
|
||||
revision: 1,
|
||||
slotId: "slot-trivia",
|
||||
stale: false,
|
||||
startedAtMs: 0,
|
||||
withdrawn: false,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { ModuleRouteDefinitionInput, ModuleRouteHandlerContext } from "@ekklesia/module-sdk";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { createMemoryMediaCache, createMemoryStore } from "../../src/browser/storage.js";
|
||||
import { createDisplayController } from "../../src/display/controller.js";
|
||||
import { ingestNativeImage } from "../../src/server/images/service.js";
|
||||
import {
|
||||
createPlaybackService,
|
||||
type SignagePlaybackService,
|
||||
} from "../../src/server/playback/service.js";
|
||||
import { createNativeImageProvider } from "../../src/server/providers/native-provider.js";
|
||||
import {
|
||||
createProviderRegistry,
|
||||
type SignageProviderRegistry,
|
||||
} from "../../src/server/providers/registry.js";
|
||||
import { registerViewerRoutes } from "../../src/server/routes/viewers.js";
|
||||
import { addSlot, createTimeline } from "../../src/server/timelines/service.js";
|
||||
import { SIGNAGE_NATIVE_PROVIDER_ID } from "../../src/shared/native-images.js";
|
||||
import { SIGNAGE_DEFAULT_SETTINGS } from "../../src/shared/settings.js";
|
||||
import { createFakeStorage, type FakeStorage } from "../support/fake-storage.js";
|
||||
import { makeImage } from "../support/images.js";
|
||||
import { createMemorySignageStore, type MemorySignageStore } from "../support/memory-store.js";
|
||||
import { fakeConfiguration, fakeHandlerContext } from "../support/module-harness.js";
|
||||
import { createFakeHost, type FakeHost } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
* The display and the server, speaking to each other for real.
|
||||
*
|
||||
* Every other display test answers the controller with a hand-written stub, and every server test
|
||||
* calls the service with a hand-written object. Each side was therefore only ever tested against its
|
||||
* own idea of the other, and in production every heartbeat a display sent was refused with a 400:
|
||||
* the display sent `null` for an absent value and the route accepted only a missing field.
|
||||
*
|
||||
* Here the **real** display controller's requests are answered by the **real** viewer routes, over
|
||||
* Signage's in-memory store. A request one side builds and the other refuses fails this suite.
|
||||
*/
|
||||
|
||||
const START = Date.parse("2026-10-05T15:00:00.000Z");
|
||||
const DEVICE_ID = "6f1c2d3e-4b5a-4c6d-8e7f-901a2b3c4d5e";
|
||||
|
||||
interface RouteCall {
|
||||
readonly method: string;
|
||||
readonly path: string;
|
||||
readonly status: number;
|
||||
readonly code: string | undefined;
|
||||
}
|
||||
|
||||
/** Matches a relative module path against the routes the module registered, and runs the handler
|
||||
* exactly as the platform would: one Request, one handler context. */
|
||||
function routeTable(routes: readonly ModuleRouteDefinitionInput[]) {
|
||||
return routes.map((route) => {
|
||||
const names: string[] = [];
|
||||
const pattern = new RegExp(
|
||||
`^${route.path.replace(/:(\w+)/gu, (_match, name: string) => {
|
||||
names.push(name);
|
||||
return "([^/]+)";
|
||||
})}$`,
|
||||
"u",
|
||||
);
|
||||
return { names, pattern, route };
|
||||
});
|
||||
}
|
||||
|
||||
describe("display ↔ server contract", () => {
|
||||
let clock: number;
|
||||
let counter: number;
|
||||
let store: MemorySignageStore;
|
||||
let storage: FakeStorage;
|
||||
let registry: SignageProviderRegistry;
|
||||
let playback: SignagePlaybackService;
|
||||
let calls: RouteCall[];
|
||||
let host: FakeHost;
|
||||
let root: HTMLElement;
|
||||
|
||||
const newId = () => {
|
||||
counter += 1;
|
||||
return `00000000-0000-4000-8000-${String(counter).padStart(12, "0")}`;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
clock = START;
|
||||
counter = 0;
|
||||
calls = [];
|
||||
store = createMemorySignageStore({ now: () => new Date(clock) });
|
||||
storage = createFakeStorage({ now: () => new Date(clock) });
|
||||
registry = createProviderRegistry({ now: () => new Date(clock), timeoutMs: 1000 });
|
||||
registry.capability.register(
|
||||
createNativeImageProvider({ defaultDurationMs: 7000, now: () => new Date(clock), store })
|
||||
.registration,
|
||||
);
|
||||
playback = createPlaybackService({
|
||||
newId,
|
||||
now: () => clock,
|
||||
registry,
|
||||
setTimer: () => undefined,
|
||||
settings: SIGNAGE_DEFAULT_SETTINGS,
|
||||
store,
|
||||
});
|
||||
await playback.ensureDefaultGroup();
|
||||
|
||||
// One native image on a pinned slot: the most ordinary thing a wall shows, and exactly the case
|
||||
// whose heartbeat carries no contribution id.
|
||||
const image = await ingestNativeImage({
|
||||
bytes: await makeImage({ format: "png", height: 1080, width: 1920 }),
|
||||
displayName: "Welcome",
|
||||
expiresAt: null,
|
||||
filename: "welcome.png",
|
||||
storage,
|
||||
store,
|
||||
});
|
||||
const timeline = await createTimeline({ name: "Lobby", newId, store });
|
||||
await addSlot({
|
||||
newId,
|
||||
pinned: { itemId: image.image.id, providerId: SIGNAGE_NATIVE_PROVIDER_ID },
|
||||
store,
|
||||
timelineId: timeline.timeline.id,
|
||||
});
|
||||
const groups = await store.listChannelGroups();
|
||||
await playback.activate(groups[0]?.group.id as string, timeline.timeline.id, "now");
|
||||
|
||||
const registered: ModuleRouteDefinitionInput[] = [];
|
||||
registerViewerRoutes(
|
||||
{ route: (definition) => registered.push(definition) },
|
||||
() => playback,
|
||||
() => registry,
|
||||
() => store,
|
||||
);
|
||||
const table = routeTable(registered);
|
||||
|
||||
host = createFakeHost({
|
||||
permissions: ["signage.display.view"],
|
||||
principal: { deviceId: DEVICE_ID, kind: "device" } as never,
|
||||
routes: [],
|
||||
});
|
||||
Object.assign(host.context.api, {
|
||||
async request(path: string, init?: RequestInit): Promise<Response> {
|
||||
const method = (init?.method ?? "GET").toUpperCase();
|
||||
const relative = `/${path.replace(/^\//u, "").split("?")[0]}`;
|
||||
for (const { names, pattern, route } of table) {
|
||||
const match = pattern.exec(relative);
|
||||
if (route.method !== method || !match) {
|
||||
continue;
|
||||
}
|
||||
const params = Object.fromEntries(names.map((name, index) => [name, match[index + 1]]));
|
||||
const context: ModuleRouteHandlerContext = fakeHandlerContext({
|
||||
config: fakeConfiguration({}),
|
||||
params: Object.freeze(params) as never,
|
||||
principal: { deviceId: DEVICE_ID, kind: "device" } as never,
|
||||
storage,
|
||||
});
|
||||
const request = new Request(
|
||||
`https://api.example.test/api/v1/modules/signage${relative}`,
|
||||
{
|
||||
...(init?.body === undefined ? {} : { body: init.body }),
|
||||
headers: init?.headers ?? {},
|
||||
method,
|
||||
},
|
||||
);
|
||||
const response = await route.handler(request, context);
|
||||
const body = (await response
|
||||
.clone()
|
||||
.json()
|
||||
.catch(() => null)) as { code?: string } | null;
|
||||
calls.push({ code: body?.code, method, path: route.path, status: response.status });
|
||||
return response;
|
||||
}
|
||||
throw new Error(
|
||||
`The display asked for ${method} ${relative}, which Signage does not serve.`,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
});
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
function controller() {
|
||||
return createDisplayController({
|
||||
context: host.context,
|
||||
decodeImage: () => Promise.resolve(),
|
||||
media: createMemoryMediaCache(),
|
||||
newViewerKey: () => "kiosk-contract-0001",
|
||||
now: () => clock,
|
||||
root,
|
||||
store: createMemoryStore(),
|
||||
});
|
||||
}
|
||||
|
||||
it("the server accepts every request the display sends", async () => {
|
||||
const display = controller();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
|
||||
const sent = calls.map((call) => `${call.method} ${call.path}`);
|
||||
expect(sent).toContain("POST /viewers/session");
|
||||
expect(sent).toContain("GET /channels/:channelId/display-state");
|
||||
expect(sent).toContain("POST /viewers/:viewerId/heartbeat");
|
||||
// Not one refusal, of any kind, for anything the display built itself.
|
||||
expect(calls.filter((call) => call.status >= 400)).toEqual([]);
|
||||
});
|
||||
|
||||
it("a heartbeat from a screen showing a native image is recorded", async () => {
|
||||
const display = controller();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
|
||||
const [viewer] = await store.listViewers();
|
||||
expect(viewer).toBeDefined();
|
||||
// What the display reported is what the roster now holds — which is only true if the server
|
||||
// took the heartbeat, rather than refusing it and leaving the session's values in place.
|
||||
expect(viewer?.reportedSelectionId).not.toBeNull();
|
||||
expect(viewer?.reportedProviderId).toBe(SIGNAGE_NATIVE_PROVIDER_ID);
|
||||
expect(viewer?.reportedContributionId).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,307 @@
|
||||
// @vitest-environment happy-dom
|
||||
import type { ModuleUiHostContext } from "@ekklesia/module-ui-sdk";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
createMemoryMediaCache,
|
||||
createMemoryStore,
|
||||
type SignageLocalStore,
|
||||
} from "../../src/browser/storage.js";
|
||||
import {
|
||||
createDisplayController,
|
||||
type DisplayChannelStateView,
|
||||
} from "../../src/display/controller.js";
|
||||
import { createFakeHost, type FakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
* A display never reaches a dead end.
|
||||
*
|
||||
* Every network path a display depends on — registering, fetching state, realtime — can fail once,
|
||||
* as a kiosk that boots before its network settles or an API that restarts will make it. Each must
|
||||
* be tried again, with backoff, until it works, and the display must then be exactly as live as if
|
||||
* nothing had happened. None of it may need a person to reload a television.
|
||||
*
|
||||
* Time is virtual: every timer the controller schedules goes through the queue below.
|
||||
*/
|
||||
|
||||
const SESSION = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "Foyer",
|
||||
};
|
||||
|
||||
function selection(id: string) {
|
||||
return {
|
||||
availableUntilMs: null,
|
||||
deadlineAtMs: 5000,
|
||||
durationMs: 5000,
|
||||
id,
|
||||
itemId: `image-${id}`,
|
||||
itemRevision: "rev-1",
|
||||
media: {
|
||||
display: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 1080,
|
||||
url: `https://cdn.invalid/${id}`,
|
||||
width: 1920,
|
||||
},
|
||||
thumbnail: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 270,
|
||||
url: `https://cdn.invalid/${id}-t`,
|
||||
width: 480,
|
||||
},
|
||||
},
|
||||
payload: { kind: "native-image" },
|
||||
presentation: null,
|
||||
providerId: "signage.native-images",
|
||||
renderer: { kind: "native-image" as const },
|
||||
revision: 1,
|
||||
scene: {
|
||||
backgroundColor: "#000000",
|
||||
backgroundImage: false,
|
||||
backgroundMode: "none" as const,
|
||||
blurPixels: 0,
|
||||
darkenOpacity: 0,
|
||||
fit: "fill" as const,
|
||||
shadow: false,
|
||||
},
|
||||
slotId: "slot-1",
|
||||
stale: false,
|
||||
startedAtMs: 0,
|
||||
withdrawn: false,
|
||||
};
|
||||
}
|
||||
|
||||
function channelState(revision = 3): DisplayChannelStateView {
|
||||
const current = selection("sel-1");
|
||||
return {
|
||||
channel: { groupId: "group-1", id: "chan-1", key: "default" },
|
||||
crossfadeMs: 0,
|
||||
current,
|
||||
playback: {
|
||||
activeTimelineId: "timeline-1",
|
||||
blackout: false,
|
||||
currentSelectionId: current.id,
|
||||
currentSlotId: current.slotId,
|
||||
deadlineAtMs: 5000,
|
||||
pendingTimelineId: null,
|
||||
remainingMs: 5000,
|
||||
revision,
|
||||
selectionRevision: 1,
|
||||
startedAtMs: 0,
|
||||
transport: "playing",
|
||||
},
|
||||
selections: [current],
|
||||
serverNowMs: 0,
|
||||
staticHold: null,
|
||||
timeline: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Server behaviour that a test can change mid-run. */
|
||||
interface Server {
|
||||
sessionFailures: number;
|
||||
stateFailing: boolean;
|
||||
sessionRequests: number;
|
||||
stateRequests: number;
|
||||
}
|
||||
|
||||
describe("a display recovers from every failed request without a reload", () => {
|
||||
let clock: number;
|
||||
let timers: Map<number, { at: number; run: () => void }>;
|
||||
let nextTimer: number;
|
||||
let root: HTMLElement;
|
||||
let local: SignageLocalStore;
|
||||
let server: Server;
|
||||
let host: FakeHost;
|
||||
let subscriptions: { onStatus?: (status: string) => void }[];
|
||||
|
||||
beforeEach(() => {
|
||||
clock = 0;
|
||||
timers = new Map();
|
||||
nextTimer = 1;
|
||||
root = document.createElement("div");
|
||||
document.body.append(root);
|
||||
local = createMemoryStore();
|
||||
server = { sessionFailures: 0, sessionRequests: 0, stateFailing: false, stateRequests: 0 };
|
||||
subscriptions = [];
|
||||
host = createFakeHost({
|
||||
permissions: ["signage.display.view"],
|
||||
routes: [
|
||||
{
|
||||
method: "POST",
|
||||
path: "viewers/session",
|
||||
respond: () => {
|
||||
server.sessionRequests += 1;
|
||||
if (server.sessionFailures > 0) {
|
||||
server.sessionFailures -= 1;
|
||||
throw new TypeError("Failed to fetch");
|
||||
}
|
||||
return jsonResponse(SESSION);
|
||||
},
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channels/chan-1/display-state",
|
||||
respond: () => {
|
||||
server.stateRequests += 1;
|
||||
if (server.stateFailing) {
|
||||
throw new TypeError("Failed to fetch");
|
||||
}
|
||||
return jsonResponse(channelState());
|
||||
},
|
||||
},
|
||||
{ method: "POST", path: /^viewers\/.*\/heartbeat$/u, respond: () => jsonResponse({}) },
|
||||
],
|
||||
});
|
||||
Object.assign(host.context, {
|
||||
realtime: {
|
||||
subscribe: (_channel: string, handlers: { onStatus?: (status: string) => void }) => {
|
||||
subscriptions.push(handlers);
|
||||
return { close: () => undefined };
|
||||
},
|
||||
} satisfies Pick<ModuleUiHostContext["realtime"], "subscribe"> as never,
|
||||
});
|
||||
});
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
for (let index = 0; index < 20; index += 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves virtual time forward, firing every timer that falls due, in order. */
|
||||
async function advance(ms: number): Promise<void> {
|
||||
const end = clock + ms;
|
||||
for (;;) {
|
||||
const due = [...timers]
|
||||
.filter(([, timer]) => timer.at <= end)
|
||||
.sort((left, right) => left[1].at - right[1].at)[0];
|
||||
if (!due) {
|
||||
break;
|
||||
}
|
||||
timers.delete(due[0]);
|
||||
clock = due[1].at;
|
||||
due[1].run();
|
||||
await settle();
|
||||
}
|
||||
clock = end;
|
||||
}
|
||||
|
||||
function build() {
|
||||
return createDisplayController({
|
||||
clearTimer: (handle) => timers.delete(handle as number),
|
||||
context: host.context,
|
||||
decodeImage: () => Promise.resolve(),
|
||||
media: createMemoryMediaCache(),
|
||||
newViewerKey: () => "viewer-fixed-key-0001",
|
||||
now: () => clock,
|
||||
root,
|
||||
setTimer: (run, delayMs) => {
|
||||
const id = nextTimer;
|
||||
nextTimer += 1;
|
||||
timers.set(id, { at: clock + delayMs, run });
|
||||
return id;
|
||||
},
|
||||
store: local,
|
||||
});
|
||||
}
|
||||
|
||||
/** One ordinary live run, so the display has a persisted snapshot to continue from, exactly as a
|
||||
* screen that has been on the wall for a while does. */
|
||||
async function runOnceLive(): Promise<void> {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
timers.clear();
|
||||
}
|
||||
|
||||
it("registers once the server answers, after its first registration failed", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 1;
|
||||
const sessionsBefore = server.sessionRequests;
|
||||
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
// Continuing from its own state while it cannot register: the honest banner.
|
||||
expect(root.dataset.offline).toBe("true");
|
||||
|
||||
await advance(60_000);
|
||||
|
||||
expect(server.sessionRequests - sessionsBefore).toBeGreaterThanOrEqual(2);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
expect(subscriptions.length).toBeGreaterThanOrEqual(2);
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("keeps retrying registration with backoff, and never gives up", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 8;
|
||||
const sessionsBefore = server.sessionRequests;
|
||||
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
// Eight failures back off for at most 1 + 2 + 4 + 8 + 16 + 32 + 60 + 60 seconds, the last two at
|
||||
// the one-minute ceiling. Five virtual minutes is enough for all of them and the success after.
|
||||
await advance(5 * 60_000);
|
||||
|
||||
expect(server.sessionRequests - sessionsBefore).toBe(9);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("retries a failed state refresh until the server answers, with no realtime nudge", async () => {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
|
||||
// The slot's deadline refresh fails, as it would mid-restart. Realtime says nothing.
|
||||
server.stateFailing = true;
|
||||
await advance(6_000);
|
||||
expect(root.dataset.offline).toBe("true");
|
||||
const failedRequests = server.stateRequests;
|
||||
|
||||
server.stateFailing = false;
|
||||
await advance(120_000);
|
||||
|
||||
expect(server.stateRequests).toBeGreaterThan(failedRequests);
|
||||
expect(root.dataset.offline).toBe("false");
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("subscribes again when the host reports its realtime stream closed for good", async () => {
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
expect(subscriptions).toHaveLength(1);
|
||||
|
||||
subscriptions[0]?.onStatus?.("closed");
|
||||
await settle();
|
||||
await advance(60_000);
|
||||
|
||||
expect(subscriptions.length).toBeGreaterThanOrEqual(2);
|
||||
await display.stop();
|
||||
});
|
||||
|
||||
it("schedules nothing after it is stopped", async () => {
|
||||
await runOnceLive();
|
||||
server.sessionFailures = 3;
|
||||
const display = build();
|
||||
await display.start();
|
||||
await settle();
|
||||
await display.stop();
|
||||
const sessionsAtStop = server.sessionRequests;
|
||||
|
||||
await advance(5 * 60_000);
|
||||
|
||||
expect(server.sessionRequests).toBe(sessionsAtStop);
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
type DisplayChannelStateView,
|
||||
type DisplayController,
|
||||
} from "../../src/display/controller.js";
|
||||
import type { ViewerSessionResponse } from "../../src/shared/display-protocol.js";
|
||||
import { createFakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
@@ -114,12 +115,14 @@ function state(overrides: Partial<DisplayChannelStateView> = {}): DisplayChannel
|
||||
};
|
||||
}
|
||||
|
||||
const SESSION = {
|
||||
/** Typed as the shared protocol message, so a stub cannot drift from what the server sends. */
|
||||
const SESSION: ViewerSessionResponse = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "Foyer",
|
||||
};
|
||||
|
||||
describe("display controller", () => {
|
||||
|
||||
@@ -3,7 +3,12 @@ import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { SignageDashboard } from "../../src/ui/SignageDashboard.js";
|
||||
import { createFakeHost, errorResponse, FAKE_SETTINGS, jsonResponse } from "./support/fake-host.js";
|
||||
import {
|
||||
createFakeHost,
|
||||
errorResponse,
|
||||
FAKE_SETTINGS,
|
||||
jsonResponse,
|
||||
} from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
* The management UI's behaviour, mounted as React rather than inspected as source.
|
||||
@@ -14,10 +19,28 @@ import { createFakeHost, errorResponse, FAKE_SETTINGS, jsonResponse } from "./su
|
||||
*/
|
||||
|
||||
// React needs this to run effects the way a browser does.
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
(
|
||||
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
|
||||
).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
let container: HTMLElement;
|
||||
let root: Root;
|
||||
const DISPLAY_SETUP_URL = "https://api.example.test/display/signage";
|
||||
const copiedText: string[] = [];
|
||||
|
||||
function dashboard(
|
||||
context: Parameters<typeof SignageDashboard>[0]["context"],
|
||||
): React.ReactElement {
|
||||
return (
|
||||
<SignageDashboard
|
||||
context={context}
|
||||
copyText={(value) => {
|
||||
copiedText.push(value);
|
||||
return Promise.resolve();
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function render(element: React.ReactElement): Promise<void> {
|
||||
await act(async () => {
|
||||
@@ -70,7 +93,9 @@ function buttonNamed(label: string): HTMLButtonElement | undefined {
|
||||
}
|
||||
|
||||
const GROUP = {
|
||||
channels: [{ id: "chan-1", isDefault: true, key: "default", name: "Default" }],
|
||||
channels: [
|
||||
{ id: "chan-1", isDefault: true, key: "default", name: "Default" },
|
||||
],
|
||||
id: "group-1",
|
||||
name: "Main",
|
||||
playback: {
|
||||
@@ -120,7 +145,18 @@ const PLAYBACK_DETAIL = {
|
||||
snapshot: GROUP.playback,
|
||||
};
|
||||
|
||||
const TIMELINE = {
|
||||
description: null,
|
||||
eligibleFrom: null,
|
||||
eligibleUntil: null,
|
||||
id: "timeline-1",
|
||||
name: "Sunday morning",
|
||||
revision: 3,
|
||||
updatedAt: "2026-08-30T15:00:00.000Z",
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
copiedText.length = 0;
|
||||
container = document.createElement("div");
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
@@ -139,9 +175,21 @@ describe("Signage dashboard", () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.playback.control"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
@@ -158,12 +206,14 @@ describe("Signage dashboard", () => {
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
|
||||
expect(container.querySelector("[data-testid='signage-current']")?.textContent).toContain(
|
||||
"welcome",
|
||||
);
|
||||
expect(container.querySelector("[data-testid='signage-remaining']")?.textContent).toBe("4s");
|
||||
expect(
|
||||
container.querySelector("[data-testid='signage-current']")?.textContent,
|
||||
).toContain("welcome");
|
||||
expect(
|
||||
container.querySelector("[data-testid='signage-remaining']")?.textContent,
|
||||
).toBe("4s");
|
||||
|
||||
await click(buttonNamed("Pause"));
|
||||
await click(buttonNamed("Next"));
|
||||
@@ -180,45 +230,200 @@ describe("Signage dashboard", () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
|
||||
// The current slide is still legible; the buttons that would be refused are simply not offered.
|
||||
expect(container.querySelector("[data-testid='signage-current']")).not.toBeNull();
|
||||
expect(container.querySelector("[data-testid='signage-controls']")).toBeNull();
|
||||
expect(
|
||||
container.querySelector("[data-testid='signage-current']"),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
container.querySelector("[data-testid='signage-controls']"),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("shows which timeline remains active after the dashboard data is reloaded", async () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.playback.control"],
|
||||
routes: [
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [TIMELINE] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
respond: () => jsonResponse({ providers: [] }),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(dashboard(host.context));
|
||||
expect(container.textContent).toContain("Active: Sunday morning");
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(candidate) => candidate.textContent === "Timelines",
|
||||
),
|
||||
);
|
||||
|
||||
expect(container.textContent).toContain("Active in Main");
|
||||
expect(buttonNamed("Active")?.disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps a failed activation visible instead of pretending it succeeded", async () => {
|
||||
const inactiveGroup = {
|
||||
...GROUP,
|
||||
playback: {
|
||||
...GROUP.playback,
|
||||
activeTimelineId: null,
|
||||
currentSelectionId: null,
|
||||
},
|
||||
};
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.playback.control"],
|
||||
routes: [
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [inactiveGroup] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [TIMELINE] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
respond: () => jsonResponse({ providers: [] }),
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
path: "playback/group-1/activate",
|
||||
respond: () =>
|
||||
errorResponse(
|
||||
"SIGNAGE_CONFLICT",
|
||||
"The request conflicts with the current state.",
|
||||
409,
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(candidate) => candidate.textContent === "Timelines",
|
||||
),
|
||||
);
|
||||
await click(buttonNamed("Activate"));
|
||||
|
||||
expect(container.textContent).toContain("Sunday morning");
|
||||
expect(container.querySelector("[role='alert']")?.textContent).toContain(
|
||||
"The request conflicts with the current state.",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows Signage's own sanitized reason when a save is refused", async () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.timelines.manage"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{ method: "GET", path: "providers", respond: () => jsonResponse({ providers: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
respond: () => jsonResponse({ providers: [] }),
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
path: "timelines",
|
||||
respond: () => errorResponse("SIGNAGE_INVALID_REQUEST", "The request is not valid.", 400),
|
||||
respond: () =>
|
||||
errorResponse(
|
||||
"SIGNAGE_INVALID_REQUEST",
|
||||
"The request is not valid.",
|
||||
400,
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Timelines",
|
||||
),
|
||||
);
|
||||
|
||||
const input = container.querySelector("input[type='text']") as HTMLInputElement;
|
||||
const input = container.querySelector(
|
||||
"input[type='text']",
|
||||
) as HTMLInputElement;
|
||||
await type(input, "Sunday morning");
|
||||
await click(buttonNamed("Create"));
|
||||
|
||||
@@ -232,10 +437,26 @@ describe("Signage dashboard", () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.timelines.manage"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "providers", respond: () => jsonResponse({ providers: [] }) },
|
||||
{ method: "GET", path: "images", respond: () => jsonResponse({ images: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
respond: () => jsonResponse({ providers: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "images",
|
||||
respond: () => jsonResponse({ images: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
@@ -275,7 +496,7 @@ describe("Signage dashboard", () => {
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Timelines",
|
||||
@@ -283,7 +504,9 @@ describe("Signage dashboard", () => {
|
||||
);
|
||||
await click(buttonNamed("Sunday morning"));
|
||||
|
||||
expect(container.querySelector("[data-testid='signage-timeline-editor']")).not.toBeNull();
|
||||
expect(
|
||||
container.querySelector("[data-testid='signage-timeline-editor']"),
|
||||
).not.toBeNull();
|
||||
expect(container.textContent).toContain("This timeline has no slots");
|
||||
});
|
||||
|
||||
@@ -294,10 +517,26 @@ describe("Signage dashboard", () => {
|
||||
contributions: [],
|
||||
permissions: ["signage.view"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
@@ -325,7 +564,7 @@ describe("Signage dashboard", () => {
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Providers",
|
||||
@@ -340,15 +579,35 @@ describe("Signage dashboard", () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{ method: "GET", path: "providers", respond: () => jsonResponse({ providers: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "providers",
|
||||
respond: () => jsonResponse({ providers: [] }),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Providers",
|
||||
@@ -356,17 +615,35 @@ describe("Signage dashboard", () => {
|
||||
);
|
||||
|
||||
expect(container.textContent).toContain("No content providers registered");
|
||||
expect(container.textContent).toContain("Signage works on its own with native images");
|
||||
expect(container.textContent).toContain(
|
||||
"Signage works on its own with native images",
|
||||
);
|
||||
});
|
||||
|
||||
it("shows the display roster with online state and offline readiness", async () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.displays.manage"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "viewers",
|
||||
@@ -378,7 +655,11 @@ describe("Signage dashboard", () => {
|
||||
channelId: "chan-1",
|
||||
deviceId: null,
|
||||
id: "viewer-1",
|
||||
lastError: { atMs: Date.now(), code: "SLIDE_DECODE_FAILED", detail: null },
|
||||
lastError: {
|
||||
atMs: Date.now(),
|
||||
code: "SLIDE_DECODE_FAILED",
|
||||
detail: null,
|
||||
},
|
||||
lastSeenAtMs: Date.now() - 4000,
|
||||
name: "Lobby north",
|
||||
offlineReady: true,
|
||||
@@ -394,27 +675,137 @@ describe("Signage dashboard", () => {
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find((tab) => tab.textContent === "Displays"),
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Displays",
|
||||
),
|
||||
);
|
||||
|
||||
expect(container.textContent).toContain("Online");
|
||||
expect(container.textContent).toContain("12 cached");
|
||||
const display = container.querySelector(
|
||||
"[data-testid='signage-display-viewer-1']",
|
||||
);
|
||||
expect(display?.closest(".signage-channel")?.textContent).toContain(
|
||||
"Default",
|
||||
);
|
||||
// A sanitized code, never a stack or a message a browser happened to have.
|
||||
expect(container.textContent).toContain("SLIDE_DECODE_FAILED");
|
||||
});
|
||||
|
||||
it("explains display registration and deletes a channel group only after confirmation", async () => {
|
||||
const secondGroup = {
|
||||
...GROUP,
|
||||
channels: [
|
||||
{ id: "chan-2", isDefault: true, key: "default", name: "Default" },
|
||||
],
|
||||
id: "group-2",
|
||||
name: "Foyer",
|
||||
playback: { ...GROUP.playback, groupId: "group-2" },
|
||||
};
|
||||
let currentGroups = [GROUP, secondGroup];
|
||||
const deleted: string[] = [];
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.displays.manage"],
|
||||
routes: [
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: currentGroups }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "viewers",
|
||||
respond: () => jsonResponse({ viewers: [] }),
|
||||
},
|
||||
{
|
||||
method: "DELETE",
|
||||
path: "channel-groups/group-1",
|
||||
respond: ({ path }) => {
|
||||
deleted.push(path);
|
||||
currentGroups = [secondGroup];
|
||||
return new Response(null, { status: 204 });
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(candidate) => candidate.textContent === "Displays",
|
||||
),
|
||||
);
|
||||
|
||||
const setupLink = [...container.querySelectorAll("a")].find(
|
||||
(candidate) => candidate.textContent?.trim() === "Open display setup",
|
||||
);
|
||||
expect(setupLink?.href).toBe(DISPLAY_SETUP_URL);
|
||||
expect(setupLink?.target).toBe("_blank");
|
||||
expect(setupLink?.rel).toContain("noopener");
|
||||
await click(buttonNamed("Copy URL"));
|
||||
expect(copiedText).toEqual([DISPLAY_SETUP_URL]);
|
||||
expect(container.textContent).toContain("Display setup URL copied.");
|
||||
expect(container.textContent).toContain("Channel groups and displays");
|
||||
expect(container.textContent).toContain("Audience channels");
|
||||
expect(container.textContent).toContain("Channel name");
|
||||
expect(container.textContent).toContain("Audience key");
|
||||
expect(container.textContent).toContain(
|
||||
"Advanced: lowercase ID sent to content providers",
|
||||
);
|
||||
await click(buttonNamed("Delete group"));
|
||||
expect(deleted).toEqual([]);
|
||||
expect(container.textContent).toContain("Displays assigned here will move");
|
||||
await click(buttonNamed("Confirm delete"));
|
||||
expect(deleted).toEqual(["channel-groups/group-1"]);
|
||||
});
|
||||
|
||||
it("uploads one request per file and reports each one's own outcome", async () => {
|
||||
const uploaded: string[] = [];
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view", "signage.assets.manage"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{ method: "GET", path: "playback/group-1", respond: () => jsonResponse(PLAYBACK_DETAIL) },
|
||||
{ method: "GET", path: "images", respond: () => jsonResponse({ images: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () => jsonResponse(PLAYBACK_DETAIL),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "images",
|
||||
respond: () => jsonResponse({ images: [] }),
|
||||
},
|
||||
{
|
||||
method: "POST",
|
||||
path: /^images\?/u,
|
||||
@@ -432,9 +823,11 @@ describe("Signage dashboard", () => {
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
await click(
|
||||
[...container.querySelectorAll("[role='tab']")].find((tab) => tab.textContent === "Images"),
|
||||
[...container.querySelectorAll("[role='tab']")].find(
|
||||
(tab) => tab.textContent === "Images",
|
||||
),
|
||||
);
|
||||
|
||||
const input = container.querySelector(
|
||||
@@ -464,29 +857,49 @@ describe("Signage dashboard", () => {
|
||||
const uploads = container.querySelector("[data-testid='signage-uploads']");
|
||||
expect(uploads?.textContent).toContain("done");
|
||||
expect(uploads?.textContent).toContain("failed");
|
||||
expect(uploads?.textContent).toContain("The uploaded file is not a decodable image.");
|
||||
expect(uploads?.textContent).toContain(
|
||||
"The uploaded file is not a decodable image.",
|
||||
);
|
||||
});
|
||||
|
||||
it("stays on screen when one panel's data cannot be loaded", async () => {
|
||||
const host = createFakeHost({
|
||||
permissions: ["signage.view"],
|
||||
routes: [
|
||||
{ method: "GET", path: "settings", respond: () => jsonResponse(FAKE_SETTINGS) },
|
||||
{ method: "GET", path: "channel-groups", respond: () => jsonResponse({ groups: [GROUP] }) },
|
||||
{ method: "GET", path: "timelines", respond: () => jsonResponse({ timelines: [] }) },
|
||||
{
|
||||
method: "GET",
|
||||
path: "settings",
|
||||
respond: () => jsonResponse(FAKE_SETTINGS),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "channel-groups",
|
||||
respond: () => jsonResponse({ groups: [GROUP] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "timelines",
|
||||
respond: () => jsonResponse({ timelines: [] }),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
path: "playback/group-1",
|
||||
respond: () =>
|
||||
errorResponse("SIGNAGE_OPERATION_FAILED", "The operation could not be completed.", 500),
|
||||
errorResponse(
|
||||
"SIGNAGE_OPERATION_FAILED",
|
||||
"The operation could not be completed.",
|
||||
500,
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await render(<SignageDashboard context={host.context} />);
|
||||
await render(dashboard(host.context));
|
||||
|
||||
expect(container.textContent).toContain("Signage could not load this");
|
||||
expect(container.textContent).toContain("The operation could not be completed.");
|
||||
expect(container.textContent).toContain(
|
||||
"The operation could not be completed.",
|
||||
);
|
||||
// The rest of the dashboard is still usable: one failing panel is not a failed screen.
|
||||
expect(container.querySelectorAll("[role='tab']").length).toBe(5);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { createBrowserMediaCache, type SignageMediaCache } from "../../src/browser/storage.js";
|
||||
|
||||
/**
|
||||
* The Cache Storage media cache hands out object URLs, and every live one pins its blob in the
|
||||
* browser until it is revoked.
|
||||
*
|
||||
* Every state refresh looks up every cached slide, so a cache that minted a fresh URL per lookup
|
||||
* leaked one blob per slide per refresh. In a real browser that exhausted blob storage within
|
||||
* minutes: the display's own state requests then failed with `net::ERR_INSUFFICIENT_RESOURCES` and
|
||||
* it fell back to its offline banner on a perfectly good network.
|
||||
*/
|
||||
|
||||
/** Just enough Cache Storage: one named cache, keyed by request URL. */
|
||||
function fakeCacheStorage() {
|
||||
const entries = new Map<string, { body: ArrayBuffer; type: string }>();
|
||||
const cache = {
|
||||
async delete(request: Request | string): Promise<boolean> {
|
||||
return entries.delete(typeof request === "string" ? request : request.url);
|
||||
},
|
||||
async keys(): Promise<Request[]> {
|
||||
return [...entries.keys()].map((url) => new Request(url));
|
||||
},
|
||||
async match(request: Request | string): Promise<Response | undefined> {
|
||||
const entry = entries.get(typeof request === "string" ? request : request.url);
|
||||
return entry
|
||||
? new Response(entry.body, { headers: { "content-type": entry.type } })
|
||||
: undefined;
|
||||
},
|
||||
async put(request: Request | string, response: Response): Promise<void> {
|
||||
entries.set(typeof request === "string" ? request : request.url, {
|
||||
body: await response.arrayBuffer(),
|
||||
type: response.headers.get("content-type") ?? "application/octet-stream",
|
||||
});
|
||||
},
|
||||
};
|
||||
return { open: async () => cache } as unknown as CacheStorage;
|
||||
}
|
||||
|
||||
describe("Signage's media cache and object URLs", () => {
|
||||
const realCreate = URL.createObjectURL;
|
||||
const realRevoke = URL.revokeObjectURL;
|
||||
let live: Set<string>;
|
||||
let media: SignageMediaCache;
|
||||
|
||||
beforeEach(() => {
|
||||
live = new Set();
|
||||
let next = 0;
|
||||
URL.createObjectURL = () => {
|
||||
next += 1;
|
||||
const url = `blob:test/${next}`;
|
||||
live.add(url);
|
||||
return url;
|
||||
};
|
||||
URL.revokeObjectURL = (url: string) => {
|
||||
live.delete(url);
|
||||
};
|
||||
media = createBrowserMediaCache({
|
||||
caches: fakeCacheStorage(),
|
||||
fetch: async () =>
|
||||
new Response(new Uint8Array([1, 2, 3]), { headers: { "content-type": "image/webp" } }),
|
||||
location: { origin: "https://api.example.test" },
|
||||
} as unknown as typeof globalThis);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
URL.createObjectURL = realCreate;
|
||||
URL.revokeObjectURL = realRevoke;
|
||||
});
|
||||
|
||||
const keys = ["slide/a", "slide/b", "slide/c"];
|
||||
|
||||
it("keeps one live object URL per cached slide, however often it is looked up", async () => {
|
||||
for (const key of keys) {
|
||||
await media.store(key, `https://files.example.test/${key}?sig=1`);
|
||||
}
|
||||
// A state refresh looks every slide up again; a long-running display does this for months.
|
||||
for (let refresh = 0; refresh < 100; refresh += 1) {
|
||||
for (const key of keys) {
|
||||
await media.find(key);
|
||||
}
|
||||
}
|
||||
expect(live.size).toBe(keys.length);
|
||||
});
|
||||
|
||||
it("hands out the same URL for the same bytes", async () => {
|
||||
await media.store("slide/a", "https://files.example.test/a?sig=1");
|
||||
const first = await media.find("slide/a");
|
||||
const second = await media.find("slide/a");
|
||||
expect(first).toBeDefined();
|
||||
expect(second).toBe(first);
|
||||
});
|
||||
|
||||
it("revokes a pruned slide's URL", async () => {
|
||||
for (const key of keys) {
|
||||
await media.store(key, `https://files.example.test/${key}?sig=1`);
|
||||
await media.find(key);
|
||||
}
|
||||
await media.prune(["slide/a"]);
|
||||
expect(live.size).toBe(1);
|
||||
expect(await media.find("slide/b")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("revokes the URL it replaces when a slide is stored again", async () => {
|
||||
await media.store("slide/a", "https://files.example.test/a?sig=1");
|
||||
await media.store("slide/a", "https://files.example.test/a?sig=2");
|
||||
await media.find("slide/a");
|
||||
expect(live.size).toBe(1);
|
||||
});
|
||||
|
||||
it("releases every URL it handed out when the display stops", async () => {
|
||||
for (const key of keys) {
|
||||
await media.store(key, `https://files.example.test/${key}?sig=1`);
|
||||
await media.find(key);
|
||||
}
|
||||
media.release();
|
||||
expect(live.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
createDisplayController,
|
||||
type DisplayChannelStateView,
|
||||
} from "../../src/display/controller.js";
|
||||
import type { DisplaySelection, ViewerSessionResponse } from "../../src/shared/display-protocol.js";
|
||||
import { createFakeHost, jsonResponse } from "./support/fake-host.js";
|
||||
|
||||
/**
|
||||
@@ -309,14 +310,26 @@ describe("a display that loses its network", () => {
|
||||
}
|
||||
}
|
||||
|
||||
function nativeSelection(id: string, slotId: string): SceneSelection {
|
||||
/** A native selection exactly as the server sends one in channel state. */
|
||||
function nativeSelection(id: string, slotId: string): DisplaySelection {
|
||||
return {
|
||||
...selection({ id, slotId }),
|
||||
media: {
|
||||
display: { url: `https://cdn.invalid/${id}?sig=a` },
|
||||
thumbnail: { url: `https://cdn.invalid/${id}-t?sig=a` },
|
||||
display: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 1080,
|
||||
url: `https://cdn.invalid/${id}?sig=a`,
|
||||
width: 1920,
|
||||
},
|
||||
} as SceneSelection;
|
||||
thumbnail: {
|
||||
expiresAtMs: 900_000,
|
||||
height: 270,
|
||||
url: `https://cdn.invalid/${id}-t?sig=a`,
|
||||
width: 480,
|
||||
},
|
||||
},
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
function state(currentId: string): DisplayChannelStateView {
|
||||
@@ -373,7 +386,8 @@ describe("a display that loses its network", () => {
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
}),
|
||||
viewerName: "Foyer",
|
||||
} satisfies ViewerSessionResponse),
|
||||
},
|
||||
{
|
||||
method: "GET",
|
||||
|
||||
@@ -37,7 +37,11 @@ export function jsonResponse(body: unknown, status = 200): Response {
|
||||
});
|
||||
}
|
||||
|
||||
export function errorResponse(code: string, message: string, status = 400): Response {
|
||||
export function errorResponse(
|
||||
code: string,
|
||||
message: string,
|
||||
status = 400,
|
||||
): Response {
|
||||
return jsonResponse({ code, message }, status);
|
||||
}
|
||||
|
||||
@@ -45,6 +49,7 @@ export interface FakeHostOptions {
|
||||
readonly permissions: readonly string[];
|
||||
readonly routes: readonly FakeHostRoute[];
|
||||
readonly contributions?: readonly ModuleContributionDescriptor[];
|
||||
readonly displayUrl?: string;
|
||||
readonly principal?: ModuleUiHostContext["principal"];
|
||||
readonly mount?: (
|
||||
options: MountModuleContributionOptions,
|
||||
@@ -69,15 +74,24 @@ export function createFakeHost(options: FakeHostOptions): FakeHost {
|
||||
return route.respond({ init, path: normalized });
|
||||
}
|
||||
}
|
||||
return errorResponse("SIGNAGE_NOT_FOUND", "The requested resource was not found.", 404);
|
||||
return errorResponse(
|
||||
"SIGNAGE_NOT_FOUND",
|
||||
"The requested resource was not found.",
|
||||
404,
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
const contributions: ModuleUiContributions = {
|
||||
list: (capabilityId) =>
|
||||
capabilityId === "signage.slide-renderer" ? (options.contributions ?? []) : [],
|
||||
capabilityId === "signage.slide-renderer"
|
||||
? (options.contributions ?? [])
|
||||
: [],
|
||||
async mount(mountOptions) {
|
||||
mounted.push({ contributionId: mountOptions.contributionId, input: mountOptions.input });
|
||||
mounted.push({
|
||||
contributionId: mountOptions.contributionId,
|
||||
input: mountOptions.input,
|
||||
});
|
||||
if (options.mount) {
|
||||
return options.mount(mountOptions);
|
||||
}
|
||||
@@ -95,8 +109,13 @@ export function createFakeHost(options: FakeHostOptions): FakeHost {
|
||||
context: {
|
||||
api,
|
||||
contributions,
|
||||
display: {
|
||||
url: options.displayUrl ?? "https://api.example.test/display/signage",
|
||||
},
|
||||
moduleId: "signage",
|
||||
permissions: { has: (permission) => options.permissions.includes(permission) },
|
||||
permissions: {
|
||||
has: (permission) => options.permissions.includes(permission),
|
||||
},
|
||||
principal: options.principal ?? { kind: "anonymous" },
|
||||
realtime: { subscribe: () => ({ close: () => undefined }) },
|
||||
},
|
||||
@@ -108,7 +127,7 @@ export function createFakeHost(options: FakeHostOptions): FakeHost {
|
||||
/** The settings payload every screen loads first. */
|
||||
export const FAKE_SETTINGS = Object.freeze({
|
||||
crossfadeMs: 1000,
|
||||
moduleVersion: "0.1.0",
|
||||
moduleVersion: "0.1.2",
|
||||
nativeImageDurationMs: 7000,
|
||||
nativePresentation: {
|
||||
backgroundColor: "#000000",
|
||||
@@ -118,5 +137,10 @@ export const FAKE_SETTINGS = Object.freeze({
|
||||
},
|
||||
rendererInputVersion: "1.0.0",
|
||||
timezone: "America/Chicago",
|
||||
uploads: { batchMaxFiles: 20, concurrency: 3, maxBytes: 26_214_400, maxPixels: 40_000_000 },
|
||||
uploads: {
|
||||
batchMaxFiles: 20,
|
||||
concurrency: 3,
|
||||
maxBytes: 26_214_400,
|
||||
maxPixels: 40_000_000,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DISPLAY_ERROR_DETAIL_MAX,
|
||||
parseDisplayHeartbeat,
|
||||
parseViewerSessionRequest,
|
||||
parseViewerSessionResponse,
|
||||
} from "../src/shared/display-protocol.js";
|
||||
|
||||
/**
|
||||
* The rules every display message follows, pinned one by one, because the production failure was
|
||||
* exactly a disagreement about one of them.
|
||||
*/
|
||||
|
||||
const FULL_HEARTBEAT = {
|
||||
cachedAssetCount: 3,
|
||||
error: null,
|
||||
offlineReady: true,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: 4,
|
||||
reportedProviderId: "signage.native-images",
|
||||
reportedSelectionId: "sel-1",
|
||||
reportedTimelineId: "timeline-1",
|
||||
};
|
||||
|
||||
describe("display heartbeat", () => {
|
||||
it("accepts null for every nullable field: null is a value, not an omission", () => {
|
||||
const result = parseDisplayHeartbeat({
|
||||
...FULL_HEARTBEAT,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: null,
|
||||
reportedProviderId: null,
|
||||
reportedSelectionId: null,
|
||||
reportedTimelineId: null,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
...FULL_HEARTBEAT,
|
||||
reportedContributionId: null,
|
||||
reportedPlaybackRevision: null,
|
||||
reportedProviderId: null,
|
||||
reportedSelectionId: null,
|
||||
reportedTimelineId: null,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("treats an absent field as not reported, so the receiver keeps what it had", () => {
|
||||
const result = parseDisplayHeartbeat({ offlineReady: false });
|
||||
expect(result).toEqual({ ok: true, value: { offlineReady: false } });
|
||||
});
|
||||
|
||||
it("ignores a field it does not know, so a newer display is never refused by an older server", () => {
|
||||
const result = parseDisplayHeartbeat({ ...FULL_HEARTBEAT, reportedSomethingNew: { a: 1 } });
|
||||
expect(result).toEqual({ ok: true, value: FULL_HEARTBEAT });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["cachedAssetCount", null],
|
||||
["cachedAssetCount", -1],
|
||||
["cachedAssetCount", 1.5],
|
||||
["offlineReady", null],
|
||||
["offlineReady", "yes"],
|
||||
["reportedSelectionId", ""],
|
||||
["reportedSelectionId", "x".repeat(65)],
|
||||
["reportedProviderId", 7],
|
||||
["reportedPlaybackRevision", -1],
|
||||
["error", { code: "" }],
|
||||
["error", { code: "BAD CODE" }],
|
||||
["error", { code: "OK", detail: "y".repeat(DISPLAY_ERROR_DETAIL_MAX + 1) }],
|
||||
["error", "SLIDE_UNRENDERABLE"],
|
||||
])("refuses %s = %j, naming that field and nothing else", (field, value) => {
|
||||
expect(parseDisplayHeartbeat({ ...FULL_HEARTBEAT, [field]: value })).toEqual({
|
||||
field,
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts a reported error with or without detail", () => {
|
||||
expect(parseDisplayHeartbeat({ error: { code: "SLIDE_UNRENDERABLE", detail: null } })).toEqual({
|
||||
ok: true,
|
||||
value: { error: { code: "SLIDE_UNRENDERABLE", detail: null } },
|
||||
});
|
||||
expect(parseDisplayHeartbeat({ error: { code: "SLIDE_UNRENDERABLE" } })).toEqual({
|
||||
ok: true,
|
||||
value: { error: { code: "SLIDE_UNRENDERABLE", detail: null } },
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses something that is not an object at all", () => {
|
||||
for (const body of [null, [], "heartbeat", 3]) {
|
||||
expect(parseDisplayHeartbeat(body)).toEqual({ field: "body", ok: false });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("viewer session", () => {
|
||||
it("requires a well-formed viewer key", () => {
|
||||
expect(parseViewerSessionRequest({ viewerKey: "kiosk-lobby-0001" })).toEqual({
|
||||
ok: true,
|
||||
value: { viewerKey: "kiosk-lobby-0001" },
|
||||
});
|
||||
for (const viewerKey of [undefined, null, "short", "has spaces in it", "x".repeat(129)]) {
|
||||
expect(parseViewerSessionRequest({ viewerKey })).toEqual({ field: "viewerKey", ok: false });
|
||||
}
|
||||
});
|
||||
|
||||
it("a display accepts only a complete registration", () => {
|
||||
const complete = {
|
||||
channelId: "chan-1",
|
||||
channelKey: "default",
|
||||
groupId: "group-1",
|
||||
heartbeatIntervalMs: 12_000,
|
||||
viewerId: "11111111-1111-4111-8111-111111111111",
|
||||
viewerName: "New display",
|
||||
};
|
||||
expect(parseViewerSessionResponse(complete)).toEqual({ ok: true, value: complete });
|
||||
const { viewerId: _omitted, ...missing } = complete;
|
||||
expect(parseViewerSessionResponse(missing)).toEqual({ field: "viewerId", ok: false });
|
||||
expect(parseViewerSessionResponse({ ...complete, heartbeatIntervalMs: 0 })).toEqual({
|
||||
field: "heartbeatIntervalMs",
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { ModuleDatabase } from "@ekklesia/module-sdk";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createTimelineStore } from "../src/server/store/drizzle-timelines.js";
|
||||
import type { NewStoredSlot } from "../src/server/store/types.js";
|
||||
|
||||
const TIMELINE_ID = "00000000-0000-4000-8000-000000000001";
|
||||
|
||||
function slot(id: string): NewStoredSlot {
|
||||
return {
|
||||
durationOverrideMs: null,
|
||||
eligibleFrom: null,
|
||||
eligibleUntil: null,
|
||||
enabled: true,
|
||||
id,
|
||||
itemId: "image-1",
|
||||
kind: "pinned-item",
|
||||
presentation: {
|
||||
backgroundColor: null,
|
||||
backgroundDarkened: null,
|
||||
backgroundMode: null,
|
||||
blurPixels: null,
|
||||
foregroundShadow: null,
|
||||
},
|
||||
providerId: "signage.native-images",
|
||||
sourceId: null,
|
||||
timelineId: TIMELINE_ID,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A narrow database contract double for the production timeline store.
|
||||
*
|
||||
* Unlike the service-level memory store, it enforces the shipped PostgreSQL
|
||||
* `signage_timeline_slots_position_check` on every insert and update. That is the boundary the
|
||||
* deployed bug crossed: the old collision-avoidance algorithm used negative positions, so the
|
||||
* actual database rejected a native-image slot before playback ever had content to resolve.
|
||||
*/
|
||||
function constraintDatabase(existing: readonly { id: string; position: number }[]): {
|
||||
readonly database: ModuleDatabase;
|
||||
readonly positions: number[];
|
||||
} {
|
||||
const positions: number[] = [];
|
||||
const enforce = (values: { position?: unknown }): void => {
|
||||
if (typeof values.position === "number") {
|
||||
expect(values.position).toBeGreaterThanOrEqual(0);
|
||||
positions.push(values.position);
|
||||
}
|
||||
};
|
||||
const transaction = {
|
||||
insert: () => ({
|
||||
values: async (values: { position?: unknown }) => enforce(values),
|
||||
}),
|
||||
select: () => ({
|
||||
from: () => ({
|
||||
where: () => ({
|
||||
orderBy: async () => existing,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
update: () => ({
|
||||
set: (values: { position?: unknown }) => ({
|
||||
where: async () => enforce(values),
|
||||
}),
|
||||
}),
|
||||
};
|
||||
return {
|
||||
database: {
|
||||
transaction: async (operation: (value: typeof transaction) => Promise<unknown>) => operation(transaction),
|
||||
} as unknown as ModuleDatabase,
|
||||
positions,
|
||||
};
|
||||
}
|
||||
|
||||
describe("production timeline slot ordering", () => {
|
||||
it("creates the first pinned native image without violating the database position constraint", async () => {
|
||||
const { database, positions } = constraintDatabase([]);
|
||||
|
||||
await createTimelineStore(database).addSlot(slot("00000000-0000-4000-8000-000000000002"));
|
||||
|
||||
expect(positions).toEqual([1, 2, 0]);
|
||||
});
|
||||
|
||||
it("reorders through a non-negative temporary range before writing the final order", async () => {
|
||||
const first = "00000000-0000-4000-8000-000000000002";
|
||||
const second = "00000000-0000-4000-8000-000000000003";
|
||||
const { database, positions } = constraintDatabase([
|
||||
{ id: first, position: 0 },
|
||||
{ id: second, position: 1 },
|
||||
]);
|
||||
|
||||
await createTimelineStore(database).reorderSlots(TIMELINE_ID, [second, first]);
|
||||
|
||||
expect(positions).toEqual([3, 4, 0, 1]);
|
||||
});
|
||||
});
|
||||
@@ -66,7 +66,7 @@ describe("Signage module manifest", () => {
|
||||
expect(manifest.manifestVersion).toBe(7);
|
||||
expect(manifest.id).toBe("signage");
|
||||
expect(manifest.name).toBe("Signage");
|
||||
expect(manifest.version).toBe("0.1.0");
|
||||
expect(manifest.version).toBe("0.1.2");
|
||||
expect(manifest.compatibility).toEqual({ moduleSdk: "^0.1.0", platform: "^0.1.0" });
|
||||
});
|
||||
|
||||
@@ -142,7 +142,7 @@ describe("Signage module manifest", () => {
|
||||
|
||||
describe("Signage server runtime", () => {
|
||||
it("exports the typed runtime definition the compiled server entrypoint publishes", async () => {
|
||||
expect(moduleRuntime).toMatchObject({ id: "signage", version: "0.1.0" });
|
||||
expect(moduleRuntime).toMatchObject({ id: "signage", version: "0.1.2" });
|
||||
});
|
||||
|
||||
it("registers its routes declaratively, with no database, storage, or realtime work", async () => {
|
||||
@@ -241,7 +241,7 @@ describe("Signage server runtime", () => {
|
||||
expect(response.status).toBe(200);
|
||||
expect(await response.json()).toEqual({
|
||||
crossfadeMs: 400,
|
||||
moduleVersion: "0.1.0",
|
||||
moduleVersion: "0.1.2",
|
||||
nativeImageDurationMs: 12_000,
|
||||
nativePresentation: SIGNAGE_DEFAULT_SETTINGS.nativePresentation,
|
||||
rendererInputVersion: "1.0.0",
|
||||
|
||||
@@ -589,6 +589,30 @@ describe("authoritative playback", () => {
|
||||
expect(announcements.resolveRequests.length).toBe(callsBefore);
|
||||
});
|
||||
|
||||
it("keeps the active timeline through a complete playback-service restart", async () => {
|
||||
const group = await seedGroup();
|
||||
const timeline = await seedPattern();
|
||||
await service.activate(group.group.id, timeline.timeline.id, "now");
|
||||
const before = await service.snapshot(group.group.id);
|
||||
|
||||
service.stop();
|
||||
clock += 2000;
|
||||
service = createPlaybackService({
|
||||
newId,
|
||||
now: () => clock,
|
||||
registry,
|
||||
setTimer: () => undefined,
|
||||
settings: { ...SIGNAGE_DEFAULT_SETTINGS, playbackHistoryLimit: 20 },
|
||||
store,
|
||||
});
|
||||
await service.start();
|
||||
|
||||
const after = await service.snapshot(group.group.id);
|
||||
expect(after.activeTimelineId).toBe(timeline.timeline.id);
|
||||
expect(after.currentSelectionId).toBe(before.currentSelectionId);
|
||||
expect(after.deadlineAtMs).toBe(before.deadlineAtMs);
|
||||
});
|
||||
|
||||
it("publishes a compact snapshot, with no payload or timeline in it", async () => {
|
||||
const group = await seedGroup();
|
||||
const timeline = await seedPattern();
|
||||
|
||||
@@ -103,7 +103,7 @@ export function createMemoryPlaybackStore(
|
||||
return Promise.resolve();
|
||||
},
|
||||
|
||||
deleteChannelGroup(groupId: string): Promise<void> {
|
||||
deleteChannelGroup(groupId: string, _fallbackChannelId: string): Promise<void> {
|
||||
groups.delete(groupId);
|
||||
playback.delete(groupId);
|
||||
for (const [id, channel] of channels) {
|
||||
|
||||
@@ -46,6 +46,20 @@ export function createMemorySignageStore(
|
||||
...playbackStore,
|
||||
...viewerStore,
|
||||
|
||||
async deleteChannelGroup(groupId: string, fallbackChannelId: string): Promise<void> {
|
||||
const removedChannelIds = new Set(
|
||||
[...playbackStore.channels.values()]
|
||||
.filter((channel) => channel.groupId === groupId)
|
||||
.map((channel) => channel.id),
|
||||
);
|
||||
for (const viewer of viewerStore.viewers.values()) {
|
||||
if (viewer.channelId !== null && removedChannelIds.has(viewer.channelId)) {
|
||||
await viewerStore.updateViewer(viewer.id, { channelId: fallbackChannelId });
|
||||
}
|
||||
}
|
||||
await playbackStore.deleteChannelGroup(groupId, fallbackChannelId);
|
||||
},
|
||||
|
||||
addImageReference(imageId: string, kind: "slot" | "static-hold"): void {
|
||||
const current = references.get(imageId) ?? { slots: 0, staticHolds: 0 };
|
||||
references.set(
|
||||
|
||||
@@ -128,6 +128,34 @@ describe("viewers", () => {
|
||||
expect(store.viewers.size).toBe(1);
|
||||
});
|
||||
|
||||
it("moves an assigned display atomically when its channel group is deleted", async () => {
|
||||
const original = (await store.listChannelGroups())[0];
|
||||
if (!original) {
|
||||
throw new Error("Expected the default group.");
|
||||
}
|
||||
const session = await openViewerSession({
|
||||
at: new Date(clock),
|
||||
deviceId: null,
|
||||
newId,
|
||||
store,
|
||||
viewerKey: "kiosk-lobby-0003",
|
||||
});
|
||||
expect(original.channels.some((channel) => channel.id === session.channel.id)).toBe(true);
|
||||
const fallbackGroupId = newId();
|
||||
const fallbackChannelId = newId();
|
||||
await store.createChannelGroup({
|
||||
channelId: fallbackChannelId,
|
||||
channelName: "Default",
|
||||
groupId: fallbackGroupId,
|
||||
name: "Foyer",
|
||||
});
|
||||
|
||||
await store.deleteChannelGroup(original.group.id, fallbackChannelId);
|
||||
|
||||
expect(await store.findChannelGroup(original.group.id)).toBeUndefined();
|
||||
expect((await store.findViewer(session.viewer.id))?.channelId).toBe(fallbackChannelId);
|
||||
});
|
||||
|
||||
it("stores only the safe device identifier a paired principal carries", async () => {
|
||||
const session = await openViewerSession({
|
||||
at: new Date(clock),
|
||||
|
||||
Reference in New Issue
Block a user