1 Commits
Author SHA1 Message Date
Jason 357c904d1b Adaptive Music v0.8.1 combat automation fixes
Validate and generate manual release / package (push) Waiting to run
2026-12-05 13:37:05 -05:00
26 changed files with 1385 additions and 136 deletions

No files matched your search

+16 -8
View File
@@ -1,4 +1,4 @@
# Adaptive Music architecture — 0.8.0
# Adaptive Music architecture — 0.8.1
Adaptive Music is an independent project by CheddahBoxMB for Foundry v14.371 and
MA 2.10.6, with no system dependency or additional required process. The expanded
@@ -86,8 +86,12 @@ path. Default ICE uses no public STUN/TURN service.
## Transitions and recovery
Manual override/silence > explicit boss > started combat in the active scene >
ambient > world default > silence. No system actor schemas are used. The existing
Manual override/silence > combatant boss override > designated encounter boss cue
> started combat in the active scene > ambient > world default > silence.
An explicit combat scene takes precedence. An unlinked encounter with
scene-bound combatants applies to their scenes. An unlinked encounter with no
scene-bound combatants is global. Begun, active encounters are resolved through
post-operation combat and combatant hooks. No system actor schemas are used. The existing
serialized controller checks campaign/session/generation and current authority.
A single active GM plus a Web Lock excludes common duplicate tabs; this is not a
server-side distributed fence or seamless handover protocol.
@@ -95,7 +99,9 @@ server-side distributed fence or seamless handover protocol.
Every queue mutation verifies the exact dedicated target, standalone topology and
its own active queue. Signed snapshots retain ordered duplicates, index, repeat,
whole-second position and state, scoped to campaign/session/fence/generation for up
to 12 hours. Ambiguous writes latch closed and stop automation; they are not retried.
to 12 hours. An interrupted ambient snapshot can survive an excursion while its
scene's encounter remains live and the ambient reference still matches.
Ambiguous writes latch closed and stop automation; they are not retried.
MA Sendspin lacks native pause in 2.10.6, so pause retains a logical stopped-queue
snapshot and resume explicitly seeks its item. A paused restore rebuilds without
briefly playing. A finished static queue can be interrupted and rebuilt in an
@@ -111,7 +117,9 @@ scene playlists would require two independently managed streams at once.
Scene Configuration and the Playlists sidebar use Foundry render hooks. The
director displays virtual catalog items for assignment and saves only opaque
references into scene flags. No Foundry Playlist document is created for an MA
references into scene flags. The GM's native Combat Tracker stores the encounter
designation on the Combat document and reflects the current playback mode.
No Foundry Playlist document is created for an MA
item. The module cedes a scene with a configured native soundtrack to Foundry.
Only explicitly owned native fallback playlists can be managed by Adaptive Music.
Positional audio and other native effects stay under Foundry’s control.
@@ -122,6 +130,6 @@ The installed v0.7.0 module was tested in a logged-in Foundry v14.371 developmen
world through the private Nginx route. The v0.8.0 browser preview used validated
ZIP assets with the real development world, MA and two listeners. It exercised
Foundry module-socket signaling, scene and combat hooks, ordered ambient
restoration, real playback controls and User document permissions. Exact server
installation of v0.8.0, the original Mac path, physical-device audibility and
WAN behavior await verification.
restoration, real playback controls and User document permissions. The operator
later verified installed v0.8.0 audio in Chrome on macOS and at a remote WAN
listener. macOS Firefox connectivity remains unresolved. See [TESTING.md](TESTING.md).
+20
View File
@@ -1,5 +1,25 @@
# Changelog
## 0.8.1 — Combat Tracker cues and Firefox diagnostics
- Follow the combatants' token scenes when Foundry creates an unlinked
encounter through its native token HUD. Switch after combat starts, keep
the cue across initiative changes, and restore ambient when combat ends.
- Add **Boss encounter** to the GM's native Combat Tracker. Beginning a
designated encounter uses the scene's default boss cue. The tracker and
Playback panel show the current music mode and expose a way back to
automation while a manual override is active.
- Retain an interrupted ambient position across a scene excursion while
the original encounter remains active.
- Record the last failed Connect action's timestamp, error code and known setup
stage in the copyable connection report.
- Record each unauthenticated WebSocket probe's duration and the site permission
state observed after that route completes. Keep opaque upgrade failures
distinct from a confirmed CSP block.
- Record installed v0.8.0 macOS operator acceptance and the Firefox connectivity
failure. The macOS Firefox fix is still awaiting diagnosis.
## 0.8.0 — playback stability and native Foundry controls
- Keep Sendspin PCM packet boundaries contiguous in Web Audio. Track source gaps,
+77 -30
View File
@@ -1,42 +1,90 @@
# Adaptive Music v0.8.0 handoff
# Adaptive Music v0.8.1 handoff
## Repository state
The v0.8.0 release audit follows the handed-off candidate `987122f`. The original
workspace Git metadata is mounted read-only. The completed local audit commit
is on `main` in the independent, remote-free checkout
`.local/v080-release-checkout`. Read the exact commit from
`dist/releases/v0.8.0/release.json` or run
`git -C .local/v080-release-checkout rev-parse HEAD`. The original workspace
retains the same source changes over its existing baseline. The release
builder runs from the clean checkout, and its source archive is compared
against that commit. Gitea access, tags, publication and production changes
The original workspace's Git metadata is read-only. Before v0.8.1 changes,
its 157 tracked and untracked source files matched the clean local release
commit `1ed6b4c` byte for byte. The original HEAD `987122f` is that commit's
parent. Develop on `v0.8.1-firefox` in the remote-free
`.local/v080-release-checkout`. Its `main` branch retains `1ed6b4c`.
The operator reported Gitea published v0.8.0 from `95b0427`. That object
is absent in both local Git databases. The published commit's ancestry
can be checked if its Git object is supplied offline.
A read-only check of the authorized private Foundry route confirmed the
installed manifest is v0.8.0 and all 28 runtime files match `1ed6b4c`.
The v0.8.1 archive is built from a clean checkout and its source is compared
against its local commit. Read its exact commit in
`dist/releases/v0.8.1/release.json`. Gitea access and production deployment
are outside this work.
## Ready for operator testing
## Installed v0.8.0 macOS acceptance
- **Operator pass:** Chrome connectivity, credentials after quitting and
reopening Chrome, automatic scene playlist activation, background-tab audio,
remote player audio over WAN, and smooth transitions. The operator heard no
stuttering or crackling during their session.
- **Operator fail:** macOS Firefox connectivity.
- **Combat follow-up:** assigned battle music worked when used as ambient,
while normal combat left ambient playing. The operator could not find
the boss designation. Combat, restoration, boss and manual controls need
hands-on acceptance with the corrected candidate.
## v0.8.1 native combat correction
The native token HUD created an unlinked encounter on Foundry 14.371 and D&D 5e
6.1.2. Installed v0.8.0 ignored it even after the native tracker started round 1.
Use the Combatant token scene when the encounter has no explicit scene. The
tracker now has a GM-only **Boss encounter** option and shows the playback mode
and **Return to automation** for a manual override. The same combat and boss
assignment can change mode without restarting the queue. Use distinct playlists
to verify the audible changes.
The authorized GUI run and its hook trace live under ignored
`.local/v081-combat-gui-*`. See [TESTING.md](TESTING.md) and
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the reproduced lifecycle and steps.
The Chromium browser preview used three distinct cues and restored ambient at
30, 33 and 46 seconds across normal, boss and manual-override encounters.
It verified turn and round continuity, End Combat cancellation, scene changes,
and returning from the manual hold. The server still reported v0.8.0 during
the previews. Headed Firefox repeated the normal combat lifecycle against the
same runtime and restored ambient at 9 seconds.
## v0.8.1 Firefox investigation
- The two WSS routes opened with HTTP 101 in Mozilla Firefox 161.0.1 on Ubuntu
from the anonymous Foundry origin and the MA origin using the native
WebSocket. Trusted TLS and the authorized private route were retained.
- The isolated stock-Firefox policy test reproduced enforced CSP, report-only
CSP, a server-side Origin rejection and a mismatched TLS certificate. Browser
script saw Origin rejection and TLS rejection as opaque upgrade failures.
- The candidate improves the token-free report with manual Connect failure
stage and time, per-route duration and post-probe permission states.
Audio, credential storage and the authenticated transport are outside the
change. The original macOS failure needs the browser-side capture described
in [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md#capture-the-firefox-failure).
- The private stock browser, scripts and raw reports under `.local/v081-*`
are test-only. See [sanitized v0.8.1 evidence](evidence/v0.8.1-live.json).
## Historical v0.8.0 audit checkpoint
- The development world keeps **Christmas — Adaptive Music demo** active with
Christmas music assigned. **Dûr-Khazrak — Adaptive Music demo** has distinct
ambient, combat and boss cues and a prepared, unstarted encounter with the
Dûr-Khazrak Champion. Its ambient uses a development playlist as a stand-in.
The authorized catalog contained no identifiable dwarven soundtrack.
- The verified server install is v0.7.2. The private route grants access to the
development world, and Foundry module installation is instance-wide. No
development-only package directory or server install access was established.
Follow the [isolated development install instructions](INSTALL.md#install-the-candidate-on-an-isolated-development-instance)
and [Mac acceptance checklist](USER-ACCEPTANCE.md).
- The preview host reported v0.7.2 during the automated audit. The operator
subsequently installed v0.8.0 and carried out the checks above.
- Automated release regressions passed with 110 JavaScript and 17 Python
tests. The dependency, repository and upstream provenance checks passed.
The updated Chromium, Firefox and Linux WebKit credential fixture closed
and reopened persistent browser profiles and tested rejection by a synthetic
MA auth endpoint after simulated revocation. The real preview verified
same-receiver auto-attachment after a page reload, Disconnect and Forget.
- Prioritize the original Mac Firefox connection failure, physical audio
artifacts and actual installed-world playback. MA-side revocation with a
disposable token, Mac sleep/wake and the actual WAN route still need operator
acceptance. The focused Ubuntu Firefox background check measured listener
audio before switching tabs and could not establish that the GM page became
hidden. Prefer a targeted reproduction over another full soak.
- MA-side revocation with a disposable token and Mac sleep/wake still need
operator acceptance. The focused Ubuntu Firefox background check measured
listener audio before switching tabs and could not establish that the GM
page became hidden.
The package targets Foundry VTT 14.371 and MA 2.10.6. It uses the pinned Sendspin
SDK and browser-hosted audio. The user authorized the existing test accounts and
@@ -97,11 +145,9 @@ December 4. See [the evidence](evidence/v0.8.0-live.json),
access. The extracted binary and signed-package hashes are in
`.local/v080-turn-fixture/`. Future runs can set `AM_LOOPBACK_TURN_CONFIG`
to a private fixture grant and use `--webkit-only`.
- A passing browser ZIP preview exercises real Foundry and MA with archive
assets. Server installation of v0.8.0, the operator's original Mac Firefox
path, native Safari, physical audibility, suspend/wake and WAN acceptance
still require the corresponding environment. The active server reports
v0.7.2. No production deployment is authorized.
- These v0.8.0 automated browser previews exercised real Foundry and MA with
archive assets while the server reported v0.7.2. See the separate installed
v0.8.0 manual results above.
The bundle is locally staged under
`dist/releases/v0.8.0/`. The install ZIP is `adaptive-music.zip` and the
@@ -189,9 +235,10 @@ xvfb-run -a -s '-screen 0 1600x1050x24 +extension GLX' \
node scripts/check_foundry_private_route.mjs --headed --firefox --playback --package-preview dist/releases/v0.8.0/adaptive-music.zip --continuity \
> .local/v080-candidate-firefox-soak.log 2>&1
python3 scripts/release.py
python3 scripts/release.py --validate dist/releases/v0.8.0/adaptive-music.zip
(cd dist/releases/v0.8.0 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.0.zip.sha256)
# Build the current candidate from the clean local release checkout.
python3 .local/v080-release-checkout/scripts/release.py --output "$PWD/dist/releases/v0.8.1"
python3 scripts/release.py --validate dist/releases/v0.8.1/adaptive-music.zip
(cd dist/releases/v0.8.1 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.1.zip.sha256)
```
The headed browser tests use the authorized private Nginx HTTPS route and retain
+14 -11
View File
@@ -1,4 +1,4 @@
# Install and connect — 0.8.0
# Install and connect — 0.8.1 candidate
## Normal setup
@@ -17,13 +17,16 @@
also lists draggable MA catalog entries for the scene’s playlist fields.
Use static playlists with available tracks. MA can list an entry whose
tracks are unavailable when Adaptive Music prepares it for playback.
Use the setup window’s **Scene Music** tab for world defaults and boss
combatant overrides.
Use the setup window’s **Scene Music** tab for world defaults and optional
combatant-specific boss overrides. For a boss encounter, check **Boss
encounter** in the native Combat Tracker before clicking **Start Combat**
to use the scene’s default boss music.
4. Open **Adaptive Music controls** from the token toolbar or Playlists sidebar.
Enable automation once. The controls show the current track, active playlist
when known, volume, position and listeners. Skip, pause, resume, stop and
repeat control the dedicated queue. An override stays active until you select
**Return to scene music**.
repeat control the dedicated queue. The Playback panel and Combat Tracker
show the current music mode. Select **Return to automation** in the tracker
or **Return to scene music** in Playback to clear a manual override.
5. Players connect automatically. If a browser requires activation, open Campaign
audio and select **Enable Audio** once. The GM can use **Enable GM audio** in the
playback controls after an automatic connection.
@@ -92,7 +95,7 @@ See [TESTING.md](TESTING.md) for private-route evidence and
Foundry loads modules from its instance-wide user-data directory. Use only a
development-only data directory. If the existing world shares an instance with
production worlds, use an isolated development instance and a development-world
copy. The confirmed server build at handoff is v0.7.2.
copy. The separately verified installed baseline is v0.8.0.
Unzip the complete release bundle on the development host and run these
commands as the Foundry data owner. Set the first two variables to the existing
@@ -104,11 +107,11 @@ the module directory.
(
set -eu
FOUNDRY_DEV_DATA='/absolute/path/to/development-only/Data'
AM_RELEASE_DIR='/absolute/path/to/extracted/v0.8.0'
AM_RELEASE_DIR='/absolute/path/to/extracted/v0.8.1'
cd "$AM_RELEASE_DIR"
grep ' adaptive-music.zip$' SHA256SUMS | sha256sum -c -
test -d "$FOUNDRY_DEV_DATA/modules"
AM_STAGE=$(mktemp -d "$FOUNDRY_DEV_DATA/adaptive-music-v080.XXXXXX")
AM_STAGE=$(mktemp -d "$FOUNDRY_DEV_DATA/adaptive-music-v081.XXXXXX")
unzip -q adaptive-music.zip -d "$AM_STAGE"
test -f "$AM_STAGE/adaptive-music/module.json"
if [ -d "$FOUNDRY_DEV_DATA/modules/adaptive-music" ]; then
@@ -125,7 +128,7 @@ the module directory.
```
Restart the development instance, launch the development world and confirm
**Manage Modules** reports **0.8.0**. Enable the module if needed, then sign in as
**Manage Modules** reports **0.8.1**. Enable the module if needed, then sign in as
**CodexDEV** and follow the acceptance checklist. For rollback, shut down the
development instance, move the candidate module out of `Data/modules` and move
`previous-adaptive-music` from the printed rollback directory back to
@@ -136,11 +139,11 @@ development instance, move the candidate module out of `Data/modules` and move
The existing stable manifest and versioned download mechanism is preserved:
- Manifest: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json`
- v0.8.0 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.0/adaptive-music.zip`
- v0.8.1 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.1/adaptive-music.zip`
These are the established repository’s URLs; this work never contacted Gitea or
verified public asset availability. After acceptance, manually publish the included
source to your existing repository, create tag/release `v0.8.0`, attach
source to your existing repository, create tag/release `v0.8.1`, attach
`adaptive-music.zip` and the included manifest/checksums, and update the branch
manifest only after its versioned asset exists. The outer bundle includes full
source, docs, licenses, metadata and SHA256SUMS. Keep the previous immutable release
+61 -8
View File
@@ -1,4 +1,57 @@
# Adaptive Music progress — 0.8.0 release audit
# Adaptive Music progress — 0.8.1 combat and Firefox
## Installed v0.8.0 manual acceptance
The operator confirmed on macOS that Chrome connected and retained credentials
after a full quit and reopen. Automatic scene playlist activation, background-tab
audio, WAN player audio and smooth transitions passed. The operator reported
that stuttering and crackling were resolved in their testing. Firefox
connectivity failed. A follow-up confirmed the battle playlist played when
assigned to ambient, while tracked combat left ambient unchanged. The operator
could not find boss designation. The corrected combat workflow still awaits
operator acceptance.
## v0.8.1 combat correction
The installed v0.8.0 reproduction used the native token HUD and Combat Tracker
on Foundry 14.371 and D&D 5e 6.1.2. Start Combat committed round 1 and turn 0
for an unlinked encounter with a token in the active scene. The module required
an explicit encounter scene and kept its ambient queue. The correction considers
the unlinked encounter's combatant scenes and reconciles from the committed
lifecycle. The Combat Tracker now lets the GM mark a boss encounter and return
to automation. Both the tracker and Playback panel identify the current cue.
The Chromium candidate preview verified the native tracker workflow with three
distinct playlists. Turn and round changes kept the combat cue, canceled End
Combat kept the encounter running, and confirmed end restored ambient after
normal, boss, and manual-override encounters. The scene excursion preserved the
interrupted ambient position. The manual override was visible in the tracker and
released to Combat through **Return to automation**.
The headed Firefox preview repeated the normal tracker lifecycle and restored
ambient at 9 seconds. The installed macOS candidate awaits operator retesting.
## v0.8.1 status
The clean local v0.8.0 release commit was reconciled against the original
workspace and the installed runtime. The original Git metadata is read-only
and the operator's published commit `95b0427` is absent locally. Both local
trees had identical source before v0.8.1 work. The installed v0.8.0 manifest
and all 28 runtime files matched the local release baseline.
Stock Firefox 161.0.1 on Ubuntu opened both private WSS routes from the
anonymous Foundry page and the MA origin. The isolated policy fixture
distinguished enforced CSP and kept Origin and certificate failures opaque.
The v0.8.1 diagnostic candidate records route timing, permissions after
the probe and the failed Connect stage without copying arbitrary error text.
The source change is confined to the connection diagnostics and their UI.
The macOS failure remains open pending the
[Firefox capture](USER-ACCEPTANCE.md#capture-the-firefox-failure).
The v0.8.1 regressions passed 115 JavaScript and 17 Python tests, plus the
Chromium, Firefox and Linux WebKit setup fixtures. Repository and upstream
verification passed. npm audit reported zero vulnerabilities. The complete
diagnostic candidate bundle is staged locally under `dist/releases/v0.8.1/`.
## Historical v0.8.0 automated audit
The operator confirmed that installed v0.7.2 plays MA audio in Chrome on a Mac.
The v0.8.0 work uses that baseline and retains the dedicated receiver architecture.
@@ -60,11 +113,11 @@ open.
| AM-002 provisioning | SDK-created identity, authenticated dedicated web-receiver pairing, no normal JSON import; real MA tests | Normal installed-world flow on Mac |
| AM-003 diagnostics | Per-route upgrade/CSP checks, staged auth/pair/sync errors, output counters and copyable GM connection report | Original Mac failure report if it persists |
| AM-004 retry retention | Tab-private draft; encrypted receiver vault; token/identity origin binding; Firefox and Chromium reattached after transport loss and reload without replacing the queue | Mac reload/retry/network lifecycle |
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox. Chromium authenticated and paired in the installed Foundry world. The MA front end’s unauthenticated Sendspin interceptor explains the failing control probe. | Original Mac-specific pre-upgrade failure remains unresolved |
| AM-006 setup usability | The three browser engines passed the narrow setup fixture. The v0.8.0 ZIP preview exercised real connection, scene assignment and transport. | Server-installed v0.8.0 |
| AM-007 continuity | Firefox ZIP preview passed 30 minutes across real combat and restoration. Three-engine renders at 44.1 and 48 kHz passed the PCM comparison. Chromium verified hidden-tab audio. | Firefox hidden tab, physical output, suspend/wake and actual WAN route |
| AM-005 cross-origin | Both WSS routes open through private Nginx in Ubuntu Chromium and Firefox, including stock Firefox 161.0.1. Chromium authenticated and paired in the earlier installed-world run. The MA front end’s unauthenticated Sendspin interceptor explains the failing historical control probe. | Mac Firefox connectivity fails. The current failure stage awaits browser capture. |
| AM-006 setup usability | The three browser engines passed the narrow setup fixture. The v0.8.0 ZIP preview exercised real connection, scene assignment and transport. | Exact v0.8.1 installed-world acceptance |
| AM-007 continuity | Firefox ZIP preview passed 30 minutes across real combat and restoration. Three-engine renders at 44.1 and 48 kHz passed the PCM comparison. The operator confirmed macOS background audio, physical output during testing and WAN audio. | Firefox hidden tab and suspend/wake |
| AM-008 credentials | Three-engine encrypted device storage across browser restarts and synthetic auth denial. Real Chromium token-free reload, Disconnect and Forget Credentials. | Separate Mac profiles, live disposable-token revocation and token rotation |
| AM-009 native integration | The Chromium ZIP preview saved native scene assignments with a pointer drag and exercised scene, combat and boss transitions. | Server-installed v0.8.0 |
| AM-009 native integration | The Chromium ZIP preview saved native scene assignments with a pointer drag and exercised scene, combat and boss transitions. The operator confirmed scene auto-activation in v0.8.0. | Manual combat, boss and ambient restoration |
| AM-010 controls | Token-toolbar and playlist-sidebar launch points, transport, manual override, return to scene and fades through the dedicated MA queue. | True overlapping playlist crossfade |
| MA catalog playback | The installed module delivered audio to two real Foundry players during ambient, combat and restoration to a seven-second offset. Stop/Enable and reload were exercised. | Physical devices, invitation renewal and WAN acceptance |
@@ -100,9 +153,9 @@ failures remains unconfirmed. The controller preserves the failed command and sk
rollback after an uncertain write. See `evidence/v0.7.0-live-follow-up.json`.
The earlier server-installed evidence is in `evidence/v0.7.0-foundry-private.json`.
The v0.8.0 bundle, including a Mac checklist, remains staged for exact server
installation, Mac physical output, suspend/wake and WAN acceptance. See
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) and [TESTING.md](TESTING.md).
The installed v0.8.0 manual results and remaining checklist are in
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md). See [TESTING.md](TESTING.md)
for the v0.8.1 fixture results and investigation.
The single queue supports sequential
fades. Durable crash restoration, seamless handover and WAN synchronization remain
unsupported.
+6 -3
View File
@@ -1,4 +1,4 @@
# Adaptive Music — 0.8.0
# Adaptive Music — 0.8.1 candidate
Independent open-source Foundry VTT music automation by **CheddahBoxMB**, targeting
Foundry v14.371 and Music Assistant 2.10.6. The module runs independently of the game
@@ -11,8 +11,11 @@ native **Scene Configuration**. Enable automation once. Open **Adaptive Music
controls** from the token toolbar or the Playlists sidebar during play. The setup
window can close.
The active scene starts its assigned music. Combat interrupts ambient music and
restores the saved track and position when combat ends. GMs can pause, resume,
The active scene starts its assigned music. Starting an encounter in the Combat
Tracker interrupts ambient and ending it restores the saved track and position.
Check **Boss encounter** before starting to use the scene's default boss cue.
The tracker and playback controls show Ambient, Combat, Boss or Manual Override.
GMs can pause, resume,
skip, stop, set repeat, adjust volume, apply a manual playlist and return to scene music.
Player audio connects automatically, with an **Enable Audio** click when required
by the browser.
+3 -1
View File
@@ -1,4 +1,4 @@
# Adaptive Music security — 0.8.0
# Adaptive Music security — 0.8.1
## Credentials and browser trust
@@ -38,6 +38,8 @@ security, Origin and private access controls remain enabled. No public MA endpoi
Origin forgery, CORS wildcard change or unrestricted proxy is introduced. Both `/ws`
and `/sendspin` must reach their authenticated MA routes. Token-free diagnostics
send no explicit MA auth frame; browsers may still send their normal ambient cookies.
The copyable report adds route timing and an allowlisted setup failure code and
stage. Arbitrary error strings and connection inputs stay out of those fields.
Browser APIs do not expose arbitrary HTTP/TLS errors and diagnostics do not invent
those causes.
+95 -6
View File
@@ -1,9 +1,98 @@
# Adaptive Music verification — 0.8.0
# Adaptive Music verification — 0.8.1
## Executed evidence
The source archive includes sanitized evidence separately from private .local inputs.
### Installed v0.8.0 manual macOS acceptance
The operator confirmed Chrome connectivity, retention after a full Chrome quit
and reopen, automatic scene playlist activation, background-tab audio, WAN
player audio and smooth transitions. Stuttering and crackling were resolved
during testing. Firefox connectivity failed. In the combat follow-up, the
operator reported that a battle playlist played when assigned to ambient,
while native combat use left the ambient cue playing. They could not find
the boss designation. The corrected combat flow and manual playback
controls still need operator acceptance.
### v0.8.1 native Combat Tracker investigation
Tested Foundry **14.371** and D&D 5e **6.1.2** in the authorized development
world. The baseline used installed v0.8.0 and the GM entered a token into
combat through its native HUD. The tracker created an active, unlinked
encounter with one combatant belonging to the active scene. On **Start Combat**,
`combatStart` arrived at round 0 with `started=false`. The subsequent
`updateCombat` and `combatTurnChange` reported round 1, turn 0 and
`started=true`. The baseline made no dedicated queue transition, reproducing
the failure without calling a module API or injecting encounter state.
Foundry v14's `Combat.scene` is optional in practice and its unlinked encounters
are visible across scenes. `Combatant.sceneId` identifies the token's scene.
D&D 5e's `Combat5e` at `75750bf1b8bd79f8448af40495c8bb5c99f49551`
delegates start, end and update/delete processing to Foundry core and adds
system-specific resource and token behavior. Adaptive Music uses
the committed document hooks and accepts explicit scene links or the token
scenes in an unlinked encounter. A turn or round change leaves the cue intact.
The Chromium package preview used three distinct playlists. A native token HUD
and native tracker controls verified adding combatants, rolling initiative,
starting an encounter, advancing turns and rounds, and canceling or confirming
End Combat. Neither preparation nor canceled End Combat changed the cue.
Confirmed End Combat restored the ordered ambient queue at track index 0 and
30 seconds. The **Boss encounter** checkbox selected the scene's default boss
cue on the next encounter. A scene excursion using Foundry's scene activation
operation played the other scene's ambient, then selected Boss on return.
Ending the boss restored the original ambient at 33 seconds. A manual silence
override displayed an explicit warning during the next encounter. **Return to
automation** selected Combat, and End Combat restored ambient at 46 seconds.
The test measured GM output and restored the development world afterward.
Headed Ubuntu Firefox 159 repeated the native token HUD, initiative, start,
turn and round, canceled end, and confirmed end checks against the same
candidate runtime. It measured GM output and restored ambient at index 0
and 9 seconds. Both candidate previews ran on Foundry 14.371 and D&D 5e 6.1.2
with server-installed metadata reporting v0.8.0.
[Foundry Combat Tracker guide](https://foundryvtt.com/article/combat/),
[combatStart hook](https://foundryvtt.com/api/v14/functions/hookEvents.combatStart.html),
[Combatant API](https://foundryvtt.com/api/v14/classes/foundry.documents.Combatant.html),
and [D&D 5e 6.1.2 Combat implementation](https://raw.githubusercontent.com/foundryvtt/dnd5e/75750bf1b8bd79f8448af40495c8bb5c99f49551/module/documents/combat.mjs).
### v0.8.1 Firefox transport investigation
The downloaded Mozilla Firefox 161.0.1 Linux archive matched Mozilla's SHA-512
listing. Real stock Firefox over the authorized private route opened native
`/ws` and `/sendspin` WebSockets with HTTP 101 from the anonymous Foundry
page and the MA origin. The test used a process-local mapping to the authorized
private proxy and normal certificate verification. No credentials were entered.
The MA page replaces its WebSocket constructor, so its control used the
native constructor retained before page script execution.
Separate live runs with stock Firefox 161.0.1 on Ubuntu also signed into the
development world, authenticated to MA and measured scene audio at the GM and
a second Foundry login. Those runs covered installed v0.8.0 and the earlier
diagnostics-only v0.8.1 browser preview.
Seven isolated stock-Firefox policy cases covered trusted cross-origin and
same-origin upgrades, enforced and report-only CSP, server-side Origin
rejection and a mismatched WSS certificate. Origin and TLS failures remained
opaque to page script. The permission API reported `prompt` even on a private
route that worked, so that reported state does not determine the cause.
Firefox's site-level local network permission and the macOS app-level permission
are separate. Record whether MA's normal HTTPS page works in the failing Firefox
profile. If it fails, verify the displayed error and compare the profile's
existing DNS and proxy settings. If MA loads, compare the two Foundry WSS routes
and look for local-network or CSP console messages. A reverse proxy's
timestamped path and response status can distinguish a received handshake
from a failure before it reached the proxy. The pinned MA 2.10.6 handlers
authenticate after upgrade. Ordinary HTTP CORS settings do not establish
authorization for a WebSocket Origin. Keep browser, TLS and proxy policy in place.
See [the Firefox capture instructions](USER-ACCEPTANCE.md#capture-the-firefox-failure),
[Mozilla local-network permissions](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [MDN's CSP connect-src reference](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Content-Security-Policy/connect-src).
### v0.8.0 handoff checkpoint
The v0.8.0 browser preview reached the actual Foundry development world through
@@ -58,7 +147,8 @@ verified per-user/world lookup, forgetting, and retained authentication across
full persistent-profile browser restarts in all three engines. The real
WebSocket client rejected the previously saved synthetic token after fixture
revocation. The real MA server was not modified for this check.
Server-installed v0.8.0, Mac Firefox and native Safari remain separate checks.
The later installed v0.8.0 Mac results are recorded above. Mac Firefox and
native Safari still require device-specific acceptance.
In the loopback WebRTC fixture, Chromium and Firefox both rendered audio across
signaling expiry and closed the sender after listener revocation. Linux WebKit
@@ -201,10 +291,9 @@ private HTTPS MA endpoint. It needs no developer console or diagnostic shell com
The development-world runs covered real Foundry hooks, socket delivery and User
permissions. The v0.8.0 preview verified continued playback through the
signaling lifetime and listener reconnection. Public release acceptance still
requires exact server installation, audibility on the actual Mac/player devices,
the original Mac connection and the WAN checks.
If AM-005 reproduces on the Mac, correlate its browser connection stage and timestamp
signaling lifetime and listener reconnection. For v0.8.1, verify the exact
installed candidate and prioritize the unresolved Mac Firefox connection.
For AM-005, correlate the reported browser stage and timestamp
with the private proxy’s request and upstream status or TCP counters. The procedure
and temporary VM-to-proxy access rollback are in ignored .local/PRIVATE-ROUTE-REQUEST.md.
+44 -8
View File
@@ -1,14 +1,48 @@
# Adaptive Music v0.8.0 Mac acceptance
# Adaptive Music Mac acceptance
Run the checklist once in Firefox and once in Chrome on your Mac. Use the
## Installed v0.8.0 operator results
These results are user-confirmed manual testing on macOS. See
[TESTING.md](TESTING.md) for automated browser and development-world evidence.
| Result | Scope |
| --- | --- |
| Pass | Chrome connectivity, Chrome credentials after a full quit and reopen, automatic scene playlist activation, background-tab audio, remote player audio over WAN, and smooth transitions. The operator heard no stuttering or crackling during testing. |
| Fail | Firefox connectivity on macOS. The operator also reported that the assigned battle playlist played when used as ambient, while normal Combat Tracker use left the ambient cue playing. |
| Usability finding | The operator could not find a way to designate a boss. Their normal combat and default boss assignments used the same playlist. |
| Awaiting candidate retest | Combat start and end, ambient restoration, boss designation, and manual playback controls. |
## Capture the Firefox failure
1. Note the Firefox and macOS versions. In the same Firefox profile and network,
open the normal MA HTTPS page and record whether it loads or shows a
certificate or connection error.
2. Return to the Foundry world. Open **Adaptive Music setup → Connection** and
reproduce **Connect** once. Note the exact error and the time with timezone.
Run **Check browser connection**, then select **Copy connection diagnostics**.
3. If either route fails, record the Foundry site's local network permission
from Firefox's site permissions or **Settings → Privacy & Security →
Permissions → Local network devices**. Also record the Firefox entry under
**System Settings → Privacy & Security → Local Network** on macOS. Leave
these settings as they are for the initial capture.
4. If available, copy the relevant Web Console line for `/ws` or `/sendspin`
using **⌘⌥K**, especially a Local Network Access, CSP or certificate error.
Share the result privately with the copied module diagnostics. Omit tokens,
cookies, raw WebSocket frames and full network exports.
See [Mozilla’s Firefox local-network permission guide](https://support.mozilla.org/en-US/kb/control-personal-device-local-network-permissions-firefox)
and [Apple’s macOS Local Network settings guide](https://support.apple.com/guide/mac-help/mchla4f49138/mac).
## Candidate checklist
Run the relevant checks against the exact candidate being accepted. Use the
private development world and sign in as **CodexDEV**, with one GM browser
connected at a time. Use the same approved development MA token in both
browsers so the existing scene assignments resolve. Put on headphones and
record your browser and macOS versions.
Before starting, confirm **Manage Modules** shows Adaptive Music **0.8.0**.
If the development instance still shows **0.7.2**, use the [local ZIP install
procedure](INSTALL.md#install-the-candidate-on-an-isolated-development-instance).
Before starting a v0.8.1 run, confirm **Manage Modules** shows Adaptive Music
**0.8.1**. Use the [local ZIP install procedure](INSTALL.md#install-the-candidate-on-an-isolated-development-instance).
Only use the dedicated development receiver.
| Check | Action | Expected result |
@@ -16,9 +50,11 @@ Only use the dedicated development receiver.
| ☐ Connect | Open **Settings → Adaptive Music setup → Connection**. Enter the approved private MA address and token. On a trusted profile, select **Remember credentials and reconnect on this trusted device** and click **Connect**. | The catalog loads and the dedicated receiver connects. Once connected, the token field is empty. Click **Enable GM audio** if prompted. |
| ☐ Christmas ambience | Activate **Christmas — Adaptive Music demo**. Open **Adaptive Music controls** from the token toolbar and enable automation if needed. | Christmas music starts. The controls show the currently playing track and its position. |
| ☐ Native assignment | Open **Configure Scene** on the Christmas scene. In **Playlists → Adaptive Music**, drag its current Christmas playlist onto **Ambient playlist** and click **Save assignments**. Reopen Configure Scene. | The dropped value survives saving and reopening. The scene's native soundtrack remains unset. |
| ☐ Combat and boss | Activate **Dûr-Khazrak — Adaptive Music demo**. Let ambient play for at least 15 seconds and note the track and time. Start the prepared encounter in the Combat Tracker. In **Scene Music → World defaults and boss combatants**, select **Dûr-Khazrak Champion**, check **Boss override** and save. | The combat cue replaces ambient. Saving the override switches to the scene's boss cue. The ambient cue uses an existing development playlist as a stand-in for a dwarven soundtrack. |
| ☐ Restore | Clear the champion's **Boss override** and save, then end the encounter. Repeat a start/end once. | The combat cue returns when the override is cleared. Ending combat returns to the saved ambient track and roughly the saved position. Rapid changes converge on ambient. |
| ☐ Manual controls | Open **Music controls** from the Playlists sidebar. Apply a **Manual playlist override**, then try pause, resume, seek, skip, volume, repeat and stop. Click **Return to scene music**. | The override takes precedence. Pause holds position, resume continues, and controls affect the dedicated receiver. Returning to scene music restores automation. |
| ☐ Combat | Activate **Dûr-Khazrak — Adaptive Music demo** or another scene with three distinct ambient, combat, and boss playlists. Note the ambient track and position. Add tokens with **Enter Combat**, roll initiative, then click **Start Combat** in the Combat Tracker. Click **Next Turn** and **Next Round**. | Adding combatants and rolling initiative leave ambient playing. Starting the encounter switches to **Combat**. Advancing turns and rounds continues the cue without a restart. |
| ☐ Boss | In a fresh encounter, check **Boss encounter** in the Combat Tracker before clicking **Start Combat**. | The scene's default boss cue starts and the tracker and Playback panel show **Boss**. A scene with the same combat and boss playlist can change mode while the music continues. |
| ☐ Cancel and restore | Open **End Combat** and cancel the confirmation, then open it again and confirm. Repeat with a second encounter. | Cancel keeps the encounter and its music running. Confirm restores the ambient queue order, track and approximate saved position. A later encounter captures a fresh position. |
| ☐ Switch scenes during combat | During an active encounter, activate another scene with its own ambient cue and no participants in that encounter. Reactivate the original scene and end the encounter. | The other scene uses its own ambient. The encounter cue returns on reactivation. Ending the encounter restores the original scene's interrupted ambient position. |
| ☐ Manual controls | Open **Music controls** from the Playlists sidebar and apply a **Manual playlist override**. Start combat and use **Return to automation** in the Combat Tracker. Also try pause, resume, seek, skip, volume, repeat, and stop. | The tracker and Playback panel show **Manual Override** while automatic cues are on hold. Return to automation takes up the currently applicable cue. Transport controls affect the dedicated receiver. |
| ☐ Player audio | Join as an ordinary development player in a separate profile. Open **Campaign audio** and select **Enable Audio** if prompted. Try **Stop Audio**, **Enable Audio** and one player reload. | The listener hears the GM's cue and audio returns after re-enabling and reloading. |
| ☐ Continuity | Listen on GM and player output through steady playback, cue changes and at least one track boundary. Cover each Foundry tab with another tab for at least one minute. Include one 30-minute play session and a Mac sleep/wake test across the two browsers. | Steady audio has no audible pops, crackle or unexpected gaps. Cue changes use a short sequential fade. Track/position continue while the tab is hidden. Record what happens during and after sleep. |
| ☐ Restart and reconnect | Quit the browser fully, reopen the same profile and return to the development world. With a working session, briefly drop and restore the test device's network. | The remembered receiver reconnects without token entry. A populated queue is preserved on attachment. Select **Return to scene music** to resume scene cues immediately if needed. |
+31
View File
@@ -1241,5 +1241,36 @@
"Physical audibility, listener quiet runs, transitions, sleep and wake",
"Live disposable MA token revocation and actual WAN listener route"
]
},
"macOperatorAcceptance": {
"source": "Operator-reported manual acceptance on installed Adaptive Music v0.8.0 on macOS",
"installedVersion": "0.8.0",
"passed": [
"Chrome connectivity",
"No stuttering or crackling during testing",
"Chrome credential retention after full quit and reopen",
"Automatic scene playlist activation",
"Background-tab audio continuity",
"Remote player audio over WAN",
"Smooth music transitions"
],
"failed": [
"Firefox connectivity on macOS"
],
"notTested": [
"Automatic combat music",
"Ambient restoration",
"Boss music",
"Manual playback controls"
],
"combatFollowUp": {
"scope": "Operator follow-up from their actual Foundry scene",
"ambientPlayback": "pass",
"battlePlaylistPlayableWhenAssignedToAmbient": true,
"combatCueSwitch": "fail: ambient continued",
"bossDesignationDiscoverability": "fail",
"combatAndBossUsedSamePlaylist": true,
"candidateManualRetest": "pending"
}
}
}
+688
View File
@@ -0,0 +1,688 @@
{
"version": "0.8.1",
"scope": "Firefox diagnostics and native Combat Tracker candidate. Private development-world package previews, transport checks and browser fixtures.",
"publicationReady": false,
"serverInstalledExactVersion": false,
"completedCoreRunPassed": true,
"macPrivateRouteVerified": false,
"macFirefoxRootCauseConfirmed": false,
"operatorAcceptanceV080": {
"source": "Operator-reported manual acceptance on installed Adaptive Music v0.8.0 on macOS",
"installedVersion": "0.8.0",
"passed": [
"Chrome connectivity",
"No stuttering or crackling during testing",
"Chrome credential retention after full quit and reopen",
"Automatic scene playlist activation",
"Background-tab audio continuity",
"Remote player audio over WAN",
"Smooth music transitions"
],
"failed": [
"Firefox connectivity on macOS"
],
"notTested": [
"Automatic combat music",
"Ambient restoration",
"Boss music",
"Manual playback controls"
],
"combatFollowUp": {
"scope": "Operator follow-up from their actual Foundry scene",
"ambientPlayback": "pass",
"battlePlaylistPlayableWhenAssignedToAmbient": true,
"combatCueSwitch": "fail: ambient continued",
"bossDesignationDiscoverability": "fail",
"combatAndBossUsedSamePlaylist": true,
"candidateManualRetest": "pending"
}
},
"localHistory": {
"originalHead": "987122ffee17ddbdb6266a12d4d8beb29903b838",
"localV080Release": "1ed6b4c8ccd35e1187b83003379fe05d3cbeed8a",
"v080SourceFilesIdentical": 157,
"reportedPublishedCommit": "95b0427",
"publishedObjectAvailableLocally": false,
"v081Branch": "v0.8.1-firefox"
},
"installedBaselineComparison": {
"scope": "anonymous exact-path read of installed Foundry module files over trusted private HTTPS",
"manifestStatus": 200,
"installedVersion": "0.8.0",
"runtimeFilesCompared": 28,
"runtimeFilesIdentical": 28,
"runtimeMismatches": []
},
"stockFirefox": {
"version": "161.0.1",
"platform": "Linux x86-64",
"archiveSha512": "9ef6ccc1b0e4376980ab88a49408924e75d3cafca248becfb8893424c6f025a58d715bf05f1f5397a4a997059de4c054a3e6490a140bdf4dc8795ec78b26e02a",
"download": "https://archive.mozilla.org/pub/firefox/releases/161.0.1/linux-x86_64/en-US/firefox-161.0.1.tar.xz",
"archiveVerifiedAgainstMozillaSha512Listing": true,
"privateRoute": {
"scope": "official Mozilla Firefox on Ubuntu, anonymous private Foundry and MA HTTPS pages, fixed unauthenticated WSS routes",
"browser": "161.0.1",
"tlsValidation": true,
"checks": {
"foundryOrigin": {
"status": 200,
"cspHeaderPresent": false,
"reportOnlyHeaderPresent": false,
"secureContext": true,
"cspMetaPresent": false,
"replaced": false,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 9,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
},
"maOrigin": {
"secureContext": true,
"cspMetaPresent": false,
"replaced": true,
"upgrades": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 195,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 19,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
],
"networkEvents": [
{
"path": "/ws",
"code": 101
},
{
"path": "/ws",
"code": 101
},
{
"path": "/sendspin",
"code": 101
}
]
}
},
"completed": true
},
"isolatedPolicyChecks": {
"scope": "isolated real Firefox HTTPS/WSS policy tests; local transport server, no MA, no Foundry, no credentials or audio",
"browser": "161.0.1",
"mozillaStockBuild": true,
"tls": "local CA trusted in disposable Firefox profile; no certificate bypass",
"checks": [
{
"name": "Trusted HTTPS cross-origin WSS allowed",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 11,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Enforced CSP blocks cross-origin before upgrade",
"results": [
{
"path": "/ws",
"code": "csp-blocked",
"elapsedMs": 1,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "csp-blocked",
"elapsedMs": 0,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same MA origin control",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Report-only CSP does not block",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 4,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Server Origin rejection stays opaque",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 31,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Same origin still succeeds under Origin restriction",
"results": [
{
"path": "/ws",
"code": "upgrade-ok",
"elapsedMs": 3,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-ok",
"elapsedMs": 2,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
},
{
"name": "Mismatched WSS certificate stays opaque and connection closed",
"results": [
{
"path": "/ws",
"code": "upgrade-failed",
"elapsedMs": 29,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
},
{
"path": "/sendspin",
"code": "upgrade-failed",
"elapsedMs": 28,
"permissions": {
"local-network": "prompt",
"loopback-network": "prompt"
}
}
]
}
],
"passed": true
}
},
"offlineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
],
"regression": {
"javascriptPassed": 115,
"javascriptFailed": 0,
"pythonPassed": 17,
"pythonFailed": 0,
"repositoryPrivacyAndAttribution": "pass",
"upstreamProvenance": "pass",
"npmAuditReportedVulnerabilities": 0
},
"remainingAcceptance": [
"Capture the failure on the operator Mac and identify its WebSocket or subsequent setup stage",
"Verify the exact server-installed v0.8.1 candidate in the affected Firefox profile and the working Chrome profile",
"Retest the corrected combat, ambient restoration, boss designation and manual playback controls on the operator Mac"
],
"combatTrackerAcceptance": {
"scope": "Authorized private development world; the candidate ZIP supplied runtime assets to the browser",
"dnd5eReviewedCommit": "75750bf1b8bd79f8448af40495c8bb5c99f49551",
"installedV080Reproduction": {
"at": "2026-12-05T18:15:47.932Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"cleanup": true,
"nativeHudAndStartCombat": true,
"encounter": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1
},
"ambientQueueChanged": false,
"lifecycle": [
{
"event": "createCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 0,
"participantsInActiveScene": 0,
"updateKeys": []
},
{
"event": "createCombatant",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1
},
{
"event": "combatStart",
"linked": false,
"linkedToActive": false,
"active": true,
"started": false,
"round": 0,
"turn": null,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "updateCombat",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
},
{
"event": "combatTurnChange",
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 1,
"participantsInActiveScene": 1,
"updateKeys": [
"round",
"turn"
]
}
]
},
"candidateNormalEncounter": {
"at": "2026-12-05T18:20:56.093Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.04104
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 30
},
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.0348
}
},
"harnessResult": "Normal encounter checks passed. The first scene-navigation locator timed out and the focused follow-up exercised the scene edge cases.",
"postCommitEvents": [
"combatRound",
"combatStart",
"combatTurn",
"combatTurnChange",
"createCombat",
"createCombatant",
"deleteCombat",
"updateCombat",
"updateCombatant"
]
},
"candidateBossSceneAndOverride": {
"at": "2026-12-05T18:29:02.740Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0.8154.6",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"bossFromSceneDefault": {
"distinct": true,
"gmRMS": 0.11936
},
"sceneExcursionDuringCombat": {
"passed": true,
"outwardMethod": "native-scene-activation",
"returnMethod": "native-scene-activation"
},
"bossRestoration": {
"index": 0,
"seconds": 33
},
"manualOverrideAndTrackerReturn": true,
"repeatedRestoration": {
"index": 0,
"seconds": 46
}
},
"onlyDedicatedQueueWritten": true
},
"candidateFirefox": {
"completed": true,
"at": "2026-12-05T18:32:54.490Z",
"scope": "actual Foundry development world, native token HUD and Combat Tracker GUI",
"browser": "159.0",
"foundry": "14.371",
"serverVersion": "0.8.0",
"system": {
"id": "dnd5e",
"version": "6.1.2",
"combatClass": "Combat5e",
"combatantClass": "Combatant5e",
"trackerClass": "CombatTracker5e"
},
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
"packageSHA256": "f5a47f711f9f22ae81717a8e563fdb27d5a6ee2bd18fee0c7567535c0ddd319d",
"cleanup": true,
"checks": {
"normalCombat": {
"state": {
"linked": false,
"linkedToActive": false,
"active": true,
"started": true,
"round": 1,
"turn": 0,
"participants": 2,
"participantsInActiveScene": 2
},
"gmRMS": 0.03617
},
"turnAndRoundWithoutRestart": true,
"cancelEndPreservedCombat": true,
"normalRestoration": {
"index": 0,
"seconds": 9
}
}
}
},
"combatCandidateOfflineSetup": [
{
"status": "pass",
"engine": "chromium",
"browser": "159.0.8154.6",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "firefox",
"browser": "159.0",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
},
{
"status": "pass",
"engine": "webkit",
"browser": "27.2",
"scope": "offline DOM fixture; no live Foundry or MA",
"checks": [
"380/640/1000px layout",
"three setup tabs",
"failed connection diagnostics exclude secrets and clear after retry",
"private field clearing",
"catalog selectors",
"ambient/combat save",
"advanced controls hidden",
"sidebar catalog refresh and pointer drag",
"track and listeners",
"pause/resume/seek/repeat/volume/stop",
"listener activation"
],
"pageErrors": []
}
]
}
+17 -2
View File
@@ -33,8 +33,23 @@ try{
const sidebar=page.locator('#fixture-playlists');
await sidebar.locator('summary').click();
assert.equal(await sidebar.locator('li').count(),0);
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');await page.getByLabel('Private GM access token').fill('fixture-token');
await page.getByLabel('Music Assistant server address').fill('https://ma.example.test');
await page.evaluate(()=>Object.defineProperty(navigator.clipboard,'writeText',{value:async text=>{window.copiedDiagnostics=text;}}));
await page.getByLabel('Private GM access token').fill('synthetic-secret-sentinel');
const copyDiagnostics=page.getByRole('button',{name:'Copy connection diagnostics'});
await page.getByRole('button',{name:'Connect',exact:true}).click();
await page.getByText(/^Connection failed\./).waitFor();
await copyDiagnostics.click();
let copied=await page.evaluate(()=>window.copiedDiagnostics);
const {at,...failure}=JSON.parse(copied).lastConnectFailure;
assert.ok(Number.isFinite(Date.parse(at)));
assert.deepEqual(failure,{code:'ws-upgrade-failed',stage:'API authentication'});
assert.doesNotMatch(copied,/synthetic-secret-sentinel|ma\.example\.test/);
await page.getByLabel('Private GM access token').fill('fixture-token');
await page.getByRole('button',{name:'Connect',exact:true}).click();await page.getByText('Campaign audio connected.',{exact:false}).waitFor();
await copyDiagnostics.click();
copied=await page.evaluate(()=>window.copiedDiagnostics);
assert.equal(JSON.parse(copied).lastConnectFailure,undefined);
assert.equal(await page.getByLabel('Private GM access token').inputValue(),'');
await page.evaluate(()=>window.refreshNativeConfiguration());
const source=sidebar.getByText('Forest at night',{exact:true}),scene=page.locator('#fixture-scene');
@@ -62,5 +77,5 @@ try{
assert.deepEqual(await page.evaluate(()=>window.controlActions),['pause','resume','seek','repeat','stop']);
if(engine==='chromium'){await mkdir(resolve(root,'dist/previews'),{recursive:true});await page.screenshot({path:resolve(root,'dist/previews/am006-setup.png'),fullPage:true});}
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input').count(),0);await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
console.log(JSON.stringify({status:'pass',engine,browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','three setup tabs','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','sidebar catalog refresh and pointer drag','track and listeners','pause/resume/seek/repeat/volume/stop','listener activation'],pageErrors:errors},null,2));
console.log(JSON.stringify({status:'pass',engine,browser:browser.version(),scope:'offline DOM fixture; no live Foundry or MA',checks:['380/640/1000px layout','three setup tabs','failed connection diagnostics exclude secrets and clear after retry','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','sidebar catalog refresh and pointer drag','track and listeners','pause/resume/seek/repeat/volume/stop','listener activation'],pageErrors:errors},null,2));
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
+22 -12
View File
@@ -2,20 +2,29 @@
export class MusicError extends Error {
constructor(code) { super(code); this.code = code; }
}
export function combatAppliesToScene(combat, sceneId) {
if (!combat.active || !combat.started || !sceneId) return false;
if (combat.sceneId) return combat.sceneId === sceneId;
return !combat.sceneIds?.length || combat.sceneIds.includes(sceneId);
}
const intent = (key, mode, playlist = null) => ({key: `${key}:${JSON.stringify(playlist)}`, mode, playlist});
const ambientIntent = scene => intent(`scene:${scene.id}`, 'ambient', scene.playlist);
const retainedAmbient = state => (state.retainedAmbient ?? []).filter(scene => scene.playlist).map(ambientIntent);
export function candidates(state) {
const scene = state.scene;
const combats = (state.combats ?? []).filter(c => c.active && c.started && c.sceneId === scene?.id);
const combats = (state.combats ?? []).filter(c => combatAppliesToScene(c,scene?.id))
.sort((a,b) => a.id.localeCompare(b.id));
const bosses = combats.flatMap(c => c.bosses ?? []).filter(b => b.active && b.playlist)
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id.localeCompare(b.id));
const make = (key, playlist) => ({ key, playlist: playlist ?? null });
return [
...(state.overrides ?? []).slice().reverse().map(o => make(`manual:${o.id}`, o.playlist)),
...bosses.map(b => make(`boss:${scene.id}:${b.id}`, b.playlist)),
...combats.filter(c => c.playlist).sort((a,b) => a.id.localeCompare(b.id))
.map(c => make(`combat:${scene.id}:${c.id}`, c.playlist)),
...(scene?.playlist ? [make(`scene:${scene.id}`, scene.playlist)] : []),
make('default', state.defaultPlaylist)
].map(i => ({ ...i, key: `${i.key}:${JSON.stringify(i.playlist)}` }));
...(state.overrides ?? []).slice().reverse().map(o => intent(`manual:${o.id}`, 'manual', o.playlist)),
...bosses.map(b => intent(`boss:${scene.id}:${b.id}`, 'boss', b.playlist)),
...combats.filter(c => c.bossPlaylist).map(c => intent(`boss-encounter:${scene.id}:${c.id}`, 'boss', c.bossPlaylist)),
...combats.filter(c => c.playlist).map(c => intent(`combat:${scene.id}:${c.id}`, 'combat', c.playlist)),
...(scene?.playlist ? [ambientIntent(scene)] : []),
intent('default', state.defaultPlaylist ? 'ambient' : 'silence', state.defaultPlaylist)
];
}
const samePlaylist = (a, b) => Boolean(a && b && a.provider === b.provider && a.id === b.id);
@@ -29,7 +38,7 @@ export class MusicController {
}
update(state) {
const input = structuredClone(state);
const signature=JSON.stringify(candidates(input).map(intent=>intent.key));
const signature=JSON.stringify([...candidates(input),...retainedAmbient(input)].map(intent=>intent.key));
if(this.#pending?.signature===signature&&this.#pending.generation===this.generation)return this.#pending.task;
if(!this.#pending&&this.current&&this.#stateSignature===signature&&!this.dirty.size&&this.authority())return Promise.resolve({unchanged:true});
const context = this.#nextContext();
@@ -77,7 +86,8 @@ export class MusicController {
async transition(state, ctx) {
ctx.check();
const choices = candidates(state), next = choices[0];
const valid = new Set(choices.map(i => i.key));
const active = new Set(choices.map(i => i.key));
const valid = new Set([...active,...retainedAmbient(state).map(i=>i.key)]);
this.frames = this.frames.filter(f => valid.has(f.intent.key));
if (this.current?.key === next.key) return { unchanged: true };
if(samePlaylist(this.current?.playlist,next.playlist)){
@@ -123,7 +133,7 @@ export class MusicController {
} finally {
await outgoing?.fade?.(true);
}
this.frames = this.frames.filter(f => !samePlaylist(f.intent.playlist,next.playlist)).slice(-this.maxFrames);
this.frames = this.frames.filter(f => !active.has(f.intent.key)||!samePlaylist(f.intent.playlist,next.playlist)).slice(-this.maxFrames);
this.dirty.clear();
this.current = next;
return { intent: next, restored: Boolean(frame) };
+13 -4
View File
@@ -1,6 +1,9 @@
import { MusicError } from './controller.mjs';
export const musicFields = ['ambient','combat','boss','fallback'];
export const referenceKey = ref => ref ? JSON.stringify([ref.provider,ref.id]) : '';
export const musicModeLabel = mode => ({
ambient:'Ambient', combat:'Combat', boss:'Boss', manual:'Manual Override', silence:'Silence'
})[mode];
export function selection(value, choices, {nativeOnly=false}={}) {
if(value==='')return null;
const choice=choices.find(c=>referenceKey(c)===value && ['native','ma'].includes(c.provider) && typeof c.id==='string' && c.id.length<=256);
@@ -9,13 +12,19 @@ export function selection(value, choices, {nativeOnly=false}={}) {
}
// Single music layer: ambient is the base queue interrupted by combat/boss/manual.
// These assignments do not address Foundry AmbientSound or sound effects.
export function buildMusicState({scene,combats=[],defaults={},overrides=[],choose=ref=>ref}) {
export function buildMusicState({scene,retainedScenes=[],combats=[],defaults={},overrides=[],choose=ref=>ref}) {
const sceneMusic = scene => {
const config = scene?.music ?? {};
const ambient=(Object.hasOwn(config,'ambient')?config.ambient:config.playlist)??defaults.ambient??null;
const fallback = config.fallback ?? defaults.fallback ?? null;
const selected=ref=>ref ? choose(ref,fallback) : null;
return {scene:scene && {id:scene.id,playlist:selected(ambient)},defaultPlaylist:scene ? null : selected(defaults.ambient),
const ambient = (Object.hasOwn(config,'ambient') ? config.ambient : config.playlist) ?? defaults.ambient;
const selected = ref => ref ? choose(ref,fallback,scene) : null;
return {config,ambient:selected(ambient),selected};
};
const {config,ambient,selected}=sceneMusic(scene);
return {scene:scene && {id:scene.id,playlist:ambient},defaultPlaylist:scene ? null : ambient,
retainedAmbient:retainedScenes.map(scene=>({id:scene.id,playlist:sceneMusic(scene).ambient})),
overrides:overrides.map(o=>({...o,playlist:selected(o.playlist)})),
combats:combats.map(c=>({...c,playlist:selected(c.playlist??config.combat??defaults.combat),
bossPlaylist:c.boss===true?selected(config.boss??defaults.boss):null,
bosses:(c.bosses??[]).map(b=>({...b,playlist:selected(b.playlist??config.boss??defaults.boss)}))}))};
}
+76 -4
View File
@@ -1,5 +1,5 @@
import {mountMusicAssignments,playlistDragType} from './music-editor.mjs';
import {referenceKey} from '../core/scene-music.mjs';
import {musicModeLabel,referenceKey} from '../core/scene-music.mjs';
import { MusicError } from '../core/controller.mjs';
const namespace = 'adaptive-music';
const key = ref => JSON.stringify([ref?.provider, ref?.id]);
@@ -48,9 +48,11 @@ export function mountPlaylistConfiguration({ document, game, container, choices,
container.append(panel); return panel;
}
// Explicit development-only UI bootstrap. Importing this file registers nothing.
export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlayback, onError = () => {} }) {
export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlayback, getPlaybackState = () => ({}),
returnToAutomation, onError = () => {} }) {
let disposed = false;
const panels = new Set();
const trackers = new Map();
const render = async (app, html) => {
if (!game.user?.isGM) return;
for(const panel of panels)if(panel.isConnected===false)panels.delete(panel);
@@ -102,10 +104,80 @@ export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlay
onError(new MusicError('unavailable'));
}
};
const hooks = [['renderSceneConfig',render],['renderCombatConfig',render],['renderPlaylistDirectory',renderDirectory]]
function refreshCombatTrackers() {
for(const [panel,refresh] of trackers){
if(panel.isConnected)refresh();
else trackers.delete(panel);
}
}
const renderCombatTracker = (app,html) => {
if(disposed||!game.user?.isGM)return;
const container = html?.querySelector ? html : html?.[0];
if(!container)return;
const existing = container.querySelector('.adaptive-combat-music');
if(existing){trackers.get(existing)?.();return;}
const dom = container.ownerDocument;
const panel = dom.createElement('section');
panel.className = 'adaptive-combat-music';
panel.setAttribute('aria-label','Adaptive Music');
const mode = dom.createElement('p');
mode.setAttribute('role','status');
const label = dom.createElement('label');
const boss = dom.createElement('input');
boss.type = 'checkbox';
label.append(boss, ' Boss encounter');
label.title = 'Use the scene’s default boss music when this encounter starts.';
const resume = dom.createElement('button');
resume.type = 'button';
resume.textContent = 'Return to automation';
panel.append(mode,label,resume);
container.prepend(panel);
let saving = false;
const refresh = () => {
const combat = app.viewed;
const state = getPlaybackState();
const cue = musicModeLabel(state.musicMode);
const text = state.overrideActive ? 'Music: Manual Override · automatic cues on hold'
: state.awaitingSceneChange ? 'Music: waiting for the next cue'
: cue ? `Music: ${cue}` : 'Music: automation off';
if(mode.textContent!==text)mode.textContent=text;
label.hidden = !combat;
boss.disabled = saving || !combat;
boss.checked = flagBoss(combat);
resume.hidden = !returnToAutomation || (!state.overrideActive && !state.awaitingSceneChange);
};
const flagBoss = combat => combat?.getFlag(namespace,'music')?.boss === true;
boss.addEventListener('change',async event=>{
event.stopPropagation();
const combat = app.viewed;
if(!game.user?.isGM || !combat?.canUserModify(game.user,'update')){refresh();return;}
const enabled = boss.checked;
saving = true;
boss.disabled = true;
try{await combat.setFlag(namespace,'music',{...combat.getFlag(namespace,'music'),boss:enabled});}
catch{onError(new MusicError('denied'));}
finally{saving=false;refresh();}
});
resume.addEventListener('click',async ()=>{
if(!game.user?.isGM)return;
resume.disabled=true;
try{await returnToAutomation();}
catch(error){onError(error);}
finally{resume.disabled=false;refresh();}
});
refreshCombatTrackers();
trackers.set(panel,refresh);
refresh();
};
const hooks = [['renderSceneConfig',render],['renderCombatConfig',render],['renderPlaylistDirectory',renderDirectory],
['renderCombatTracker',renderCombatTracker]]
.map(([event,handler])=>[event,Hooks.on(event,handler)]);
return {
refreshDirectory:app=>renderDirectory(app,app?.element),
dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id); for (const panel of panels) panel.remove(); panels.clear(); }
refreshCombatTrackers,
dispose() { disposed = true; for (const [event,id] of hooks) Hooks.off(event,id);
for (const panel of [...panels,...trackers.keys()]) panel.remove();
panels.clear();trackers.clear();
}
};
}
+28 -5
View File
@@ -38,6 +38,12 @@ const messages={
'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.',
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
};
const connectionStages=new Set(['API authentication','Sendspin authentication','Noise handshake','receiver pairing',
'clock synchronization','dedicated receiver verification','catalog retrieval','dedicated queue verification']);
function diagnosticFailure(error){
return {code:Object.hasOwn(messages,error?.code)?error.code:'unavailable',
...(connectionStages.has(error?.stage)&&{stage:error.stage})};
}
export function connectionMessage(error){
if(error?.code==='ws-upgrade-failed'&&error.stage==='Sendspin authentication')return 'The browser could not open the receiver’s /sendspin WebSocket. Check both routes from this Foundry page.';
if(error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command))return 'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped after an unconfirmed queue write.';
@@ -105,12 +111,13 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
const report=make('div');report.setAttribute('aria-live','polite');
let transportResults=[],busy=false,hadDeviceCredential=initial.deviceCredential;
const run=async(action,label)=>{
let transportResults=[],transportCheckAt,lastConnectFailure,busy=false,hadDeviceCredential=initial.deviceCredential;
const run=async(action,label,onFailure)=>{
if(busy||!game.user.isGM)return;
busy=true;retainError.hidden=true;render();
try{await action();}
catch(error){
onFailure?.(error);
busy=false;render();error.field?.focus?.();
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
}finally{busy=false;render();}
@@ -129,6 +136,7 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
catch{return false;}
}
const connect=button(actions,'Connect',()=>run(async()=>{
lastConnectFailure=undefined;
let maUrl;
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
@@ -148,7 +156,8 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
address.value=connection.draftFields?.maUrl??address.value;
await onCatalog();
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error),
error=>{lastConnectFailure={at:new Date().toISOString(),...diagnosticFailure(error)};}));
connect.className='adaptive-primary';
const nextButton=button(actions,'Choose scene music',()=>next?.());
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
@@ -158,13 +167,27 @@ export function mountConnectionWizard({game,container,connection,onCatalog=()=>{
await connection.forgetCredentials();remember.checked=false;token.value='';status.textContent='Credentials removed from this device.';await onCatalog();
},'Could not forget credentials'));
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
report.replaceChildren();transportResults=[];transportCheckAt=undefined;
transportResults=await probeWebSockets(validatedAddress());
transportCheckAt=new Date().toISOString();
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
status.textContent='Browser checks complete.';
},'Browser connection check failed'));
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
const d=connection.status;
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,bufferedMs:d.bufferedMs,underruns:d.underruns,bufferOverruns:d.bufferOverruns,sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,gapMs:d.gapMs,overlapMs:d.overlapMs,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
const details={
state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,
decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,
droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,bufferedMs:d.bufferedMs,
underruns:d.underruns,bufferOverruns:d.bufferOverruns,
sourceGaps:d.sourceGaps,sourceOverlaps:d.sourceOverlaps,gapMs:d.gapMs,overlapMs:d.overlapMs,
muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,
listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,
transport:transportResults,transportCheckAt,lastConnectFailure,
automaticConnectFailure:d.deviceError?diagnosticFailure({code:d.deviceError}):undefined,
secureContext:globalThis.isSecureContext,
};
await navigator.clipboard.writeText(JSON.stringify(details,null,2));
status.textContent='Connection diagnostics copied.';
},'Could not copy diagnostics'));
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
+10 -4
View File
@@ -40,19 +40,24 @@ function openPlayback(){
}
function ensureRuntime(){
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError,onModeChange:refreshCombatTrackers});
return runtime;
}
function playbackMode(){
return {musicMode:runtime?.musicMode,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange};
}
function refreshCombatTrackers(){interfaces?.refreshCombatTrackers();}
function start({preserveQueue=false}={}){
if(!gmAuthority()||automationRunning)return;
automationRunning=true;
const active=ensureRuntime();
if(preserveQueue)return active.deferUntilMusicChanges();
if(preserveQueue){active.deferUntilMusicChanges();refreshCombatTrackers();return;}
return active.refresh().catch(error=>{if(error.code!=='stale')onError(error);});
}
function stop(){
automationRunning=false;
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
refreshCombatTrackers();
}
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
function ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
@@ -70,7 +75,7 @@ function sendInvites(){
}
const connection={
get draftFields(){return {maUrl:privateDraft?.maUrl??savedDevice?.maUrl,targetName:privateDraft?.targetName??savedDevice?.targetName,retainedToken:!!privateDraft?.token,deviceCredential:!!savedDevice,savedConnection:savedConnection()?.version===1};},
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),deviceReconnect,deviceError:deviceError?.code,hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange};},
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),deviceReconnect,deviceError:deviceError?.code,hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning,...playbackMode()};},
async open(profile){
if(!gmAuthority()||connectionOpening||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
// Claim browser audio activation before authentication performs asynchronous work.
@@ -240,7 +245,8 @@ Hooks.once('ready',()=>{
if(game.socket&&game.user.setFlag){bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{latestInvite=invite;if(listenerStopped)return;peers.reset();await listenWebRTC(invite);}});bootstrap.start().then(sendInvites).catch(onError);inviteTimer=setInterval(()=>{sendInvites();if(game.user.isGM&&runtime&&!gmHost.connected&&privateProfile){stop();peers.reset();sentInvites.clear();onError();}},15000);}
gateway=new GatewayClient({origin:globalThis.location?.origin??'http://localhost'});audio=new ListenerAudio();
if(game.user.isGM){
interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,openPlayback,onError});
interfaces=startConfigurationInterfaces({game,Hooks,getChoices:choices,openPlayback,getPlaybackState:playbackMode,
returnToAutomation:()=>setOverrides([]),onError});
void interfaces.refreshDirectory(ui.playlists);
if(game.world?.id)receiverVault.loadCredential(credentialScope()).then(credential=>{
if(!devicePaused&&!connectionOpening&&connectionGeneration===0)savedDevice=credential;
+7 -2
View File
@@ -1,5 +1,5 @@
import {connectionMessage} from './connection-wizard.mjs';
import {referenceKey,selection} from '../core/scene-music.mjs';
import {musicModeLabel,referenceKey,selection} from '../core/scene-music.mjs';
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
@@ -10,6 +10,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
make('h2','Playback');
const now=make('section');now.className='adaptive-now';
const state=make('p','Stopped',now);state.className='adaptive-state';
const mode=make('p',null,now);mode.className='adaptive-music-mode';mode.setAttribute('role','status');
const track=make('h3','Nothing playing',now);
const playlist=make('p',null,now);
const timing=make('p',null,now);
@@ -75,6 +76,10 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
const queueError=['uncertain','receiver-access-lost'].includes(d.lastError?.code);
const canControl=connected&&trackStatus?.source==='Music Assistant'&&!queueError;
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
const cue=musicModeLabel(d.musicMode);
const modeText=cue?`Music: ${cue}`:'';
if(mode.textContent!==modeText)mode.textContent=modeText;
mode.hidden=!cue;
track.textContent=trackStatus?.title||'Nothing playing';
playlist.textContent=trackStatus?.playlist||'';
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
@@ -93,7 +98,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
const enabled=isRunning();
automationText.textContent=enabled
? d.overrideActive?'Manual override active':d.awaitingSceneChange?'Automation will resume at the next scene cue':'Automation active'
? d.overrideActive?'Automatic cues are on hold. Select Return to scene music to resume.':d.awaitingSceneChange?'Automation will resume at the next scene cue':'Automation active'
: game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
+31 -13
View File
@@ -1,4 +1,4 @@
import { candidates,MusicController } from '../core/controller.mjs';
import { candidates,combatAppliesToScene,MusicController } from '../core/controller.mjs';
import { buildMusicState } from '../core/scene-music.mjs';
import { NativeProvider } from '../providers/native/provider.mjs';
export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
@@ -7,7 +7,7 @@ export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
// All music configuration uses module-owned flags; no actor/system schema access.
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
previousController, onError = () => {} }) {
previousController, onError = () => {}, onModeChange = () => {} }) {
const flag = d => d?.getFlag('adaptive-music', 'music');
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
@@ -23,18 +23,33 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
if(previousController.dirty.has(previousController.providers.native))controller.dirty.add(provider);
}
let overrides = [],deferredState;
const sceneDocument = scene => ({id:scene.id,music:flag(scene),nativePlaylist:scene.playlist});
const getState = () => {
const scene = [...game.scenes].find(s => s.active);
const scene = game.scenes.active ?? [...game.scenes].find(s => s.active);
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
const nativeScenePlaylist=scene?.playlist?.id??scene?.playlist;
const choose=(ref,fallback)=>{
if(nativeScenePlaylist)return null;
const choose=(ref,fallback,scene)=>{
if(scene?.nativePlaylist)return null;
return ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
};
return buildMusicState({scene:scene&&{id:scene.id,music:flag(scene)},
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose,
combats:[...game.combats].map(c=>({id:c.id,sceneId:c.scene?.id??c.scene,active:c.active,started:c.started,playlist:flag(c)?.playlist,
bosses:[...c.combatants].map(b=>{const f=flag(b)??flag(b.token)??{};return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};})}))});
const combats = [...game.combats].map(combat=>{
const settings = flag(combat) ?? {};
const combatants = [...combat.combatants];
return {
id:combat.id, sceneId:combat.scene?.id ?? combat.scene, active:combat.active, started:combat.started,
// Foundry v14 creates unlinked encounters by default. Token combatants
// retain their own scene association even when the encounter has none.
sceneIds:[...new Set(combatants.map(b=>b.sceneId?.id ?? b.sceneId ?? b.token?.parent?.id).filter(Boolean))],
playlist:settings.playlist, boss:settings.boss === true,
bosses:combatants.map(b=>{
const f = flag(b) ?? flag(b.token) ?? {};
return {id:b.id,active:f.boss===true&&f.inactive!==true,priority:Number.isFinite(f.priority)?f.priority:0,playlist:f.playlist};
})
};
});
const retainedScenes = [...game.scenes].filter(s=>s.id!==scene?.id&&
combats.some(combat=>combatAppliesToScene(combat,s.id))).map(sceneDocument);
return buildMusicState({scene:scene&&sceneDocument(scene),retainedScenes,combats,
defaults:{...defaults,ambient:Object.hasOwn(defaults,'ambient')?defaults.ambient:game.settings.get('adaptive-music','defaultPlaylist')},overrides,choose});
};
const refresh = () => {
if (!isEnabled() || !authority()) return Promise.resolve();
@@ -42,10 +57,12 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
const intent=candidates(state)[0].key;
if(deferredState===intent)return Promise.resolve();
deferredState=undefined;
return controller.update(state);
return controller.update(state).finally(onModeChange);
};
if(!game.settings.settings?.has('adaptive-music.defaultPlaylist'))game.settings.register('adaptive-music', 'defaultPlaylist', { scope: 'world', config: false, type: Object, default: null });
const events = ['updateScene', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
// Combat start/turn hooks precede the document update on the initiating
// client. Reconcile the committed state on document hooks instead.
const events = ['updateScene', 'canvasReady', 'createCombat', 'updateCombat', 'deleteCombat', 'createCombatant',
'updateCombatant', 'deleteCombatant', 'updateToken', 'updateSetting', 'deletePlaylist', 'deletePlaylistSound'];
const subscriptions = events.map(event => [event, Hooks.on(event, (document,changes) => {
if(event==='updateSetting'&&!['adaptive-music.musicDefaults','adaptive-music.defaultPlaylist'].includes(document?.key))return;
@@ -53,8 +70,9 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
refresh().catch(error=>{if(error.code!=='stale')onError(error);});
})]);
return { controller, refresh,get overrideActive(){return overrides.length>0;},get awaitingSceneChange(){return deferredState!==undefined;},
get musicMode(){return overrides.length>0?'manual':controller.current?.mode;},
deferUntilMusicChanges:()=>{deferredState=candidates(getState())[0].key;},
setOverrides: value => { deferredState=undefined;overrides = structuredClone(value); return refresh(); },
setOverrides: value => { deferredState=undefined;overrides = structuredClone(value);onModeChange();return refresh(); },
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
};
}
+17 -14
View File
@@ -4,22 +4,14 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
const base=new URL(baseUrl);
if(base.username||base.password||base.search||base.hash||base.pathname!=='/'||!['https:','http:'].includes(base.protocol))throw {code:'address-invalid'};
if(globalThis.location?.protocol==='https:'&&base.protocol!=='https:')throw {code:'mixed-content'};
// Permissions are advisory. Browser support and names vary, and "prompt"
// does not establish that this particular destination needs permission.
const permissions={};
for(const name of ['local-network','local-network-access','local-network-devices','loopback-network']){
try{
const state=(await globalThis.navigator?.permissions?.query({name}))?.state;
if(['granted','prompt','denied'].includes(state))permissions[name]=state;
}catch{}
}
const results=[];
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
for(const path of ['/ws','/sendspin']){
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
results.push(await new Promise(resolve=>{
const started=performance.now();
const code=await new Promise(resolve=>{
let socket,timer,done=false,csp=false;
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code,...(Object.keys(permissions).length&&{permissions})});};
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve(code);};
const policy=event=>{
if(event.disposition!=='enforce'||!['connect-src','default-src'].includes(event.effectiveDirective))return;
if(event.blockedURI===url.href||event.blockedURI===url.origin||event.blockedURI===url.origin+'/'){
@@ -29,7 +21,18 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
events?.addEventListener('securitypolicyviolation',policy);
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
}));
});
const elapsedMs=Math.round(performance.now()-started);
// A prompt can change the site's permission during this probe. These values
// are advisory and browser support and permission names vary.
const permissions={};
for(const name of ['local-network','local-network-access','local-network-devices','loopback-network']){
try{
const state=(await globalThis.navigator?.permissions?.query({name}))?.state;
if(['granted','prompt','denied'].includes(state))permissions[name]=state;
}catch{}
}
results.push({path,code,elapsedMs,...(Object.keys(permissions).length&&{permissions})});
}
return results;
}
@@ -39,7 +42,7 @@ export const diagnosticMessage=result=>{
return ({
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
'upgrade-timeout':'The WebSocket upgrade timed out. Check for a browser permission prompt and try opening the normal MA HTTPS page in this profile.',
'upgrade-failed':'The browser did not expose a successful upgrade. Try opening the normal MA HTTPS page in this profile and check this Foundry site’s permissions. Browser code cannot read the failed handshake’s HTTP status or TLS error.'
}[result.code]??'Diagnostic unavailable.')+hint;
};
+5
View File
@@ -46,3 +46,8 @@
.adaptive-catalog { margin: .4rem; padding: .4rem; }
.adaptive-catalog ul { padding-inline-start: 1.25rem; }
.adaptive-catalog li[draggable] { cursor: grab; }
.adaptive-combat-music {display:grid;gap:.3rem;margin:.35rem .5rem;padding:.45rem .6rem;border:1px solid var(--color-border-light-primary,#777);border-radius:.3rem;}
.adaptive-combat-music p {margin:0;overflow-wrap:anywhere;font-weight:600;}
.adaptive-combat-music label {display:flex;align-items:center;gap:.3rem;min-height:1.65rem;}
.adaptive-combat-music button {width:100%;}
.adaptive-combat-music [hidden],.adaptive-music-setup .adaptive-music-mode[hidden] {display:none!important;}
+1 -1
View File
@@ -10,7 +10,7 @@ const collection=items=>{const map=new Map(items.map(x=>[x.id,x]));map[Symbol.it
const scene={id:'scene',name:'Moonlit forest',documentName:'Scene',active:true,getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;window.saved=flag}};
const game={user:{isGM:true},settings:{get:(ns,k)=>settings[k],set:async(ns,k,v)=>{settings[k]=v}},playlists:collection([{id:'native',name:'Foundry fallback'}]),scenes:collection([scene]),combats:[]};
let trackState='playing',position=12,repeat='off';window.controlActions=[];
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'denied'};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90,repeat}),
const connection={status:{state:'disconnected',catalog:0,audioContext:'closed'},open:async p=>{if(p.token!=='fixture-token')throw {code:'ws-upgrade-failed',stage:'API authentication',detail:p.token};catalog=[{provider:'ma',id:'ambient',kind:'playlist',name:'Forest at night'},{provider:'ma',id:'combat',kind:'playlist',name:'Battle drums'}];connection.status={state:'connected',catalog:2,audioContext:'running',hasPrivateDraft:true,peers:2}},refresh:async()=>{},resume:async()=>{},disconnect:async()=>{},playback:async()=>({source:'Music Assistant',state:trackState,title:'Forest at night',position,duration:90,repeat}),
control:async(action,value)=>{window.controlActions.push(action);if(action==='seek')position=value;else if(action==='repeat')repeat=value;else trackState={pause:'paused',resume:'playing',stop:'idle'}[action];},setVolume:value=>{connection.status.volume=value;}};
const Setup=createSetupClass({game,connection,getChoices:async()=>[{provider:'native',id:'native',name:'Foundry fallback'},...catalog],start(){},stop(){},setOverrides(){},onError(){},Base:class{}});
document.querySelector('#app').append(await new Setup()._renderHTML());window.ready=true;
+26
View File
@@ -38,3 +38,29 @@ test('synchronous browser CSP rejection waits for the asynchronous enforcement e
}});
assert.deepEqual(results.map(r=>r.code),['csp-blocked','csp-blocked']);
});
test('probe samples the site permission after each route and records its elapsed time',async t=>{
const permissions=Object.getOwnPropertyDescriptor(globalThis.navigator,'permissions');
let state='prompt';
Object.defineProperty(globalThis.navigator,'permissions',{configurable:true,value:{query:async({name})=>{
if(name!=='local-network')throw new TypeError('Unknown permission');
return {state};
}}});
t.after(()=>{
if(permissions)Object.defineProperty(globalThis.navigator,'permissions',permissions);
else delete globalThis.navigator.permissions;
});
const results=await probeWebSockets('https://ma.example.test',{createSocket:url=>{
const socket={close(){}};
queueMicrotask(()=>{
const opened=url.endsWith('/ws');
state=opened?'granted':'denied';
if(opened)socket.onopen();
else socket.onerror();
});
return socket;
}});
assert.deepEqual(results.map(result=>result.permissions),[{'local-network':'granted'},{'local-network':'denied'}]);
assert.ok(results.every(result=>Number.isSafeInteger(result.elapsedMs)&&result.elapsedMs>=0));
assert.match(diagnosticMessage(results[1]),/reports denied local network access/);
});
+29
View File
@@ -67,6 +67,35 @@ test('scene change during manual never resurrects previous scene', async () => {
await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')});
assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0);
});
test('a scene excursion during a live encounter keeps only its interrupted ambient snapshot',async()=>{
const f=fixture();
const a=scene(), b=scene('B'), fight=combat();
const original={scene:a,combats:[fight]};
await f.controller.update({scene:a});
f.playback={...f.playback,offset:36};
await f.controller.update(original);
await f.controller.update({scene:b,combats:[fight],retainedAmbient:[a]});
assert.equal(f.playback.items[0],'B');
await f.controller.update(original);
assert.equal(f.controller.current.mode,'combat');
await f.controller.update({scene:a});
assert.equal(f.controller.current.mode,'ambient');
assert.equal(f.playback.offset,36);
await f.controller.update(original);
await f.controller.update({scene:b,combats:[fight],retainedAmbient:[a]});
await f.controller.update({scene:b});
assert.equal(f.controller.frames.length,0);
assert.equal((await f.controller.update({scene:a})).restored,false);
});
test('same playlist may change combat mode to boss without restarting the queue',async()=>{
const f=fixture(), fight=combat(), state={scene:scene(),combats:[fight]};
await f.controller.update(state);
const before=f.log.length;
await f.controller.update({...state,combats:[{...fight,bossPlaylist:fight.playlist}]});
assert.equal(f.controller.current.mode,'boss');
assert.equal(f.log.length,before);
});
test('boss removed during manual and deleted combat cannot return', async () => {
const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]};
await f.controller.update(base); await f.controller.update(big);
+35
View File
@@ -62,3 +62,38 @@ test('Foundry bootstrap registers local settings/hooks and disposes without ambi
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[]});
await runtime.refresh();assert.equal(registered,1);assert.ok(callbacks.size>0);runtime.dispose();assert.equal(callbacks.size,0);
});
test('Foundry runtime uses committed unlinked combatant scenes and coalesces initiative changes',async()=>{
const callbacks=new Map(), calls=[];
const Hooks={on(event,callback){callbacks.set(event,callback);return event;},off(event){callbacks.delete(event);}};
const ref=id=>({provider:'ma',id});
const scene={id:'A',active:true,getFlag:()=>({ambient:ref('ambient'),combat:ref('battle'),boss:ref('boss')})};
const encounter={id:'fight',scene:null,active:true,started:false,
combatants:[{id:'token',sceneId:'A',getFlag:()=>undefined}],getFlag:()=>({boss:true})};
const combats=collection([encounter]);
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[scene],combats,
settings:{register(){},get(){return null;}}};
const maProvider={supports:()=>true,resolve:async ref=>ref,apply:async ref=>calls.push(ref.id),stopOwned:async()=>{},snapshot:async()=>({}),
restore:async()=>calls.push('restored')};
const runtime=startNativeRuntime({game,Hooks,campaign:'c',session:'s',ownedPlaylistIds:[],maProvider});
await runtime.refresh();
assert.equal(runtime.musicMode,'ambient');
assert.equal(callbacks.has('combatStart'),false);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient']);
combats.set(encounter.id,encounter);
encounter.started=true;
callbacks.get('updateCombat')(encounter,{round:1,turn:0});
await runtime.controller.tail;
assert.equal(runtime.musicMode,'boss');
callbacks.get('updateCombat')(encounter,{turn:1});
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss']);
combats.delete(encounter.id);
callbacks.get('deleteCombat')(encounter);
await runtime.controller.tail;
assert.deepEqual(calls,['ambient','boss','restored']);
assert.equal(runtime.musicMode,'ambient');
runtime.dispose();
});
+13
View File
@@ -19,6 +19,19 @@ test('native fallback is explicit, manual silence wins and legacy ambient does n
assert.equal(candidates(state)[0].playlist,null);assert.equal(state.scene.playlist.id,'fallback');assert.equal(state.combats[0].playlist.id,'fallback');
assert.equal(buildMusicState({scene:{id:'s',music:{ambient:null,playlist:native('old')}}}).scene.playlist,null);
});
test('unlinked encounters follow their token scenes and a designated boss uses the scene default',()=>{
const encounter={id:'fight',active:true,started:true,sceneId:null,sceneIds:['A'],boss:true};
const cue=(id,combat=encounter,music={ambient:ma('ambient'),combat:ma('fight'),boss:ma('climax')})=>
candidates(buildMusicState({scene:{id,music},combats:[combat]}))[0];
assert.equal(cue('A').mode,'boss');
assert.equal(cue('A').playlist.id,'climax');
assert.equal(cue('A',{...encounter,boss:false}).mode,'combat');
assert.equal(cue('A',{...encounter,started:false}).mode,'ambient');
assert.equal(cue('B').mode,'ambient');
assert.equal(cue('B',{...encounter,sceneId:'B'}).mode,'boss');
assert.equal(cue('A',encounter,{combat:ma('fight')}).mode,'combat');
assert.equal(cue('A',{...encounter,bosses:[{id:'leader',active:true,playlist:ma('custom')}]}).playlist.id,'custom');
});
test('unavailable saved MA selections are preserved but new forged IDs/non-native fallback and role loss deny',async()=>{
let flag={ambient:ma('old')};const document={getFlag:()=>flag,setFlag:async(ns,k,v)=>{flag=v;}};const game={user:{isGM:true}};
await saveMusicAssignments({document,game,choices:[],values:{ambient:referenceKey(ma('old'))}});assert.equal(flag.ambient.id,'old');