2 Commits
Author SHA1 Message Date
Jason fbc265b526 Adaptive Music v0.8.3 multiplayer and floating music controls
Validate and generate manual release / package (push) Waiting to run
2026-12-05 20:29:27 -05:00
CheddahBoxMB acc8cbafc6 Upload files to "/" 2026-12-05 13:39:54 -05:00
33 changed files with 1673 additions and 131 deletions

No files matched your search

+18 -6
View File
@@ -1,4 +1,4 @@
# Adaptive Music architecture — 0.8.1
# 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,9 +80,13 @@ 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
@@ -93,8 +97,9 @@ 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,
@@ -108,6 +113,13 @@ 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
+21
View File
@@ -1,5 +1,26 @@
# 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
+53 -11
View File
@@ -1,21 +1,63 @@
# Adaptive Music v0.8.1 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 original workspace's Git metadata is read-only. Before v0.8.1 changes,
its 157 tracked and untracked source files matched the clean local release
commit `1ed6b4c` byte for byte. The original HEAD `987122f` is that commit's
parent. Develop on `v0.8.1-firefox` in the remote-free
`.local/v080-release-checkout`. Its `main` branch retains `1ed6b4c`.
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 is v0.8.0 and all 28 runtime files match `1ed6b4c`.
The v0.8.1 archive is built from a clean checkout and its source is compared
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.1/release.json`. Gitea access and production deployment
`dist/releases/v0.8.2/release.json`. Gitea access and production deployment
are outside this work.
## Installed v0.8.0 macOS acceptance
@@ -27,8 +69,8 @@ are outside this work.
- **Operator fail:** macOS Firefox connectivity.
- **Combat follow-up:** assigned battle music worked when used as ambient,
while normal combat left ambient playing. The operator could not find
the boss designation. Combat, restoration, boss and manual controls need
hands-on acceptance with the corrected candidate.
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
@@ -236,9 +278,9 @@ xvfb-run -a -s '-screen 0 1600x1050x24 +extension GLX' \
> .local/v080-candidate-firefox-soak.log 2>&1
# Build the current candidate from the clean local release checkout.
python3 .local/v080-release-checkout/scripts/release.py --output "$PWD/dist/releases/v0.8.1"
python3 scripts/release.py --validate dist/releases/v0.8.1/adaptive-music.zip
(cd dist/releases/v0.8.1 && sha256sum -c SHA256SUMS && sha256sum -c adaptive-music-release-v0.8.1.zip.sha256)
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
+13 -11
View File
@@ -1,4 +1,4 @@
# Install and connect — 0.8.1 candidate
# 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
@@ -27,9 +27,11 @@
repeat control the dedicated queue. The Playback panel and Combat Tracker
show the current music mode. Select **Return to automation** in the tracker
or **Return to scene music** in Playback to clear a manual override.
5. Players connect automatically. If a browser requires activation, open Campaign
audio and select **Enable Audio** once. The GM can use **Enable GM audio** in the
playback controls after an automatic connection.
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.
@@ -95,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 separately verified installed baseline is v0.8.0.
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
@@ -107,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.1'
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-v081.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
@@ -128,7 +130,7 @@ the module directory.
```
Restart the development instance, launch the development world and confirm
**Manage Modules** reports **0.8.1**. 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
@@ -139,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.1 asset: `https://cheddahboxmb.duckdns.org/CheddahBoxMB/adaptive-music/releases/download/v0.8.1/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.1`, 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
+43 -4
View File
@@ -1,4 +1,43 @@
# Adaptive Music progress — 0.8.1 combat and Firefox
# 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
@@ -8,8 +47,8 @@ audio, WAN player audio and smooth transitions passed. The operator reported
that stuttering and crackling were resolved in their testing. Firefox
connectivity failed. A follow-up confirmed the battle playlist played when
assigned to ambient, while tracked combat left ambient unchanged. The operator
could not find boss designation. The corrected combat workflow still awaits
operator acceptance.
could not find boss designation. The operator subsequently passed the corrected
workflow in v0.8.1.
## v0.8.1 combat correction
@@ -27,7 +66,7 @@ normal, boss, and manual-override encounters. The scene excursion preserved the
interrupted ambient position. The manual override was visible in the tracker and
released to Combat through **Return to automation**.
The headed Firefox preview repeated the normal tracker lifecycle and restored
ambient at 9 seconds. The installed macOS candidate awaits operator retesting.
ambient at 9 seconds. The operator passed the v0.8.1 combat acceptance.
## v0.8.1 status
+12 -3
View File
@@ -1,4 +1,4 @@
# Adaptive Music — 0.8.1 candidate
# 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
@@ -17,8 +17,17 @@ 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
+11 -2
View File
@@ -1,4 +1,4 @@
# Adaptive Music security — 0.8.1
# Adaptive Music security — 0.8.3
## Credentials and browser trust
@@ -51,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
+82 -3
View File
@@ -1,9 +1,88 @@
# Adaptive Music verification — 0.8.1
# 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
@@ -12,8 +91,8 @@ player audio and smooth transitions. Stuttering and crackling were resolved
during testing. Firefox connectivity failed. In the combat follow-up, the
operator reported that a battle playlist played when assigned to ambient,
while native combat use left the ambient cue playing. They could not find
the boss designation. The corrected combat flow and manual playback
controls still need operator acceptance.
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
+20 -6
View File
@@ -1,5 +1,13 @@
# Adaptive Music Mac acceptance
## 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
@@ -10,7 +18,7 @@ These results are user-confirmed manual testing on macOS. See
| Pass | Chrome connectivity, Chrome credentials after a full quit and reopen, automatic scene playlist activation, background-tab audio, remote player audio over WAN, and smooth transitions. The operator heard no stuttering or crackling during testing. |
| Fail | Firefox connectivity on macOS. The operator also reported that the assigned battle playlist played when used as ambient, while normal Combat Tracker use left the ambient cue playing. |
| Usability finding | The operator could not find a way to designate a boss. Their normal combat and default boss assignments used the same playlist. |
| Awaiting candidate retest | Combat start and end, ambient restoration, boss designation, and manual playback controls. |
| Passed in v0.8.1 | Combat start and end, ambient restoration, boss designation, and manual playback controls. |
## Capture the Firefox failure
@@ -41,8 +49,8 @@ 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 a v0.8.1 run, confirm **Manage Modules** shows Adaptive Music
**0.8.1**. Use the [local ZIP install procedure](INSTALL.md#install-the-candidate-on-an-isolated-development-instance).
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 |
@@ -55,15 +63,21 @@ Only use the dedicated development receiver.
| ☐ Cancel and restore | Open **End Combat** and cancel the confirmation, then open it again and confirm. Repeat with a second encounter. | Cancel keeps the encounter and its music running. Confirm restores the ambient queue order, track and approximate saved position. A later encounter captures a fresh position. |
| ☐ Switch scenes during combat | During an active encounter, activate another scene with its own ambient cue and no participants in that encounter. Reactivate the original scene and end the encounter. | The other scene uses its own ambient. The encounter cue returns on reactivation. Ending the encounter restores the original scene's interrupted ambient position. |
| ☐ Manual controls | Open **Music controls** from the Playlists sidebar and apply a **Manual playlist override**. Start combat and use **Return to automation** in the Combat Tracker. Also try pause, resume, seek, skip, volume, repeat, and stop. | The tracker and Playback panel show **Manual Override** while automatic cues are on hold. Return to automation takes up the currently applicable cue. Transport controls affect the dedicated receiver. |
| ☐ Player audio | Join as an ordinary development player in a separate profile. Open **Campaign audio** and select **Enable Audio** if prompted. Try **Stop Audio**, **Enable Audio** and one player reload. | The listener hears the GM's cue and audio returns after re-enabling and reloading. |
| ☐ 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**
+14 -1
View File
@@ -684,5 +684,18 @@
],
"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"
}
}
+587
View File
@@ -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
View File
@@ -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"
}
+39 -2
View File
@@ -76,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','failed connection diagnostics exclude secrets and clear after retry','private field clearing','catalog selectors','ambient/combat save','advanced controls hidden','sidebar catalog refresh and pointer drag','track and listeners','pause/resume/seek/repeat/volume/stop','listener activation'],pageErrors:errors},null,2));
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));}
+7 -5
View File
@@ -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
View File
@@ -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();}
}
+74 -6
View File
@@ -31,12 +31,14 @@ const samePlaylist = (a, b) => Boolean(a && b && a.provider === b.provider && a.
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),...retainedAmbient(input)].map(intent=>intent.key));
if(this.#pending?.signature===signature&&this.#pending.generation===this.generation)return this.#pending.task;
@@ -52,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'));
}
@@ -67,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();
}
@@ -83,7 +146,7 @@ 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 active = new Set(choices.map(i => i.key));
@@ -99,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) {
@@ -109,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) {
@@ -126,12 +190,16 @@ 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 => !active.has(f.intent.key)||!samePlaylist(f.intent.playlist,next.playlist)).slice(-this.maxFrames);
this.dirty.clear();
+18
View File
@@ -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;
}
+15 -1
View File
@@ -1,12 +1,25 @@
import {mountMusicAssignments,playlistDragType} from './music-editor.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 }) {
@@ -137,7 +150,8 @@ export function startConfigurationInterfaces({ game, Hooks, getChoices, openPlay
const combat = app.viewed;
const state = getPlaybackState();
const cue = musicModeLabel(state.musicMode);
const text = state.overrideActive ? 'Music: Manual Override · automatic cues on hold'
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;
+1
View File
@@ -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.',
+82
View File
@@ -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;
+136 -31
View File
@@ -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();
@@ -44,7 +49,8 @@ function ensureRuntime(){
return runtime;
}
function playbackMode(){
return {musicMode:runtime?.musicMode,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange};
return {musicMode:runtime?.musicMode,overrideActive:runtime?.overrideActive,awaitingSceneChange:runtime?.awaitingSceneChange,
campaignPaused:runtime?.controller.campaignPaused??false};
}
function refreshCombatTrackers(){interfaces?.refreshCombatTrackers();}
function start({preserveQueue=false}={}){
@@ -59,15 +65,71 @@ function stop(){
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
refreshCombatTrackers();
}
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
function ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
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 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 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();}
}
@@ -156,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;
@@ -174,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);
},
@@ -213,38 +277,78 @@ 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){
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);
@@ -254,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;},
@@ -268,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;}
};
});
+157
View File
@@ -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();
};
}
+5 -3
View File
@@ -36,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());
@@ -74,8 +75,8 @@ 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;
@@ -89,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;
@@ -100,7 +102,7 @@ export function mountPlaybackPanel({game,container,connection,getChoices,start,s
automationText.textContent=enabled
? 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;
+9 -4
View File
@@ -1,12 +1,11 @@
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,
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,
@@ -52,7 +51,7 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
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();
@@ -71,6 +70,12 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
})]);
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);onModeChange();return refresh(); },
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
+44 -10
View File
@@ -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);}
};
}
+25
View File
@@ -46,8 +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;}
+14 -1
View File
@@ -5,6 +5,7 @@
<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}};
@@ -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>
+20 -5
View File
@@ -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();}
}
});
+66
View File
@@ -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');
+12 -2
View File
@@ -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;
+2 -2
View File
@@ -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;}
});
+12 -6
View File
@@ -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,14 +51,19 @@ 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);
@@ -70,7 +76,7 @@ test('Foundry runtime uses committed unlinked combatant scenes and coalesces ini
const encounter={id:'fight',scene:null,active:true,started:false,
combatants:[{id:'token',sceneId:'A',getFlag:()=>undefined}],getFlag:()=>({boss:true})};
const combats=collection([encounter]);
const game={ready:true,user:{id:'gm'},users:[{id:'gm',isGM:true,active:true}],playlists:collection([]),scenes:[scene],combats,
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')};
+43 -2
View File
@@ -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()=>{