Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fbc265b526 | ||
|
|
acc8cbafc6 | ||
|
|
357c904d1b |
No files matched your search
+33
-13
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music architecture — 0.8.0
|
||||
# Adaptive Music architecture — 0.8.3
|
||||
|
||||
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
|
||||
@@ -80,28 +80,46 @@ Up to eight listeners negotiate automatically. A signaling invitation expires
|
||||
after 30 minutes. Established DTLS-SRTP media continues while its listener and GM
|
||||
remain authorized. Failed negotiation times out after 20 seconds and a disconnected
|
||||
peer is dropped after 10 seconds. The reconciliation loop can invite the listener
|
||||
again. One user gesture unlocks browser audio when required. A stable
|
||||
HTMLAudioElement plays the incoming track, with an optional activated Web Audio
|
||||
path. Default ICE uses no public STUN/TURN service.
|
||||
again. Foundry's connection and User document events reconcile listeners
|
||||
without replacing the GM transport. One user gesture unlocks browser audio when
|
||||
required. A stable HTMLAudioElement and optional activated Web Audio path play
|
||||
the incoming track. Each listener's local output applies their saved mute and
|
||||
volume settings downstream of WebRTC. Default ICE uses no public STUN/TURN service.
|
||||
The GM's personal monitor gain sits on the local output branch after the split
|
||||
to the listener stream. Campaign volume remains upstream of that split.
|
||||
|
||||
## 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.
|
||||
Authority requires one active full Gamemaster. Foundry's Assistant GM role is
|
||||
eligible for listener audio. A Web Lock excludes common duplicate tabs. Queue
|
||||
commands retain their existing session and generation fences.
|
||||
|
||||
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
|
||||
idle state for replay. The Playback panel can set MA's dedicated queue repeat
|
||||
mode. Logical pause state is memory-only.
|
||||
|
||||
The floating bar's campaign pause holds the serialized controller. The
|
||||
dedicated MA queue pauses in place, and an active owned native fallback uses
|
||||
its snapshot and stop operations. Play resumes the original position when the
|
||||
cue still applies. A different current cue takes precedence, and the prior
|
||||
cue's pre-pause snapshot remains available under normal restoration rules.
|
||||
The hold belongs to the active GM runtime and ends if that session is disposed.
|
||||
|
||||
Reconnecting to a remembered receiver can preserve its existing queue. When the
|
||||
trusted device auto-reconnects with a populated queue, the next music intent
|
||||
or explicit return to scene music takes control. Crash or reload can lose the
|
||||
@@ -111,7 +129,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 +142,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).
|
||||
@@ -1,5 +1,46 @@
|
||||
# Changelog
|
||||
|
||||
## 0.8.3 — floating music controls
|
||||
|
||||
- Add a draggable, collapsible Adaptive Music bar for players and the GM.
|
||||
Personal mute and volume share the existing listening preferences.
|
||||
- Give the GM separate campaign volume, track skip, and one-click access to
|
||||
playback and overrides. The GM's personal listening level affects only their
|
||||
own Music Assistant output.
|
||||
- Add **Pause all music** and **Play all music** for Adaptive Music. The
|
||||
campaign pause holds scene and combat automation until Play is selected.
|
||||
|
||||
## 0.8.2 — multiplayer continuity and player listening
|
||||
|
||||
- Use Foundry's full Gamemaster role for Music Assistant controller authority.
|
||||
Player, Trusted Player and Assistant GM connections leave the existing host
|
||||
session and catalog running.
|
||||
- Reconcile listener connections on Foundry login, logout and User updates.
|
||||
Late listeners join the existing WebRTC stream, using browser audio activation
|
||||
where required.
|
||||
- Add **Campaign audio** to the player Playlists sidebar. The existing listening
|
||||
window now shows status and offers personal mute and volume, saved per Foundry user.
|
||||
|
||||
## 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,
|
||||
|
||||
+119
-30
@@ -1,42 +1,132 @@
|
||||
# Adaptive Music v0.8.0 handoff
|
||||
# Adaptive Music v0.8.3 handoff
|
||||
|
||||
## Floating music controls
|
||||
|
||||
The music bar mounts at Foundry ready for the full GM and authorized
|
||||
listeners. It shares saved listening preferences with Campaign audio and uses
|
||||
a separate client setting for position and collapse. The GM monitor gain is
|
||||
local. Campaign pause uses the fenced controller and blocks scene transitions
|
||||
until Play. The new controls are packaged under `dist/releases/v0.8.3/` from
|
||||
the `v0.8.3-music-bar` branch in `.local/v080-release-checkout`.
|
||||
|
||||
The development world was inactive during this change. Repeat the new rows in
|
||||
[USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) in an installed world with the GM and
|
||||
at least one player connected. The private browser attempt is recorded under
|
||||
`.local/v083-bar-live.log`.
|
||||
|
||||
## Multiplayer release blocker
|
||||
|
||||
The operator passed the v0.8.1 combat corrections and reported a late-join
|
||||
failure that stopped GM playback and emptied the catalog. In the development
|
||||
world, GUI logins as Player and Trusted Player left v0.8.1 playback running.
|
||||
An Assistant GM join reproduced the loss. Foundry's `isGM` counted both that user
|
||||
and the full Gamemaster. The old single-GM guard closed the MA API and Sendspin
|
||||
sockets when it saw both. The Foundry socket stayed connected.
|
||||
|
||||
v0.8.2 distinguishes the full Gamemaster role from listeners, reconciles
|
||||
roster changes on `userConnected` and User updates, and keeps the player's
|
||||
output controls in the existing Campaign audio window. The sound level is
|
||||
local to the listener. Foundry User Settings retain only mute and volume.
|
||||
See [TESTING.md](TESTING.md) and [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md).
|
||||
|
||||
The sanitized report is [evidence/v0.8.2-live.json](evidence/v0.8.2-live.json).
|
||||
The private test runner and raw evidence are under `.local/v082-multiplayer-*`
|
||||
and `.local/v082-run-mixed.py`. The world server reported v0.8.1 during the
|
||||
v0.8.2 runtime preview. The final package fingerprint matches the tested preview.
|
||||
Three Chrome/Firefox listeners and the GM passed 30 audio checks over six
|
||||
minutes. The remembered GM credential restored the receiver and connected
|
||||
listeners after reload. The test removed its fixtures and restored development
|
||||
world settings. Verify the installed candidate with the operator's
|
||||
party and capture the separate unresolved macOS Firefox private-route failure
|
||||
using the acceptance checklist.
|
||||
|
||||
## 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. The remote-free `.local/v080-release-checkout` has the prior candidate
|
||||
on `v0.8.2-multiplayer` and the floating controls on `v0.8.3-music-bar`.
|
||||
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 was v0.8.0 and all 28 runtime files matched `1ed6b4c`.
|
||||
A later check matched all 28 installed v0.8.1 runtime files to `251a019`.
|
||||
The v0.8.2 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.2/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. The operator passed combat, restoration, boss and
|
||||
manual controls with the corrected v0.8.1 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 +187,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 +277,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.3"
|
||||
python3 scripts/release.py --validate dist/releases/v0.8.3/adaptive-music.zip
|
||||
(cd dist/releases/v0.8.3 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.3.zip.sha256)
|
||||
```
|
||||
|
||||
The headed browser tests use the authorized private Nginx HTTPS route and retain
|
||||
|
||||
+20
-15
@@ -1,4 +1,4 @@
|
||||
# Install and connect — 0.8.0
|
||||
# Install and connect — 0.8.3 candidate
|
||||
|
||||
## Normal setup
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
Foundry user-data `Data/modules/` directory and reload the isolated test world.
|
||||
The ZIP contains one `adaptive-music/` directory. Do not install the outer release
|
||||
bundle or source archive as the module.
|
||||
2. As the single active GM, open Settings → Adaptive Music setup. In **Connection**,
|
||||
2. As the single active full Gamemaster, open Settings → Adaptive Music setup. In **Connection**,
|
||||
enter the private **HTTPS Music Assistant server address** and a dedicated
|
||||
long-lived token from MA → Settings → Profile. On a trusted browser, check
|
||||
**Remember credentials and reconnect on this trusted device**. Select
|
||||
@@ -17,16 +17,21 @@
|
||||
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**.
|
||||
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.
|
||||
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, Trusted Players and Assistant GMs can open **Campaign audio** in the
|
||||
Playlists sidebar. Select **Enable Audio** if the browser requires activation.
|
||||
Mute and listening volume affect only that user's sound. Foundry saves those
|
||||
preferences for the user. The GM can use **Enable GM audio** in Playback after
|
||||
an automatic connection.
|
||||
|
||||
The opted-in browser can reconnect on world entry. **Disconnect** ends its live
|
||||
session and pauses automatic reconnection until you connect again.
|
||||
@@ -92,7 +97,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 multiplayer baseline was v0.8.1.
|
||||
|
||||
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 +109,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.3'
|
||||
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-v083.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 +130,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.3**. 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 +141,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.3 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.3/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.3`, 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
|
||||
|
||||
+100
-8
@@ -1,4 +1,96 @@
|
||||
# Adaptive Music progress — 0.8.0 release audit
|
||||
# Adaptive Music progress — 0.8.3 music bar
|
||||
|
||||
## v0.8.3 floating controls
|
||||
|
||||
The floating bar gives players a direct route to activation, local volume and
|
||||
mute. The GM has independent local listening controls, shared campaign volume,
|
||||
track skip and a shortcut to the detailed Playback window. Campaign pause
|
||||
holds automated music cues and preserves the active queue's position. Play
|
||||
selects the current cue when it changed during the hold.
|
||||
|
||||
Development-world acceptance is pending. The test route returned Foundry's
|
||||
no-active-game message. See [TESTING.md](TESTING.md) for the automated scope
|
||||
and [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md) for the installed checks.
|
||||
|
||||
## v0.8.2 release-blocking regression
|
||||
|
||||
The operator passed v0.8.1 combat, initiative, boss, restoration, manual controls
|
||||
and audio quality. They then reported that a late join stopped the host and
|
||||
emptied the catalog. Development GUI tests kept audio running for Player and
|
||||
Trusted Player, and reproduced the failure with an Assistant GM while the
|
||||
original GM's Foundry socket stayed connected. The v0.8.1 host predicate used
|
||||
the broader Foundry `isGM` flag for exclusive Music Assistant authority.
|
||||
|
||||
The v0.8.2 predicate considers the full Gamemaster role and treats the
|
||||
Assistant GM as a listener for this module. Join and logout reconciliation
|
||||
uses Foundry's connection event as well as User updates. Campaign audio
|
||||
offers per-user mute, volume and status through one existing listening window.
|
||||
|
||||
Independent Chrome and Firefox sessions in the development world passed late
|
||||
and simultaneous joins. All three regular listeners received decoded audio, and
|
||||
the Assistant GM's join and departure kept the host playing. Player-side mute
|
||||
and volume affected only that player and persisted across logout and login.
|
||||
Combat, Boss, Ambient restoration, scene changes and manual playback passed
|
||||
with three listeners connected. Across six minutes of playback the GM and
|
||||
all listeners had measurable audio at 30 of 30 checks. The GM's remembered
|
||||
credential reopened the same receiver with the queue intact, and all three
|
||||
listeners recovered. The v0.8.2 bundle is staged under `dist/releases/v0.8.2/`.
|
||||
See [TESTING.md](TESTING.md) for scope and [USER-ACCEPTANCE.md](USER-ACCEPTANCE.md)
|
||||
for the exact installed build. The separate macOS Firefox connection failure
|
||||
still needs the operator's private-route diagnostics.
|
||||
|
||||
## 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 operator subsequently passed the corrected
|
||||
workflow in v0.8.1.
|
||||
|
||||
## 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 operator passed the v0.8.1 combat acceptance.
|
||||
|
||||
## 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 +152,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 +192,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.
|
||||
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music — 0.8.0
|
||||
# Adaptive Music — 0.8.3 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,11 +11,23 @@ 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.
|
||||
Players can open **Campaign audio** from the Playlists sidebar to check their
|
||||
connection, enable sound, mute, or adjust their own volume. Audio comes from the
|
||||
full GM's browser. Personal listening preferences are saved to the Foundry account.
|
||||
|
||||
The floating **Adaptive Music** bar opens on world entry. Drag its title to
|
||||
move it or select **Hide** to collapse it. **My volume** and **Mute** control
|
||||
the current browser's Adaptive Music stream. The GM also gets **Campaign
|
||||
volume**, **Skip track**, and one-click access to the full **Playback controls**.
|
||||
**Pause all music** pauses the campaign for every listener and holds automatic
|
||||
cues. **Play all music** resumes the saved position or plays the cue that now
|
||||
applies if the scene or combat changed while paused.
|
||||
|
||||
The GM browser hosts Music Assistant playback and player WebRTC connections. Keep
|
||||
that tab open. The encrypted device credential stays in the browser profile where
|
||||
|
||||
+13
-2
@@ -1,4 +1,4 @@
|
||||
# Adaptive Music security — 0.8.0
|
||||
# Adaptive Music security — 0.8.3
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -49,7 +51,16 @@ selection, grouping, transfer or global stop is offered. Unknown writes latch cl
|
||||
Queue snapshots are signed and campaign/session/fence/generation-bound; later
|
||||
sessions reject them. Browser authority cannot replace a distributed server fence.
|
||||
|
||||
Players receive scoped expiring encrypted capabilities, not MA secrets or addresses.
|
||||
Player, Trusted Player and Assistant GM sessions receive scoped, expiring audio
|
||||
capabilities. The module grants Music Assistant controller authority only to the
|
||||
sole active full Gamemaster. The listener interface can change the current
|
||||
Foundry user's local output settings. This uses a separate User Setting with
|
||||
only volume and mute values. The GM's personal volume and mute use the local
|
||||
monitor branch. The campaign pause uses the existing authorized queue commands
|
||||
and the explicitly owned native fallback when active.
|
||||
Foundry still enforces the world's document permissions. The Assistant GM role
|
||||
can carry world administration privileges independently of Adaptive Music's
|
||||
controller role.
|
||||
Public ephemeral keys on permission-controlled User documents authenticate invitation
|
||||
delivery. Both ordinary test players were denied a write to the GM’s User flags in
|
||||
the installed development world. SDP is encrypted, bounded, replay protected and validated for a single audio
|
||||
|
||||
+174
-6
@@ -1,9 +1,177 @@
|
||||
# Adaptive Music verification — 0.8.0
|
||||
# Adaptive Music verification — 0.8.3
|
||||
|
||||
## Executed evidence
|
||||
|
||||
The source archive includes sanitized evidence separately from private .local inputs.
|
||||
|
||||
### v0.8.3 floating music bar
|
||||
|
||||
The JavaScript regression suite covers cue changes while paused, same-queue
|
||||
resume, native ambient position, failed transitions and canceled authority.
|
||||
The GM audio graph test checks that the local monitor and the listener output
|
||||
are on separate branches. Chromium, Firefox and WebKit DOM fixtures exercise
|
||||
player and GM controls, personal and campaign volume, pause and play, and the
|
||||
bar's collapse and drag controls. All 122 JavaScript and 17 Python tests passed.
|
||||
Repository and upstream checks passed, and npm audit reported zero vulnerabilities.
|
||||
The development server reported no active game session at the join screen, so
|
||||
live v0.8.3 acceptance remains pending.
|
||||
|
||||
### Installed v0.8.1 operator follow-up
|
||||
|
||||
The operator confirmed combat automation, initiative advancement, boss music,
|
||||
ambient restoration, manual controls and audio quality. The multiplayer report
|
||||
was a separate failure. When another user joined, playback stopped and Scene
|
||||
Music lost its catalog until that user left.
|
||||
|
||||
### v0.8.2 multiplayer reproduction
|
||||
|
||||
With v0.8.1, the GM started audio and had a populated catalog before any other
|
||||
account joined. Independent GUI logins as Player and Trusted Player kept the
|
||||
GM catalog and each listener received audio. Joining as Assistant GM reproduced
|
||||
the reported audio and catalog failure. Foundry reported one active full
|
||||
Gamemaster and two active `isGM` users. The GM's two MA sockets closed while the
|
||||
Foundry socket remained connected. The previous authority check counted
|
||||
`isGM` users and its User update handler closed the GM audio host and emptied
|
||||
the catalog when the count rose above one.
|
||||
|
||||
Earlier multiplayer runs joined the GM and two ordinary players before starting
|
||||
music. Those runs exercised real audio and permissions, and missed both the
|
||||
late join during active playback and Foundry's Assistant GM role distinction.
|
||||
v0.8.2 uses the full Gamemaster role for the exclusive controller and uses the
|
||||
documented connection hook to reconcile listener joins and departures.
|
||||
The role of the account in the operator's original report was unspecified.
|
||||
|
||||
[Foundry User API](https://foundryvtt.com/api/v14/classes/foundry.documents.User.html),
|
||||
[role constants](https://foundryvtt.com/api/variables/CONST.USER_ROLES.html),
|
||||
and [userConnected hook](https://foundryvtt.com/api/functions/hookEvents.userConnected.html).
|
||||
|
||||
### v0.8.2 live multiplayer candidate
|
||||
|
||||
The authorized Foundry 14.371 development world ran the package's runtime via
|
||||
browser preview on Ubuntu using Chrome for Testing and Firefox. Foundry still
|
||||
reported the server-installed v0.8.1, which independently matched all 28 files
|
||||
from the local v0.8.1 runtime. The preview used normal browser TLS checks and
|
||||
real Foundry accounts. It measured the host output and decoded listener audio.
|
||||
|
||||
The GM started music alone. A Chrome Player joined first, then a Firefox
|
||||
Trusted Player and Chrome Player joined together. An additional Assistant GM
|
||||
joined and left in Firefox. The GM kept its receiver, both MA sockets and all
|
||||
13 catalog choices. A Player's 25% volume yielded about one quarter of its
|
||||
input RMS. Mute brought that player's local output to zero while it continued
|
||||
receiving audio, and the GM and other listeners kept hearing audio. A fresh
|
||||
login retained the Player's mute and volume. Both Player and Trusted Player
|
||||
were denied changes to shared automation and a test scene's music flags.
|
||||
|
||||
The world used distinct ambient, combat and boss playlists. All three listeners
|
||||
followed the native tracker cues, ambient restoration, scene activation and
|
||||
manual playback. The normal encounter used an unstarted Foundry fixture after
|
||||
the automation pointer missed the token HUD. The boss encounter used the
|
||||
native token HUD. Both used the native Combat Tracker to roll initiative,
|
||||
start and end combat. Ambient restored to track index 0 at 41 and 66 seconds.
|
||||
|
||||
Over 360 seconds, the GM catalog and sockets stayed stable. The GM and all
|
||||
three listeners had a measurable signal at 30 of 30 checks, and each listener's
|
||||
received bytes and audio samples advanced at every interval. The remembered GM
|
||||
credential reattached to the same receiver after reload, kept the queue and
|
||||
restored audio to all three listeners. Player sessions made zero requests to
|
||||
MA. The test restored the development world, and all MA queue writes targeted
|
||||
the dedicated receiver.
|
||||
|
||||
The automated suite passed 117 JavaScript and 17 Python tests. The Chromium,
|
||||
Firefox and WebKit setup and credential fixtures passed, including browser
|
||||
restart and fixture revocation. Repository and upstream audits passed. npm
|
||||
audit reported zero vulnerabilities. Measurements and scope are recorded in the
|
||||
[sanitized v0.8.2 evidence](evidence/v0.8.2-live.json).
|
||||
|
||||
### 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 operator later passed the corrected combat flow and
|
||||
manual playback controls in v0.8.1.
|
||||
|
||||
### 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 +226,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 +370,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.
|
||||
|
||||
|
||||
+61
-11
@@ -1,14 +1,56 @@
|
||||
# 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.1 operator results
|
||||
|
||||
The operator confirmed automatic combat, initiative progression, boss music,
|
||||
ambient restoration, manual controls, and audio quality. They also reported
|
||||
that joining the world during playback stopped the GM audio and left Scene
|
||||
Music without a catalog. Playback recovered after logout. Multiplayer
|
||||
acceptance remains the v0.8.2 release gate.
|
||||
|
||||
## 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. |
|
||||
| Passed in v0.8.1 | 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.3 run, confirm **Manage Modules** shows Adaptive Music
|
||||
**0.8.3**. 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,18 +58,26 @@ 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. |
|
||||
| ☐ 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. |
|
||||
| ☐ 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. |
|
||||
| ☐ Late and simultaneous joins | Start music with the GM alone. Join as a Player, then join two more sessions together, including a Trusted Player. Use Chrome and Firefox. Repeat with an Assistant Gamemaster if that role is used in your world. | The GM keeps the same cue, receiver and catalog. Each player hears current audio after any needed browser activation. A Foundry account is sufficient for listening. |
|
||||
| ☐ Personal listening controls | In the Playlists sidebar open **Campaign audio**. Change one listener to 25% and toggle **Mute**. Log out and back in as that user, then unmute. | Only that user changes level. The user's mute and volume survive reentry. The GM and the other listeners continue playing. |
|
||||
| ☐ Floating music bar | As a player, drag the bar and select **Hide**, then **Show**. Set **My volume** and mute. As the GM, mute your own output and change **Campaign volume**. | The bar stays available on the map. Personal controls affect only the current browser, and Campaign volume affects the shared Music Assistant stream. |
|
||||
| ☐ Pause and play all | As the GM, pause and play once on the same cue. Pause again and activate a scene with a different playlist before selecting Play. | The group hears silence while paused. The first Play resumes at the saved position. The second Play starts the new scene's cue. Native effects continue under Foundry's own controls. |
|
||||
| ☐ Multiplayer cues | Keep the group connected through combat, boss, End Combat, a scene change and a manual override. | All listeners hear the same cue changes while retaining their own volume settings. |
|
||||
| ☐ 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. |
|
||||
| ☐ Disconnect and forget | Click **Disconnect**, restart the browser and verify it stays disconnected. Reconnect intentionally, click **Forget Credentials**, then restart again. | Disconnect pauses automatic reconnect. Forgetting removes the stored device token. The next connection requires token entry. |
|
||||
| ☐ MA revocation | If testing revocation, use a disposable development token. At the end of that test, revoke only that token in MA Profile and retry from the same browser. | The revoked token cannot authenticate and the setup reports auth denial. Re-enter the approved token and private address before using the prepared scenes again. |
|
||||
|
||||
If a check fails, record local time with timezone, the browser and OS version,
|
||||
the scene and cue, and whether the GM, a player or both were affected. For an
|
||||
audio artifact, note the track position, duration and whether the tab was
|
||||
the scene and cue, and whether the GM, a player or both were affected. For a
|
||||
join failure, note the Foundry role that joined, the join order and whether
|
||||
Scene Music lost its catalog. For an audio artifact, note the track position,
|
||||
duration and whether the tab was
|
||||
hidden, reconnecting or changing cues. Copy **Connection → Copy connection
|
||||
diagnostics** for the GM and record the status shown in **Campaign audio**
|
||||
for each affected listener. For connection issues, run **Check browser connection**
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
],
|
||||
"operatorAcceptanceV081": {
|
||||
"source": "Operator-reported installed v0.8.1 manual testing",
|
||||
"passed": [
|
||||
"Automatic combat music",
|
||||
"Initiative progression",
|
||||
"Boss music",
|
||||
"Ambient restoration",
|
||||
"Manual controls",
|
||||
"Audio quality"
|
||||
],
|
||||
"releaseBlockingFailure": "A player login stopped GM playback and removed the catalog; logout restored fetching.",
|
||||
"reportedPlayerRole": "Not specified"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,587 @@
|
||||
{
|
||||
"version": "0.8.2",
|
||||
"scope": "Private Foundry development-world baseline and mixed-browser candidate runtime previews, plus local regressions",
|
||||
"publicationReady": false,
|
||||
"serverInstalledExactVersion": false,
|
||||
"completedCoreRunPassed": true,
|
||||
"macPrivateRouteVerified": false,
|
||||
"operatorAcceptanceV081": {
|
||||
"source": "Operator-reported installed v0.8.1 manual testing",
|
||||
"passed": [
|
||||
"Automatic combat music",
|
||||
"Initiative progression",
|
||||
"Boss music",
|
||||
"Ambient restoration",
|
||||
"Manual controls",
|
||||
"Audio quality"
|
||||
],
|
||||
"releaseBlockingFailure": "A player login stopped GM playback and removed the catalog; logout restored fetching.",
|
||||
"reportedPlayerRole": "Not specified"
|
||||
},
|
||||
"installedBaselineRuntimeComparison": {
|
||||
"scope": "anonymous exact-path read of installed Foundry module files over trusted private HTTPS",
|
||||
"manifestStatus": 200,
|
||||
"installedVersion": "0.8.1",
|
||||
"runtimeFilesCompared": 28,
|
||||
"runtimeFilesIdentical": 28,
|
||||
"runtimeMismatches": []
|
||||
},
|
||||
"baseline": {
|
||||
"at": "2026-12-05T18:53:48.339Z",
|
||||
"scope": "Foundry development-world GUI logins with independent browser contexts, dedicated receiver",
|
||||
"runtimeAssetsSHA256": "fc23b02b1df425ed3154e43aed3f60088aa797c38a862efeaa4781471bad8093",
|
||||
"packageSHA256": "8e27dd86e1f93d3a0785a28a49bbe20cb35c444f5a242e876ec1cc882dedd4e9",
|
||||
"foundry": "14.371",
|
||||
"serverVersion": "0.8.1",
|
||||
"engines": {
|
||||
"chromium": "159.0.8154.6"
|
||||
},
|
||||
"onlyDedicatedQueueWritten": true,
|
||||
"cleanup": true,
|
||||
"confirmedRootCase": "A late Assistant GM join made the old isGM-based guard close both MA sockets.",
|
||||
"gmAlone": {
|
||||
"summaryConnected": true,
|
||||
"summaryCatalogChoices": 13,
|
||||
"hasAvailableCatalog": true,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 1,
|
||||
"activeFullGMs": 1,
|
||||
"rms": 0.04012488569058989
|
||||
},
|
||||
"lateJoin": [
|
||||
{
|
||||
"description": "Player",
|
||||
"role": 1,
|
||||
"foundryIsGM": false,
|
||||
"summaryConnected": true,
|
||||
"summaryCatalogChoices": 13,
|
||||
"hasAvailableCatalog": true,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 1,
|
||||
"activeFullGMs": 1,
|
||||
"gmClockAdvanced": true,
|
||||
"maSocketsClosedSincePlay": 0,
|
||||
"listenerAudio": true
|
||||
},
|
||||
{
|
||||
"description": "Trusted Player",
|
||||
"role": 2,
|
||||
"foundryIsGM": false,
|
||||
"summaryConnected": true,
|
||||
"summaryCatalogChoices": 13,
|
||||
"hasAvailableCatalog": true,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 1,
|
||||
"activeFullGMs": 1,
|
||||
"gmClockAdvanced": true,
|
||||
"maSocketsClosedSincePlay": 0,
|
||||
"listenerAudio": true
|
||||
},
|
||||
{
|
||||
"description": "Assistant GM control case",
|
||||
"role": 3,
|
||||
"foundryIsGM": true,
|
||||
"summaryConnected": true,
|
||||
"summaryCatalogChoices": 13,
|
||||
"hasAvailableCatalog": false,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 2,
|
||||
"activeFullGMs": 1,
|
||||
"gmClockAdvanced": false,
|
||||
"maSocketsClosedSincePlay": 2
|
||||
}
|
||||
],
|
||||
"notes": "The hidden connection tab still displayed its stale connected summary. The live Foundry socket, closed MA sockets, stopped audio clock, and missing Scene Music catalog were measured independently.",
|
||||
"foundrySocketDisconnects": 0
|
||||
},
|
||||
"candidateJoinsAndLocalControls": {
|
||||
"at": "2026-12-05T19:05:45.974Z",
|
||||
"scope": "Foundry development-world GUI logins with independent browser contexts, dedicated receiver",
|
||||
"runtimeAssetsSHA256": "001640e13504ee0dd0b4d1d1cad22134daf194e54a6e3cd3839f1bbc6f06de3e",
|
||||
"packageSHA256": "c10bbb550ec600c582e5f044c4dcf7b79652879c36b7d8a9de066a87d5f1b35f",
|
||||
"foundry": "14.371",
|
||||
"serverVersion": "0.8.1",
|
||||
"engines": {
|
||||
"chromium": "159.0.8154.6",
|
||||
"firefox": "159.0"
|
||||
},
|
||||
"onlyDedicatedQueueWritten": true,
|
||||
"cleanup": true,
|
||||
"phases": {
|
||||
"gmAlone": {
|
||||
"connected": true,
|
||||
"catalogChoices": 13,
|
||||
"hasAvailableCatalog": true,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 1,
|
||||
"activeFullGMs": 1,
|
||||
"rms": 0.0376457506053313
|
||||
},
|
||||
"individualJoin": {
|
||||
"permission": {
|
||||
"role": 1,
|
||||
"foundryIsGM": false
|
||||
},
|
||||
"audio": {
|
||||
"rms": 0.18813604887456326,
|
||||
"bytes": 1374,
|
||||
"energy": 0.029702336390144513,
|
||||
"samples": 13920
|
||||
},
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.11432
|
||||
},
|
||||
"gate": {
|
||||
"controlRejected": true,
|
||||
"gmMenuAvailable": false,
|
||||
"sceneWriteRejected": true
|
||||
}
|
||||
},
|
||||
"simultaneousJoin": {
|
||||
"listeners": [
|
||||
{
|
||||
"bytes": 87156,
|
||||
"rms": 0.14137
|
||||
},
|
||||
{
|
||||
"bytes": 32928,
|
||||
"rms": 0.13995
|
||||
},
|
||||
{
|
||||
"bytes": 18367,
|
||||
"rms": 0.11148
|
||||
}
|
||||
],
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.22792
|
||||
},
|
||||
"roles": [
|
||||
{
|
||||
"role": 2,
|
||||
"foundryIsGM": false
|
||||
},
|
||||
{
|
||||
"role": 1,
|
||||
"foundryIsGM": false
|
||||
}
|
||||
],
|
||||
"gates": [
|
||||
{
|
||||
"controlRejected": true,
|
||||
"gmMenuAvailable": false,
|
||||
"sceneWriteRejected": true
|
||||
},
|
||||
{
|
||||
"controlRejected": true,
|
||||
"gmMenuAvailable": false,
|
||||
"sceneWriteRejected": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"assistantJoin": {
|
||||
"permission": {
|
||||
"role": 3,
|
||||
"foundryIsGM": true
|
||||
},
|
||||
"audio": {
|
||||
"rms": 0.1857330142680303,
|
||||
"bytes": 20569,
|
||||
"energy": 0.7933958871843928,
|
||||
"samples": 120480
|
||||
},
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.11677
|
||||
},
|
||||
"gate": {
|
||||
"controlRejected": true,
|
||||
"gmMenuAvailable": false,
|
||||
"sceneWriteRejected": null
|
||||
}
|
||||
},
|
||||
"assistantLogout": {
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.12284
|
||||
},
|
||||
"remaining": [
|
||||
{
|
||||
"bytes": 159353,
|
||||
"rms": 0.12483
|
||||
},
|
||||
{
|
||||
"bytes": 105182,
|
||||
"rms": 0.12524
|
||||
},
|
||||
{
|
||||
"bytes": 162382,
|
||||
"rms": 0.27907
|
||||
}
|
||||
]
|
||||
},
|
||||
"localMix": {
|
||||
"quarter": {
|
||||
"local": 0.027069456983698843,
|
||||
"incoming": 0.1082382650030415
|
||||
},
|
||||
"muted": {
|
||||
"local": 0,
|
||||
"incoming": 0.10330119351387644
|
||||
},
|
||||
"untouched": [
|
||||
{
|
||||
"local": 0.12999302119140788,
|
||||
"incoming": 0.12999302119140788
|
||||
},
|
||||
{
|
||||
"local": 0.10522020398150214,
|
||||
"incoming": 0.10522020398150214
|
||||
}
|
||||
],
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.12545
|
||||
}
|
||||
},
|
||||
"reconnect": {
|
||||
"savedVolumeAndMute": true,
|
||||
"rejoinedAudio": {
|
||||
"local": 0.0043508963105295655,
|
||||
"incoming": 0.09564166615949304
|
||||
},
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.1574
|
||||
},
|
||||
"others": [
|
||||
{
|
||||
"bytes": 150275,
|
||||
"rms": 0.16162
|
||||
},
|
||||
{
|
||||
"bytes": 251804,
|
||||
"rms": 0.11233
|
||||
},
|
||||
{
|
||||
"bytes": 3739,
|
||||
"rms": 0.1435
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"harnessNote": "Join, control isolation and rejoin checks passed. A test pointer timeout starting the subsequent encounter led to a separate focused transition and duration run."
|
||||
},
|
||||
"candidateTransitionsAndDuration": {
|
||||
"at": "2026-12-05T19:08:22.486Z",
|
||||
"scope": "Foundry development-world GUI logins with independent browser contexts, dedicated receiver",
|
||||
"runtimeAssetsSHA256": "001640e13504ee0dd0b4d1d1cad22134daf194e54a6e3cd3839f1bbc6f06de3e",
|
||||
"packageSHA256": "c10bbb550ec600c582e5f044c4dcf7b79652879c36b7d8a9de066a87d5f1b35f",
|
||||
"foundry": "14.371",
|
||||
"serverVersion": "0.8.1",
|
||||
"engines": {
|
||||
"chromium": "159.0.8154.6",
|
||||
"firefox": "159.0"
|
||||
},
|
||||
"onlyDedicatedQueueWritten": true,
|
||||
"cleanup": true,
|
||||
"phases": {
|
||||
"gmAlone": {
|
||||
"connected": true,
|
||||
"catalogChoices": 13,
|
||||
"hasAvailableCatalog": true,
|
||||
"socketConnected": true,
|
||||
"activeGMFlags": 1,
|
||||
"activeFullGMs": 1,
|
||||
"rms": 0.04257364351922578
|
||||
},
|
||||
"transitionParty": {
|
||||
"roles": [
|
||||
{
|
||||
"role": 1,
|
||||
"foundryIsGM": false
|
||||
},
|
||||
{
|
||||
"role": 2,
|
||||
"foundryIsGM": false
|
||||
},
|
||||
{
|
||||
"role": 1,
|
||||
"foundryIsGM": false
|
||||
}
|
||||
],
|
||||
"audible": [
|
||||
{
|
||||
"bytes": 45245,
|
||||
"rms": 0.10862
|
||||
},
|
||||
{
|
||||
"bytes": 32124,
|
||||
"rms": 0.10361
|
||||
},
|
||||
{
|
||||
"bytes": 1287,
|
||||
"rms": 0.01968
|
||||
}
|
||||
],
|
||||
"gm": {
|
||||
"catalogChoices": 13,
|
||||
"rms": 0.09174
|
||||
}
|
||||
},
|
||||
"combat": {
|
||||
"prepared": "unstarted-core-fixture",
|
||||
"listeners": [
|
||||
{
|
||||
"bytes": 120490,
|
||||
"rms": 0.03282
|
||||
},
|
||||
{
|
||||
"bytes": 107374,
|
||||
"rms": 0.03426
|
||||
},
|
||||
{
|
||||
"bytes": 150933,
|
||||
"rms": 0.0437
|
||||
}
|
||||
],
|
||||
"restored": {
|
||||
"index": 0,
|
||||
"seconds": 41,
|
||||
"allListeners": [
|
||||
{
|
||||
"bytes": 170792,
|
||||
"rms": 0.09777
|
||||
},
|
||||
{
|
||||
"bytes": 157698,
|
||||
"rms": 0.09725
|
||||
},
|
||||
{
|
||||
"bytes": 253720,
|
||||
"rms": 0.10896
|
||||
}
|
||||
]
|
||||
},
|
||||
"initiativeDidNotRestart": true
|
||||
},
|
||||
"boss": {
|
||||
"prepared": "token-hud",
|
||||
"listeners": [
|
||||
{
|
||||
"bytes": 273794,
|
||||
"rms": 0.07048
|
||||
},
|
||||
{
|
||||
"bytes": 260726,
|
||||
"rms": 0.06743
|
||||
},
|
||||
{
|
||||
"bytes": 451959,
|
||||
"rms": 0.04784
|
||||
}
|
||||
],
|
||||
"restored": {
|
||||
"index": 0,
|
||||
"seconds": 66,
|
||||
"allListeners": [
|
||||
{
|
||||
"bytes": 314211,
|
||||
"rms": 0.10057
|
||||
},
|
||||
{
|
||||
"bytes": 301203,
|
||||
"rms": 0.09554
|
||||
},
|
||||
{
|
||||
"bytes": 534595,
|
||||
"rms": 0.10016
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"sceneAndManual": {
|
||||
"otherListeners": [
|
||||
{
|
||||
"bytes": 346215,
|
||||
"rms": 0.02421
|
||||
},
|
||||
{
|
||||
"bytes": 333348,
|
||||
"rms": 0.02596
|
||||
},
|
||||
{
|
||||
"bytes": 598733,
|
||||
"rms": 0.02808
|
||||
}
|
||||
],
|
||||
"manualListeners": [
|
||||
{
|
||||
"bytes": 384431,
|
||||
"rms": 0.04368
|
||||
},
|
||||
{
|
||||
"bytes": 371703,
|
||||
"rms": 0.04618
|
||||
},
|
||||
{
|
||||
"bytes": 675809,
|
||||
"rms": 0.03875
|
||||
}
|
||||
],
|
||||
"backToAutomation": [
|
||||
{
|
||||
"bytes": 406853,
|
||||
"rms": 0.03773
|
||||
},
|
||||
{
|
||||
"bytes": 394235,
|
||||
"rms": 0.03511
|
||||
},
|
||||
{
|
||||
"bytes": 720158,
|
||||
"rms": 0.0477
|
||||
}
|
||||
]
|
||||
},
|
||||
"soak": {
|
||||
"seconds": 360.0130000000001,
|
||||
"intervals": 30,
|
||||
"stableCatalogAndSockets": true,
|
||||
"listenerPacketsAdvancedEveryInterval": true,
|
||||
"gmAudibleIntervals": 30,
|
||||
"listenerAudibleIntervals": [
|
||||
30,
|
||||
30,
|
||||
30
|
||||
]
|
||||
},
|
||||
"gmCredentialReload": {
|
||||
"reattachedSameReceiver": true,
|
||||
"tokenFieldEmpty": true,
|
||||
"queuePreserved": true,
|
||||
"listenersRecovered": [
|
||||
{
|
||||
"bytes": 11630,
|
||||
"rms": 0.13284
|
||||
},
|
||||
{
|
||||
"bytes": 11665,
|
||||
"rms": 0.12935
|
||||
},
|
||||
{
|
||||
"bytes": 9506,
|
||||
"rms": 0.15943
|
||||
}
|
||||
]
|
||||
},
|
||||
"playerDirectMusicAssistant": 0
|
||||
}
|
||||
},
|
||||
"credentialPersistenceFixtures": [
|
||||
{
|
||||
"engine": "chromium",
|
||||
"browser": "159.0.8154.6",
|
||||
"lockedKeys": true,
|
||||
"scopeIsolation": true,
|
||||
"authenticatedAfterBrowserRestart": true,
|
||||
"revokedAuthDeniedByFixture": true,
|
||||
"pause": true,
|
||||
"forgetSurvivedBrowserRestart": true
|
||||
},
|
||||
{
|
||||
"engine": "firefox",
|
||||
"browser": "159.0",
|
||||
"lockedKeys": true,
|
||||
"scopeIsolation": true,
|
||||
"authenticatedAfterBrowserRestart": true,
|
||||
"revokedAuthDeniedByFixture": true,
|
||||
"pause": true,
|
||||
"forgetSurvivedBrowserRestart": true
|
||||
},
|
||||
{
|
||||
"engine": "webkit",
|
||||
"browser": "27.2",
|
||||
"lockedKeys": true,
|
||||
"scopeIsolation": true,
|
||||
"authenticatedAfterBrowserRestart": true,
|
||||
"revokedAuthDeniedByFixture": true,
|
||||
"pause": true,
|
||||
"forgetSurvivedBrowserRestart": true
|
||||
}
|
||||
],
|
||||
"regressions": {
|
||||
"javascriptPassed": 117,
|
||||
"pythonPassed": 17,
|
||||
"npmAuditReportedVulnerabilities": 0,
|
||||
"upstreamProvenance": "pass",
|
||||
"repositoryPrivacyAndAttribution": "pass",
|
||||
"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": []
|
||||
}
|
||||
]
|
||||
},
|
||||
"acceptanceRemaining": [
|
||||
"Install and manually accept exact v0.8.2 in the operator multiplayer session",
|
||||
"Retest the original macOS Firefox private-route connection separately"
|
||||
]
|
||||
}
|
||||
+2
-2
@@ -2,7 +2,7 @@
|
||||
"id": "adaptive-music",
|
||||
"title": "Adaptive Music",
|
||||
"description": "Scene and combat playlist automation with native Foundry fallback, private GM Music Assistant setup and Sendspin/WebRTC campaign audio.",
|
||||
"version": "0.8.0",
|
||||
"version": "0.8.3",
|
||||
"authors": [
|
||||
{
|
||||
"name": "CheddahBoxMB"
|
||||
@@ -24,5 +24,5 @@
|
||||
"socket": true,
|
||||
"url": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music",
|
||||
"manifest": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/raw/branch/main/module.json",
|
||||
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.0/adaptive-music.zip"
|
||||
"download": "https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.3/adaptive-music.zip"
|
||||
}
|
||||
@@ -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');
|
||||
@@ -61,6 +76,43 @@ try{
|
||||
await page.getByRole('button',{name:'Stop playback',exact:true}).click();await page.getByText('Stopped',{exact:true}).waitFor();
|
||||
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));
|
||||
await page.evaluate(()=>window.listener());assert.equal(await page.locator('input:not([type="range"])').count(),0);
|
||||
assert.equal(await page.getByRole('slider',{name:'Listening volume'}).count(),1);
|
||||
await page.getByRole('button',{name:'Mute',exact:true}).click();await page.getByRole('button',{name:'Unmute',exact:true}).waitFor();
|
||||
await page.getByRole('button',{name:'Enable Audio'}).click();assert.equal(await page.evaluate(()=>window.activated),true);assert.deepEqual(errors,[]);
|
||||
const bar=page.getByRole('region',{name:'Adaptive Music bar'});
|
||||
await page.setViewportSize({width:380,height:600});
|
||||
await page.evaluate(()=>window.musicBar(false));
|
||||
await bar.getByRole('button',{name:'Enable audio'}).click();
|
||||
await bar.getByRole('button',{name:'Mute',exact:true}).click();
|
||||
await bar.getByRole('slider',{name:'My volume'}).press('ArrowLeft');
|
||||
assert.equal(await bar.getByRole('button',{name:'Pause all music'}).count(),0);
|
||||
assert.equal(await bar.getByRole('slider',{name:'Campaign volume'}).count(),0);
|
||||
await bar.getByRole('button',{name:'Hide',exact:true}).click();
|
||||
await bar.getByRole('slider').waitFor({state:'hidden'});
|
||||
await bar.getByRole('button',{name:'Show',exact:true}).click();
|
||||
assert.deepEqual(await page.evaluate(()=>window.barActions),[
|
||||
['enable'],['local',{muted:true}],['local',{volume:99}],['layout',{collapsed:true}],['layout',{collapsed:false}],
|
||||
]);
|
||||
await page.evaluate(()=>window.musicBar(true));
|
||||
assert.ok((await bar.boundingBox()).width<=380-16);
|
||||
await bar.getByRole('button',{name:'Pause all music'}).click();
|
||||
await bar.getByText('Campaign music paused').waitFor();
|
||||
assert.equal(await bar.getByRole('button',{name:'Skip track'}).isDisabled(),true);
|
||||
await bar.getByRole('button',{name:'Play all music'}).click();
|
||||
await bar.getByRole('button',{name:'Skip track'}).click();
|
||||
await bar.getByRole('slider',{name:'Campaign volume'}).press('ArrowLeft');
|
||||
await bar.getByRole('button',{name:'Playback controls'}).click();
|
||||
assert.deepEqual(await page.evaluate(()=>window.barActions),[
|
||||
['pause',true],['pause',false],['skip'],['campaign-volume',99],['playback'],
|
||||
]);
|
||||
const grip=await bar.getByText('Adaptive Music',{exact:true}).boundingBox();
|
||||
await page.mouse.move(grip.x+20,grip.y+5);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(4,260,{steps:5});
|
||||
await page.mouse.up();
|
||||
assert.equal(Math.round((await bar.boundingBox()).x),8);
|
||||
assert.equal(await page.evaluate(()=>window.barActions.at(-1)[0]),'layout');
|
||||
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','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','floating bar roles, local vs campaign volume, pause/play, collapse and drag'],pageErrors:errors},null,2));
|
||||
}finally{await browser?.close();await new Promise(resolve=>server.close(resolve));}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {activeMusicGM,isMusicListener} from '../foundry/authority.mjs';
|
||||
const ns='adaptive-music',flag='audioPublicKey',channel='module.adaptive-music';
|
||||
const encode=a=>btoa(String.fromCharCode(...a));
|
||||
const decode=s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));
|
||||
@@ -24,7 +25,7 @@ export class AutoListeners {
|
||||
}
|
||||
recipientKey(user){const value=user?.getFlag(ns,flag);return valid(value)?value:null;}
|
||||
async send(user,invite){
|
||||
if(!this.#isGM()||!this.#public||!user.active||user.isGM||user.isBanned||invite.userId!==user.id)throw new MusicError('denied');
|
||||
if(!this.#isGM()||!this.#public||!user.active||!isMusicListener(user)||invite.userId!==user.id)throw new MusicError('denied');
|
||||
const recipient=this.recipientKey(user);if(!recipient)throw new MusicError('unavailable');
|
||||
const header={type:'audio-invite-v1',campaign:this.#game.world.id,from:this.#game.user.id,to:user.id,sender:this.#public.epoch,recipient:recipient.epoch,id:crypto.randomUUID()};
|
||||
const iv=crypto.getRandomValues(new Uint8Array(12)),key=await this.#key(recipient,'encrypt');
|
||||
@@ -33,16 +34,17 @@ export class AutoListeners {
|
||||
this.#socket.emit(channel,{...header,iv:encode(iv),cipher:encode(new Uint8Array(cipher))});
|
||||
}
|
||||
async receive(packet){
|
||||
if(this.#closed||!this.#keys||this.#game.user.isGM||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
|
||||
if(this.#closed||!this.#keys||!isMusicListener(this.#game.user)||packet?.type!=='audio-invite-v1'||packet.to!==this.#game.user.id||packet.campaign!==this.#game.world.id||packet.recipient!==this.#public.epoch)return;
|
||||
if(Object.keys(packet).sort().join(',')!=='campaign,cipher,from,id,iv,recipient,sender,to,type'||typeof packet.id!=='string'||packet.id.length!==36||typeof packet.cipher!=='string'||packet.cipher.length>16384||typeof packet.iv!=='string'||packet.iv.length!==16||this.#pending>=2||this.#received.has(packet.id)||this.#received.size>=256)throw new MusicError('denied');
|
||||
const gms=[...this.#game.users].filter(u=>u.active&&u.isGM),gm=gms[0];
|
||||
if(gms.length!==1||gm.id!==packet.from||gm.isBanned)throw new MusicError('denied');
|
||||
const gm=activeMusicGM(this.#game.users);
|
||||
if(gm?.id!==packet.from)throw new MusicError('denied');
|
||||
const remote=this.recipientKey(gm);if(remote?.epoch!==packet.sender)throw new MusicError('denied');
|
||||
const localEpoch=this.#public.epoch;this.#pending++;
|
||||
try{
|
||||
const {iv,cipher,...header}=packet;
|
||||
const plain=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(iv),additionalData:new TextEncoder().encode(JSON.stringify(header))},await this.#key(remote,'decrypt'),decode(cipher));
|
||||
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||!gm.active||!gm.isGM||gm.isBanned||[...this.#game.users].filter(u=>u.active&&u.isGM).length!==1)throw new MusicError('stale');
|
||||
if(this.#closed||this.#public.epoch!==localEpoch||this.#received.has(packet.id)||this.recipientKey(gm)?.epoch!==remote.epoch||
|
||||
activeMusicGM(this.#game.users)?.id!==gm.id||!isMusicListener(this.#game.user))throw new MusicError('stale');
|
||||
const invite=JSON.parse(new TextDecoder().decode(plain));
|
||||
if(invite.transport!=='webrtc-v1'||invite.userId!==this.#game.user.id||invite.expires<=Date.now()||invite.expires>Date.now()+1800000)throw new MusicError('denied');
|
||||
this.#received.add(packet.id);await this.#onInvite(invite);
|
||||
|
||||
+16
-2
@@ -19,6 +19,7 @@ function browserAudioContext(){
|
||||
catch{throw new MusicError('audio-context-unavailable');}
|
||||
}
|
||||
export class GMAudioHost{
|
||||
#monitor; #monitorLevel=1;
|
||||
#authority;#sdk;#core;#context;#destination;#timeline;#transitionGain;#transitioning=false;#fadeNext=false;#client;#provider;#catalog=[];#session;#live=false;#socket;#generation=-1; #allowed=new Set(); #apiTransport; #gain; #releaseLock; #catalogPlayback=false; #status='disconnected'; #starting=false; #epoch=0; #phase='idle'; #frames=0; #samples=0; #energy=0; #lastAudio=0; #attachedQueue=false; #lastError; #meter;
|
||||
constructor({authority,onDisconnect=()=>{},pageUrl=globalThis.location?.href,loadSDK=()=>import('../../vendor/sendspin-5.0.0.mjs'),createContext=browserAudioContext,createSocket=url=>new WebSocket(url)}){this.#authority=authority;this.onDisconnect=onDisconnect;this.pageUrl=pageUrl;this.loadSDK=loadSDK;this.createContext=createContext;this.createSocket=createSocket;}
|
||||
get status(){let outputRMS=0;if(this.#meter){const data=new Float32Array(this.#meter.fftSize);this.#meter.getFloatTimeDomainData(data);outputRMS=Math.sqrt(data.reduce((sum,v)=>sum+v*v,0)/data.length);}return {state:this.#live?'connected':this.#starting?'connecting':this.#status,catalog:this.#catalog.length,audioContext:this.#context?.state??'closed',catalogPlayback:this.#catalogPlayback,stage:this.#phase,decodedFrames:this.#frames,lastAudioAt:this.#lastAudio,outputRMS,rms:this.#samples?Math.sqrt(this.#energy/this.#samples):0,attachedExistingQueue:this.#attachedQueue,volume:this.#core?.volume??100,muted:this.#core?.muted??false,pauseMode:this.#client?.supportsNativePause()===false?'emulated':'native',...this.#timeline?.diagnostics,audioTime:this.#context?.currentTime,lastError:this.#lastError};}
|
||||
@@ -101,7 +102,15 @@ export class GMAudioHost{
|
||||
await this.#apiTransport.connect();check();
|
||||
this.#phase='Sendspin authentication';this.#socket=await this.#authenticatedSocket(base,profile.token,identity.clientId);check();
|
||||
this.#core=new this.#sdk.SendspinCore({webSocket:this.#socket,storage,clientName:profile.targetName,productName:'Web Browser',codecs:['pcm'],bufferCapacity:768000,requiredLeadTimeMs:350,minBufferMs:350,useHardwareVolume:false,unpairedAccess:false,reconnect:{enabled:false}});
|
||||
this.#transitionGain=this.#context.createGain();this.#gain=this.#context.createGain();this.#transitionGain.connect(this.#gain);this.#timeline=new PcmTimeline(this.#context,this.#transitionGain);this.#meter=this.#context.createAnalyser?.();if(this.#meter){this.#gain.connect(this.#meter);this.#meter.connect(this.#destination);this.#meter.connect(this.#context.destination);}else{this.#gain.connect(this.#destination);this.#gain.connect(this.#context.destination);}
|
||||
this.#transitionGain=this.#context.createGain();this.#gain=this.#context.createGain();this.#transitionGain.connect(this.#gain);this.#timeline=new PcmTimeline(this.#context,this.#transitionGain);
|
||||
this.#meter=this.#context.createAnalyser?.();
|
||||
if(this.#meter)this.#gain.connect(this.#meter);
|
||||
const output=this.#meter??this.#gain;
|
||||
output.connect(this.#destination);
|
||||
this.#monitor=this.#context.createGain();
|
||||
this.#monitor.gain.value=this.#monitorLevel;
|
||||
output.connect(this.#monitor);
|
||||
this.#monitor.connect(this.#context.destination);
|
||||
this.#core.onVolumeUpdate=()=>this.#gain.gain.setTargetAtTime(this.#core.muted?0:Math.pow(Math.min(100,Math.max(0,this.#core.volume))/100,1.5),this.#context.currentTime,0.015);
|
||||
this.#core.onAudioData=chunk=>this.#schedule(chunk);
|
||||
this.#core.onConnectionClose=()=>this.#connectionLost(epoch,'Sendspin connection lost');
|
||||
@@ -195,5 +204,10 @@ export class GMAudioHost{
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
playbackStatus(){return this.#observe(()=>this.#ready().playbackStatus());}
|
||||
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;this.#meter=null;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
setMonitorLevel(level){
|
||||
if(!Number.isFinite(level)||level<0||level>1)throw new MusicError('denied');
|
||||
this.#monitorLevel=level;
|
||||
this.#monitor?.gain.setTargetAtTime(level,this.#context.currentTime,0.015);
|
||||
}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;this.#meter=null;this.#monitor=null;this.#timeline=null;this.#transitionGain=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
}
|
||||
+96
-18
@@ -2,34 +2,45 @@
|
||||
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);
|
||||
|
||||
export class MusicController {
|
||||
#pending;
|
||||
#stateSignature;
|
||||
#campaignHold;
|
||||
constructor({ campaign, session, providers, authority, maxFrames = 16 }) {
|
||||
Object.assign(this, { campaign, session, providers, authority, maxFrames });
|
||||
this.dirty = new Set();
|
||||
this.generation = 0; this.frames = []; this.current = null; this.tail = Promise.resolve();
|
||||
}
|
||||
update(state) {
|
||||
if (this.campaignPaused) return Promise.resolve({ unchanged: true });
|
||||
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();
|
||||
@@ -43,6 +54,7 @@ export class MusicController {
|
||||
return task;
|
||||
}
|
||||
control(action, value) {
|
||||
if (this.campaignPaused) return Promise.reject(new MusicError('campaign-paused'));
|
||||
if (!['pause', 'resume', 'stop', 'seek', 'next', 'repeat'].includes(action) || !this.providers.ma?.control) {
|
||||
return Promise.reject(new MusicError('unsupported'));
|
||||
}
|
||||
@@ -58,7 +70,67 @@ export class MusicController {
|
||||
}finally{await provider.fade?.(true);}
|
||||
});
|
||||
}
|
||||
get campaignPaused() { return Boolean(this.#campaignHold); }
|
||||
pauseCampaign({ attachedMA = false } = {}) {
|
||||
if (this.#campaignHold) return this.#campaignHold.ready;
|
||||
const hold = this.#campaignHold = { sources: new Map() };
|
||||
hold.ready = this.#enqueue(async () => {
|
||||
if (this.#campaignHold !== hold) throw new MusicError('stale');
|
||||
const ctx = this.#nextContext();
|
||||
ctx.check();
|
||||
const active = this.providers[this.current?.playlist?.provider];
|
||||
const providers = new Set([active, attachedMA ? this.providers.ma : undefined].filter(Boolean));
|
||||
const captures = [];
|
||||
for (const provider of providers) {
|
||||
if (provider.playbackStatus && (await provider.playbackStatus()).state !== 'playing') continue;
|
||||
const snapshot = await provider.snapshot(ctx);
|
||||
captures.push({ provider, snapshot, useTransport: Boolean(provider.playbackStatus && provider.control) });
|
||||
}
|
||||
for (const capture of captures) {
|
||||
const { provider, useTransport } = capture;
|
||||
ctx.check();
|
||||
try {
|
||||
await provider.fade?.(false, ctx);
|
||||
if (useTransport) await provider.control('pause', undefined, ctx);
|
||||
else await provider.stopOwned(ctx);
|
||||
hold.sources.set(provider, capture);
|
||||
ctx.check();
|
||||
} finally { await provider.fade?.(true); }
|
||||
}
|
||||
}).catch(error => {
|
||||
if (!hold.sources.size && this.#campaignHold === hold) this.#campaignHold = undefined;
|
||||
throw error;
|
||||
});
|
||||
return hold.ready;
|
||||
}
|
||||
resumeCampaign(getState) {
|
||||
const hold = this.#campaignHold;
|
||||
if (!hold) return Promise.resolve();
|
||||
return this.#enqueue(async () => {
|
||||
if (this.#campaignHold !== hold) return;
|
||||
const ctx = this.#nextContext();
|
||||
ctx.check();
|
||||
const state = getState();
|
||||
const next = state && candidates(state)[0];
|
||||
const sameCue = next && (next.key === this.current?.key || samePlaylist(next.playlist, this.current?.playlist));
|
||||
if (!next || sameCue) {
|
||||
for (const [provider, { useTransport, snapshot }] of hold.sources) {
|
||||
ctx.check();
|
||||
if (useTransport) await provider.control('resume', undefined, ctx);
|
||||
else await provider.restore(snapshot, ctx);
|
||||
hold.sources.delete(provider);
|
||||
}
|
||||
if (sameCue) this.current = next;
|
||||
} else {
|
||||
await this.transition(state, ctx, hold);
|
||||
}
|
||||
ctx.check();
|
||||
this.#stateSignature = undefined;
|
||||
this.#campaignHold = undefined;
|
||||
});
|
||||
}
|
||||
cancel() {
|
||||
this.#campaignHold = undefined;
|
||||
this.generation++;
|
||||
this.abort?.abort();
|
||||
}
|
||||
@@ -74,10 +146,11 @@ export class MusicController {
|
||||
const task = this.tail.catch(() => {}).then(operation);
|
||||
this.tail = task; return task;
|
||||
}
|
||||
async transition(state, ctx) {
|
||||
async transition(state, ctx, hold) {
|
||||
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)){
|
||||
@@ -89,7 +162,8 @@ export class MusicController {
|
||||
const prepared = provider ? await provider.resolve(next.playlist, ctx) : null;
|
||||
ctx.check();
|
||||
const old = this.current, outgoing = old?.playlist && this.providers[old.playlist.provider];
|
||||
const snapshot = outgoing ? await outgoing.snapshot(ctx) : null;
|
||||
const heldSource = hold?.sources.get(outgoing);
|
||||
const snapshot = heldSource ? heldSource.snapshot : outgoing ? await outgoing.snapshot(ctx) : null;
|
||||
ctx.check();
|
||||
const frame = this.frames.findLast(f => f.intent.key === next.key);
|
||||
if (old && snapshot) {
|
||||
@@ -99,10 +173,10 @@ export class MusicController {
|
||||
this.frames.push(...shared.map(intent => ({intent, snapshot})));
|
||||
this.frames = this.frames.slice(-this.maxFrames);
|
||||
}
|
||||
const cleanup = new Set([...this.dirty, outgoing].filter(Boolean));
|
||||
const cleanup = new Set([...this.dirty, heldSource ? null : outgoing].filter(Boolean));
|
||||
for (const p of [outgoing, provider]) if (p) this.dirty.add(p);
|
||||
try {
|
||||
await outgoing?.fade?.(false,ctx);
|
||||
if (!heldSource) await outgoing?.fade?.(false,ctx);
|
||||
for (const p of cleanup) { ctx.check(); await p.stopOwned(ctx); }
|
||||
ctx.check();
|
||||
if (provider) {
|
||||
@@ -116,14 +190,18 @@ export class MusicController {
|
||||
if (!['stale','uncertain','receiver-access-lost'].includes(error.code)) {
|
||||
ctx.check();
|
||||
for (const p of this.dirty) { ctx.check(); await p.stopOwned(ctx); }
|
||||
if (snapshot) { ctx.check(); await outgoing.restore(snapshot, ctx); this.current = old; }
|
||||
if (snapshot) {
|
||||
ctx.check();
|
||||
if (!heldSource) await outgoing.restore(snapshot, ctx);
|
||||
this.current = old;
|
||||
}
|
||||
this.dirty.clear();
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
await outgoing?.fade?.(true);
|
||||
if (!heldSource) 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) };
|
||||
|
||||
@@ -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}) {
|
||||
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),
|
||||
export function buildMusicState({scene,retainedScenes=[],combats=[],defaults={},overrides=[],choose=ref=>ref}) {
|
||||
const sceneMusic = scene => {
|
||||
const config = scene?.music ?? {};
|
||||
const fallback = config.fallback ?? defaults.fallback ?? null;
|
||||
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)}))}))};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
// Foundry v14 distinguishes full Gamemasters from Assistant Gamemasters.
|
||||
export function isMusicGM(user) {
|
||||
return user?.role === 4 && !user.isBanned;
|
||||
}
|
||||
|
||||
export function isMusicListener(user) {
|
||||
return [1,2,3].includes(user?.role) && !user.isBanned;
|
||||
}
|
||||
|
||||
export function activeMusicGM(users) {
|
||||
let host;
|
||||
for (const user of users) {
|
||||
if (!user.active || !isMusicGM(user)) continue;
|
||||
if (host) return undefined;
|
||||
host = user;
|
||||
}
|
||||
return host;
|
||||
}
|
||||
@@ -1,12 +1,25 @@
|
||||
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';
|
||||
import {isMusicListener} from './authority.mjs';
|
||||
const namespace = 'adaptive-music';
|
||||
const key = ref => JSON.stringify([ref?.provider, ref?.id]);
|
||||
function validChoice(choice) {
|
||||
return choice && ['native','ma'].includes(choice.provider) && typeof choice.id === 'string' &&
|
||||
choice.id.length > 0 && choice.id.length <= 256 && typeof choice.name === 'string';
|
||||
}
|
||||
export function mountListeningShortcut({html,game,openListener}) {
|
||||
const container=html?.querySelector?html:html?.[0];
|
||||
if(!isMusicListener(game.user)||!container||container.querySelector('.adaptive-listening-shortcut'))return;
|
||||
const button=container.ownerDocument.createElement('button');
|
||||
button.type='button';
|
||||
button.className='adaptive-listening-shortcut';
|
||||
button.textContent='Campaign audio';
|
||||
button.addEventListener('click',openListener);
|
||||
const list=container.querySelector('.directory-list');
|
||||
if(list)list.before(button);
|
||||
else container.prepend(button);
|
||||
}
|
||||
// Pass only owned native playlists and controller-authorized MA catalog choices.
|
||||
// No gateway credential, endpoint or upstream URI belongs in this interface.
|
||||
export async function savePlaylistConfiguration({ document, game, choices, selected }) {
|
||||
@@ -48,9 +61,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 +117,81 @@ 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.campaignPaused ? 'Music: Campaign paused'
|
||||
: 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();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -27,6 +27,7 @@ const messages={
|
||||
'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.',
|
||||
'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.',
|
||||
'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.',
|
||||
'campaign-paused':'Select Play all music to resume campaign playback.',
|
||||
'private-storage-unavailable':'This browser denied private storage. Allow site storage for this Foundry address and retry.',
|
||||
'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.',
|
||||
'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.',
|
||||
@@ -38,6 +39,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 +112,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 +137,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 +157,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 +168,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';
|
||||
|
||||
@@ -1,4 +1,86 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
|
||||
export function listeningPreferences(value) {
|
||||
return {
|
||||
volume:Number.isFinite(value?.volume)?Math.min(100,Math.max(0,Math.round(value.volume))):100,
|
||||
muted:value?.muted===true,
|
||||
};
|
||||
}
|
||||
|
||||
// The gain is downstream of the received stream and belongs to this player.
|
||||
export class CampaignAudio {
|
||||
#element; #context; #source; #gain; #stream; #blocked=false; #preferences;
|
||||
constructor({preferences,createElement,createContext=()=>new AudioContext()}) {
|
||||
this.#preferences=listeningPreferences(preferences);
|
||||
this.createElement=createElement;
|
||||
this.createContext=createContext;
|
||||
}
|
||||
get status() {
|
||||
const routed=Boolean(this.#source);
|
||||
const running=this.#context?.state==='running';
|
||||
return {...this.#preferences,needsActivation:this.#blocked||routed&&!running,
|
||||
playing:!!this.#stream&&(routed?running:!this.#element?.paused)};
|
||||
}
|
||||
setPreferences(value) {
|
||||
this.#preferences=listeningPreferences({...this.#preferences,...value});
|
||||
this.#mix();
|
||||
return {...this.#preferences};
|
||||
}
|
||||
async attach(stream) {
|
||||
this.clear();
|
||||
this.#stream=stream;
|
||||
this.#element??=this.createElement();
|
||||
this.#element.srcObject=stream;
|
||||
this.#route();
|
||||
if(!this.#source)await this.#play();
|
||||
}
|
||||
async enable() {
|
||||
try{this.#context??=this.createContext();}catch{}
|
||||
// Call both entry points inside the gesture, before awaiting activation.
|
||||
const resumed=this.#context?.resume().catch(()=>{});
|
||||
const played=this.#stream&&!this.#source?this.#play():undefined;
|
||||
await resumed;
|
||||
this.#route();
|
||||
if(!this.#source)await played;
|
||||
}
|
||||
#route() {
|
||||
if(this.#stream&&this.#context?.state==='running'&&!this.#source){
|
||||
if(!this.#gain){
|
||||
this.#gain=this.#context.createGain();
|
||||
this.#gain.gain.value=this.#preferences.muted?0:this.#preferences.volume/100;
|
||||
this.#gain.connect(this.#context.destination);
|
||||
}
|
||||
this.#source=this.#context.createMediaStreamSource(this.#stream);
|
||||
this.#source.connect(this.#gain);
|
||||
this.#blocked=false;
|
||||
}
|
||||
this.#mix();
|
||||
}
|
||||
#mix() {
|
||||
const {volume,muted}=this.#preferences;
|
||||
if(this.#element){
|
||||
this.#element.volume=volume/100;
|
||||
this.#element.muted=muted||Boolean(this.#source);
|
||||
}
|
||||
this.#gain?.gain.setTargetAtTime(muted?0:volume/100,this.#context.currentTime,0.015);
|
||||
}
|
||||
async #play() {
|
||||
const stream=this.#stream;
|
||||
try{await this.#element.play();if(stream===this.#stream)this.#blocked=false;}
|
||||
catch{if(stream===this.#stream&&!this.#source)this.#blocked=true;}
|
||||
}
|
||||
clear() {
|
||||
this.#source?.disconnect();this.#source=null;
|
||||
this.#stream=null;this.#blocked=false;
|
||||
if(this.#element){this.#element.pause();this.#element.srcObject=null;}
|
||||
}
|
||||
close() {
|
||||
this.clear();
|
||||
void this.#context?.close().catch(()=>{});
|
||||
this.#element?.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// Gateway-terminated PCM test transport, NOT a Sendspin pass-through client.
|
||||
export class ListenerAudio {
|
||||
#context; #abort; #nodes=new Set(); #fetch;
|
||||
|
||||
+145
-34
@@ -1,14 +1,16 @@
|
||||
import {connectionMessage} from './connection-wizard.mjs';
|
||||
import {ReceiverVault} from './receiver-vault.mjs';
|
||||
import {connectionDraft} from './connection-draft.mjs';
|
||||
import {startNativeRuntime,primaryGM} from './runtime.mjs';
|
||||
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
|
||||
import {startNativeRuntime} from './runtime.mjs';
|
||||
import {activeMusicGM,isMusicGM,isMusicListener} from './authority.mjs';
|
||||
import {startConfigurationInterfaces,mountPlaylistConfiguration,mountListeningShortcut} from './configuration.mjs';
|
||||
import {GatewayClient} from '../providers/ma/remote.mjs';
|
||||
import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {AutoListeners} from '../audio/auto-listeners.mjs';
|
||||
import {PeerAudio} from '../audio/peer-audio.mjs';
|
||||
import {ListenerAudio} from './listener-audio.mjs';
|
||||
import {CampaignAudio,ListenerAudio,listeningPreferences} from './listener-audio.mjs';
|
||||
import {createSetupClass,createListenerClass,createPlaybackClass} from './setup.mjs';
|
||||
import {mountMusicBar} from './music-bar.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
|
||||
const id='adaptive-music';
|
||||
@@ -17,10 +19,13 @@ const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:
|
||||
const credentialScope=()=>receiverScope({});
|
||||
const accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
|
||||
const savedConnection=()=>game.settings.get(id,'savedConnection');
|
||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
|
||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,playerOutput;
|
||||
let authorityHooks=[],socketHooks=[],bootstrap,privateProfile,privateDraft,inviteTimer,listenerHost,listenerStopped=false,inviteTail=Promise.resolve();
|
||||
const sentInvites=new Map();
|
||||
let connectionGeneration=0,connectionTesting=false,preferenceWrites=Promise.resolve();
|
||||
let automationRunning=false,previousController,savedDevice,deviceReconnect=false,devicePaused=false,deviceError,connectionOpening=false;
|
||||
let playbackApp,setupType;
|
||||
const gmAuthority=()=>game.ready&&game.user.isGM&&!game.user.isBanned&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
|
||||
let playbackApp,setupType,listenerType,gmListening,disposeMusicBar;
|
||||
const gmAuthority=()=>game.ready&&isMusicGM(game.user)&&activeMusicGM(game.users)?.id===game.user.id&&game.socket?.connected===true;
|
||||
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean);
|
||||
const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
|
||||
const queueNeedsReview=error=>['uncertain','receiver-access-lost'].includes(error?.code);
|
||||
@@ -31,7 +36,7 @@ function openSetup(){
|
||||
return new setupType().render({force:true});
|
||||
}
|
||||
function openPlayback(){
|
||||
if(!game.user.isGM)return;
|
||||
if(!isMusicGM(game.user))return;
|
||||
if(!playbackApp){
|
||||
const Playback=createPlaybackClass({game,connection,getChoices:choices,start,stop,setOverrides,onError,openSetup});
|
||||
playbackApp=new Playback();
|
||||
@@ -40,29 +45,91 @@ 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,
|
||||
campaignPaused:runtime?.controller.campaignPaused??false};
|
||||
}
|
||||
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(!gmAuthority())throw new MusicError('denied');if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
|
||||
function openListener(){
|
||||
if(!isMusicListener(game.user))return;
|
||||
const existing=foundry.applications.instances.get('adaptive-music-listener');
|
||||
if(existing)return existing.bringToFront();
|
||||
return new listenerType().render({force:true});
|
||||
}
|
||||
function resumeListener(){
|
||||
if(!isMusicListener(game.user)||!playerOutput)throw new MusicError('denied');
|
||||
listenerStopped=false;
|
||||
const activated=playerOutput.enable();
|
||||
if(game.socket?.connected&&!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);
|
||||
return activated;
|
||||
}
|
||||
function listenerStatus(){
|
||||
const output=playerOutput?.status??{volume:100,muted:false};
|
||||
let status='Waiting for GM audio.';
|
||||
if(listenerStopped)status='Audio stopped. Select Enable Audio to rejoin.';
|
||||
else if(!game.socket?.connected)status='Foundry disconnected. Waiting to reconnect.';
|
||||
else if(output.needsActivation)status='GM audio is ready. Select Enable Audio.';
|
||||
else if(output.playing)status=output.muted?'Listening · Muted':'Listening';
|
||||
else if(peers?.diagnostics().peers.length)status='Connecting to GM audio…';
|
||||
return {...output,status};
|
||||
}
|
||||
function changeListening(value,{save=true}={}){
|
||||
let preferences;
|
||||
if(isMusicGM(game.user)&&gmListening){
|
||||
preferences=gmListening=listeningPreferences({...gmListening,...value});
|
||||
gmHost.setMonitorLevel(preferences.muted?0:preferences.volume/100);
|
||||
}else if(isMusicListener(game.user)&&playerOutput){
|
||||
preferences=playerOutput.setPreferences(value);
|
||||
}else throw new MusicError('denied');
|
||||
if(!save)return;
|
||||
preferenceWrites=preferenceWrites.catch(()=>{}).then(()=>game.settings.set(id,'listenerPreferences',preferences));
|
||||
return preferenceWrites;
|
||||
}
|
||||
function setCampaignPaused(paused){
|
||||
if(!gmAuthority())throw new MusicError('denied');
|
||||
if(!paused)return runtime?.resumeCampaign();
|
||||
if(!automationRunning&&!gmHost.connected)throw new MusicError('unavailable');
|
||||
return ensureRuntime().pauseCampaign({attachedMA:gmHost.connected});
|
||||
}
|
||||
function startMusicBar(){
|
||||
const controller=isMusicGM(game.user);
|
||||
if(!globalThis.document?.body||(!controller&&!isMusicListener(game.user)))return;
|
||||
disposeMusicBar=mountMusicBar({document,getPreferences:()=>game.settings.get(id,'musicBar'),
|
||||
savePreferences:preferences=>game.settings.set(id,'musicBar',preferences),
|
||||
getListening:controller?()=>gmListening:listenerStatus,changeListening,
|
||||
enableAudio:controller?connection.resume:resumeListener,onError,
|
||||
gm:controller?{
|
||||
status:()=>{
|
||||
const host=gmHost.status;
|
||||
return {...playbackMode(),automationRunning,connected:gmHost.connected,canControl:gmAuthority(),volume:host.volume,
|
||||
needsActivation:host.audioContext!=='running',canSkip:gmHost.connected&&!queueNeedsReview(host.lastError)&&
|
||||
runtime?.controller.current?.playlist?.provider!=='native'};
|
||||
},
|
||||
setPaused:setCampaignPaused,skip:()=>connection.control('next'),setVolume:connection.setVolume,
|
||||
returnToScene:()=>setOverrides([]),openPlayback,openSetup
|
||||
}:undefined});
|
||||
}
|
||||
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;}
|
||||
function attachListenerSource(stream){listenerSource?.disconnect();if(listenerContext){listenerSource=listenerContext.createMediaStreamSource(stream);listenerSource.connect(listenerContext.destination);remoteAudio.muted=true;}}
|
||||
function resumeListener(){if(game.user.isGM)return gmHost.resumeAudio();listenerStopped=false;const element=ensureRemoteAudio();let resumed=Promise.resolve();if(globalThis.AudioContext){listenerContext??=new AudioContext();resumed=listenerContext.resume();if(element.srcObject)attachListenerSource(element.srcObject);}const play=element.play();play.catch(()=>{});if(!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);return resumed.then(()=>{listenerState=element.srcObject?'Campaign audio enabled.':'Audio enabled. Waiting for GM audio.';});}
|
||||
function sendInvites(){
|
||||
inviteTail=inviteTail.catch(()=>{}).then(async()=>{
|
||||
if(!bootstrap||!gmHost?.connected||!gmAuthority())return;
|
||||
for(const user of game.users){
|
||||
if(!user.active||user.isGM||user.isBanned)continue;const key=bootstrap.recipientKey(user);if(!key)continue;
|
||||
if(!user.active||!isMusicListener(user))continue;const key=bootstrap.recipientKey(user);if(!key)continue;
|
||||
const previous=sentInvites.get(user.id);if(previous?.epoch===key.epoch&&peers.hasListener(user.id))continue;
|
||||
try{const invite=peers.invite(user.id,{ttlMs:1800000,...(privateProfile?.listenerNetwork??{})});await bootstrap.send(user,invite);sentInvites.set(user.id,{epoch:key.epoch});}catch{onError();}
|
||||
}
|
||||
@@ -70,7 +137,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.
|
||||
@@ -151,6 +218,7 @@ const connection={
|
||||
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
|
||||
async refresh(){const catalog=await gmHost.refreshCatalog();await interfaces?.refreshDirectory(ui.playlists);return catalog;},
|
||||
resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||
setCampaignPaused,
|
||||
async playback(){
|
||||
if(!gmAuthority())throw new MusicError('denied');
|
||||
const current=runtime?.controller.current?.playlist;
|
||||
@@ -169,6 +237,7 @@ const connection={
|
||||
},
|
||||
control(action,value){
|
||||
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
|
||||
if(runtime?.controller.campaignPaused)throw new MusicError('campaign-paused');
|
||||
if(action==='stop'&&automationRunning&&runtime?.controller.current?.playlist)return setOverrides([{id:'gm-stop',playlist:null}]);
|
||||
return ensureRuntime().controller.control(action,value);
|
||||
},
|
||||
@@ -208,39 +277,80 @@ async function reconnectTrustedDevice(){
|
||||
}finally{deviceReconnect=false;}
|
||||
}
|
||||
function listenWebRTC(invite){
|
||||
if(game.user.isGM||!peers)throw Error('Listener only');
|
||||
ensureRemoteAudio().play().catch(()=>{});listenerState='Connecting to GM audio…';return peers.listen(invite);
|
||||
if(!isMusicListener(game.user)||!peers||!activeMusicGM(game.users))throw new MusicError('denied');
|
||||
listenerHost=activeMusicGM(game.users).id;
|
||||
return peers.listen(invite);
|
||||
}
|
||||
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
|
||||
function clearListener(){listenerHost=null;peers?.reset();playerOutput?.clear();}
|
||||
function stopWebRTC(){listenerStopped=true;clearListener();}
|
||||
Hooks.once('init',()=>{
|
||||
Hooks.on('getSceneControlButtons',controls=>{
|
||||
if(!game.user?.isGM||!controls.tokens?.tools)return;
|
||||
if(!isMusicGM(game.user)||!controls.tokens?.tools)return;
|
||||
const tools=controls.tokens.tools;
|
||||
tools.adaptiveMusic={name:'adaptiveMusic',title:'Adaptive Music controls',icon:'fa-solid fa-music',order:Object.keys(tools).length,button:true,onChange:openPlayback};
|
||||
});
|
||||
game.settings.register(id,'savedConnection',{scope:'user',config:false,type:Object,default:{}});
|
||||
game.settings.register(id,'listenerPreferences',{scope:'user',config:false,type:Object,default:{volume:100,muted:false}});
|
||||
game.settings.register(id,'musicBar',{scope:'client',config:false,type:Object,default:{}});
|
||||
game.settings.register(id,'advancedDevelopment',{name:'Show advanced development controls',hint:'Optional companion and manual test capabilities. Not needed for normal music setup.',scope:'client',config:true,type:Boolean,default:false});
|
||||
game.settings.register(id,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false});
|
||||
game.settings.register(id,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true});
|
||||
game.settings.register(id,'musicDefaults',{scope:'world',config:false,type:Object,default:{}});
|
||||
if(game.settings.registerMenu){
|
||||
// The factory reads live module state when the settings menu is rendered.
|
||||
const Setup=createSetupClass({game,gateway:{get status(){return gateway?.status;},connect:async code=>{if(gmHost?.connected)throw Error('Disconnect GM host first');const result=await gateway.connect(code);await runtime?.refresh();return result;},refresh:()=>gateway.refresh(),disconnect:()=>gateway.disconnect(),audioRequest:code=>gateway.audioRequest(code)},
|
||||
audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&primaryGM(game.users)===game.user.id,connection});
|
||||
const Listener=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus:()=>listenerState});
|
||||
setupType=Setup;
|
||||
game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Enable Audio',hint:'Connects automatically to GM audio. Enable sound if your browser asks.',icon:'fas fa-headphones',type:Listener,restricted:false});
|
||||
game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:Setup,restricted:true});
|
||||
setupType=createSetupClass({game,gateway:{get status(){return gateway?.status;},connect:async code=>{if(!gmAuthority()||gmHost?.connected)throw new MusicError('denied');const result=await gateway.connect(code);await runtime?.refresh();return result;},refresh:()=>gateway.refresh(),disconnect:()=>gateway.disconnect(),audioRequest:code=>gateway.audioRequest(code)},
|
||||
audio:{start:request=>audio.start(request),stop:()=>audio.stop()},getChoices:choices,start,stop,setOverrides,onError,canConnect:()=>!gmHost?.connected&&gmAuthority(),canConfigure:()=>isMusicGM(game.user),connection});
|
||||
listenerType=createListenerClass({game,gateway:{audioRequest:code=>gateway.audioRequest(code)},audio:{start:request=>audio.start(request),stop:()=>audio.stop()},listenWebRTC,stopWebRTC,onError,resumeListener,listenerStatus,changeListening});
|
||||
}
|
||||
});
|
||||
Hooks.once('ready',()=>{
|
||||
gmHost=new GMAudioHost({authority:gmAuthority,onDisconnect:()=>{stop();peers?.reset();sentInvites.clear();onError();}});
|
||||
if(game.socket){peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&!user.isGM&&!user.isBanned;},onError,onStream:stream=>{ensureRemoteAudio().srcObject=stream;attachListenerSource(stream);(listenerContext?.state==='running'?Promise.resolve():remoteAudio.play()).then(()=>{listenerState='Campaign audio connected.';}).catch(()=>{listenerState='GM audio connected. Select Enable Audio to allow sound.';ui.notifications.info('Adaptive Music: open Campaign audio and select Enable Audio to allow sound.');});}});game.socket.on('disconnect',()=>{stop();privateProfile=null;gmHost.close();peers.reset();sentInvites.clear();latestInvite=null;listenerState='Foundry disconnected. Waiting for the GM to reconnect.';remoteAudio?.pause();});}
|
||||
if(game.socket)authorityHooks=['updateUser','deleteUser'].map(event=>[event,Hooks.on(event,()=>{peers.reconcile();if(!game.user.isGM&&[...game.users].filter(u=>u.active&&u.isGM).length!==1){peers.reset();remoteAudio?.pause();latestInvite=null;listenerState='Waiting for one active GM.';}sendInvites();if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();remoteAudio?.pause();}})]);
|
||||
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);}
|
||||
if(isMusicGM(game.user)){
|
||||
gmListening=listeningPreferences(game.settings.get(id,'listenerPreferences'));
|
||||
gmHost.setMonitorLevel(gmListening.muted?0:gmListening.volume/100);
|
||||
}
|
||||
if(isMusicListener(game.user)){
|
||||
playerOutput=new CampaignAudio({preferences:game.settings.get(id,'listenerPreferences'),createElement:()=>{
|
||||
const element=document.createElement('audio');element.autoplay=true;document.body.append(element);return element;
|
||||
}});
|
||||
if(listenerType)game.settings.registerMenu(id,'listen',{name:'Campaign audio',label:'Open listening controls',hint:'Connects to GM audio and controls your own sound.',icon:'fas fa-headphones',type:listenerType,restricted:false});
|
||||
const renderListener=(_app,html)=>mountListeningShortcut({html,game,openListener});
|
||||
authorityHooks.push(['renderPlaylistDirectory',Hooks.on('renderPlaylistDirectory',renderListener)]);
|
||||
renderListener(ui.playlists,ui.playlists?.element);
|
||||
}
|
||||
if(game.socket){
|
||||
peers=new PeerAudio({socket:game.socket,userId:game.user.id,isGM:gmAuthority,
|
||||
isAuthorizedUser:id=>{const user=game.users.get(id);return user?.active&&isMusicListener(user);},
|
||||
onError:()=>playerOutput?.clear(),
|
||||
onStream:stream=>{if(!listenerStopped&&isMusicListener(game.user))void playerOutput?.attach(stream);}
|
||||
});
|
||||
socketHooks=[
|
||||
['disconnect',()=>{stop();privateProfile=null;gmHost.close();clearListener();sentInvites.clear();}],
|
||||
['connect',()=>{if(!listenerStopped)bootstrap?.start().then(sendInvites).catch(onError);}]
|
||||
];
|
||||
for(const [event,handler] of socketHooks)game.socket.on(event,handler);
|
||||
const reconcile=()=>{
|
||||
peers.reconcile();
|
||||
if(listenerHost&&(!isMusicListener(game.user)||activeMusicGM(game.users)?.id!==listenerHost))clearListener();
|
||||
if(gmHost.connected&&!gmAuthority()){stop();gmHost.close();peers.reset();sentInvites.clear();}
|
||||
else sendInvites();
|
||||
};
|
||||
for(const event of ['userConnected','updateUser','deleteUser'])authorityHooks.push([event,Hooks.on(event,reconcile)]);
|
||||
}
|
||||
if(game.socket&&game.user.setFlag&&(isMusicGM(game.user)||isMusicListener(game.user))){
|
||||
bootstrap=new AutoListeners({game,isGM:gmAuthority,onInvite:async invite=>{
|
||||
if(listenerStopped)return;
|
||||
clearListener();
|
||||
await listenWebRTC(invite);
|
||||
}});
|
||||
bootstrap.start().then(sendInvites).catch(onError);
|
||||
inviteTimer=setInterval(()=>{sendInvites();if(isMusicGM(game.user)&&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});
|
||||
if(isMusicGM(game.user)){
|
||||
if(setupType)game.settings.registerMenu(id,'setup',{name:'Adaptive Music setup',label:'Configure music',hint:'Music Assistant connection, scene music and Foundry fallback.',icon:'fas fa-music',type:setupType,restricted:true});
|
||||
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;
|
||||
@@ -248,13 +358,14 @@ Hooks.once('ready',()=>{
|
||||
return reconnectTrustedDevice();
|
||||
}).catch(error=>{deviceError=error;onError(error);if(game.settings.get(id,'enabled'))void start();});
|
||||
renewTimer=setInterval(()=>{
|
||||
if(gateway.connected&&primaryGM(game.users)===game.user.id)gateway.renew().catch(onError);
|
||||
if(gateway.connected&&gmAuthority())gateway.renew().catch(onError);
|
||||
if(!deviceError||['ws-upgrade-failed','ws-disconnected','ws-auth-timeout'].includes(deviceError.code))void reconnectTrustedDevice();
|
||||
},15000);
|
||||
}
|
||||
startMusicBar();
|
||||
game.modules.get(id).api={
|
||||
startDevelopment:start,stopDevelopment:stop,setOverrides,
|
||||
async connectGateway(code){if(!game.user.isGM||primaryGM(game.users)!==game.user.id||gmHost?.connected)throw Error('Controller unavailable');const result=await gateway.connect(code);await runtime?.refresh();return result;},
|
||||
async connectGateway(code){if(!gmAuthority()||gmHost?.connected)throw new MusicError('denied');const result=await gateway.connect(code);await runtime?.refresh();return result;},
|
||||
gatewayDiagnostics:()=>gateway.status,
|
||||
async readGMCatalog(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');return gmHost.readCatalog({...profile,campaign:game.world.id});},
|
||||
async startGMHost(profile){if(runtime||gateway.connected)throw Error('Stop automation and disconnect optional companion first');const result=await gmHost.start({...profile,campaign:game.world.id});peers.setSource(gmHost.stream);return result;},
|
||||
@@ -262,8 +373,8 @@ Hooks.once('ready',()=>{
|
||||
listenWebRTC,
|
||||
peerStats:()=>peers.stats(),
|
||||
async closeGMHost(){await connection.disconnect();},
|
||||
async mountConfiguration(document,container){return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});},
|
||||
async mountConfiguration(document,container){if(!isMusicGM(game.user))throw new MusicError('denied');return mountPlaylistConfiguration({document,container,game,choices:await choices(),onError});},
|
||||
enableAudio(code){return audio.start(gateway.audioRequest(code));},stopAudio:()=>audio.stop(),
|
||||
dispose(){stop();listenerSource?.disconnect();listenerContext?.close();privateProfile=null;bootstrap?.close();clearInterval(inviteTimer);for(const [event,hook]of authorityHooks)Hooks.off(event,hook);authorityHooks=[];interfaces?.dispose();clearInterval(renewTimer);gateway.disconnect();audio.stop();gmHost?.close();peers?.close();remoteAudio?.pause();remoteAudio?.remove();interfaces=null;}
|
||||
dispose(){stop();disposeMusicBar?.();playerOutput?.close();privateProfile=null;bootstrap?.close();clearInterval(inviteTimer);for(const [event,hook]of authorityHooks)Hooks.off(event,hook);authorityHooks=[];for(const [event,handler] of socketHooks)game.socket?.off(event,handler);socketHooks=[];interfaces?.dispose();clearInterval(renewTimer);gateway.disconnect();audio.stop();gmHost?.close();peers?.close();interfaces=null;}
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import {musicModeLabel} from '../core/scene-music.mjs';
|
||||
|
||||
export function mountMusicBar({document, getPreferences, savePreferences, getListening, changeListening,
|
||||
enableAudio, gm, onError}) {
|
||||
const win = document.defaultView;
|
||||
const root = document.createElement('section');
|
||||
root.className = 'adaptive-music-bar';
|
||||
root.setAttribute('aria-label', 'Adaptive Music bar');
|
||||
const make = (parent, tag, text) => {
|
||||
const element = document.createElement(tag);
|
||||
if (text) element.textContent = text;
|
||||
parent.append(element);
|
||||
return element;
|
||||
};
|
||||
const setText = (element, text) => {
|
||||
if (element.textContent !== text) element.textContent = text;
|
||||
};
|
||||
const header = make(root, 'header');
|
||||
const grip = make(header, 'strong', 'Adaptive Music');
|
||||
grip.className = 'adaptive-bar-grip';
|
||||
const button = (parent, text, action) => {
|
||||
const control = make(parent, 'button', text);
|
||||
control.type = 'button';
|
||||
control.addEventListener('click', action);
|
||||
return control;
|
||||
};
|
||||
let preferences = getPreferences() ?? {}, busy = false, disposed = false;
|
||||
const collapse = button(header, 'Hide', () => {
|
||||
saveLayout({collapsed: !preferences.collapsed});
|
||||
render();
|
||||
fit();
|
||||
});
|
||||
collapse.setAttribute('aria-controls', 'adaptive-music-bar-controls');
|
||||
const content = make(root, 'div');
|
||||
content.id = 'adaptive-music-bar-controls';
|
||||
const status = make(content, 'p');
|
||||
status.setAttribute('role', 'status');
|
||||
const primary = make(content, 'div');
|
||||
primary.className = 'adaptive-bar-actions';
|
||||
const enable = button(primary, 'Enable audio', () => void run(enableAudio));
|
||||
const mute = button(primary, 'Mute', () => void run(() => changeListening({muted: !getListening().muted})));
|
||||
const volume = slider(content, 'My volume',
|
||||
value => write(() => changeListening({volume: value}, {save: false})),
|
||||
value => write(() => changeListening({volume: value})));
|
||||
let pause, skip, settings, automatic, campaignVolume;
|
||||
if (gm) {
|
||||
const transport = make(content, 'div');
|
||||
transport.className = 'adaptive-bar-actions';
|
||||
pause = button(transport, 'Pause all music', () => void run(() => gm.setPaused(!gm.status().campaignPaused)));
|
||||
skip = button(transport, 'Skip track', () => void run(gm.skip));
|
||||
settings = button(transport, 'Playback controls', () => void run(() => gm.status().connected || gm.status().automationRunning
|
||||
? gm.openPlayback() : gm.openSetup()));
|
||||
automatic = button(transport, 'Return to scene music', () => void run(gm.returnToScene));
|
||||
campaignVolume = slider(content, 'Campaign volume', undefined, value => void run(() => gm.setVolume(value)));
|
||||
}
|
||||
|
||||
function slider(parent, title, preview, commit) {
|
||||
const row = make(parent, 'label');
|
||||
make(row, 'span', title);
|
||||
const input = make(row, 'input');
|
||||
input.type = 'range'; input.min = '0'; input.max = '100'; input.value = '100';
|
||||
const readout = make(row, 'span', '100%');
|
||||
readout.setAttribute('aria-hidden', 'true');
|
||||
input.addEventListener('input', () => { showValue(input.value); preview?.(Number(input.value)); });
|
||||
input.addEventListener('change', () => commit(Number(input.value)));
|
||||
input.addEventListener('blur', render);
|
||||
function showValue(value) {
|
||||
input.setAttribute('aria-valuetext', `${value}%`);
|
||||
setText(readout, `${value}%`);
|
||||
}
|
||||
return (value, disabled = false) => {
|
||||
input.disabled = disabled;
|
||||
if (document.activeElement !== input || disabled) input.value = String(value);
|
||||
showValue(input.value);
|
||||
};
|
||||
}
|
||||
function write(action) {
|
||||
try { Promise.resolve(action()).then(render, onError); }
|
||||
catch (error) { onError(error); }
|
||||
}
|
||||
async function run(action) {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try { await action(); }
|
||||
catch (error) { onError(error); }
|
||||
finally { busy = false; render(); }
|
||||
}
|
||||
function render() {
|
||||
if (disposed) return;
|
||||
const listening = getListening();
|
||||
content.hidden = preferences.collapsed === true;
|
||||
setText(collapse, content.hidden ? 'Show' : 'Hide');
|
||||
collapse.setAttribute('aria-expanded', String(!content.hidden));
|
||||
setText(mute, listening.muted ? 'Unmute' : 'Mute');
|
||||
mute.setAttribute('aria-pressed', String(listening.muted));
|
||||
volume(listening.volume);
|
||||
let nextStatus = listening.status;
|
||||
if (gm) {
|
||||
const state = gm.status(), mode = musicModeLabel(state.musicMode);
|
||||
nextStatus = state.campaignPaused ? 'Campaign music paused'
|
||||
: (mode ?? (state.connected ? 'Music Assistant connected' : 'Connect Music Assistant'));
|
||||
enable.hidden = !state.canControl || !state.connected || !state.needsActivation;
|
||||
setText(pause, state.campaignPaused ? 'Play all music' : 'Pause all music');
|
||||
pause.disabled = !state.canControl || busy || (!state.connected && !state.automationRunning && !state.campaignPaused);
|
||||
skip.disabled = !state.canControl || busy || !state.canSkip || state.campaignPaused;
|
||||
setText(settings, state.connected || state.automationRunning ? 'Playback controls' : 'Music setup');
|
||||
automatic.hidden = !state.overrideActive && !state.awaitingSceneChange;
|
||||
automatic.disabled = !state.canControl || busy;
|
||||
campaignVolume(state.volume, !state.canControl || !state.connected);
|
||||
}
|
||||
setText(status, nextStatus);
|
||||
}
|
||||
function saveLayout(patch) {
|
||||
preferences = {...preferences, ...patch};
|
||||
write(() => savePreferences(preferences));
|
||||
}
|
||||
function place(x, y) {
|
||||
const next = {
|
||||
x: Math.min(Math.max(8, x), Math.max(8, win.innerWidth - root.offsetWidth - 8)),
|
||||
y: Math.min(Math.max(8, y), Math.max(8, win.innerHeight - root.offsetHeight - 8)),
|
||||
};
|
||||
root.style.left = `${next.x}px`;
|
||||
root.style.top = `${next.y}px`;
|
||||
root.style.right = 'auto';
|
||||
return next;
|
||||
}
|
||||
function fit() {
|
||||
if (Number.isFinite(preferences.x) && Number.isFinite(preferences.y)) place(preferences.x, preferences.y);
|
||||
}
|
||||
let drag;
|
||||
grip.addEventListener('pointerdown', event => {
|
||||
if (event.button !== 0) return;
|
||||
const rect = root.getBoundingClientRect();
|
||||
drag = {x: event.clientX - rect.left, y: event.clientY - rect.top};
|
||||
grip.setPointerCapture(event.pointerId);
|
||||
});
|
||||
grip.addEventListener('pointermove', event => {
|
||||
if (drag) drag.position = place(event.clientX - drag.x, event.clientY - drag.y);
|
||||
});
|
||||
function endDrag() {
|
||||
if (drag?.position) saveLayout(drag.position);
|
||||
drag = undefined;
|
||||
}
|
||||
grip.addEventListener('pointerup', endDrag);
|
||||
grip.addEventListener('pointercancel', endDrag);
|
||||
win.addEventListener('resize', fit);
|
||||
document.body.append(root);
|
||||
render();
|
||||
fit();
|
||||
const timer = win.setInterval(render, 750);
|
||||
return () => {
|
||||
disposed = true;
|
||||
win.clearInterval(timer);
|
||||
win.removeEventListener('resize', fit);
|
||||
root.remove();
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
@@ -35,6 +36,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
};
|
||||
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
|
||||
toggle.className='adaptive-primary';
|
||||
const playCampaign=button(controls,'Play all music',()=>connection.setCampaignPaused(false));
|
||||
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop'));
|
||||
const skip=button(controls,'Skip track',()=>connection.control('next'));
|
||||
const unlock=button(controls,'Enable GM audio',()=>connection.resume());
|
||||
@@ -73,8 +75,12 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
function render(){
|
||||
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused';
|
||||
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 canControl=connected&&trackStatus?.source==='Music Assistant'&&!queueError&&!d.campaignPaused;
|
||||
state.textContent=d.campaignPaused?'Campaign music paused':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)}`:'';
|
||||
@@ -84,6 +90,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
|
||||
seek.setAttribute('aria-valuetext',clock(Number(seek.value)));
|
||||
}
|
||||
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
|
||||
playCampaign.hidden=!d.campaignPaused;playCampaign.disabled=busy||queueError;
|
||||
stopTrack.disabled=busy||!canControl||!(playing||paused);
|
||||
skip.disabled=busy||!canControl||!playing;
|
||||
automatic.hidden=!d.overrideActive&&!d.awaitingSceneChange;automatic.disabled=busy;
|
||||
@@ -93,9 +100,9 @@ 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;
|
||||
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy||d.campaignPaused;
|
||||
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
|
||||
if(queueError){
|
||||
failure.textContent=`Queue needs review. ${connectionMessage(d.lastError)}`;failure.hidden=false;
|
||||
|
||||
+40
-17
@@ -1,13 +1,12 @@
|
||||
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)
|
||||
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
|
||||
import { activeMusicGM } from './authority.mjs';
|
||||
// Explicit development bootstrap. No hooks or document mutations occur on import.
|
||||
// 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 = () => {} }) {
|
||||
isEnabled = () => true, authority = () => game.ready && activeMusicGM(game.users)?.id === game.user.id,
|
||||
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,29 +22,46 @@ 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();
|
||||
if (!isEnabled() || !authority() || controller.campaignPaused) return Promise.resolve();
|
||||
const state=getState();
|
||||
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 +69,15 @@ 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;},
|
||||
pauseCampaign: options => controller.pauseCampaign(options).finally(onModeChange),
|
||||
resumeCampaign: () => controller.resumeCampaign(() => {
|
||||
if (!isEnabled()) return undefined;
|
||||
const state = getState();
|
||||
return deferredState === candidates(state)[0].key ? undefined : state;
|
||||
}).then(refresh).finally(onModeChange),
|
||||
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(); }
|
||||
};
|
||||
}
|
||||
+44
-10
@@ -6,7 +6,8 @@ import {mountPlaybackPanel} from './playback-panel.mjs';
|
||||
const namespace='adaptive-music';
|
||||
const tabs=[['connection','Connection'],['scene','Scene Music'],['playback','Playback']];
|
||||
|
||||
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,connection,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,
|
||||
canConfigure=()=>game.user.isGM,connection,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicSetup extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music',resizable:true},position:{width:760,height:620}};
|
||||
#tab='connection';
|
||||
@@ -14,7 +15,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
#timer;
|
||||
|
||||
async _renderHTML(){
|
||||
if(!game.user.isGM)throw new MusicError('denied');
|
||||
if(!canConfigure())throw new MusicError('denied');
|
||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
||||
const make=(tag,text,parent=root)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
const nav=make('div');nav.className='adaptive-tabs';nav.setAttribute('role','tablist');nav.setAttribute('aria-label','Adaptive Music setup');
|
||||
@@ -44,7 +45,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
const button=(parent,label,action,status,className)=>{
|
||||
const b=make('button',label,parent);b.type='button';if(className)b.className=className;
|
||||
b.addEventListener('click',async()=>{
|
||||
if(!game.user.isGM||b.disabled)return;
|
||||
if(!canConfigure()||b.disabled)return;
|
||||
b.disabled=true;
|
||||
try{await action();}catch(error){if(status)status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;}
|
||||
});return b;
|
||||
@@ -118,7 +119,7 @@ export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOv
|
||||
if(globalThis.document===dom&&typeof root.isConnected==='boolean'){
|
||||
this.#timer=setInterval(()=>{
|
||||
if(!root.isConnected)return;
|
||||
if(this.#tab==='connection')refreshConnection();
|
||||
refreshConnection();
|
||||
if(connection?.status.catalog!==lastCatalog){
|
||||
lastCatalog=connection?.status.catalog;void refreshAssignments();
|
||||
}
|
||||
@@ -151,22 +152,55 @@ export function createPlaybackClass({game,connection,getChoices,start,stop,setOv
|
||||
};
|
||||
}
|
||||
|
||||
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,listenerStatus=()=>'Waiting for the GM to connect Music Assistant.',resumeListener=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
export function createListenerClass({game,gateway,audio,listenWebRTC,stopWebRTC=()=>{},onError,
|
||||
listenerStatus=()=>({status:'Waiting for GM audio.',volume:100,muted:false}),resumeListener=()=>{},
|
||||
changeListening=()=>{},Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicListener extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio'},position:{width:480}};
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-listener',window:{title:'Campaign audio'},position:{width:340}};
|
||||
#timer;
|
||||
async _renderHTML(){
|
||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
||||
const note=dom.createElement('p');note.textContent='Campaign audio connects automatically while the GM receiver is online. Your browser may require one audio activation click. No microphone or Music Assistant login is needed.';root.append(note);
|
||||
const status=dom.createElement('p');status.setAttribute('role','status');status.textContent=listenerStatus();root.append(status);
|
||||
const enable=dom.createElement('button');enable.type='button';enable.textContent='Enable Audio';enable.addEventListener('click',()=>{Promise.resolve(resumeListener()).then(()=>{status.textContent=listenerStatus();}).catch(()=>{status.textContent='Audio is waiting. Keep this tab open; check with the GM if it does not connect.';});});root.append(enable);
|
||||
const stop=dom.createElement('button');stop.type='button';stop.textContent='Stop Audio';stop.addEventListener('click',()=>{stopWebRTC();audio.stop();status.textContent='Audio stopped. Select Enable Audio to reconnect.';});root.append(stop);
|
||||
const status=dom.createElement('p');status.setAttribute('role','status');root.append(status);
|
||||
const label=dom.createElement('label');label.textContent='Listening volume ';
|
||||
const volume=dom.createElement('input');volume.type='range';volume.min='0';volume.max='100';volume.step='1';
|
||||
volume.setAttribute('aria-label','Listening volume');label.append(volume);root.append(label);
|
||||
const actions=dom.createElement('div');actions.className='adaptive-listener-actions';root.append(actions);
|
||||
const button=(text,action)=>{
|
||||
const control=dom.createElement('button');control.type='button';control.textContent=text;
|
||||
control.addEventListener('click',()=>perform(action));actions.append(control);return control;
|
||||
};
|
||||
const enable=button('Enable Audio',resumeListener);
|
||||
const mute=button('Mute',()=>changeListening({muted:!listenerStatus().muted}));
|
||||
button('Stop Audio',()=>{stopWebRTC();return audio.stop();});
|
||||
const notice=dom.createElement('p');notice.hidden=true;notice.setAttribute('role','alert');root.append(notice);
|
||||
function refresh(){
|
||||
const state=listenerStatus();
|
||||
if(status.textContent!==state.status)status.textContent=state.status;
|
||||
volume.value=String(state.volume);
|
||||
volume.setAttribute('aria-valuetext',`${state.volume}%`);
|
||||
mute.textContent=state.muted?'Unmute':'Mute';
|
||||
mute.setAttribute('aria-pressed',String(state.muted));
|
||||
enable.classList.toggle('adaptive-activation-required',state.needsActivation===true);
|
||||
}
|
||||
async function perform(action){
|
||||
notice.hidden=true;
|
||||
try{await action();}
|
||||
catch(error){notice.textContent='The audio setting could not be applied.';notice.hidden=false;onError(error);}
|
||||
finally{refresh();}
|
||||
}
|
||||
volume.addEventListener('input',()=>void perform(()=>changeListening({volume:Number(volume.value)},{save:false})));
|
||||
volume.addEventListener('change',()=>void perform(()=>changeListening({volume:Number(volume.value)})));
|
||||
if(game.settings.get('adaptive-music','advancedDevelopment')===true){
|
||||
const dev=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Advanced development';dev.append(summary);
|
||||
const input=dom.createElement('input');input.type='password';input.setAttribute('aria-label','Manual listener capability');dev.append(input);
|
||||
const manual=dom.createElement('button');manual.type='button';manual.textContent='Use manual invitation';manual.addEventListener('click',()=>{try{const code=JSON.parse(input.value);input.value='';Promise.resolve(code.transport==='webrtc-v1'?listenWebRTC(code):audio.start(gateway.audioRequest(code))).catch(onError);}catch{onError(new MusicError('denied'));}});dev.append(manual);root.append(dev);
|
||||
}
|
||||
refresh();
|
||||
clearInterval(this.#timer);
|
||||
this.#timer=setInterval(()=>{if(root.isConnected)refresh();else clearInterval(this.#timer);},750);
|
||||
return root;
|
||||
}
|
||||
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
|
||||
};
|
||||
}
|
||||
@@ -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;
|
||||
};
|
||||
@@ -46,3 +46,33 @@
|
||||
.adaptive-catalog { margin: .4rem; padding: .4rem; }
|
||||
.adaptive-catalog ul { padding-inline-start: 1.25rem; }
|
||||
.adaptive-catalog li[draggable] { cursor: grab; }
|
||||
.adaptive-listening-shortcut {margin:.35rem .5rem;width:calc(100% - 1rem);}
|
||||
.adaptive-listener-actions {display:flex;flex-wrap:wrap;gap:.35rem;}
|
||||
.adaptive-activation-required {font-weight:700;}
|
||||
.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;}
|
||||
|
||||
.adaptive-music-bar {
|
||||
position:fixed;z-index:125;right:.75rem;top:4.75rem;
|
||||
box-sizing:border-box;width:max-content;max-width:min(24rem,calc(100vw - 16px));
|
||||
max-height:calc(100dvh - 16px);overflow:auto;
|
||||
color:#f3eee5;background:#211f1d;border:1px solid #796d59;border-radius:.5rem;
|
||||
box-shadow:0 .35rem 1rem #0007;font-size:.875rem;line-height:1.3;
|
||||
}
|
||||
.adaptive-music-bar header {display:flex;align-items:center;gap:.75rem;padding:.35rem .45rem .35rem .7rem;}
|
||||
.adaptive-music-bar .adaptive-bar-grip {flex:1;min-width:0;cursor:grab;touch-action:none;user-select:none;}
|
||||
.adaptive-music-bar .adaptive-bar-grip:active {cursor:grabbing;}
|
||||
.adaptive-music-bar #adaptive-music-bar-controls {display:grid;gap:.5rem;padding:.55rem .7rem;border-top:1px solid #796d59;}
|
||||
.adaptive-music-bar p {margin:0;white-space:normal;color:#ddd1be;}
|
||||
.adaptive-music-bar .adaptive-bar-actions {display:flex;flex-wrap:wrap;gap:.35rem;}
|
||||
.adaptive-music-bar button {width:auto;min-height:1.75rem;padding:.25rem .55rem;background:#302b25;border:1px solid #796d59;color:inherit;font:inherit;}
|
||||
.adaptive-music-bar button:disabled {opacity:.55;cursor:default;}
|
||||
.adaptive-music-bar button[aria-pressed="true"] {background:#594023;}
|
||||
.adaptive-music-bar :is(button,input):focus-visible {outline:2px solid #efbd76;outline-offset:2px;}
|
||||
.adaptive-music-bar label {display:grid;grid-template-columns:6.5rem minmax(3rem,1fr) 2.7rem;gap:.35rem;align-items:center;}
|
||||
.adaptive-music-bar label span:last-child {text-align:end;font-variant-numeric:tabular-nums;}
|
||||
.adaptive-music-bar input[type="range"] {width:100%;min-width:0;accent-color:#efbd76;}
|
||||
.adaptive-music-bar [hidden],.adaptive-music-setup button[hidden] {display:none!important;}
|
||||
@@ -5,12 +5,13 @@
|
||||
<script type="module">
|
||||
import {createSetupClass,createListenerClass} from '/src/foundry/setup.mjs';
|
||||
import {startConfigurationInterfaces} from '/src/foundry/configuration.mjs';
|
||||
import {mountMusicBar} from '/src/foundry/music-bar.mjs';
|
||||
let flag={},catalog=[];const settings={ownedPlaylistIds:'native',musicDefaults:{},enabled:false,advancedDevelopment:false};
|
||||
const collection=items=>{const map=new Map(items.map(x=>[x.id,x]));map[Symbol.iterator]=function*(){yield*map.values()};return map};
|
||||
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;
|
||||
@@ -27,5 +28,17 @@ window.nativeConfiguration=async()=>{
|
||||
};
|
||||
window.closeNativeConfiguration=()=>{interfaces.dispose();directory.remove();sheet.remove();};
|
||||
};
|
||||
window.listener=async()=>{const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
|
||||
window.listener=async()=>{let preferences={volume:100,muted:false};const Listener=createListenerClass({game,audio:{stop(){}},resumeListener:()=>{window.activated=true},listenerStatus:()=>({status:'Waiting for GM audio.',...preferences}),changeListening:value=>{preferences={...preferences,...value};},Base:class{}});document.querySelector('#app').replaceChildren(await new Listener()._renderHTML())};
|
||||
window.musicBar = controller => {
|
||||
window.disposeBar?.();
|
||||
let layout={}, listening={volume:100,muted:false,status:'Listening'};
|
||||
let state={connected:true,canControl:true,canSkip:true,campaignPaused:false,musicMode:'ambient',volume:100};
|
||||
window.barActions=[];
|
||||
const record=(...action)=>window.barActions.push(action);
|
||||
window.disposeBar=mountMusicBar({document,getPreferences:()=>layout,savePreferences:value=>{layout=value;record('layout',value);},
|
||||
getListening:()=>listening,changeListening:(value,options)=>{listening={...listening,...value};if(options?.save!==false)record('local',value);},
|
||||
enableAudio:()=>record('enable'),onError:error=>{throw error;},
|
||||
gm:controller?{status:()=>state,setPaused:paused=>{state.campaignPaused=paused;record('pause',paused);},skip:()=>record('skip'),
|
||||
setVolume:volume=>{state.volume=volume;record('campaign-volume',volume);},openPlayback:()=>record('playback')}:undefined});
|
||||
};
|
||||
</script>
|
||||
@@ -2,9 +2,9 @@ import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {AutoListeners} from '../../src/audio/auto-listeners.mjs';
|
||||
import {newAudioInvite} from '../../src/audio/signal-codec.mjs';
|
||||
const user=(id,isGM=false)=>({id,isGM,active:true,async setFlag(ns,k,v){this.value=structuredClone(v);},getFlag(){return this.value;}});
|
||||
async function fixture(){
|
||||
const gm=user('gm',true),player=user('player'),other=user('other'),users=[gm,player,other],packets=[],received=[];
|
||||
const user=(id,role=1)=>({id,role,get isGM(){return this.role>=3;},active:true,async setFlag(ns,k,v){this.value=structuredClone(v);},getFlag(){return this.value;}});
|
||||
async function fixture(role){
|
||||
const gm=user('gm',4),player=user('player',role),other=user('other'),users=[gm,player,other],packets=[],received=[];
|
||||
const socket={on(){},off(){},emit(channel,packet){packets.push(packet);}};
|
||||
const host=new AutoListeners({game:{world:{id:'world'},user:gm,users,socket},isGM:()=>gm.active,onInvite:assert.fail});
|
||||
const listener=new AutoListeners({game:{world:{id:'world'},user:player,users,socket},isGM:()=>false,onInvite:invite=>received.push(invite)});
|
||||
@@ -30,8 +30,23 @@ test('parallel bootstrap replay, multiple GMs, revoked roles and expired capabil
|
||||
const f=await fixture();try{
|
||||
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));
|
||||
const attempts=await Promise.allSettled([f.listener.receive(f.packets[0]),f.listener.receive(f.packets[0])]);assert.equal(attempts.filter(r=>r.status==='fulfilled').length,1);assert.equal(f.received.length,1);
|
||||
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));f.other.isGM=true;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.other.isGM=false;
|
||||
f.gm.isGM=false;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.gm.isGM=true;
|
||||
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));f.other.role=4;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.other.role=1;
|
||||
f.gm.role=3;await assert.rejects(f.listener.receive(f.packets[1]),{code:'denied'});f.gm.role=4;
|
||||
await f.host.send(f.player,{...newAudioInvite({session:'session',userId:'player'}),expires:Date.now()-1});await assert.rejects(f.listener.receive(f.packets[2]),{code:'denied'});
|
||||
}finally{f.close();}
|
||||
});
|
||||
test('Trusted Players and Assistant GMs receive invites only from the full GM',async()=>{
|
||||
for(const role of [2,3]){
|
||||
const f=await fixture(role);
|
||||
try{
|
||||
const invite=newAudioInvite({session:'session',userId:'player'});
|
||||
await f.host.send(f.player,invite);
|
||||
await f.listener.receive(f.packets[0]);
|
||||
assert.deepEqual(f.received,[invite]);
|
||||
await f.host.send(f.player,newAudioInvite({session:'session',userId:'player'}));
|
||||
f.player.role=0;
|
||||
await f.listener.receive(f.packets[1]);
|
||||
assert.equal(f.received.length,1);
|
||||
}finally{f.close();}
|
||||
}
|
||||
});
|
||||
@@ -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/);
|
||||
});
|
||||
@@ -41,6 +41,72 @@ test('manual MA controls wait for the scene transition and carry the current fen
|
||||
await assert.rejects(obsolete,{code:'stale'});
|
||||
assert.equal(log.length,3);
|
||||
});
|
||||
test('campaign pause holds an attached MA queue and resumes it in place', async () => {
|
||||
const {controller,provider,log}=fixture();
|
||||
controller.providers.ma=provider;
|
||||
provider.playbackStatus=async()=>({state:'playing'});
|
||||
provider.control=async(action,value,ctx)=>{ctx.check();log.push([action]);};
|
||||
await controller.pauseCampaign({attachedMA:true});
|
||||
assert.equal(controller.campaignPaused,true);
|
||||
await assert.rejects(controller.control('next'),{code:'campaign-paused'});
|
||||
await controller.resumeCampaign(()=>undefined);
|
||||
assert.equal(controller.campaignPaused,false);
|
||||
assert.deepEqual(log,[['pause'],['resume']]);
|
||||
});
|
||||
test('campaign pause covers an attached MA queue alongside an owned native fallback', async () => {
|
||||
const {controller,provider,log}=fixture();
|
||||
const state={scene:scene()};
|
||||
controller.providers.ma={
|
||||
snapshot:provider.snapshot,
|
||||
playbackStatus:async()=>({state:'playing'}),
|
||||
control:async(action,value,ctx)=>{ctx.check();log.push([action]);},
|
||||
};
|
||||
await controller.update(state);
|
||||
await controller.pauseCampaign({attachedMA:true});
|
||||
await controller.resumeCampaign(()=>state);
|
||||
assert.deepEqual(log.map(([action])=>action),['resolve','apply','stop','pause','restore','resume']);
|
||||
});
|
||||
test('campaign pause defers cue changes and keeps the pre-pause ambient position', async () => {
|
||||
const f=fixture(), c=f.controller;
|
||||
const base={scene:scene()}, combatState={...base,combats:[combat()]};
|
||||
await c.update(base);
|
||||
f.playback={...f.playback,offset:31};
|
||||
await c.pauseCampaign();
|
||||
assert.equal(c.campaignPaused,true);
|
||||
await c.update(combatState);
|
||||
assert.equal(c.current.mode,'ambient');
|
||||
assert.deepEqual(f.log,[['resolve','A'],['apply','A'],['stop']]);
|
||||
await c.resumeCampaign(()=>combatState);
|
||||
assert.equal(c.current.mode,'combat');
|
||||
assert.deepEqual(f.log.slice(3),[['resolve','combat'],['apply','combat']]);
|
||||
await c.update(base);
|
||||
assert.equal(f.playback.offset,31);
|
||||
assert.equal(f.playback.paused,false);
|
||||
});
|
||||
test('a failed next cue leaves the campaign on hold until Play is retried', async () => {
|
||||
const f=fixture(), c=f.controller;
|
||||
const current={scene:scene()}, other={scene:scene('B')};
|
||||
await c.update(current);
|
||||
await c.pauseCampaign();
|
||||
const apply=f.provider.apply;
|
||||
f.provider.apply=async()=>{throw new MusicError('unavailable');};
|
||||
await assert.rejects(c.resumeCampaign(()=>other),{code:'unavailable'});
|
||||
assert.equal(c.campaignPaused,true);
|
||||
assert.equal(c.current.mode,'ambient');
|
||||
assert.equal(f.log.some(([action])=>action==='restore'),false);
|
||||
f.provider.apply=apply;
|
||||
await c.resumeCampaign(()=>other);
|
||||
assert.equal(c.campaignPaused,false);
|
||||
assert.deepEqual(f.playback.items,['B']);
|
||||
});
|
||||
test('a campaign pause queued before runtime disposal cannot issue a write', async () => {
|
||||
const {controller,provider,log}=fixture();
|
||||
controller.providers.ma=provider;
|
||||
const pending=controller.pauseCampaign({attachedMA:true});
|
||||
controller.cancel();
|
||||
await assert.rejects(pending,{code:'stale'});
|
||||
assert.deepEqual(log,[]);
|
||||
});
|
||||
test('inactive, unstarted and other scene combats ignored; boss ties stable', () => {
|
||||
for (const change of [{active:false},{started:false},{sceneId:'B'}]) {
|
||||
assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A');
|
||||
@@ -67,6 +133,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);
|
||||
|
||||
@@ -76,7 +76,9 @@ test('wizard inspects only the imported dedicated identity, loads stable catalog
|
||||
socket.onmessage?.({data:JSON.stringify({message_id:msg.message_id,result})});
|
||||
});},close(){this.onclose?.();}};queueMicrotask(()=>socket.onopen?.());return socket;
|
||||
};
|
||||
const context={state:'running',destination:{},resume(){return Promise.resolve();},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){}}),close:async()=>{}};
|
||||
const gains=[], edges=[], streamOutput={stream:{getTracks:()=>[]}};
|
||||
const context={state:'running',destination:{},resume(){return Promise.resolve();},createMediaStreamDestination:()=>streamOutput,
|
||||
createGain(){const node={gain:{value:1,setTargetAtTime(value){this.value=value;}},connect(output){edges.push([node,output]);}};gains.push(node);return node;},close:async()=>{}};
|
||||
const sdk={loadSendspinClientIdentity:()=>({clientId:target}),SendspinCore:class{timeSyncInfo={synced:true};async connect(){}disconnect(){}}};
|
||||
const originalNavigator=globalThis.navigator;
|
||||
Object.defineProperty(globalThis,'navigator',{configurable:true,value:{locks:{request:async(name,opts,fn)=>fn({})}}});
|
||||
@@ -85,7 +87,15 @@ test('wizard inspects only the imported dedicated identity, loads stable catalog
|
||||
const supplied={maUrl:'https://ma.example.test',token:'private-fixture',identityStorage:{'sendspin-identity-sk':'A'.repeat(43)},campaign:'world',targetName:player.name,webSocketAuthLogSafe:true,allowCatalogPlayback:true};
|
||||
const profile=await host.inspect(supplied);assert.equal(profile.target,target);assert.deepEqual(profile.approvedProviders,['approved']);
|
||||
const catalog=await host.readCatalog(profile,{reconnecting:true});const again=await host.inspect(supplied);assert.equal(profile.catalogKey,again.catalogKey);
|
||||
host.setMonitorLevel(0.25);
|
||||
await host.start(profile);assert.equal(host.connected,true);assert.equal(host.supports(catalog[0]),true);assert.equal(host.supports({provider:'ma',id:'forged'}),false);
|
||||
const [,shared,monitor]=gains;
|
||||
assert.ok(edges.some(([from,to])=>from===shared&&to===streamOutput));
|
||||
assert.ok(edges.some(([from,to])=>from===monitor&&to===context.destination));
|
||||
assert.equal(monitor.gain.value,0.25);
|
||||
host.setMonitorLevel(0);
|
||||
assert.equal(monitor.gain.value,0);
|
||||
assert.equal(shared.gain.value,1);
|
||||
assert.ok(calls.filter(c=>c.command==='players/get').every(c=>c.args.player_id===target));assert.ok(!calls.some(c=>c.command==='players/all'||c.command==='player_queues/play_media'));assert.ok(requested>=3);
|
||||
await host.close();assert.equal(host.supports(catalog[0]),false);
|
||||
}finally{await host.close();Object.defineProperty(globalThis,'navigator',{configurable:true,value:originalNavigator});}
|
||||
@@ -118,7 +128,7 @@ test('automatic provisioning uses the bound API session, waits for queue registr
|
||||
const sdk={loadSendspinClientIdentity(storage){if(!storage.getItem('sendspin-identity-sk'))storage.setItem('sendspin-identity-sk','A'.repeat(43));return {clientId:player.player_id};},SendspinCore:class{
|
||||
timeSyncInfo={synced:true};pairingToken='private-pairing-fixture';constructor(config){core=this;this.config=config;softwareVolume=config.useHardwareVolume===false;}async connect(){this.config.storage.setItem('pairing-fixture','retained');}disconnect(){}
|
||||
}};
|
||||
const context={state:'running',destination:{},resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){}}),close:async()=>{}};
|
||||
const context={state:'running',destination:{},resume:async()=>{},createMediaStreamDestination:()=>({stream:{getTracks:()=>[]}}),createGain:()=>({connect(){},gain:{value:1}}),close:async()=>{}};
|
||||
const locks={async request(_name,_options,callback){
|
||||
if(lockHeld)return callback(null);
|
||||
lockHeld=true;
|
||||
|
||||
@@ -3,11 +3,11 @@ import assert from 'node:assert/strict';
|
||||
test('installable development entry defaults automation off and imports no gateway',async()=>{
|
||||
const once=new Map(),settings=new Map(),module={};let registrations=0;
|
||||
globalThis.Hooks={once(e,fn){once.set(e,fn);},on(){registrations++;},off(){}};
|
||||
globalThis.game={user:{isGM:true},playlists:[],modules:{get:()=>module},settings:{register(ns,key,definition){settings.set(key,definition);},get(ns,key){return settings.get(key).default;}}};
|
||||
globalThis.game={user:{role:4,isGM:true},playlists:[],modules:{get:()=>module},settings:{register(ns,key,definition){settings.set(key,definition);},get(ns,key){return settings.get(key).default;}}};
|
||||
globalThis.ui={notifications:{warn(){}}};
|
||||
try{
|
||||
await import('../../src/foundry/module.mjs');once.get('init')();once.get('ready')();
|
||||
assert.equal(settings.get('enabled').default,false);assert.equal(settings.get('ownedPlaylistIds').default,'');
|
||||
assert.equal(registrations,4);assert.equal(typeof module.api.mountConfiguration,'function');assert.throws(()=>module.api.setOverrides([]));module.api.dispose();
|
||||
assert.equal(registrations,5);assert.equal(typeof module.api.mountConfiguration,'function');assert.throws(()=>module.api.setOverrides([]));module.api.dispose();
|
||||
}finally{delete globalThis.game;delete globalThis.Hooks;delete globalThis.ui;}
|
||||
});
|
||||
@@ -1,7 +1,8 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { NativeProvider } from '../../src/providers/native/provider.mjs';
|
||||
import { primaryGM, startNativeRuntime } from '../../src/foundry/runtime.mjs';
|
||||
import { startNativeRuntime } from '../../src/foundry/runtime.mjs';
|
||||
import {activeMusicGM,isMusicListener} from '../../src/foundry/authority.mjs';
|
||||
const collection = items => { const m=new Map(items.map(x=>[x.id,x])); m[Symbol.iterator]=function*(){yield* this.values();}; return m; };
|
||||
function fixture() {
|
||||
const calls=[];
|
||||
@@ -50,15 +51,55 @@ test('scene-linked playlist conflict and lost authority fail before mutation',as
|
||||
provider.sceneConflict=()=>false;
|
||||
await assert.rejects(provider.stopOwned({...ctx,check(){throw new Error('lost');}}));assert.equal(calls.length,0);
|
||||
});
|
||||
test('GM election deterministic and no GM means none',()=>{
|
||||
assert.equal(primaryGM([{id:'z',active:true,isGM:true},{id:'a',active:true,isGM:true},{id:'0',active:false,isGM:true}]),'a');
|
||||
assert.equal(primaryGM([]),undefined);
|
||||
test('only one active full GM has authority and assistants are listeners',()=>{
|
||||
const gm={id:'a',active:true,role:4,isGM:true};
|
||||
const assistant={id:'b',active:true,role:3,isGM:true};
|
||||
assert.equal(activeMusicGM([assistant,gm,{active:false,role:4}]),gm);
|
||||
assert.equal(activeMusicGM([assistant]),undefined);
|
||||
assert.equal(activeMusicGM([gm,{id:'z',active:true,role:4}]),undefined);
|
||||
assert.equal(activeMusicGM([{...gm,isBanned:true}]),undefined);
|
||||
assert.equal(isMusicListener(assistant),true);
|
||||
});
|
||||
test('Foundry bootstrap registers local settings/hooks and disposes without ambient or actor access',async()=>{
|
||||
const callbacks=new Map();let index=0,registered=0;
|
||||
const Hooks={on(e,cb){callbacks.set(++index,cb);return index;},off(e,id){callbacks.delete(id);}};
|
||||
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[],combats:[],
|
||||
const game={ready:true,user:{id:'gm'},users:[{id:'gm',role:4,active:true}],playlists:collection([]),scenes:[],combats:[],
|
||||
settings:{register(){registered++;},get(){return null;}}};
|
||||
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',role:4,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();
|
||||
});
|
||||
@@ -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');
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import {test} from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {createSetupClass,createListenerClass} from '../../src/foundry/setup.mjs';
|
||||
import {ListenerAudio} from '../../src/foundry/listener-audio.mjs';
|
||||
import {CampaignAudio,ListenerAudio} from '../../src/foundry/listener-audio.mjs';
|
||||
class Element{
|
||||
constructor(tag,dom){this.tag=tag;this.ownerDocument=dom;this.children=[];this.listeners={};this.dataset={};this.value='';}
|
||||
append(...children){this.children.push(...children);if(this.tag==='select'&&!this.value&&children[0]?.tag==='option')this.value=children[0].value;}
|
||||
replaceChildren(...children){this.children=[];this.append(...children);}
|
||||
setAttribute(){}
|
||||
classList={toggle(){}};
|
||||
addEventListener(name,fn){this.listeners[name]=fn;}
|
||||
}
|
||||
const descendants=node=>[node,...node.children.flatMap(descendants)];
|
||||
@@ -38,7 +39,47 @@ test('browser PCM sink resumes from gesture, decodes stereo frames and closes it
|
||||
|
||||
test('normal listener has one activation action and no token or invitation entry',async()=>{
|
||||
const dom={createElement:tag=>new Element(tag,dom)};globalThis.document=dom;let clicks=0;
|
||||
try{const Listener=createListenerClass({game:{settings:{get:()=>false}},audio:{stop(){}},resumeListener:()=>{clicks++;},Base:class{}});const root=await new Listener()._renderHTML();assert.ok(!descendants(root).some(e=>e.tag==='input'));await descendants(root).find(e=>e.textContent==='Enable Audio').listeners.click();assert.equal(clicks,1);}finally{delete globalThis.document;}
|
||||
const Listener=createListenerClass({game:{settings:{get:()=>false}},audio:{stop(){}},resumeListener:()=>{clicks++;},Base:class{}});
|
||||
const app=new Listener();
|
||||
try{
|
||||
const root=await app._renderHTML();
|
||||
assert.deepEqual(descendants(root).filter(e=>e.tag==='input').map(e=>e.type),['range']);
|
||||
await descendants(root).find(e=>e.textContent==='Enable Audio').listeners.click();
|
||||
assert.equal(clicks,1);
|
||||
}finally{app._onClose();delete globalThis.document;}
|
||||
});
|
||||
|
||||
test('WebRTC listening gain and mute are local and retained through stream replacement',async()=>{
|
||||
function player(initial){
|
||||
let mix;
|
||||
const element={paused:true,
|
||||
async play(){this.paused=false;},
|
||||
pause(){this.paused=true;},
|
||||
remove(){}
|
||||
};
|
||||
const context={currentTime:0,destination:{},state:'suspended',
|
||||
async resume(){this.state='running';},async close(){},
|
||||
createGain:()=>({gain:{setTargetAtTime(value){mix=value;}},connect(){},disconnect(){}}),
|
||||
createMediaStreamSource:()=>({connect(){},disconnect(){}})
|
||||
};
|
||||
const output=new CampaignAudio({preferences:initial,createElement:()=>element,createContext:()=>context});
|
||||
return {output,element,get mix(){return mix;}};
|
||||
}
|
||||
const first=player({volume:35,muted:true}),second=player();
|
||||
for(const listener of [first,second]){
|
||||
await listener.output.enable();
|
||||
await listener.output.attach({});
|
||||
}
|
||||
assert.equal(first.mix,0);
|
||||
assert.equal(second.mix,1);
|
||||
first.output.setPreferences({muted:false});
|
||||
assert.equal(first.mix,0.35);
|
||||
assert.equal(second.mix,1);
|
||||
await first.output.attach({});
|
||||
assert.equal(first.mix,0.35);
|
||||
assert.equal(first.element.muted,true);
|
||||
assert.equal(first.output.status.playing,true);
|
||||
first.output.close();second.output.close();
|
||||
});
|
||||
|
||||
test('failed wizard authentication can retry without reentering token',async()=>{
|
||||
|
||||
Reference in new issue
Block a user